UniSet  2.6.0
SharedMemory.h
1 /*
2  * Copyright (c) 2015 Pavel Vainerman.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as
6  * published by the Free Software Foundation, version 2.1.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * Lesser General Lesser Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 // -----------------------------------------------------------------------------
17 #ifndef SharedMemory_H_
18 #define SharedMemory_H_
19 // -----------------------------------------------------------------------------
20 #include <unordered_map>
21 #include <string>
22 #include <memory>
23 #include <deque>
24 #include <time.h>
25 #include "IONotifyController.h"
26 #include "Mutex.h"
27 #include "PassiveTimer.h"
28 #include "NCRestorer.h"
29 #include "WDTInterface.h"
30 #include "LogServer.h"
31 #include "DebugStream.h"
32 #include "LogAgregator.h"
33 #include "VMonitor.h"
34 // -----------------------------------------------------------------------------
35 #ifndef vmonit
36 #define vmonit( var ) vmon.add( #var, var )
37 #endif
38 // --------------------------------------------------------------------------
39 namespace uniset
40 {
41  // -----------------------------------------------------------------------------
42 
326  public IONotifyController
327  {
328  public:
329  SharedMemory( uniset::ObjectId id, const std::string& datafile, const std::string& confname = "" );
330  virtual ~SharedMemory();
331 
333  static std::shared_ptr<SharedMemory> init_smemory( int argc, const char* const* argv );
334 
336  static void help_print( int argc, const char* const* argv );
337 
338  // функция определяет "готовность" SM к работе.
339  // должна использоваться другими процессами, для того,
340  // чтобы понять, когда можно получать от SM данные.
341  virtual CORBA::Boolean exist() override;
342 
343  virtual uniset::SimpleInfo* getInfo( const char* userparam = 0 ) override;
344 
345  void addReadItem( Restorer_XML::ReaderSlot sl );
346 
347  // ------------ HISTORY --------------------
348  typedef std::deque<long> HBuffer;
349 
350  struct HistoryItem
351  {
352  explicit HistoryItem( size_t bufsize = 0 ): id(uniset::DefaultObjectId), buf(bufsize) {}
353  HistoryItem( const uniset::ObjectId _id, const size_t bufsize, const long val ): id(_id), buf(bufsize, val) {}
354 
355  inline void init( size_t size, long val )
356  {
357  if( size > 0 )
358  buf.assign(size, val);
359  }
360 
361  uniset::ObjectId id;
362  HBuffer buf;
363 
364  IOStateList::iterator ioit;
365 
366  void add( long val, size_t size )
367  {
368  // т.к. буфер у нас уже заданного размера
369  // то просто удаляем очередную точку в начале
370  // и добавляем в конце
371  buf.pop_front();
372  buf.push_back(val);
373  }
374  };
375 
376  typedef std::list<HistoryItem> HistoryList;
377 
378  struct HistoryInfo
379  {
380  HistoryInfo()
381  {
382  ::clock_gettime(CLOCK_REALTIME, &fuse_tm);
383  }
384 
385  long id = { 0 }; // ID
386  HistoryList hlst; // history list
387  size_t size = { 0 };
388  std::string filter = { "" }; // filter field
389  uniset::ObjectId fuse_id = { uniset::DefaultObjectId }; // fuse sesnsor
390  bool fuse_invert = { false };
391  bool fuse_use_val = { false };
392  long fuse_val = { 0 };
393  timespec fuse_tm = { 0, 0 }; // timestamp
394  };
395 
396  friend std::ostream& operator<<( std::ostream& os, const HistoryInfo& h );
397 
398  typedef std::list<HistoryInfo> History;
399 
400  // т.к. могуть быть одинаковые "детонаторы" для разных "историй" то,
401  // вводим не просто map, а "map списка историй".
402  // точнее итераторов-историй.
403  typedef std::list<History::iterator> HistoryItList;
404  typedef std::unordered_map<uniset::ObjectId, HistoryItList> HistoryFuseMap;
405 
406  typedef sigc::signal<void, const HistoryInfo&> HistorySlot;
407  HistorySlot signal_history();
409  inline int getHistoryStep() const
410  {
411  return histSaveTime;
412  }
413 
414  // -------------------------------------------------------------------------------
415 
416  inline std::shared_ptr<LogAgregator> logAgregator()
417  {
418  return loga;
419  }
420  inline std::shared_ptr<DebugStream> log()
421  {
422  return smlog;
423  }
424 
425  protected:
426  typedef std::list<Restorer_XML::ReaderSlot> ReadSlotList;
427  ReadSlotList lstRSlot;
428 
429  virtual void sysCommand( const uniset::SystemMessage* sm ) override;
430  virtual void timerInfo( const uniset::TimerMessage* tm ) override;
431  virtual void askSensors( UniversalIO::UIOCommand cmd ) {};
432  void sendEvent( uniset::SystemMessage& sm );
433  void initFromReserv();
434  bool initFromSM( uniset::ObjectId sm_id, uniset::ObjectId sm_node );
435 
436  // действия при завершении работы
437  virtual void sigterm( int signo ) override;
438  virtual bool activateObject() override;
439  virtual bool deactivateObject() override;
440  bool readItem( const std::shared_ptr<UniXML>& xml, UniXML::iterator& it, xmlNode* sec );
441 
442  void buildEventList( xmlNode* cnode );
443  void readEventList( const std::string& oname );
444 
445  std::mutex mutexStart;
446 
448  {
449  public:
450  HeartBeatInfo():
454  timer_running(false),
455  ptReboot(UniSetTimer::WaitUpTime)
456  {}
457 
458  uniset::ObjectId a_sid; // аналоговый счётчик
459  uniset::ObjectId d_sid; // дискретный датчик состояния процесса
460  IOStateList::iterator a_it;
461  IOStateList::iterator d_it;
462 
463  timeout_t reboot_msec;
468  bool timer_running;
469  PassiveTimer ptReboot;
470  };
471 
472  enum Timers
473  {
474  tmHeartBeatCheck,
475  tmEvent,
476  tmHistory,
477  tmPulsar,
478  tmLastOfTimerID
479  };
480 
481  int heartbeatCheckTime;
482  std::string heartbeat_node;
483  int histSaveTime;
484 
485  void checkHeartBeat();
486 
487  typedef std::list<HeartBeatInfo> HeartBeatList;
488  HeartBeatList hblist; // список датчиков "сердцебиения"
489  std::shared_ptr<WDTInterface> wdt;
490  std::atomic_bool activated;
491  std::atomic_bool workready;
492 
493  typedef std::list<uniset::ObjectId> EventList;
494  EventList elst;
495  std::string e_filter;
496  int evntPause;
497  int activateTimeout;
498 
499  virtual void logging( uniset::SensorMessage& sm ) override;
500  virtual void dumpOrdersList( const uniset::ObjectId sid, const IONotifyController::ConsumerListInfo& lst ) override {};
501  virtual void dumpThresholdList( const uniset::ObjectId sid, const IONotifyController::ThresholdExtList& lst ) override {}
502 
503  bool dblogging = { false };
504 
507  // оптимизация с использованием userdata (IOController::USensorInfo::userdata) нужна
508  // чтобы не использовать поиск в HistoryFuseMap (см. checkFuse)
509  // т.к. 0,1 - использует IONotifyController (см. IONotifyController::UserDataID)
510  // то используем не занятый "2" - в качестве элемента userdata
511  static const size_t udataHistory = 2;
512 
513  History hist;
514  HistoryFuseMap histmap;
516  virtual void checkFuse( std::shared_ptr<IOController::USensorInfo>& usi, IOController* );
517  virtual void saveToHistory();
518 
519  void buildHistoryList( xmlNode* cnode );
520  void checkHistoryFilter( UniXML::iterator& it );
521 
522  IOStateList::iterator itPulsar;
523  uniset::ObjectId sidPulsar;
524  int msecPulsar;
525 
526  xmlNode* confnode;
527 
528  std::shared_ptr<LogAgregator> loga;
529  std::shared_ptr<DebugStream> smlog;
530  std::shared_ptr<LogServer> logserv;
531  std::string logserv_host = {""};
532  int logserv_port = {0};
533 
534  VMonitor vmon;
535 
536  private:
537  HistorySlot m_historySignal;
538  };
539  // --------------------------------------------------------------------------
540 } // end of namespace uniset
541 // -----------------------------------------------------------------------------
542 #endif // SharedMemory_H_
543 // -----------------------------------------------------------------------------
Пассивный таймер
Definition: PassiveTimer.h:90
HistoryFuseMap histmap
Definition: SharedMemory.h:514
Definition: IONotifyController.h:194
virtual void dumpOrdersList(const uniset::ObjectId sid, const IONotifyController::ConsumerListInfo &lst) override
Definition: SharedMemory.h:500
Definition: CallbackTimer.h:29
virtual void sigterm(int signo) override
Definition: SharedMemory.cc:350
Definition: SharedMemory.h:350
Definition: UniXML.h:43
int getHistoryStep() const
Definition: SharedMemory.h:409
Definition: SharedMemory.h:447
virtual bool activateObject() override
Definition: SharedMemory.cc:296
timeout_t reboot_msec
Definition: SharedMemory.h:463
Definition: MessageType.h:166
Definition: SharedMemory.h:325
const ObjectId DefaultObjectId
Definition: UniSetTypes.h:56
Definition: IONotifyController.h:131
virtual void dumpThresholdList(const uniset::ObjectId sid, const IONotifyController::ThresholdExtList &lst) override
Definition: SharedMemory.h:501
Definition: MessageType.h:122
virtual void logging(uniset::SensorMessage &sm) override
сохранение информации об изменении состояния датчика
Definition: SharedMemory.cc:611
std::list< ThresholdInfoExt > ThresholdExtList
Definition: IONotifyController.h:263
sigc::slot< bool, const std::shared_ptr< UniXML > &, UniXML::iterator &, xmlNode * > ReaderSlot
Definition: Restorer.h:51
Definition: SharedMemory.h:378
Definition: MessageType.h:209
HistorySlot signal_history()
Definition: SharedMemory.cc:733
static const size_t udataHistory
Definition: SharedMemory.h:511
virtual bool deactivateObject() override
Definition: SharedMemory.cc:286
Definition: IOController.h:37
static std::shared_ptr< SharedMemory > init_smemory(int argc, const char *const *argv)
Definition: SharedMemory.cc:508
Definition: UniSetTypes_i.idl:64
long ObjectId
Definition: UniSetTypes_i.idl:30
static void help_print(int argc, const char *const *argv)
Definition: SharedMemory.cc:32
static const timeout_t WaitUpTime
Definition: PassiveTimer.h:69