aboutsummaryrefslogtreecommitdiffstats
path: root/vespa-maven-plugin/src/main/java/ai/vespa/hosted/plugin/AbstractVespaMojo.java
blob: b7aef045f77dea2b345008b9ee8145971bc57958 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.hosted.plugin;

import ai.vespa.hosted.api.ControllerHttpClient;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.yolean.Exceptions;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

import static java.util.stream.Collectors.joining;

/**
 * Base class for hosted Vespa plugin mojos.
 *
 * @author jonmv
 */
public abstract class AbstractVespaMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true)
    protected MavenProject project;

    @Parameter(property = "endpoint", defaultValue = "https://api.vespa-external.aws.oath.cloud:4443")
    protected String endpoint;

    @Parameter(property = "tenant")
    protected String tenant;

    @Parameter(property = "application")
    protected String application;

    @Parameter(property = "instance")
    protected String instance;

    @Parameter(property = "tags")
    protected String tags;

    @Parameter(property = "apiKey")
    protected String apiKey;

    @Parameter(property = "apiKeyFile")
    protected String apiKeyFile;

    @Parameter(property = "apiCertificateFile")
    protected String apiCertificateFile;

    // Fields set up as part of setup().
    protected ApplicationId id;
    protected ControllerHttpClient controller;

    protected boolean requireInstance() { return false; }

    @Override
    public final void execute() throws MojoExecutionException, MojoFailureException {
        try {
            setup();
            doExecute();
        }
        catch (MojoFailureException | MojoExecutionException e) {
            throw e;
        }
        catch (Exception e) {
            String message = "Execution failed for application " + name() + ":\n" + Exceptions.toMessageString(e);
            if (e.getSuppressed().length > 0)
                message += "\nSuppressed:\n" + Stream.of(e.getSuppressed()).map(Exceptions::toMessageString).collect(joining("\n"));

            throw new MojoExecutionException(message, e);
        }
    }

    /** Override this in subclasses, instead of {@link #execute()}. */
    protected abstract void doExecute() throws Exception;

    /** Return the name of the relevant entity, e.g., application with or without instance. */
    protected String name() { return tenant + "." + application; }

    protected void setup() throws MojoExecutionException {
        tenant = firstNonBlank(tenant, project.getProperties().getProperty("tenant"))
                .orElseThrow(() -> new MojoExecutionException("'tenant' must be specified as a parameter or project property"));
        application = firstNonBlank(application, project.getProperties().getProperty("application"))
                .orElseThrow(() -> new MojoExecutionException("'application' must be specified as a parameter or project property"));
        instance = firstNonBlank(instance, project.getProperties().getProperty("instance"), requireInstance() ? null : InstanceName.defaultName().value())
                .orElseThrow(() -> new MojoExecutionException("'instance' must be specified as a parameter or project property"));
        id = ApplicationId.from(tenant, application, instance);

        Optional<Path> apiKeyPath = apiKeyPath(tenant);
        if ( ! isNullOrBlank(apiKey)) {
            controller = ControllerHttpClient.withSignatureKey(URI.create(endpoint), apiKey, id);
        }
        else if (apiKeyPath.isPresent()) {
            controller = isNullOrBlank(apiCertificateFile)
                    ? ControllerHttpClient.withSignatureKey(URI.create(endpoint), apiKeyPath.get(), id)
                    : ControllerHttpClient.withKeyAndCertificate(URI.create(endpoint), apiKeyPath.get(), Paths.get(apiCertificateFile));
        }
        else {
            throw new IllegalArgumentException("One of the properties 'apiKey' or 'apiKeyFile' is required.");
        }
    }

    private Optional<Path> apiKeyPath(String tenant) {
        if (!isNullOrBlank(apiKeyFile)) return Optional.of(Paths.get(apiKeyFile));

        Path cliApiKeyFile = Optional.ofNullable(System.getenv("VESPA_CLI_HOME"))
                                     .map(Paths::get)
                                     .orElseGet(() -> Paths.get(System.getProperty("user.home"), ".vespa"))
                                     .resolve(tenant + ".api-key.pem");
        if (Files.exists(cliApiKeyFile)) return Optional.of(cliApiKeyFile);

        return Optional.empty();
    }

    protected String projectPathOf(String first, String... rest) {
        return project.getBasedir().toPath().resolve(Path.of(first, rest)).toString();
    }

    /** Returns the first of the given strings which is non-null and non-blank, or throws IllegalArgumentException. */
    protected static Optional<String> firstNonBlank(String... values) {
        for (String value : values)
            if (value != null && ! value.isBlank())
                return Optional.of(value);

        return Optional.empty();
    }

    protected static Optional<String> optionalOf(String value) {
        return Optional.ofNullable(value)
                       .filter(data -> ! data.isBlank());
    }

    protected static <T> Optional<T> optionalOf(String value, Function<String, T> mapper) {
        return Optional.ofNullable(value)
                       .filter(data -> ! data.isBlank())
                       .map(mapper);
    }

    protected static boolean isNullOrBlank(String value) {
        return Optional.ofNullable(value)
                .filter(s -> !s.isBlank())
                .isEmpty();
    }

}