aboutsummaryrefslogtreecommitdiffstats
path: root/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/CliArguments.java
blob: 9c8e156b824f0f12f7ab03bfdb8e62e79b2d82bd (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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;

/**
 * Parses command line arguments
 *
 * @author bjorncs
 */
class CliArguments {

    private static final Options optionsDefinition = createOptions();

    private static final String BENCHMARK_OPTION = "benchmark";
    private static final String CA_CERTIFICATES_OPTION = "ca-certificates";
    private static final String CERTIFICATE_OPTION = "certificate";
    private static final String CONNECTIONS_OPTION = "connections";
    private static final String DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION = "disable-ssl-hostname-verification";
    private static final String ENDPOINT_OPTION = "endpoint";
    private static final String FILE_OPTION = "file";
    private static final String HEADER_OPTION = "header";
    private static final String HELP_OPTION = "help";
    private static final String MAX_STREAMS_PER_CONNECTION = "max-streams-per-connection";
    private static final String PRIVATE_KEY_OPTION = "private-key";
    private static final String ROUTE_OPTION = "route";
    private static final String TIMEOUT_OPTION = "timeout";
    private static final String TRACE_OPTION = "trace";
    private static final String VERSION_OPTION = "version";

    private final CommandLine arguments;

    private CliArguments(CommandLine arguments) throws CliArgumentsException {
        validateArgumentCombination(arguments);
        this.arguments = arguments;
    }

    static CliArguments fromRawArgs(String[] rawArgs) throws CliArgumentsException {
        CommandLineParser parser = new DefaultParser();
        try {
            return new CliArguments(parser.parse(optionsDefinition, rawArgs));
        } catch (ParseException e) {
            throw new CliArgumentsException(e);
        }
    }

    private static void validateArgumentCombination(CommandLine args) throws CliArgumentsException {
        if (!args.hasOption(HELP_OPTION) && !args.hasOption(VERSION_OPTION)) {
            if (!args.hasOption(ENDPOINT_OPTION)) {
                throw new CliArgumentsException("Endpoint must be specified");
            }
            if (!args.hasOption(FILE_OPTION)) {
                throw new CliArgumentsException("Feed file must be specified");
            }
            if (args.hasOption(CERTIFICATE_OPTION) != args.hasOption(PRIVATE_KEY_OPTION)) {
                throw new CliArgumentsException(
                        String.format("Both '%s' and '%s' must be specified together", CERTIFICATE_OPTION, PRIVATE_KEY_OPTION));
            }
        } else if (args.hasOption(HELP_OPTION) && args.hasOption(VERSION_OPTION)) {
            throw new CliArgumentsException(String.format("Cannot specify both '%s' and '%s'", HELP_OPTION, VERSION_OPTION));
        }
    }

    URI endpoint() throws CliArgumentsException {
        try {
            return ((URL) arguments.getParsedOptionValue(ENDPOINT_OPTION)).toURI();
        } catch (ParseException | URISyntaxException e) {
            throw new CliArgumentsException("Invalid endpoint: " + e.getMessage(), e);
        }
    }

    boolean helpSpecified() { return has(HELP_OPTION); }

    boolean versionSpecified() { return has(VERSION_OPTION); }

    OptionalInt connections() throws CliArgumentsException {  return intValue(CONNECTIONS_OPTION); }

    OptionalInt maxStreamsPerConnection() throws CliArgumentsException { return intValue(MAX_STREAMS_PER_CONNECTION); }

    Optional<CertificateAndKey> certificateAndKey() throws CliArgumentsException {
        Path certificateFile = fileValue(CERTIFICATE_OPTION).orElse(null);
        Path privateKeyFile = fileValue(PRIVATE_KEY_OPTION).orElse(null);
        if (privateKeyFile == null && certificateFile == null) return Optional.empty();
        return Optional.of(new CertificateAndKey(certificateFile, privateKeyFile));
    }

    Optional<Path> caCertificates() throws CliArgumentsException { return fileValue(CA_CERTIFICATES_OPTION); }

    Path inputFile() throws CliArgumentsException {  return fileValue(FILE_OPTION).get(); }

    Map<String, String> headers() throws CliArgumentsException {
        String[] rawArguments = arguments.getOptionValues(HEADER_OPTION);
        if (rawArguments == null) return Collections.emptyMap();
        Map<String, String> headers = new HashMap<>();
        for (String rawArgument : rawArguments) {
            if (rawArgument.startsWith("\"") || rawArgument.startsWith("'")) {
                rawArgument = rawArgument.substring(1);
            }
            if (rawArgument.endsWith("\"") || rawArgument.endsWith("'")) {
                rawArgument = rawArgument.substring(0, rawArgument.length() - 1);
            }
            int colonIndex = rawArgument.indexOf(':');
            if (colonIndex == -1) throw new CliArgumentsException("Invalid header: '" + rawArgument + "'");
            headers.put(rawArgument.substring(0, colonIndex), rawArgument.substring(colonIndex + 1).trim());
        }
        return Collections.unmodifiableMap(headers);
    }

    boolean sslHostnameVerificationDisabled() { return has(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION); }

    boolean benchmarkModeEnabled() { return has(BENCHMARK_OPTION); }

    Optional<String> route() { return stringValue(ROUTE_OPTION); }

    OptionalInt traceLevel() throws CliArgumentsException { return intValue(TRACE_OPTION); }

    Optional<Duration> timeout() throws CliArgumentsException {
        OptionalDouble timeout = doubleValue(TIMEOUT_OPTION);
        return timeout.isPresent()
                ? Optional.of(Duration.ofMillis((long)(timeout.getAsDouble()*1000)))
                : Optional.empty();
    }

    private OptionalInt intValue(String option) throws CliArgumentsException {
        try {
            Number number = (Number) arguments.getParsedOptionValue(option);
            return number != null ? OptionalInt.of(number.intValue()) : OptionalInt.empty();
        } catch (ParseException e) {
            throw newInvalidValueException(option, e);
        }
    }

    private Optional<Path> fileValue(String option) throws CliArgumentsException {
        try {
            File certificateFile = (File) arguments.getParsedOptionValue(option);
            if (certificateFile == null) return Optional.empty();
            return Optional.of(certificateFile.toPath());
        } catch (ParseException e) {
            throw newInvalidValueException(option, e);
        }
    }

    private Optional<String> stringValue(String option) { return Optional.ofNullable(arguments.getOptionValue(option)); }

    private OptionalDouble doubleValue(String option) throws CliArgumentsException {
        try {
            Number number = (Number) arguments.getParsedOptionValue(option);
            return number != null ? OptionalDouble.of(number.doubleValue()) : OptionalDouble.empty();
        } catch (ParseException e) {
            throw newInvalidValueException(option, e);
        }
    }

    private boolean has(String option) { return arguments.hasOption(option); }

    private static CliArgumentsException newInvalidValueException(String option, ParseException cause) {
        return new CliArgumentsException(String.format("Invalid value for '%s': %s", option, cause.getMessage()), cause);
    }

    private static Options createOptions() {
        // TODO Add description to each option
        return new Options()
                .addOption(Option.builder()
                        .longOpt(HELP_OPTION)
                        .build())
                .addOption(Option.builder()
                        .longOpt(VERSION_OPTION)
                        .build())
                .addOption(Option.builder()
                        .longOpt(ENDPOINT_OPTION)
                        .hasArg()
                        .type(URL.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(HEADER_OPTION)
                        .hasArgs()
                        .build())
                .addOption(Option.builder()
                        .longOpt(FILE_OPTION)
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(CONNECTIONS_OPTION)
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(MAX_STREAMS_PER_CONNECTION)
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(CERTIFICATE_OPTION)
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(PRIVATE_KEY_OPTION)
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(CA_CERTIFICATES_OPTION)
                        .type(File.class)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION)
                        .build())
                .addOption(Option.builder()
                        .longOpt(BENCHMARK_OPTION)
                        .build())
                .addOption(Option.builder()
                        .longOpt(ROUTE_OPTION)
                        .hasArg()
                        .build())
                .addOption(Option.builder()
                        .longOpt(TIMEOUT_OPTION)
                        .hasArg()
                        .type(Number.class)
                        .build())
                .addOption(Option.builder()
                        .longOpt(TRACE_OPTION)
                        .hasArg()
                        .type(Number.class)
                        .build());
    }

    void printHelp(OutputStream out) {
        HelpFormatter formatter = new HelpFormatter();
        PrintWriter writer = new PrintWriter(out);
        formatter.printHelp(
                writer,
                formatter.getWidth(),
                "vespa-feed-client <options>",
                "Vespa feed client",
                optionsDefinition,
                formatter.getLeftPadding(),
                formatter.getDescPadding(),
                "");
        writer.flush();
    }

    static class CliArgumentsException extends Exception {
        CliArgumentsException(String message, Throwable cause) { super(message, cause); }
        CliArgumentsException(Throwable cause) { super(cause.getMessage(), cause); }
        CliArgumentsException(String message) { super(message); }
    }

    static class CertificateAndKey {
        final Path certificateFile;
        final Path privateKeyFile;

        CertificateAndKey(Path certificateFile, Path privateKeyFile) {
            this.certificateFile = certificateFile;
            this.privateKeyFile = privateKeyFile;
        }
    }

}