com.openshift.restclient.IClient Java Examples

The following examples show how to use com.openshift.restclient.IClient. 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: OpenShiftTopologyConnector.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public void start(StartContext context) throws StartException {
    ServiceTarget target = context.getChildTarget();

    ClientService clientService = new ClientService();
    target.addService(ClientService.SERVICE_NAME, clientService)
            .install();

    NamespaceService namespaceService = new NamespaceService();
    target.addService(NamespaceService.SERVICE_NAME, namespaceService)
            .addDependency(ClientService.SERVICE_NAME, IClient.class, namespaceService.getClientInjector())
            .install();

    ServiceWatcher watcher = new ServiceWatcher();
    target.addService(ServiceWatcher.SERVICE_NAME, watcher)
            .addDependency(ClientService.SERVICE_NAME, IClient.class, watcher.getClientInjector())
            .addDependency(NamespaceService.SERVICE_NAME, String.class, watcher.getNamespaceInjector())
            .addDependency(TopologyManagerActivator.SERVICE_NAME, TopologyManager.class, watcher.getTopologyManagerInjector())
            .install();
}
 
Example #2
Source File: ClientService.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private IClient openshiftClient() throws IOException {
    String kubeHost = serviceHost("kubernetes");
    int kubePort = servicePort("kubernetes");

    Path tokenFile = Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/token");
    String scheme = "http";
    String token = null;
    if (Files.exists(tokenFile)) {
        token = new String(Files.readAllBytes(tokenFile));
        scheme = "https";
    }

    return new ClientBuilder(scheme + "://" + kubeHost + ":" + kubePort)
            .usingToken(token)
            .build();
}
 
Example #3
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 6 votes vote down vote up
default IClient getClient(TaskListener listener, String displayName,
        Map<String, String> overrides, String token) {
    Auth auth = getAuth();
    ClientBuilder cb = new ClientBuilder(getApiURL(overrides))
            .sslCertificateCallback(auth)
            .usingToken(token)
            .sslCertificateCollection(getApiURL(overrides), auth.getCerts());
    if (auth.useCert())
        cb.sslCertCallbackWithDefaultHostnameVerifier(true);
    IClient client = cb.build();
    if (client == null) {
        listener.getLogger().println(
                String.format(MessageConstants.CANNOT_GET_CLIENT,
                        displayName, getApiURL(overrides)));
    }
    return new RetryIClient(client, listener);
}
 
Example #4
Source File: OpenshiftClientStorageProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private IClient getClient(ClientStorageProviderModel providerModel) {
    synchronized (this) {
        if (client == null) {
            client = new ClientBuilder(providerModel.get(OpenshiftClientStorageProviderFactory.CONFIG_PROPERTY_OPENSHIFT_URI)).build();
        }
    }

    return client;
}
 
Example #5
Source File: OpenshiftClientStorageProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public OpenshiftClientStorageProvider create(KeycloakSession session, ComponentModel model) {
    ClientStorageProviderModel providerModel = createProviderModel(model);
    IClient client = getClient(providerModel);

    if (client != null) {
        return new OpenshiftClientStorageProvider(session, providerModel, client);
    }

    client.getAuthorizationContext().setToken(providerModel.get(OpenshiftClientStorageProviderFactory.CONFIG_PROPERTY_ACCESS_TOKEN));

    return new OpenshiftClientStorageProvider(session, providerModel, client);
}
 
Example #6
Source File: IOpenShiftBuildVerifier.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
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 #7
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
default boolean doesDCTriggerOnImageTag(IClient client,
        IDeploymentConfig dc, String imageTag, boolean chatty,
        TaskListener listener) {
    if (dc == null || imageTag == null)
        throw new RuntimeException(
                "needed param null for doesDCTriggerOnImageTag");
    if (listener == null)
        chatty = false;

    Collection<IDeploymentTrigger> triggers = dc.getTriggers();
    for (IDeploymentTrigger trigger : triggers) {
        if (trigger instanceof IDeploymentImageChangeTrigger) {
            IDeploymentImageChangeTrigger ict = (IDeploymentImageChangeTrigger) trigger;
            if (chatty)
                listener.getLogger().println(
                        "\n\n found ict " + ict.toString() + " with from "
                                + ict.getFrom().getNameAndTag()
                                + ", auto: " + ict.isAutomatic());
            if (ict.getFrom().getNameAndTag().contains(imageTag)
                    && ict.isAutomatic()) {
                if (chatty)
                    listener.getLogger().println(
                            "\n\n ict  triggers off of " + imageTag);
                return true;
            }
        }
    }

    return false;

}
 
Example #8
Source File: OpenShiftImageStreams.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
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 #9
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: IOpenShiftExec.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
default IClient getClient(TaskListener listener, String displayName,
        Map<String, String> overrides, String token) {
    Auth auth = getAuth();
    ClientBuilder cb = null;
    long timeoutInMS = this.getTimeout(listener,
            Boolean.parseBoolean(getVerbose(overrides)), overrides);
    if (timeoutInMS > Integer.MAX_VALUE) {
        int timeoutInMin = (int) (timeoutInMS / 60000);
        cb = new ClientBuilder(getApiURL(overrides))
                .sslCertificateCallback(auth)
                .withReadTimeout(timeoutInMin, TimeUnit.MINUTES)
                .withWriteTimeout(timeoutInMin, TimeUnit.MINUTES)
                .withConnectTimeout(timeoutInMin, TimeUnit.MINUTES)
                .usingToken(token)
                .sslCertificateCollection(getApiURL(overrides),
                        auth.getCerts());
    } else {
        cb = new ClientBuilder(getApiURL(overrides))
                .sslCertificateCallback(auth)
                .withReadTimeout((int) timeoutInMS, TimeUnit.MILLISECONDS)
                .withWriteTimeout((int) timeoutInMS, TimeUnit.MILLISECONDS)
                .withConnectTimeout((int) timeoutInMS,
                        TimeUnit.MILLISECONDS)
                .usingToken(token)
                .sslCertificateCollection(getApiURL(overrides),
                        auth.getCerts());
    }

    if (auth.useCert())
        cb.sslCertCallbackWithDefaultHostnameVerifier(true);
    IClient client = cb.build();
    if (client == null) {
        listener.getLogger().println(
                String.format(MessageConstants.CANNOT_GET_CLIENT,
                        displayName, getApiURL(overrides)));
    }
    return new RetryIClient(client, listener);

}
 
Example #11
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
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 #13
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default IClient getClient(TaskListener listener, String displayName,
        Map<String, String> overrides) {
    return this.getClient(listener, displayName, overrides, Auth
            .deriveBearerToken(getAuthToken(overrides), listener,
                    Boolean.getBoolean(getVerbose(overrides)), overrides));
}
 
Example #14
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
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: IOpenShiftCreator.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default boolean makeRESTCall(boolean chatty, TaskListener listener,
        String path, ModelNode resource, Map<String, String> overrides) {
    // TODO openshift-restclient-java's IApiTypeMapper is not really
    // accessible from our perspective,
    // without accessing/recreating the underlying OkHttpClient, so until
    // that changes, we use our own
    // type mapping
    if (OpenShiftApiObjHandler.apiMap.get(path) == null) {
        listener.getLogger().println(
                String.format(MessageConstants.TYPE_NOT_SUPPORTED, path));
        return false;
    }

    // if they have specified a namespace in the json/yaml, honor that vs.
    // the one specified in the build step,
    // though the user then needs to insure that the service account for the
    // one specified in the build step
    // has access to that namespace
    String namespace = resource.get("metadata").get("namespace").asString();
    boolean setOnResource = false;
    if (UNDEFINED.equals(namespace))
        namespace = getNamespace(overrides);
    else
        setOnResource = true;

    IClient client = this.getClient(listener, DISPLAY_NAME, overrides);

    if (client == null) {
        return false;
    }

    KubernetesResource kr = new KubernetesResource(resource, client, null);
    if (setOnResource)
        kr.setNamespace(namespace);
    if (chatty)
        listener.getLogger().println(
                "\nOpenShiftCreator calling create on for type "
                        + OpenShiftApiObjHandler.apiMap.get(path)[1]
                        + " and resource " + kr.toJson(false));
    client.execute("POST", OpenShiftApiObjHandler.apiMap.get(path)[1],
            namespace, null, null, kr);

    return true;
}
 
Example #16
Source File: OpenShiftBuildCanceller.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
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;
    }
}
 
Example #17
Source File: OpenshiftClientStorageProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
OpenshiftClientStorageProvider(KeycloakSession session, ClientStorageProviderModel providerModel, IClient client) {
    this.session = session;
    this.providerModel = providerModel;
    this.client = client;
}
 
Example #18
Source File: OpenshiftSAClientAdapter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public OpenshiftSAClientAdapter(String clientId, IResource resource, IClient client, KeycloakSession session, RealmModel realm, ClientStorageProviderModel component) {
    super(session, realm, component);
    this.resource = resource;
    this.clientId = clientId;
    this.client = client;
}
 
Example #19
Source File: IOpenShiftPlugin.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
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 #20
Source File: ServiceWatcher.java    From thorntail with Apache License 2.0 4 votes vote down vote up
public Injector<IClient> getClientInjector() {
    return this.clientInjector;
}
 
Example #21
Source File: IOpenShiftDeleterLabels.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default boolean coreLogic(Launcher launcher, TaskListener listener,
        Map<String, String> overrides) {
    boolean chatty = Boolean.parseBoolean(getVerbose(overrides));
    listener.getLogger().println(
            String.format(MessageConstants.START_DELETE_OBJS, DISPLAY_NAME,
                    getNamespace(overrides)));

    updateApiTypes(chatty, listener, overrides);

    // get oc client
    IClient client = this.getClient(listener, DISPLAY_NAME, overrides);

    if (client != null) {
        // verify valid type is specified
        Set<String> types = OpenShiftApiObjHandler.apiMap.keySet();
        String resourceKind = null;
        int deletes = 0;
        String[] inputTypes = getTypes(overrides).split(",");
        String[] inputKeys = getKeys(overrides).split(",");
        String[] inputValues = getValues(overrides).split(",");

        if (inputKeys.length != inputValues.length) {
            listener.getLogger().println(
                    String.format(
                            MessageConstants.EXIT_DELETE_KEY_TYPE_MISMATCH,
                            inputValues.length, inputKeys.length));
            return false;
        }

        // we do a list of maps so that users can specify different value
        // options for a common key
        List<Map<String, String>> listOfLabels = new ArrayList<Map<String, String>>();
        for (int j = 0; j < inputKeys.length; j++) {
            Map<String, String> labels = new HashMap<String, String>();
            labels.put(inputKeys[j], inputValues[j]);
            listOfLabels.add(labels);
        }

        for (int i = 0; i < inputTypes.length; i++) {
            if (OpenShiftApiObjHandler.typeShortcut
                    .containsKey(inputTypes[i])) {
                resourceKind = OpenShiftApiObjHandler.typeShortcut
                        .get(inputTypes[i]);
            } else {
                for (String type : types) {

                    if (type.equalsIgnoreCase(inputTypes[i])) {
                        resourceKind = type;
                        break;
                    }

                }
            }

            if (resourceKind == null) {
                listener.getLogger().println(
                        String.format(MessageConstants.TYPE_NOT_SUPPORTED,
                                inputTypes[i]));
                continue;
            }

            // rc[0] will be successful deletes, rc[1] will be failed
            // deletes, but no failed deletes in the labels scenario
            int[] rc = new int[2];
            rc = deleteAPIObjs(client, listener, getNamespace(overrides),
                    resourceKind, null, listOfLabels, chatty);
            deletes = deletes + rc[0];
        }

        listener.getLogger().println(
                String.format(MessageConstants.EXIT_DELETE_GOOD,
                        DISPLAY_NAME, deletes));
        return true;
    }
    return false;
}
 
Example #22
Source File: IOpenShiftBuilder.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
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 #23
Source File: IOpenShiftBuilder.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
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 #24
Source File: IOpenShiftDeleterList.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default boolean coreLogic(Launcher launcher, TaskListener listener,
        Map<String, String> overrides) {
    boolean chatty = Boolean.parseBoolean(getVerbose(overrides));
    listener.getLogger().println(
            String.format(MessageConstants.START_DELETE_OBJS, DISPLAY_NAME,
                    getNamespace(overrides)));

    updateApiTypes(chatty, listener, overrides);

    // get oc client
    IClient client = this.getClient(listener, DISPLAY_NAME, overrides);

    if (client != null) {
        // verify valid type is specified
        Set<String> types = OpenShiftApiObjHandler.apiMap.keySet();
        String resourceKind = null;
        int deletes = 0;
        int fails = 0;
        int badType = 0;
        String[] inputTypes = getTypes(overrides).split(",");
        String[] inputKeys = getKeys(overrides).split(",");

        if (inputTypes.length != inputKeys.length) {
            listener.getLogger().println(
                    String.format(
                            MessageConstants.EXIT_DELETE_KEY_TYPE_MISMATCH,
                            inputTypes.length, inputKeys.length));
            return false;
        }

        for (int i = 0; i < inputTypes.length; i++) {
            if (OpenShiftApiObjHandler.typeShortcut
                    .containsKey(inputTypes[i])) {
                resourceKind = OpenShiftApiObjHandler.typeShortcut
                        .get(inputTypes[i]);
            } else {
                for (String type : types) {

                    if (type.equalsIgnoreCase(inputTypes[i])) {
                        resourceKind = type;
                        break;
                    }

                }
            }

            if (resourceKind == null) {
                listener.getLogger().println(
                        String.format(MessageConstants.TYPE_NOT_SUPPORTED,
                                inputTypes[i]));
                badType++;
                continue;
            }

            // rc[0] will be successful deletes, rc[1] will be failed
            // deletes
            int[] rc = new int[2];
            rc = deleteAPIObjs(client, listener, getNamespace(overrides),
                    resourceKind, inputKeys[i], null, chatty);
            deletes = deletes + rc[0];
            fails = fails + rc[1];
        }

        if (fails == 0 && badType == 0) {
            listener.getLogger().println(
                    String.format(MessageConstants.EXIT_DELETE_GOOD,
                            DISPLAY_NAME, deletes));
            return true;
        } else {
            listener.getLogger().println(
                    String.format(MessageConstants.EXIT_DELETE_BAD,
                            DISPLAY_NAME, deletes, fails + badType));
        }
    }
    return false;
}
 
Example #25
Source File: RetryIClient.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public IClient clone() {
    return new RetryIClient(client.clone(), listener);
}
 
Example #26
Source File: RetryIClient.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
public RetryIClient(IClient c, TaskListener l) {
    client = c;
    listener = l;
}
 
Example #27
Source File: IOpenShiftBuildVerifier.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
default boolean coreLogic(Launcher launcher, TaskListener listener,
        Map<String, String> overrides) throws InterruptedException {
    boolean chatty = Boolean.parseBoolean(getVerbose(overrides));
    boolean checkDeps = Boolean
            .parseBoolean(getCheckForTriggeredDeployments(overrides));
    listener.getLogger().println(
            String.format(MessageConstants.START_BUILD_RELATED_PLUGINS,
                    DISPLAY_NAME, getBldCfg(overrides),
                    getNamespace(overrides)));

    // get oc client
    IClient client = this.getClient(listener, DISPLAY_NAME, overrides);

    if (client != null) {
        String bldId = getLatestBuildID(client, overrides);

        if (!checkDeps) {
            listener.getLogger()
                    .println(
                            String.format(
                                    MessageConstants.WAITING_ON_BUILD_STARTED_ELSEWHERE,
                                    bldId));
        } else {
            listener.getLogger()
                    .println(
                            String.format(
                                    MessageConstants.WAITING_ON_BUILD_STARTED_ELSEWHERE_PLUS_DEPLOY,
                                    bldId));
        }

        return this
                .verifyBuild(
                        TimeUnit.NANOSECONDS.toMillis(System.nanoTime()),
                        getTimeout(listener, chatty, overrides), client,
                        getBldCfg(overrides), bldId,
                        getNamespace(overrides), chatty, listener,
                        DISPLAY_NAME, checkDeps, false, overrides);

    } else {
        return false;
    }

}
 
Example #28
Source File: OpenShiftDeployCanceller.java    From jenkins-plugin with Apache License 2.0 4 votes vote down vote up
@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 #29
Source File: NamespaceService.java    From thorntail with Apache License 2.0 4 votes vote down vote up
public Injector<IClient> getClientInjector() {
    return this.clientInjector;
}
 
Example #30
Source File: ClientService.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Override
public IClient getValue() throws IllegalStateException, IllegalArgumentException {
    return this.client;
}