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