use of io.fabric8.annotations.Path in project curiostack by curioswitch.
the class DeployPodTask method exec.
@TaskAction
public void exec() {
ImmutableDeploymentExtension config = getProject().getExtensions().getByType(DeploymentExtension.class);
final ImmutableDeploymentConfiguration deploymentConfig = config.getTypes().getByName(type);
ImmutableGcloudExtension gcloud = getProject().getRootProject().getExtensions().getByType(GcloudExtension.class);
ImmutableList.Builder<EnvVar> envVars = ImmutableList.<EnvVar>builder().addAll(deploymentConfig.envVars().entrySet().stream().map((entry) -> new EnvVar(entry.getKey(), entry.getValue(), null))::iterator).addAll(deploymentConfig.secretEnvVars().entrySet().stream().map((entry) -> new EnvVar(entry.getKey(), null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelectorBuilder().withName(entry.getValue().get(0)).withKey(entry.getValue().get(1)).build()).build()))::iterator);
if (!deploymentConfig.envVars().containsKey("JAVA_OPTS")) {
int heapSize = deploymentConfig.jvmHeapMb();
StringBuilder javaOpts = new StringBuilder();
javaOpts.append("--add-opens java.base/jdk.internal.misc=ALL-UNNAMED ").append("--add-opens jdk.unsupported/sun.misc=ALL-UNNAMED ").append("-Xms").append(heapSize).append("m ").append("-Xmx").append(heapSize).append("m ").append("-Dconfig.resource=application-").append(type).append(".conf ").append("-Dmonitoring.stackdriverProjectId=").append(gcloud.clusterProject()).append(" ").append("-Dmonitoring.serverName=").append(deploymentConfig.deploymentName()).append(" ");
if (!deploymentConfig.request()) {
int numCpus = (int) Math.ceil(Double.parseDouble(deploymentConfig.cpu()));
int numWorkers = numCpus * 2;
javaOpts.append("-XX:ParallelGCThreads=").append(numCpus).append(" ").append("-Dcom.linecorp.armeria.numCommonWorkers=").append(numWorkers).append(" ").append("-Dio.netty.availableProcessors=").append(numCpus).append(" ");
}
if (!type.equals("prod")) {
javaOpts.append("-Dcom.linecorp.armeria.verboseExceptions=true ");
}
envVars.add(new EnvVar("JAVA_OPTS", javaOpts.toString(), null));
}
Map<String, Quantity> resources = ImmutableMap.of("cpu", new Quantity(deploymentConfig.cpu()), "memory", new Quantity(deploymentConfig.memoryMb() + "Mi"));
Deployment deployment = new DeploymentBuilder().withMetadata(new ObjectMetaBuilder().withNamespace(deploymentConfig.namespace()).withName(deploymentConfig.deploymentName()).build()).withSpec(new DeploymentSpecBuilder().withReplicas(deploymentConfig.replicas()).withStrategy(new DeploymentStrategyBuilder().withType("RollingUpdate").withRollingUpdate(new RollingUpdateDeploymentBuilder().withNewMaxUnavailable(0).build()).build()).withSelector(new LabelSelectorBuilder().withMatchLabels(ImmutableMap.of("name", deploymentConfig.deploymentName())).build()).withTemplate(new PodTemplateSpecBuilder().withMetadata(new ObjectMetaBuilder().withLabels(ImmutableMap.of("name", deploymentConfig.deploymentName(), "revision", System.getenv().getOrDefault("REVISION_ID", "none"))).withAnnotations(ImmutableMap.<String, String>builder().put("prometheus.io/scrape", "true").put("prometheus.io/scheme", "https").put("prometheus.io/path", "/internal/metrics").put("prometheus.io/port", String.valueOf(deploymentConfig.containerPort())).build()).build()).withSpec(new PodSpecBuilder().withContainers(new ContainerBuilder().withResources(new ResourceRequirementsBuilder().withLimits(!deploymentConfig.request() ? resources : ImmutableMap.of()).withRequests(deploymentConfig.request() ? resources : ImmutableMap.of()).build()).withImage(deploymentConfig.image()).withName(deploymentConfig.deploymentName()).withEnv(envVars.build()).withImagePullPolicy("Always").withReadinessProbe(createProbe(deploymentConfig, Duration.ofSeconds(5))).withLivenessProbe(createProbe(deploymentConfig, Duration.ofSeconds(15))).withPorts(ImmutableList.of(new ContainerPortBuilder().withContainerPort(deploymentConfig.containerPort()).withName("http").build())).withVolumeMounts(new VolumeMountBuilder().withName("tls").withMountPath("/etc/tls").withReadOnly(true).build(), new VolumeMountBuilder().withName("rpcacls").withMountPath("/etc/rpcacls").withReadOnly(true).build()).build()).withVolumes(new VolumeBuilder().withName("tls").withSecret(new SecretVolumeSourceBuilder().withSecretName("server-tls").build()).build(), new VolumeBuilder().withName("rpcacls").withConfigMap(new ConfigMapVolumeSourceBuilder().withName("rpcacls").build()).build()).build()).build()).build()).build();
KubernetesClient client = new DefaultKubernetesClient();
Service service = new ServiceBuilder().withMetadata(new ObjectMetaBuilder().withName(deploymentConfig.deploymentName()).withNamespace(deploymentConfig.namespace()).withAnnotations(ImmutableMap.<String, String>builder().put("service.alpha.kubernetes.io/app-protocols", "{\"https\":\"HTTPS\"}").put("prometheus.io/scrape", "true").put("prometheus.io/scheme", "https").put("prometheus.io/path", "/internal/metrics").put("prometheus.io/port", String.valueOf(deploymentConfig.containerPort())).put("prometheus.io/probe", "true").build()).build()).withSpec(createServiceSpec(deploymentConfig)).build();
Map<String, Service> additionalServices = new HashMap<>();
for (String path : deploymentConfig.additionalServicePaths()) {
String sanitizedPath = path;
if (sanitizedPath.endsWith("/*")) {
sanitizedPath = sanitizedPath.substring(0, path.length() - 2);
}
String serviceName = deploymentConfig.deploymentName() + sanitizedPath.replace('/', '-');
additionalServices.put(path, new ServiceBuilder().withMetadata(new ObjectMetaBuilder().withName(serviceName).withNamespace(deploymentConfig.namespace()).withAnnotations(ImmutableMap.of("service.alpha.kubernetes.io/app-protocols", "{\"https\":\"HTTPS\"}")).build()).withSpec(createServiceSpec(deploymentConfig)).build());
}
client.resource(deployment).createOrReplace();
deployService(service, client);
additionalServices.values().forEach(s -> deployService(s, client));
if (deploymentConfig.externalHost() != null) {
List<HTTPIngressPath> ingressPaths = new ArrayList<>();
additionalServices.forEach((path, s) -> ingressPaths.add(createIngressPath(path, s.getMetadata().getName(), deploymentConfig)));
ingressPaths.add(createIngressPath("/*", deploymentConfig.deploymentName(), deploymentConfig));
Ingress ingress = new IngressBuilder().withMetadata(new ObjectMetaBuilder().withNamespace(deploymentConfig.namespace()).withName(deploymentConfig.deploymentName()).withAnnotations(ImmutableMap.of("kubernetes.io/tls-acme", "true", "kubernetes.io/ingress.class", "gce")).build()).withSpec(new IngressSpecBuilder().withTls(new IngressTLSBuilder().withSecretName(deploymentConfig.deploymentName() + "-tls").withHosts(deploymentConfig.externalHost()).build()).withRules(new IngressRuleBuilder().withHost(deploymentConfig.externalHost()).withHttp(new HTTPIngressRuleValueBuilder().withPaths(ingressPaths).build()).build()).build()).build();
client.resource(ingress).createOrReplace();
}
}
use of io.fabric8.annotations.Path in project docker-maven-plugin by fabric8io.
the class DockerAssemblyManager method createDockerTarArchive.
/**
* Create an docker tar archive from the given configuration which can be send to the Docker host for
* creating the image.
*
* @param imageName Name of the image to create (used for creating build directories)
* @param params Mojos parameters (used for finding the directories)
* @param buildConfig configuration for how to build the image
* @param log Logger used to display warning if permissions are to be normalized
* @param finalCustomizer finalCustomizer to be applied to the tar archive
* @return file holding the path to the created assembly tar file
* @throws MojoExecutionException
*/
public File createDockerTarArchive(String imageName, MojoParameters params, final BuildImageConfiguration buildConfig, Logger log, ArchiverCustomizer finalCustomizer) throws MojoExecutionException {
final BuildDirs buildDirs = createBuildDirs(imageName, params);
final AssemblyConfiguration assemblyConfig = buildConfig.getAssemblyConfiguration();
final List<ArchiverCustomizer> archiveCustomizers = new ArrayList<>();
// Build up assembly. In dockerfile mode this must be added explicitly in the Dockerfile with an ADD
if (hasAssemblyConfiguration(assemblyConfig)) {
createAssemblyArchive(assemblyConfig, params, buildDirs);
}
try {
if (buildConfig.isDockerFileMode()) {
// Use specified docker directory which must include a Dockerfile.
final File dockerFile = buildConfig.getAbsoluteDockerFilePath(params);
if (!dockerFile.exists()) {
throw new MojoExecutionException("Configured Dockerfile \"" + buildConfig.getDockerFile() + "\" (resolved to \"" + dockerFile + "\") doesn't exist");
}
FixedStringSearchInterpolator interpolator = DockerFileUtil.createInterpolator(params, buildConfig.getFilter());
verifyGivenDockerfile(dockerFile, buildConfig, interpolator, log);
interpolateDockerfile(dockerFile, buildDirs, interpolator);
// User dedicated Dockerfile from extra directory
archiveCustomizers.add(new ArchiverCustomizer() {
@Override
public TarArchiver customize(TarArchiver archiver) throws IOException {
DefaultFileSet fileSet = DefaultFileSet.fileSet(dockerFile.getParentFile());
addDockerIgnoreIfPresent(fileSet);
// Exclude non-interpolated dockerfile from source tree
// Interpolated Dockerfile is already added as it was created into the output directory when
// using dir dir mode
excludeDockerfile(fileSet, dockerFile);
// directly to docker.tar (as the output builddir is not picked up in archive mode)
if (isArchive(assemblyConfig)) {
String name = dockerFile.getName();
archiver.addFile(new File(buildDirs.getOutputDirectory(), name), name);
}
archiver.addFileSet(fileSet);
return archiver;
}
});
} else {
// Create custom docker file in output dir
DockerFileBuilder builder = createDockerFileBuilder(buildConfig, assemblyConfig);
builder.write(buildDirs.getOutputDirectory());
// Add own Dockerfile
final File dockerFile = new File(buildDirs.getOutputDirectory(), DOCKERFILE_NAME);
archiveCustomizers.add(new ArchiverCustomizer() {
@Override
public TarArchiver customize(TarArchiver archiver) throws IOException {
archiver.addFile(dockerFile, DOCKERFILE_NAME);
return archiver;
}
});
}
// If required make all files in the assembly executable
if (assemblyConfig != null) {
AssemblyConfiguration.PermissionMode mode = assemblyConfig.getPermissions();
if (mode == AssemblyConfiguration.PermissionMode.exec || mode == AssemblyConfiguration.PermissionMode.auto && EnvUtil.isWindows()) {
archiveCustomizers.add(new AllFilesExecCustomizer(log));
}
}
if (finalCustomizer != null) {
archiveCustomizers.add(finalCustomizer);
}
return createBuildTarBall(buildDirs, archiveCustomizers, assemblyConfig, buildConfig.getCompression());
} catch (IOException e) {
throw new MojoExecutionException(String.format("Cannot create %s in %s", DOCKERFILE_NAME, buildDirs.getOutputDirectory()), e);
}
}
use of io.fabric8.annotations.Path in project docker-maven-plugin by fabric8io.
the class DockerPathUtilTest method resolveNonExistentPath.
@Test
@Ignore("TODO: there is no parent to the root directory, so how can '../../relative/path' be resolved?")
public void resolveNonExistentPath() throws Exception {
// ../../relative/path
String toResolve = join(SEP, DOT + DOT, DOT + DOT, "relative", "path");
String rootDir = getFirstDirectory(createTmpFile(DockerPathUtilTest.class.getName())).getAbsolutePath();
// '/' and '../../relative/path' to ??
assertEquals(new File(rootDir, RELATIVE_PATH), DockerPathUtil.resolveAbsolutely(toResolve, rootDir));
}
use of io.fabric8.annotations.Path in project docker-maven-plugin by fabric8io.
the class DockerPathUtilTest method resolveAbsolutelyWithAbsolutePathAndRelativeBaseDir.
/**
* The supplied base directory is relative, but isn't used because the supplied path is absolute.
*/
@Test
public void resolveAbsolutelyWithAbsolutePathAndRelativeBaseDir() {
String absolutePath = createTmpFile(className).getAbsolutePath();
assertEquals(new File(absolutePath), DockerPathUtil.resolveAbsolutely(absolutePath, REL_BASE_DIR));
}
use of io.fabric8.annotations.Path in project docker-maven-plugin by fabric8io.
the class DockerPathUtilTest method resolveAbsolutelyWithRelativePathAndTrailingSlash.
@Test
public void resolveAbsolutelyWithRelativePathAndTrailingSlash() {
// relative/path/
String toResolve = RELATIVE_PATH + SEP;
// /base/directory
String absBaseDir = ABS_BASE_DIR;
// '/base/directory' and 'relative/path/' to '/base/directory/relative/path'
assertEquals(new File(absBaseDir + SEP + toResolve), DockerPathUtil.resolveAbsolutely(toResolve, absBaseDir));
}
Aggregations