Search in sources :

Example 1 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project curiostack by curioswitch.

the class RequestNamespaceCertTask method exec.

@TaskAction
public void exec() {
    ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
    final KeyPairGenerator keygen;
    try {
        keygen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new IllegalStateException("Could not find RSA, can't happen.", e);
    }
    keygen.initialize(256, new SecureRandom());
    KeyPair keyPair = keygen.generateKeyPair();
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + cluster.namespace() + ".ns.cluster.stellarstation.com"), keyPair.getPublic());
    Stream<GeneralName> generalNames = Streams.concat(Stream.of(new GeneralName(GeneralName.dNSName, "*." + cluster.namespace()), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc"), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc.cluster.local")), cluster.extraNamespaceTlsHosts().stream().map(name -> new GeneralName(GeneralName.dNSName, name)));
    GeneralNames subjectAltNames = new GeneralNames(generalNames.toArray(GeneralName[]::new));
    ExtensionsGenerator extensions = new ExtensionsGenerator();
    try {
        extensions.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.setAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions.generate());
    } catch (IOException e) {
        throw new IllegalStateException("Could not encode cert name, can't happen.", e);
    }
    final ContentSigner signer;
    try {
        signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        throw new IllegalStateException("Could not find signer, can't happen.", e);
    }
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    StringWriter csrWriter = new StringWriter();
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(csrWriter)) {
        pemWriter.writeObject(csr);
    } catch (IOException e) {
        throw new IllegalStateException("Could not encode csr, can't happen.", e);
    }
    String encodedCsr = Base64.getEncoder().encodeToString(csrWriter.toString().getBytes(StandardCharsets.UTF_8));
    Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", cluster.namespace() + ".server.crt"), "spec", ImmutableMap.of("request", encodedCsr, "usages", ImmutableList.of("digital signature", "key encipherment", "server auth", "client auth")));
    final byte[] encodedApiRequest;
    try {
        encodedApiRequest = OBJECT_MAPPER.writeValueAsBytes(csrApiRequest);
    } catch (JsonProcessingException e) {
        throw new IllegalStateException("Could not encode yaml", e);
    }
    ImmutableGcloudExtension config = getProject().getRootProject().getExtensions().getByType(GcloudExtension.class);
    String command = config.download() ? CommandUtil.getGcloudSdkBinDir(getProject()).resolve("kubectl").toAbsolutePath().toString() : "kubectl";
    getProject().exec(exec -> {
        exec.executable(command);
        exec.args("create", "-f", "-");
        exec.setStandardInput(new ByteArrayInputStream(encodedApiRequest));
    });
    getProject().exec(exec -> {
        exec.executable(command);
        exec.args("certificate", "approve", cluster.namespace() + ".server.crt");
    });
    // Need to wait a bit for certificate to propagate before fetching.
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    // Gradle Exec seems to be flaky when reading from stdout, so use normal ProcessBuilder.
    final byte[] certificateBytes;
    try {
        Process getCertProcess = new ProcessBuilder(command, "get", "csr", cluster.namespace() + ".server.crt", "-o", "jsonpath={.status.certificate}").start();
        certificateBytes = ByteStreams.toByteArray(getCertProcess.getInputStream());
    } catch (IOException e) {
        throw new UncheckedIOException("Could not fetch certificate.", e);
    }
    String certificate = new String(Base64.getDecoder().decode(certificateBytes), StandardCharsets.UTF_8);
    final JcaPKCS8Generator keyGenerator;
    final PemObject keyObject;
    try {
        keyGenerator = new JcaPKCS8Generator(keyPair.getPrivate(), null);
        keyObject = keyGenerator.generate();
    } catch (PemGenerationException e) {
        throw new IllegalStateException("Could not encode to pkcs8.", e);
    }
    StringWriter keyWriter = new StringWriter();
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(keyWriter)) {
        pemWriter.writeObject(keyObject);
    } catch (IOException e) {
        throw new IllegalStateException("Could not encode csr, can't happen.", e);
    }
    String key = keyWriter.toString();
    KubernetesClient client = new DefaultKubernetesClient();
    Secret certificateSecret = new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("server-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("server.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "server-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
    client.resource(certificateSecret).createOrReplace();
}
Also used : KeyPair(java.security.KeyPair) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Extension(org.bouncycastle.asn1.x509.Extension) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Security(java.security.Security) SecureRandom(java.security.SecureRandom) TaskAction(org.gradle.api.tasks.TaskAction) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) DefaultTask(org.gradle.api.DefaultTask) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KeyPairGenerator(java.security.KeyPairGenerator) PemObject(org.bouncycastle.util.io.pem.PemObject) ImmutableMap(com.google.common.collect.ImmutableMap) Streams(com.google.common.collect.Streams) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Base64(java.util.Base64) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Stream(java.util.stream.Stream) GcloudExtension(org.curioswitch.gradle.plugins.gcloud.GcloudExtension) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteStreams(com.google.common.io.ByteStreams) Secret(io.fabric8.kubernetes.api.model.Secret) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) X500Principal(javax.security.auth.x500.X500Principal) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) ContentSigner(org.bouncycastle.operator.ContentSigner) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) ImmutableList(com.google.common.collect.ImmutableList) ClusterExtension(org.curioswitch.gradle.plugins.gcloud.ClusterExtension) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) TimeUnit(java.util.concurrent.TimeUnit) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) CommandUtil(org.curioswitch.gradle.plugins.shared.CommandUtil) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) NoSuchProviderException(java.security.NoSuchProviderException) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) UncheckedIOException(java.io.UncheckedIOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) StringWriter(java.io.StringWriter) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) Secret(io.fabric8.kubernetes.api.model.Secret) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) NoSuchProviderException(java.security.NoSuchProviderException) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) TaskAction(org.gradle.api.tasks.TaskAction)

Example 2 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project docker-maven-plugin by fabric8io.

the class DockerAssemblyManager method verifyGivenDockerfile.

// visible for testing
void verifyGivenDockerfile(File dockerFile, BuildImageConfiguration buildConfig, FixedStringSearchInterpolator interpolator, Logger log) throws IOException {
    AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration();
    if (assemblyConfig == null) {
        return;
    }
    String name = assemblyConfig.getName();
    for (String keyword : new String[] { "ADD", "COPY" }) {
        List<String[]> lines = DockerFileUtil.extractLines(dockerFile, keyword, interpolator);
        for (String[] line : lines) {
            if (!line[0].startsWith("#")) {
                // Skip command flags like --chown
                int i;
                for (i = 1; i < line.length; i++) {
                    String component = line[i];
                    if (!component.startsWith("--")) {
                        break;
                    }
                }
                // contains an ADD/COPY ... targetDir .... All good.
                if (i < line.length && line[i].contains(name)) {
                    return;
                }
            }
        }
    }
    log.warn("Dockerfile %s does not contain an ADD or COPY directive to include assembly created at %s. Ignoring assembly.", dockerFile.getPath(), name);
}
Also used : AssemblyConfiguration(io.fabric8.maven.docker.config.AssemblyConfiguration)

Example 3 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8 by jboss-fuse.

the class ContainerConnectAction method executSshCommand.

/**
 * Executes the ssh command.
 */
private void executSshCommand(CommandSession session, String username, String password, String hostname, String port, String cmd) throws Exception {
    if (cmd == null || cmd.length() == 0) {
        // ENTESB-6826: we're connecting in "shell" mode, which isn't wise when running from bin/client or ssh
        if (session.getKeyboard().getClass().getName().equals("org.apache.sshd.common.channel.ChannelPipedInputStream")) {
            System.err.println("When connecting to remote container using \"fabric:container-connect\" using ssh or bin/client, please establish SSH session (run bin/client) first and then run \"fabric:container-connect\"");
            return;
        }
    }
    // Create the client from prototype
    SshClient client = createClient();
    String agentSocket;
    if (this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME) != null) {
        agentSocket = this.session.get(SshAgent.SSH_AUTHSOCKET_ENV_NAME).toString();
        client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, agentSocket);
    }
    try {
        ConnectFuture future = client.connect(hostname, Integer.parseInt(port));
        future.await();
        sshSession = future.getSession();
        Object oldIgnoreInterrupts = this.session.get(Console.IGNORE_INTERRUPTS);
        this.session.put(Console.IGNORE_INTERRUPTS, Boolean.TRUE);
        try {
            System.out.println("Connected");
            boolean authed = false;
            if (!authed) {
                if (username == null) {
                    throw new FabricAuthenticationException("No username specified.");
                }
                log.debug("Prompting user for password");
                String pwd = password != null ? password : ShellUtils.readLine(session, "Password: ", true);
                sshSession.authPassword(username, pwd);
                int ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                if ((ret & ClientSession.AUTHED) == 0) {
                    System.err.println("Password authentication failed");
                } else {
                    authed = true;
                }
            }
            if (!authed) {
                throw new FabricAuthenticationException("Failed to authenticate.");
            }
            // If user is authenticated credentials to session for future use.
            ShellUtils.storeFabricCredentials(session, username, password);
            ClientChannel channel;
            if (cmd != null && cmd.length() > 0) {
                channel = sshSession.createChannel("exec", cmd);
                channel.setIn(new ByteArrayInputStream(new byte[0]));
            } else {
                channel = sshSession.createChannel("shell");
                channel.setIn(new NoCloseInputStream(System.in));
                ((ChannelShell) channel).setPtyColumns(ShellUtils.getTermWidth(session));
                ((ChannelShell) channel).setupSensibleDefaultPty();
                ((ChannelShell) channel).setAgentForwarding(true);
            }
            channel.setOut(new NoCloseOutputStream(System.out));
            channel.setErr(new NoCloseOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
        } finally {
            session.put(Console.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
            sshSession.close(false);
        }
    } finally {
        client.stop();
    }
}
Also used : NoCloseInputStream(org.apache.sshd.common.util.NoCloseInputStream) SshClient(org.apache.sshd.SshClient) FabricAuthenticationException(io.fabric8.api.FabricAuthenticationException) ByteArrayInputStream(java.io.ByteArrayInputStream) ConnectFuture(org.apache.sshd.client.future.ConnectFuture) ChannelShell(org.apache.sshd.client.channel.ChannelShell) NoCloseOutputStream(org.apache.sshd.common.util.NoCloseOutputStream) ClientChannel(org.apache.sshd.ClientChannel)

Example 4 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8 by jboss-fuse.

the class ContainerStopAction method doExecute.

protected Object doExecute() throws Exception {
    Collection<String> expandedNames = super.expandGlobNames(containers);
    for (String containerName : expandedNames) {
        validateContainerName(containerName);
        if (!force && FabricCommand.isPartOfEnsemble(fabricService, containerName)) {
            System.out.println("Container is part of the ensemble. If you still want to stop it, please use --force option.");
            return null;
        }
        Container found = FabricCommand.getContainer(fabricService, containerName);
        applyUpdatedCredentials(found);
        if (found.isAlive()) {
            found.stop(force);
            found = FabricCommand.getContainer(fabricService, containerName);
            if (!found.isAlive()) {
                System.out.println("Container '" + found.getId() + "' stopped successfully.");
            } else {
                // In case of SSH container we can have timing issue with this command
                // so we will poll the status of container for a fixed number of times
                // if it's not stopped then we will output the message, otherwise we will continue normally
                int count = 0;
                boolean alive = true;
                for (count = 0; count < attemptNumber; count++) {
                    found = FabricCommand.getContainer(fabricService, containerName);
                    if (!found.isAlive()) {
                        alive = false;
                    } else {
                        Thread.sleep(pollingInterval);
                    }
                }
                if (alive) {
                    System.out.println("Container '" + found.getId() + "' was not stopped successfully, something went wrong. Check Logs.");
                }
            }
        } else {
            System.err.println("Container '" + found.getId() + "' already stopped.");
        }
    }
    return null;
}
Also used : Container(io.fabric8.api.Container)

Example 5 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8 by jboss-fuse.

the class ServerInvokerImpl method onCommand.

protected void onCommand(final Transport transport, Object data) {
    try {
        final DataByteArrayInputStream bais = new DataByteArrayInputStream((Buffer) data);
        final int size = bais.readInt();
        final long correlation = bais.readVarLong();
        // Use UTF8Buffer instead of string to avoid encoding/decoding UTF-8 strings
        // for every request.
        final UTF8Buffer service = readBuffer(bais).utf8();
        final Buffer encoded_method = readBuffer(bais);
        final ServiceFactoryHolder holder = holders.get(service);
        final MethodData methodData = holder.getMethodData(encoded_method);
        final Object svc = holder.factory.get();
        Runnable task = new Runnable() {

            public void run() {
                final DataByteArrayOutputStream baos = new DataByteArrayOutputStream();
                try {
                    // make space for the size field.
                    baos.writeInt(0);
                    baos.writeVarLong(correlation);
                } catch (IOException e) {
                    // should not happen
                    throw new RuntimeException(e);
                }
                // Lets decode the remaining args on the target's executor
                // to take cpu load off the
                methodData.invocationStrategy.service(methodData.serializationStrategy, holder.loader, methodData.method, svc, bais, baos, new Runnable() {

                    public void run() {
                        holder.factory.unget();
                        final Buffer command = baos.toBuffer();
                        // Update the size field.
                        BufferEditor editor = command.buffer().bigEndianEditor();
                        editor.writeInt(command.length);
                        queue().execute(new Runnable() {

                            public void run() {
                                transport.offer(command);
                            }
                        });
                    }
                });
            }
        };
        Executor executor;
        if (svc instanceof Dispatched) {
            executor = ((Dispatched) svc).queue();
        } else {
            executor = blockingExecutor;
        }
        executor.execute(task);
    } catch (Exception e) {
        LOGGER.info("Error while reading request", e);
    }
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) EOFException(java.io.EOFException) Dispatched(io.fabric8.dosgi.api.Dispatched) Executor(java.util.concurrent.Executor)

Aggregations

IOException (java.io.IOException)9 File (java.io.File)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 Container (io.fabric8.api.Container)5 JMXRequest (io.fabric8.api.commands.JMXRequest)4 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 FabricService (io.fabric8.api.FabricService)3 ContainerCreateConfig (io.fabric8.maven.docker.access.ContainerCreateConfig)3 Arguments (io.fabric8.maven.docker.config.Arguments)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Properties (java.util.Properties)3 TemplatedResource (com.netflix.spinnaker.halyard.core.resource.v1.TemplatedResource)2 ArtifactService (com.netflix.spinnaker.halyard.deploy.services.v1.ArtifactService)2 GenerateService (com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService)2 SpinnakerRuntimeSettings (com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings)2 Container (io.fabric8.kubernetes.api.model.Container)2