aboutsummaryrefslogtreecommitdiffstats
path: root/searchcore/src/apps/vespa-dump-feed/vespa-dump-feed.cpp
blob: 985747529296720e0835f876cc2f72ad576d760f (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/config/print/fileconfigwriter.h>
#include <vespa/document/config/config-documenttypes.h>
#include <vespa/document/repo/documenttyperepo.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/documentapi/documentapi.h>
#include <vespa/messagebus/destinationsession.h>
#include <vespa/messagebus/rpcmessagebus.h>
#include <vespa/messagebus/network/rpcnetworkparams.h>
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/util/signalhandler.h>
#include <vespa/vespalib/process/process.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/config/common/exceptions.h>
#include <vespa/config/helper/configgetter.hpp>
#include <vespa/vespalib/util/signalhandler.h>

typedef vespalib::SignalHandler SIG;

//-----------------------------------------------------------------------------

class OutputFile
{
private:
    FILE *file;

public:
    OutputFile(const std::string &name)
        : file(fopen(name.c_str(), "w")) {}
    bool valid() const { return (file != 0); }
    void write(const char *data, size_t length) {
        size_t res = fwrite(data, 1, length, file);
        assert(res == length);
        (void) res;
    }
    ~OutputFile() { fclose(file); }
};

//-----------------------------------------------------------------------------

class FeedHandler : public mbus::IMessageHandler
{
private:
    mbus::RPCMessageBus          _mbus;
    mbus::DestinationSession::UP _session;
    OutputFile                  &_idx;
    OutputFile                  &_dat;
    size_t                       _numDocs;

    void handleDocumentPut(const document::Document::SP & doc);
    virtual void handleMessage(mbus::Message::UP message) override;

public:
    FeedHandler(std::shared_ptr<const document::DocumentTypeRepo> repo, OutputFile &idx, OutputFile &dat);
    std::string getRoute() { return _session->getConnectionSpec(); }
    virtual ~FeedHandler();
};

void
FeedHandler::handleDocumentPut(const document::Document::SP & doc)
{
    if (doc) {
        vespalib::nbostream datStream(12345);
        vespalib::nbostream idxStream(12);
        doc->serialize(datStream);
        idxStream << uint64_t(datStream.size());
        _dat.write(datStream.peek(), datStream.size());
        _idx.write(idxStream.peek(), idxStream.size());
        ++_numDocs;
    }
}

void
FeedHandler::handleMessage(mbus::Message::UP message)
{
    mbus::Reply::UP reply;
    documentapi::DocumentMessage::UP msg((documentapi::DocumentMessage*)message.release());
    switch (msg->getType()) {
    case documentapi::DocumentProtocol::MESSAGE_PUTDOCUMENT:
    handleDocumentPut(((documentapi::PutDocumentMessage&)(*msg)).getDocumentSP());
    break;
    default:
    break;
    }
    reply = msg->createReply(); // use default reply for all messages
    msg->swapState(*reply);
    _session->reply(std::move(reply)); // handle all messages synchronously
}

FeedHandler::FeedHandler(std::shared_ptr<const document::DocumentTypeRepo> repo, OutputFile &idx, OutputFile &dat)
    : _mbus(mbus::MessageBusParams().addProtocol(std::make_shared<documentapi::DocumentProtocol>(repo)),
            mbus::RPCNetworkParams()),
      _session(_mbus.getMessageBus()
               .createDestinationSession(mbus::DestinationSessionParams()
                                         .setBroadcastName(false)
                                         .setMessageHandler(*this)
                                         .setName("dump-feed"))),
      _idx(idx),
      _dat(dat),
      _numDocs()
{
}

FeedHandler::~FeedHandler()
{
    _session.reset();
    fprintf(stderr, "%zu document puts dumped to disk\n", _numDocs);
}

//-----------------------------------------------------------------------------

class App
{
public:
    int main(int argc, char **argv);
};

template <typename CFG>
bool writeConfig(std::unique_ptr<CFG> cfg, const std::string &dirName) {
    if (cfg.get() == 0) {
        return false;
    }
    std::string fileName = dirName + "/" + CFG::CONFIG_DEF_NAME + ".cfg";
    try {
        config::FileConfigWriter w(fileName);
        return w.write(*cfg);
    } catch (config::ConfigWriteException & e) {
        fprintf(stderr, "Unable to write config to disk: %s\n", e.what());
    }
    return false;
}

template <typename CFG>
std::unique_ptr<CFG> getConfig() {
    std::unique_ptr<CFG> ret(config::ConfigGetter<CFG>::getConfig("client"));
    if (ret.get() == 0) {
        fprintf(stderr, "error: could not obtain config (%s)\n", CFG::CONFIG_DEF_NAME.c_str());
    }
    return ret;
}

std::shared_ptr<const document::DocumentTypeRepo> getRepo() {
    typedef document::config::DocumenttypesConfig DCFG;
    std::unique_ptr<DCFG> dcfg = getConfig<DCFG>();
    std::shared_ptr<const document::DocumentTypeRepo> ret;
    if (dcfg.get() != 0) {
        ret.reset(new document::DocumentTypeRepo(*dcfg));
    }
    return ret;
}

void setupSignals() {
    SIG::PIPE.ignore();
}

int usage() {
    fprintf(stderr, "Usage: vespa-dump-feed <input-feed> <output-directory>\n\n");
    fprintf(stderr, "  Takes an XML vespa feed as input and dumps its contents as serialized documents.\n");
    fprintf(stderr, "  In addition to the actual documents, an index file containing document sizes\n");
    fprintf(stderr, "  and the appropriate config file(s) needed for deserialization are also stored.\n");
    fprintf(stderr, "  This utility can be run anywhere vespa-feeder can be run with default config id.\n");
    return 1;
}

int
App::main(int argc, char **argv)
{
    setupSignals();
    if (argc != 3) {
        return usage();
    }
    std::string feedFile = argv[1];
    std::string dirName = argv[2];
    fprintf(stderr, "input feed: %s\n", feedFile.c_str());
    fprintf(stderr, "output directory: %s\n", dirName.c_str());
    vespalib::mkdir(dirName);
    typedef document::config::DocumenttypesConfig DCFG;
    if (!writeConfig(getConfig<DCFG>(), dirName)) {
        fprintf(stderr, "error: could not save config to disk\n");
        return 1;
    }
    std::shared_ptr<const document::DocumentTypeRepo> repo = getRepo();
    if (repo.get() == 0) {
        fprintf(stderr, "error: could not create document type repo\n");
        return 1;
    }
    {
        OutputFile idxFile(dirName + "/doc.idx");
        OutputFile datFile(dirName + "/doc.dat");
        if (!idxFile.valid() || !datFile.valid()) {
            fprintf(stderr, "error: could not open output document files\n");
            return 1;
        }
        FeedHandler feedHooks(repo, idxFile, datFile);
        std::string route = feedHooks.getRoute();
        fprintf(stderr, "route to self: %s\n", route.c_str());
        std::string feedCmd(vespalib::make_string("vespa-feeder --route \"%s\" %s",
                                                  route.c_str(), feedFile.c_str()));
        fprintf(stderr, "running feed command: %s\n", feedCmd.c_str());
        vespalib::string feederOutput;
        bool feedingOk = vespalib::Process::run(feedCmd, feederOutput);
        if (!feedingOk) {
            fprintf(stderr, "error: feed command failed\n");
            fprintf(stderr, "feed command output:\n-----\n%s\n-----\n", feederOutput.c_str());
            return 1;
        }
    }
    return 0;
}

//-----------------------------------------------------------------------------

int main(int argc, char **argv) {
    App app;
    return app.main(argc, argv);
}