summaryrefslogtreecommitdiff
path: root/src/mongo/s/write_ops/batched_command_request.cpp
blob: 70bfd38327f383fce69ef9cfcbec6c368121bac2 (plain)
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/**
 *    Copyright (C) 2013 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

#include "mongo/s/write_ops/batched_command_request.h"

#include "mongo/bson/bsonobjiterator.h"
#include "mongo/db/namespace_string.h"

namespace mongo {

    using std::auto_ptr;
    using std::string;
    using std::vector;

    const size_t BatchedCommandRequest::kMaxWriteBatchSize = 1000;

    BatchedCommandRequest::BatchedCommandRequest( BatchType batchType ) :
            _batchType( batchType ) {
        switch ( getBatchType() ) {
        case BatchedCommandRequest::BatchType_Insert:
            _insertReq.reset( new BatchedInsertRequest );
            return;
        case BatchedCommandRequest::BatchType_Update:
            _updateReq.reset( new BatchedUpdateRequest );
            return;
        default:
            dassert( getBatchType() == BatchedCommandRequest::BatchType_Delete );
            _deleteReq.reset( new BatchedDeleteRequest );
            return;
        }
    }

// This macro just invokes a given method on one of the three types of ops with parameters
#define INVOKE(M,...) \
{\
    switch ( getBatchType() ) {\
    case BatchedCommandRequest::BatchType_Insert:\
        return _insertReq->M(__VA_ARGS__);\
    case BatchedCommandRequest::BatchType_Update:\
        return _updateReq->M(__VA_ARGS__);\
    default:\
        dassert( getBatchType() == BatchedCommandRequest::BatchType_Delete );\
        return _deleteReq->M(__VA_ARGS__);\
    }\
}

    BatchedCommandRequest::BatchType BatchedCommandRequest::getBatchType() const {
        return _batchType;
    }

    BatchedInsertRequest* BatchedCommandRequest::getInsertRequest() const {
        return _insertReq.get();
    }

    BatchedUpdateRequest* BatchedCommandRequest::getUpdateRequest() const {
        return _updateReq.get();
    }

    BatchedDeleteRequest* BatchedCommandRequest::getDeleteRequest() const {
        return _deleteReq.get();
    }

    bool BatchedCommandRequest::isInsertIndexRequest() const {
        if ( _batchType != BatchedCommandRequest::BatchType_Insert ) return false;
        return getNSS().isSystemDotIndexes();
    }

    static bool extractUniqueIndex( const BSONObj& indexDesc ) {
        return indexDesc["unique"].trueValue();
    }

    bool BatchedCommandRequest::isUniqueIndexRequest() const {
        if ( !isInsertIndexRequest() ) return false;
        return extractUniqueIndex( getInsertRequest()->getDocumentsAt( 0 ) );
    }

    bool BatchedCommandRequest::isValidIndexRequest( string* errMsg ) const {

        string dummy;
        if ( !errMsg )
            errMsg = &dummy;
        dassert( isInsertIndexRequest() );

        if ( sizeWriteOps() != 1 ) {
            *errMsg = "invalid batch request for index creation";
            return false;
        }

        const NamespaceString& targetNSS = getTargetingNSS();
        if ( !targetNSS.isValid() ) {
            *errMsg = targetNSS.ns() + " is not a valid namespace to index";
            return false;
        }

        const NamespaceString& reqNSS = getNSS();
        if ( reqNSS.db().compare( targetNSS.db() ) != 0 ) {
            *errMsg = targetNSS.ns() + " namespace is not in the request database "
                      + reqNSS.db().toString();
            return false;
        }

        return true;
    }

    string BatchedCommandRequest::getTargetingNS() const {
        return getTargetingNSS().toString();
    }

    const NamespaceString& BatchedCommandRequest::getTargetingNSS() const {
        if ( !isInsertIndexRequest() ) return getNSS();
        INVOKE(getTargetingNSS);
    }

    static BSONObj extractIndexKeyPattern( const BSONObj& indexDesc ) {
        return indexDesc["key"].Obj();
    }

    BSONObj BatchedCommandRequest::getIndexKeyPattern() const {
        dassert( isInsertIndexRequest() );
        return extractIndexKeyPattern( getInsertRequest()->getDocumentsAt( 0 ) );
    }

    bool BatchedCommandRequest::isVerboseWC() const {
        if ( !isWriteConcernSet() ) {
            return true;
        }

        BSONObj writeConcern = getWriteConcern();
        BSONElement wElem = writeConcern["w"];
        if ( !wElem.isNumber() || wElem.Number() != 0 ) {
            return true;
        }

        return false;
    }

    void BatchedCommandRequest::cloneTo( BatchedCommandRequest* other ) const {
        other->_insertReq.reset();
        other->_updateReq.reset();
        other->_deleteReq.reset();
        other->_batchType = _batchType;

        switch ( getBatchType() ) {
        case BatchedCommandRequest::BatchType_Insert:
            other->_insertReq.reset( new BatchedInsertRequest );
            _insertReq->cloneTo( other->_insertReq.get() );
            return;
        case BatchedCommandRequest::BatchType_Update:
            other->_updateReq.reset( new BatchedUpdateRequest );
            _updateReq->cloneTo( other->_updateReq.get() );
            return;
        default:
            dassert( getBatchType() == BatchedCommandRequest::BatchType_Delete );
            other->_deleteReq.reset( new BatchedDeleteRequest );
            _deleteReq->cloneTo( other->_deleteReq.get() );
            return;
        }
    }

    bool BatchedCommandRequest::isValid( std::string* errMsg ) const {
        INVOKE( isValid, errMsg );
    }

    BSONObj BatchedCommandRequest::toBSON() const {
        INVOKE( toBSON );
    }

    bool BatchedCommandRequest::parseBSON( const BSONObj& source, std::string* errMsg ) {
        INVOKE( parseBSON, source, errMsg );
    }

    void BatchedCommandRequest::clear() {
        INVOKE( clear );
    }

    std::string BatchedCommandRequest::toString() const {
        INVOKE( toString );
    }

    void BatchedCommandRequest::setNSS( const NamespaceString& nss ) {
        INVOKE( setCollNameNS, nss );
    }

    void BatchedCommandRequest::setNS( StringData collName ) {
        INVOKE( setCollName, collName );
    }

    const std::string& BatchedCommandRequest::getNS() const {
        INVOKE( getCollName );
    }

    const NamespaceString& BatchedCommandRequest::getNSS() const {
        INVOKE(getCollNameNS);
    }

    std::size_t BatchedCommandRequest::sizeWriteOps() const {
        switch ( getBatchType() ) {
        case BatchedCommandRequest::BatchType_Insert:
            return _insertReq->sizeDocuments();
        case BatchedCommandRequest::BatchType_Update:
            return _updateReq->sizeUpdates();
        default:
            return _deleteReq->sizeDeletes();
        }
    }

    void BatchedCommandRequest::setWriteConcern( const BSONObj& writeConcern ) {
        INVOKE( setWriteConcern, writeConcern );
    }

    void BatchedCommandRequest::unsetWriteConcern() {
        INVOKE( unsetWriteConcern );
    }

    bool BatchedCommandRequest::isWriteConcernSet() const {
        INVOKE( isWriteConcernSet );
    }

    const BSONObj& BatchedCommandRequest::getWriteConcern() const {
        INVOKE( getWriteConcern );
    }

    void BatchedCommandRequest::setOrdered( bool continueOnError ) {
        INVOKE( setOrdered, continueOnError );
    }

    void BatchedCommandRequest::unsetOrdered() {
        INVOKE( unsetOrdered );
    }

    bool BatchedCommandRequest::isOrderedSet() const {
        INVOKE( isOrderedSet );
    }

    bool BatchedCommandRequest::getOrdered() const {
        INVOKE( getOrdered );
    }

    void BatchedCommandRequest::setMetadata(BatchedRequestMetadata* metadata) {
        INVOKE( setMetadata, metadata );
    }

    void BatchedCommandRequest::unsetMetadata() {
        INVOKE( unsetMetadata );
    }

    bool BatchedCommandRequest::isMetadataSet() const {
        INVOKE( isMetadataSet );
    }

    BatchedRequestMetadata* BatchedCommandRequest::getMetadata() const {
        INVOKE( getMetadata );
    }

    /**
     * Generates a new request with insert _ids if required.  Otherwise returns NULL.
     */
    BatchedCommandRequest* //
    BatchedCommandRequest::cloneWithIds(const BatchedCommandRequest& origCmdRequest) {

        if (origCmdRequest.getBatchType() != BatchedCommandRequest::BatchType_Insert
            || origCmdRequest.isInsertIndexRequest())
            return NULL;

        auto_ptr<BatchedInsertRequest> idRequest;
        BatchedInsertRequest* origRequest = origCmdRequest.getInsertRequest();

        const vector<BSONObj>& inserts = origRequest->getDocuments();

        size_t i = 0u;
        for (vector<BSONObj>::const_iterator it = inserts.begin(); it != inserts.end(); ++it, ++i) {

            const BSONObj& insert = *it;
            BSONObj idInsert;

            if (insert["_id"].eoo()) {
                BSONObjBuilder idInsertB;
                idInsertB.append("_id", OID::gen());
                idInsertB.appendElements(insert);
                idInsert = idInsertB.obj();
            }

            if (NULL == idRequest.get() && !idInsert.isEmpty()) {
                idRequest.reset(new BatchedInsertRequest);
                origRequest->cloneTo(idRequest.get());
            }

            if (!idInsert.isEmpty()) {
                idRequest->setDocumentAt(i, idInsert);
            }
        }

        if (NULL == idRequest.get())
            return NULL;

        // Command request owns idRequest
        return new BatchedCommandRequest(idRequest.release());
    }

    bool BatchedCommandRequest::containsNoIDUpsert(const BatchedCommandRequest& request) {

        if (request.getBatchType() != BatchedCommandRequest::BatchType_Update)
            return false;

        const vector<BatchedUpdateDocument*>& updates = 
            request.getUpdateRequest()->getUpdates();

        for (vector<BatchedUpdateDocument*>::const_iterator it = updates.begin(); 
            it != updates.end(); ++it) {

            const BatchedUpdateDocument* updateDoc = *it;
            if (updateDoc->getUpsert() && updateDoc->getQuery()["_id"].eoo()) 
                return true;
        }

        return false;
    }

    bool BatchedCommandRequest::containsUpserts( const BSONObj& writeCmdObj ) {

        BSONElement updatesEl = writeCmdObj[BatchedUpdateRequest::updates()];
        if ( updatesEl.type() != Array ) {
            return false;
        }

        BSONObjIterator it( updatesEl.Obj() );
        while ( it.more() ) {
            BSONElement updateEl = it.next();
            if ( !updateEl.isABSONObj() ) continue;
            if ( updateEl.Obj()[BatchedUpdateDocument::upsert()].trueValue() ) return true;
        }

        return false;
    }

    bool BatchedCommandRequest::getIndexedNS( const BSONObj& writeCmdObj,
                                              string* nsToIndex,
                                              string* errMsg ) {

        BSONElement documentsEl = writeCmdObj[BatchedInsertRequest::documents()];
        if ( documentsEl.type() != Array ) {
            *errMsg = "index write batch is invalid";
            return false;
        }

        BSONObjIterator it( documentsEl.Obj() );
        if ( !it.more() ) {
            *errMsg = "index write batch is empty";
            return false;
        }

        BSONElement indexDescEl = it.next();
        *nsToIndex = indexDescEl["ns"].str();
        if ( *nsToIndex == "" ) {
            *errMsg = "index write batch contains an invalid index descriptor";
            return false;
        }

        if ( it.more() ) {
            *errMsg = "index write batches may only contain a single index descriptor";
            return false;
        }

        return true;
    }

} // namespace mongo