JobOperatorTemplate.h 15.1 KB
Newer Older
1
//================================================================================
2
// Name        : JobOperatorTemplate.h
3
// Author      : Alessio Netti
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
5
// Copyright   : Leibniz Supercomputing Centre
6
// Description : Template implementing features needed by Operators.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//================================================================================

//================================================================================
// 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.
//================================================================================

28
29
#ifndef PROJECT_JOBOPERATORTEMPLATE_H
#define PROJECT_JOBOPERATORTEMPLATE_H
30

31
#include "OperatorTemplate.h"
32
33

/**
34
35
 * @brief Template that implements features needed by Job Operators and
 *        complying to OperatorInterface.
36
 *
37
 * @details This template is derived from OperatorTemplate, and is adjusted to
38
 *          simplify job-related computations.
39
 *
40
 * @ingroup operator
41
42
 */
template <typename S>
43
class JobOperatorTemplate : virtual public OperatorTemplate<S> {
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    // 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
    *
58
    * @param name       Name of the operator
59
    */
60
61
    JobOperatorTemplate(const string name) :
            OperatorTemplate<S>(name),
62
63
            _jobDataVec(nullptr) {
        
64
        _unitAccess.store(false);
65
        this->_dynamic = true;
66
67
68
69
70
71
    }

    /**
    * @brief            Copy constructor
    *
    */
72
73
    JobOperatorTemplate(const JobOperatorTemplate& other) :
            OperatorTemplate<S>(other),
74
75
            _jobDataVec(nullptr) {
        
76
        _unitAccess.store(false);
77
        this->_dynamic = true;
78
79
80
81
82
83
    }

    /**
    * @brief            Assignment operator
    *
    */
84
85
    JobOperatorTemplate& operator=(const JobOperatorTemplate& other) {
        OperatorTemplate<S>::operator=(other);
86
        _jobDataVec = nullptr;
87
        this->_dynamic = true;
88
        return *this;
89
90
91
92
93
    }
            
    /**
    * @brief            Class destructor
    */
94
    virtual ~JobOperatorTemplate() {
95
96
97
        if(_jobDataVec)
            delete _jobDataVec;
    }
98
    
99
    /**
100
    * @brief              Returns the units of this operator
101
102
    *
    *                     The units returned by this method are of the UnitInterface type. The actual units, in their
103
    *                     derived type, are used internally. This type of operator employs dynamic units that are
104
105
    *                     generated at runtime: as such, an internal unit lock is acquired upon calling this method,
    *                     and must later be released through the releaseUnits() method.
106
    *
107
    * @return             The vector of UnitInterface objects of this operator
108
    */
109
110
111
112
113
114
115
116
117
118
119
    virtual vector<UnitPtr>& getUnits() override	{
        // Spinlock to regulate access to units - normally innocuous
        while(_unitAccess.exchange(true)) {}
        return this->_baseUnits;
    }
    
    /**
     * @brief             Releases the access lock to units
     * 
     *                    This method must be called anytime operations on units are performed through getUnits().
     */
120
    virtual void releaseUnits() override {
121
        _unitAccess.store(false);
122
    }
123
    
124
125
126
127
    /**
    * @brief              Performs an on-demand compute task
    *
    *                     Unlike the protected computeAsync and compute methods, computeOnDemand allows to interactively
128
    *                     perform data analytics queries on the operator, which must have the _streaming attribute set
129
130
131
132
133
134
135
136
    *                     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;
137
        if( !this->_streaming ) {
138
            try {
139
                // Getting exclusive access to the operator
140
                while( this->_onDemandLock.exchange(true) ) {}
141
                uint32_t jobId = MQTTChecker::topicToJob(node);
142
143
                if(_jobDataVec)
                    _jobDataVec->clear();
144
                vector<qeJobData>* buf = this->_queryEngine.queryJob(jobId, 0, 0, _jobDataVec, true, false);
145
146
                if(buf) _jobDataVec = buf;
                if(buf && !buf->empty()) {
147
                    U_Ptr jobUnit = jobDataToUnit(_jobDataVec->at(0));
148

149
                    this->compute(jobUnit, _jobDataVec->at(0));
150
151
152
153
                    for (const auto &o : jobUnit->getOutputs()) {
                        outMap.insert(make_pair(o->getName(), o->getLatestValue()));
                        o->clearReadingQueue();
                    }
154
155
156
157
158
159
160
                    if(this->_flatten) {
                        for (const auto& su : jobUnit->getSubUnits())
                            for (const auto &o : su->getOutputs()) {
                                outMap.insert(make_pair(o->getName(), o->getLatestValue()));
                                o->clearReadingQueue();
                            }
                    }
161
                } else
162
                    throw std::runtime_error("Operator " + this->_name + ": cannot retrieve job data!");
163
            } catch(const exception& e) {
164
                this->_onDemandLock.store(false);
165
166
                throw;
            }
167
168
            this->_onDemandLock.store(false);
        } else if( this->_keepRunning ) {
169
            bool found = false;
170
171
172
            //Spinning explicitly as we need to iterate on the derived Unit objects
            while(_unitAccess.exchange(true)) {}
            for(const auto& u : this->_units)
173
                if(u->getName() == node) {
174
                    found = true;
175
                    for(const auto& o : u->getBaseOutputs())
176
                        outMap.insert(make_pair(o->getName(), o->getLatestValue()));
177
178
179
180
181
                    if(this->_flatten) {
                        for (const auto& su : u->getSubUnits())
                            for (const auto &o : su->getOutputs())
                                outMap.insert(make_pair(o->getName(), o->getLatestValue()));
                    }
182
                }
183
            releaseUnits();
184
185

            if(!found)
186
                throw std::domain_error("Job " + node + " does not belong to the domain of " + this->_name + "!");
187
        } else
188
            throw std::runtime_error("Operator " + this->_name + ": not available for on-demand query!");
189
190
        return outMap;
    }
191
    
192
protected:
193
    
194
    using OperatorTemplate<S>::compute;
195
196
197
198
199
    
    /**
    * @brief              Data analytics (job) computation logic
    *
    *                     This method contains the actual logic used by the analyzed, and is automatically called by
200
201
    *                     the computeAsync method. This variant of the compute() method defined in OperatorTemplate also
    *                     includes a job data structure in its list of arguments, and is specialized for job operators.
202
203
204
205
206
207
    *
    * @param unit         Shared pointer to unit to be processed
    * @param jobData      Job data structure 
    */
    virtual void compute(U_Ptr unit, qeJobData& jobData) = 0;
    
208
209
210
211
    /**
     * @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
212
     *                  OperatorTemplate, and it is used to manage job units both in on-demand and streaming mode. The
213
214
215
216
217
218
     *                  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
     */
219
    virtual U_Ptr jobDataToUnit(const qeJobData& jobData) {
220
221
        string jobTopic = MQTTChecker::jobToTopic(jobData.jobId);
        U_Ptr jobUnit = nullptr;
222
        if(!this->_unitCache)
223
            throw std::runtime_error("Initialization error in operator " + this->_name + "!");
224

225
226
        if (this->_unitCache->count(jobTopic)) {
            jobUnit = this->_unitCache->at(jobTopic);
227
            if(!this->_streaming)
228
                LOG(debug) << "Operator " << this->_name << ": cache hit for unit " << jobTopic << ".";
229
230
            
        } else {
231
            if (!this->_unitCache->count(SensorNavigator::templateKey))
232
                throw std::runtime_error("No template unit in operator " + this->_name + "!");
233
            if(!this->_streaming)
234
                LOG(debug) << "Operator " << this->_name << ": cache miss for unit " << jobTopic << ".";
235
236
            U_Ptr uTemplate = this->_unitCache->at(SensorNavigator::templateKey);
            shared_ptr<SensorNavigator> navi = this->_queryEngine.getNavigator();
237
238
239
240
            UnitGenerator<S> unitGen(navi);
            vector<string> nodes;
            for (const auto &n : jobData.nodes)
                nodes.push_back(translateNodeName(n));
241
242
243
244
            // The job unit is generated as a hierarchical unit with the top level unit and the sub-units having
            // the same set of output sensors
            jobUnit = unitGen.generateHierarchicalUnit(jobTopic, nodes, uTemplate->getOutputs(), uTemplate->getInputs(), 
                      uTemplate->getOutputs(), uTemplate->getInputMode(), jobTopic, this->_relaxed);
245
246

            // Initializing sensors if necessary
247
            jobUnit->init(this->_cacheSize, this->_flatten);
248
            this->addToUnitCache(jobUnit);
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
        }
        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
     */
264
    virtual string translateNodeName(string n) { return MQTTChecker::formatTopic(n) + std::string(1, MQTT_SEP); }
265
266
267
268
269
    
    /**
    * @brief              Performs a compute task
    *
    *                     This method is tasked with scheduling the next compute task, and invoking the internal
270
271
    *                     compute() method, which encapsulates the real logic of the operator. The compute method
    *                     is automatically called over units as required by the operator's configuration.
272
    *                     
273
    *                     In the case of job operators, this method will also automatically retrieve the list of jobs
274
275
276
277
278
    *                     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 {
279
280
281
        if(this->_delayInterval > 0) {
            sleep(this->_delayInterval);
            this->_delayInterval = 0;
282
            LOG(info) << "Operator " + this->_name + ": starting computation after delayed start!";
283
284
285
        }

        try {
286
287
            if(_jobDataVec)
                _jobDataVec->clear();
288
            vector<qeJobData>* buf = this->_queryEngine.queryJob(0, this->_interval * 1000000, 0, _jobDataVec, true, true);
289
290
            if(buf) {
                _jobDataVec = buf;
291
292
                _tempUnits.clear();
                // Producing units from the job data, discarding invalid jobs in the process
293
                for(const auto& job : *_jobDataVec) {
294
295
                    try {
                        _tempUnits.push_back(jobDataToUnit(job));
296
297
298
299
                    } catch(const invalid_argument& e2) { 
                        LOG(error) << e2.what(); 
                        _tempUnits.push_back(nullptr); 
                        continue; }
300
                }
301
302
                
                // Performing actual computation on each unit
303
304
305
                for(size_t idx=0; idx<_tempUnits.size(); idx++)
                    if(_tempUnits[idx])
                        this->compute(_tempUnits[idx], _jobDataVec->at(idx));
306
307
308
309
                // Acquiring the spinlock to refresh the exposed units
                while(_unitAccess.exchange(true)) {}
                this->clearUnits();
                for(const auto& ju : _tempUnits)
310
                    if(ju) {
311
                        this->addUnit(ju);
312
313
314
315
316
                        if(this->_flatten) {
                            for (const auto& su : ju->getSubUnits())
                                this->addUnit(su);
                        }
                    }
317
318
                _unitAccess.store(false);
                _tempUnits.clear();
319
320
            }
            else
321
                LOG(error) << "Operator " + this->_name + ": cannot retrieve job data!";
322
        } catch(const exception& e) {
323
            LOG(error) << "Operator " + this->_name + ": internal error " + e.what() + " during computation!";
324
            _unitAccess.store(false);
325
326
        }

327
328
329
        if (this->_timer && this->_keepRunning) {
            this->_timer->expires_at(timestamp2ptime(this->nextReadingTime()));
            this->_pendingTasks++;
330
            this->_timer->async_wait(bind(&JobOperatorTemplate::computeAsync, this));
331
        }
332
        this->_pendingTasks--;
333
    }
334
    
335
336
    // Vector of recently-modified units
    vector<U_Ptr> _tempUnits;
337
    // Spinlock used to regulate access to the internal units map, for "visualization" purposes
338
    atomic<bool> _unitAccess;
339
340
    // Vector of job data structures used to retrieve job data at runtime
    vector<qeJobData>* _jobDataVec;
341
342
    // Logger object
    boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
343
344
345
346
    

};

347
#endif //PROJECT_JOBOPERATORTEMPLATE_H