EvBStateMachine.h 12.9 KB
Newer Older
1
2
3
#ifndef _evb_StateMachine_h_
#define _evb_StateMachine_h_

4
#include <boost/interprocess/permissions.hpp>
5
#include <boost/interprocess/sync/named_semaphore.hpp>
6
7
8
9
10
11
12
13
#include <boost/statechart/event_base.hpp>
#include <boost/statechart/state.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>

#include "evb/Exception.h"
#include "evb/InfoSpaceItems.h"
14
15
#include "log4cplus/logger.h"
#include "log4cplus/loggingmacros.h"
16
17
18
19
20
#include "xcept/tools.h"
#include "xdaq/Application.h"
#include "xdaq2rc/RcmsStateNotifier.h"
#include "xdata/String.h"

21
#include <regex>
22
23
24
25
26
27
28
29
30
31
32
33
#include <string>


namespace evb {

  ///////////////////
  // Public events //
  ///////////////////
  class Configure : public boost::statechart::event<Configure> {};
  class Halt : public boost::statechart::event<Halt> {};
  class Enable : public boost::statechart::event<Enable> {};
  class Stop : public boost::statechart::event<Stop> {};
34
  class Clear : public boost::statechart::event<Clear> {};
35
36
37
38
39

  ////////////////////////////////
  // Internal transition events //
  ////////////////////////////////

40
  class StartConfigure: public boost::statechart::event<StartConfigure> {};
41
42
  class ConfigureDone: public boost::statechart::event<ConfigureDone> {};
  class DrainingDone: public boost::statechart::event<DrainingDone> {};
43
  class ClearingDone: public boost::statechart::event<ClearingDone> {};
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

  class Fail : public boost::statechart::event<Fail>
  {
  public:
    Fail(xcept::Exception& exception) : exception_(exception) {};
    std::string getReason() const { return exception_.message(); }
    std::string getTraceback() const { return xcept::stdformat_exception_history(exception_); }
    xcept::Exception& getException() const { return exception_; }

  private:
    mutable xcept::Exception exception_;
  };

  struct StateName {
    virtual ~StateName() {};
    virtual std::string stateName() const = 0;
  };

  /////////////////////////////////
  // The evb state machine //
  /////////////////////////////////

  template<class MostDerived, class InitialState>
  class EvBStateMachine :
    public boost::statechart::state_machine<MostDerived,InitialState>
  {

  public:

    EvBStateMachine(xdaq::Application*);

    void processSoapEvent(const std::string& event, std::string& newStateName);
    std::string processFSMEvent(const boost::statechart::event_base&);

    void appendConfigurationItems(InfoSpaceItems&);
    void appendMonitoringItems(InfoSpaceItems&);
    void updateMonitoringItems();

    void notifyRCMS(const std::string& stateName);
    void failEvent(const Fail&);
    void unconsumed_event(const boost::statechart::event_base&);
    log4cplus::Logger& getLogger() const { return app_->getApplicationLogger(); }

    uint32_t getRunNumber() const { return runNumber_.value_; }
88
89
    const std::string& getStateName() const { return stateName_; }
    const std::string& getReasonForError() const { return reasonForError_; }
90
    void clearError() { reasonForError_.clear(); }
91

92
    using SoapFsmEvents = std::list<std::string>;
93
94
    SoapFsmEvents getSoapFsmEvents() const { return soapFsmEvents_; }

95
96
97
    void acquireLock(const std::string& name);
    void releaseLock(const std::string& name);

98
99
100
101
102
103
  protected:

    virtual void do_processSoapEvent(const std::string& event, std::string& newStateName);

    xdaq::Application* app_;
    xdaq2rc::RcmsStateNotifier rcmsStateNotifier_;
104
    std::string reasonForError_;
105
106
107
108
109
110
111
112
113
114

    SoapFsmEvents soapFsmEvents_;

  private:

    boost::shared_mutex eventMutex_;
    boost::shared_mutex stateNameMutex_;

    xdata::UnsignedInteger32 runNumber_;
    std::string stateName_;
115
    volatile bool haveLock_;
116
117
118

    xdata::UnsignedInteger32 monitoringRunNumber_;
    xdata::String monitoringStateName_;
119
    xdata::String monitoringErrorMsg_;
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
  };


  ////////////////////////////
  // Wrapper state template //
  ////////////////////////////

  template< class MostDerived,
            class Context,
            class InnerInitial = boost::mpl::list<>,
            boost::statechart::history_mode historyMode = boost::statechart::has_no_history >
  class EvBState : public StateName,
                   public boost::statechart::state<MostDerived, Context, InnerInitial, historyMode>
  {
  public:
    std::string stateName() const
    { return stateName_; }

  protected:
139
140
    using boost_state = boost::statechart::state<MostDerived, Context, InnerInitial, historyMode>;
    using my_state = EvBState;
141
142

    EvBState(const std::string stateName, typename boost_state::my_context& c) :
143
      boost_state(c), stateName_(stateName) {};
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    virtual ~EvBState() {};

    virtual void entryAction() {};
    virtual void exitAction() {};

    const std::string stateName_;

    void safeEntryAction()
    {
      std::string msg = "Failed to enter " + stateName_ + " state";
      try
      {
        entryAction();
      }
      catch(xcept::Exception& e)
      {
        XCEPT_DECLARE_NESTED(exception::FSM,
161
                             sentinelException, msg, e);
162
163
164
165
166
167
168
        this->post_event( Fail(sentinelException) );
      }
      catch(std::exception& e)
      {
        msg += ": ";
        msg += e.what();
        XCEPT_DECLARE(exception::FSM,
169
                      sentinelException, msg );
170
171
172
173
174
175
        this->post_event( Fail(sentinelException) );
      }
      catch(...)
      {
        msg += ": unknown exception";
        XCEPT_DECLARE(exception::FSM,
176
                      sentinelException, msg );
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        this->post_event( Fail(sentinelException) );
      }
    };

    void safeExitAction()
    {
      std::string msg = "Failed to leave " + stateName_ + " state";
      try
      {
        exitAction();
      }
      catch(xcept::Exception& e)
      {
        XCEPT_DECLARE_NESTED(exception::FSM,
191
                             sentinelException, msg, e);
192
193
194
195
196
197
198
        this->post_event( Fail(sentinelException) );
      }
      catch(std::exception& e)
      {
        msg += ": ";
        msg += e.what();
        XCEPT_DECLARE(exception::FSM,
199
                      sentinelException, msg );
200
201
202
203
204
205
        this->post_event( Fail(sentinelException) );
      }
      catch(...)
      {
        msg += ": unknown exception";
        XCEPT_DECLARE(exception::FSM,
206
                      sentinelException, msg );
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        this->post_event( Fail(sentinelException) );
      }
    };

  };

} //namespace evb

////////////////////////////////////////////////////////////////////////////////
// Implementation follows                                                     //
////////////////////////////////////////////////////////////////////////////////

template<class MostDerived,class InitialState>
evb::EvBStateMachine<MostDerived,InitialState>::EvBStateMachine
(
  xdaq::Application* app
):
224
225
226
227
228
229
230
231
  app_(app),
  rcmsStateNotifier_
  (
    getLogger(),
    app->getApplicationDescriptor(),
    app->getApplicationContext()
  ),
  runNumber_(0),
232
233
  stateName_("uninitialized"),
  haveLock_(false)
234
235
236
{
  xdata::InfoSpace *is = app->getApplicationInfoSpace();
  is->fireItemAvailable("rcmsStateListener",
237
                        rcmsStateNotifier_.getRcmsStateListenerParameter() );
238
  is->fireItemAvailable("foundRcmsStateListener",
239
                        rcmsStateNotifier_.getFoundRcmsStateListenerParameter() );
240
241
242
243
244
245
246
  rcmsStateNotifier_.findRcmsStateListener();
  rcmsStateNotifier_.subscribeToChangesInRcmsStateListener(is);

  soapFsmEvents_.push_back("Configure");
  soapFsmEvents_.push_back("Halt");
  soapFsmEvents_.push_back("Enable");
  soapFsmEvents_.push_back("Stop");
247
  soapFsmEvents_.push_back("Clear");
248
249
250
251
252
253
254
255
256
257
258
  soapFsmEvents_.push_back("Fail");
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::processSoapEvent
(
  const std::string& soapEvent,
  std::string& newStateName
)
{
259
260
  LOG4CPLUS_INFO(getLogger(),"Received FSM SOAP command "+soapEvent);

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  do_processSoapEvent(soapEvent, newStateName);
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::do_processSoapEvent
(
  const std::string& soapEvent,
  std::string& newStateName
)
{
  if ( soapEvent == "Configure" )
    newStateName = processFSMEvent( Configure() );
  else if ( soapEvent == "Enable" )
    newStateName = processFSMEvent( Enable() );
  else if ( soapEvent == "Halt" )
    newStateName = processFSMEvent( Halt() );
  else if ( soapEvent == "Stop" )
    newStateName = processFSMEvent( Stop() );
280
281
  else if ( soapEvent == "Clear" )
    newStateName = processFSMEvent( Clear() );
282
283
284
  else if ( soapEvent == "Fail" )
  {
    XCEPT_DECLARE(exception::FSM,
285
                  sentinelException, "Externally requested by SOAP command" );
286
287
288
289
290
    newStateName = processFSMEvent( Fail(sentinelException) );
  }
  else
  {
    XCEPT_DECLARE(exception::FSM, sentinelException,
291
                  "Received an unknown state machine event '" + soapEvent + "'");
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
    newStateName = processFSMEvent( Fail(sentinelException) );
  }
}


template <class MostDerived,class InitialState>
std::string evb::EvBStateMachine<MostDerived,InitialState>::processFSMEvent
(
  const boost::statechart::event_base& event
)
{
  boost::unique_lock<boost::shared_mutex> eventUniqueLock(eventMutex_);
  this->process_event(event);

  boost::unique_lock<boost::shared_mutex> stateNameUniqueLock(stateNameMutex_);
  stateName_ = this->template state_cast<const StateName&>().stateName();
  return stateName_;
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::appendConfigurationItems
(
  InfoSpaceItems& params
)
{
  runNumber_ = 0;

  params.add("runNumber", &runNumber_);
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::appendMonitoringItems
(
  InfoSpaceItems& items
)
{
  monitoringRunNumber_ = 0;
  monitoringStateName_ = "Halted";
332
  monitoringErrorMsg_ = "";
333
334
335

  items.add("runNumber", &monitoringRunNumber_);
  items.add("stateName", &monitoringStateName_);
336
  items.add("errorMsg", &monitoringErrorMsg_);
337
338
339
340
341
342
343
344
345
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::updateMonitoringItems()
{
  boost::shared_lock<boost::shared_mutex> stateNameSharedLock(stateNameMutex_);
  monitoringStateName_ = stateName_;
  monitoringRunNumber_ = runNumber_;
346
  monitoringErrorMsg_ = reasonForError_;
347
348
349
}


350
351
352
template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::acquireLock(const std::string& name)
{
353
354
355
  boost::interprocess::permissions permissions;
  permissions.set_unrestricted();
  boost::interprocess::named_semaphore semaphore(boost::interprocess::open_or_create,name.c_str(),1,permissions);
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

  if ( haveLock_ || semaphore.try_wait() )
  {
    haveLock_ = true;
  }
  else
  {
    std::string msg = "Another ";
    if (name == "evb::readoutunit")
      msg += "RU or EVM";
    else if (name == "evb::bu")
      msg += "BU";
    else
      msg += "EvB application";
    msg += " is already in Configured or Enabled state on this machine. Please destroy or Halt the other instance first.";
    XCEPT_DECLARE(exception::FSM, sentinelException,msg);
    this->post_event( Fail(sentinelException) );
  }
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::releaseLock(const std::string& name)
{
  if ( haveLock_ )
  {
    boost::interprocess::named_semaphore semaphore(boost::interprocess::open_only,name.c_str());
    semaphore.post();
  }
  haveLock_ = false;
}


389
390
391
392
393
394
395
396
397
398
399
400
401
template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::notifyRCMS
(
  const std::string& stateName
)
{
  rcmsStateNotifier_.stateChanged(stateName, "New state is " + stateName);
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::failEvent(const Fail& evt)
{
402
  reasonForError_ = evt.getTraceback();
403
  LOG4CPLUS_FATAL(getLogger(), "Failed: " << reasonForError_);
404

405
406
407
408
409
410
411
412
  try
  {
    rcmsStateNotifier_.stateChanged("Failed", evt.getReason());
  }
  catch(...) // Catch anything to make sure that we end in a well defined state
  {
    LOG4CPLUS_FATAL(getLogger(),"Failed to notify RCMS that we failed!");
  }
413

414
415
416
417
418
419
420
421
  try
  {
    app_->notifyQualified("fatal", evt.getException());
  }
  catch(...) // Catch anything to make sure that we end in a well defined state
  {
    LOG4CPLUS_FATAL(getLogger(),"Failed to notify the sentinel that we failed!");
  }
422
423
424
425
426
427
428
429
430
431
432
}


template <class MostDerived,class InitialState>
void evb::EvBStateMachine<MostDerived,InitialState>::unconsumed_event
(
  const boost::statechart::event_base& evt
)
{
  boost::shared_lock<boost::shared_mutex> stateNameSharedLock(stateNameMutex_);

433
434
  const std::regex e("[A-Za-z0-9]+evb[0-9a-z]+([a-zA-Z]+)E", std::regex::extended);
  std::smatch what;
435
  std::string event = typeid(evt).name();
436
  if ( std::regex_match(event,what,e) )
437
    event = what[1];
438
  LOG4CPLUS_ERROR(getLogger(),
439
440
                  "The '" << event << "' event is not supported from the '"
                  << stateName_ << "' state! '");
441
442
443
444
445
446
447
448
449
450
451
}


#endif //_evb_StateMachine_h_

/// emacs configuration
/// Local Variables: -
/// mode: c++ -
/// c-basic-offset: 2 -
/// indent-tabs-mode: nil -
/// End: -