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