com.openshift.restclient.ResourceKind Java Examples
The following examples show how to use
com.openshift.restclient.ResourceKind.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceWatcher.java From thorntail with Apache License 2.0 | 5 votes |
@Override public void connected(List<IResource> resources) { this.listenerState.set(ListenerState.CONNECTED); resources.stream() .filter(p -> p.getKind().equals(ResourceKind.SERVICE)) .forEach(r -> { Set<Registration> regs = registrationsForService((IService) r); regs.forEach(topologyManagerInjector.getValue()::register); }); }
Example #2
Source File: NamespaceService.java From thorntail with Apache License 2.0 | 5 votes |
@Override public void start(StartContext context) throws StartException { this.client = this.clientInjector.getValue(); this.namespace = System.getenv("KUBERNETES_NAMESPACE"); if (this.namespace == null) { Path namespaceFile = Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); if (Files.exists(namespaceFile)) { try { this.namespace = new String(Files.readAllBytes(namespaceFile)); } catch (IOException ignored) { // shouldn't happen, this file is on tmpfs // but if it happened anyway, we'll try the following options } } } if (this.namespace == null) { this.namespace = System.getenv("OPENSHIFT_BUILD_NAMESPACE"); } if (this.namespace == null) { List<IProject> projects = this.client.list(ResourceKind.PROJECT); if (projects.size() != 1) { throw new StartException("Unable to automatically detect the " + "Kubernetes namespace to use. Set the environment " + "variable KUBERNETES_NAMESPACE and try again."); } this.namespace = projects.get(0).getNamespace().getNamespaceName(); } }
Example #3
Source File: IOpenShiftBuildVerifier.java From jenkins-plugin with Apache License 2.0 | 5 votes |
default String getLatestBuildID(IClient client, Map<String, String> overrides) { Map<String, String> filter = new HashMap<String, String>(); filter.put("openshift.io/build-config.name", getBldCfg(overrides)); List<IBuild> blds = client.list(ResourceKind.BUILD, getNamespace(overrides), filter); // we'll get a list of startimes that we'll sort on to get the latest; // we'll also build a map of startimes to build ids, so that we return // the build ID related to the latest starttime List<String> starttimes = new ArrayList<String>(); Map<String, String> timeToID = new HashMap<String, String>(); /* * in case multiple builds have the same start time (parallel builds), * use our custom comparator to make sure build-4 comes before build-38; * then, if consecutive builds have the same start time, that later id * number will be later in this list, and replace earlier entries in the * timeToID map */ Collections.sort(blds, new BuildNameComparator()); for (IBuild bld : blds) { starttimes.add(bld.getBuildStatus().getStartTime()); timeToID.put(bld.getBuildStatus().getStartTime(), bld.getName()); } String starttime = null; if (starttimes.size() > 0) { Collections.sort(starttimes); starttime = starttimes.get(starttimes.size() - 1); } return timeToID.get(starttime); }
Example #4
Source File: IOpenShiftPlugin.java From jenkins-plugin with Apache License 2.0 | 5 votes |
default boolean didICTCauseDeployment(IClient client, IDeploymentConfig dc, String imageTag, boolean chatty, TaskListener listener, long wait) throws InterruptedException { long currTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - (wait / 3) <= currTime) { dc = client.get(ResourceKind.DEPLOYMENT_CONFIG, dc.getName(), dc.getNamespace()); if (!dc.didImageTrigger(imageTag)) { if (chatty) listener.getLogger().println("\n ICT did not fire"); try { Thread.sleep(10000); } catch (InterruptedException e) { // need to throw as this indicates the step as been // cancelled throw e; } } else { if (chatty) listener.getLogger().println( "\n ICT fired for deployment " + dc.toJson(false)); return true; } } if (chatty) { listener.getLogger().println( "\n done checking dc " + dc.toJson(false)); } return false; }
Example #5
Source File: IOpenShiftPlugin.java From jenkins-plugin with Apache License 2.0 | 5 votes |
default IReplicationController getLatestReplicationController( IDeploymentConfig dc, String namespace, IClient client, TaskListener listener) { int latestVersion = dc.getLatestVersionNumber(); if (latestVersion == 0) return null; // start at the latest, but ignore newer replication controllers that // are cancelled IReplicationController rc = null; while (latestVersion > 0) { String repId = dc.getName() + "-" + latestVersion; try { rc = client.get(ResourceKind.REPLICATION_CONTROLLER, repId, namespace); } catch (Throwable t) { if (listener != null) t.printStackTrace(listener.getLogger()); } if (rc != null) { if ("true".equalsIgnoreCase(rc .getAnnotation("openshift.io/deployment.cancelled"))) { rc = null; latestVersion--; } else { break; } } } return rc; }
Example #6
Source File: OpenShiftImageStreams.java From jenkins-plugin with Apache License 2.0 | 5 votes |
protected String getCommitId(TaskListener listener, Map<String, String> overrides) { boolean chatty = Boolean.parseBoolean(verbose); // get oc client (sometime REST, sometimes Exec of oc command setAuth(Auth.createInstance(null, getApiURL(overrides), overrides)); // setToken(new TokenAuthorizationStrategy(Auth.deriveBearerToken(null, // authToken, listener, chatty))); // get oc client IClient client = this.getClient(listener, DISPLAY_NAME, overrides); String commitId = null; String imageStream = getImageStreamName(overrides); try { IImageStream isImpl = client.get(ResourceKind.IMAGE_STREAM, imageStream, getNamespace(overrides)); // we will treat the OpenShiftImageStream "imageID" as the Jenkins // "commitId" commitId = isImpl.getImageId(tag); } catch (com.openshift.restclient.NotFoundException e) { if (chatty) listener.getLogger().println( "\n\nImageStream " + imageStream + " not found"); } if (chatty) listener.getLogger().println( "\n\nOpenShiftImageStreams image ID used for Jenkins 'commitId' is " + commitId); return commitId; }
Example #7
Source File: OpenshiftStartedEnvironment.java From pnc with Apache License 2.0 | 5 votes |
/** * Enable ssh forwarding * * @return port, to which ssh is forwarded */ private Integer startSshService() { ModelNode serviceConfigurationNode = createModelNode( Configurations.getContentAsString(Resource.PNC_BUILDER_SSH_SERVICE, openshiftBuildAgentConfig), environmetVariables); sshService = new Service( serviceConfigurationNode, client, ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.SERVICE)); sshService.setNamespace(environmentConfiguration.getPncNamespace()); try { Service resultService = client.create(this.sshService, sshService.getNamespace()); return resultService.getNode() .get("spec") .get("ports") .asList() .stream() .filter(m -> m.get("name").asString().equals(SSH_SERVICE_PORT_NAME)) .findAny() .orElseThrow( () -> new RuntimeException( "No ssh service in response! Service data: " + describeService(resultService))) .get("nodePort") .asInt(); } catch (Throwable e) { logger.error("Cannot create service.", e); return null; } }
Example #8
Source File: ServiceWatcher.java From thorntail with Apache License 2.0 | 4 votes |
private void startWatcher() { IClient client = clientInjector.getValue(); listenerState.set(ListenerState.STARTING); openShiftWatcher = client.watch(namespaceInjector.getValue(), this, ResourceKind.SERVICE); }
Example #9
Source File: OpenShiftDeployCanceller.java From jenkins-plugin with Apache License 2.0 | 4 votes |
@Override public boolean coreLogic(Launcher launcher, TaskListener listener, Map<String, String> overrides) { listener.getLogger().println( String.format(MessageConstants.START_DEPLOY_RELATED_PLUGINS, DISPLAY_NAME, getDepCfg(overrides), getNamespace(overrides))); // get oc client IClient client = this.getClient(listener, DISPLAY_NAME, overrides); if (client != null) { IDeploymentConfig dc = client.get(ResourceKind.DEPLOYMENT_CONFIG, getDepCfg(overrides), getNamespace(overrides)); if (dc == null) { listener.getLogger() .println( String.format( MessageConstants.EXIT_DEPLOY_RELATED_PLUGINS_NO_CFG, DISPLAY_NAME, getDepCfg(overrides))); return false; } boolean chatty = Boolean.parseBoolean(getVerbose(overrides)); IReplicationController rc = getLatestReplicationController(dc, getNamespace(overrides), client, chatty ? listener : null); if (rc != null) { String state = this.getReplicationControllerState(rc); if (state.equalsIgnoreCase(STATE_FAILED) || state.equalsIgnoreCase(STATE_COMPLETE) || state.equalsIgnoreCase(STATE_CANCELLED)) { listener.getLogger() .println( String.format( MessageConstants.EXIT_DEPLOY_CANCEL_GOOD_NOOP, rc.getName(), state)); return true; } rc.setAnnotation("openshift.io/deployment.cancelled", "true"); rc.setAnnotation("openshift.io/deployment.status-reason", "The deployment was cancelled by the user"); client.update(rc); listener.getLogger().println( String.format( MessageConstants.EXIT_DEPLOY_CANCEL_GOOD_DIDIT, rc.getName())); return true; } else { if (dc.getLatestVersionNumber() > 0) { listener.getLogger() .println( String.format( MessageConstants.EXIT_DEPLOY_CANCEL_BAD_NO_REPCTR, getDepCfg(overrides))); return false; } else { listener.getLogger() .println( String.format( MessageConstants.EXIT_DEPLOY_CANCEL_GOOD_NO_REPCTR, getDepCfg(overrides))); return true; } } } else { return false; } }
Example #10
Source File: IOpenShiftBuilder.java From jenkins-plugin with Apache License 2.0 | 4 votes |
default IStoppable getBuildPodLogs(IClient client, String bldId, Map<String, String> overrides, boolean chatty, TaskListener listener, AtomicBoolean needToFollow) { IStoppable stop = null; List<IPod> pods = client .list(ResourceKind.POD, getNamespace(overrides)); for (IPod pod : pods) { if (chatty) listener.getLogger().println( "\nOpenShiftBuilder found pod " + pod.getName()); // build pod starts with build id if (pod.getName().startsWith(bldId)) { if (chatty) listener.getLogger().println( "\nOpenShiftBuilder going with build pod " + pod); final String container = pod.getContainers().iterator().next() .getName(); stop = pod .accept(new CapabilityVisitor<IPodLogRetrievalAsync, IStoppable>() { @Override public IStoppable visit( IPodLogRetrievalAsync capability) { return capability .start(new IPodLogRetrievalAsync.IPodLogListener() { @Override public void onOpen() { } @Override public void onMessage(String message) { listener.getLogger().print( message); } @Override public void onClose(int code, String reason) { } @Override public void onFailure(IOException e) { // If follow fails, try to // restart it on the next loop. needToFollow.compareAndSet( false, true); } }, new IPodLogRetrievalAsync.Options() .follow().container(container)); } }, null); break; } } return stop; }
Example #11
Source File: IOpenShiftBuilder.java From jenkins-plugin with Apache License 2.0 | 4 votes |
default void waitOnBuild(IClient client, long startTime, String bldId, TaskListener listener, Map<String, String> overrides, long wait, boolean follow, boolean chatty) throws InterruptedException { IBuild bld = null; String bldState = null; // get internal OS Java REST Client error if access pod logs while bld // is in Pending state // instead of Running, Complete, or Failed IStoppable stop = null; final AtomicBoolean needToFollow = new AtomicBoolean(follow); while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) < (startTime + wait)) { bld = client .get(ResourceKind.BUILD, bldId, getNamespace(overrides)); bldState = bld.getStatus(); if (Boolean.parseBoolean(getVerbose(overrides))) listener.getLogger().println( "\nOpenShiftBuilder bld state: " + bldState); if (isBuildRunning(bldState) && needToFollow.compareAndSet(true, false)) { stop = this.getBuildPodLogs(client, bldId, overrides, chatty, listener, needToFollow); } if (isBuildFinished(bldState)) { if (follow && stop == null) stop = this.getBuildPodLogs(client, bldId, overrides, chatty, listener, needToFollow); break; } try { Thread.sleep(1000); } catch (InterruptedException e) { // need to throw as this indicates the step as been cancelled // also attempt to cancel build on openshift side OpenShiftBuildCanceller canceller = new OpenShiftBuildCanceller( getApiURL(overrides), getNamespace(overrides), getAuthToken(overrides), getVerbose(overrides), getBldCfg(overrides)); canceller.setAuth(getAuth()); canceller.coreLogic(null, listener, overrides); throw e; } } if (stop != null) stop.stop(); }
Example #12
Source File: IOpenShiftPlugin.java From jenkins-plugin with Apache License 2.0 | 4 votes |
default Map<String, String> constructBuildUrl(TaskListener listener, Map<String, String> overrides, boolean chatty) { // for our pipeline strategy / build annotaion logic, we will construct // the BUILD_URL env var // if it is not set (which can occur with freestyle jobs when the // openshift-sync plugin is not // leveraged String jobName = overrides.get(JOB_NAME); String buildNum = overrides.get(BUILD_NUMBER); // we check for null but these should always be there from a jenkins api // guarantee perspective if (jobName != null && buildNum != null) { jobName = jobName.replace(" ", "%20"); IClient client = getClient(listener, getDisplayName(), overrides); List<IRoute> routes = new ArrayList<IRoute>(); try { routes = client.list(ResourceKind.ROUTE, getNamespace(overrides)); } catch (Throwable t) { if (chatty) t.printStackTrace(listener.getLogger()); } for (IRoute route : routes) { if (route.getServiceName().equals("jenkins")) { String base = route.getURL(); if (!base.endsWith("/")) base = base + "/"; overrides.put(BUILD_URL_ENV_KEY, base + "job/" + jobName + "/" + buildNum + "/"); break; } } if (!overrides.containsKey(BUILD_URL_ENV_KEY)) overrides .put(BUILD_URL_ENV_KEY, Jenkins.getInstance() .getRootUrl() + "job/" + jobName + "/" + buildNum + "/"); } else { if (chatty) listener.getLogger() .printf("\n missing jenkins job/build info: job %s build %s \n", jobName, buildNum); } return overrides; }
Example #13
Source File: IOpenShiftPlugin.java From jenkins-plugin with Apache License 2.0 | 4 votes |
default boolean verifyBuild(long startTime, long wait, IClient client, String bldCfg, String bldId, String namespace, boolean chatty, TaskListener listener, String displayName, boolean checkDeps, boolean annotateRC, Map<String, String> env) throws InterruptedException { String bldState = null; while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) < (startTime + wait)) { IBuild bld = client.get(ResourceKind.BUILD, bldId, namespace); bldState = bld.getStatus(); if (chatty) listener.getLogger().println( "\nOpenShiftBuilder post bld launch bld state: " + bldState); if (!isBuildFinished(bldState)) { try { Thread.sleep(1000); } catch (InterruptedException e) { // need to throw as this indicates the step as been // cancelled // also attempt to cancel build on openshift side OpenShiftBuildCanceller canceller = new OpenShiftBuildCanceller( getApiURL(env), getNamespace(env), getAuthToken(env), getVerbose(env), bldCfg); canceller.setAuth(getAuth()); canceller.coreLogic(null, listener, env); throw e; } } else { break; } } if (bldState == null || !bldState.equals(STATE_COMPLETE)) { String displayState = bldState; if (displayState == null) displayState = "NotStarted"; listener.getLogger().println( String.format(MessageConstants.EXIT_BUILD_BAD, displayName, bldId, wait, displayState)); return false; } else { if (checkDeps) { // calling this will annotate any RC that was created as a // result of this build, with the jenkins job info. boolean triggerSuccess = didAllImagesChangeIfNeeded(bldCfg, listener, chatty, client, namespace, wait, annotateRC, env); if (triggerSuccess) { listener.getLogger() .println( String.format( MessageConstants.EXIT_BUILD_GOOD_DEPLOY_GOOD, displayName, bldId)); return true; } else { listener.getLogger() .println( String.format( MessageConstants.EXIT_BUILD_GOOD_DEPLOY_BAD, displayName, bldId)); return false; } } else { listener.getLogger() .println( String.format( MessageConstants.EXIT_BUILD_GOOD_DEPLOY_IGNORED, displayName, bldId)); return true; } } }
Example #14
Source File: IOpenShiftPlugin.java From jenkins-plugin with Apache License 2.0 | 4 votes |
default boolean didImageChangeFromPreviousVersion(IClient client, int latestVersion, boolean chatty, TaskListener listener, String depCfg, String namespace, String latestImageHexID, String imageTag) { // now get previous RC, fetch image Hex ID, and compare int previousVersion = latestVersion - 1; if (previousVersion < 1) { if (chatty) listener.getLogger().println( "\n first version skip image compare"); return true; } IReplicationController prevRC = null; try { prevRC = client.get(ResourceKind.REPLICATION_CONTROLLER, depCfg + "-" + previousVersion, namespace); } catch (Throwable t) { if (chatty) t.printStackTrace(listener.getLogger()); } if (prevRC == null) { listener.getLogger().println( "\n\n could not obtain previous replication controller"); return false; } // get the dc again from the rc vs. passing the dc in aIClient client, // IDeploymentConfig dc, String imageTag, boolean chatty, TaskListener // listener, long wait)s a form of cross reference verification String dcJson = prevRC .getAnnotation("openshift.io/encoded-deployment-config"); if (dcJson == null || dcJson.length() == 0) { listener.getLogger() .println( "\n\n associated DeploymentConfig for previous ReplicationController missing"); return false; } ModelNode dcNode = ModelNode.fromJSONString(dcJson); IDeploymentConfig dc = new DeploymentConfig(dcNode, client, null); String previousImageHexID = dc .getImageHexIDForImageNameAndTag(imageTag); if (previousImageHexID == null || previousImageHexID.length() == 0) { // don't count ill obtained prev image id as successful image id // change listener.getLogger() .println( "\n\n could not obtain hex image ID for previous deployment"); return false; } if (latestImageHexID.equals(previousImageHexID)) { if (chatty) listener.getLogger().println( "\n images still the same " + latestImageHexID); return false; } else { if (chatty) listener.getLogger().println( "\n image did change, new image " + latestImageHexID + " old image " + previousImageHexID); return true; } }
Example #15
Source File: OpenShiftBuildCanceller.java From jenkins-plugin with Apache License 2.0 | 4 votes |
public boolean coreLogic(Launcher launcher, TaskListener listener, Map<String, String> overrides) { boolean chatty = Boolean.parseBoolean(verbose); listener.getLogger().println( String.format(MessageConstants.START_BUILD_RELATED_PLUGINS, DISPLAY_NAME, getBldCfg(overrides), getNamespace(overrides))); // get oc client IClient client = getClient(listener, DISPLAY_NAME, overrides); if (client != null) { /* * try { */List<IBuild> list = client.list(ResourceKind.BUILD, getNamespace(overrides)); int count = 0; for (IBuild bld : list) { String phaseStr = bld.getStatus(); // if build active, let's cancel it String buildName = bld.getName(); if (buildName.startsWith(getBldCfg(overrides)) && !isBuildFinished(phaseStr)) { if (chatty) listener.getLogger().println( "\nOpenShiftBuildCanceller found active build " + buildName); // re-get bld (etcd employs optimistic update) bld = client.get(ResourceKind.BUILD, buildName, getNamespace(overrides)); // call cancel api bld.accept( new CapabilityVisitor<IBuildCancelable, IBuild>() { public IBuild visit(IBuildCancelable cancelable) { return cancelable.cancel(); } }, null); listener.getLogger().println( String.format(MessageConstants.CANCELLED_BUILD, buildName)); count++; } } listener.getLogger().println( String.format(MessageConstants.EXIT_BUILD_CANCEL, DISPLAY_NAME, count)); return true; /* * } catch (HttpClientException e1) { * e1.printStackTrace(listener.getLogger()); return false; } */} else { return false; } }