use of io.fabric8.kubernetes.api.model.Status in project fabric8-maven-plugin by fabric8io.
the class OpenshiftBuildService method waitForOpenShiftBuildToComplete.
private void waitForOpenShiftBuildToComplete(OpenShiftClient client, Build build) throws MojoExecutionException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch logTerminateLatch = new CountDownLatch(1);
final String buildName = KubernetesHelper.getName(build);
final AtomicReference<Build> buildHolder = new AtomicReference<>();
// Don't query for logs directly, Watch over the build pod:
waitUntilPodIsReady(buildName + "-build", 120, log);
log.info("Waiting for build " + buildName + " to complete...");
try (LogWatch logWatch = client.pods().withName(buildName + "-build").watchLog()) {
KubernetesClientUtil.printLogsAsync(logWatch, "Failed to tail build log", logTerminateLatch, log);
Watcher<Build> buildWatcher = getBuildWatcher(latch, buildName, buildHolder);
try (Watch watcher = client.builds().withName(buildName).watch(buildWatcher)) {
// Check if the build is already finished to avoid waiting indefinitely
Build lastBuild = client.builds().withName(buildName).get();
if (OpenshiftHelper.isFinished(KubernetesResourceUtil.getBuildStatusPhase(lastBuild))) {
log.debug("Build %s is already finished", buildName);
buildHolder.set(lastBuild);
latch.countDown();
}
waitUntilBuildFinished(latch);
logTerminateLatch.countDown();
build = buildHolder.get();
if (build == null) {
log.debug("Build watcher on %s was closed prematurely", buildName);
build = client.builds().withName(buildName).get();
}
String status = KubernetesResourceUtil.getBuildStatusPhase(build);
if (OpenshiftHelper.isFailed(status) || OpenshiftHelper.isCancelled(status)) {
throw new MojoExecutionException("OpenShift Build " + buildName + " failed: " + KubernetesResourceUtil.getBuildStatusReason(build));
}
if (!OpenshiftHelper.isFinished(status)) {
log.warn("Could not wait for the completion of build %s. It may be may be still running (status=%s)", buildName, status);
} else {
log.info("Build %s in status %s", buildName, status);
}
}
}
}
use of io.fabric8.kubernetes.api.model.Status in project fabric8-maven-plugin by fabric8io.
the class PodLogService method onPod.
private void onPod(Watcher.Action action, Pod pod, KubernetesClient kubernetes, String namespace, String ctrlCMessage, boolean followLog) {
String name = KubernetesHelper.getName(pod);
if (action.equals(Watcher.Action.DELETED)) {
addedPods.remove(name);
if (Objects.equals(watchingPodName, name)) {
watchingPodName = null;
addedPods.remove(name);
}
} else {
if (action.equals(Watcher.Action.ADDED) || action.equals(Watcher.Action.MODIFIED)) {
addedPods.put(name, pod);
}
}
Pod watchPod = KubernetesResourceUtil.getNewestPod(addedPods.values());
newestPodName = KubernetesHelper.getName(watchPod);
Logger statusLog = Objects.equals(name, newestPodName) ? context.getNewPodLog() : context.getOldPodLog();
if (!action.equals(Watcher.Action.MODIFIED) || watchingPodName == null || !watchingPodName.equals(name)) {
statusLog.info("%s status: %s%s", name, getPodStatusDescription(pod), getPodStatusMessagePostfix(action));
}
if (watchPod != null && KubernetesHelper.isPodRunning(watchPod)) {
watchLogOfPodName(kubernetes, namespace, ctrlCMessage, followLog, watchPod, KubernetesHelper.getName(watchPod));
}
}
use of io.fabric8.kubernetes.api.model.Status in project fabric8-maven-plugin by fabric8io.
the class ImageStreamService method findTagSha.
private String findTagSha(OpenShiftClient client, String imageStreamName, String namespace) throws MojoExecutionException {
ImageStream currentImageStream = null;
for (int i = 0; i < IMAGE_STREAM_TAG_RETRIES; i++) {
if (i > 0) {
log.info("Retrying to find tag on ImageStream %s", imageStreamName);
try {
Thread.sleep(IMAGE_STREAM_TAG_RETRY_TIMEOUT_IN_MILLIS);
} catch (InterruptedException e) {
log.debug("interrupted", e);
}
}
currentImageStream = client.imageStreams().withName(imageStreamName).get();
if (currentImageStream == null) {
continue;
}
ImageStreamStatus status = currentImageStream.getStatus();
if (status == null) {
continue;
}
List<NamedTagEventList> tags = status.getTags();
if (tags == null || tags.isEmpty()) {
continue;
}
// Iterate all imagestream tags and get the latest one by 'created' attribute
TagEvent latestTag = null;
TAG_EVENT_LIST: for (NamedTagEventList list : tags) {
List<TagEvent> items = list.getItems();
if (items == null || items.isEmpty()) {
continue TAG_EVENT_LIST;
}
for (TagEvent tag : items) {
latestTag = latestTag == null ? tag : newerTag(tag, latestTag);
}
}
if (latestTag != null && StringUtils.isNotBlank(latestTag.getImage())) {
String image = latestTag.getImage();
log.info("Found tag on ImageStream " + imageStreamName + " tag: " + image);
return image;
}
}
// No image found, even after several retries:
if (currentImageStream == null) {
throw new MojoExecutionException("Could not find a current ImageStream with name " + imageStreamName + " in namespace " + namespace);
} else {
throw new MojoExecutionException("Could not find a tag in the ImageStream " + imageStreamName);
}
}
use of io.fabric8.kubernetes.api.model.Status in project fabric8-maven-plugin by fabric8io.
the class KubernetesResourceUtil method getDockerContainerID.
public static String getDockerContainerID(Pod pod) {
PodStatus status = pod.getStatus();
if (status != null) {
List<ContainerStatus> containerStatuses = status.getContainerStatuses();
if (containerStatuses != null) {
for (ContainerStatus containerStatus : containerStatuses) {
String containerID = containerStatus.getContainerID();
if (StringUtils.isNotBlank(containerID)) {
String prefix = "://";
int idx = containerID.indexOf(prefix);
if (idx > 0) {
return containerID.substring(idx + prefix.length());
}
return containerID;
}
}
}
}
return null;
}
use of io.fabric8.kubernetes.api.model.Status in project fabric8-maven-plugin by fabric8io.
the class ServiceUrlUtil method getServiceURL.
/**
* Returns the URL to access the service; using the environment variables, routes
* or service clusterIP address
*
* @throws IllegalArgumentException if the URL cannot be found for the serviceName and namespace
*/
public static String getServiceURL(KubernetesClient client, String serviceName, String serviceNamespace, String serviceProtocol, boolean serviceExternal) {
Service srv = null;
String serviceHost = serviceToHostOrBlank(serviceName);
String servicePort = serviceToPortOrBlank(serviceName);
String serviceProto = serviceProtocol != null ? serviceProtocol : serviceToProtocol(serviceName, servicePort);
// Use specified or fallback namespace.
String actualNamespace = StringUtils.isNotBlank(serviceNamespace) ? serviceNamespace : client.getNamespace();
// 1. Inside Kubernetes: Services as ENV vars
if (!serviceExternal && StringUtils.isNotBlank(serviceHost) && StringUtils.isNotBlank(servicePort) && StringUtils.isNotBlank(serviceProtocol)) {
return serviceProtocol + "://" + serviceHost + ":" + servicePort;
// 2. Anywhere: When namespace is passed System / Env var. Mostly needed for integration tests.
} else if (StringUtils.isNotBlank(actualNamespace)) {
srv = client.services().inNamespace(actualNamespace).withName(serviceName).get();
}
if (srv == null) {
// lets try use environment variables
String hostAndPort = getServiceHostAndPort(serviceName, "", "");
if (!hostAndPort.startsWith(":")) {
return serviceProto + "://" + hostAndPort;
}
}
if (srv == null) {
throw new IllegalArgumentException("No kubernetes service could be found for name: " + serviceName + " in namespace: " + actualNamespace);
}
String answer = KubernetesHelper.getOrCreateAnnotations(srv).get(Fabric8Annotations.SERVICE_EXPOSE_URL.toString());
if (StringUtils.isNotBlank(answer)) {
return answer;
}
if (OpenshiftHelper.isOpenShift(client)) {
OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
Route route = openShiftClient.routes().inNamespace(actualNamespace).withName(serviceName).get();
if (route != null) {
return (serviceProto + "://" + route.getSpec().getHost()).toLowerCase();
}
}
ServicePort port = findServicePortByName(srv, null);
if (port == null) {
throw new RuntimeException("Couldn't find port: " + null + " for service:" + serviceName);
}
String clusterIP = srv.getSpec().getClusterIP();
if ("None".equals(clusterIP)) {
throw new IllegalStateException("Service: " + serviceName + " in namespace:" + serviceNamespace + "is head-less. Search for endpoints instead.");
}
Integer portNumber = port.getPort();
if (StringUtils.isBlank(clusterIP)) {
IngressList ingresses = client.extensions().ingresses().inNamespace(serviceNamespace).list();
if (ingresses != null) {
List<Ingress> items = ingresses.getItems();
if (items != null) {
for (Ingress item : items) {
String ns = KubernetesHelper.getNamespace(item);
if (Objects.equal(serviceNamespace, ns)) {
IngressSpec spec = item.getSpec();
if (spec != null) {
List<IngressRule> rules = spec.getRules();
List<IngressTLS> tls = spec.getTls();
if (rules != null) {
for (IngressRule rule : rules) {
HTTPIngressRuleValue http = rule.getHttp();
if (http != null) {
List<HTTPIngressPath> paths = http.getPaths();
if (paths != null) {
for (HTTPIngressPath path : paths) {
IngressBackend backend = path.getBackend();
if (backend != null) {
String backendServiceName = backend.getServiceName();
if (serviceName.equals(backendServiceName) && portsMatch(port, backend.getServicePort())) {
String pathPostfix = path.getPath();
if (tls != null) {
for (IngressTLS tlsHost : tls) {
List<String> hosts = tlsHost.getHosts();
if (hosts != null) {
for (String host : hosts) {
if (StringUtils.isNotBlank(host)) {
return String.format("https://%s/%s", host, preparePath(pathPostfix));
}
}
}
}
}
answer = rule.getHost();
if (StringUtils.isNotBlank(answer)) {
return String.format("http://%s/%s", answer, preparePath(pathPostfix));
}
}
}
}
}
}
}
}
}
}
}
}
}
// lets try use the status on GKE
ServiceStatus status = srv.getStatus();
if (status != null) {
LoadBalancerStatus loadBalancerStatus = status.getLoadBalancer();
if (loadBalancerStatus != null) {
List<LoadBalancerIngress> loadBalancerIngresses = loadBalancerStatus.getIngress();
if (loadBalancerIngresses != null) {
for (LoadBalancerIngress loadBalancerIngress : loadBalancerIngresses) {
String ip = loadBalancerIngress.getIp();
if (StringUtils.isNotBlank(ip)) {
clusterIP = ip;
break;
}
}
}
}
}
}
if (StringUtils.isBlank(clusterIP)) {
// on vanilla kubernetes we can use nodePort to access things externally
boolean found = false;
Integer nodePort = port.getNodePort();
if (nodePort != null) {
NodeList nodeList = client.nodes().list();
if (nodeList != null) {
List<Node> items = nodeList.getItems();
if (items != null) {
for (Node item : items) {
NodeStatus status = item.getStatus();
if (!found && status != null) {
List<NodeAddress> addresses = status.getAddresses();
if (addresses != null) {
for (NodeAddress address : addresses) {
String ip = address.getAddress();
if (StringUtils.isNotBlank(ip)) {
clusterIP = ip;
portNumber = nodePort;
found = true;
break;
}
}
}
}
if (!found) {
NodeSpec spec = item.getSpec();
if (spec != null) {
clusterIP = spec.getExternalID();
if (StringUtils.isNotBlank(clusterIP)) {
portNumber = nodePort;
break;
}
}
}
}
}
}
}
}
return (serviceProto + "://" + clusterIP + ":" + portNumber).toLowerCase();
}
Aggregations