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();
}
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();
}
}
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×tamps=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();
});
}
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);
}
}
}
}
Aggregations