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

import com.yahoo.document.Document;
import com.yahoo.document.DocumentId;
import com.yahoo.document.json.JsonWriter;
import com.yahoo.documentapi.SyncParameters;
import com.yahoo.documentapi.messagebus.MessageBusDocumentAccess;
import com.yahoo.documentapi.messagebus.MessageBusParams;
import com.yahoo.documentapi.messagebus.MessageBusSyncSession;
import com.yahoo.documentapi.messagebus.protocol.GetDocumentMessage;
import com.yahoo.documentapi.messagebus.protocol.GetDocumentReply;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.Reply;
import com.yahoo.messagebus.Trace;
import com.yahoo.text.Utf8;
import com.yahoo.vespaclient.ClusterDef;
import com.yahoo.vespaclient.ClusterList;

import java.util.Iterator;

/**
 * The document retriever is responsible for retrieving documents using the Document API and printing the result to standard out.
 *
 * @author bjorncs
 */
@SuppressWarnings("removal") // TODO: Remove on Vespa 9
public class DocumentRetriever {

    private final ClusterList clusterList;
    private final DocumentAccessFactory documentAccessFactory;
    private final ClientParameters params;

    private MessageBusSyncSession session;
    private MessageBusDocumentAccess documentAccess;

    public DocumentRetriever(ClusterList clusterList,
                             DocumentAccessFactory documentAccessFactory,
                             ClientParameters params) {
        this.clusterList = clusterList;
        this.documentAccessFactory = documentAccessFactory;
        this.params = params;
    }

    public void shutdown() {
        try {
            if (session != null) {
                session.destroy();
            }
        } catch (IllegalStateException e) {
            // Ignore exception on shutdown
        }
        try {
            if (documentAccess != null) {
                documentAccess.shutdown();
            }
        } catch (IllegalStateException e) {
            // Ignore exception on shutdown
        }
    }

    public void retrieveDocuments() throws DocumentRetrieverException {
        boolean first = true;
        String route = params.cluster.isEmpty() ? params.route : resolveClusterRoute(params.cluster);

        MessageBusParams messageBusParams = createMessageBusParams(params.configId, params.timeout, route);
        documentAccess = documentAccessFactory.createDocumentAccess(messageBusParams);
        session = documentAccess.createSyncSession(new SyncParameters.Builder().build());
        int trace = params.traceLevel;
        if (trace > 0) {
            session.setTraceLevel(trace);
        }

        Iterator<String> iter = params.documentIds;
        if (params.jsonOutput && !params.printIdsOnly) {
            System.out.println('[');
        }
        while (iter.hasNext()) {
            if (params.jsonOutput && !params.printIdsOnly) {
                if (!first) {
                    System.out.println(',');
                } else {
                    first = false;
                }
            }
            String docid = iter.next();
            Message msg = createDocumentRequest(docid);
            Reply reply = session.syncSend(msg);
            printReply(reply);
        }
        if (params.jsonOutput && !params.printIdsOnly) {
            System.out.println(']');
        }
    }

    private String resolveClusterRoute(String clusterName) throws DocumentRetrieverException {
        if (clusterList.getStorageClusters().isEmpty()) {
            throw new DocumentRetrieverException("The Vespa cluster does not have any content clusters declared.");
        }

        ClusterDef clusterDef = null;
        for (ClusterDef c : clusterList.getStorageClusters()) {
            if (c.getName().equals(clusterName)) {
                clusterDef = c;
            }
        }
        if (clusterDef == null) {
            String names = createClusterNamesString();
            throw new DocumentRetrieverException(String.format(
                    "The Vespa cluster contains the content clusters %s, not %s. Please select a valid vespa cluster.",
                    names, clusterName));
        }
        return clusterDef.getRoute();
    }

    private MessageBusParams createMessageBusParams(String configId, double timeout, String route) {
        MessageBusParams messageBusParams = new MessageBusParams();
        messageBusParams.setRoute(route);
        messageBusParams.setProtocolConfigId(configId);
        messageBusParams.setRoutingConfigId(configId);
        messageBusParams.setDocumentManagerConfigId(configId);

        if (timeout > 0) {
            messageBusParams.getSourceSessionParams().setTimeout(timeout);
        }
        return messageBusParams;
    }

    private Message createDocumentRequest(String docid) {
        GetDocumentMessage msg = new GetDocumentMessage(new DocumentId(docid), params.fieldSet);
        msg.setPriority(params.priority); // TODO: Remove on Vespa 9
        msg.setRetryEnabled(!params.noRetry);
        return msg;
    }

    @SuppressWarnings("deprecation")
    private void printReply(Reply reply) {
        Trace trace = reply.getTrace();
        if (!trace.getRoot().isEmpty()) {
            System.out.println(trace);
        }

        if (reply.hasErrors()) {
            System.err.print("Request failed: ");
            for (int i = 0; i < reply.getNumErrors(); i++) {
                System.err.printf("\n  %s", reply.getError(i));
            }
            System.err.println();
            return;
        }

        if (!(reply instanceof GetDocumentReply)) {
            System.err.printf("Unexpected reply %s: '%s'\n", reply.getType(), reply.toString());
            return;
        }

        GetDocumentReply documentReply = (GetDocumentReply) reply;
        Document document = documentReply.getDocument();

        if (document == null) {
            System.out.println("Document not found.");
            return;
        }

        if (params.showDocSize) {
            System.out.printf("Document size: %d bytes.\n", document.getSerializedSize());
        }
        if (params.printIdsOnly) {
            System.out.println(document.getId());
        } else {
            if (params.jsonOutput) {
                System.out.print(Utf8.toString(JsonWriter.toByteArray(document, params.tensorShortForm, params.tensorDirectValues)));
            } else {
                System.out.print(document.toXML("  "));
            }
        }
    }

    private String createClusterNamesString() {
        StringBuilder names = new StringBuilder();
        for (ClusterDef c : clusterList.getStorageClusters()) {
            if (names.length() > 0) {
                names.append(", ");
            }
            names.append(c.getName());
        }
        return names.toString();
    }
}