Search in sources :

Example 1 with CommandResult

use of org.aesh.command.CommandResult in project infinispan by infinispan.

the class Install method exec.

@Override
public CommandResult exec(ContextAwareCommandInvocation invocation) {
    if (namespace != null && (targetNamespaces == null || targetNamespaces.isEmpty())) {
        throw Messages.MSG.noTargetNamespaces();
    }
    KubernetesClient client = KubernetesContext.getClient(invocation);
    if (source == null) {
        // Determine whether this is OpenShift or K8S+OLM
        List<GenericKubernetesResource> sources = client.genericKubernetesResources(Kube.OPERATOR_CATALOGSOURCE_CRD).inAnyNamespace().list().getItems();
        Optional<GenericKubernetesResource> catalog = sources.stream().filter(cs -> Version.getProperty("infinispan.olm.k8s.source").equals(cs.getMetadata().getName())).findFirst();
        if (!catalog.isPresent()) {
            catalog = sources.stream().filter(cs -> Version.getProperty("infinispan.olm.openshift.source").equals(cs.getMetadata().getName())).findFirst();
        }
        if (catalog.isPresent()) {
            GenericKubernetesResource catalogSource = catalog.get();
            source = catalogSource.getMetadata().getName();
            sourceNamespace = catalogSource.getMetadata().getNamespace();
        } else {
            throw Messages.MSG.noCatalog();
        }
    }
    String olmName = Version.getProperty("infinispan.olm.name");
    if (namespace == null) {
        namespace = Kube.defaultOperatorNamespace(client);
    } else {
        // Non-global, we need to create an operator group
        GenericKubernetesResource group = new GenericKubernetesResource();
        group.setKind(Kube.OPERATOR_OPERATORGROUP_CRD.getKind());
        ObjectMeta groupMetadata = new ObjectMeta();
        groupMetadata.setName(olmName);
        groupMetadata.setNamespace(namespace);
        group.setMetadata(groupMetadata);
        GenericKubernetesResource groupSpec = new GenericKubernetesResource();
        groupSpec.setAdditionalProperty("targetNamespaces", targetNamespaces);
        group.setAdditionalProperty("spec", groupSpec);
        client.genericKubernetesResources(Kube.OPERATOR_OPERATORGROUP_CRD).inNamespace(namespace).createOrReplace(group);
    }
    GenericKubernetesResource subscription = new GenericKubernetesResource();
    subscription.setKind(Kube.OPERATOR_SUBSCRIPTION_CRD.getKind());
    ObjectMeta subscriptionMetadata = new ObjectMeta();
    subscriptionMetadata.setName(olmName);
    subscriptionMetadata.setNamespace(namespace);
    subscription.setMetadata(subscriptionMetadata);
    GenericKubernetesResource subscriptionSpec = new GenericKubernetesResource();
    subscriptionSpec.setAdditionalProperty("name", olmName);
    subscriptionSpec.setAdditionalProperty("installPlanApproval", manual ? "Manual" : "Automatic");
    subscriptionSpec.setAdditionalProperty("source", source);
    subscriptionSpec.setAdditionalProperty("sourceNamespace", sourceNamespace);
    if (channel != null) {
        subscriptionSpec.setAdditionalProperty("channel", channel);
    }
    subscription.setAdditionalProperty("spec", subscriptionSpec);
    client.genericKubernetesResources(Kube.OPERATOR_SUBSCRIPTION_CRD).inNamespace(namespace).createOrReplace(subscription);
    return CommandResult.SUCCESS;
}
Also used : CommandDefinition(org.aesh.command.CommandDefinition) OptionList(org.aesh.command.option.OptionList) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Messages(org.infinispan.cli.logging.Messages) CliCommand(org.infinispan.cli.commands.CliCommand) List(java.util.List) Version(org.infinispan.commons.util.Version) KubernetesContext(org.infinispan.cli.impl.KubernetesContext) ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) CommandResult(org.aesh.command.CommandResult) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Optional(java.util.Optional) Option(org.aesh.command.option.Option) ContextAwareCommandInvocation(org.infinispan.cli.impl.ContextAwareCommandInvocation) ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource)

Example 2 with CommandResult

use of org.aesh.command.CommandResult in project infinispan by infinispan.

the class Help method execute.

@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    Shell shell = commandInvocation.getShell();
    if (manPages == null || manPages.size() == 0) {
        shell.writeln("Call `help <command>` where command is one of:");
        List<TerminalString> commandNames = ((ContextAwareCommandInvocation) commandInvocation).getContext().getRegistry().getAllCommandNames().stream().map(n -> new TerminalString(n)).collect(Collectors.toList());
        // then we print out the completions
        shell.write(Parser.formatDisplayListTerminalString(commandNames, shell.size().getHeight(), shell.size().getWidth()));
        // then on the next line we write the line again
        shell.writeln("");
        return CommandResult.SUCCESS;
    }
    if (manPages.size() <= 0) {
        shell.write("No manual entry for " + manPages.get(0) + Config.getLineSeparator());
        return CommandResult.SUCCESS;
    }
    if (manProvider == null) {
        shell.write("No manual provider defined");
        return CommandResult.SUCCESS;
    }
    InputStream inputStream = manProvider.getManualDocument(manPages.get(0));
    if (inputStream != null) {
        setCommandInvocation(commandInvocation);
        try {
            fileParser.setInput(inputStream);
            afterAttach();
        } catch (IOException ex) {
            throw new CommandException(ex);
        }
    }
    return CommandResult.SUCCESS;
}
Also used : CommandDefinition(org.aesh.command.CommandDefinition) Parser(org.aesh.readline.util.Parser) ManProvider(org.aesh.command.settings.ManProvider) MetaInfServices(org.kohsuke.MetaInfServices) TerminalPage(org.aesh.command.man.TerminalPage) Command(org.aesh.command.Command) FileParser(org.aesh.command.man.FileParser) ArrayList(java.util.ArrayList) ManFileParser(org.aesh.command.man.parser.ManFileParser) CommandResult(org.aesh.command.CommandResult) ANSI(org.aesh.terminal.utils.ANSI) Shell(org.aesh.command.shell.Shell) Config(org.aesh.terminal.utils.Config) ContextAwareCommandInvocation(org.infinispan.cli.impl.ContextAwareCommandInvocation) CliManProvider(org.infinispan.cli.impl.CliManProvider) IOException(java.io.IOException) CommandInvocation(org.aesh.command.invocation.CommandInvocation) Collectors(java.util.stream.Collectors) CommandException(org.aesh.command.CommandException) Arguments(org.aesh.command.option.Arguments) List(java.util.List) TerminalString(org.aesh.readline.terminal.formatting.TerminalString) AeshFileDisplayer(org.aesh.command.man.AeshFileDisplayer) HelpCompleter(org.infinispan.cli.completers.HelpCompleter) InputStream(java.io.InputStream) Shell(org.aesh.command.shell.Shell) InputStream(java.io.InputStream) TerminalString(org.aesh.readline.terminal.formatting.TerminalString) IOException(java.io.IOException) CommandException(org.aesh.command.CommandException)

Example 3 with CommandResult

use of org.aesh.command.CommandResult in project infinispan by infinispan.

the class Shell method exec.

@Override
public CommandResult exec(ContextAwareCommandInvocation invocation) {
    KubernetesClient client = KubernetesContext.getClient(invocation);
    namespace = Kube.getNamespaceOrDefault(client, namespace);
    GenericKubernetesResource infinispan = client.genericKubernetesResources(INFINISPAN_CLUSTER_CRD).inNamespace(namespace).withName(name).get();
    if (infinispan == null) {
        throw Messages.MSG.noSuchService(name, namespace);
    }
    String endpointSecretName = Kube.getProperty(infinispan, "spec", "security", "endpointSecretName");
    String certSecretName = Kube.getProperty(infinispan, "spec", "security", "endpointEncryption", "certSecretName");
    Pod pod;
    if (podName == null) {
        pod = client.pods().inNamespace(namespace).withLabel("infinispan_cr", name).list().getItems().stream().filter(p -> "running".equalsIgnoreCase(p.getStatus().getPhase())).findFirst().orElse(null);
    } else {
        pod = client.pods().inNamespace(namespace).withName(podName).get();
    }
    if (pod == null) {
        throw Messages.MSG.noRunningPodsInService(name);
    }
    // Port forwarding mode
    List<ContainerPort> ports = pod.getSpec().getContainers().get(0).getPorts();
    // Find the `infinispan` port
    ContainerPort containerPort = ports.stream().filter(p -> "infinispan".equals(p.getName())).findFirst().get();
    try (LocalPortForward portForward = client.pods().inNamespace(namespace).withName(pod.getMetadata().getName()).portForward(containerPort.getContainerPort())) {
        StringBuilder connection = new StringBuilder();
        List<String> args = new ArrayList<>();
        if (certSecretName != null) {
            connection.append("https://");
            Secret secret = Kube.getSecret(client, namespace, certSecretName);
            final byte[] cert;
            final String suffix;
            if (secret.getData().containsKey("keystore.p12")) {
                cert = Base64.getDecoder().decode(secret.getData().get("keystore.p12"));
                suffix = ".p12";
                String password = new String(Base64.getDecoder().decode(secret.getData().get("password")));
                args.add("-s");
                args.add(password);
            } else {
                cert = new String(Base64.getDecoder().decode(secret.getData().get("tls.crt"))).getBytes(StandardCharsets.UTF_8);
                suffix = ".pem";
            }
            Path certPath = Files.createTempFile("clitrust", suffix, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
            Files.write(certPath, cert);
            args.add("-t");
            args.add(certPath.toString());
            args.add("--hostname-verifier");
            args.add(".*");
        } else {
            connection.append("http://");
        }
        if (endpointSecretName != null) {
            Secret secret = Kube.getSecret(client, namespace, endpointSecretName);
            Map<String, String> credentials = Kube.decodeOpaqueSecrets(secret);
            if (username == null) {
                if (credentials.size() != 1) {
                    throw Messages.MSG.usernameRequired();
                } else {
                    Map.Entry<String, String> entry = credentials.entrySet().iterator().next();
                    connection.append(entry.getKey());
                    connection.append(':');
                    connection.append(entry.getValue());
                    connection.append('@');
                }
            } else {
                connection.append(username);
                if (credentials.containsKey(username)) {
                    connection.append(':');
                    connection.append(credentials.get(username));
                }
                connection.append('@');
            }
        }
        InetAddress localAddress = portForward.getLocalAddress();
        if (localAddress.getAddress().length == 4) {
            connection.append(localAddress.getHostAddress());
        } else {
            connection.append('[').append(localAddress.getHostAddress()).append(']');
        }
        connection.append(':');
        connection.append(portForward.getLocalPort());
        args.add("-c");
        args.add(connection.toString());
        Messages.CLI.debugf("cli %s", args);
        CLI.main(new DefaultShell(), args.toArray(new String[0]), System.getProperties(), false);
        return CommandResult.SUCCESS;
    } catch (Throwable t) {
        TerminalString error = new TerminalString(Util.getRootCause(t).getLocalizedMessage(), new TerminalColor(Color.RED, Color.DEFAULT, Color.Intensity.BRIGHT));
        invocation.getShell().writeln(error.toString());
        return CommandResult.FAILURE;
    }
}
Also used : CommandDefinition(org.aesh.command.CommandDefinition) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) LocalPortForward(io.fabric8.kubernetes.client.LocalPortForward) Argument(org.aesh.command.option.Argument) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) TerminalColor(org.aesh.readline.terminal.formatting.TerminalColor) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) Map(java.util.Map) CommandResult(org.aesh.command.CommandResult) Path(java.nio.file.Path) DEFAULT_CLUSTER_NAME(org.infinispan.cli.commands.kubernetes.Kube.DEFAULT_CLUSTER_NAME) Option(org.aesh.command.option.Option) ContextAwareCommandInvocation(org.infinispan.cli.impl.ContextAwareCommandInvocation) Files(java.nio.file.Files) Messages(org.infinispan.cli.logging.Messages) Util(org.infinispan.commons.util.Util) Color(org.aesh.readline.terminal.formatting.Color) Pod(io.fabric8.kubernetes.api.model.Pod) CliCommand(org.infinispan.cli.commands.CliCommand) StandardCharsets(java.nio.charset.StandardCharsets) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) Base64(java.util.Base64) List(java.util.List) TerminalString(org.aesh.readline.terminal.formatting.TerminalString) CLI(org.infinispan.cli.commands.CLI) KubernetesContext(org.infinispan.cli.impl.KubernetesContext) INFINISPAN_CLUSTER_CRD(org.infinispan.cli.commands.kubernetes.Kube.INFINISPAN_CLUSTER_CRD) DefaultShell(org.infinispan.cli.impl.DefaultShell) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Secret(io.fabric8.kubernetes.api.model.Secret) Path(java.nio.file.Path) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) LocalPortForward(io.fabric8.kubernetes.client.LocalPortForward) Pod(io.fabric8.kubernetes.api.model.Pod) ArrayList(java.util.ArrayList) TerminalString(org.aesh.readline.terminal.formatting.TerminalString) TerminalString(org.aesh.readline.terminal.formatting.TerminalString) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource) Secret(io.fabric8.kubernetes.api.model.Secret) DefaultShell(org.infinispan.cli.impl.DefaultShell) TerminalColor(org.aesh.readline.terminal.formatting.TerminalColor) ContainerPort(io.fabric8.kubernetes.api.model.ContainerPort) Map(java.util.Map) InetAddress(java.net.InetAddress)

Aggregations

List (java.util.List)3 CommandDefinition (org.aesh.command.CommandDefinition)3 CommandResult (org.aesh.command.CommandResult)3 ContextAwareCommandInvocation (org.infinispan.cli.impl.ContextAwareCommandInvocation)3 GenericKubernetesResource (io.fabric8.kubernetes.api.model.GenericKubernetesResource)2 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)2 ArrayList (java.util.ArrayList)2 Option (org.aesh.command.option.Option)2 TerminalString (org.aesh.readline.terminal.formatting.TerminalString)2 ContainerPort (io.fabric8.kubernetes.api.model.ContainerPort)1 ObjectMeta (io.fabric8.kubernetes.api.model.ObjectMeta)1 Pod (io.fabric8.kubernetes.api.model.Pod)1 Secret (io.fabric8.kubernetes.api.model.Secret)1 LocalPortForward (io.fabric8.kubernetes.client.LocalPortForward)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InetAddress (java.net.InetAddress)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1