use of io.fabric8.insight.metrics.model.Request 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();
}
use of io.fabric8.insight.metrics.model.Request in project docker-maven-plugin by fabric8io.
the class QueryService method getLatestContainerForImage.
/**
* Get the id of the latest container started for an image
*
* @param image for which its container are looked up
* @return container or <code>null</code> if no container has been started for this image.
* @throws DockerAccessException if the request fails
*/
public Container getLatestContainerForImage(String image) throws DockerAccessException {
long newest = 0;
Container result = null;
for (Container container : getContainersForImage(image)) {
long timestamp = container.getCreated();
if (timestamp < newest) {
continue;
}
newest = timestamp;
result = container;
}
return result;
}
use of io.fabric8.insight.metrics.model.Request in project docker-maven-plugin by fabric8io.
the class EcrExtendedAuthTest method testHeaders.
@Test
public void testHeaders() throws ParseException {
EcrExtendedAuth eea = new EcrExtendedAuth(logger, "123456789012.dkr.ecr.eu-west-1.amazonaws.com");
AuthConfig localCredentials = new AuthConfig("username", "password", null, null);
Date signingTime = AwsSigner4Request.TIME_FORMAT.parse("20161217T211058Z");
HttpPost request = eea.createSignedRequest(localCredentials, signingTime);
assertEquals("ecr.eu-west-1.amazonaws.com", request.getFirstHeader("host").getValue());
assertEquals("20161217T211058Z", request.getFirstHeader("X-Amz-Date").getValue());
assertEquals("AWS4-HMAC-SHA256 Credential=username/20161217/eu-west-1/ecr/aws4_request, SignedHeaders=content-type;host;x-amz-target, Signature=1bab0f5c269debe913e532011d5d192b190bb4c55d3de1bc1506eefb93e058e1", request.getFirstHeader("Authorization").getValue());
}
use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.
the class JolokiaFabricConnector method connect.
/**
* connects to a fabric
*/
public void connect() {
if (this.j4p != null || this.fabricServiceFacade != null) {
disconnect();
}
this.j4p = J4pClient.url(this.url).user(this.userName).password(this.password).build();
/* This needs further investigation...
DefaultHttpClient httpClient = (DefaultHttpClient) j4p.getHttpClient();
httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return true;
}
});
*/
this.fabricServiceFacade = new FabricServiceFacade(this);
this.fabricMBeanFacade = new FabricMBean(this);
}
use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.
the class OpenShiftDeployAgent method onConfigurationChanged.
protected void onConfigurationChanged() {
LOGGER.info("Configuration has changed; so checking the Fabric managed Java cartridges on OpenShift are up to date");
Container[] containers = fabricService.get().getContainers();
for (Container container : containers) {
Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService.get(), container.getOverlayProfile());
Map<String, String> openshiftConfiguration = effectiveProfile.getConfiguration(OpenShiftConstants.OPENSHIFT_PID);
if (openshiftConfiguration != null) {
DeploymentUpdater deployTask = null;
try {
deployTask = createDeployTask(container, openshiftConfiguration);
} catch (MalformedURLException e) {
LOGGER.error("Failed to create DeploymentUpdater. " + e, e);
}
if (deployTask != null && OpenShiftUtils.isFabricManaged(openshiftConfiguration)) {
String containerId = container.getId();
IOpenShiftConnection connection = OpenShiftUtils.createConnection(container);
CreateOpenshiftContainerOptions options = OpenShiftUtils.getCreateOptions(container);
if (connection == null || options == null) {
LOGGER.warn("Ignoring container which has no openshift connection or options. connection: " + connection + " options: " + options);
} else {
try {
IApplication application = OpenShiftUtils.getApplication(container, connection);
if (application != null) {
final String gitUrl = application.getGitUrl();
if (gitUrl != null) {
LOGGER.info("Git URL is " + gitUrl);
final CartridgeGitRepository repo = new CartridgeGitRepository(containerId);
final List<IOpenShiftSSHKey> sshkeys = application.getDomain().getUser().getSSHKeys();
final CredentialsProvider credentials = new CredentialsProvider() {
@Override
public boolean supports(CredentialItem... items) {
return true;
}
@Override
public boolean isInteractive() {
return true;
}
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
LOGGER.info("Credential request " + uri + " items " + Arrays.asList(items));
int i = -1;
for (CredentialItem item : items) {
if (item instanceof CredentialItem.StringType) {
CredentialItem.StringType stringType = (CredentialItem.StringType) item;
int idx = ++i < sshkeys.size() ? i : 0;
if (idx < sshkeys.size()) {
IOpenShiftSSHKey sshKey = sshkeys.get(idx);
String passphrase = sshKey.getPublicKey();
LOGGER.info("For item " + item + " index " + i + " using passphrase: " + passphrase);
stringType.setValue(passphrase);
} else {
LOGGER.warn("No ssh keys we can pass into git!");
}
continue;
} else {
LOGGER.warn("Unknown CredentialItem " + item);
}
}
return true;
}
};
final DeploymentUpdater finalDeployTask = deployTask;
SshSessionFactoryUtils.useOpenShiftSessionFactory(new Callable<Object>() {
@Override
public Object call() throws Exception {
repo.cloneOrPull(gitUrl, credentials);
finalDeployTask.updateDeployment(repo.getGit(), repo.getLocalRepo(), credentials);
return null;
}
});
}
}
} catch (Exception e) {
LOGGER.error("Failed to update container " + containerId + ". Reason: " + e, e);
} finally {
OpenShiftUtils.close(connection);
}
}
}
}
}
}
Aggregations