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
// Copyright (C) 2013-2020 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>
#include <util/state_model.h>
#include <string><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

namespace isc {
namespace util {

/********************************** State *******************************/

State::State(const int value, const std::string& label, StateHandler handler,
             const StatePausing& state_pausing)
    : LabeledValue(value, label), handler_(handler), pausing_(state_pausing),
      was_paused_(false) {
}

State::~State() {
}

void
State::run() {
    (handler_)();
}

bool
State::shouldPause() {
    if ((pausing_ == STATE_PAUSE_ALWAYS) ||
        ((pausing_ == STATE_PAUSE_ONCE) && (!was_paused_))) {
        was_paused_ = true;
        return (true);
    }
    return (false);
}

/********************************** StateSet *******************************/

StateSet::StateSet() {
}

StateSet::~StateSet() {
}

void
StateSet::add(const int value, const std::string& label, StateHandler handler,
              const StatePausing& state_pausing) {
    try {
        LabeledValueSet::add(LabeledValuePtr(new State(value, label, handler,
                                                       state_pausing)));
    } catch (const std::exception& ex) {
        isc_throw(StateModelError, "StateSet: cannot add state :" << ex.what());
    }

}

const StatePtr
StateSet::getState(int value) {
    if (!isDefined(value)) {
        isc_throw(StateModelError," StateSet: state is undefined");
    }

    // Since we have to use dynamic casting, to get a state pointer
    // we can't return a reference.
    StatePtr state = boost::dynamic_pointer_cast<State>(get(value));
    return (state);
}

/********************************** StateModel *******************************/


// Common state model states
const int StateModel::NEW_ST;
const int StateModel::END_ST;

const int StateModel::SM_DERIVED_STATE_MIN;

// Common state model events
const int StateModel::NOP_EVT;
const int StateModel::START_EVT;
const int StateModel::END_EVT;
const int StateModel::FAIL_EVT;

const int StateModel::SM_DERIVED_EVENT_MIN;

StateModel::StateModel() : events_(), states_(), dictionaries_initted_(false),
                           curr_state_(NEW_ST), prev_state_(NEW_ST),
                           last_event_(NOP_EVT), next_event_(NOP_EVT),
                           on_entry_flag_(false), on_exit_flag_(false),
                           paused_(false), mutex_(new std::mutex) {
}

StateModel::~StateModel(){
}

void
StateModel::startModel(const int start_state) {
    // Initialize dictionaries of events and states.
    initDictionaries();

    // Set the current state to starting state and enter the run loop.
    setState(start_state);

    // Start running the model.
    runModel(START_EVT);
}

void
StateModel::runModel(unsigned int run_event) {
    /// If the dictionaries aren't built bail out.
    if (!dictionaries_initted_) {
        abortModel("runModel invoked before model has been initialized");
    }

    try {
        // Seed the loop with the given event as the next to process.
        postNextEvent(run_event);
        do {
            // Invoke the current state's handler.  It should consume the
            // next event, then determine what happens next by setting
            // current state and/or the next event.
            getState(curr_state_)->run();

            // Keep going until a handler sets next event to a NOP_EVT.
        } while (!isModelDone() && getNextEvent() != NOP_EVT);
    } catch (const std::exception& ex) {
        // The model has suffered an unexpected exception. This constitutes
        // a model violation and indicates a programmatic shortcoming.
        // In theory, the model should account for all error scenarios and
        // deal with them accordingly.  Transition to END_ST with FAILED_EVT
        // via abortModel.
        abortModel(ex.what());
    }
}

void
StateModel::nopStateHandler() {
}

void
StateModel::initDictionaries() {
    std::lock_guard<std::mutex> lock(*mutex_);
    if (dictionaries_initted_) {
        isc_throw(StateModelError, "Dictionaries already initialized");
    }
    // First let's build and verify the dictionary of events.
    try {
        defineEvents();
        verifyEvents();
    } catch (const std::exception& ex) {
        isc_throw(StateModelError, "Event set is invalid: " << ex.what());
    }

    // Next let's build and verify the dictionary of states.
    try {
        defineStates();
        verifyStates();
    } catch (const std::exception& ex) {
        isc_throw(StateModelError, "State set is invalid: " << ex.what());
    }

    // Record that we are good to go.
    dictionaries_initted_ = true;
}

void
StateModel::defineEvent(unsigned int event_value, const std::string& label) {
    if (!isModelNewInternal()) {
        // Don't allow for self-modifying models.
        isc_throw(StateModelError, "Events may only be added to a new model."
                   << event_value << " - " << label);
    }

    // Attempt to add the event to the set.
    try {
        events_.add(event_value, label);
    } catch (const std::exception& ex) {
        isc_throw(StateModelError, "Error adding event: " << ex.what());
    }
}

const EventPtr&
StateModel::getEvent(unsigned int event_value) {
    if (!events_.isDefined(event_value)) {
        isc_throw(StateModelError,
                  "Event value is not defined:" << event_value);
    }

    return (events_.get(event_value));
}

void
StateModel::defineState(unsigned int state_value, const std::string& label,
                        StateHandler handler, const StatePausing& state_pausing) {
    if (!isModelNewInternal()) {
        // Don't allow for self-modifying maps.
        isc_throw(StateModelError, "States may only be added to a new model."
                   << state_value << " - " << label);
    }

    // Attempt to add the state to the set.
    try {
        states_.add(state_value, label, handler, state_pausing);
    } catch (const std::exception& ex) {
        isc_throw(StateModelError, "Error adding state: " << ex.what());
    }
}

const StatePtr
StateModel::getState(unsigned int state_value) {
    std::lock_guard<std::mutex> lock(*mutex_);
    return getStateInternal(state_value);
}

const StatePtr
StateModel::getStateInternal(unsigned int state_value) {
    if (!states_.isDefined(state_value)) {
        isc_throw(StateModelError,
                  "State value is not defined:" << state_value);
    }

    return (states_.getState(state_value));
}

void
StateModel::defineEvents() {
    defineEvent(NOP_EVT, "NOP_EVT");
    defineEvent(START_EVT, "START_EVT");
    defineEvent(END_EVT, "END_EVT");
    defineEvent(FAIL_EVT, "FAIL_EVT");
}

void
StateModel::verifyEvents() {
    getEvent(NOP_EVT);
    getEvent(START_EVT);
    getEvent(END_EVT);
    getEvent(FAIL_EVT);
}

void
StateModel::defineStates() {
    defineState(NEW_ST, "NEW_ST",
                std::bind(&StateModel::nopStateHandler, this));
    defineState(END_ST, "END_ST",
                std::bind(&StateModel::nopStateHandler, this));
}

void
StateModel::verifyStates() {
    getStateInternal(NEW_ST);
    getStateInternal(END_ST);
}

void
StateModel::onModelFailure(const std::string&) {
    // Empty implementation to make deriving classes simpler.
}

void
StateModel::transition(unsigned int state, unsigned int event) {
    std::lock_guard<std::mutex> lock(*mutex_);
    setStateInternal(state);
    postNextEventInternal(event);
}

void
StateModel::endModel() {
    transition(END_ST, END_EVT);
}

void
StateModel::unpauseModel() {
    std::lock_guard<std::mutex> lock(*mutex_);
    paused_ = false;
}

void
StateModel::abortModel(const std::string& explanation) {
    transition(END_ST, FAIL_EVT);

    std::ostringstream stream ;
    stream << explanation << " : " << getContextStr();
    onModelFailure(stream.str());
}

void
StateModel::setState(unsigned int state) {
    std::lock_guard<std::mutex> lock(*mutex_);
    setStateInternal(state);
}

void
StateModel::setStateInternal(unsigned int state) {
    if (state != END_ST && !states_.isDefined(state)) {
        isc_throw(StateModelError,
                  "Attempt to set state to an undefined value: " << state );
    }

    prev_state_ = curr_state_;
    curr_state_ = state;

    // Set the "do" flags if we are transitioning.
    on_entry_flag_ = ((state != END_ST) && (prev_state_ != curr_state_));

    // At this time they are calculated the same way.
    on_exit_flag_ = on_entry_flag_;

    // If we're entering the new state we need to see if we should
    // pause the state model in this state.
    if (on_entry_flag_ && !paused_ && getStateInternal(state)->shouldPause()) {
        paused_ = true;
    }
}

void
StateModel::postNextEvent(unsigned int event_value) {
    std::lock_guard<std::mutex> lock(*mutex_);
    postNextEventInternal(event_value);
}

void
StateModel::postNextEventInternal(unsigned int event_value) {
    // Check for FAIL_EVT as special case of model error before events are
    // defined.
    if (event_value != FAIL_EVT && !events_.isDefined(event_value)) {
        isc_throw(StateModelError,
                  "Attempt to post an undefined event, value: " << event_value);
    }

    last_event_ = next_event_;
    next_event_ = event_value;
}

bool
StateModel::doOnEntry() {
    std::lock_guard<std::mutex> lock(*mutex_);
    bool ret = on_entry_flag_;
    on_entry_flag_ = false;
    return (ret);
}

bool
StateModel::doOnExit() {
    std::lock_guard<std::mutex> lock(*mutex_);
    bool ret = on_exit_flag_;
    on_exit_flag_ = false;
    return (ret);
}

unsigned int
StateModel::getCurrState() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return (curr_state_);
}

unsigned int
StateModel::getPrevState() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return (prev_state_);
}

unsigned int
StateModel::getLastEvent() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return (last_event_);
}

unsigned int
StateModel::getNextEvent() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return (next_event_);
}

bool
StateModel::isModelNew() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return isModelNewInternal();
}

bool
StateModel::isModelNewInternal() const {
    return (curr_state_ == NEW_ST);
}

bool
StateModel::isModelRunning() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return ((curr_state_ != NEW_ST) && (curr_state_ != END_ST));
}

bool
StateModel::isModelWaiting() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return ((curr_state_ != NEW_ST) && (curr_state_ != END_ST) &&
            (next_event_ == NOP_EVT));
}

bool
StateModel::isModelDone() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return (curr_state_ == END_ST);
}

bool
StateModel::didModelFail() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return ((curr_state_ == END_ST) && (next_event_ == FAIL_EVT));
}

bool
StateModel::isModelPaused() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return (paused_);
}

std::string
StateModel::getStateLabel(const int state) const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return getStateLabelInternal(state);
}

std::string
StateModel::getStateLabelInternal(const int state) const {
    return (states_.getLabel(state));
}

std::string
StateModel::getEventLabel(const int event) const {
    std::lock_guard<std::mutex> lock(*mutex_);
    return getEventLabelInternal(event);
}

std::string
StateModel::getEventLabelInternal(const int event) const {
    return (events_.getLabel(event));
}

std::string
StateModel::getContextStr() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    std::ostringstream stream;
    stream << "current state: [ "
            << curr_state_ << " " << getStateLabelInternal(curr_state_)
            << " ] next event: [ "
            << next_event_ << " " << getEventLabelInternal(next_event_) << " ]";
    return (stream.str());
}

std::string
StateModel::getPrevContextStr() const {
    std::lock_guard<std::mutex> lock(*mutex_);
    std::ostringstream stream;
    stream << "previous state: [ "
           << prev_state_ << " " << getStateLabelInternal(prev_state_)
           << " ] last event: [ "
           << next_event_ << " " << getEventLabelInternal(last_event_) << " ]";
    return (stream.str());
}

} // namespace isc::util
} // namespace isc