Changed LICENSE. Now referenced to web site and file on project root directory
[anna.git] / include / anna / core / oam / Module.hpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 #ifndef anna_core_oam_Module_hpp
10 #define anna_core_oam_Module_hpp
11
12
13 // STL
14 #include <string>
15 #include <vector>
16 #include <map>
17
18 #include <anna/core/RuntimeException.hpp>
19
20 #include <anna/core/oam/defines.hpp>
21 #include <anna/core/oam/Handler.hpp>
22
23 #include <cstdarg>
24
25
26 namespace anna {
27 namespace xml {
28 class Node;
29 }
30 namespace oam {
31 class CounterScope;
32 class CounterRecorder;
33 }
34 }
35
36
37 namespace anna {
38
39 namespace oam {
40
41 class Handler;
42
43 /**
44 * Class used to implement context-module-alarms/counters. Each process module (within library or process itself) must
45 * inherit from this, defining specific-alarm/counters codes (better public enum type) which will be managed within each
46 * module (usually through a management singleton class). This allow code reusability regarding alarm/counter conditions
47 * usually badly managed with API return codes instead of self-governing alarms shared and reusabled by any API client,
48 * or counters with fixed-inflexible values. It is posible to manage more than one oam module per library or proccess,
49 * simply defining more children classes, but the normal way is to use only one.
50 *
51 * <pre>
52 *
53 * Example of use:
54 *
55 *  class OamModule : public anna::oam::Module, public anna::Singleton <OamModule>
56 *  {
57 *              struct Counter
58 *              {
59 *                 enum _v // types
60 *                 {
61 *                    None = -1,
62 *                    ErrorLDAP
63 *                 };
64 *
65 *                 anna_declare_enum(Counter);
66 *              };
67 *
68 *              struct Alarm
69 *              {
70 *                 enum _v // types
71 *                 {
72 *                    None = -1,
73 *                    ErrorOnNode__s__WithSessionId__d__
74 *                 };
75 *
76 *                 anna_declare_enum(Alarm);
77 *              };
78 *
79 *        OamModule() : anna::oam::Module ("Main Proccess 'HTE_CLDAP' OAM module") {;};
80 *
81 *        friend class anna::Singleton <OamModule>;
82 *  };
83 *
84 * Normally, we will use one scope per module (library/proccess) but we could define many oam modules per subsystem functionality.
85 * For example, libanna.diameter.b have oam modules for comm.db and codec.db. Also, macros as 'anna_declare_enum' are useful to
86 * define default descriptions for counter and alarm types.
87 *
88 *
89 * == REGISTRATION for all the linked scopes ==
90 *
91 * anna::<project>::oam::Handler *projectHandler = new anna::<project>::oam::Handler(); // handler for project alarms
92 *
93 * OamModule & oam_proc = OamModule::instantiate();
94 * <library_namespace>::OamModule & oam_lib = <library_namespace>::OamModule::instantiate();
95 * oam_proc.setHandler(projectHandler);
96 * oam_proc.initializeCounterScope (1);
97 * oam_proc.registerCounter (OamModule::Counter::ErrorLDAP, "ErrorLDAP", 0);
98 * oam_proc.registerAlarm (OamModule::Alarm::ErrorOnNode__s__WithSessionId__d__, "Error on node", 1, "nodeName,errorCode", anna::oam::MSAlarmId::NODE_ERROR);
99 *
100 * oam_lib.setHandler(projectHandler);
101 * oam_lib.initializeCounterScope (2); // different scope for different modules (normal way)
102 * oam_lib.registerCounter (<library_namespace>::OamModule::Counter::<type>, "counter description", 0);
103 * oam_lib.registerAlarm (<library_namespace>::OamModule::Alarm::<type>, "alarm description", 2, <dynamic variable names CSL>, anna::oam::MSAlarmId::<type>);
104 *
105 * -> LAUNCH for all local scopes (library launches will be done at library code):
106 * oam_proc.count (OamModule::Counter::ErrorLDAP);
107 * oam_proc.activateAlarm (OamModule::Alarm::ErrorOnNode__s__WithSessionId__d__, "my node", a_session_id);
108 *
109 *
110 * == MULTI-CONTEXT APPLICATIONS ==
111 *
112 * Suppose two contexts, one with scopes 1 and 4 for process and library respectively, and
113 * the other defined by 2 and 5:
114 *
115 * oam_proc.initializeCounterScope (1, "Main OAM Module - Context A");
116 * oam_proc.initializeCounterScope (2, "Main OAM Module - Context B");
117 * Counters registration ...
118 *
119 * oam_lib.initializeCounterScope (4, "Encoder OAM Module - Context A");
120 * oam_lib.initializeCounterScope (5, "Encoder OAM Module - Context B");
121 * Counters registration ...
122 *
123 * Application must switch between these scope ids to distinguise the contexts:
124 *
125 * Context A:
126 * oam_proc.setActiveCounterScope(1);
127 * oam_lib.setActiveCounterScope(4);
128 *
129 * Context B:
130 * oam_proc.setActiveCounterScope(2);
131 * oam_lib.setActiveCounterScope(5);
132 *
133 * </pre>
134 */
135 class Module {
136
137   Handler a_defaultHandler;        // default OAM handler
138   Handler *a_handler;              // Handler reference
139
140   std::string a_className;         // module description
141   bool a_counters_enabled;         // Enable/Disable registered counters over this module (default is 'true')
142   bool a_alarms_enabled;           // Enable/Disable registered alarms over this module (default is 'true')
143
144   // dynamic modifications over alarm text
145   bool a_alarms_preffix_enabled;   // Show own module alarm preffix
146   bool a_alarms_suffix_enabled;    // Show own module alarm suffix
147   std::string alarmComponentsToText(const std::vector<std::string> & components, const std::string & psL, const std::string & psS, const std::string & psR) const throw();
148
149   // GENERIC COUNTERS
150   anna::oam::CounterScope* a_active_counter_scope; // Current scope for counters generation
151   typedef std::map <int, anna::oam::CounterScope*> scope_container;
152   scope_container a_scopes; // Module can manage N scope clones (usually, there is only one registered scope: mono-context applications)
153   typedef std::map < int /*type*/, counter_data_t > counter_container;
154   counter_container a_counters;
155
156   // GENERIC ALARMS
157   typedef std::map < int /*type*/, alarm_data_t > alarm_container;
158   alarm_container a_alarms;
159
160   void alarmEvent(bool activation, const int & type, va_list argList) const throw();
161
162   // Counters
163   typedef scope_container::iterator scope_iterator;
164   typedef scope_container::const_iterator const_scope_iterator;
165   scope_iterator scope_find(const int &key) throw() { return a_scopes.find(key); }
166   scope_iterator scope_begin() throw() { return a_scopes.begin(); }
167   scope_iterator scope_end() throw() { return a_scopes.end(); }
168   static anna::oam::CounterScope* scope(scope_iterator ii) throw() { return ii->second; }
169   const_scope_iterator scope_begin() const throw() { return a_scopes.begin(); }
170   const_scope_iterator scope_end() const throw() { return a_scopes.end(); }
171   static const anna::oam::CounterScope* scope(const_scope_iterator ii) throw() { return ii->second; }
172   anna::oam::CounterScope *getScope(const int &id) throw();
173   typedef counter_container::iterator counter_iterator;
174   typedef counter_container::const_iterator const_counter_iterator;
175 //   bool counter_remove(const int &key) throw();
176   const_counter_iterator counter_find(const int &key) const throw() { return a_counters.find(key); }
177   const_counter_iterator counter_begin() const throw() { return a_counters.begin(); }
178   const_counter_iterator counter_end() const throw() { return a_counters.end(); }
179   counter_iterator counter_find(const int &key) throw() { return a_counters.find(key); }
180   counter_iterator counter_begin() throw() { return a_counters.begin(); }
181   counter_iterator counter_end() throw() { return a_counters.end(); }
182   CounterRecorder* a_counterRecorder;
183   bool a_counterRecording;
184
185   class RecordingGuard {
186     public:
187       RecordingGuard(Module*);
188       ~RecordingGuard();
189     private:
190       Module *a_module;
191   };
192
193   // Alarms
194   typedef alarm_container::iterator alarm_iterator;
195   typedef alarm_container::const_iterator const_alarm_iterator;
196 //   bool alarm_remove(const int &key) throw();
197   const_alarm_iterator alarm_find(const int &key) const throw() { return a_alarms.find(key); }
198   const_alarm_iterator alarm_begin() const throw() { return a_alarms.begin(); }
199   const_alarm_iterator alarm_end() const throw() { return a_alarms.end(); }
200   alarm_iterator alarm_find(const int &key) throw() { return a_alarms.find(key); }
201   alarm_iterator alarm_begin() throw() { return a_alarms.begin(); }
202   alarm_iterator alarm_end() throw() { return a_alarms.end(); }
203   void getAlarmPreffixSuffixAndZoneSeparator(std::string & preffix, std::string & suffix, char & zS) const throw();
204
205
206 public:
207
208   static const int MaxScope = 100; /**< Numero maximo de ambitos */
209
210
211   /** Constructor
212       @param className Logical name for the class (better use fullNaming format including namespace resolution)
213    */
214   Module(const std::string &className) :    a_className(className),
215     a_handler(&a_defaultHandler),
216     a_counters_enabled(true),
217     a_counterRecorder(NULL),
218     a_counterRecording(false),
219     a_alarms_enabled(true),
220     a_alarms_preffix_enabled(true),
221     a_alarms_suffix_enabled(true) {;}
222
223   /**
224    * Destructor
225    */
226   virtual ~Module();
227
228
229   /**
230   * Enable all the counters registered in this module (enabled by default at constructor).
231   * Usually managed at PROCCESS implementation
232   */
233   void enableCounters(void) throw();
234
235   /**
236   * Disable all the counters registered in this module (enabled by default at constructor).
237   * Usually managed at PROCCESS implementation
238   */
239   void disableCounters(void) throw();
240
241   /**
242   * Enable all the alarms registered in this module (enabled by default at constructor).
243   * Usually managed at PROCCESS implementation
244   */
245   void enableAlarms(void) throw();
246
247   /**
248   * Disable all the alarms registered in this module (enabled by default at constructor).
249   * Usually managed at PROCCESS implementation
250   */
251   void disableAlarms(void) throw();
252
253   /**
254   * Show own module alarm preffix (enabled by default at constructor).
255   * Usually managed at PROCCESS implementation
256   */
257   void enableAlarmsPreffix(void) throw();
258
259   /**
260   * Show own module alarm suffix (enabled by default at constructor).
261   * Usually managed at PROCCESS implementation
262   */
263   void enableAlarmsSuffix(void) throw();
264
265   /**
266   * Hide own module alarm preffix (enabled by default at constructor).
267   * Usually managed at PROCCESS implementation
268   */
269   void disableAlarmsPreffix(void) throw();
270
271   /**
272   * Hide own module alarm suffix (enabled by default at constructor).
273   * Usually managed at PROCCESS implementation
274   */
275   void disableAlarmsSuffix(void) throw();
276
277   /**
278   * Sets the operations handler. By default, all modules will use the default anna::oam::Handler.
279   * This method will be used only when a different behaviour is needed, for example for the project
280   * specific events.
281   *
282   * Used ONLY at PROCCESS implementation (initial tasks)
283   *
284   * @param handler Handler used for OAM operations (registering and launch). NULL is ignored
285   */
286   void setHandler(Handler *handler) throw() { if(handler) a_handler = handler; }
287
288   /**
289   * Counter scope registration. Usually, only one scope id will be registered, but multicontext applications
290   * could manage scope clones where all the counters are REPLICATED in order to manage separate sub-facilities.
291   * Multicontext applications must invoke N times to this method, and then register the common counters.
292   * Each context must activate with 'setActiveCounterScope()', the correct scope id.
293   * After invocation, provided scope id will be activated.
294   * Used ONLY at PROCCESS implementation (initial tasks)
295   *
296   * @param scopeId Counter scope id. It must be non negative (0 is usually reserved for core platform counters).
297   * @param description Counter scope id description. If missing, module description will be set, but is
298   * a good idea add different names between replicated scopes, i.e.: 'Main OAM Module - Context X', etc.
299   * better than 'Main OAM Module' for all of them. Also, you can use the same description for all scopes
300   * (that is the case of default assignment).
301   */
302   void initializeCounterScope(const int & scopeId, const std::string & description = "") throw(anna::RuntimeException);
303
304
305   /**
306   * Multicontext application could decide the correct scope id in order to sure right sub-module counting.
307   * Applications that only initializes one scope (which becomes active after that), don't need to use this method.
308   * Used ONLY at PROCCESS implementation (normal tasks)
309   *
310   * @param scopeId Counter scope id which becomes active.
311   */
312   void setActiveCounterScope(const int & scopeId) throw();
313
314
315   /**
316   * Gets the current activated counter scope
317   *
318   * @return Activated counter scope
319   */
320   const anna::oam::CounterScope* getActiveCounterScope() const throw() { return a_active_counter_scope; }
321
322   /**
323   * Child oam module classes should define descriptions for each enum type. A good practice would be the use of
324   * 'anna_declare_enum' macro in order to define names for enum types. This is an oam-internal description which
325   * should be redefined at application layer during registering. Returns undefined by default.
326   *
327   * @param type Counter enum-identification within the own context/module
328   *
329   * @return Default alarm description
330   */
331   virtual std::string getDefaultInternalAlarmDescription(const int & type) const throw();
332
333   /**
334   * Child oam module classes should define descriptions for each enum type. A good practice would be the use of
335   * 'anna_declare_enum' macro in order to define names for enum types. This is an oam-internal description which
336   * should be redefined at application layer during registering. Returns undefined by default.
337   *
338   * @param type Counter enum-identification within the own context/module
339   *
340   * @return Default counter description
341   */
342   virtual std::string getDefaultInternalCounterDescription(const int & type) const throw();
343
344
345   /**
346   * Counter registration providing the specific documentacion codes.
347   * To guarantee clone operations, no scope initialization will be possible after use of this method.
348   * Used ONLY at PROCCESS implementation (initial tasks)
349   *
350   * @param type Counter enum-identification added within the module (defined enum type on @Singleton child class)
351   * @param description Counter description added within the module. If empty string is provided, default description
352   * for non-registered will be searched (#getDefaultInternalCounterDescription).
353   * @param offset Counter offset over (1000 * scope id). Offset has 0-999 range.
354   */
355   void registerCounter(const int &type, const std::string &description, const int &offset) throw(anna::RuntimeException);
356
357
358   /**
359   * Alarm registration providing the specific process codes useful for manage any kind of alarm generation: external id
360   * (which could be a database unique idenfier), dynamic variables used during text parsing to allow advanced manipulation,
361   * and activation/cancellation codes (which could be used at a certain management system node).
362   *
363   * @param type Alarm enum-identification added within the module (defined enum type on @Singleton child class)
364   * @param description Alarm description added within the module. If empty string is provided, default description
365   * for non-registered will be searched (#getDefaultInternalAlarmDescription).
366   * @param externalId External text identification.
367   * @param dynamicVariablesCSL Comma-separated list of dynamic variable names (same order than launched with #activateAlarm and #cancelAlarm).
368   * @param activationId Alarm activation identifier
369   * @param cancellationId Alarm cancellation identifier. If missing, the alarm will interpreted as non-transferable
370   */
371   void registerAlarm(const int &type, const std::string &description, const int &externalId, const std::string &dynamicVariablesCSL, const int &activationId, const int &cancellationId = -1) throw(anna::RuntimeException);
372
373
374   /**
375      Gets the OAM module name
376
377      @param OAM module name
378   */
379   const char *getClassName() const throw() { return a_className.c_str(); }
380
381
382   /**
383      Gets counter data for type provided. NULL if not found.
384
385      @param type Alarm enum-identification within the own context/module.
386   */
387   const counter_data_t *counter(const int &type) const throw() {
388     const_counter_iterator it = counter_find(type);
389     return ((it != counter_end()) ? (&(*it).second) : NULL);
390   }
391
392   /**
393      Gets alarm data for type provided. NULL if not found.
394
395      @param type Counter enum-identification within the own context/module.
396   */
397   const alarm_data_t *alarm(const int &type) const throw() {
398     const_alarm_iterator it = alarm_find(type);
399     return ((it != alarm_end()) ? (&(*it).second) : NULL);
400   }
401
402
403   /**
404   * Notifies counter increase with certain amount within the ativated scope
405   * Used at MODULE implementation (library or proccess itself)
406   *
407   * @param type Counter enum-identification within the own context/module
408   * @param amount Units increased. Default is 1
409   */
410   void count(const int & type, const int & amount = 1) throw(anna::RuntimeException);
411
412
413   /**
414   * Reset all counters accumulated amount (analysis purposes)
415   * Usually managed at PROCCESS implementation
416   *
417   * @param scopeId Restrict reset to provided scope id. If missing, all scopes will be affected.
418   *
419   * @return Number of affected counters which have been reset (only those which have non-zero accumulated count).
420   */
421   int resetCounters(const int & scopeId = -1) throw();
422
423
424   /**
425   * Sets the instance for the class which will save the counters information.
426   * @counterRecorder Provided instance
427   * @warning It should be invoked periodically as a common solution
428   */
429   void setCounterRecorder(CounterRecorder* counterRecorder) throw() { a_counterRecorder = counterRecorder; }
430
431   /**
432   * Dumps the modified counters from last invocation to this method.
433   * A counter recorder should have been assigned by mean setCounterRecorder(), which
434   * will have the specific behaviour. This procedure is oriented to have physical storage
435   * for counters information.
436   */
437   void recordCounters() throw(anna::RuntimeException);
438
439
440   /**
441   * Activates alarm with dynamic-composed text parsed with provided data (...).
442   * Used at MODULE implementation (library or proccess itself)
443   *
444   * @param alarmType Alarm enum-identification within the own context/module
445   * @param ... Optional parsing data for dynamic-composed text.
446   */
447   void activateAlarm(int type, ...) const throw(anna::RuntimeException);
448
449
450   /**
451   * Send transferable alarm cancellation, with dynamic-composed text parsed with provided data (...)
452   * Used at MODULE implementation (library or proccess itself)
453   *
454   * @param alarmType Alarm enum-identification within the own context/module
455   * @param ... Optional parsing data for dynamic-composed text.
456   */
457   void cancelAlarm(int type, ...) const throw(anna::RuntimeException);
458
459
460   /**
461   * Class string representation
462   * Usually managed at PROCCESS implementation
463   *
464   * @return String with class content
465   */
466   virtual std::string asString(void) const throw();
467
468
469   /**
470   * Class XML representation
471   * Usually managed at PROCCESS implementation
472   *
473   * @return XML with class content
474   */
475   virtual anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
476
477
478 protected:
479
480   /**
481   * Module alarm preffix components used to add aditional information over alarm text.
482   * Oam modules push-back this additional components to global 'Configuration' preffix components.
483   * To disable, use 'disableAlarmsPreffix()'.
484   * Note that preffix components string should be multilanguage texts if alarm texts are based on
485   * language-context traslations.
486   * Used at MODULE implementation (library or proccess itself)
487   *
488   * @param components Alarm preffix components defined by oam module. Empty on default implementation.
489   */
490   virtual void readAlarmPreffixComponents(std::vector<std::string> & components) const throw() {;}
491
492
493   /**
494   * Module alarm suffix components used to add aditional information over alarm text.
495   * Oam modules push-back this additional components to global 'Configuration' suffix components.
496   * To disable, use 'disableAlarmsSuffix()'.
497   * Note that suffix components string should be multilanguage texts if alarm texts are based on
498   * language-context traslations.
499   * Used at MODULE implementation (library or proccess itself)
500   *
501   * @param components Alarm suffix components defined by oam module. Empty on default implementation.
502   */
503   virtual void readAlarmSuffixComponents(std::vector<std::string> & components) const throw() {;}
504
505
506   friend class RecordingGuard;
507 };
508
509 }
510 }
511
512 #endif
513