Search in sources :

Example 41 with Request

use of io.fabric8.insight.metrics.model.Request in project curiostack by curioswitch.

the class CreateClientCertTask method exec.

@TaskAction
public void exec() {
    ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
    String commonName = (String) getProject().getRootProject().findProperty("commonName");
    checkNotNull(commonName, "-PcommonName must be set");
    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=" + commonName), keyPair.getPublic());
    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));
    String csrName = cluster.namespace() + "." + commonName + ".client.crt";
    Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", csrName), "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() ? new File(config.platformConfig().gcloudBinDir(), "kubectl").getAbsolutePath() : "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", csrName);
    });
    // Need to wait a bit for certificate to propagate before fetching.
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    ByteArrayOutputStream certStream = new ByteArrayOutputStream();
    getProject().exec(exec -> {
        exec.executable(command);
        exec.args("get", "csr", csrName, "-o", "jsonpath={.status.certificate}");
        exec.setStandardOutput(certStream);
    });
    String certificate = new String(Base64.getDecoder().decode(certStream.toByteArray()), 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(commonName + "-client-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("client.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "client-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
    client.resource(certificateSecret).createOrReplace();
}
Also used : ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) 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) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) Secret(io.fabric8.kubernetes.api.model.Secret) PemObject(org.bouncycastle.util.io.pem.PemObject) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) PemObject(org.bouncycastle.util.io.pem.PemObject) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) NoSuchProviderException(java.security.NoSuchProviderException) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) File(java.io.File) TaskAction(org.gradle.api.tasks.TaskAction)

Example 42 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by fabric8io.

the class DevOpsConnector method createGerritRepo.

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd, String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {
    // lets add defaults if not env vars
    if (Strings.isNullOrBlank(gerritUser)) {
        gerritUser = "admin";
    }
    if (Strings.isNullOrBlank(gerritPwd)) {
        gerritPwd = "secret";
    }
    log.info("A Gerrit git repo will be created for this name : " + repoName);
    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http", true);
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace + " on Kubernetes address: " + kubernetes.getMasterUrl());
    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpClient httpclientPost = HttpClients.createDefault();
    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;
    HttpGet httpget = new HttpGet(GERRIT_URL);
    System.out.println("Requesting : " + httpget.getURI());
    try {
        // Initial request without credentials returns "HTTP/1.1 401 Unauthorized"
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getStatusLine());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // Get current current "WWW-Authenticate" header from response
            // WWW-Authenticate:Digest realm="My Test Realm", qop="auth",
            // nonce="cdcf6cbe6ee17ae0790ed399935997e8", opaque="ae40d7c8ca6a35af15460d352be5e71c"
            Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
            System.out.println("authHeader = " + authHeader);
            DigestScheme digestScheme = new DigestScheme();
            // Parse realm, nonce sent by server.
            digestScheme.processChallenge(authHeader);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(gerritUser, gerritPwd);
            httpget.addHeader(digestScheme.authenticate(creds, httpget, null));
            HttpPost httpPost = new HttpPost(GERRIT_URL);
            httpPost.addHeader(digestScheme.authenticate(creds, httpPost, null));
            httpPost.addHeader("Content-Type", "application/json");
            CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
            createRepoDTO.setDescription(gerritGitRepoDescription);
            createRepoDTO.setName(repoName);
            createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(createRepoDTO);
            HttpEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclientPost.execute(httpPost, responseHandler);
            System.out.println("responseBody : " + responseBody);
        }
    } catch (MalformedChallengeException e) {
        e.printStackTrace();
    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        System.out.println("Gerrit Server is not responding");
    } catch (HttpResponseException e) {
        System.out.println("Response from Gerrit Server : " + e.getMessage());
        throw new Exception("Repository " + repoName + " already exists !");
    } finally {
        httpclient.close();
        httpclientPost.close();
    }
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponse(org.apache.http.HttpResponse) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) SAXException(org.xml.sax.SAXException) WebApplicationException(javax.ws.rs.WebApplicationException) AuthenticationException(org.apache.http.auth.AuthenticationException) ConnectException(java.net.ConnectException) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) Header(org.apache.http.Header) CreateRepositoryDTO(io.fabric8.gerrit.CreateRepositoryDTO) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConnectException(java.net.ConnectException)

Example 43 with Request

use of io.fabric8.insight.metrics.model.Request in project syndesis by syndesisio.

the class SupportUtil method getLogs.

public Optional<Reader> getLogs(String label, String integrationName) {
    return client.pods().list().getItems().stream().filter(pod -> integrationName.equals(pod.getMetadata().getLabels().get(label))).findAny().map(pod -> pod.getMetadata().getName()).flatMap(podName -> {
        PodOperationsImpl pod = (PodOperationsImpl) client.pods().withName(podName);
        try {
            Request request = new Request.Builder().url(pod.getResourceUrl().toString() + "/log?pretty=false&timestamps=true").build();
            Response response = null;
            try {
                response = okHttpClient.newCall(request).execute();
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected response from /log endpoint: " + response);
                }
                return Optional.of(new RegexBasedMasqueradeReader(new BufferedReader(response.body().charStream()), MASKING_REGEXP));
            } catch (IOException e) {
                // NOPMD
                LOG.error("Error downloading log file for integration {}", integrationName, e);
                if (response != null) {
                    response.close();
                }
            }
        } catch (MalformedURLException e) {
            LOG.error("Error downloading log file for integration {}", integrationName, e);
        }
        return Optional.empty();
    });
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) Yaml(org.yaml.snakeyaml.Yaml) DumperOptions(org.yaml.snakeyaml.DumperOptions) Service(org.springframework.stereotype.Service) Map(java.util.Map) OutputStreamWriter(java.io.OutputStreamWriter) IntegrationOverview(io.syndesis.common.model.integration.IntegrationOverview) Response(okhttp3.Response) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) ZipEntry(java.util.zip.ZipEntry) HttpClientUtils(io.fabric8.kubernetes.client.utils.HttpClientUtils) OutputStream(java.io.OutputStream) ImageStreamTag(io.fabric8.openshift.api.model.ImageStreamTag) Request(okhttp3.Request) PodOperationsImpl(io.fabric8.kubernetes.client.dsl.internal.PodOperationsImpl) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) Collection(java.util.Collection) NamespacedOpenShiftClient(io.fabric8.openshift.client.NamespacedOpenShiftClient) FileOutputStream(java.io.FileOutputStream) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) IOException(java.io.IOException) StreamingOutput(javax.ws.rs.core.StreamingOutput) ListResult(io.syndesis.common.model.ListResult) FileUtils(org.apache.commons.io.FileUtils) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) OkHttpClient(okhttp3.OkHttpClient) StringReader(java.io.StringReader) IntegrationSupportHandler(io.syndesis.server.endpoint.v1.handler.integration.support.IntegrationSupportHandler) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) IntegrationHandler(io.syndesis.server.endpoint.v1.handler.integration.IntegrationHandler) BufferedReader(java.io.BufferedReader) UriInfo(javax.ws.rs.core.UriInfo) InputStream(java.io.InputStream) Response(okhttp3.Response) MalformedURLException(java.net.MalformedURLException) Request(okhttp3.Request) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) PodOperationsImpl(io.fabric8.kubernetes.client.dsl.internal.PodOperationsImpl)

Example 44 with Request

use of io.fabric8.insight.metrics.model.Request in project zalenium by zalando.

the class KubernetesContainerClient method buildResourceMaps.

private void buildResourceMaps() {
    for (Resources resource : Resources.values()) {
        String envValue = environment.getStringEnvVariable(resource.getEnvVar(), null);
        if (StringUtils.isNotBlank(envValue)) {
            Map<String, Quantity> resourceMap = null;
            switch(resource.getResourceType()) {
                case REQUEST:
                    resourceMap = seleniumPodRequests;
                    break;
                case LIMIT:
                    resourceMap = seleniumPodLimits;
                    break;
                default:
                    break;
            }
            if (resourceMap != null) {
                Quantity quantity = new Quantity(envValue);
                resourceMap.put(resource.getRequestType(), quantity);
            }
        }
    }
}
Also used : Quantity(io.fabric8.kubernetes.api.model.Quantity)

Aggregations

IOException (java.io.IOException)17 HashMap (java.util.HashMap)9 File (java.io.File)8 Test (org.junit.Test)8 ByteArrayInputStream (java.io.ByteArrayInputStream)5 MalformedURLException (java.net.MalformedURLException)5 Map (java.util.Map)5 FabricService (io.fabric8.api.FabricService)4 RuntimeProperties (io.fabric8.api.RuntimeProperties)4 AbstractRuntimeProperties (io.fabric8.api.scr.AbstractRuntimeProperties)4 MavenResolver (io.fabric8.maven.MavenResolver)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Date (java.util.Date)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Container (io.fabric8.api.Container)3 NameValidator (io.fabric8.api.NameValidator)3 FileInputStream (java.io.FileInputStream)3