JobAnalyzerTemplate.h 21.9 KB
Newer Older
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
//================================================================================
// Name        : JobAnalyzerTemplate.h
// Author      : Alessio Netti
// Copyright   : Leibniz Supercomputing Centre
// Description : Template implementing features needed by Analyzers.
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
// Copyright (C) 2018-2019 Leibniz Supercomputing Centre
//
// 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; either version 2
// of the License, or (at your option) any later version.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//================================================================================

#ifndef PROJECT_JOBANALYZERTEMPLATE_H
#define PROJECT_JOBANALYZERTEMPLATE_H

#include "AnalyzerInterface.h"
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <unordered_set>

/**
 * Template that implements features needed by Job Analyzers and complying to AnalyzerInterface.
 *
 * This template is derived from AnalyzerTemplate, and is adjusted to simplify job-related computations.
 *
 */
template <typename S>
class JobAnalyzerTemplate : public AnalyzerInterface {
    // The template shall only be instantiated for classes which derive from SensorBase
    static_assert(is_base_of<SensorBase, S>::value, "S must derive from SensorBase!");

protected:
    
    // For readability
    using S_Ptr = shared_ptr<S>;
    using U_Ptr = shared_ptr< UnitTemplate<S> >;

public:
    
    /**
    * @brief            Class constructor
    *
    * @param name       Name of the analyzer
    */
    JobAnalyzerTemplate(const string name) :
            AnalyzerInterface(name),
            _unitCache(nullptr),
            _insertionLUT(nullptr),
            _queryEngine(QueryEngine::getInstance()),
            _jobUnitsQueue(nullptr),
            _jobDataVec(nullptr) {
        
        _mapAccess.store(false);
    }

    /**
    * @brief            Copy constructor
    *
    */
    JobAnalyzerTemplate(const JobAnalyzerTemplate& other) :
            AnalyzerInterface(other),
            _unitCache(nullptr),
            _insertionLUT(nullptr),
            _queryEngine(QueryEngine::getInstance()),
            _jobUnitsQueue(nullptr),
            _jobDataVec(nullptr) {
        
        _mapAccess.store(false);
        for(auto u : other._units) {
            _units.push_back(u);
            _baseUnits.push_back(u);
        }
    }

    /**
    * @brief            Assignment operator
    *
    */
    JobAnalyzerTemplate& operator=(const JobAnalyzerTemplate& other) {
        AnalyzerInterface::operator=(other);
        _units.clear();

        for(auto u : other._units) {
            _units.push_back(u);
            _baseUnits.push_back(u);
        }
        _jobUnitsQueue.reset(nullptr);
        _jobDataVec = nullptr;
    }
            
    /**
    * @brief            Class destructor
    */
    virtual ~JobAnalyzerTemplate() {
        _units.clear();
        _baseUnits.clear();

        if(_unitCache) {
            _unitCache->clear();
            delete _unitCache;
        }
        if(_insertionLUT) {
            _insertionLUT->clear();
            delete _insertionLUT;
        }
        if(_jobDataVec)
            delete _jobDataVec;
    }

    /**
    * @brief            Prints the current analyzer configuration
    *
    * @param ll         Logging level at which the configuration is printed
    */
    virtual void printConfig(LOG_LEVEL ll) override {
        if(_mqttPart!="")
            LOG_VAR(ll) << "            MQTT part:       " << _mqttPart;
        LOG_VAR(ll) << "            Sync readings:   " << (_sync ? "enabled" : "disabled");
        LOG_VAR(ll) << "            Streaming mode:  " << (_streaming ? "enabled" : "disabled");
        LOG_VAR(ll) << "            MinValues:       " << _minValues;
        LOG_VAR(ll) << "            Interval:        " << _interval;
        LOG_VAR(ll) << "            Unit Cache Size: " << _unitCacheLimit;
        LOG_VAR(ll) << "            Start delay:     " << _delayInterval;
        LOG_VAR(ll) << "            Units:           none";
    }

    /**
    * @brief              Perform a REST-triggered PUT action
    *
    *                     This implementation supplies a "jobs" action that can be used to retrieve the list of jobs
    *                     that have been recently processed by this analyzer.
    *
    * @param action       Name of the action to be performed
    * @param queries      Vector of queries (key-value pairs)
    *
    * @return             Response to the request as a <response, data> pair
    */
    virtual restResponse_t REST(const string& action, const unordered_map<string, string>& queries) override {
        std::ostringstream data;
        if(action=="jobs") {
            uint32_t maxJobs = queries.count("max")>0 ? stoull(queries.at("max")) : 100;
            bool json = queries.count("json")>0 ? queries.at("json")=="true" : false;
            uint32_t jobCtr = 0;
            if(!_unitCache)
                throw std::runtime_error("Initialization error in analyzer " + _name + "!");
            
            while( _mapAccess.exchange(true) ) {}
            if(json) {
                boost::property_tree::ptree root, units, sensors;
                for (auto it = _insertionLUT->rbegin(); it != _insertionLUT->rend() && jobCtr < maxJobs; ++it) {
                    for (const auto &s : *it->getBaseOutputs())
                        sensors.push_back(boost::property_tree::ptree::value_type("", boost::property_tree::ptree(s->getName())));
                    units.add_child(*it->getName(), sensors);
                    jobCtr++;
                }
                root.add_child(_name, units);
                boost::property_tree::write_json(data, root, true);
            } else {
                for (auto it = _insertionLUT->rbegin(); it != _insertionLUT->rend() && jobCtr < maxJobs; ++it) {
                    for (const auto &s : *it->getBaseOutputs())
                        data << *it->getName() << "::" << s->getMqtt() << "\n";
                    jobCtr++;
                }
            }
            _mapAccess.store(false);
        } else
            throw invalid_argument("Unknown plugin action " + action + " requested!");
        restResponse_t resp;
        resp.data = data.str();
        return  resp;
    }

    /**
    * @brief              Adds an unit to this analyzer
    *
    * @param u            Shared pointer to a UnitInterface object
    */
    virtual void addUnit(UnitPtr u)  override {
        // Since the AnalyzerInterface method accepts UnitInterface objects, we must cast the input argument
        // to its actual type, which is UnitTemplate<S>
        if (U_Ptr dUnit = dynamic_pointer_cast< UnitTemplate<S> >(u)) {
            _units.push_back(dUnit);
            _baseUnits.push_back(u);
        }
        else
            LOG(error) << "Analyzer " << _name << ": Type mismatch when storing output sensor! Sensor omitted";
    }
    
    /**
    * @brief              Returns the units of this analyzer
    *
    *                     The units returned by this method are of the UnitInterface type. The actual units, in their
    *                     derived type, are used internally. This type of analyzer employs dynamic units that are
    *                     generated at runtime: as such, lock-free access to the units that have been modified
    *                     recently has to be guaranteed. If the pop parameter is true, recently-modified units
    *                     will be popped from an internal spsc queue, and returned. This mode is to be used when
    *                     retrieving new data to be sent. If pop=false, this method will return an empty vector, as
    *                     job analyzers do not have permanent units.
    *
    * @param pop          If the analyzer stores units dynamically as they are modified, these will be returned too 
    * @return             The vector of UnitInterface objects of this analyzer
    */
    virtual vector<UnitPtr>& getUnits(bool pop=false) override	{
        if(pop) {
            _baseUnits.clear();
            _units.clear();
            unordered_set<string> unitSet;
            U_Ptr u;
            while(_jobUnitsQueue.pop(u))
                if(unitSet.insert(u->getName()))
                    addUnit(u);
            return _baseUnits;
        } else
            return _dummyBaseUnits;
    }

    /**
    * @brief              Clears all the units contained in this analyzer
    */
    virtual void clearUnits() override { _units.clear(); _baseUnits.clear(); _unitID = -1; }

    /**
    * @brief              Starts this analyzer
    */
    virtual void start() override {
        if(_keepRunning) {
            LOG(info) << "Analyzer " << _name << " already running.";
            return;
        } else if(!_streaming) {
            LOG(error) << "On-demand analyzer " << _name << " cannot be started.";
            return;
        }

        _keepRunning = 1;
        _pendingTasks++;
        _timer->async_wait(bind(&AnalyzerTemplate<S>::computeAsync, this));
        if(_delayInterval == 0)
            LOG(info) << "Analyzer " << _name << " started.";
        else
            LOG(info) << "Analyzer " << _name << " will be started after a delay of " << _delayInterval << " seconds.";
    }

    /**
    * @brief              Stops this analyzer
    */
    virtual void stop() override {
        if(_keepRunning == 0) {
            LOG(info) << "Analyzer " << _name << " already stopped.";
            return;
        } else if(!_streaming) {
            LOG(error) << "On-demand analyzer " << _name << " cannot be stopped.";
            return;
        }

        _keepRunning = 0;
        wait();
        LOG(info) << "Analyzer " << _name << " stopped.";
    }

    /**
    * @brief              Initializes this analyzer
    *
    * @param io           Boost ASIO service to be used
    */
    virtual void init(boost::asio::io_service& io) override { 
        AnalyzerInterface::init(io); 
        _jobUnitsQueue.reset(new boost::lockfree::spsc_queue<U_Ptr>(_unitCacheLimit));
    }

    /**
    * @brief              Performs an on-demand compute task
    *
    *                     Unlike the protected computeAsync and compute methods, computeOnDemand allows to interactively
    *                     perform data analytics queries on the analyzer, which must have the _streaming attribute set
    *                     to false. A unit is generated on the fly, corresponding to the input node given as input,
    *                     and results are returned in the form of a map.
    *
    * @param node         Unit name for which the query must be performed
    * @return             a map<string, reading_t> containing the output of the query
    */
    virtual map<string, reading_t> computeOnDemand(const string& node="__root__") override {
        map<string, reading_t> outMap;
        if( !_streaming ) {
            try {
                // Getting exclusive access to the analyzer
                while( _onDemandLock.exchange(true) ) {}
                uint32_t jobId = MQTTChecker::topicToJob(node);
                vector<qeJobData>* buf = _queryEngine.queryJob(jobId, 0, 0, _jobDataVec, true, false);
                if(buf) _jobDataVec = buf;
                if(buf && !buf->empty()) {
                    U_Ptr jobUnit = jobDataToUnit(buf[0]);

                    compute(jobUnit);
                    for (const auto &o : jobUnit->getOutputs()) {
                        outMap.insert(make_pair(o->getName(), o->getLatestValue()));
                        o->clearReadingQueue();
                    }
                } else
                    throw std::runtime_error("Analyzer " + _name + ": cannot retrieve job data!");
            } catch(const exception& e) {
                _onDemandLock.store(false);
                throw;
            }
            _onDemandLock.store(false);
        } else if( _keepRunning ) {
            bool found = false;
            while( _mapAccess.exchange(true) ) {}
            for(const auto& kv : _unitCache)
                if(kv.first == node) {
                    found = true;
                    for(const auto& o : kv.second->getBaseOutputs())
                        outMap.insert(make_pair(o->getName(), o->getLatestValue()));
                }
            _mapAccess.store(false);

            if(!found)
                throw std::domain_error("Job " + node + " does not belong to the domain of " + _name + "!");
        } else
            throw std::runtime_error("Analyzer " + _name + ": not available for on-demand query!");
        return outMap;
    }

    /**
    * @brief              Adds an unit to the internal cache of units
    *
    *                     The cache is used to speed up response times to queries of on-demand analyzers, and reduce
    *                     overall overhead. The cache has a limited size: once this size is reached, at every insertion
    *                     the oldest entry in the cache is removed.
    *
    * @param unit         Shared pointer to the Unit objecy to be added to the cache
    */
    void addToUnitCache(U_Ptr unit) {
        if (!_unitCache) {
            _unitCache = new map<string, U_Ptr>();
            _insertionLUT = new map<uint64_t, U_Ptr>();
        }

        if (_unitCache->size() >= _unitCacheLimit) {
            U_Ptr oldest = _insertionLUT->begin()->second;
            _unitCache->erase(oldest->getName());
        }
        _unitCache->insert(make_pair(unit->getName(), unit));
        // The template unit must never be deleted, even if the cache is full; therefore, we omit its entry from
        // the insertion time LUT, so that it is never picked for deletion
        if (unit->getName() != SensorNavigator::templateKey)
            _insertionLUT->insert(make_pair(getTimestamp(), unit));
    }

protected:

    /**
    * @brief              Returns the timestamp associated with the next compute task
    *
    *                     If the sync option is enabled, the timestamp will be adjusted to be synchronized with the
    *                     other sensor readings.
    *
    * @return             Timestamp of the next compute task
    */
    uint64_t nextReadingTime() {
        uint64_t now = getTimestamp();
        uint64_t next;
        if (_sync) {
            uint64_t interval64 = static_cast<uint64_t>(_interval);
            uint64_t now_ms = now / 1000 / 1000;
            uint64_t waitToStart = interval64 - (now_ms%interval64); //synchronize all measurements with other sensors
            if(!waitToStart ){ // less than 1 ms seconds is too small, so we wait the entire interval for the next measurement
                return (now_ms + interval64)*1000*1000;
            }
            return (now_ms + waitToStart)*1000*1000;
        } else {
            return now + MS_TO_NS(_interval);
        }
    }

    /**
     * @brief           This method encapsulates all logic to generate and manage job units
     * 
     *                  The algorithm implemented in this method is very similar to that used in computeOnDemand in
     *                  AnalyzerTemplate, and it is used to manage job units both in on-demand and streaming mode. The
     *                  internal unit cache is used to store recent job units. Moreover, the job data returned by the
     *                  QueryEngine is converted to a format compatible with the UnitGenerator.
     * 
     * @param jobData   a qeJobData struct containing job information
     * @return          A shared pointer to a job unit object
     */
    virtual U_Ptr jobDataToUnit(qeJobData& jobData) {
        string jobTopic = MQTTChecker::jobToTopic(jobData.jobId);
        U_Ptr jobUnit = nullptr;
        if(!_unitCache)
            throw std::runtime_error("Initialization error in analyzer " + _name + "!");

        if (_unitCache->count(jobTopic)) {
            jobUnit = _unitCache->at(jobTopic);
            LOG(debug) << "Analyzer " << _name << ": cache hit for unit " << jobTopic << ".";
            
        } else {
            if (!_unitCache->count(SensorNavigator::templateKey))
                throw std::runtime_error("No template unit in analyzer " + _name + "!");
            LOG(debug) << "Analyzer " << _name << ": cache miss for unit " << jobTopic << ".";
            U_Ptr uTemplate = _unitCache->at(SensorNavigator::templateKey);
            shared_ptr<SensorNavigator> navi = _queryEngine.getNavigator();
            UnitGenerator<S> unitGen(navi);
            vector<string> nodes;
            for (const auto &n : jobData.nodes)
                nodes.push_back(translateNodeName(n));
            jobUnit = unitGen.generateJobUnit(jobTopic, nodes, uTemplate->getInputs(), uTemplate->getOutputs(), uTemplate->getInputMode(), jobTopic, _relaxed);

            // Initializing sensors if necessary
            for (const auto s : jobUnit->getOutputs())
                if (!s->isInit())
                    s->initSensor(_cacheSize);

            // Spinlock to regulate access to the internal unit map - normally innocuous
            while( _mapAccess.exchange(true) ) {}
            addToUnitCache(jobUnit);
            _mapAccess.store(false);
        }
        return jobUnit;
    }
    
    /**
     * @brief             Translates a node name as returned by the resource manager to an internal representation
     * 
     *                    The external node name is usually just the hostname associated to the machine. This 
     *                    representation usually needs to be converted to an internal one that reflects the hierarchy
     *                    described by the sensor navigator. Since this logic is sytem-dependent, users can freely
     *                    override this method.
     * 
     * @param n           Raw node hostname
     * @return            Converted sensor navigator-friendly node name
     */
    virtual string translateNodeName(string n) { return n; }
    
    /**
    * @brief              Performs a compute task
    *
    *                     This method is tasked with scheduling the next compute task, and invoking the internal
    *                     compute() method, which encapsulates the real logic of the analyzer. The compute method
    *                     is automatically called over units as required by the Analyzer's configuration.
    *                     
    *                     In the case of job analyzers, this method will also automatically retrieve the list of jobs
    *                     that were running in the last interval. One unit for each of them is instantiated (or 
    *                     retrieved from the local unit cache, if available) and then the compute phase starts.
    *
    */
    virtual void computeAsync() override {
        if(_delayInterval > 0) {
            sleep(_delayInterval);
            _delayInterval = 0;
            LOG(info) << "Analyzer " + _name + ": starting computation after delayed start!";
        }

        try {
            vector<qeJobData>* buf = _queryEngine.queryJob(0, _interval * 1000000, 0, _jobDataVec, true, true);
            if(buf) {
                _jobDataVec = buf;
                for(const auto& job : *_jobDataVec) {
                    U_Ptr jobUnit = jobDataToUnit(job);
                    compute(jobUnit);
                    _jobUnitsQueue->push(jobUnit);
                }
            }
            else
                LOG(error) << "Analyzer " + _name + ": cannot retrieve job data!";
        } catch(const exception& e) {
            LOG(error) << "Analyzer " + _name + ": internal error " + e.what() + " during computation!";
        }

        if (_timer && _keepRunning) {
            _timer->expires_at(timestamp2ptime(nextReadingTime()));
            _pendingTasks++;
            _timer->async_wait(bind(&JobAnalyzerTemplate::computeAsync, this));
        }
        _pendingTasks--;
    }

    /**
    * @brief              Data analytics computation logic
    *
    *                     This method contains the actual logic used by the analyzed, and is automatically called by
    *                     the computeAsync method.
    *
    * @param unit         Shared pointer to unit to be processed
    */
    virtual void compute(U_Ptr unit) = 0;

    // Cache for frequently used units in ondemand and job modes
    map<string, U_Ptr>* _unitCache;
    // Helper map to keep track of the cache insertion times
    map<uint64_t, U_Ptr>* _insertionLUT;
    // Vector of pointers to the internal units
    vector<U_Ptr>   _units;
    // Vector of pointers to the internal units, casted to UnitInterface - only efficient way to do this in C++
    // unless we use raw arrays
    vector<UnitPtr> _baseUnits;
    // Instance of a QueryEngine object to get sensor data
    QueryEngine&    _queryEngine;
    // Queue of recently-modified units that is periodically emptied when messages are pushed
    std::unique_ptr<boost::lockfree::spsc_queue<U_Ptr>> _jobUnitsQueue;
    // Spinlock used to regulate access to the internal units map, for "visualization" purposes
    atomic<bool> _mapAccess;
    // Dummy vector used to hide dynamic units in getUnits, while avoiding heap allocations
    // It is quite ugly, but it is also the most convenient way to achieve this
    vector<UnitPtr> _dummyBaseUnits;
    // Vector of job data structures used to retrieve job data at runtime
    vector<qeJobData>* _jobDataVec;
    

};

#endif //PROJECT_JOBANALYZERTEMPLATE_H