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