use of io.fabric8.docker.client.Config 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.docker.client.Config in project carbon-apimgt by wso2.
the class ServiceDiscovererKubernetes method buildConfig.
/**
* Builds the Config required by DefaultOpenShiftClient
* Also sets the system properties
* (1) to not refer .kube/config file and
* (2) the client to use service account procedure to get authenticated and authorised
*
* @return {@link io.fabric8.kubernetes.client.Config} object to build the client
* @throws ServiceDiscoveryException if an error occurs while building the config using externally stored token
*/
private Config buildConfig(Map<String, String> implParameters) throws ServiceDiscoveryException, APIMgtDAOException {
System.setProperty(TRY_KUBE_CONFIG, "false");
System.setProperty(TRY_SERVICE_ACCOUNT, "true");
/*
* Common to both situations,
* - Token found inside APIM pod
* - Token stored in APIM resources/security folder }
*/
ConfigBuilder configBuilder = new ConfigBuilder().withMasterUrl(implParameters.get(MASTER_URL)).withCaCertFile(implParameters.get(CA_CERT_PATH));
/*
* Check if a service account token File Name is given in the configuration
* - if not : assume APIM is running inside a pod and look for the pod's token
*/
String externalSATokenFileName = implParameters.get(EXTERNAL_SA_TOKEN_FILE_NAME);
if (StringUtils.isEmpty(externalSATokenFileName)) {
log.debug("Looking for service account token in " + POD_MOUNTED_SA_TOKEN_FILE_PATH);
String podMountedSAToken = APIFileUtils.readFileContentAsText(implParameters.get(POD_MOUNTED_SA_TOKEN_FILE_PATH));
return configBuilder.withOauthToken(podMountedSAToken).build();
} else {
log.info("Using externally stored service account token");
return configBuilder.withOauthToken(resolveToken("encrypted" + externalSATokenFileName)).build();
}
}
use of io.fabric8.docker.client.Config in project docker-maven-plugin by fabric8io.
the class StopMojo method getNetworksToRemove.
private Set<Network> getNetworksToRemove(QueryService queryService, PomLabel pomLabel) throws DockerAccessException {
if (!autoCreateCustomNetworks) {
return Collections.emptySet();
}
Set<Network> customNetworks = new HashSet<>();
Set<Network> networks = queryService.getNetworks();
for (ImageConfiguration image : getResolvedImages()) {
final NetworkConfig config = image.getRunConfiguration().getNetworkingConfig();
if (config.isCustomNetwork()) {
Network network = getNetworkByName(networks, config.getCustomNetwork());
if (network != null) {
customNetworks.add(network);
for (Container container : getContainersToStop(queryService, image)) {
if (!shouldStopContainer(container, pomLabel, image)) {
// it's sill in use don't collect it
customNetworks.remove(network);
}
}
}
}
}
return customNetworks;
}
use of io.fabric8.docker.client.Config in project fabric8 by jboss-fuse.
the class JoinAction method doExecute.
@Override
protected Object doExecute() throws Exception {
if (nonManaged) {
profile = "unmanaged";
}
String oldName = runtimeProperties.getRuntimeIdentity();
if (System.getenv("OPENSHIFT_BROKER_HOST") != null && containerName != null) {
System.err.println("Containers in OpenShift cannot be renamed");
return null;
}
if (containerName == null) {
containerName = oldName;
}
FabricValidations.validateContainerName(containerName);
Configuration bootConfiguration = configAdmin.getConfiguration(BootstrapConfiguration.COMPONENT_PID, null);
Configuration dataStoreConfiguration = configAdmin.getConfiguration(Constants.DATASTORE_PID, null);
Configuration configZook = configAdmin.getConfiguration(Constants.ZOOKEEPER_CLIENT_PID, null);
if (configZook.getProperties() != null && configZook.getProperties().get("zookeeper.url") != null) {
System.err.println("This container is already connected to a fabric");
return null;
}
Dictionary<String, Object> bootProperties = bootConfiguration.getProperties();
if (bootProperties == null) {
bootProperties = new Hashtable<>();
}
if (resolver != null) {
bootProperties.put(ZkDefs.LOCAL_RESOLVER_PROPERTY, resolver);
}
if (manualIp != null) {
bootProperties.put(ZkDefs.MANUAL_IP, manualIp);
}
if (bindAddress != null) {
bootProperties.put(ZkDefs.BIND_ADDRESS, bindAddress);
}
zookeeperPassword = zookeeperPassword != null ? zookeeperPassword : ShellUtils.retrieveFabricZookeeperPassword(session);
if (zookeeperPassword == null) {
zookeeperPassword = promptForZookeeperPassword();
}
if (zookeeperPassword == null || zookeeperPassword.isEmpty()) {
System.out.println("No password specified. Cannot join fabric ensemble.");
return null;
}
ShellUtils.storeZookeeperPassword(session, zookeeperPassword);
log.debug("Encoding ZooKeeper password.");
String encodedPassword = PasswordEncoder.encode(zookeeperPassword);
bootProperties.put(ZkDefs.MINIMUM_PORT, String.valueOf(minimumPort));
bootProperties.put(ZkDefs.MAXIMUM_PORT, String.valueOf(maximumPort));
Hashtable<String, Object> dataStoreProperties = new Hashtable<String, Object>();
Configuration cfg = configAdmin.getConfiguration(Constants.DATASTORE_PID, null);
Dictionary<String, Object> props = cfg.getProperties();
if (props != null) {
for (Enumeration<String> keys = cfg.getProperties().keys(); keys.hasMoreElements(); ) {
String k = keys.nextElement();
dataStoreProperties.put(k, cfg.getProperties().get(k));
}
}
augmentDataStoreProperties(zookeeperPassword, dataStoreProperties);
if (!containerName.equals(oldName)) {
if (force || permissionToRenameContainer()) {
if (!registerContainer(containerName, zookeeperPassword, profile, force)) {
System.err.println("A container with the name: " + containerName + " is already member of the cluster. You can specify a different name as an argument.");
return null;
}
bootProperties.put(SystemProperties.KARAF_NAME, containerName);
// Ensure that if we bootstrap CuratorFramework via RuntimeProperties password is set before the URL.
bootProperties.put("zookeeper.password", encodedPassword);
bootProperties.put("zookeeper.url", zookeeperUrl);
// Rename the container
Path propsPath = runtimeProperties.getConfPath().resolve("system.properties");
Properties systemProps = new Properties(propsPath.toFile());
systemProps.put(SystemProperties.KARAF_NAME, containerName);
// Also pass zookeeper information so that the container can auto-join after the restart.
systemProps.put("zookeeper.url", zookeeperUrl);
systemProps.put("zookeeper.password", encodedPassword);
systemProps.save();
System.setProperty("runtime.id", containerName);
System.setProperty(SystemProperties.KARAF_NAME, containerName);
System.setProperty("karaf.restart", "true");
System.setProperty("karaf.restart.clean", "false");
if (!nonManaged) {
installBundles();
}
// it's only a(n almost certain) way of synchronizing CM and ManagedService.update()
if (!OsgiUtils.updateCmConfigurationAndWait(bundleContext, bootConfiguration, bootProperties, 10, TimeUnit.SECONDS)) {
log.warn("Timeout waiting for update of PID: {}", BootstrapConfiguration.COMPONENT_PID);
}
if (!OsgiUtils.updateCmConfigurationAndWait(bundleContext, dataStoreConfiguration, dataStoreProperties, 10, TimeUnit.SECONDS)) {
log.warn("Timeout waiting for update of PID: {}", Constants.DATASTORE_PID);
}
// we don't want fileinstall to trigger ConfigAdmin update
Bundle fileinstall = new BundleUtils(bundleContext).findBundle("org.apache.felix.fileinstall");
if (fileinstall != null) {
fileinstall.stop(Bundle.STOP_TRANSIENT);
}
persistConfiguration(configAdmin, Constants.DATASTORE_PID, dataStoreProperties);
// Restart the container
bundleContext.getBundle(0).stop();
return null;
} else {
return null;
}
} else {
bootConfiguration.update(bootProperties);
dataStoreConfiguration.update(dataStoreProperties);
persistConfiguration(configAdmin, Constants.DATASTORE_PID, dataStoreProperties);
if (!registerContainer(containerName, zookeeperPassword, profile, force)) {
System.err.println("A container with the name: " + containerName + " is already member of the cluster. You can specify a different name as an argument.");
return null;
}
Configuration config = configAdmin.getConfiguration(Constants.ZOOKEEPER_CLIENT_PID, null);
Hashtable<String, Object> properties = new Hashtable<String, Object>();
properties.put("zookeeper.url", zookeeperUrl);
properties.put("zookeeper.password", PasswordEncoder.encode(encodedPassword));
config.setBundleLocation(null);
config.update(properties);
if (!nonManaged) {
installBundles();
}
return null;
}
}
use of io.fabric8.docker.client.Config in project fabric8 by jboss-fuse.
the class Activator method updated.
public void updated(Dictionary<String, ?> config) {
PropertyResolver propertyResolver;
if (config == null) {
propertyResolver = new PropertyResolver() {
@Override
public String get(String propertyName) {
return m_bundleContext.getProperty(propertyName);
}
};
} else {
propertyResolver = new DictionaryPropertyResolver(config);
}
MavenConfiguration mavenConfig = new MavenConfigurationImpl(propertyResolver, PID);
MavenResolver resolver = new AetherBasedResolver(mavenConfig);
MavenResolver oldResolver = m_resolver.getAndSet(resolver);
ServiceRegistration<MavenResolver> registration = m_bundleContext.registerService(MavenResolver.class, resolver, null);
registration = m_resolverReg.getAndSet(registration);
if (registration != null) {
registration.unregister();
}
if (oldResolver != null) {
try {
oldResolver.close();
} catch (IOException e) {
// Ignore
}
}
}
Aggregations