forked from telefonicaid/fiware-orion
-
Notifications
You must be signed in to change notification settings - Fork 40
/
orionldPostBatchUpsert.cpp
534 lines (463 loc) · 20.4 KB
/
orionldPostBatchUpsert.cpp
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/*
*
* Copyright 2019 FIWARE Foundation e.V.
*
* This file is part of Orion-LD Context Broker.
*
* Orion-LD Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion-LD Context Broker 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 Orion-LD Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* orionld at fiware dot org
*
* Author: Gabriel Quaresma and Ken Zangelin
*/
extern "C"
{
#include "kbase/kMacros.h" // K_FT
#include "kjson/KjNode.h" // KjNode
#include "kjson/kjBuilder.h" // kjString, kjObject, ...
#include "kjson/kjLookup.h" // kjLookup
#include "kjson/kjClone.h" // kjClone
}
#include "logMsg/logMsg.h" // LM_*
#include "logMsg/traceLevels.h" // Lmt*
#include "common/globals.h" // parse8601Time
#include "rest/ConnectionInfo.h" // ConnectionInfo
#include "rest/httpHeaderAdd.h" // httpHeaderLocationAdd
#include "orionTypes/OrionValueType.h" // orion::ValueType
#include "orionTypes/UpdateActionType.h" // ActionType
#include "parse/CompoundValueNode.h" // CompoundValueNode
#include "ngsi/ContextAttribute.h" // ContextAttribute
#include "ngsi10/UpdateContextRequest.h" // UpdateContextRequest
#include "ngsi10/UpdateContextResponse.h" // UpdateContextResponse
#include "mongoBackend/mongoUpdateContext.h" // mongoUpdateContext
#include "rest/uriParamNames.h" // URI_PARAM_PAGINATION_OFFSET, URI_PARAM_PAGINATION_LIMIT
#include "mongoBackend/MongoGlobal.h" // getMongoConnection()
#include "orionld/rest/orionldServiceInit.h" // orionldHostName, orionldHostNameLen
#include "orionld/common/orionldErrorResponse.h" // orionldErrorResponseCreate
#include "orionld/common/SCOMPARE.h" // SCOMPAREx
#include "orionld/common/CHECK.h" // CHECK
#include "orionld/common/orionldState.h" // orionldState
#include "orionld/common/entitySuccessPush.h" // entitySuccessPush
#include "orionld/common/entityErrorPush.h" // entityErrorPush
#include "orionld/common/entityIdCheck.h" // entityIdCheck
#include "orionld/common/entityTypeCheck.h" // entityTypeCheck
#include "orionld/common/entityIdAndTypeGet.h" // entityIdAndTypeGet
#include "orionld/common/entityLookupById.h" // entityLookupById
#include "orionld/common/typeCheckForNonExistingEntities.h" // typeCheckForNonExistingEntities
#include "orionld/common/duplicatedInstances.h" // duplicatedInstances
#include "orionld/types/OrionldProblemDetails.h" // OrionldProblemDetails
#include "orionld/context/orionldCoreContext.h" // orionldDefaultUrl, orionldCoreContext
#include "orionld/context/orionldContextPresent.h" // orionldContextPresent
#include "orionld/context/orionldContextItemAliasLookup.h" // orionldContextItemAliasLookup
#include "orionld/context/orionldContextItemExpand.h" // orionldContextItemExpand
#include "orionld/context/orionldContextFromTree.h" // orionldContextFromTree
#include "orionld/kjTree/kjStringValueLookupInArray.h" // kjStringValueLookupInArray
#include "orionld/kjTree/kjEntityIdLookupInEntityArray.h" // kjEntityIdLookupInEntityArray
#include "orionld/kjTree/kjTreeToUpdateContextRequest.h" // kjTreeToUpdateContextRequest
#include "orionld/kjTree/kjEntityIdArrayExtract.h" // kjEntityIdArrayExtract
#include "orionld/kjTree/kjEntityArrayErrorPurge.h" // kjEntityArrayErrorPurge
#include "orionld/serviceRoutines/orionldPostBatchUpsert.h" // Own Interface
// -----------------------------------------------------------------------------
//
// entityTypeGet - lookup 'type' in a KjTree
//
static char* entityTypeGet(KjNode* entityNodeP, KjNode** contextNodePP)
{
char* type = NULL;
for (KjNode* itemP = entityNodeP->value.firstChildP; itemP != NULL; itemP = itemP->next)
{
if (SCOMPARE5(itemP->name, 't', 'y', 'p', 'e', 0) || SCOMPARE6(itemP->name, '@', 't', 'y', 'p', 'e', 0))
type = itemP->value.s;
if (SCOMPARE9(itemP->name, '@', 'c', 'o', 'n', 't', 'e', 'x', 't', 0))
*contextNodePP = itemP;
}
return type;
}
// -----------------------------------------------------------------------------
//
// entityTypeAndCreDateGet -
//
static void entityTypeAndCreDateGet(KjNode* dbEntityP, char** idP, char** typeP, double* creDateP)
{
for (KjNode* nodeP = dbEntityP->value.firstChildP; nodeP != NULL; nodeP = nodeP->next)
{
if (SCOMPARE3(nodeP->name, 'i', 'd', 0) || SCOMPARE4(nodeP->name, '@', 'i', 'd', 0))
*idP = nodeP->value.s;
else if (SCOMPARE5(nodeP->name, 't', 'y', 'p', 'e', 0) || SCOMPARE6(nodeP->name, '@', 't', 'y', 'p', 'e', 0))
*typeP = nodeP->value.s;
else if (SCOMPARE8(nodeP->name, 'c', 'r', 'e', 'D', 'a', 't', 'e', 0))
{
if (nodeP->type == KjFloat)
*creDateP = nodeP->value.f;
else if (nodeP->type == KjInt)
*creDateP = (double) nodeP->value.i;
}
}
}
// ----------------------------------------------------------------------------
//
// entityLookupInDb - lookup an entioty id in an array of entities
//
// idTypeAndCreDateFromDb looks like this:
// [
// {
// "id":"urn:ngsi-ld:entity:E1",
// "type":"https://uri.etsi.org/ngsi-ld/default-context/Vehicle",
// "creDate":1619077285.144012
// },
// {
// "id":"urn:ngsi-ld:entity:E2",
// "type":"https://uri.etsi.org/ngsi-ld/default-context/Vehicle",
// "creDate":1619077285.144012
// }
// ]
static KjNode* entityLookupInDb(KjNode* idTypeAndCreDateFromDb, const char* entityId)
{
if (idTypeAndCreDateFromDb == NULL)
return NULL;
for (KjNode* entityP = idTypeAndCreDateFromDb->value.firstChildP; entityP != NULL; entityP = entityP->next)
{
KjNode* idNodeP = kjLookup(entityP, "id");
if ((idNodeP != NULL) && (idNodeP->type == KjString))
{
if (strcmp(idNodeP->value.s, entityId) == 0)
return entityP;
}
}
return NULL;
}
// ----------------------------------------------------------------------------
//
// orionldPostBatchUpsert -
//
// POST /ngsi-ld/v1/entityOperations/upsert
//
// From the spec:
// This operation allows creating a batch of NGSI-LD Entities, updating each of them if they already exist.
//
// An optional flag indicating the update mode (only applies in case the Entity already exists):
// - ?options=replace (default)
// - ?options=update
//
// Replace: All the existing Entity content shall be replaced - like PUT
// Update: Existing Entity content shall be updated - like PATCH
//
bool orionldPostBatchUpsert(ConnectionInfo* ciP)
{
// Error or not, the Link header should never be present in the reponse
orionldState.noLinkHeader = true;
//
// Prerequisites for URI params:
// * both 'update' and 'replace' cannot be set in options (replace is default)
//
if ((orionldState.uriParamOptions.update == true) && (orionldState.uriParamOptions.replace == true))
{
orionldErrorResponseCreate(OrionldBadRequestData, "URI Param Error", "options: both /update/ and /replace/ present");
orionldState.httpStatusCode = SccBadRequest;
return false;
}
//
// Prerequisites for the payload in orionldState.requestTree:
// * must be an array with objects
// * cannot be empty
// * all entities must contain an entity::id (one level down)
// * no entity can contain an entity::type (one level down)
//
ARRAY_CHECK(orionldState.requestTree, "toplevel");
EMPTY_ARRAY_CHECK(orionldState.requestTree, "toplevel");
KjNode* incomingTree = orionldState.requestTree;
KjNode* createdArrayP = kjArray(orionldState.kjsonP, "created");
KjNode* updatedArrayP = kjArray(orionldState.kjsonP, "updated");
KjNode* errorsArrayP = kjArray(orionldState.kjsonP, "errors");
//
// Entities that already exist in the DB cannot have a type != type-in-db
// To assure this, we need to extract all existing entities from the database
// Also, those entities that do not exist MUST have an entity type present.
//
// Create idArray as an array of entity IDs, extracted from orionldState.requestTree
//
KjNode* idArray = kjEntityIdArrayExtract(orionldState.requestTree, errorsArrayP);
//
// 02. Query database extracting three fields: { id, type and creDate } for each of the entities
// whose Entity::Id is part of the array "idArray".
// The result is "idTypeAndCredateFromDb" - an array of "tiny" entities with { id, type and creDate }
//
KjNode* idTypeAndCreDateFromDb = dbEntityListLookupWithIdTypeCreDate(idArray, false);
orionldState.batchEntities = idTypeAndCreDateFromDb; // So that TRoE knows what entities existed prior to the upsert call
//
// 03. Creation Date from DB entities, and type-check
//
// LOOP OVER idTypeAndCreDateFromDb.
// Add all the entities to "removeArray", unless an error occurs (with non-matching types for example)
//
KjNode* removeArray = NULL; // This array contains the Entity::Id of all entities to be removed from DB
int entitiesToRemove = 0;
if (idTypeAndCreDateFromDb != NULL)
{
for (KjNode* dbEntityP = idTypeAndCreDateFromDb->value.firstChildP; dbEntityP != NULL; dbEntityP = dbEntityP->next)
{
char* idInDb = NULL;
char* typeInDb = NULL;
double creDateInDb = 0;
char* typeInPayload = NULL;
KjNode* contextNodeP = NULL;
OrionldContext* contextP = NULL;
KjNode* entityP;
OrionldProblemDetails pd;
// Get entity id, type and creDate from the DB
entityTypeAndCreDateGet(dbEntityP, &idInDb, &typeInDb, &creDateInDb);
//
// For the entity in question - get id and type from the incoming payload
// First look up the entity with ID 'idInDb' in the incoming payload
//
entityP = entityLookupById(incomingTree, idInDb);
if (entityP == NULL)
continue;
typeInPayload = entityTypeGet(entityP, &contextNodeP);
if (contextNodeP != NULL)
contextP = orionldContextFromTree(NULL, true, contextNodeP, &pd);
if (contextP == NULL)
contextP = orionldState.contextP;
//
// If type exists in the incoming payload, it must be equal to the type in the DB
// If not, it's an error, so:
// - add entityId to errorsArrayP
// - add entityId to removeArray
// - remove from incomingTree
//
// Remember, the type in DB is expanded. We must expand the 'type' in the incoming payload as well, before we compare
//
if (typeInPayload != NULL)
{
char* typeInPayloadExpanded = orionldContextItemExpand(contextP, typeInPayload, true, NULL); // entity type
if (strcmp(typeInPayloadExpanded, typeInDb) != 0)
{
//
// As the entity type differed, this entity will not be updated in DB, nor will it be removed:
// - removed from incomingTree
// - not added to "removeArray"
//
LM_W(("Bad Input (orig entity type: '%s'. New entity type: '%s'", typeInDb, typeInPayloadExpanded));
entityErrorPush(errorsArrayP, idInDb, OrionldBadRequestData, "non-matching entity type", typeInPayload, 400, false);
kjChildRemove(incomingTree, entityP);
continue;
}
}
else
{
// Add 'type' to entity in incoming tree, if necessary
KjNode* typeNodeP = kjString(orionldState.kjsonP, "type", typeInDb);
kjChildAdd(entityP, typeNodeP);
}
//
// Add creDate from DB to the entity of the incoming tree
//
KjNode* creDateNodeP = kjFloat(orionldState.kjsonP, idInDb, creDateInDb);
if (orionldState.creDatesP == NULL)
orionldState.creDatesP = kjObject(orionldState.kjsonP, NULL);
kjChildAdd(orionldState.creDatesP, creDateNodeP);
//
// Add the Entity-ID to "removeArray" for later removal, before re-creation
//
if (removeArray == NULL)
removeArray = kjArray(orionldState.kjsonP, NULL);
KjNode* idNodeP = kjString(orionldState.kjsonP, NULL, idInDb);
kjChildAdd(removeArray, idNodeP);
++entitiesToRemove;
}
}
//
// 04. Entity::type is MANDATORY for entities that did not already exist
// Erroneous entities must be:
// - reported via entityErrorPush()
// - removed from "removeArray"
// - removed from "incomingTree"
//
// So, before calling 'typeCheckForNonExistingEntities' we must make sure the removeArray exists
//
if (removeArray == NULL)
removeArray = kjArray(orionldState.kjsonP, NULL);
typeCheckForNonExistingEntities(incomingTree, idTypeAndCreDateFromDb, errorsArrayP, removeArray);
//
// 05. Remove the entities in "removeArray" from DB
//
if (orionldState.uriParamOptions.update == false)
{
if ((removeArray != NULL) && (removeArray->value.firstChildP != NULL))
dbEntitiesDelete(removeArray);
}
//
// 06. Fill in UpdateContextRequest from "incomingTree"
//
//
// Before the tree is destroyed by kjTreeToUpdateContextRequest(),
// remove+merge any duplicated entities from the array and save the array for TRoE.
//
// If more than ONE instance of an entity:
// - For REPLACE - remove all entity instances but the last
// - For UPDATE - remove all instances and add a new one - merged from all of them
//
if (orionldState.uriParamOptions.update == true)
duplicatedInstances(incomingTree, NULL, false, true, errorsArrayP); // Existing entities are MERGED, existing attributes are replaced
else
duplicatedInstances(incomingTree, NULL, true, true, errorsArrayP); // Existing entities are REPLACED
KjNode* treeP = (troe == true)? kjClone(orionldState.kjsonP, incomingTree) : incomingTree;
UpdateContextRequest mongoRequest;
mongoRequest.updateActionType = ActionTypeAppend;
kjTreeToUpdateContextRequest(&mongoRequest, treeP, errorsArrayP, idTypeAndCreDateFromDb);
//
// 07. Set 'modDate' to "RIGHT NOW"
//
for (unsigned int ix = 0; ix < mongoRequest.contextElementVector.size(); ++ix)
{
mongoRequest.contextElementVector[ix]->entityId.modDate = orionldState.timestamp.tv_sec;
}
//
// 08. Call mongoBackend - to create/modify the entities
// In case of REPLACE, all entities have been removed from the DB prior to this call, so, they will all be created.
//
UpdateContextResponse mongoResponse;
orionldState.httpStatusCode = mongoUpdateContext(&mongoRequest,
&mongoResponse,
orionldState.tenant,
ciP->servicePathV,
ciP->uriParam,
ciP->httpHeaders.xauthToken,
ciP->httpHeaders.correlator,
ciP->httpHeaders.ngsiv2AttrsFormat,
ciP->apiVersion,
NGSIV2_NO_FLAVOUR);
//
// Now check orionldState.errorAttributeArray to see whether any attribute failed to be updated
//
// bool partialUpdate = (orionldState.errorAttributeArrayP[0] == 0)? false : true;
// bool retValue = true;
//
if (orionldState.httpStatusCode == SccOk)
{
for (unsigned int ix = 0; ix < mongoResponse.contextElementResponseVector.vec.size(); ix++)
{
const char* entityId = mongoResponse.contextElementResponseVector.vec[ix]->contextElement.entityId.id.c_str();
if (mongoResponse.contextElementResponseVector.vec[ix]->statusCode.code == SccOk)
{
// Creation or Update?
KjNode* dbEntityP = entityLookupInDb(idTypeAndCreDateFromDb, entityId);
if (dbEntityP == NULL)
entitySuccessPush(createdArrayP, entityId);
else
entitySuccessPush(updatedArrayP, entityId);
}
else
entityErrorPush(errorsArrayP,
entityId,
OrionldBadRequestData,
"",
mongoResponse.contextElementResponseVector.vec[ix]->statusCode.reasonPhrase.c_str(),
400,
false);
}
for (unsigned int ix = 0; ix < mongoRequest.contextElementVector.vec.size(); ix++)
{
const char* entityId = mongoRequest.contextElementVector.vec[ix]->entityId.id.c_str();
// Creation or Update?
KjNode* dbEntityP = entityLookupInDb(idTypeAndCreDateFromDb, entityId);
if (dbEntityP == NULL)
{
if (kjStringValueLookupInArray(createdArrayP, entityId) == NULL)
entitySuccessPush(createdArrayP, entityId);
}
else
{
if (kjStringValueLookupInArray(updatedArrayP, entityId) == NULL)
entitySuccessPush(updatedArrayP, entityId);
}
}
}
//
// We have entity ids in three arrays:
// errorsArrayP
// updatedArrayP
// createdArrayP
//
// 1. The broker returns 201 if all entities have been created:
// - errorsArrayP EMPTY
// - updatedArrayP EMPTY
// - createdArrayP NOT EMPTY
//
// 2. The broker returns 204 if all entities have been updated:
// - errorsArrayP EMPTY
// - createdArrayP EMPTY
// - updatedArrayP NOT EMPTY
//
// 3. Else, 207 is returned
//
KjNode* successArrayP = NULL;
if ((errorsArrayP->value.firstChildP == NULL) && (updatedArrayP->value.firstChildP == NULL))
{
orionldState.httpStatusCode = 201;
orionldState.responseTree = createdArrayP;
successArrayP = createdArrayP; // for kjEntityArrayErrorPurge
successArrayP->name = (char*) "success";
}
else if ((errorsArrayP->value.firstChildP == NULL) && (createdArrayP->value.firstChildP == NULL))
{
orionldState.httpStatusCode = 204;
orionldState.responseTree = NULL;
successArrayP = updatedArrayP; // for kjEntityArrayErrorPurge
successArrayP->name = (char*) "success";
}
else
{
orionldState.httpStatusCode = 207;
//
// For v1.3.1, merge updatedArrayP and createdArrayP into successArrayP
// FIXME: This will be amended in the spec and this code will need to change
//
if (updatedArrayP->value.firstChildP != NULL)
{
successArrayP = updatedArrayP;
if (createdArrayP->value.firstChildP != NULL)
{
// Concatenate arrays
successArrayP->lastChild->next = createdArrayP->value.firstChildP;
successArrayP->lastChild = createdArrayP->lastChild;
}
}
else if (createdArrayP->value.firstChildP != NULL)
{
successArrayP = createdArrayP;
if (updatedArrayP->value.firstChildP != NULL)
{
// Concatenate arrays
successArrayP->lastChild->next = updatedArrayP->value.firstChildP;
successArrayP->lastChild = updatedArrayP->lastChild;
}
}
else
successArrayP = updatedArrayP; // Empty array
successArrayP->name = (char*) "success";
//
// Add the success/error arrays to the response-tree
//
orionldState.responseTree = kjObject(orionldState.kjsonP, NULL);
kjChildAdd(orionldState.responseTree, successArrayP);
kjChildAdd(orionldState.responseTree, errorsArrayP);
}
mongoRequest.release();
mongoResponse.release();
if (troe == true)
kjEntityArrayErrorPurge(orionldState.requestTree, errorsArrayP, successArrayP);
return true;
}