Java Code Examples for com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse#error()

The following examples show how to use com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse#error() . 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: PublishArtifactExecutor.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse execute() {
    ArtifactPlan artifactPlan = publishArtifactRequest.getArtifactPlan();
    final ArtifactStoreConfig artifactStoreConfig = publishArtifactRequest.getArtifactStore().getArtifactStoreConfig();
    try {
        final DockerClient docker = clientFactory.docker(artifactStoreConfig);
        Map<String, String> environmentVariables = publishArtifactRequest.getEnvironmentVariables() == null ? new HashMap<>() : publishArtifactRequest.getEnvironmentVariables();
        environmentVariables.putAll(System.getenv());
        final DockerImage image = artifactPlan.getArtifactPlanConfig().imageToPush(publishArtifactRequest.getAgentWorkingDir(), environmentVariables);

        LOG.info(format("Pushing docker image `%s` to docker registry `%s`.", image, artifactStoreConfig.getRegistryUrl()));
        consoleLogger.info(format("Pushing docker image `%s` to docker registry `%s`.", image, artifactStoreConfig.getRegistryUrl()));

        docker.push(image.toString(), progressHandler);
        docker.close();

        publishArtifactResponse.addMetadata("image", image.toString());
        publishArtifactResponse.addMetadata("digest", progressHandler.getDigest());
        consoleLogger.info(format("Image `%s` successfully pushed to docker registry `%s`.", image, artifactStoreConfig.getRegistryUrl()));
        return DefaultGoPluginApiResponse.success(publishArtifactResponse.toJSON());
    } catch (Exception e) {
        consoleLogger.error(String.format("Failed to publish %s: %s", artifactPlan, e));
        LOG.error(String.format("Failed to publish %s: %s", artifactPlan, e.getMessage()), e);
        return DefaultGoPluginApiResponse.error(String.format("Failed to publish %s: %s", artifactPlan, e.getMessage()));
    }
}
 
Example 2
Source File: GetRolesExecutor.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse execute() throws IOException {
    if (request.getRoles().isEmpty()) {
        LOG.debug("[Get User Roles] Server sent empty roles config. Nothing to do!.");
        return DefaultGoPluginApiResponse.success("[]");
    }

    GitHub gitHub = clientBuilder.from(request.getAuthConfig().gitHubConfiguration());
    GHUser user = gitHub.getUser(request.getUsername());

    if (user == null) {
        LOG.error(format("[Get User Roles] User %s does not exist in GitHub.", request.getUsername()));
        return DefaultGoPluginApiResponse.error("");
    }

    List<String> roles = gitHubAuthorizer.authorize(user, request.getAuthConfig(), request.getRoles());

    LOG.debug(format("[Get User Roles] User %s has %s roles.", request.getUsername(), roles));
    return DefaultGoPluginApiResponse.success(GSON.toJson(roles));
}
 
Example 3
Source File: BaseGoPlugin.java    From gocd-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest request) throws UnhandledRequestTypeException {
    try {
        switch (request.requestName()) {
            case "configuration":
            case "go.plugin-settings.get-configuration":
                return handleGetConfigRequest(request);
            case "validate":
            case "go.plugin-settings.validate-configuration":
                return handleValidation(request);
            case "execute":
                return handleTaskExecution(request);
            case "view":
            case "go.plugin-settings.get-view":
                return handleTaskView(request);
            default:
                return DefaultGoPluginApiResponse.badRequest(String.format("Invalid request name %s", request.requestName()));
        }
    } catch (Throwable e) {
        return DefaultGoPluginApiResponse.error(e.getMessage());
    }
}
 
Example 4
Source File: StatusReportGenerationErrorHandler.java    From kubernetes-elastic-agents with Apache License 2.0 5 votes vote down vote up
public static GoPluginApiResponse handle(PluginStatusReportViewBuilder builder, Exception e) {
    try {
        LOG.error(format("Error while generating status report: {0}", e.getMessage()), e);
        final Template template = builder.getTemplate("error.template.ftlh");
        final String errorView = builder.build(template, new StatusReportGenerationError(e));

        final JsonObject responseJSON = new JsonObject();
        responseJSON.addProperty("view", errorView);

        return DefaultGoPluginApiResponse.success(responseJSON.toString());
    } catch (Exception ex) {
        LOG.error(format("Failed to generate error report: {0}", e.getMessage()), e);
        return DefaultGoPluginApiResponse.error(format("Failed to generate error report: {0}", e.toString()));
    }
}
 
Example 5
Source File: ValidateUserRequestExecutor.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse execute() throws Exception {
    GitHub gitHub = clientBuilder.from(request.getAuthConfig().gitHubConfiguration());
    GHUser user = gitHub.getUser(request.getUsername());
    if (user == null) {
        LOG.error(format("[Is Valid User] User %s does not exist in GitHub.", request.getUsername()));
        return DefaultGoPluginApiResponse.error(String.format("User '%s' does not exist in GitHub.", request.getUsername()));
    } else {
        LOG.debug(format("[Is Valid User] %s is valid user.", request.getUsername()));
        return DefaultGoPluginApiResponse.success("");
    }
}
 
Example 6
Source File: StatusReportGenerationErrorHandler.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
public static GoPluginApiResponse handle(PluginStatusReportViewBuilder builder, Exception e) {
    try {
        LOG.error(format("Error while generating status report: {0}", e.getMessage()), e);
        final Template template = builder.getTemplate("error.template.ftlh");
        final String errorView = builder.build(template, new StatusReportGenerationError(e));

        final JsonObject responseJSON = new JsonObject();
        responseJSON.addProperty("view", errorView);

        return DefaultGoPluginApiResponse.success(responseJSON.toString());
    } catch (Exception ex) {
        LOG.error(format("Failed to generate error report: {0}", e.getMessage()), e);
        return DefaultGoPluginApiResponse.error(format("Failed to generate error report: {0}.", e.toString()));
    }
}
 
Example 7
Source File: FetchArtifactExecutor.java    From docker-registry-artifact-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public GoPluginApiResponse execute() {
    try {
        final Map<String, String> artifactMap = fetchArtifactRequest.getMetadata();
        validateMetadata(artifactMap);
        FetchArtifactConfig fetchArtifactConfig = fetchArtifactRequest.getFetchArtifactConfig();

        final String artifactPrefix = fetchArtifactConfig.getEnvironmentVariablePrefix();
        final boolean skipImagePulling = fetchArtifactConfig.getSkipImagePulling();
        final String imageToPull = artifactMap.get("image");

        if (skipImagePulling) {
            consoleLogger.info(String.format("Not pulling docker image `%s` due to `Skip Image Pulling` configuration being set.", imageToPull));
            LOG.info(String.format("Not pulling docker image `%s` due to `Skip Image Pulling` configuration being set.", imageToPull));
        } else {
            consoleLogger.info(String.format("Pulling docker image `%s` from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));
            LOG.info(String.format("Pulling docker image `%s` from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));

            DockerClient docker = clientFactory.docker(fetchArtifactRequest.getArtifactStoreConfig());
            docker.pull(imageToPull, dockerProgressHandler);
            docker.close();

            consoleLogger.info(String.format("Image `%s` successfully pulled from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));

            if (!dockerProgressHandler.getDigest().equals(artifactMap.get("digest"))) {
                throw new RuntimeException(format("Expecting pulled image digest to be [%s] but it is [%s].", artifactMap.get("digest"), dockerProgressHandler.getDigest()));
            }
        }

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", StringUtils.isEmpty(artifactPrefix) ? "ARTIFACT_IMAGE" : String.format("%s_ARTIFACT_IMAGE", artifactPrefix));
        jsonObject.addProperty("value", imageToPull);

        JsonArray jsonElements = new JsonArray();
        jsonElements.add(jsonObject);

        return DefaultGoPluginApiResponse.success(jsonElements.toString());
    } catch (Exception e) {
        final String message = format("Failed pull docker image: %s", e);
        consoleLogger.error(message);
        LOG.error(message);
        return DefaultGoPluginApiResponse.error(message);
    }
}
 
Example 8
Source File: KubernetesPlugin.java    From kubernetes-elastic-agents with Apache License 2.0 4 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest request) {
    ClusterProfileProperties clusterProfileProperties;
    try {
        switch (Request.fromString(request.requestName())) {
            case REQUEST_GET_CAPABILITIES:
                return new GetCapabilitiesExecutor().execute();
            case PLUGIN_SETTINGS_GET_ICON:
                return new GetPluginSettingsIconExecutor().execute();
            case REQUEST_GET_ELASTIC_AGENT_PROFILE_METADATA:
                return new GetProfileMetadataExecutor().execute();
            case REQUEST_GET_ELASTIC_AGENT_PROFILE_VIEW:
                return new GetProfileViewExecutor().execute();
            case REQUEST_VALIDATE_ELASTIC_AGENT_PROFILE:
                return ProfileValidateRequest.fromJSON(request.requestBody()).executor().execute();
            case REQUEST_GET_CLUSTER_PROFILE_METADATA:
                return new GetClusterProfileMetadataExecutor().execute();
            case REQUEST_GET_CLUSTER_PROFILE_VIEW:
                return new GetClusterProfileViewRequestExecutor().execute();
            case REQUEST_VALIDATE_CLUSTER_PROFILE_CONFIGURATION:
                return ClusterProfileValidateRequest.fromJSON(request.requestBody()).executor(pluginRequest).execute();
            case REQUEST_CREATE_AGENT:
                CreateAgentRequest createAgentRequest = CreateAgentRequest.fromJSON(request.requestBody());
                clusterProfileProperties = createAgentRequest.clusterProfileProperties();
                return createAgentRequest.executor(getAgentInstancesFor(clusterProfileProperties), pluginRequest).execute();
            case REQUEST_SHOULD_ASSIGN_WORK:
                ShouldAssignWorkRequest shouldAssignWorkRequest = ShouldAssignWorkRequest.fromJSON(request.requestBody());
                clusterProfileProperties = shouldAssignWorkRequest.clusterProfileProperties();
                return shouldAssignWorkRequest.executor(getAgentInstancesFor(clusterProfileProperties)).execute();
            case REQUEST_SERVER_PING:
                ServerPingRequest serverPingRequest = ServerPingRequest.fromJSON(request.requestBody());
                List<ClusterProfileProperties> listOfClusterProfileProperties = serverPingRequest.allClusterProfileProperties();
                refreshInstancesForAllClusters(listOfClusterProfileProperties);
                return serverPingRequest.executor(clusterSpecificAgentInstances, pluginRequest).execute();
            case REQUEST_JOB_COMPLETION:
                JobCompletionRequest jobCompletionRequest = JobCompletionRequest.fromJSON(request.requestBody());
                clusterProfileProperties = jobCompletionRequest.clusterProfileProperties();
                return jobCompletionRequest.executor(getAgentInstancesFor(clusterProfileProperties), pluginRequest).execute();
            case REQUEST_CLUSTER_STATUS_REPORT:
                ClusterStatusReportRequest clusterStatusReportRequest = ClusterStatusReportRequest.fromJSON(request.requestBody());
                clusterProfileProperties = clusterStatusReportRequest.clusterProfileProperties();
                KubernetesClientFactory.instance().clearOutExistingClient();
                refreshInstancesForCluster(clusterProfileProperties);
                return clusterStatusReportRequest.executor().execute();
            case REQUEST_ELASTIC_AGENT_STATUS_REPORT:
                AgentStatusReportRequest statusReportRequest = AgentStatusReportRequest.fromJSON(request.requestBody());
                clusterProfileProperties = statusReportRequest.clusterProfileProperties();
                refreshInstancesForCluster(clusterProfileProperties);
                return statusReportRequest.executor().execute();
            case REQUEST_CLUSTER_PROFILE_CHANGED:
                return new DefaultGoPluginApiResponse(200);
            case REQUEST_MIGRATE_CONFIGURATION:
                return MigrateConfigurationRequest.fromJSON(request.requestBody()).executor().execute();
            default:
                throw new UnhandledRequestTypeException(request.requestName());
        }
    } catch (Exception e) {
        LOG.error("Failed to handle request " + request.requestName(), e);
        return DefaultGoPluginApiResponse.error("Failed to handle request " + request.requestName());
    }
}
 
Example 9
Source File: DummyArtifactPlugin.java    From go-plugins with Apache License 2.0 4 votes vote down vote up
private GoPluginApiResponse fetchArtifact(FetchArtifactRequest fetchArtifactRequest) throws IOException {
    ArtifactStoreConfig artifactStoreConfig = fetchArtifactRequest.getArtifactStoreConfig();
    String artifactPath = fetchArtifactRequest.getFetchArtifact().getPath();
    PublishMetadata metadata = fetchArtifactRequest.getMetadata();

    HttpUrl httpUrl = HttpUrl.parse(artifactStoreConfig.getUrl())
            .newBuilder()
            .addPathSegment("files")
            .addPathSegment(metadata.getJobIdentifier().getPipeline())
            .addPathSegment(metadata.getJobIdentifier().getPipelineCounter())
            .addPathSegment(metadata.getJobIdentifier().getStage())
            .addPathSegment(metadata.getJobIdentifier().getStageCounter())
            .addPathSegment(metadata.getJobIdentifier().getJob())
            .addPathSegments(artifactPath)
            .build();

    Request request = new Request.Builder()
            .url(httpUrl)
            .get()
            .addHeader("Authorization", Credentials.basic(artifactStoreConfig.getUsername(), artifactStoreConfig.getPassword()))
            .addHeader("Confirm", "true")
            .build();

    Response response = CLIENT.newCall(request).execute();
    if (!response.isRedirect() && response.isSuccessful()) {
        return DefaultGoPluginApiResponse.success("[\n" +
                "  {\n" +
                "    \"name\": \"VAR1\",\n" +
                "    \"value\": \"VALUE1\",\n" +
                "    \"secure\": true\n" +
                "  },\n" +
                "  {\n" +
                "    \"name\": \"VAR2\",\n" +
                "    \"value\": \"VALUE2\",\n" +
                "    \"secure\": false\n" +
                "  },\n" +
                "  {\n" +
                "    \"name\": \"GO_JOB_NAME\",\n" +
                "    \"value\": \"new job name\",\n" +
                "    \"secure\": false\n" +
                "  }\n" +
                "]\n");
    }

    LOG.error(format("Failed to fetch artifact[%s] with status %d. Error: %s", artifactPath, response.code(), response.body().string()));
    return DefaultGoPluginApiResponse.error(response.body().string());
}
 
Example 10
Source File: DummyArtifactPlugin.java    From go-plugins with Apache License 2.0 4 votes vote down vote up
private GoPluginApiResponse publishArtifact(PublishArtifactRequest publishArtifactRequest) {
    ArtifactConfig artifactConfig = publishArtifactRequest.getArtifactPlan().getArtifactConfig();
    ArtifactStoreConfig artifactStoreConfig = publishArtifactRequest.getArtifactStore().getArtifactStoreConfig();
    JobIdentifier jobIdentifier = publishArtifactRequest.getJobIdentifier();

    try {
        File artifact = new File(publishArtifactRequest.getAgentWorkingDir() + File.separator + artifactConfig.getSource());

        if (!artifact.exists()) {
            return DefaultGoPluginApiResponse.error(format("Artifact `%s` does not exist at location `%s`.", artifact.getName(), artifact.getParentFile().getAbsolutePath()));
        }

        if (!artifact.canRead()) {
            return DefaultGoPluginApiResponse.error(format("Does not have permission to read artifact `%s`", artifact.getName()));
        }

        if (artifact.isDirectory()) {
            return DefaultGoPluginApiResponse.error(format("Artifact `%s` is a directory.", artifact.getName()));
        }

        RequestBody body = RequestBody.create(MediaType.parse("application/java-archive"), artifact);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", artifactConfig.getSource(), body)
                .build();

        HttpUrl httpUrl = HttpUrl.parse(artifactStoreConfig.getUrl())
                .newBuilder()
                .addPathSegment("files")
                .addPathSegment(jobIdentifier.getPipeline())
                .addPathSegment(jobIdentifier.getPipelineCounter())
                .addPathSegment(jobIdentifier.getStage())
                .addPathSegment(jobIdentifier.getStageCounter())
                .addPathSegment(jobIdentifier.getJob())
                .addPathSegment(artifactConfig.getDestination())
                .addPathSegment(new File(artifactConfig.getSource()).getName())
                .build();


        Request request = new Request.Builder()
                .url(httpUrl)
                .post(requestBody)
                .addHeader("Authorization", Credentials.basic(artifactStoreConfig.getUsername(), artifactStoreConfig.getPassword()))
                .addHeader("Confirm", "true")
                .build();

        Response response = CLIENT.newCall(request).execute();
        if (!response.isRedirect() && response.isSuccessful()) {
            return DefaultGoPluginApiResponse.success(GSON.toJson(singletonMap("metadata", new PublishMetadata(artifactConfig.getSource(), jobIdentifier))));
        }

        LOG.error(format("Failed to upload artifact[%s] with status %d. Error: %s", artifactConfig.getSource(), response.code(), response.body().string()));
        return DefaultGoPluginApiResponse.error(response.body().string());
    } catch (Exception e) {
        LOG.error(format("Failed to upload artifact[%s] Error: %s", artifactConfig.getSource(), e.getMessage()));
        return DefaultGoPluginApiResponse.error(e.getMessage());
    }
}