aboutsummaryrefslogtreecommitdiffstats
path: root/vespaclient-java/src/main/java/com/yahoo/vespavisit/VdsVisitTarget.java
blob: 7dfa3a2cf2ed34d7a8e661f131e4c59bd8b701ee (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespavisit;

import com.yahoo.documentapi.DocumentAccess;
import com.yahoo.documentapi.VisitorControlHandler;
import com.yahoo.documentapi.VisitorDataHandler;
import com.yahoo.documentapi.VisitorDestinationParameters;
import com.yahoo.documentapi.VisitorDestinationSession;
import com.yahoo.documentapi.messagebus.MessageBusDocumentAccess;
import com.yahoo.documentapi.messagebus.MessageBusParams;
import java.util.logging.Level;
import com.yahoo.log.LogSetup;
import com.yahoo.messagebus.network.Identity;
import com.yahoo.net.HostName;
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.lang.reflect.Constructor;
import java.util.logging.Logger;

/**
 * Example client using visiting
 *
 * @author Einar M R Rosenvinge
 */
public class VdsVisitTarget {

    private static final Logger log = Logger.getLogger(VdsVisitTarget.class.getName());

    private boolean printIds = false;
    DocumentAccess access;
    VisitorDestinationSession session;
    String slobrokAddress = null;
    int port = -1;
    private boolean verbose = false;
    private int processTime = 0;
    private String handlerClassName = StdOutVisitorHandler.class.getName();
    private String[] handlerArgs = null;

    public boolean isPrintIds() {
        return printIds;
    }

    public String getSlobrokAddress() {
        return slobrokAddress;
    }

    public boolean isVerbose() {
        return verbose;
    }

    public int getPort() {
        return port;
    }

    public int getProcessTime() {
        return processTime;
    }

    public String getHandlerClassName() {
        return handlerClassName;
    }

    public String[] getHandlerArgs() {
        return handlerArgs;
    }

    public static void main(String args[]) {
        LogSetup.initVespaLogging("vespa-visit-target");
        VdsVisitTarget visitTarget = new VdsVisitTarget();


        try {
            visitTarget.parseArguments(args);
            visitTarget.initShutdownHook();
            visitTarget.run();
            System.exit(0);
        } catch (HelpShownException e) {
            System.exit(0);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (org.apache.commons.cli.ParseException e) {
            System.err.println("Failed to parse arguments. Try --help for syntax. " + e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Options createOptions() {
        Options options = new Options();

        options.addOption("h", "help", false, "Show this syntax page.");

        options.addOption(Option.builder("s")
                .longOpt("bindtoslobrok")
                .hasArg(true)
                .argName("address")
                .desc("Bind to the given slobrok address.")
                .build());

        options.addOption(Option.builder("t")
                .longOpt("bindtosocket")
                .hasArg(true)
                .argName("port")
                .desc("Bind to the given TCP port")
                .type(Number.class)
                .build());

        options.addOption(Option.builder("p")
                .longOpt("processtime")
                .hasArg(true)
                .argName("msecs")
                .desc("Sleep this amount of millisecs before processing message. (Debug option for pretending to be slow client).")
                .type(Number.class)
                .build());

        options.addOption(Option.builder("c")
                .longOpt("visithandler")
                .hasArg(true)
                .argName("classname")
                .desc("Use the given class as a visit handler (defaults to StdOutVisitorHandler)")
                .build());

        options.addOption(Option.builder("o")
                .longOpt("visitoptions")
                .hasArg(true)
                .argName("args")
                .desc("Option arguments to pass through to the visitor handler instance")
                .build());

        options.addOption("i", "printids", false, "Display only document identifiers.");
        options.addOption("v", "verbose", false, "Indent XML, show progress and info on STDERR.");

        return options;
    }

    private void printSyntax(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("vespa-visit-target <options>", "Retrieve results from a visitor", options ,
                            "One, and only one, of the binding options must be present.\n" +
                            "\n" +
                            "For more detailed information, such as defaults and format of\n" +
                            "arguments, refer to 'man vespa-visit-target'.\n");
    }

    class HelpShownException extends Exception {}

    void parseArguments(String args[]) throws ParseException, HelpShownException {
        Options options = createOptions();

        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("h")) {
            printSyntax(options);
            throw new HelpShownException();
        }
        if (line.hasOption("s")) {
            slobrokAddress = line.getOptionValue("s");
        }
        if (line.hasOption("t")) {
            port = ((Number) line.getParsedOptionValue("t")).intValue();
        }
        if (line.hasOption("i")) {
            printIds = true;
        }
        if (line.hasOption("p")) {
            processTime = ((Number) line.getParsedOptionValue("p")).intValue();
        }
        if (line.hasOption("v")) {
            verbose = true;
        }
        if (line.hasOption("c")) {
            handlerClassName = line.getOptionValue("c");
        }
        if (line.hasOption("o")) {
            handlerArgs = line.getOptionValue("o").split(" ");
        }

        if (!(slobrokAddress == null ^ port == -1)) {
            throw new IllegalArgumentException("You must specify one, and only one, binding option");
        }
        if (port != -1 && port < 0 || port > 65535) {
            throw new IllegalArgumentException("The port must be in the range 0-65535");
        }
        if (verbose) {
            if (port != -1) {
                System.err.println("Binding to socket " + getTcpAddress());
            } else {
                System.err.println("Binding to slobrok address: " + slobrokAddress + "/visit-destination");
            }
        }
    }

    private String getTcpAddress() {
        String hostname = HostName.getLocalhost();
        return "tcp/" + hostname + ":" + port + "/visit-destination";
    }

    @SuppressWarnings("unchecked")
    public void run() throws Exception {
        initShutdownHook();
        log.log(Level.FINE, "Starting VdsVisitTarget");
        MessageBusParams mbusParams = new MessageBusParams();
        mbusParams.getRPCNetworkParams().setIdentity(new Identity(slobrokAddress));

        if (port > 0) {
            mbusParams.getRPCNetworkParams().setListenPort(port);
        }

        access = new MessageBusDocumentAccess(mbusParams);

        VdsVisitHandler handler;

        Class<?> cls = Thread.currentThread().getContextClassLoader()
                .loadClass(handlerClassName);
        try {
            // Any custom data handlers may have a constructor that takes in args,
            // so that the user can pass cmd line options to them
            Class<?>[] consTypes = new Class<?>[] { boolean.class, boolean.class,
                    boolean.class, boolean.class, boolean.class,
                    boolean.class, int.class, String[].class };
            Constructor<?> cons = cls.getConstructor(consTypes);
            handler = (VdsVisitHandler)cons.newInstance(
                    printIds, verbose, verbose, verbose, false, false,
                    processTime, handlerArgs);
        } catch (NoSuchMethodException e) {
            // Retry, this time matching the StdOutVisitorHandler constructor
            // arg list
            Class<?>[] consTypes = new Class<?>[] { boolean.class, boolean.class,
                    boolean.class, boolean.class, boolean.class,
                    boolean.class, int.class, boolean.class };
            Constructor<?> cons = cls.getConstructor(consTypes);
            handler = (VdsVisitHandler)cons.newInstance(
                    printIds, verbose, verbose, verbose, false, false, processTime, false);
        }

        VisitorDataHandler dataHandler = handler.getDataHandler();
        VisitorControlHandler controlHandler = handler.getControlHandler();

        VisitorDestinationParameters params = new VisitorDestinationParameters(
                "visit-destination", dataHandler);
        session = access.createVisitorDestinationSession(params);
        while (!controlHandler.isDone()) {
            Thread.sleep(1000);
        }
    }

    private void initShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new CleanUpThread());
    }

    class CleanUpThread extends Thread {
        public void run() {
            try {
                if (session != null) {
                    session.destroy();
                }
            } catch (IllegalStateException ise) {
                //ignore this
            }
            try {
                if (access != null) {
                    access.shutdown();
                }
            } catch (IllegalStateException ise) {
                //ignore this too
            }
        }
    }

}