• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

telefonicaid / fiware-orion / 43408076090

13 Nov 2026 10:17AM UTC coverage: 80.401% (+3.4%) from 76.998%
43408076090

push

github

web-flow
Merge pull request #4829 from telefonicaid/feature/4827_coverage_lm_traces

Keep LM_T traces in coverage builds

21206 of 27923 branches covered (75.94%)

Branch coverage included in aggregate %.

17323 of 19998 relevant lines covered (86.62%)

114641.41 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.11
/src/lib/cache/subCache.cpp
1
/*
2
*
3
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
4
*
5
* This file is part of Orion Context Broker.
6
*
7
* Orion Context Broker is free software: you can redistribute it and/or
8
* modify it under the terms of the GNU Affero General Public License as
9
* published by the Free Software Foundation, either version 3 of the
10
* License, or (at your option) any later version.
11
*
12
* Orion Context Broker is distributed in the hope that it will be useful,
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
15
* General Public License for more details.
16
*
17
* You should have received a copy of the GNU Affero General Public License
18
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
19
*
20
* For those usages not covered by this license please contact with
21
* iot_support at tid dot es
22
*
23
* Author: Ken Zangelin
24
*/
25
#include <sys/types.h>
26
#include <regex.h>
27
#include <string>
28
#include <vector>
29
#include <map>
30

31
#include "logMsg/logMsg.h"
32
#include "logMsg/traceLevels.h"
33

34
#include "common/sem.h"
35
#include "common/string.h"
36
#include "apiTypesV2/HttpInfo.h"
37
#include "apiTypesV2/MqttInfo.h"
38
#include "apiTypesV2/Subscription.h"
39
#include "mongoBackend/MongoGlobal.h"
40
#include "mongoBackend/mongoSubCache.h"
41
#include "cache/subCache.h"
42
#include "alarmMgr/alarmMgr.h"
43
#include "mongoBackend/dbConstants.h"
44
#include "mongoDriver/connectionOperations.h"
45

46
using std::map;
47

48

49

50
/* ****************************************************************************
51
*
52
* subCacheState - maintains the state of the subscription cache
53
*/
54
volatile SubCacheState subCacheState = ScsIdle;
55

56

57
//
58
// The subscription cache maintains in memory all subscriptions.
59
// The reason for this cache is to avoid a very slow mongo operation ... (Fermin)
60
//
61
// The 'mongo part' of the cache is implemented in mongoBackend/mongoSubCache.cpp/h and used in:
62
//   - MongoCommonUpdate.cpp               (in function addTriggeredSubscriptions_withCache)
63
//   - mongoUnsubscribeContext.cpp         (in function mongoUnsubscribeContext)
64
//   - contextBroker.cpp                   (to initialize and sybchronize)
65
//
66
// To manipulate the subscription cache, a semaphore is necessary, as various threads can be
67
// reading/inserting/removing subs at the same time.
68
// This semaphore is NOT optional, like the mongo request semaphore.
69
//
70
// Two functions have been added to common/sem.cpp|h for this: cacheSemTake/Give.
71
//
72

73

74
/* ****************************************************************************
75
*
76
* EntityInfo::EntityInfo -
77
*/
78
EntityInfo::EntityInfo
2,338 ✔
79
(
80
  const std::string&  _entityId,
81
  const std::string&  _entityType,
82
  bool                _isPattern,
83
  bool                _isTypePattern
84
)
2,338 ✔
85
:
86
entityId(_entityId), isPattern(_isPattern), entityType(_entityType), isTypePattern(_isTypePattern)
2,338 ✔
87
{
88
  if (isPattern)
2,338 ✔
89
  {
90
    if (!regComp(&entityIdPattern, _entityId.c_str(), REG_EXTENDED))
666 !
91
    {
92
      alarmMgr.badInput(clientIp, "invalid regular expression for idPattern", _entityId);
×
93
      isPattern = false;  // FIXME P6: this entity should not be let into the system. Must be stopped before.
×
94
                          //           Right here, best thing to do is simply to say it is not a regex
95
      entityIdPatternToBeFreed = false;
×
96
    }
97
    else
98
    {
99
      entityIdPatternToBeFreed = true;
666 ✔
100
    }
101
  }
102
  else
103
  {
104
    entityIdPatternToBeFreed = false;
1,672 ✔
105
  }
106

107
  if (isTypePattern)
2,338 ✔
108
  {
109
    if (!regComp(&entityTypePattern, _entityType.c_str(), REG_EXTENDED))
372 !
110
    {
111
      alarmMgr.badInput(clientIp, "invalid regular expression for typePattern", _entityType);
×
112
      isTypePattern = false;  // FIXME P6: this entity should not be let into the system. Must be stopped before.
×
113
                          //           Right here, best thing to do is simply to say it is not a regex
114
      entityTypePatternToBeFreed = false;
×
115
    }
116
    else
117
    {
118
      entityTypePatternToBeFreed = true;
372 ✔
119
    }
120
  }
121
  else
122
  {
123
    entityTypePatternToBeFreed = false;
1,966 ✔
124
  }
125
}
2,338 ✔
126

127

128

129
/* ****************************************************************************
130
*
131
* EntityInfo::match -
132
*/
133
bool EntityInfo::match
3,310 ✔
134
(
135
  const std::string&  id,
136
  const std::string&  type
137
)
138
{
139
  bool matchedType = false;
3,310 ✔
140
  bool matchedId   = false;
3,310 ✔
141

142
  // Check id
143
  if (isPattern)
3,310 ✔
144
  {
145
    // REGEX-comparison this->entityIdPattern VS id
146
    matchedId =  (regexec(&entityIdPattern, id.c_str(), 0, NULL, 0) == 0);
992 ✔
147
  }
148
  else if (id == entityId)
2,318 ✔
149
  {
150
    matchedId =  true;
1,948 ✔
151
  }
152
  else
153
  {
154
    matchedId = false;
370 ✔
155
  }
156

157
  // short-circuit, optimization
158
  if (matchedId)
3,310 ✔
159
  {
160
    // Check type
161
    if (isTypePattern)
2,926 ✔
162
    {
163
      // REGEX-comparison this->entityTypePattern VS type
164
      matchedType = (regexec(&entityTypePattern, type.c_str(), 0, NULL, 0) == 0);
508 ✔
165
    }
166
    else if ((!type.empty())  && (!entityType.empty()) && (entityType != type))
2,418 !
167
    {
168
      matchedType = false;
26 ✔
169
    }
170
    else
171
    {
172
      matchedType = true;
2,392 ✔
173
    }
174
  }
175

176
  return matchedId && matchedType;
3,310 ✔
177
}
178

179

180

181
/* ****************************************************************************
182
*
183
* EntityInfo::release -
184
*/
185
void EntityInfo::release(void)
4,676 ✔
186
{
187
  if (entityIdPatternToBeFreed)
4,676 ✔
188
  {
189
    regfree(&entityIdPattern);  // If regcomp fails it frees up itself (see glibc sources for details)
666 ✔
190
    entityIdPatternToBeFreed = false;
666 ✔
191
  }
192

193
  if (entityTypePatternToBeFreed)
4,676 ✔
194
  {
195
    regfree(&entityTypePattern);  // If regcomp fails it frees up itself (see glibc sources for details)
372 ✔
196
    entityTypePatternToBeFreed = false;
372 ✔
197
  }
198
}
4,676 ✔
199

200

201

202
/* ****************************************************************************
203
*
204
* SubCache -
205
*/
206
typedef struct SubCache
207
{
208
  CachedSubscription* head;
209
  CachedSubscription* tail;
210

211
  // Statistics counters
212
  int                 noOfRefreshes;
213
  int                 noOfInserts;
214
  int                 noOfRemoves;
215
  int                 noOfUpdates;
216
} SubCache;
217

218

219

220
/* ****************************************************************************
221
*
222
* subCache -
223
*/
224
static SubCache  subCache            = { NULL, NULL, 0, 0, 0, 0 };
225
bool             subCacheActive      = false;
226
bool             subCacheMultitenant = false;
227

228

229

230
/* ****************************************************************************
231
*
232
* subCacheInit -
233
*/
234
void subCacheInit(bool multitenant)
2,548 ✔
235
{
236
  LM_T(LmtSubCache, ("Initializing subscription cache"));
2,548 ✔
237
  subCacheMultitenant = multitenant;
2,548 ✔
238

239
  subCache.head   = NULL;
2,548 ✔
240
  subCache.tail   = NULL;
2,548 ✔
241

242
  subCacheStatisticsReset("subCacheInit");
2,548 ✔
243

244
  subCacheActive = true;
2,548 ✔
245
}
2,548 ✔
246

247

248

249
/* ****************************************************************************
250
*
251
* subCacheDisable -
252
*
253
*/
254
#ifdef UNIT_TEST
255
void subCacheDisable(void)
58 ✔
256
{
257
  subCacheActive = false;
58 ✔
258
}
58 ✔
259
#endif
260

261

262

263
/* ****************************************************************************
264
*
265
* subCacheItems -
266
*/
267
int subCacheItems(void)
6 ✔
268
{
269
  CachedSubscription* cSubP = subCache.head;
6 ✔
270
  int                 items = 0;
6 ✔
271

272
  while (cSubP != NULL)
6 !
273
  {
274
    ++items;
×
275
    cSubP = cSubP->next;
×
276
  }
277

278
  return items;
6 ✔
279
}
280

281

282

283
/* ****************************************************************************
284
*
285
* attributeMatch -
286
*/
287
static bool attributeMatch(CachedSubscription* cSubP, const std::vector<std::string>& attrV)
6,568 ✔
288
{
289
  // If the list of attributes to check is empty, then no match
290
  if (attrV.size() == 0)
6,568 ✔
291
  {
292
    return false;
1,322 ✔
293
  }
294

295
  if (cSubP->notifyConditionV.size() == 0)
5,246 ✔
296
  {
297
    return true;
4,426 ✔
298
  }
299

300
  for (unsigned int ncvIx = 0; ncvIx < cSubP->notifyConditionV.size(); ++ncvIx)
884 ✔
301
  {
302
    for (unsigned int aIx = 0; aIx < attrV.size(); ++aIx)
1,072 ✔
303
    {
304
      if (cSubP->notifyConditionV[ncvIx] == attrV[aIx])
1,008 ✔
305
      {
306
        return true;
790 ✔
307
      }
308
    }
309
  }
310

311
  return false;
30 ✔
312
}
313

314

315

316
/* ****************************************************************************
317
*
318
* servicePathMatch -
319
*/
320
static bool servicePathMatch(CachedSubscription* cSubP, char* servicePath)
3,326 ✔
321
{
322
  const char*  spath;
323

324
  // Special case. "/#" matches EVERYTHING
325
  if ((strlen(servicePath) == 2) && (servicePath[0] == '/') && (servicePath[1] == '#') && (servicePath[2] == 0))
3,326 !
326
  {
327
    return true;
×
328
  }
329

330
  //
331
  // Empty service path?
332
  //
333
  if ((strlen(servicePath) == 0) && (strlen(cSubP->servicePath) == 0))
3,326 !
334
  {
335
    return true;
×
336
  }
337

338
  //
339
  // Default service path for a subscription is "/".
340
  // So, if empty, set it to "/"
341
  //
342
  if (servicePath[0] == 0)
3,326 !
343
  {
344
    servicePath = (char*) "/";
×
345
  }
346

347
  spath = cSubP->servicePath;
3,326 ✔
348

349
  //
350
  // No wildcard - exact match
351
  //
352
  if (spath[strlen(spath) - 1] != '#')
3,326 ✔
353
  {
354
    return (strcmp(servicePath, cSubP->servicePath) == 0);
108 ✔
355
  }
356

357

358
  //
359
  // Wildcard - remove '#' and compare to the length of _servicePath.
360
  //            If equal upto the length of _servicePath, then it is a match
361
  //
362
  // Actually, there is more than one way to match here:
363
  // If we have a servicePath of the subscription as
364
  // "/a/b/#", then the following service-paths must match:
365
  //   1. /a/b
366
  //   2. /a/b/ AND /a/b/.+  (any path below /a/b/)
367
  //
368
  // What should NOT match is "/a/b2".
369
  //
370
  unsigned int len = strlen(spath) - 2;
3,218 ✔
371

372
  // 1. /a/b - (removing 2 chars from the cache-subscription removes "/#"
373

374
  if ((spath[len] == '/') && (strlen(servicePath) == len) && (strncmp(spath, servicePath, len) == 0))
3,218 !
375
  {
376
    return true;
×
377
  }
378

379
  // 2. /a/b/.+
380
  len = strlen(spath) - 1;
3,218 ✔
381
  if (strncmp(spath, servicePath, len) == 0)
3,218 !
382
  {
383
    return true;
3,218 ✔
384
  }
385

386
  return false;
×
387
}
388

389

390

391
/* ****************************************************************************
392
*
393
* subHasAltType
394
*
395
*/
396
static bool subHasAltType(CachedSubscription* cSubP, ngsiv2::SubAltType targetAltType)
1,496 ✔
397
{
398
  if (cSubP->subAltTypeV.size() != 0)
1,496 ✔
399
  {
400
    for (unsigned int ix = 0; ix < cSubP->subAltTypeV.size(); ix++)
38 ✔
401
    {
402
      if (cSubP->subAltTypeV[ix] == targetAltType)
36 ✔
403
      {
404
        return true;
34 ✔
405
      }
406
    }
407
  }
408
  return false;
1,462 ✔
409
}
410

411

412

413
/* ****************************************************************************
414
*
415
* matchAltType -
416
*
417
*/
418
static bool matchAltType(CachedSubscription* cSubP, ngsiv2::SubAltType targetAltType)
3,416 ✔
419
{
420
  // If subAltTypeV size == 0 default alteration types are update with change and create
421
  if (cSubP->subAltTypeV.size() == 0)
3,416 ✔
422
  {
423
    if ((isChangeAltType(targetAltType)) || (targetAltType == ngsiv2::SubAltType::EntityCreate))
3,292 ✔
424
    {
425
      return true;
3,250 ✔
426
    }
427
    else
428
    {
429
      return false;
42 ✔
430
    }
431
  }
432
  for (unsigned int ix = 0; ix < cSubP->subAltTypeV.size(); ix++)
174 ✔
433
  {
434
    ngsiv2::SubAltType altType = cSubP->subAltTypeV[ix];
126 ✔
435

436
    // EntityUpdate is special, it is a "sub-type" of EntityChange
437
    if (isChangeAltType(targetAltType))
126 ✔
438
    {
439
      if ((altType == ngsiv2::SubAltType::EntityUpdate) || (isChangeAltType(altType)))
46 ✔
440
      {
441
        return true;
36 ✔
442
      }
443
    }
444
    else if (altType == targetAltType)
80 ✔
445
    {
446
      return true;
40 ✔
447
    }
448
  }
449

450
  return false;
48 ✔
451
}
452

453

454

455
/* ****************************************************************************
456
*
457
* subMatch -
458
*/
459
static bool subMatch
3,416 ✔
460
(
461
  CachedSubscription*              cSubP,
462
  const char*                      tenant,
463
  const char*                      servicePath,
464
  const char*                      entityId,
465
  const char*                      entityType,
466
  const std::vector<std::string>&  attributes,
467
  const std::vector<std::string>&  attrsWithModifiedValue,
468
  const std::vector<std::string>&  attrsWithModifiedMd,
469
  ngsiv2::SubAltType               targetAltType
470
)
471
{
472
  // If notifyOnMetadataChange is false and only metadata has been changed, we "downgrade" to ngsiv2::EntityUpdate
473
  if (!cSubP->notifyOnMetadataChange && (targetAltType == ngsiv2::EntityChangeOnlyMetadata))
3,416 ✔
474
  {
475
    targetAltType = ngsiv2::EntityUpdate;
6 ✔
476
  }
477

478
  // Check alteration type
479
  if (!matchAltType(cSubP, targetAltType))
3,416 ✔
480
  {
481
    return false;
90 ✔
482
  }
483

484
  //
485
  // Check to filter out due to tenant - only valid if Broker has started with -multiservice option
486
  //
487
  if (subCacheMultitenant == true)
3,326 ✔
488
  {
489
    if ((cSubP->tenant == NULL) || (tenant == NULL) || (cSubP->tenant[0] == 0) || (tenant[0] == 0))
136 !
490
    {
491
      if ((cSubP->tenant != NULL) && (cSubP->tenant[0] != 0))
36 !
492
      {
493
        LM_T(LmtSubCacheMatch, ("No match due to tenant I"));
×
494
        return false;
×
495
      }
496

497
      if ((tenant != NULL) && (tenant[0] != 0))
36 !
498
      {
499
        LM_T(LmtSubCacheMatch, ("No match due to tenant II"));
×
500
        return false;
×
501
      }
502
    }
36 ✔
503
    else if (strcmp(cSubP->tenant, tenant) != 0)
100 !
504
    {
505
      LM_T(LmtSubCacheMatch, ("No match due to tenant III"));
×
506
      return false;
×
507
    }
508
  }
509

510
  if (servicePathMatch(cSubP, (char*) servicePath) == false)
3,326 !
511
  {
512
    LM_T(LmtSubCacheMatch, ("No match due to servicePath"));
×
513
    return false;
×
514
  }
515

516
  //
517
  // If one of the attribute names in the expression
518
  // of the subscription has the same name as the incoming attribute. there is a match.
519
  // Additionaly, if the attribute list in cSubP is empty, there is a match (this is the
520
  // case of ONANYCHANGE subscriptions).
521
  //
522
  // Depending of the alteration type, we use the list of attributes in the request or the list
523
  // with effective modifications. Note that EntityDelete doesn't check the list
524
  // The second part of the || (i.e. isChangeAltType and sub alt types include entityUpdate) is due to issue #4647
525
  // (not sure if a smarter and cleaner solution is possible...)
526
  if ((targetAltType == ngsiv2::EntityUpdate) || ((isChangeAltType(targetAltType)) && (subHasAltType(cSubP, ngsiv2::EntityUpdate))))
3,326 ✔
527
  {
528
    if (!attributeMatch(cSubP, attributes))
56 !
529
    {
530
      LM_T(LmtSubCacheMatch, ("No match due to attributes"));
×
531
      return false;
×
532
    }
533
  }
534
  else if ((isChangeAltType(targetAltType)) || (targetAltType == ngsiv2::EntityCreate))
3,270 ✔
535
  {
536
    // No match if: 1) there is no change in the *value* of attributes listed in conditions.attrs and 2) there is no change
537
    // in the *metadata* of the attributes listed in conditions.attrs (the 2) only if notifyOnMetadataChange is true)
538
    bool b1 = attributeMatch(cSubP, attrsWithModifiedValue);
3,256 ✔
539
    bool b2 = attributeMatch(cSubP, attrsWithModifiedMd);
3,256 ✔
540
    if (!b1 && !(cSubP->notifyOnMetadataChange && b2))
3,256 !
541
    {
542
      LM_T(LmtSubCacheMatch, ("No match due to attributes"));
16 ✔
543
      return false;
16 ✔
544
    }
545
  }
546

547
  for (unsigned int ix = 0; ix < cSubP->entityIdInfos.size(); ++ix)
3,720 ✔
548
  {
549
    EntityInfo* eiP = cSubP->entityIdInfos[ix];
3,310 ✔
550

551
    if (eiP->match(entityId, entityType))
16,550 ✔
552
    {
553
      return true;
2,900 ✔
554
    }
555
  }
556

557
  LM_T(LmtSubCacheMatch, ("No match due to EntityInfo"));
410 ✔
558
  return false;
410 ✔
559
}
560

561

562

563
/* ****************************************************************************
564
*
565
* subCacheMatch -
566
*/
567
void subCacheMatch
×
568
(
569
  const char*                        tenant,
570
  const char*                        servicePath,
571
  const char*                        entityId,
572
  const char*                        entityType,
573
  const char*                        attr,
574
  ngsiv2::SubAltType                 targetAltType,
575
  std::vector<CachedSubscription*>*  subVecP
576
)
577
{
578
  CachedSubscription* cSubP = subCache.head;
×
579

580
  while (cSubP != NULL)
×
581
  {
582
    std::vector<std::string> attrV;
×
583

584
    attrV.push_back(attr);
×
585

586
    if (subMatch(cSubP, tenant, servicePath, entityId, entityType, attrV, attrV, attrV, targetAltType))
×
587
    {
588
      subVecP->push_back(cSubP);
×
589
      LM_T(LmtSubCache, ("added subscription '%s': lastNotificationTime: %lu",
×
590
                         cSubP->subscriptionId, cSubP->lastNotificationTime));
591
    }
592

593
    cSubP = cSubP->next;
×
594
  }
×
595
}
×
596

597

598

599
/* ****************************************************************************
600
*
601
* subCacheMatch -
602
*/
603
void subCacheMatch
11,666 ✔
604
(
605
  const char*                        tenant,
606
  const char*                        servicePath,
607
  const char*                        entityId,
608
  const char*                        entityType,
609
  const std::vector<std::string>&    attributes,
610
  const std::vector<std::string>&    attrsWithModifiedValue,
611
  const std::vector<std::string>&    attrsWithModifiedMd,
612
  ngsiv2::SubAltType                 targetAltType,
613
  std::vector<CachedSubscription*>*  subVecP
614
)
615
{
616
  CachedSubscription* cSubP = subCache.head;
11,666 ✔
617

618
  while (cSubP != NULL)
15,082 ✔
619
  {
620
    if (subMatch(cSubP, tenant, servicePath, entityId, entityType, attributes, attrsWithModifiedValue, attrsWithModifiedMd, targetAltType))
3,416 ✔
621
    {
622
      subVecP->push_back(cSubP);
2,900 ✔
623
      LM_T(LmtSubCache, ("added subscription '%s': lastNotificationTime: %lu",
2,900 ✔
624
                         cSubP->subscriptionId, cSubP->lastNotificationTime));
625
    }
626

627
    cSubP = cSubP->next;
3,416 ✔
628
  }
629
}
11,666 ✔
630

631

632

633
/* ****************************************************************************
634
*
635
* subCacheItemDestroy -
636
*/
637
void subCacheItemDestroy(CachedSubscription* cSubP)
2,330 ✔
638
{
639
  if (cSubP->tenant != NULL)
2,330 ✔
640
  {
641
    free(cSubP->tenant);
438 ✔
642
    cSubP->tenant = NULL;
438 ✔
643
  }
644

645
  if (cSubP->servicePath != NULL)
2,330 !
646
  {
647
    free(cSubP->servicePath);
2,330 ✔
648
    cSubP->servicePath = NULL;
2,330 ✔
649
  }
650

651
  if (cSubP->subscriptionId != NULL)
2,330 !
652
  {
653
    free(cSubP->subscriptionId);
2,330 ✔
654
    cSubP->subscriptionId = NULL;
2,330 ✔
655
  }
656

657
  cSubP->httpInfo.release();
2,330 ✔
658
  cSubP->mqttInfo.release();
2,330 ✔
659
  cSubP->kafkaInfo.release();
2,330 ✔
660

661
  for (unsigned int ix = 0; ix < cSubP->entityIdInfos.size(); ++ix)
4,668 ✔
662
  {
663
    cSubP->entityIdInfos[ix]->release();
2,338 ✔
664
    delete cSubP->entityIdInfos[ix];
2,338 !
665
  }
666

667
  cSubP->entityIdInfos.clear();
2,330 ✔
668

669
  while (cSubP->attributes.size() > 0)
3,288 ✔
670
  {
671
    cSubP->attributes.erase(cSubP->attributes.begin());
958 ✔
672
  }
673
  cSubP->attributes.clear();
2,330 ✔
674

675
  cSubP->notifyConditionV.clear();
2,330 ✔
676

677
  cSubP->next = NULL;
2,330 ✔
678
}
2,330 ✔
679

680

681

682
/* ****************************************************************************
683
*
684
* subCacheDestroy -
685
*/
686
void subCacheDestroy(void)
7,878 ✔
687
{
688
  LM_T(LmtSubCache, ("destroying subscription cache"));
7,878 ✔
689

690
  CachedSubscription* cSubP  = subCache.head;
7,878 ✔
691

692
  if (subCache.head == NULL)
7,878 ✔
693
  {
694
    return;
6,434 ✔
695
  }
696

697
  while (cSubP->next)
1,884 ✔
698
  {
699
    CachedSubscription* prev = cSubP;
440 ✔
700

701
    cSubP = cSubP->next;
440 ✔
702
    subCacheItemDestroy(prev);
440 ✔
703
    LM_T(LmtSubCache,  ("removing CachedSubscription at %p", prev));
440 ✔
704
    delete prev;
440 !
705
  }
706

707
  subCacheItemDestroy(cSubP);
1,444 ✔
708
  LM_T(LmtSubCache,  ("removing CachedSubscription at %p", cSubP));
1,444 ✔
709
  delete cSubP;
1,444 !
710

711
  subCache.head  = NULL;
1,444 ✔
712
  subCache.tail  = NULL;
1,444 ✔
713
}
714

715

716

717
/* ****************************************************************************
718
*
719
* tenantMatch -
720
*/
721
static bool tenantMatch(const char* tenant1, const char* tenant2)
9,670 ✔
722
{
723
  if (!subCacheMultitenant)
9,670 ✔
724
  {
725
    // If no multitenant is in use, then tenant match always
726
    return true;
9,270 ✔
727
  }
728

729
  //
730
  // Removing complications with NULL, giving NULL tenants the value of an empty string;
731
  //
732
  tenant1 = (tenant1 == NULL)? "" : tenant1;
400 !
733
  tenant2 = (tenant2 == NULL)? "" : tenant2;
400 ✔
734

735
  if (strlen(tenant1) != strlen(tenant2))
400 !
736
  {
737
    return false;
×
738
  }
739

740
  if (strcmp(tenant1, tenant2) == 0)
400 !
741
  {
742
    return true;
400 ✔
743
  }
744

745
  return false;
×
746
}
747

748

749

750
/* ****************************************************************************
751
*
752
* subCacheItemLookup -
753
*
754
* FIXME P7: lookups would be A LOT faster if the subCache used a hash-table instead of
755
*           just a single linked link for the subscriptions.
756
*           The hash could be adding each char in 'tenant' and 'subscriptionId' to a 8-bit
757
*           integer and then we'd have a vector of 256 linked lists.
758
*           Another way of implementing this would be to use a std::vector or std::map.
759
*/
760
CachedSubscription* subCacheItemLookup(const char* tenant, const char* subscriptionId)
9,402 ✔
761
{
762
  CachedSubscription* cSubP = subCache.head;
9,402 ✔
763

764
  while (cSubP != NULL)
11,538 ✔
765
  {
766
    if ((tenantMatch(tenant, cSubP->tenant)) && (strcmp(subscriptionId, cSubP->subscriptionId) == 0))
9,670 !
767
    {
768
      return cSubP;
7,534 ✔
769
    }
770

771
    cSubP = cSubP->next;
2,136 ✔
772
  }
773

774
  return NULL;
1,868 ✔
775
}
776

777

778

779
/* ****************************************************************************
780
*
781
* subCacheUpdateStatisticsIncrement -
782
*/
783
void subCacheUpdateStatisticsIncrement(void)
440 ✔
784
{
785
  ++subCache.noOfUpdates;
440 ✔
786
}
440 ✔
787

788

789

790
/* ****************************************************************************
791
*
792
* subCacheItemInsert -
793
*
794
* First of all, insertion is done at the end of the list, so,
795
* cSubP->next must ALWAYS be zero at insertion time
796
*
797
* Note that this is the insert function that *really inserts* the
798
* CachedSubscription in the list of CachedSubscriptions.
799
*
800
* All other subCacheItemInsert functions create the subscription and then
801
* calls this function.
802
*
803
* So, the subscription itself is untouched by this function, is it ONLY inserted
804
* in the list (only the 'next' field is modified).
805
*
806
*/
807
void subCacheItemInsert(CachedSubscription* cSubP)
2,330 ✔
808
{
809
  cSubP->next = NULL;
2,330 ✔
810

811
  LM_T(LmtSubCache, ("inserting sub '%s', lastNotificationTime: %lu",
2,330 ✔
812
                     cSubP->subscriptionId, cSubP->lastNotificationTime));
813

814
  ++subCache.noOfInserts;
2,330 ✔
815

816
  // First insertion?
817
  if ((subCache.head == NULL) && (subCache.tail == NULL))
2,330 !
818
  {
819
    subCache.head   = cSubP;
1,450 ✔
820
    subCache.tail   = cSubP;
1,450 ✔
821

822
    return;
1,450 ✔
823
  }
824

825
  subCache.tail->next  = cSubP;
880 ✔
826
  subCache.tail        = cSubP;
880 ✔
827
}
828

829

830

831
/* ****************************************************************************
832
*
833
* subCacheItemInsert - create a new sub, fill it in, and add it to cache
834
*
835
* Note that 'count' and 'failsCounter', which is the counter of how many times a notification has been
836
* fired and has failed, are set to ZERO
837
*/
838
void subCacheItemInsert
1,520 ✔
839
(
840
  const char*                             tenant,
841
  const char*                             servicePath,
842
  const ngsiv2::HttpInfo&                 httpInfo,
843
  const ngsiv2::MqttInfo&                 mqttInfo,
844
  const ngsiv2::KafkaInfo&                kafkaInfo,
845
  const std::vector<EntityId>&            entIdVector,
846
  const std::vector<std::string>&         attributes,
847
  const std::vector<std::string>&         metadata,
848
  const std::vector<std::string>&         conditionAttrs,
849
  const std::vector<ngsiv2::SubAltType>&  altTypes,
850
  const char*                             subscriptionId,
851
  int64_t                                 expirationTime,
852
  int64_t                                 maxFailsLimit,
853
  int64_t                                 throttling,
854
  RenderFormat                            renderFormat,
855
  int64_t                                 lastNotificationTime,
856
  int64_t                                 lastNotificationSuccessTime,
857
  int64_t                                 lastNotificationFailureTime,
858
  int64_t                                 lastSuccessCode,
859
  const std::string&                      lastFailureReason,
860
  StringFilter*                           stringFilterP,
861
  StringFilter*                           mdStringFilterP,
862
  const std::string&                      status,
863
  double                                  statusLastChange,
864
  const std::string&                      jexlExpression,
865
  const std::string&                      q,
866
  const std::string&                      geometry,
867
  const std::string&                      coords,
868
  const std::string&                      georel,
869
  bool                                    blacklist,
870
  bool                                    onlyChanged,
871
  bool                                    covered,
872
  bool                                    notifyOnMetadataChange
873
)
874
{
875
  //
876
  // Add the subscription to the subscription cache.
877
  //
878

879
  CachedSubscription* cSubP = new CachedSubscription();
1,520 !
880
  LM_T(LmtSubCache,  ("allocated CachedSubscription at %p", cSubP));
1,520 ✔
881

882

883
  //
884
  // First the non-complex values
885
  //
886
  cSubP->tenant                = (tenant[0] == 0)? NULL : strdup(tenant);
1,520 ✔
887
  cSubP->servicePath           = strdup(servicePath);
1,520 ✔
888
  cSubP->subscriptionId        = strdup(subscriptionId);
1,520 ✔
889
  cSubP->expirationTime        = expirationTime;
1,520 ✔
890
  cSubP->maxFailsLimit         = maxFailsLimit;
1,520 ✔
891
  cSubP->throttling            = throttling;
1,520 ✔
892
  cSubP->lastNotificationTime  = lastNotificationTime;
1,520 ✔
893
  cSubP->lastFailure           = lastNotificationFailureTime;
1,520 ✔
894
  cSubP->lastSuccess           = lastNotificationSuccessTime;
1,520 ✔
895
  cSubP->lastFailureReason     = lastFailureReason;
1,520 ✔
896
  cSubP->lastSuccessCode       = lastSuccessCode;
1,520 ✔
897
  cSubP->renderFormat          = renderFormat;
1,520 ✔
898
  cSubP->next                  = NULL;
1,520 ✔
899
  cSubP->count                 = 0;
1,520 ✔
900
  cSubP->failsCounter          = 0;
1,520 ✔
901
  cSubP->status                = status;
1,520 ✔
902
  cSubP->statusLastChange      = statusLastChange;
1,520 ✔
903
  cSubP->jexlExpression        = jexlExpression;
1,520 ✔
904
  cSubP->expression.q          = q;
1,520 ✔
905
  cSubP->expression.geometry   = geometry;
1,520 ✔
906
  cSubP->expression.coords     = coords;
1,520 ✔
907
  cSubP->expression.georel     = georel;
1,520 ✔
908
  cSubP->blacklist             = blacklist;
1,520 ✔
909
  cSubP->onlyChanged           = onlyChanged;
1,520 ✔
910
  cSubP->covered               = covered;
1,520 ✔
911
  cSubP->notifyOnMetadataChange= notifyOnMetadataChange;
1,520 ✔
912
  cSubP->notifyConditionV      = conditionAttrs;
1,520 ✔
913
  cSubP->subAltTypeV           = altTypes;
1,520 ✔
914
  cSubP->attributes            = attributes;
1,520 ✔
915
  cSubP->metadata              = metadata;
1,520 ✔
916

917
  // empty cache entry, no relation with DB actually exists
918
  // (thus validity flag set to false)
919
  cSubP->failsCounterFromDb      = 0;
1,520 ✔
920
  cSubP->failsCounterFromDbValid = false;
1,520 ✔
921

922
  cSubP->httpInfo.fill(httpInfo);
1,520 ✔
923
  cSubP->mqttInfo.fill(mqttInfo);
1,520 ✔
924
  cSubP->kafkaInfo.fill(kafkaInfo);
1,520 ✔
925

926
  //
927
  // String filters
928
  //
929
  std::string  errorString;
1,520 ✔
930
  if (stringFilterP != NULL)
1,520 !
931
  {
932
    //
933
    // NOTE (for both 'q' and 'mq' string filters)
934
    //   Here, the cached subscription should have a String Filter but if 'fill()' fails, it won't.
935
    //   The subscription is already in mongo and hopefully this erroneous situation is fixed
936
    //   once the sub-cache is refreshed.
937
    //
938
    //   This 'but' should be minimized once the issue 2082 gets implemented.
939
    //   [ Only reason for fill() to fail (apart from out-of-memory) seems to be an invalid regex ]
940
    //
941
    cSubP->expression.stringFilter.fill(stringFilterP, &errorString);
1,520 ✔
942
  }
943

944
  if (mdStringFilterP != NULL)
1,520 !
945
  {
946
    cSubP->expression.mdStringFilter.fill(mdStringFilterP, &errorString);
1,520 ✔
947
  }
948

949

950

951
  //
952
  // Convert all EntIds to EntityInfo
953
  //
954
  for (unsigned int ix = 0; ix < entIdVector.size(); ++ix)
3,044 ✔
955
  {
956
    const EntityId*      eIdP = &entIdVector[ix];
1,524 ✔
957
    bool                 isPattern      = (eIdP->id.empty());
1,524 ✔
958
    bool                 isTypePattern  = (eIdP->type.empty());
1,524 ✔
959
    std::string          id             = (eIdP->id.empty())? eIdP->idPattern   : eIdP->id;
1,524 ✔
960
    std::string          type           = (eIdP->type.empty())? eIdP->typePattern : eIdP->type;
1,524 ✔
961

962
    EntityInfo* eP = new EntityInfo(id, type, isPattern, isTypePattern);
1,524 !
963

964
    cSubP->entityIdInfos.push_back(eP);
1,524 ✔
965
  }
1,524 ✔
966

967

968
  //
969
  // Insert the subscription in the cache
970
  //
971
  LM_T(LmtSubCache, ("Inserting NEW sub '%s', lastNotificationTime: %lu",
1,520 ✔
972
                     cSubP->subscriptionId, cSubP->lastNotificationTime));
973

974
  subCacheItemInsert(cSubP);
1,520 ✔
975
}
1,520 ✔
976

977

978

979
/* ****************************************************************************
980
*
981
* subCacheStatisticsGet -
982
*/
983
void subCacheStatisticsGet
6 ✔
984
(
985
  int*   refreshes,
986
  int*   inserts,
987
  int*   removes,
988
  int*   updates,
989
  int*   items,
990
  char*  list,
991
  int    listSize
992
)
993
{
994
  *refreshes = subCache.noOfRefreshes;
6 ✔
995
  *inserts   = subCache.noOfInserts;
6 ✔
996
  *removes   = subCache.noOfRemoves;
6 ✔
997
  *updates   = subCache.noOfUpdates;
6 ✔
998
  *items     = subCacheItems();
6 ✔
999

1000
  CachedSubscription* cSubP = subCache.head;
6 ✔
1001

1002
  //
1003
  // NOTE
1004
  //   If the listBuffer is big enough to hold the entire list of cached subscriptions,
1005
  //   subCacheStatisticsGet returns that list for the response of "GET /cache/statistics".
1006
  //   Minimum size of the list is set to 128 bytes and the needed size is detected later.
1007
  //   If the list-buffer is not big enough to hold the entire list, a warning text is showed instead.
1008
  //
1009
  //
1010
  *list = 0;
6 ✔
1011
  if (listSize > 128)
6 !
1012
  {
1013
    while (cSubP != NULL)
6 !
1014
    {
1015
      char          msg[256];
1016
      unsigned int  bytesLeft = listSize - strlen(list);
×
1017

1018
#if 0
1019
      //
1020
      // FIXME P5: To be removed once sub-update is OK in QA
1021
      //
1022
      int now = getCurrentTime();
1023
      snprintf(msg, sizeof(msg), "%s|N:%lu|E:%lu|T:%lu|DUR:%lu",
1024
               cSubP->subscriptionId,
1025
               cSubP->lastNotificationTime,
1026
               cSubP->expirationTime,
1027
               cSubP->throttling,
1028
               cSubP->expirationTime - now);
1029
#else
1030
        snprintf(msg, sizeof(msg), "%s", cSubP->subscriptionId);
×
1031
#endif
1032
      //
1033
      // If "msg" and ", " has no room in the "list", then no list is shown.
1034
      // (the '+ 2' if for the string ", ")
1035
      //
1036
      if (strlen(msg) + 2 > bytesLeft)
×
1037
      {
1038
        snprintf(list, listSize, "too many subscriptions");
×
1039
        break;
×
1040
      }
1041

1042
      if (list[0] != 0)
×
1043
        strcat(list, ", ");
×
1044

1045
      strcat(list, msg);
×
1046

1047
      cSubP = cSubP->next;
×
1048
    }
1049
  }
1050
  else
1051
  {
1052
    snprintf(list, listSize, "too many subscriptions");
×
1053
  }
1054

1055
  LM_T(LmtSubCache, ("Statistics: refreshes: %d (%d)", *refreshes, subCache.noOfRefreshes));
6 ✔
1056
}
6 ✔
1057

1058

1059

1060
/* ****************************************************************************
1061
*
1062
* subCacheStatisticsReset -
1063
*/
1064
void subCacheStatisticsReset(const char* by)
2,554 ✔
1065
{
1066
  subCache.noOfRefreshes  = 0;
2,554 ✔
1067
  subCache.noOfInserts    = 0;
2,554 ✔
1068
  subCache.noOfRemoves    = 0;
2,554 ✔
1069
  subCache.noOfUpdates    = 0;
2,554 ✔
1070

1071
  LM_T(LmtSubCache, ("Statistics reset by %s: refreshes is now %d", by, subCache.noOfRefreshes));
2,554 ✔
1072
}
2,554 ✔
1073

1074

1075
/* ****************************************************************************
1076
*
1077
* subCacheItemRemove -
1078
*/
1079
int subCacheItemRemove(CachedSubscription* cSubP)
446 ✔
1080
{
1081
  CachedSubscription* current = subCache.head;
446 ✔
1082
  CachedSubscription* prev    = NULL;
446 ✔
1083

1084
  LM_T(LmtSubCache, ("in subCacheItemRemove, trying to remove '%s'", cSubP->subscriptionId));
446 ✔
1085
  while (current != NULL)
470 !
1086
  {
1087
    if (current == cSubP)
470 ✔
1088
    {
1089
      // Removing first item ?
1090
      if (cSubP == subCache.head)
446 ✔
1091
      {
1092
        subCache.head = cSubP->next;
422 ✔
1093
      }
1094

1095
      // Removing last item?
1096
      if (cSubP == subCache.tail)
446 ✔
1097
      {
1098
        subCache.tail = prev;
6 ✔
1099
      }
1100

1101
      // Removing middle item?
1102
      if (prev != NULL)
446 ✔
1103
      {
1104
        prev->next = cSubP->next;
24 ✔
1105
      }
1106

1107
      LM_T(LmtSubCache, ("in subCacheItemRemove, REMOVING '%s'", cSubP->subscriptionId));
446 ✔
1108
      ++subCache.noOfRemoves;
446 ✔
1109

1110
      subCacheItemDestroy(cSubP);
446 ✔
1111
      delete cSubP;
446 !
1112

1113
      return 0;
446 ✔
1114
    }
1115

1116
    prev    = current;
24 ✔
1117
    current = current->next;
24 ✔
1118
  }
1119

1120
  LM_E(("Runtime Error (item to remove from sub-cache not found)"));
×
1121
  return -1;
×
1122
}
1123

1124

1125

1126
/* ****************************************************************************
1127
*
1128
* subCacheRefresh -
1129
*
1130
* WARNING
1131
*  The cache semaphore must be taken before this function is called:
1132
*    cacheSemTake(__FUNCTION__, "Reason");
1133
*  And released after subCacheRefresh finishes, of course.
1134
*/
1135
void subCacheRefresh(void)
2,746 ✔
1136
{
1137
  std::vector<std::string> databases;
2,746 ✔
1138

1139
  LM_T(LmtSubCache, ("Refreshing subscription cache"));
2,746 ✔
1140

1141
  // Empty the cache
1142
  subCacheDestroy();
2,746 ✔
1143

1144
  // Get list of database
1145
  if (mongoMultitenant())
2,746 ✔
1146
  {
1147
    getOrionDatabases(&databases);
102 ✔
1148
  }
1149

1150
  // Add the 'default tenant'
1151
  databases.push_back(getDbPrefix());
2,746 ✔
1152

1153

1154
  // Now refresh the subCache for each and every tenant
1155
  for (unsigned int ix = 0; ix < databases.size(); ++ix)
5,506 ✔
1156
  {
1157
    LM_T(LmtSubCache, ("DB %d: %s", ix, databases[ix].c_str()));
2,760 ✔
1158
    mongoSubCacheRefresh(databases[ix]);
2,760 ✔
1159
  }
1160

1161
  ++subCache.noOfRefreshes;
2,746 ✔
1162
  LM_T(LmtSubCache, ("Refreshed subscription cache [%d]", subCache.noOfRefreshes));
2,746 ✔
1163
}
2,746 ✔
1164

1165

1166

1167
/* ****************************************************************************
1168
*
1169
* CachedSubSaved -
1170
*/
1171
typedef struct CachedSubSaved
1172
{
1173
  int64_t      lastNotificationTime;
1174
  int64_t      count;
1175
  int64_t      failsCounter;
1176
  int64_t      lastFailure;
1177
  int64_t      lastSuccess;
1178
  std::string  lastFailureReason;
1179
  int64_t      lastSuccessCode;
1180
  std::string  status;
1181
  double       statusLastChange;
1182
} CachedSubSaved;
1183

1184

1185

1186
/* ****************************************************************************
1187
*
1188
* subCacheSync -
1189
*
1190
* 1. Save subscriptionId, lastNotificationTime, count, failsCounter, lastFailure, and lastSuccess for all items in cache (savedSubV)
1191
* 2. Refresh cache (count and failsCounter set to 0)
1192
* 3. Compare lastNotificationTime/Failure/Success in savedSubV with the new cache-contents and:
1193
*    3.1 Update cache-items where 'saved lastNotificationTime/Failure/Success' > 'cached lastNotificationTime/Failure/Success'
1194
*    3.2 Remember this more correct lastNotificationTime/Failure/Success (must be flushed to mongo) -
1195
*        by clearing out (set to -1) those lastNotificationTimes/Failure/Success that are newer in cache
1196
* 4. Update 'count' and 'failsCounter' for each item in savedSubV where non-zero
1197
* 5. Update 'lastNotificationTime/Failure/Success' for each item in savedSubV where non -1
1198
* 6. Free the vector created in step 1 - savedSubV
1199
*
1200
* NOTE
1201
*   This function runs in a separate thread and it allocates temporal objects (in savedSubV).
1202
*   If the broker dies when this function is executing, all these temporal objects will be reported
1203
*   as memory leaks.
1204
*   We see this in our valgrind tests, where we force the broker to die.
1205
*   This is of course not a real leak, we only see this as a leak as the function hasn't finished to
1206
*   execute until the point where the temporal objects are deleted (See '6. Free the vector savedSubV').
1207
*   To fix this little problem, we have created a variable 'subCacheState' that is set to ScsSynchronizing while
1208
*   the sub-cache synchronization is working.
1209
*   In serviceRoutinesV2/exitTreat.cpp this variable is checked and if iot is set to ScsSynchronizing, then a
1210
*   sleep for a few seconds is performed before the broker exits (this is only for DEBUG compilations).
1211
*/
1212
void subCacheSync(void)
256 ✔
1213
{
1214
  std::map<std::string, CachedSubSaved*> savedSubV;
256 ✔
1215

1216
  cacheSemTake(__FUNCTION__, "Synchronizing subscription cache");
256 ✔
1217
  subCacheState = ScsSynchronizing;
256 ✔
1218

1219

1220
  //
1221
  // 1. Save subscriptionId, lastNotificationTime, count, failsCounter, lastFailure, and lastSuccess for all items in cache
1222
  //
1223
  CachedSubscription* cSubP = subCache.head;
256 ✔
1224

1225
  while (cSubP != NULL)
554 ✔
1226
  {
1227
    //
1228
    // FIXME P7: For some reason, sometimes the same subscription is found twice in the cache (Issue 2216)
1229
    //           Once the issue 2216 is fixed, this if-block must be removed.
1230
    //
1231
    if (savedSubV[cSubP->subscriptionId] != NULL)
596 !
1232
    {
1233
      cSubP = cSubP->next;
×
1234
      continue;
×
1235
    }
1236

1237
    CachedSubSaved* cssP       = new CachedSubSaved();
298 !
1238

1239
    cssP->lastNotificationTime = cSubP->lastNotificationTime;
298 ✔
1240
    cssP->count                = cSubP->count;
298 ✔
1241
    cssP->failsCounter         = cSubP->failsCounter;
298 ✔
1242
    cssP->lastFailure          = cSubP->lastFailure;
298 ✔
1243
    cssP->lastSuccess          = cSubP->lastSuccess;
298 ✔
1244
    cssP->lastFailureReason    = cSubP->lastFailureReason;
298 ✔
1245
    cssP->lastSuccessCode      = cSubP->lastSuccessCode;
298 ✔
1246
    cssP->status               = cSubP->status;
298 ✔
1247
    cssP->statusLastChange     = cSubP->statusLastChange;
298 ✔
1248

1249
    savedSubV[cSubP->subscriptionId] = cssP;
298 ✔
1250
    cSubP = cSubP->next;
298 ✔
1251
  }
1252

1253
  LM_T(LmtCacheSync, ("Pushed back %d items to savedSubV", savedSubV.size()));
256 ✔
1254

1255

1256
  //
1257
  // 2. Refresh cache (count and failsCounter set to 0)
1258
  //
1259
  subCacheRefresh();
256 ✔
1260

1261
  // 3. Check if DB or local cache is newer, updating DB in the second case
1262
  cSubP = subCache.head;
256 ✔
1263
  while (cSubP != NULL)
554 ✔
1264
  {
1265
    CachedSubSaved* cssP = savedSubV[cSubP->subscriptionId];
298 ✔
1266

1267
    // Not-NULL in some of this means "dirty" data to update in DB at the end
1268
    // Note that count and failsCounter are special: they are update in DB
1269
    // using $inc and not $set and they are flushed during the cache refresh process.
1270
    // There aren't pointer for them
1271
    int64_t*      lastNotificationTimeP = NULL;
298 ✔
1272
    int64_t*      lastFailureP          = NULL;
298 ✔
1273
    int64_t*      lastSuccessP          = NULL;
298 ✔
1274
    std::string*  failureReasonP        = NULL;
298 ✔
1275
    int64_t*      statusCodeP           = NULL;
298 ✔
1276
    std::string*  statusP               = NULL;
298 ✔
1277
    double*       statusLastChangeP     = NULL;
298 ✔
1278

1279
    if (cssP != NULL)
298 !
1280
    {
1281
      if (cssP->lastNotificationTime > cSubP->lastNotificationTime)
298 ✔
1282
      {
1283
        // cssP->lastNotificationTime is newer than what's currently in DB => update in cSubP and DB
1284
        cSubP->lastNotificationTime = cssP->lastNotificationTime;
148 ✔
1285
        lastNotificationTimeP = &cSubP->lastNotificationTime;
148 ✔
1286
      }
1287

1288
      if (cssP->lastFailure > cSubP->lastFailure)
298 ✔
1289
      {
1290
        // cssP->lastFailure is newers than what's currently in DB => update in cSubP and DB
1291
        cSubP->lastFailure       = cssP->lastFailure;
68 ✔
1292
        cSubP->lastFailureReason = cssP->lastFailureReason;
68 ✔
1293
        lastFailureP   = &cSubP->lastFailure;
68 ✔
1294
        failureReasonP = &cSubP->lastFailureReason;
68 ✔
1295
      }
1296

1297
      if (cssP->lastSuccess > cSubP->lastSuccess)
298 ✔
1298
      {
1299
        // cssP->lastSuccess is newer than what's currently in DB => update in cSubP and DB
1300
        cSubP->lastSuccess     = cssP->lastSuccess;
84 ✔
1301
        cSubP->lastSuccessCode = cssP->lastSuccessCode;
84 ✔
1302
        lastSuccessP = &cSubP->lastSuccess;
84 ✔
1303
        statusCodeP  = &cSubP->lastSuccessCode;
84 ✔
1304
      }
1305

1306
      if (cssP->statusLastChange > cSubP->statusLastChange)
298 ✔
1307
      {
1308
        // cssP->status is newer than what's currently in DB => update in cSubP and DB
1309
        cSubP->status           = cssP->status;
26 ✔
1310
        cSubP->statusLastChange = cssP->statusLastChange;
26 ✔
1311
        statusP           = &cSubP->status;
26 ✔
1312
        statusLastChangeP = &cSubP->statusLastChange;
26 ✔
1313
      }
1314

1315
      std::string tenant = (cSubP->tenant == NULL)? "" : cSubP->tenant;
298 !
1316

1317
      // Note that in step 2 subCacheRefresh() sets failsCounterFromDb from DB,
1318
      // but that is done *before* updating the counter with mongoSubUpdateOnCacheSync()
1319
      // Thus, we have to do a mirror increase in the cache
1320
      cSubP->failsCounterFromDb += cssP->failsCounter;
298 ✔
1321

1322
      mongoSubUpdateOnCacheSync(tenant,
298 ✔
1323
                                cSubP->subscriptionId,
298 ✔
1324
                                cssP->count,
298 ✔
1325
                                cssP->failsCounter,
298 ✔
1326
                                lastNotificationTimeP,
1327
                                lastFailureP,
1328
                                lastSuccessP,
1329
                                failureReasonP,
1330
                                statusCodeP,
1331
                                statusP,
1332
                                statusLastChangeP);
1333
    }
298 ✔
1334

1335
    cSubP = cSubP->next;
298 ✔
1336
  }
1337

1338
  //
1339
  // 5. Free the vector savedSubV
1340
  //
1341
  for (std::map<std::string, CachedSubSaved*>::iterator it = savedSubV.begin(); it != savedSubV.end(); ++it)
554 ✔
1342
  {
1343
    delete it->second;
298 !
1344
  }
1345
  savedSubV.clear();
256 ✔
1346

1347

1348
  subCacheState = ScsIdle;
256 ✔
1349
  cacheSemGive(__FUNCTION__, "Synchronizing subscription cache");
256 ✔
1350
}
256 ✔
1351

1352

1353

1354
/* ****************************************************************************
1355
*
1356
* subCacheRefresherThread -
1357
*/
1358
static void* subCacheRefresherThread(void* vP)
2,490 ✔
1359
{
1360
  extern int subCacheInterval;
1361

1362
  while (1)
1363
  {
1364
    sleep(subCacheInterval);
2,746 ✔
1365
    subCacheSync();
256 ✔
1366
  }
1367

1368
  return NULL;
1369
}
1370

1371

1372

1373
/* ****************************************************************************
1374
*
1375
* subCacheStart -
1376
*/
1377
void subCacheStart(void)
2,490 ✔
1378
{
1379
  pthread_t  tid;
1380
  int        ret;
1381

1382
  // Populate subscription cache from database
1383
  subCacheRefresh();
2,490 ✔
1384

1385
  ret = pthread_create(&tid, NULL, subCacheRefresherThread, NULL);
2,490 ✔
1386

1387
  if (ret != 0)
2,490 !
1388
  {
1389
    LM_E(("Runtime Error (error creating thread: %d)", ret));
×
1390
    return;
×
1391
  }
1392
  pthread_detach(tid);
2,490 ✔
1393
}
1394

1395

1396

1397
extern bool noCache;
1398
/* ****************************************************************************
1399
*
1400
* subNotificationErrorStatus -
1401
*
1402
* This function marks a subscription to be erroneous, i.e. notifications are
1403
* not working.
1404
* A timestamp for this last failure is set for the sub-item in the sub-cache  and
1405
* the consecutive number of notification errors for the subscription is incremented.
1406
*
1407
* If error == true, then the subscription is marked as non-erroneous.
1408
*/
1409
void subNotificationErrorStatus
4,750 ✔
1410
(
1411
  const std::string&  tenant,
1412
  const std::string&  subscriptionId,
1413
  bool                error,
1414
  long long           statusCode,
1415
  const std::string&  failureReason,
1416
  long long           failsCounter,
1417
  long long           maxFailsLimit
1418
)
1419
{
1420
  bool maxFailsReached = maxFailsLimit > 0 && failsCounter >= maxFailsLimit;
4,750 ✔
1421

1422
  // FIXME P5: the noCache block is missplaced: subCache.cpp should contain only the
1423
  // logic related with cache
1424
  if (noCache)
4,750 ✔
1425
  {
1426
    // The field 'count' has already been taken care of (see processSubscriptions())
1427
    // It is not used taken into account in mongoSubUpdateOnNotif()
1428

1429
    time_t now = time(NULL);
2,338 ✔
1430

1431
    if (error)
2,338 ✔
1432
    {
1433
      std::string status           = "";
200 ✔
1434
      double      statusLastChange = -1;
200 ✔
1435
      if (maxFailsReached)
200 ✔
1436
      {
1437
        LM_W(("Subscription %s automatically disabled due to failsCounter (%d) overpasses maxFailsLimit (%d)", subscriptionId.c_str(), failsCounter + 1, maxFailsLimit));
36 ✔
1438
        status           = STATUS_INACTIVE;
36 ✔
1439
        statusLastChange = getCurrentTime();
36 ✔
1440
      }
1441
      // fails == 1, lastSuccess == -1, statusCode == -1, status == "" | "inactive"
1442
      mongoSubUpdateOnNotif(tenant, subscriptionId, 1, now, now, -1, failureReason, -1, status, statusLastChange);
200 ✔
1443
    }
200 ✔
1444
    else
1445
    {
1446
      // fails = 0, lastFailure == -1, failureReason == "", status == ""
1447
      mongoSubUpdateOnNotif(tenant, subscriptionId, 0, now, -1, now, "", statusCode, "", -1);
8,552 ✔
1448
    }
1449

1450
    return;
2,338 ✔
1451
  }
1452

1453
  time_t now = time(NULL);
2,412 ✔
1454

1455
  cacheSemTake(__FUNCTION__, "Looking up an item for lastSuccess/Failure");
2,412 ✔
1456

1457
  CachedSubscription* subP = subCacheItemLookup(tenant.c_str(), subscriptionId.c_str());
2,412 ✔
1458

1459
  if (subP == NULL)
2,412 !
1460
  {
1461
    cacheSemGive(__FUNCTION__, "Looking up an item for lastSuccess/Failure");
×
1462
    const char* errorString = "intent to update error status of non-existing subscription";
×
1463

1464
    alarmMgr.badInput(clientIp, errorString);
×
1465
    return;
×
1466
  }
1467

1468
  if (error)
2,412 ✔
1469
  {
1470
    subP->failsCounter++;
268 ✔
1471
    subP->lastFailure       = now;
268 ✔
1472
    subP->lastFailureReason = failureReason;
268 ✔
1473

1474
    if (maxFailsReached)
268 ✔
1475
    {
1476
      // update the status to inactive
1477
      LM_W(("Subscription %s automatically disabled due to failsCounter (%d) overpasses maxFailsLimit (%d)", subscriptionId.c_str(), failsCounter + 1, maxFailsLimit));
60 ✔
1478

1479
      double now = getCurrentTime();
60 ✔
1480
      subP->status = STATUS_INACTIVE;
60 ✔
1481
      subP->statusLastChange = now;
60 ✔
1482

1483
      LM_T(LmtSubCache, ("Update the status to %s (lastChange: %d)", subP->status.c_str(), now));
60 ✔
1484
    }
1485
  }
1486
  else
1487
  {
1488
    // no fails mean notification ok, thus reseting the counter
1489
    // in addition, DB consolidated data is marked as invalid
1490
    subP->failsCounter            = 0;
2,144 ✔
1491
    subP->lastSuccess             = now;
2,144 ✔
1492
    subP->lastSuccessCode         = statusCode;
2,144 ✔
1493
    subP->failsCounterFromDbValid = false;
2,144 ✔
1494
  }
1495

1496
  cacheSemGive(__FUNCTION__, "Looking up an item for lastSuccess/Failure");
2,412 ✔
1497
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc