use of io.fabric8.annotations.ServiceName in project halyard by spinnaker.
the class ResourceBuilder method buildResourceRequirements.
static ResourceRequirements buildResourceRequirements(String serviceName, DeploymentEnvironment deploymentEnvironment) {
Map<String, Map> customSizing = deploymentEnvironment.getCustomSizing().get(serviceName);
if (customSizing == null) {
return null;
}
ResourceRequirementsBuilder resourceRequirementsBuilder = new ResourceRequirementsBuilder();
if (customSizing.get("requests") != null) {
resourceRequirementsBuilder.addToRequests("memory", new QuantityBuilder().withAmount(CustomSizing.stringOrNull(customSizing.get("requests").get("memory"))).build());
resourceRequirementsBuilder.addToRequests("cpu", new QuantityBuilder().withAmount(CustomSizing.stringOrNull(customSizing.get("requests").get("cpu"))).build());
}
if (customSizing.get("limits") != null) {
resourceRequirementsBuilder.addToLimits("memory", new QuantityBuilder().withAmount(CustomSizing.stringOrNull(customSizing.get("limits").get("memory"))).build());
resourceRequirementsBuilder.addToLimits("cpu", new QuantityBuilder().withAmount(CustomSizing.stringOrNull(customSizing.get("limits").get("cpu"))).build());
}
return resourceRequirementsBuilder.build();
}
use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.
the class Services method toServiceUrl.
public static String toServiceUrl(String serviceName, String serviceProtocol, String servicePortName, String servicePath, boolean serviceExternal) {
KubernetesClient client = KubernetesHolder.getClient();
String serviceNamespace = client.getNamespace();
String actualProtocol = Strings.isNullOrBlank(serviceProtocol) ? DEFAULT_PROTO : serviceProtocol;
return URLUtils.pathJoin(KubernetesHelper.getServiceURL(client, serviceName, serviceNamespace, actualProtocol, servicePortName, serviceExternal), servicePath);
}
use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.
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.annotations.ServiceName in project fabric8 by fabric8io.
the class SessionListener method applyConfiguration.
private boolean applyConfiguration(KubernetesClient client, Controller controller, Configuration configuration, Session session, List<KubernetesList> kubeConfigs) throws Exception {
Logger log = session.getLogger();
Map<Integer, Callable<Boolean>> conditions = new TreeMap<>();
Callable<Boolean> sessionPodsReady = new SessionPodsAreReady(client, session);
Callable<Boolean> servicesReady = new SessionServicesAreReady(client, session, configuration);
Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
for (KubernetesList c : kubeConfigs) {
entities.addAll(enhance(session, configuration, c).getItems());
}
if (containsImageStreamResources(entities)) {
// no need to use a local image registry
// as we are using OpenShift and
} else {
String registry = getLocalDockerRegistry();
if (Strings.isNotBlank(registry)) {
log.status("Adapting resources to pull images from registry: " + registry);
addRegistryToImageNameIfNotPresent(entities, registry);
} else {
log.status("No local fabric8 docker registry found");
}
}
List<Object> items = new ArrayList<>();
items.addAll(entities);
// Ensure services are processed first.
Collections.sort(items, new Comparator<Object>() {
@Override
public int compare(Object left, Object right) {
if (left instanceof Service) {
return -1;
} else if (right instanceof Service) {
return 1;
} else {
return 0;
}
}
});
boolean isOpenshift = client.isAdaptable(OpenShiftClient.class);
String namespace = session.getNamespace();
String routeDomain = null;
if (Strings.isNotBlank(configuration.getKubernetesDomain())) {
routeDomain = configuration.getKubernetesDomain();
}
preprocessEnvironment(client, controller, configuration, session);
Set<HasMetadata> extraEntities = new TreeSet<>(new HasMetadataComparator());
for (Object entity : items) {
if (entity instanceof Pod) {
Pod pod = (Pod) entity;
log.status("Applying pod:" + getName(pod));
Set<Secret> secrets = generateSecrets(client, session, pod.getMetadata());
String serviceAccountName = pod.getSpec().getServiceAccountName();
if (Strings.isNotBlank(serviceAccountName)) {
generateServiceAccount(client, session, secrets, serviceAccountName);
}
controller.applyPod(pod, session.getId());
conditions.put(1, sessionPodsReady);
} else if (entity instanceof Service) {
Service service = (Service) entity;
String serviceName = getName(service);
log.status("Applying service:" + serviceName);
controller.applyService(service, session.getId());
conditions.put(2, servicesReady);
if (isOpenshift) {
Route route = Routes.createRouteForService(routeDomain, namespace, service, log);
if (route != null) {
log.status("Applying route for:" + serviceName);
controller.applyRoute(route, "route for " + serviceName);
extraEntities.add(route);
}
}
} else if (entity instanceof ReplicationController) {
ReplicationController replicationController = (ReplicationController) entity;
log.status("Applying replication controller:" + getName(replicationController));
Set<Secret> secrets = generateSecrets(client, session, replicationController.getSpec().getTemplate().getMetadata());
String serviceAccountName = replicationController.getSpec().getTemplate().getSpec().getServiceAccountName();
if (Strings.isNotBlank(serviceAccountName)) {
generateServiceAccount(client, session, secrets, serviceAccountName);
}
controller.applyReplicationController(replicationController, session.getId());
conditions.put(1, sessionPodsReady);
} else if (entity instanceof ReplicaSet || entity instanceof Deployment || entity instanceof DeploymentConfig) {
log.status("Applying " + entity.getClass().getSimpleName() + ".");
controller.apply(entity, session.getId());
conditions.put(1, sessionPodsReady);
} else if (entity instanceof OAuthClient) {
OAuthClient oc = (OAuthClient) entity;
// these are global so lets create a custom one for the new namespace
ObjectMeta metadata = KubernetesHelper.getOrCreateMetadata(oc);
String name = metadata.getName();
if (isOpenshift) {
OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
OAuthClient current = openShiftClient.oAuthClients().withName(name).get();
boolean create = false;
if (current == null) {
current = oc;
create = true;
}
boolean updated = false;
// lets add a new redirect entry
List<String> redirectURIs = current.getRedirectURIs();
String namespaceSuffix = "-" + namespace;
String redirectUri = "http://" + name + namespaceSuffix;
if (Strings.isNotBlank(routeDomain)) {
redirectUri += "." + Strings.stripPrefix(routeDomain, ".");
}
if (!redirectURIs.contains(redirectUri)) {
redirectURIs.add(redirectUri);
updated = true;
}
current.setRedirectURIs(redirectURIs);
log.status("Applying OAuthClient:" + name);
controller.setSupportOAuthClients(true);
if (create) {
openShiftClient.oAuthClients().create(current);
} else {
if (updated) {
// TODO this should work!
// openShiftClient.oAuthClients().withName(name).replace(current);
openShiftClient.oAuthClients().withName(name).delete();
current.getMetadata().setResourceVersion(null);
openShiftClient.oAuthClients().create(current);
}
}
}
} else if (entity instanceof HasMetadata) {
log.status("Applying " + entity.getClass().getSimpleName() + ":" + KubernetesHelper.getName((HasMetadata) entity));
controller.apply(entity, session.getId());
} else if (entity != null) {
log.status("Applying " + entity.getClass().getSimpleName() + ".");
controller.apply(entity, session.getId());
}
}
entities.addAll(extraEntities);
// Wait until conditions are meet.
if (!conditions.isEmpty()) {
Callable<Boolean> compositeCondition = new CompositeCondition(conditions.values());
WaitStrategy waitStrategy = new WaitStrategy(compositeCondition, configuration.getWaitTimeout(), configuration.getWaitPollInterval());
if (!waitStrategy.await()) {
log.error("Timed out waiting for pods/services!");
return false;
} else {
log.status("All pods/services are currently 'running'!");
}
} else {
log.warn("No pods/services/replication controllers defined in the configuration!");
}
return true;
}
use of io.fabric8.annotations.ServiceName in project fabric8 by fabric8io.
the class InternalServiceRegistar method getService.
@Override
public Service getService(String serviceName) {
Map<String, String> env = System.getenv();
String prefix = serviceName.toUpperCase();
String serviceHost = env.get(prefix + HOST_SUFFIX);
String defaultPortName = prefix + SERVICE_PORT;
String namedPortPrefix = defaultPortName + "_";
List<ServicePort> servicePorts = new ArrayList<>();
for (Map.Entry<String, String> entry : env.entrySet()) {
String key = entry.getKey();
if (key.startsWith(namedPortPrefix)) {
String name = key.substring(namedPortPrefix.length());
String portValue = entry.getValue();
String protocolValue = env.get(key + "_" + PROTO_SUFFIX);
servicePorts.add(new ServicePortBuilder().withName(name.toLowerCase()).withPort(Integer.parseInt(portValue)).withProtocol(protocolValue != null ? protocolValue : "TCP").build());
}
}
// Check if we need to fallback to single port.
if (servicePorts.isEmpty()) {
String portValue = env.get(defaultPortName);
String protocolValue = env.get(defaultPortName + PROTO_SUFFIX);
servicePorts.add(new ServicePortBuilder().withPort(Integer.parseInt(portValue)).withProtocol(protocolValue != null ? protocolValue : "TCP").build());
}
return new ServiceBuilder().withNewMetadata().withName(serviceName).endMetadata().withNewSpec().withClusterIP(serviceHost).withPorts(servicePorts).endSpec().build();
}
Aggregations