<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se.kth.karamel.backend.command;

import dnl.utils.text.table.TextTable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import se.kth.karamel.backend.ClusterDefinitionService;
import se.kth.karamel.backend.ClusterManager;
import se.kth.karamel.backend.ClusterService;
import se.kth.karamel.backend.launcher.amazon.Ec2Context;
import se.kth.karamel.backend.running.model.ClusterEntity;
import se.kth.karamel.backend.running.model.GroupEntity;
import se.kth.karamel.backend.running.model.MachineEntity;
import se.kth.karamel.backend.running.model.tasks.Task;
import se.kth.karamel.client.model.json.JsonCluster;
import se.kth.karamel.common.ClasspathResourceUtil;
import se.kth.karamel.common.SshKeyPair;
import se.kth.karamel.common.exception.KaramelException;

/**
 *
 * @author kamal
 */
public class CommandService {

  private static String chosenCluster = null;
  private static String autoselectedCluster = null;
  private static final ClusterService clusterService = ClusterService.getInstance();
//  private static final KaramelApi api = new KaramelApiImpl();

  public static CommandResponse processCommand(String command, String... args) throws KaramelException {
    String cmd = command.toLowerCase().trim();
    String nextCmd = null;
    selectCluster();
    String result = "command not found";
    if (cmd.equals("help")) {
      try {
        result = ClasspathResourceUtil.readContent("se/kth/karamel/backend/command/cheatsheet");
      } catch (IOException ex) {
        result = "sorry, couldn't load the cheatsheet";
      }
    } else if (cmd.equals("clusters")) {
      result = clusters();
    } else if (cmd.equals("list")) {
      List<String> defs = ClusterDefinitionService.listClusters();
      StringBuilder builder = new StringBuilder();
      builder.append("Yaml Definitions:").append("\n").append("---------------------").append("\n");
      for (String def : defs) {
        builder.append(def).append("\n");
      }
      builder.append("\n").append("Running Clusters:").append("\n").append("----------------------").append("\n");
      builder.append(clusters());
      result = builder.toString();
    } else if (cmd.equals("save")) {
      if (args.length == 0) {
        throw new KaramelException("Provide the yaml definition");
      }
      ClusterDefinitionService.saveYaml(args[0]);
      result = "Yaml updated";
    } else if (cmd.equals("yaml")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        JsonCluster json = cluster.getDefinition();
        try {
          result = ClusterDefinitionService.jsonToYaml(json);
        } catch (KaramelException ex) {
          result = "sorry couldn't load the yaml";
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("pause")) {
      if (chosenCluster() != null) {
        try {
          clusterService.pauseCluster(chosenCluster());
          result = "Pausing the installation...";
          nextCmd = "watch -n 2 status";
        } catch (KaramelException ex) {
          result = ex.getMessage();
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("resume")) {
      if (chosenCluster() != null) {
        try {
          clusterService.resumeCluster(chosenCluster());
          result = "Resuming the installation...";
          nextCmd = "watch -n 2 status";
        } catch (KaramelException ex) {
          result = ex.getMessage();
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("purge")) {
      if (chosenCluster() != null) {
        try {
          clusterService.purgeCluster(chosenCluster());
          result = "Purging " + chosenCluster();
          nextCmd = "watch -n 2 status";
        } catch (KaramelException ex) {
          result = ex.getMessage();
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("status")) {
      if (chosenCluster() != null) {
        StringBuilder builder = new StringBuilder();
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        builder.append(clusterEntity.getName()).append(" is ").append(clusterEntity.getPhase());
        if (clusterEntity.isPaused()) {
          builder.append(" but it is paused.");
        }
        if (clusterEntity.isFailed()) {
          builder.append(" Some failures have happened.");
        }
        builder.append("\n");
        builder.append(machinesTasksTable(clusterEntity));
        result = builder.toString();
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("detail")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        JsonCluster json = cluster.getDefinition();

        try {
          result = ClusterDefinitionService.serializeJson(json);
        } catch (KaramelException ex) {
          result = "sorry couldn't load the yaml";
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("groups")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        String[] columnNames = {"Name", "Phase", "Failed"};
        String[][] data = new String[clusterEntity.getGroups().size()][3];
        for (int i = 0; i < clusterEntity.getGroups().size(); i++) {
          GroupEntity group = clusterEntity.getGroups().get(i);
          data[i][0] = group.getName();
          data[i][1] = String.valueOf(group.getPhase());
          data[i][2] = String.valueOf(group.isFailed());
        }
        result = makeTable(columnNames, 2, data, true);
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("machines")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        ArrayList<MachineEntity> machines = new ArrayList<>();
        for (GroupEntity group : clusterEntity.getGroups()) {
          for (MachineEntity machine : group.getMachines()) {
            machines.add(machine);
          }
        }
        result = machinesTable(machines, true);
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("tasks")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        result = machinesTasksTable(clusterEntity);
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else {
      boolean found = false;
      Pattern p = Pattern.compile("use\\s+(\\w+)");
      Matcher matcher = p.matcher(cmd);
      if (!found && matcher.matches()) {
        found = true;
        String clusterName = matcher.group(1);
        if (cluster(clusterName) != null) {
          chosenCluster = clusterName;
          result = String.format("switched to %s now", clusterName);
        } else {
          result = String.format("cluster %s is not registered yet!!", clusterName);
        }
      }

      p = Pattern.compile("remove\\s+(\\w+)");
      matcher = p.matcher(cmd);
      if (!found && matcher.matches()) {
        found = true;
        String clusterName = matcher.group(1);
        if (cluster(clusterName) != null) {
          result = String.format("%s is running now, terminate it first!!", clusterName);
        } else {
          ClusterDefinitionService.removeDefinition(clusterName);<commit_msg>next command for status commands<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se.kth.karamel.backend.command;

import dnl.utils.text.table.TextTable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import se.kth.karamel.backend.ClusterDefinitionService;
import se.kth.karamel.backend.ClusterManager;
import se.kth.karamel.backend.ClusterService;
import se.kth.karamel.backend.launcher.amazon.Ec2Context;
import se.kth.karamel.backend.running.model.ClusterEntity;
import se.kth.karamel.backend.running.model.GroupEntity;
import se.kth.karamel.backend.running.model.MachineEntity;
import se.kth.karamel.backend.running.model.tasks.Task;
import se.kth.karamel.client.model.json.JsonCluster;
import se.kth.karamel.common.ClasspathResourceUtil;
import se.kth.karamel.common.SshKeyPair;
import se.kth.karamel.common.exception.KaramelException;

/**
 *
 * @author kamal
 */
public class CommandService {

  private static String chosenCluster = null;
  private static String autoselectedCluster = null;
  private static final ClusterService clusterService = ClusterService.getInstance();
//  private static final KaramelApi api = new KaramelApiImpl();

  public static CommandResponse processCommand(String command, String... args) throws KaramelException {
    String cmd = command.toLowerCase().trim();
    String nextCmd = null;
    selectCluster();
    String result = "command not found";
    if (cmd.equals("help")) {
      try {
        result = ClasspathResourceUtil.readContent("se/kth/karamel/backend/command/cheatsheet");
      } catch (IOException ex) {
        result = "sorry, couldn't load the cheatsheet";
      }
    } else if (cmd.equals("clusters")) {
      result = clusters();
    } else if (cmd.equals("list")) {
      List<String> defs = ClusterDefinitionService.listClusters();
      StringBuilder builder = new StringBuilder();
      builder.append("Yaml Definitions:").append("\n").append("---------------------").append("\n");
      for (String def : defs) {
        builder.append(def).append("\n");
      }
      builder.append("\n").append("Running Clusters:").append("\n").append("----------------------").append("\n");
      builder.append(clusters());
      result = builder.toString();
    } else if (cmd.equals("save")) {
      if (args.length == 0) {
        throw new KaramelException("Provide the yaml definition");
      }
      ClusterDefinitionService.saveYaml(args[0]);
      result = "Yaml updated";
    } else if (cmd.equals("yaml")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        JsonCluster json = cluster.getDefinition();
        try {
          result = ClusterDefinitionService.jsonToYaml(json);
        } catch (KaramelException ex) {
          result = "sorry couldn't load the yaml";
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("pause")) {
      if (chosenCluster() != null) {
        try {
          clusterService.pauseCluster(chosenCluster());
          result = "Pausing the installation...";
          nextCmd = "watch -n 2 status";
        } catch (KaramelException ex) {
          result = ex.getMessage();
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("resume")) {
      if (chosenCluster() != null) {
        try {
          clusterService.resumeCluster(chosenCluster());
          result = "Resuming the installation...";
          nextCmd = "watch -n 2 status";
        } catch (KaramelException ex) {
          result = ex.getMessage();
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("purge")) {
      if (chosenCluster() != null) {
        try {
          clusterService.purgeCluster(chosenCluster());
          result = "Purging " + chosenCluster();
          nextCmd = "watch -n 2 status";
        } catch (KaramelException ex) {
          result = ex.getMessage();
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("status")) {
      if (chosenCluster() != null) {
        StringBuilder builder = new StringBuilder();
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        builder.append(clusterEntity.getName()).append(" is ").append(clusterEntity.getPhase());
        if (clusterEntity.isPaused()) {
          builder.append(" but it is paused.");
        }
        if (clusterEntity.isFailed()) {
          builder.append(" Some failures have happened.");
        }
        builder.append("\n");
        builder.append(machinesTasksTable(clusterEntity));
        result = builder.toString();
        nextCmd = "watch -n 2 status";
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("detail")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        JsonCluster json = cluster.getDefinition();

        try {
          result = ClusterDefinitionService.serializeJson(json);
          nextCmd = "watch -n 2 detail";
        } catch (KaramelException ex) {
          result = "sorry couldn't load the yaml";
        }
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("groups")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        String[] columnNames = {"Name", "Phase", "Failed"};
        String[][] data = new String[clusterEntity.getGroups().size()][3];
        for (int i = 0; i < clusterEntity.getGroups().size(); i++) {
          GroupEntity group = clusterEntity.getGroups().get(i);
          data[i][0] = group.getName();
          data[i][1] = String.valueOf(group.getPhase());
          data[i][2] = String.valueOf(group.isFailed());
        }
        result = makeTable(columnNames, 2, data, true);
        nextCmd = "watch -n 2 groups";
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("machines")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        ArrayList<MachineEntity> machines = new ArrayList<>();
        for (GroupEntity group : clusterEntity.getGroups()) {
          for (MachineEntity machine : group.getMachines()) {
            machines.add(machine);
          }
        }
        result = machinesTable(machines, true);
        nextCmd = "watch -n 2 machines";
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else if (cmd.equals("tasks")) {
      if (chosenCluster() != null) {
        ClusterManager cluster = cluster(chosenCluster());
        ClusterEntity clusterEntity = cluster.getRuntime();
        result = machinesTasksTable(clusterEntity);
        nextCmd = "watch -n 2 tasks";
      } else {
        result = "no cluster has been chosen yet!!";
      }
    } else {
      boolean found = false;
      Pattern p = Pattern.compile("use\\s+(\\w+)");
      Matcher matcher = p.matcher(cmd);
      if (!found && matcher.matches()) {
        found = true;
        String clusterName = matcher.group(1);
        if (cluster(clusterName) != null) {
          chosenCluster = clusterName;
          result = String.format("switched to %s now", clusterName);
        } else {
          result = String.format("cluster %s is not registered yet!!", clusterName);
        }
      }

      p = Pattern.compile("remove\\s+(\\w+)");
      matcher = p.matcher(cmd);
      if (!found && matcher.matches()) {
        found = true;
        String clusterName = matcher.group(1);
        if (cluster(clusterName) != null) {
          result = String.format("%s is running now, terminate it first!!", clusterName);
        } else {
          ClusterDefinitionService.removeDefinition(clusterName);
{'fraction_non_alphanumeric': 0.13856606472376184, 'fraction_numerical': 0.0019667441444662973, 'mean_word_length': 2.60550064460679, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5109808', 'n_tokens_mistral': 4690, 'n_tokens_neox': 4590, 'n_words': 1138}