aboutsummaryrefslogtreecommitdiffstats
path: root/memfilepersistence/src/tests/spi/memfiletestutils.h
blob: 450d87451b90b425278e079726e3b4887fc1e30f (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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * \class storage::memfile::MemFileTestUtils
 * \ingroup memfile
 *
 * \brief Utilities for unit tests of the MemFile layer.
 *
 * The memfile layer typically needs a MemFileEnvironment object that must be
 * set up. This class creates such an object to be used by unit tests. Other
 * utilities useful for only MemFile testing can be added here too.
 */

#pragma once

#include <vespa/memfilepersistence/memfile/memfilecache.h>
#include <tests/helper/testhelper.h>
#include <vespa/persistence/spi/persistenceprovider.h>
#include <vespa/memfilepersistence/spi/memfilepersistenceprovider.h>
#include <vespa/document/base/testdocman.h>
#include <vespa/document/update/documentupdate.h>
#include <vespa/storageframework/defaultimplementation/clock/realclock.h>
#include <vespa/storageframework/defaultimplementation/component/componentregisterimpl.h>

namespace storage {
namespace memfile {

struct FakeClock : public framework::Clock {
public:
    typedef std::unique_ptr<FakeClock> UP;

    framework::MicroSecTime _absoluteTime;

    FakeClock() {}

    virtual void addSecondsToTime(uint32_t nr) {
        _absoluteTime += framework::MicroSecTime(nr * uint64_t(1000000));
    }

    framework::MicroSecTime getTimeInMicros() const override {
        return _absoluteTime;
    }
    framework::MilliSecTime getTimeInMillis() const override {
        return getTimeInMicros().getMillis();
    }
    framework::SecondTime getTimeInSeconds() const override {
        return getTimeInMicros().getSeconds();
    }
    framework::MonotonicTimePoint getMonotonicTime() const override {
        return framework::MonotonicTimePoint(std::chrono::microseconds(
                getTimeInMicros().getTime()));
    }
};

struct MemFileTestEnvironment {
    MemFileTestEnvironment(uint32_t numDisks,
                           framework::ComponentRegister& reg,
                           const document::DocumentTypeRepo& repo);

    vdstestlib::DirConfig _config;
    MemFilePersistenceProvider _provider;
};

class MemFileTestUtils : public Types, public document::TestDocMan, public CppUnit::TestFixture {
private:
        // This variables are kept in test class. Instances that needs to be
        // unique per test needs to be setup in setupDisks and cleared in
        // tearDown
    document::BucketIdFactory _bucketIdFactory;
    framework::defaultimplementation::ComponentRegisterImpl::UP _componentRegister;
    FakeClock::UP _clock;
    std::unique_ptr<MemFileTestEnvironment> _env;

public:
    MemFileTestUtils();
    virtual ~MemFileTestUtils();

    void setupDisks(uint32_t disks);

    void tearDown() override{
        _env.reset();
        _componentRegister.reset();
        _clock.reset();
    }

    std::string getMemFileStatus(const document::BucketId& id, uint32_t disk = 0);

    std::string getModifiedBuckets();

    /**
       Flushes all cached data to disk and updates the bucket database accordingly.
    */
    void flush();

    FakeClock& getFakeClock() { return *_clock; }

    spi::Result flush(const document::BucketId& id, uint16_t disk = 0);

    MemFilePersistenceProvider& getPersistenceProvider();

    MemFilePtr getMemFile(const document::BucketId& id, uint16_t disk = 0);

    Environment& env();

    MemFilePersistenceThreadMetrics& getMetrics();

    MemFileTestEnvironment& getEnv() { return *_env; }

    /**
       Performs a put to the given disk.
       Returns the document that was inserted.
    */
    document::Document::SP doPutOnDisk(
            uint16_t disk,
            uint32_t location,
            Timestamp timestamp,
            uint32_t minSize = 0,
            uint32_t maxSize = 128);

    document::Document::SP doPut(
            uint32_t location,
            Timestamp timestamp,
            uint32_t minSize = 0,
            uint32_t maxSize = 128)
        { return doPutOnDisk(0, location, timestamp, minSize, maxSize); }

    /**
       Performs a remove to the given disk.
       Returns the new doccount if document was removed, or -1 if not found.
    */
    bool doRemoveOnDisk(
            uint16_t disk,
            const document::BucketId& bid,
            const document::DocumentId& id,
            Timestamp timestamp,
            OperationHandler::RemoveType persistRemove);

    bool doRemove(
            const document::BucketId& bid,
            const document::DocumentId& id,
            Timestamp timestamp,
            OperationHandler::RemoveType persistRemove) {
        return doRemoveOnDisk(0, bid, id, timestamp, persistRemove);
    }

    bool doUnrevertableRemoveOnDisk(uint16_t disk,
                                    const document::BucketId& bid,
                                    const DocumentId& id,
                                    Timestamp timestamp);

    bool doUnrevertableRemove(const document::BucketId& bid,
                              const DocumentId& id,
                              Timestamp timestamp)
    {
        return doUnrevertableRemoveOnDisk(0, bid, id, timestamp);
    }

    virtual const document::BucketIdFactory& getBucketIdFactory() const
        { return _bucketIdFactory; }

    document::BucketIdFactory& getBucketIdFactory()
        { return _bucketIdFactory; }

    /**
     * Do a remove toward storage set up in test environment.
     *
     * @id Document to remove.
     * @disk If set, use this disk, otherwise lookup in bucket db.
     * @unrevertableRemove If set, instead of adding put, turn put to remove.
     * @usedBits Generate bucket to use from docid using this amount of bits.
     */
    void doRemove(const DocumentId& id, Timestamp, uint16_t disk,
                  bool unrevertableRemove = false, uint16_t usedBits = 16);

    spi::GetResult doGetOnDisk(
            uint16_t disk,
            const document::BucketId& bucketId,
            const document::DocumentId& docId,
            const document::FieldSet& fields);

    spi::GetResult doGet(
            const document::BucketId& bucketId,
            const document::DocumentId& docId,
            const document::FieldSet& fields)
        { return doGetOnDisk(0, bucketId, docId, fields); }

    document::DocumentUpdate::SP createBodyUpdate(
            const document::DocumentId& id,
            const document::FieldValue& updateValue);

    document::DocumentUpdate::SP createHeaderUpdate(
            const document::DocumentId& id,
            const document::FieldValue& updateValue);

    virtual const document::DocumentTypeRepo::SP getTypeRepo() const
    { return document::TestDocMan::getTypeRepoSP(); }

    /**
     * Do a put toward storage set up in test environment.
     *
     * @doc Document to put. Use TestDocMan to generate easily.
     * @disk If set, use this disk, otherwise lookup in bucket db.
     * @usedBits Generate bucket to use from docid using this amount of bits.
     */
    void doPut(const Document::SP& doc, Timestamp,
               uint16_t disk, uint16_t usedBits = 16);

    void doPut(const document::Document::SP& doc,
               document::BucketId bid,
               Timestamp time,
               uint16_t disk = 0);

    spi::UpdateResult doUpdate(document::BucketId bid,
                               const document::DocumentUpdate::SP& update,
                               Timestamp time,
                               uint16_t disk = 0);

    /**
     * Create a test bucket with various content representing most states a
     * bucket can represent. (Such that tests have a nice test bucket to use
     * that require operations to handle all the various bucket contents.
     *
     * @disk If set, use this disk, otherwise lookup in bucket db.
     */
    void createTestBucket(const BucketId&, uint16_t disk = 0xffff);

    /**
     * In-place modify doc so that it has no more body fields.
     */
    void clearBody(document::Document& doc);

    /**
     * Copy all header data from src into dest, replacing any
     * header fields it may already have there. NOTE: this will
     * also overwrite document ID, type etc!
     */
    void copyHeader(document::Document& dest,
                    const document::Document& src);

    /**
     * Copy all body data from src into dest, replacing any
     * body fields it may already have there.
     */
    void copyBody(document::Document& dest,
                  const document::Document& src);

    std::string stringifyFields(const Document& doc) const;

    struct IoErrors {
        int _afterReads;
        int _afterWrites;

        IoErrors()
            : _afterReads(0),
              _afterWrites(0)
        {
        }

        IoErrors& afterReads(int n) {
            _afterReads = n;
            return *this;
        }

        IoErrors& afterWrites(int n) {
            _afterWrites = n;
            return *this;
        }
    };

    /**
     * Replaces internal LazyFile factory so that it produces LazyFile
     * implementations that trigger I/O exceptions on read/write. Optionally,
     * can supply a parameter setting explicit bounds on how many operations
     * are allowed on a file before trigging exceptions from there on out. A
     * bound of -1 in practice means "don't fail ever" while 0 means "fail the
     * next op of that type".
     */
    void simulateIoErrorsForSubsequentlyOpenedFiles(
            const IoErrors& errs = IoErrors());

    /**
     * Replace internal LazyFile factory with the default, non-failing impl.
     */
    void unSimulateIoErrorsForSubsequentlyOpenedFiles();
};

class SingleDiskMemFileTestUtils : public MemFileTestUtils
{
public:
    void setUp() override {
        setupDisks(1);
    }
};

} // memfile
} // storage