use of io.fabric8.maven.core.model.Configuration in project fabric8 by jboss-fuse.
the class Configuration method fromMap.
public static Configuration fromMap(Map<String, String> map, KubernetesClient testKubernetesClient) {
Configuration configuration = new Configuration();
try {
configuration.masterUrl = getStringProperty(KUBERNETES_MASTER, map, FALLBACK_CONFIG.getMasterUrl());
configuration.environment = getStringProperty(FABRIC8_ENVIRONMENT, map, null);
configuration.environmentInitEnabled = getBooleanProperty(ENVIRONMENT_INIT_ENABLED, map, true);
configuration.environmentConfigUrl = getKubernetesConfigurationUrl(map);
configuration.environmentDependencies = Strings.splitAndTrimAsList(getStringProperty(ENVIRONMENT_DEPENDENCIES, map, ""), "\\s+");
configuration.namespaceLazyCreateEnabled = getBooleanProperty(NAMESPACE_LAZY_CREATE_ENABLED, map, DEFAULT_NAMESPACE_LAZY_CREATE_ENABLED);
configuration.properties = map;
String existingNamespace = getStringProperty(NAMESPACE_TO_USE, map, null);
configuration.sessionId = UUID.randomUUID().toString();
configuration.namespaceCleanupConfirmationEnabled = getBooleanProperty(NAMESPACE_CLEANUP_CONFIRM_ENABLED, map, false);
configuration.deleteAllResourcesOnExit = getBooleanProperty(NAMESPACE_DELETE_ALL_RESOURCES_ON_EXIT, map, false);
configuration.namespaceCleanupTimeout = getLongProperty(NAMESPACE_CLEANUP_TIMEOUT, map, DEFAULT_NAMESPACE_CLEANUP_TIMEOUT);
configuration.waitTimeout = getLongProperty(WAIT_TIMEOUT, map, DEFAULT_WAIT_TIMEOUT);
configuration.waitPollInterval = getLongProperty(WAIT_POLL_INTERVAL, map, DEFAULT_WAIT_POLL_INTERVAL);
configuration.waitForServiceList = Strings.splitAndTrimAsList(getStringProperty(WAIT_FOR_SERVICE_LIST, map, ""), "\\s+");
configuration.waitForServiceConnectionEnabled = getBooleanProperty(WAIT_FOR_SERVICE_CONNECTION_ENABLED, map, DEFAULT_WAIT_FOR_SERVICE_CONNECTION_ENABLED);
configuration.waitForServiceConnectionTimeout = getLongProperty(WAIT_FOR_SERVICE_CONNECTION_TIMEOUT, map, DEFAULT_NAMESPACE_CLEANUP_TIMEOUT);
configuration.ansiLoggerEnabled = getBooleanProperty(ANSI_LOGGER_ENABLED, map, true);
configuration.kubernetesDomain = getStringProperty(KUBERNETES_DOMAIN, map, "");
configuration.gofabric8Enabled = getBooleanProperty(GOFABRIC8_ENABLED, map, false);
configuration.createNamespaceForTest = getBooleanProperty(CREATE_NAMESPACE_FOR_TEST, map, false);
KubernetesClient kubernetesClient = getOrCreateKubernetesClient(configuration, testKubernetesClient);
boolean failOnMissingEnvironmentNamespace = getBooleanProperty(FAIL_ON_MISSING_ENVIRONMENT_NAMESPACE, map, false);
String defaultDevelopNamespace = existingNamespace;
if (Strings.isNullOrBlank(defaultDevelopNamespace)) {
defaultDevelopNamespace = kubernetesClient.getNamespace();
}
String developNamespace = getStringProperty(DEVELOPMENT_NAMESPACE, map, defaultDevelopNamespace);
configuration.kubernetesClient = kubernetesClient;
String environmentNamespace = findNamespaceForEnvironment(configuration.environment, map, kubernetesClient, developNamespace, failOnMissingEnvironmentNamespace);
String providedNamespace = selectNamespace(environmentNamespace, existingNamespace);
if (configuration.createNamespaceForTest) {
configuration.namespace = NAMESPACE_PREFIX + configuration.sessionId;
} else {
String namespace = Strings.isNotBlank(providedNamespace) ? providedNamespace : developNamespace;
;
if (Strings.isNullOrBlank(namespace)) {
namespace = kubernetesClient.getNamespace();
if (Strings.isNullOrBlank(namespace)) {
namespace = KubernetesHelper.defaultNamespace();
}
}
configuration.namespace = namespace;
}
// We default to "cleanup=true" when generating namespace and "cleanup=false" when using existing namespace.
configuration.namespaceCleanupEnabled = getBooleanProperty(NAMESPACE_CLEANUP_ENABLED, map, Strings.isNullOrBlank(providedNamespace));
} catch (Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new RuntimeException(t);
}
}
return configuration;
}
use of io.fabric8.maven.core.model.Configuration in project fabric8 by jboss-fuse.
the class ConfigurationTest method testNamespaceNotFoundFromConfigMap.
@Ignore
public void testNamespaceNotFoundFromConfigMap() {
String devNamespace = "myproject";
String environmentKey = "testing";
String testNamespace = devNamespace;
Map<String, String> data = new HashMap<>();
data.put("staging", " name: Staging\n" + " namespace: myproject-staging\n" + " order: 0");
server.expect().withPath("/api/v1/namespaces/" + devNamespace + "/configmaps/fabric8-environments").andReturn(200, new ConfigMapBuilder().withNewMetadata().withName("fabric8-environments").endMetadata().withData(data).build()).once();
Map<String, String> map = new HashMap<>();
map.put(FABRIC8_ENVIRONMENT, environmentKey);
map.put(DEVELOPMENT_NAMESPACE, devNamespace);
Configuration configuration = Configuration.fromMap(map, kubernetesClient);
assertEquals(testNamespace, configuration.getNamespace());
assertTrue(configuration.isAnsiLoggerEnabled());
assertTrue(configuration.isEnvironmentInitEnabled());
assertTrue(configuration.isNamespaceLazyCreateEnabled());
assertFalse(configuration.isNamespaceCleanupEnabled());
assertFalse(configuration.isCreateNamespaceForTest());
}
use of io.fabric8.maven.core.model.Configuration in project fabric8 by jboss-fuse.
the class FactoryMethodProducer method produce.
@Override
public T produce(CreationalContext<T> ctx) {
List<Object> arguments = new ArrayList<>();
for (AnnotatedParameter<X> parameter : factoryMethod.getParameters()) {
Type type = parameter.getBaseType();
ServiceName parameterServiceName = parameter.getAnnotation(ServiceName.class);
Protocol parameterProtocol = parameter.getAnnotation(Protocol.class);
PortName parameterPortName = parameter.getAnnotation(PortName.class);
Path parameterPath = parameter.getAnnotation(Path.class);
Endpoint paramEndpoint = parameter.getAnnotation(Endpoint.class);
External paramExternal = parameter.getAnnotation(External.class);
Configuration configuration = parameter.getAnnotation(Configuration.class);
// A point without @ServiceName is invalid.
// Even if method defines @ServiceName, the annotation on the injection point takes precedence
String serviceName = pointName;
String serviceProtocol = or(pointProtocol, parameterProtocol != null ? parameterProtocol.value() : null);
String servicePort = or(pointPort, parameterPortName != null ? parameterPortName.value() : null);
String servicePath = or(pointPath, parameterPath != null ? parameterPath.value() : null);
Boolean serviceEndpoint = paramEndpoint != null ? paramEndpoint.value() : false;
Boolean serviceExternal = paramExternal != null ? paramExternal.value() : false;
// If the @ServiceName exists on the current String property
if (parameterServiceName != null && String.class.equals(type)) {
try {
String serviceUrl = getServiceUrl(serviceName, serviceProtocol, servicePort, servicePath, serviceEndpoint, serviceExternal, ctx);
arguments.add(serviceUrl);
} catch (Throwable t) {
throw new RuntimeException(String.format(SERVICE_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
}
} else // If the @ServiceName exists on the current List property
if (parameterServiceName != null && List.class.equals(Types.asClass(type))) {
try {
List<String> endpointList = getEndpointList(serviceName, serviceProtocol, servicePort, servicePath, serviceExternal, ctx);
arguments.add(endpointList);
} catch (Throwable t) {
throw new RuntimeException(String.format(SERVICE_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
}
} else // If the @ServiceName exists on the current List property
if (parameterServiceName != null && Set.class.equals(Types.asClass(type))) {
try {
List<String> endpointList = getEndpointList(serviceName, serviceProtocol, servicePort, servicePath, serviceExternal, ctx);
arguments.add(new HashSet<>(endpointList));
} catch (Throwable t) {
throw new RuntimeException(String.format(SERVICE_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
}
} else // If the @ServiceName exists on the current property which is a non-String
if (parameterServiceName != null && !String.class.equals(type)) {
try {
Object serviceBean = getServiceBean(serviceName, serviceProtocol, servicePort, servicePath, serviceEndpoint, serviceExternal, type, ctx);
arguments.add(serviceBean);
} catch (Throwable t) {
throw new RuntimeException(String.format(BEAN_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), type, serviceName), t);
}
} else // If the current parameter is annotated with @Configuration
if (configuration != null) {
try {
Object config = getConfiguration(serviceName, (Class<Object>) type, ctx);
arguments.add(config);
} catch (Throwable t) {
throw new RuntimeException(String.format(CONF_LOOKUP_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), serviceName), t);
}
} else {
try {
Object other = BeanProvider.getContextualReference(Types.asClass(type), true);
arguments.add(other);
} catch (Throwable t) {
throw new RuntimeException(String.format(PARAMETER_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), parameter.getPosition()), t);
}
}
}
try {
return (T) factoryMethod.getJavaMember().invoke(bean.create(ctx), arguments.toArray());
} catch (Throwable t) {
throw new RuntimeException(String.format(INVOCATION_ERROR_FORMAT, factoryMethod.getJavaMember().getName(), factoryMethod.getJavaMember().getDeclaringClass().getName(), arguments), t);
}
}
use of io.fabric8.maven.core.model.Configuration in project fabric8 by jboss-fuse.
the class KubernetesModelProcessorProcessor method process.
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
CompilationTaskFactory compilationTaskFactory = new CompilationTaskFactory(processingEnv);
Set<TypeElement> processors = new HashSet<>();
// 1st pass collect classes to compile.
for (Element element : roundEnv.getElementsAnnotatedWith(KubernetesModelProcessor.class)) {
processors.add(getClassElement(element));
}
if (processors.isEmpty()) {
return true;
}
StringWriter writer = new StringWriter();
try {
Callable<Boolean> compileTask = compilationTaskFactory.create(processors, writer);
if (!compileTask.call()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to compile provider classes. See output below.");
printCompileErrors(compilationTaskFactory);
return false;
}
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error to compile provider classes, due to: " + e.getMessage() + ". See output below.");
return false;
} finally {
String output = writer.toString();
if (Strings.isNullOrBlank(output)) {
output = "success";
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Fabric8 model generator compiler output:" + output);
}
// 2nd pass generate json.
for (Element element : roundEnv.getElementsAnnotatedWith(KubernetesModelProcessor.class)) {
KubernetesModelProcessor annotation = element.getAnnotation(KubernetesModelProcessor.class);
String kubernetesJsonFileName = annotation.value();
KubernetesResource json = readJson(kubernetesJsonFileName);
Builder<? extends KubernetesResource> builder;
if (json instanceof KubernetesList) {
builder = new KubernetesListBuilder((KubernetesList) json);
} else if (json instanceof Template) {
builder = new TemplateBuilder((Template) json);
} else if (json != null) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Unknown Kubernetes json type:" + json.getClass());
return false;
} else {
return false;
}
try {
if (element instanceof TypeElement) {
for (ExecutableElement methodElement : ElementFilter.methodsIn(element.getEnclosedElements())) {
TypeElement classElement = getClassElement(element);
Class<?> cls = Class.forName(classElement.getQualifiedName().toString());
final Object instance = cls.newInstance();
final String methodName = methodElement.getSimpleName().toString();
if (builder instanceof Visitable) {
((Visitable) builder).accept(new Visitor() {
@Override
public void visit(Object o) {
for (Method m : findMethods(instance, methodName, o.getClass())) {
Named named = m.getAnnotation(Named.class);
if (named != null && !Strings.isNullOrBlank(named.value())) {
String objectName = getName(o);
// If a name has been explicitly specified check if there is a match
if (!named.value().equals(objectName)) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Named method:" + m.getName() + " with name:" + named.value() + " doesn't match: " + objectName + ", ignoring");
return;
}
}
try {
m.invoke(instance, o);
} catch (IllegalAccessException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error invoking visitor method:" + m.getName() + " on:" + instance + "with argument:" + o);
} catch (InvocationTargetException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error invoking visitor method:" + m.getName() + " on:" + instance + "with argument:" + o);
}
}
}
});
} else {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Json type is not visitable.");
}
}
}
json = builder.build();
generateJson(kubernetesJsonFileName, json);
} catch (Exception ex) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error creating Kubernetes configuration:" + ex.getMessage());
}
}
return true;
}
use of io.fabric8.maven.core.model.Configuration in project fabric8-maven-plugin by fabric8io.
the class ResourceMojo method generateResources.
private KubernetesList generateResources(List<ImageConfiguration> images) throws IOException, MojoExecutionException {
// Manager for calling enrichers.
openshiftDependencyResources = new OpenShiftDependencyResources(log);
loadOpenShiftOverrideResources();
EnricherContext.Builder ctxBuilder = new EnricherContext.Builder().project(project).session(session).goalFinder(goalFinder).config(extractEnricherConfig()).resources(resources).images(resolvedImages).log(log).useProjectClasspath(useProjectClasspath).openshiftDependencyResources(openshiftDependencyResources);
if (resources != null) {
ctxBuilder.namespace(resources.getNamespace());
}
EnricherManager enricherManager = new EnricherManager(resources, ctxBuilder.build());
// Generate all resources from the main resource diretory, configuration and enrich them accordingly
KubernetesListBuilder builder = generateAppResources(images, enricherManager);
// Add resources found in subdirectories of resourceDir, with a certain profile
// applied
addProfiledResourcesFromSubirectories(builder, resourceDir, enricherManager);
return builder.build();
}
Aggregations