File: history.c

package info (click to toggle)
cfengine3 3.15.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 34,456 kB
  • sloc: ansic: 145,932; sh: 8,550; makefile: 1,558; yacc: 1,192; python: 1,056; lex: 758; perl: 211; pascal: 149; awk: 58; xml: 21; sed: 13
file content (816 lines) | stat: -rw-r--r-- 25,350 bytes parent folder | download
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
/*
  Copyright 2019 Northern.tech AS

  This file is part of CFEngine 3 - written and maintained by Northern.tech AS.

  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the
  Free Software Foundation; version 3.

  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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

  To the extent this program is licensed as part of the Enterprise
  versions of CFEngine, the applicable Commercial Open Source License
  (COSL) may apply to this file if you as a licensee so wish it. See
  included file COSL.txt.
*/


#include <history.h>

#include <monitoring.h>                                      /* MakeTimekey */
#include <actuator.h>
#include <promises.h>
#include <ornaments.h>
#include <locks.h>
#include <policy.h>
#include <vars.h>
#include <known_dirs.h>
#include <sysinfo.h>
#include <unix.h>
#include <scope.h>
#include <eval_context.h>
#include <item_lib.h>
#include <exec_tools.h>
#include <conversion.h>
#include <instrumentation.h>
#include <files_interfaces.h>
#include <pipes.h>
#include <matching.h>
#include <string_lib.h>
#include <regex.h>                                       /* StringMatchFull */
#include <timeout.h>
#include <constants.h>
#include <time_classes.h>
#include <file_lib.h>
#include <assert.h>


#define CF_DUNBAR_WORK 30


typedef struct
{
    char *path;
    Item *output;
} CustomMeasurement;

static int MONITOR_RESTARTED = true;
static CustomMeasurement ENTERPRISE_DATA[CF_DUNBAR_WORK];

static void PutRecordForTime(CF_DB *db, time_t time, const Averages *values)
{
    char timekey[CF_MAXVARSIZE];

    MakeTimekey(time, timekey);

    WriteDB(db, timekey, values, sizeof(Averages));
}

static void Nova_SaveFilePosition(const char *handle, const char *name, long fileptr)
{
    CF_DB *dbp;
    char *key = StringConcatenate(2, handle, name);

    if (!OpenDB(&dbp, dbid_static))
    {
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Saving state for %s at %ld", key, fileptr);
    WriteDB(dbp, key, &fileptr, sizeof(long));
    CloseDB(dbp);
    free(key);
}

static long Nova_RestoreFilePosition(const char *handle, const char *name)
{
    CF_DB *dbp;
    long fileptr;
    char *key = StringConcatenate(2, handle, name);

    if (!OpenDB(&dbp, dbid_static))
    {
        return 0L;
    }

    ReadDB(dbp, key, &fileptr, sizeof(long));
    Log(LOG_LEVEL_VERBOSE, "Resuming state for %s at %ld", key, fileptr);
    CloseDB(dbp);
    free(key);
    return fileptr;
}

static void Nova_DumpSlowlyVaryingObservations(void)
{
    CF_DB *dbp;
    CF_DBC *dbcp;
    char *key;
    void *stored;
    int ksize, vsize;
    char name[CF_BUFSIZE];

    if (!OpenDB(&dbp, dbid_static))
    {
        return;
    }

    snprintf(name, CF_BUFSIZE - 1, "%s%cstatic_data", GetStateDir(), FILE_SEPARATOR);


    FILE *fout = safe_fopen(name, "w");
    if (fout == NULL)
    {
        Log(LOG_LEVEL_ERR, "Unable to save discovery data in '%s'. (fopen: %s)", name, GetErrorStr());
        CloseDB(dbp);
        return;
    }

/* Acquire a cursor for the database. */

    if (!NewDBCursor(dbp, &dbcp))
    {
        Log(LOG_LEVEL_INFO, "Unable to scan class db");
        CloseDB(dbp);
        return;
    }

    while (NextDB(dbcp, &key, &ksize, &stored, &vsize))
    {
        char buf[CF_MAXVARSIZE], lval[CF_MAXVARSIZE], rval[CF_BUFSIZE];

        strncpy(buf, key, CF_MAXVARSIZE - 1);

        sscanf(buf, "%s:", lval);

        if (stored != NULL)
        {
            strncpy(rval, stored, CF_BUFSIZE - 1);
            fprintf(fout, "%s:%s\n", lval, rval);
        }
    }

    DeleteDBCursor(dbcp);
    CloseDB(dbp);
    fclose(fout);
}

static void Nova_HistoryUpdate(time_t time, const Averages *newvals)
{
    CF_DB *dbp;

    if (!OpenDB(&dbp, dbid_history))
    {
        return;
    }

    PutRecordForTime(dbp, time, newvals);

    CloseDB(dbp);
}

static Item *NovaReSample(EvalContext *ctx, int slot, const Attributes *attr, const Promise *pp, PromiseResult *result)
{
    assert(attr != NULL);
    Attributes a = *attr; // TODO: try to remove this local copy
    CfLock thislock;
    char eventname[CF_BUFSIZE];
    struct timespec start;
    FILE *fin = NULL;
    mode_t maskval = 0;
    const char *handle = PromiseGetHandle(pp);

    if (a.measure.stream_type && strcmp(a.measure.stream_type, "pipe") == 0)
    {
        if (!IsExecutable(CommandArg0(pp->promiser)))
        {
            cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a, "%s promises to be executable but isn't\n", pp->promiser);
            *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL);
            return NULL;
        }
        else
        {
            Log(LOG_LEVEL_VERBOSE, "Promiser string contains a valid executable (%s) - ok", CommandArg0(pp->promiser));
        }
    }

    // Force a measurement if restarted:
    const int ifelapsed = MONITOR_RESTARTED ? 0 : a.transaction.ifelapsed;
    const int expireafter = a.transaction.expireafter;

    CFSTARTTIME = time(NULL);

    thislock = AcquireLock(ctx, pp->promiser, VUQNAME, CFSTARTTIME, ifelapsed, expireafter, pp, false);

    if (thislock.lock == NULL)
    {
        if (strcmp(a.measure.history_type, "log") == 0)
        {
            DeleteItemList(ENTERPRISE_DATA[slot].output);
            ENTERPRISE_DATA[slot].output = NULL;
        }
        else
        {
            /* If static or time-series, and too soon or busy then use a cached value
               to avoid artificial gaps in the history */
        }

        MONITOR_RESTARTED = false;
        return ENTERPRISE_DATA[slot].output;
    }
    else
    {
        DeleteItemList(ENTERPRISE_DATA[slot].output);
        ENTERPRISE_DATA[slot].output = NULL;

        Log(LOG_LEVEL_INFO, "Sampling \'%s\' ...(timeout=%d,owner=%ju,group=%ju)", pp->promiser, a.contain.timeout,
              (uintmax_t)a.contain.owner, (uintmax_t)a.contain.group);

        start = BeginMeasure();

        if (a.contain.timeout != 0)
        {
            SetTimeOut(a.contain.timeout);
        }

        /* Stream types */

        if (a.measure.stream_type && strcmp(a.measure.stream_type, "file") == 0)
        {
            long filepos = 0;
            struct stat sb;

            Log(LOG_LEVEL_VERBOSE, "Stream \"%s\" is a plain file", pp->promiser);

            if (stat(pp->promiser, &sb) == -1)
            {
                Log(LOG_LEVEL_INFO, "Unable to find stream '%s'. (stat: %s)",
                    pp->promiser, GetErrorStr());
                YieldCurrentLock(thislock);
                MONITOR_RESTARTED = false;

                return NULL;
            }

            fin = safe_fopen(pp->promiser, "r");

            if (a.measure.growing)
            {
                filepos = Nova_RestoreFilePosition(handle, pp->promiser);

                if (sb.st_size >= filepos)
                {
                    fseek(fin, filepos, SEEK_SET);
                }
            }
        }
        else if (a.measure.stream_type && strcmp(a.measure.stream_type, "pipe") == 0)
        {
            Log(LOG_LEVEL_VERBOSE, "(Setting pipe umask to %jo)", (uintmax_t)a.contain.umask);
            maskval = umask(a.contain.umask);

            if (a.contain.umask == 0)
            {
                Log(LOG_LEVEL_VERBOSE, "Programming %s running with umask 0! Use umask= to set", pp->promiser);
            }


            // Mark: This is strange that we used these wrappers. Currently no way of setting these
            a.contain.owner = -1;
            a.contain.group = -1;
            a.contain.chdir = NULL;
            a.contain.chroot = NULL;
            // Mark: they were unset, and would fail for non-root(!)

            if (a.contain.shelltype == SHELL_TYPE_POWERSHELL)
            {
#ifdef __MINGW32__
                fin =
                    cf_popen_powershell_setuid(pp->promiser, "r", a.contain.owner, a.contain.group, a.contain.chdir,
                                      a.contain.chroot, false);
#else // !__MINGW32__
                Log(LOG_LEVEL_ERR, "Powershell is only supported on Windows");
                YieldCurrentLock(thislock);
                MONITOR_RESTARTED = false;
                return NULL;
#endif // !__MINGW32__
            }
            else if (a.contain.shelltype == SHELL_TYPE_USE)
            {
                fin =
                    cf_popen_shsetuid(pp->promiser, "r", a.contain.owner, a.contain.group, a.contain.chdir,
                                      a.contain.chroot, false);
            }
            else
            {
                fin =
                    cf_popensetuid(pp->promiser, "r", a.contain.owner, a.contain.group, a.contain.chdir,
                                   a.contain.chroot, false);
            }
        }

        /* generic file stream */

        if (fin == NULL)
        {
            cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a,
                 "Couldn't open pipe to command '%s'. (cf_popen: %s)", pp->promiser, GetErrorStr());
            *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL);
            YieldCurrentLock(thislock);
            MONITOR_RESTARTED = false;
            return ENTERPRISE_DATA[slot].output;
        }

        size_t line_size = CF_BUFSIZE;
        char *line = xmalloc(line_size);

        for (;;)
        {
            ssize_t res = CfReadLine(&line, &line_size, fin);
            if (res == -1)
            {
                if (!feof(fin))
                {
                    cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_TIMEOUT, pp, &a, "Sample stream '%s'. (fread: %s)",
                         pp->promiser, GetErrorStr());
                    *result = PromiseResultUpdate(*result, PROMISE_RESULT_TIMEOUT);
                    YieldCurrentLock(thislock);
                    free(line);
                    return ENTERPRISE_DATA[slot].output;
                }
                else
                {
                    break;
                }
            }

            AppendItem(&(ENTERPRISE_DATA[slot].output), line, NULL);
            Log(LOG_LEVEL_INFO, "Sampling => %s", line);
        }

        free(line);

        if (a.measure.stream_type && strcmp(a.measure.stream_type, "file") == 0)
        {
            long fileptr = ftell(fin);

            fclose(fin);
            Nova_SaveFilePosition(handle, pp->promiser, fileptr);
        }
        else if (a.measure.stream_type && strcmp(a.measure.stream_type, "pipe") == 0)
        {
            cf_pclose(fin);
        }
    }

    if (a.contain.timeout != 0)
    {
        alarm(0);
        signal(SIGALRM, SIG_DFL);
    }

    Log(LOG_LEVEL_INFO, "Collected sample of %s", pp->promiser);
    umask(maskval);
    YieldCurrentLock(thislock);
    MONITOR_RESTARTED = false;

    snprintf(eventname, CF_BUFSIZE - 1, "Sample(%s)", pp->promiser);
    EndMeasure(eventname, start);
    return ENTERPRISE_DATA[slot].output;
}

void HistoryUpdate(EvalContext *ctx, const Averages *const newvals)
{
    CfLock thislock;
    time_t now = time(NULL);

/* We do this only once per hour - this should not be changed */

    Banner("Update long-term history");

    Policy *history_db_policy = PolicyNew();
    Promise *pp = NULL;
    {
        Bundle *bp = PolicyAppendBundle(history_db_policy, NamespaceDefault(), "history_db_bundle", "agent", NULL, NULL);
        PromiseType *tp = BundleAppendPromiseType(bp, "history_db");

        pp = PromiseTypeAppendPromise(tp, "the long term memory", (Rval) { NULL, RVAL_TYPE_NOPROMISEE }, NULL, NULL);
    }
    assert(pp);

    thislock = AcquireLock(ctx, pp->promiser, VUQNAME, now, 59, 0, pp, false);

    if (thislock.lock == NULL)
    {
        PolicyDestroy(history_db_policy);
        return;
    }

/* Refresh the class context of the agent */

    EvalContextClear(ctx);

    DetectEnvironment(ctx);
    time_t t = SetReferenceTime();
    UpdateTimeClasses(ctx, t);

    EvalContextHeapPersistentLoadAll(ctx);
    LoadSystemConstants(ctx);

    YieldCurrentLock(thislock);
    PolicyDestroy(history_db_policy);

    Nova_HistoryUpdate(CFSTARTTIME, newvals);

    Nova_DumpSlowlyVaryingObservations();
}

static Item *NovaGetMeasurementStream(EvalContext *ctx, const Attributes *a, const Promise *pp, PromiseResult *result)
{
    int i;

    for (i = 0; i < CF_DUNBAR_WORK; i++)
    {
        if (ENTERPRISE_DATA[i].path == NULL)
        {
            break;
        }

        if (strcmp(ENTERPRISE_DATA[i].path, pp->promiser) == 0)
        {
            ENTERPRISE_DATA[i].output = NovaReSample(ctx, i, a, pp, result);
            return ENTERPRISE_DATA[i].output;
        }
    }

    ENTERPRISE_DATA[i].path = xstrdup(pp->promiser);
    ENTERPRISE_DATA[i].output = NovaReSample(ctx, i, a, pp, result);
    return ENTERPRISE_DATA[i].output;
}

static PromiseResult NovaExtractValueFromStream(EvalContext *ctx, const char *handle,
                                                Item *stream, const Attributes *a,
                                                const Promise *pp, double *value_out)
{
    char value[CF_MAXVARSIZE];
    int count = 1, found = false, match_count = 0, done = false;
    double real_val = 0;
    Item *ip, *match = NULL;
    bool ok_conversion = true;

    for (ip = stream; ip != NULL; ip = ip->next)
    {
        if (count == a->measure.select_line_number)
        {
            found = true;
            match = ip;
            match_count++;
        }

        if (a->measure.select_line_matching && StringMatchFull(a->measure.select_line_matching, ip->name))
        {
            Log(LOG_LEVEL_VERBOSE, "  Found regex '%s' matches line '%s'", a->measure.select_line_matching, ip->name);
            found = true;
            match = ip;

            if (a->measure.extraction_regex)
            {
                switch (a->measure.data_type)
                {
                case CF_DATA_TYPE_INT:
                case CF_DATA_TYPE_REAL:
                case CF_DATA_TYPE_COUNTER:

                    strncpy(value, ExtractFirstReference(a->measure.extraction_regex, match->name), CF_MAXVARSIZE - 1);

                    if (strcmp(value, "CF_NOMATCH") == 0)
                    {
                        ok_conversion = false;
                        Log(LOG_LEVEL_VERBOSE, "Was not able to match a value with '%s' on '%s'",
                            a->measure.extraction_regex, match->name);
                    }
                    else
                    {
                        if (ok_conversion)
                        {
                            Log(LOG_LEVEL_VERBOSE, "Found candidate match value of '%s'", value);

                            if (a->measure.policy == MEASURE_POLICY_SUM || a->measure.policy == MEASURE_POLICY_AVERAGE)
                            {
                                double delta = 0;
                                if (DoubleFromString(value, &delta))
                                {
                                    real_val += delta;
                                }
                                else
                                {
                                    Log(LOG_LEVEL_ERR, "Error in double conversion from string value: %s", value);
                                    return PROMISE_RESULT_FAIL;
                                }
                            }
                            else
                            {
                                if (!DoubleFromString(value, &real_val))
                                {
                                    Log(LOG_LEVEL_ERR, "Error in double conversion from string value: %s", value);
                                    return PROMISE_RESULT_FAIL;
                                }
                            }

                            match_count++;

                            if (a->measure.policy == MEASURE_POLICY_FIRST)
                            {
                                done = true;
                            }
                        }
                    }
                    break;

                default:
                    Log(LOG_LEVEL_ERR, "Unexpected data type in data_type attribute: %d", a->measure.data_type);
                }
            }

        }

        count++;

        if (done)
        {
            break;
        }
    }

    if (!found)
    {
        cfPS(ctx, LOG_LEVEL_VERBOSE, PROMISE_RESULT_FAIL, pp, a, "Could not locate the line for promise '%s'", handle);
        *value_out = 0.0;
        return PROMISE_RESULT_FAIL;
    }

    switch (a->measure.data_type)
    {
    case CF_DATA_TYPE_COUNTER:

        real_val = (double) match_count;
        break;

    case CF_DATA_TYPE_INT:

        if (match_count > 1)
        {
            Log(LOG_LEVEL_INFO, "Warning: %d lines matched the line_selection \"%s\"- making best average",
                  match_count, a->measure.select_line_matching);
        }

        if (match_count > 0 && a->measure.policy == MEASURE_POLICY_AVERAGE) // If not "average" then "sum"
        {
            real_val /= match_count;
        }
        break;

    case CF_DATA_TYPE_REAL:

        if (match_count > 1)
        {
            Log(LOG_LEVEL_INFO, "Warning: %d lines matched the line_selection \"%s\"- making best average",
                  match_count, a->measure.select_line_matching);
        }

        if (match_count > 0)
        {
            real_val /= match_count;
        }

        break;

    default:
        Log(LOG_LEVEL_ERR, "Unexpected data type in data_type attribute: %d", a->measure.data_type);
    }

    if (!ok_conversion)
    {
        cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Unable to extract a value from the matched line '%s'", match->name);
        PromiseRef(LOG_LEVEL_INFO, pp);
        *value_out = 0.0;
        return PROMISE_RESULT_FAIL;
    }

    Log(LOG_LEVEL_INFO, "Extracted value \"%f\" for promise \"%s\"", real_val, handle);
    *value_out = real_val;
    return PROMISE_RESULT_NOOP;
}

static void NovaLogSymbolicValue(EvalContext *ctx, const char *handle, Item *stream,
                                 const Attributes *a, const Promise *pp, PromiseResult *result)
{
    char value[CF_BUFSIZE], sdate[CF_MAXVARSIZE], filename[CF_BUFSIZE];
    int count = 1, found = false, match_count = 0;
    Item *ip, *match = NULL, *matches = NULL;
    time_t now = time(NULL);

    if (stream == NULL)
    {
        Log(LOG_LEVEL_VERBOSE, "No stream to measure");
        return;
    }

    Log(LOG_LEVEL_VERBOSE, "Locate and log sample ...");

    for (ip = stream; ip != NULL; ip = ip->next)
    {
        if (ip->name == NULL)
        {
            continue;
        }

        if (count == a->measure.select_line_number)
        {
            Log(LOG_LEVEL_VERBOSE, "Found line %d by number...", count);
            found = true;
            match_count = 1;
            match = ip;

            if (a->measure.extraction_regex)
            {
                Log(LOG_LEVEL_VERBOSE, "Now looking for a matching extractor \"%s\"", a->measure.extraction_regex);
                strncpy(value, ExtractFirstReference(a->measure.extraction_regex, match->name), CF_MAXVARSIZE - 1);
                Log(LOG_LEVEL_INFO, "Extracted value \"%s\" for promise \"%s\"", value, handle);
                AppendItem(&matches, value, NULL);
            }
            else
            {
                Log(LOG_LEVEL_INFO, "Using entire line \"%s\" for promise \"%s\"", match->name, handle);
                AppendItem(&matches, match->name, NULL);
            }
            break;
        }

        if (a->measure.select_line_matching && StringMatchFull(a->measure.select_line_matching, ip->name))
        {
            Log(LOG_LEVEL_VERBOSE, "Found line %d by pattern...", count);
            found = true;
            match = ip;
            match_count++;

            if (a->measure.extraction_regex)
            {
                Log(LOG_LEVEL_VERBOSE, "Now looking for a matching extractor \"%s\"", a->measure.extraction_regex);
                strncpy(value, ExtractFirstReference(a->measure.extraction_regex, match->name), CF_MAXVARSIZE - 1);
                Log(LOG_LEVEL_INFO, "Extracted value \"%s\" for promise \"%s\"", value, handle);
                AppendItem(&matches, value, NULL);
            }
            else
            {
                Log(LOG_LEVEL_INFO, "Using entire line \"%s\" for promise \"%s\"", match->name, handle);
                AppendItem(&matches, match->name, NULL);
            }
        }

        count++;
    }

    if (!found)
    {
        cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Promiser '%s' found no matching line.", pp->promiser);
        *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL);
        return;
    }

    if (match_count > 1)
    {
        Log(LOG_LEVEL_INFO, "Warning: %d lines matched the line_selection \"%s\"- matching to last", match_count,
              a->measure.select_line_matching);
    }

    switch (a->measure.data_type)
    {
    case CF_DATA_TYPE_COUNTER:
        Log(LOG_LEVEL_VERBOSE, "Counted %d for %s", match_count, handle);
        snprintf(value, CF_MAXVARSIZE, "%d", match_count);
        break;

    case CF_DATA_TYPE_STRING_LIST:
        ItemList2CSV_bound(matches, value, sizeof(value), ',');
        break;

    default:
        snprintf(value, CF_BUFSIZE, "%s", matches->name);
    }

    DeleteItemList(matches);

    if (a->measure.history_type && strcmp(a->measure.history_type, "log") == 0)
    {
        snprintf(filename, CF_BUFSIZE, "%s%c%s_measure.log", GetStateDir(), FILE_SEPARATOR, handle);

        FILE *fout = safe_fopen(filename, "a");
        if (fout == NULL)
        {
            cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Unable to open the output log \"%s\"", filename);
            *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL);
            PromiseRef(LOG_LEVEL_ERR, pp);
            return;
        }

        strncpy(sdate, ctime(&now), CF_MAXVARSIZE - 1);
        if (Chop(sdate, CF_EXPANDSIZE) == -1)
        {
            Log(LOG_LEVEL_ERR, "Chop was called on a string that seemed to have no terminator");
        }

        fprintf(fout, "%s,%ld,%s\n", sdate, (long) now, value);
        Log(LOG_LEVEL_VERBOSE, "Logging: %s,%s to %s", sdate, value, filename);

        fclose(fout);
    }
    else                        // scalar or static
    {
        CF_DB *dbp;
        char id[CF_MAXVARSIZE];

        if (!OpenDB(&dbp, dbid_static))
        {
            return;
        }

        snprintf(id, CF_MAXVARSIZE - 1, "%s:%d", handle, a->measure.data_type);
        WriteDB(dbp, id, value, strlen(value) + 1);
        CloseDB(dbp);
    }
}

PromiseResult VerifyMeasurement(EvalContext *ctx, double *this,
                                const Attributes *a, const Promise *pp)
{
    const char *handle = PromiseGetHandle(pp);
    Item *stream = NULL;
    int slot = 0;
    double new_value;

    if (!handle)
    {
        Log(LOG_LEVEL_ERR, "The promised measurement has no handle to register it by.");
        return PROMISE_RESULT_NOOP;
    }
    else
    {
        Log(LOG_LEVEL_VERBOSE, "Considering promise \"%s\"", handle);
    }

    PromiseResult result = PROMISE_RESULT_NOOP;
    switch (a->measure.data_type)
    {
    case CF_DATA_TYPE_COUNTER:
    case CF_DATA_TYPE_INT:
    case CF_DATA_TYPE_REAL:

        /* First see if we can accommodate this measurement */
        Log(LOG_LEVEL_VERBOSE, "Promise '%s' is numerical in nature", handle);

        stream = NovaGetMeasurementStream(ctx, a, pp, &result);

        if (strcmp(a->measure.history_type, "weekly") == 0)
        {
            if ((slot = NovaRegisterSlot(handle, pp->comment ? pp->comment : "User defined measure",
                                         a->measure.units ? a->measure.units : "unknown", 0.0f, 100.0f, true)) < 0)
            {
                return result;
            }

            result = PromiseResultUpdate(result, NovaExtractValueFromStream(ctx, handle, stream, a, pp, &this[slot]));
            Log(LOG_LEVEL_VERBOSE, "Setting Nova slot %d=%s to %lf", slot, handle, this[slot]);
        }
        else if (strcmp(a->measure.history_type, "log") == 0)
        {
            Log(LOG_LEVEL_VERBOSE, "Promise to log a numerical value");
            NovaLogSymbolicValue(ctx, handle, stream, a, pp, &result);
        }
        else                    /* static */
        {
            Log(LOG_LEVEL_VERBOSE, "Promise to store a static numerical value");
            result = PromiseResultUpdate(result, NovaExtractValueFromStream(ctx, handle, stream, a, pp, &new_value));
            NovaNamedEvent(handle, new_value);
        }
        break;

    default:

        Log(LOG_LEVEL_VERBOSE, "Promise '%s' is symbolic in nature", handle);
        stream = NovaGetMeasurementStream(ctx, a, pp, &result);
        NovaLogSymbolicValue(ctx, handle, stream, a, pp, &result);
        break;
    }

    return result;

// stream gets de-allocated in ReSample
}