KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > management > selfmanagement > RuleManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.management.selfmanagement;
24
25 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
26 import com.sun.enterprise.config.serverbeans.Applications;
27 import com.sun.enterprise.config.serverbeans.ApplicationRef;
28 import com.sun.enterprise.config.serverbeans.Mbean;
29 import com.sun.enterprise.config.serverbeans.Domain;
30 import com.sun.enterprise.config.serverbeans.Clusters;
31 import com.sun.enterprise.config.serverbeans.Cluster;
32 import com.sun.enterprise.config.serverbeans.Server;
33 import com.sun.enterprise.config.serverbeans.ManagementRule;
34 import com.sun.enterprise.config.serverbeans.ElementProperty;
35 import com.sun.enterprise.config.serverbeans.ServerTags;
36
37 import com.sun.enterprise.config.ConfigContext;
38 import com.sun.enterprise.config.ConfigException;
39 import com.sun.enterprise.config.ConfigUpdate;
40
41 import com.sun.enterprise.admin.server.core.AdminService;
42 import com.sun.enterprise.admin.common.ObjectNames;
43 import com.sun.enterprise.admin.selfmanagement.event.*;
44 import com.sun.enterprise.management.selfmanagement.LogMgmtEventsNotificationListener;
45 import com.sun.enterprise.admin.server.core.CustomMBeanRegistration;
46
47 import com.sun.appserv.management.alert.MailAlert;
48 import com.sun.enterprise.server.ApplicationServer;
49 import com.sun.enterprise.server.ServerContext;
50
51 import javax.management.ObjectName JavaDoc;
52 import javax.management.MBeanServer JavaDoc;
53 import javax.management.NotificationEmitter JavaDoc;
54 import javax.management.NotificationListener JavaDoc;
55 import javax.management.NotificationFilter JavaDoc;
56 import javax.management.NotificationFilterSupport JavaDoc;
57 import javax.management.InstanceNotFoundException JavaDoc;
58 import javax.management.RuntimeOperationsException JavaDoc;
59 import javax.management.MalformedObjectNameException JavaDoc;
60 import javax.management.InstanceAlreadyExistsException JavaDoc;
61
62 import java.util.Collections JavaDoc;
63 import java.util.Map JavaDoc;
64 import java.util.HashMap JavaDoc;
65 import java.util.Hashtable JavaDoc;
66 import java.util.Set JavaDoc;
67 import java.util.Iterator JavaDoc;
68 import java.util.logging.Logger JavaDoc;
69 import java.util.logging.Level JavaDoc;
70 import java.lang.reflect.Constructor JavaDoc;
71 import java.lang.String JavaDoc;
72
73 import com.sun.logging.LogDomains;
74 import com.sun.enterprise.util.i18n.StringManager;
75
76 /**
77  * This is the core class, which manages the runtime of the
78  * configured management_rules.
79  *
80  * @author Pankaj Jairath
81  */

82 public class RuleManager {
83     
84     /** Logger for self management service */
85     private static Logger JavaDoc _logger = null;
86     
87     /** Local Strings manager for the class */
88     private static StringManager localStrings = null;
89     
90     static {
91         _logger = LogDomains.getLogger(LogDomains.SELF_MANAGEMENT_LOGGER);
92         localStrings = StringManager.getManager(RuleManager.class);
93     }
94     
95     /** A HashMap that contains all enabled and active rules */
96     private Map JavaDoc<String JavaDoc,Rule> activeRules = null;
97     
98     /** HashMap that contains all enabled but inactive rules */
99     private Map JavaDoc<String JavaDoc,Rule> inActiveRules = null;
100     
101     /** HashMap that contains all the rules that have no actions. These
102      * would have their configured events logged.
103      */

104     private Map JavaDoc<String JavaDoc,Rule> noActionRules = null;
105      
106     /** A HashMap that contains all the disabled rules */
107     private Map JavaDoc<String JavaDoc,Rule> disabledRules = null;
108     
109     /** */
110     private final String JavaDoc USER_DEFINED_TYPE = "user";
111        
112     /** */
113     private ConfigContext configCtx = null;
114     /** */
115     private String JavaDoc instanceName = null;
116
117     /** Instance MBeanServer */
118     private MBeanServer JavaDoc instanceMbs = null;
119     
120     /** SMTP host for service alert mails */
121     private String JavaDoc mailSMTPHost = null;
122     
123     /** Recipients of service alert messages */
124     private String JavaDoc srvAlertRecipients = null;
125
126     /** Self management service instance */
127     private SelfManagementService service = null;
128        
129     /** Creates a new instance of RuleManager */
130     public RuleManager(SelfManagementService service) {
131         this.service = service;
132         instanceName = (ApplicationServer.getServerContext()).getInstanceName();
133         AdminService adSrv = AdminService.getAdminService();
134         instanceMbs = (adSrv.getAdminContext()).getMBeanServer();
135         configCtx = (ApplicationServer.getServerContext()).getConfigContext();
136     
137         activeRules = Collections.synchronizedMap(new HashMap JavaDoc<String JavaDoc,Rule>());
138         inActiveRules = Collections.synchronizedMap(new HashMap JavaDoc<String JavaDoc,Rule>());
139         noActionRules = Collections.synchronizedMap(new HashMap JavaDoc<String JavaDoc, Rule>());
140         disabledRules = Collections.synchronizedMap(new HashMap JavaDoc<String JavaDoc,Rule>());
141     }
142     
143     /**
144      *
145      */

146     public void addRule(String JavaDoc ruleName, String JavaDoc description, Event ruleEvent,
147                       String JavaDoc actionMBeanName, Object JavaDoc handback,
148                       ConfigContext ctxToUse) throws InstanceNotFoundException JavaDoc {
149         ObjectName JavaDoc actionObjName = null;
150         Object JavaDoc alertAction = null;
151         Rule ruleInstance = new Rule(ruleName, description);
152         //rule.setRuleEvent(ruleEvent);
153
if (ctxToUse!=null) {
154             configCtx = ctxToUse;
155         }
156         
157         try {
158             if (actionMBeanName != null) {
159             
160                 Domain domain = ServerBeansFactory.getDomainBean(configCtx);
161                 ApplicationRef appRef = verifyActionMBean(actionMBeanName, domain,
162                                                           ctxToUse);
163        
164        
165                 if (appRef != null) {
166                     Applications apps = domain.getApplications();
167                     Mbean definedMBean = apps.getMbeanByName(actionMBeanName);
168                 
169                    
170                     if (appRef.isEnabled() && definedMBean.isEnabled() ) {
171                         if ((definedMBean.getObjectType()).equals(USER_DEFINED_TYPE)) {
172                             actionObjName = registerAction(ruleEvent,actionMBeanName,
173                                                            definedMBean,false, handback);
174                         } else {
175                             // system defined, need to explictly load
176
actionObjName = registerAction(ruleEvent,actionMBeanName,
177                                                            definedMBean,true, handback);
178                         }
179                         //obtain the action instance from name
180
setupRuleBinding(Rule.ENABLED, ruleInstance, ruleEvent,
181                                          (Object JavaDoc)actionObjName);
182                         //rule.setActionMBean(actionInstance);
183
//rule.setState(Rule.ENABLED);
184
//addToActiveRuleMap(ruleName,rule);
185
} else {
186                         /* action is disabled, but rule is active; Add a default mail
187                          * alert
188                          */

189                         alertAction = registerAlertAction(ruleEvent, actionMBeanName,
190                                                           ruleName, handback);
191                         _logger.log(Level.WARNING,"sgmt.ruleactiondisabled",
192                                     new Object JavaDoc[]{ruleName,actionMBeanName});
193                         
194                         setupRuleBinding(Rule.INACTIVE, ruleInstance, ruleEvent,
195                                          alertAction);
196                         //rule.setActionMbean(actionInstance);
197
//rule.setState(Rule.INACTIVE);
198
//addToInActiveRuleSet(ruleName,rule);
199
}
200                  } else {
201                      //log error, invalid action MBean provided for this rule
202
_logger.log(Level.SEVERE, "smgt.invalid_action", new Object JavaDoc[]{
203                                  ruleName, actionMBeanName});
204                      //config error
205
}
206             } else {
207                 //no action rule, event would simply record itself
208
setupRuleBinding(Rule.NOACTION, ruleInstance, ruleEvent, null);
209             }
210         } catch (ConfigException ex) {
211             _logger.log(Level.INFO, "config_error", ex);
212         } catch (InstanceNotFoundException JavaDoc ex) {
213             //log it,
214
_logger.log(Level.INFO, "smgt.error_reg_action", new Object JavaDoc[]{
215                         ruleName, actionMBeanName});
216             registerAlertAction(ruleEvent, actionMBeanName, ruleName, handback);
217         } catch (MalformedObjectNameException JavaDoc ex) {
218             _logger.log(Level.WARNING, "sgmt.error_reg_action", new Object JavaDoc[]{
219                         ruleName, actionMBeanName});
220         } catch (RuntimeOperationsException JavaDoc ex) {
221             //log it, actionMBean is not a listener type, add to inactive rules
222
_logger.log(Level.WARNING, "smgt.error_reg_action", new Object JavaDoc[]{
223                         ruleName,actionMBeanName});
224             registerAlertAction(ruleEvent, actionMBeanName, ruleName, handback);
225         } catch (RuntimeException JavaDoc ex) {
226             /*
227              *log it, as thrown from customRegistration, add to inactive rules
228              */

229             _logger.log(Level.WARNING, "smgt.error_reg_action", new Object JavaDoc[] {
230                         ruleName, actionMBeanName});
231             registerAlertAction(ruleEvent, actionMBeanName, ruleName, handback);
232        }
233     }
234         
235     /**
236      * Verify's whether the action MBean is a referenced application
237      * by the server instance and also has a valid definition at the domain
238      * level
239      *
240      * @param actionMBeanName
241      * @param domain
242      * @return ApplicationRef
243      */

244     private ApplicationRef verifyActionMBean(String JavaDoc actionMBeanName,
245                                              Domain domain,
246                                              ConfigContext ctxToUse) {
247         ApplicationRef appRef = null;
248         if (ctxToUse != null) {
249            configCtx = ctxToUse;
250         }
251         
252         try {
253             Server instanceBean = ServerBeansFactory.getServerBean(configCtx);
254             appRef = instanceBean.getApplicationRefByRef(actionMBeanName);
255         
256             if (appRef == null) {
257                 //check at cluster level, if this instance is part of cluster
258
Clusters clusters = domain.getClusters();
259                 Cluster[] cluster = clusters.getCluster();
260                 for (Cluster val : cluster) {
261                     if ((val.getServerRefByRef(instanceName)) != null) {
262                         appRef = val.getApplicationRefByRef(actionMBeanName);
263                         break;
264                     }
265                 }
266             }
267         
268             //should have obtained the app reference, if all well
269
if (appRef != null) {
270                 //check there exists a definition
271
Applications apps = domain.getApplications();
272                 Mbean definedMBean = apps.getMbeanByName(actionMBeanName);
273                 if (definedMBean == null ) {
274                     appRef = null;
275                 }
276             }
277         } catch (ConfigException ex) {
278             _logger.log(Level.INFO, "smgt.config_error", ex);
279         }
280         
281         return appRef;
282     }
283
284     /**
285      * Handles deletion of an existing rule
286      *
287      * @param name The Rule name which needs to be deleted
288      */

289     public void deleteRule(String JavaDoc name) {
290         Event ruleEvent = null;
291         String JavaDoc description = null;
292         Rule ruleInstance = null;
293         
294         try {
295             if (activeRules.containsKey(name)) {
296                 //remove from the active list and its binding
297
ruleInstance = activeRules.remove(name);
298                 ruleEvent = ruleInstance.getEvent();
299                 NotificationFilter JavaDoc filter = ruleEvent.getNotificationFilter();
300                 ObjectName JavaDoc eventObjName = ruleEvent.getObjectName();
301
302                 ObjectName JavaDoc actionObjName = (ObjectName JavaDoc)ruleInstance.getAction();
303                 instanceMbs.removeNotificationListener(eventObjName,actionObjName,
304                                                        filter, null);
305                 ruleEvent.destroy();
306
307             } else if (inActiveRules.containsKey(name)) {
308                 //remove from in active set and its binding
309
ruleInstance = inActiveRules.remove(name);
310                 //alert action ?
311
ruleEvent = ruleInstance.getEvent();
312                 ruleEvent.destroy();
313             } else if (noActionRules.containsKey(name)) {
314                 //remove from no action set and its binding
315
ruleInstance = noActionRules.remove(name);
316                 ruleEvent = ruleInstance.getEvent();
317                 ruleEvent.destroy();
318             } else if (disabledRules.containsKey(name)) {
319                 //remove from disabled set
320
ruleInstance = disabledRules.remove(name);
321             } else {
322                 //log error
323
_logger.log(Level.WARNING,"sgmt.delete_invalidname", name);
324                 return;
325             }
326         } catch (Exception JavaDoc ex) {
327             _logger.log(Level.WARNING, "sgmt.error_delete_rule",
328                         new Object JavaDoc[]{name,ex.toString()});
329             return;
330         }
331        
332         description = ruleInstance.getDescription();
333
334         _logger.log(Level.INFO,"sgmt.deleted_rule",
335                     new Object JavaDoc[] {name,description});
336
337         //ensure gc of contained event
338
ruleInstance = null;
339     }
340
341     
342     /**
343      * Handles addition of disabled rules under management_rules
344      * as configured in domain.xml
345      *
346      * @param ruleName
347      * Identifies the defined management rule.
348      * @param description
349      * Associates message with the intent of the defined rule.
350      */

351     public void addDisabledRule(String JavaDoc ruleName, String JavaDoc ruleDescription) {
352         Rule ruleInstance = new Rule(ruleName, ruleDescription);
353         setupRuleBinding(Rule.DISABLED, ruleInstance, null, null);
354     }
355     
356     /**
357      * Determines if an event already exists which matches the
358      * details of the passed type and configured event properties
359      *
360      *@return Event : The already existing event instance
361      * null : If no such event has been configured
362      */

363     Event checkEventExists(String JavaDoc type, ElementProperty[] eventProps) {
364         //placeHolder
365
return null;
366         
367     }
368     
369     /**
370      * For valid and enabled rule definitions registers the action to the
371      * defined event.
372      *
373      * @param ruleEvent
374      * @param actionMBeanName
375      * @param definedActionMBean
376      * @param isSystemDefined
377      * @param handback
378      * @return ObjectName
379      */

380     private ObjectName JavaDoc registerAction(Event ruleEvent, String JavaDoc actionMBeanName,
381                            Mbean definedActionMBean, boolean isSystemDefined, Object JavaDoc handback)
382                                               throws InstanceNotFoundException JavaDoc,
383                                                      MalformedObjectNameException JavaDoc {
384        ObjectName JavaDoc actionObjName = null;
385        ObjectName JavaDoc eventObjName = ruleEvent.getObjectName();
386        NotificationFilter JavaDoc filter = ruleEvent.getNotificationFilter();
387
388        try {
389             //check if this is a system defined rule then explictly load the MBean
390
if (isSystemDefined) {
391                 CustomMBeanRegistration obj = getCustomMBeanRegistration();
392                 actionObjName = obj.registerMBean(definedActionMBean);
393                 instanceMbs.addNotificationListener(eventObjName, actionObjName,
394                                                     filter, null);
395             } else {
396                 //user defined should have been loaded by adminservice
397
//if mbean has defined object name, use that to obtain
398
//obj instance else use objectnames static call for apps
399
String JavaDoc objName = definedActionMBean.getObjectName();
400                 if (objName == null) {
401                     //should have been assigned implict obj name
402
actionObjName = ObjectNames.getApplicationObjectName(
403                                                                    instanceName,
404                                                                    actionMBeanName);
405                 } else {
406                     //actionObjName = new ObjectName(objName);
407
actionObjName = getCascadedObjectName(objName);
408                 }
409
410                 instanceMbs.addNotificationListener(eventObjName, actionObjName,
411                                                     filter, null);
412                 if (handback!=null) {
413                 createLoggingListener (ruleEvent, handback);
414                 }
415             }
416         } catch (RuntimeException JavaDoc ex) {
417             if ( ex.getCause() instanceof InstanceAlreadyExistsException JavaDoc) {
418                 String JavaDoc objName = definedActionMBean.getObjectName();
419                 actionObjName = getCascadedObjectName(objName);
420             } else {
421                 throw ex;
422             }
423         }
424
425       return actionObjName;
426     }
427     
428     /**
429      * Registers MailAlert listener for the defined enabled rule incase the
430      * there has been error loading/registering the action when loading
431      * the system applications.
432      *
433      * @param ruleEvent
434      * @param actionMBeanName
435      * @param ruleName
436      * @param handback
437      */

438     private Object JavaDoc registerAlertAction(Event ruleEvent, String JavaDoc actionMBeanName,
439                                        String JavaDoc ruleName, Object JavaDoc handback)
440                                        throws InstanceNotFoundException JavaDoc {
441         NotificationFilterSupport JavaDoc filter = null;
442         if (srvAlertRecipients == null) {
443             //disable the event in filter
444
filter = new NotificationFilterSupport JavaDoc();
445             filter.disableAllTypes();
446         }
447         String JavaDoc subject = localStrings.getString("ruleMgr.alert_action",
448                                                     ruleName, actionMBeanName);
449         MailAlert alertAction = new MailAlert();
450         alertAction.setSubject(subject);
451         alertAction.setRecipients(srvAlertRecipients);
452         
453
454         ObjectName JavaDoc eventObjName = ruleEvent.getObjectName();
455         // instanceMbs.addNotificationListener(eventObjName, alertAction, filter, null);
456
createLoggingListener (ruleEvent, handback);
457
458         return alertAction;
459     }
460     /**
461      * Setup the the bindings for the RuelManager for defined rules in
462      * domain.xml
463      *
464      * @param ruleState
465      * @param ruleInstance
466      * @param ruleEvent
467      * @param action
468      * Incase of enabled rule, this would be it's object name
469      * Incase of inactive rule, this would be mail alert obj listener.
470      */

471     private void setupRuleBinding(int ruleState, Rule ruleInstance,
472                                   Event ruleEvent, Object JavaDoc action) {
473         
474         String JavaDoc ruleName = ruleInstance.getName();
475         
476         ruleInstance.setState(ruleState);
477         if (ruleState != Rule.DISABLED) {
478             ruleInstance.setEvent(ruleEvent);
479             ruleInstance.setAction(action);
480             ruleInstance.setEnabled(true);
481         }
482         
483         switch (ruleState) {
484         case Rule.ENABLED:
485             activeRules.put(ruleName, ruleInstance);
486             break;
487              
488         case Rule.INACTIVE:
489             inActiveRules.put(ruleName, ruleInstance);
490             break;
491         
492         case Rule.NOACTION:
493             noActionRules.put(ruleName, ruleInstance);
494             break;
495             
496         case Rule.DISABLED:
497             //event and action would be null by default during rule creation
498
disabledRules.put(ruleName, ruleInstance);
499             break;
500         }
501     }
502
503     /**
504      * Retrives the custom MBean interface responsible for loading/registering
505      * the custom defined MBeans.
506      */

507     private CustomMBeanRegistration getCustomMBeanRegistration() {
508
509         //This a temp support, till appropriate provider is provided later
510
final String JavaDoc CUSTOM_REGRISTRATION_IMPL_CLASS =
511           "com.sun.enterprise.admin.mbeans.custom.loading.CustomMBeanRegistrationImpl";
512         CustomMBeanRegistration customObj = null;
513
514         Constructor JavaDoc ctor = null;
515     Object JavaDoc[] args = null;
516
517         try {
518             Class JavaDoc c = Class.forName(CUSTOM_REGRISTRATION_IMPL_CLASS);
519             Class JavaDoc[] params = new Class JavaDoc[]{javax.management.MBeanServer JavaDoc.class};
520             ctor = c.getConstructor(params);
521             args = new Object JavaDoc[]{instanceMbs};
522
523             customObj = (CustomMBeanRegistration) ctor.newInstance(args);
524         } catch (Exception JavaDoc ex) {
525             _logger.log(Level.FINE,"smgt.internal_error", ex);
526         }
527
528         return customObj;
529     }
530     
531     /**
532      * Sets the service property which defines the mail SMTP host to be
533      * used for sending the service alert messages
534      *
535      * @param value
536      * SMTP host
537      */

538     public void setMailSMTPHost(String JavaDoc value) {
539         if ( mailSMTPHost != null) {
540             mailSMTPHost = value;
541         } else {
542             mailSMTPHost = "localhost";
543         }
544     }
545     
546     /**
547      * Sets the service property which defines the recipients of alert
548      * messages from the service
549      *
550      * @param value
551      * Recipients of alert messages
552      */

553     public void setRecipients(String JavaDoc value) {
554         srvAlertRecipients = value;
555     }
556     
557     /*
558      * Provides the cascading aware object name
559      */

560     private ObjectName JavaDoc getCascadedObjectName(String JavaDoc actionMBeanName)
561                                            throws MalformedObjectNameException JavaDoc{
562         ObjectName JavaDoc configObjName = new ObjectName JavaDoc(actionMBeanName);
563         String JavaDoc serverNameKey = ServerTags.SERVER;
564         Hashtable JavaDoc properties = configObjName.getKeyPropertyList();
565         properties.put(serverNameKey, instanceName);
566         ObjectName JavaDoc casdObjName = new ObjectName JavaDoc(configObjName.getDomain(),
567                                                      properties);
568         return (casdObjName);
569     }
570
571     
572     private void createLoggingListener (Event event, Object JavaDoc handback)
573         throws InstanceNotFoundException JavaDoc{
574     NotificationListener logListener = LogMgmtEventsNotificationListener.getInstance();
575     instanceMbs.addNotificationListener (event.getObjectName(), logListener, event.getNotificationFilter(), handback);
576     return;
577     }
578
579    /**
580     * Handles an update to a configured rule.
581     *
582     * @param rule - The config bean for the rule from the old config
583     * context
584     * @param configUp - Contains the config changes for the rule
585     * @param ctxToUse - The updated config context
586     */

587    void updateRule(ManagementRule rule, ConfigUpdate configUp,
588                    ConfigContext ctxToUse) throws Exception JavaDoc {
589        String JavaDoc name = rule.getName();
590        Rule ruleInstance = getRuleInstance(name);
591
592        // null should not be the case with validator check
593
if (ruleInstance!=null) {
594            synchronized(ruleInstance) {
595                String JavaDoc description = ruleInstance.getDescription();
596                Set JavaDoc<String JavaDoc> attributesChg = configUp.getAttributeSet();
597                for (String JavaDoc attribute : attributesChg) {
598                    if (attribute.equals(ServerTags.ENABLED)) {
599                        String JavaDoc oldValue = configUp.getOldValue(attribute);
600                        String JavaDoc newValue = configUp.getNewValue(attribute);
601                        _logger.log(Level.INFO,"sgmt.updateruleattribute",
602                                    new Object JavaDoc[]{attribute,oldValue,newValue});
603                        if (ruleInstance.isEnabled() && newValue.equals("false")) {
604                            if (service.isServiceEnabled()) {
605                                //disable the rule
606
disableRule(ruleInstance,false);
607                                _logger.log(Level.INFO,"smgt.disabledrule",
608                                            new Object JavaDoc[]{name,description});
609                             } else {
610                                //with validator, may not need this
611
_logger.log(Level.WARNING,"sgmt.error_disablerule_noservice",
612                                            new Object JavaDoc[]{name,description});
613                             }
614                        } else if (!ruleInstance.isEnabled() && newValue.equals("true")) {
615                            //enabled the rule
616
if (service.isServiceEnabled()) {
617                                service.addRule(rule,ctxToUse);
618                                _logger.log(Level.INFO,"smgt.enabledrule",
619                                            new Object JavaDoc[]{name,description});
620                            } else {
621                                //with validator, may not need this
622
_logger.log(Level.WARNING,"sgmt.error_enablerule_noservice",
623                                           new Object JavaDoc[]{name,description});
624                            }
625                        } else {
626                           _logger.log(Level.INFO,"smgt.cannot_changesstate",
627                                       new Object JavaDoc[]{name,description});
628                        }
629                    }
630                }
631            }
632        }
633    }
634
635    private Rule getRuleInstance(String JavaDoc ruleName) {
636        Rule rule = null;
637        if (activeRules.containsKey(ruleName)) {
638            rule = activeRules.get(ruleName);
639        } else if (disabledRules.containsKey(ruleName)) {
640            rule = disabledRules.get(ruleName);
641        } else if (inActiveRules.containsKey(ruleName)) {
642            rule = inActiveRules.get(ruleName);
643        } else if (noActionRules.containsKey(ruleName)) {
644            rule = noActionRules.get(ruleName);
645        }
646
647        return rule;
648    }
649
650    private Map JavaDoc getRuleMap(String JavaDoc ruleName) {
651        Map JavaDoc ruleMap = null;
652   
653        if (activeRules.containsKey(ruleName)) {
654            ruleMap = activeRules;
655        } else if (disabledRules.containsKey(ruleName)) {
656            ruleMap = disabledRules;
657        } else if (inActiveRules.containsKey(ruleName)) {
658            ruleMap = inActiveRules;
659        } else if (noActionRules.containsKey(ruleName)) {
660            ruleMap = noActionRules;
661        }
662
663        return ruleMap;
664    }
665
666    private void disableRule(Rule ruleInstance, boolean disableService) throws Exception JavaDoc {
667        /*
668         * The disableService param determines whether the call is due
669         * to service being disabled and thus the rule would get implicitly
670         * /internally disabled or due to an explict call to disable the
671         * configured rule.
672         */

673        String JavaDoc ruleName = ruleInstance.getName();
674        Event ruleEvent = ruleInstance.getEvent();
675      
676  
677        try {
678            if (ruleInstance.getState() == Rule.ENABLED) {
679                //remove the event action binding
680
NotificationFilter JavaDoc filter = ruleEvent.getNotificationFilter();
681                ObjectName JavaDoc eventObjName = ruleEvent.getObjectName();
682                ObjectName JavaDoc actionObjName = (ObjectName JavaDoc)ruleInstance.getAction();
683
684                instanceMbs.removeNotificationListener(eventObjName,actionObjName,
685                                                       filter, null);
686                ruleInstance.setAction(null);
687                if (!disableService) {
688                    activeRules.remove(ruleName);
689                }
690            } else if (ruleInstance.getState() == Rule.INACTIVE) {
691                //remove event binding, default action (when supported)
692
ruleInstance.setAction(null);
693                if (!disableService) {
694                    inActiveRules.remove(ruleName);
695                }
696            } else if (ruleInstance.getState() == Rule.NOACTION) {
697                ruleInstance.setAction(null);
698                if (!disableService) {
699                    noActionRules.remove(ruleName);
700                }
701            }
702
703            //notificationfiltersupport?
704
ruleEvent.destroy();
705            ruleInstance.setEvent(null);
706            if (!disableService) {
707                //call is for explict rule disable
708
ruleInstance.setEnabled(false);
709                ruleInstance.setState(Rule.DISABLED);
710                disabledRules.put(ruleName,ruleInstance);
711                
712            }
713        } catch (Exception JavaDoc ex) {
714            _logger.log(Level.WARNING,"sgmt.error_disablerule",
715                        new Object JavaDoc[]{ruleName,ex});
716            throw ex;
717        }
718
719    }
720
721   /**
722    * Handles disabling the service. Would internally disable all
723    * enabled rules.
724    */

725   synchronized void disableService() throws Exception JavaDoc {
726       int size = activeRules.size() + inActiveRules.size() + noActionRules.size();
727       Map JavaDoc<String JavaDoc,Rule> completeMap = (Map JavaDoc<String JavaDoc,Rule>) new HashMap JavaDoc(size);
728       completeMap.putAll(activeRules);
729       completeMap.putAll(inActiveRules);
730       completeMap.putAll(noActionRules);
731
732       Set JavaDoc<String JavaDoc> rules = completeMap.keySet();
733       for (String JavaDoc name : rules) {
734           Rule ruleInstance = completeMap.get(name);
735           disableRule(ruleInstance,true);
736       }
737   }
738
739   /**
740    * Handles addition of action
741    *
742    * @param ruleName : Identifies the rule to which action is being added
743    * @param actionName : Identifies the action MBean name
744    */

745   void addAction(String JavaDoc ruleName, String JavaDoc actionName, ConfigContext ctxToUse) {
746        Rule ruleInstance = getRuleInstance(ruleName);
747        if (ruleInstance!=null) {
748            synchronized(ruleInstance) {
749                bindAction(ruleInstance,actionName,ctxToUse);
750            }
751        }
752    }
753
754   private void bindAction(Rule ruleInstance, String JavaDoc actionMBeanName,
755                           ConfigContext ctxToUse) {
756       String JavaDoc ruleName = ruleInstance.getName();
757       Event ruleEvent = ruleInstance.getEvent();
758       ObjectName JavaDoc actionObjName = null;
759
760       try {
761           Domain domain = ServerBeansFactory.getDomainBean(ctxToUse);
762           ApplicationRef appRef = verifyActionMBean(actionMBeanName, domain, ctxToUse);
763
764
765           if (appRef != null) {
766               Applications apps = domain.getApplications();
767               Mbean definedMBean = apps.getMbeanByName(actionMBeanName);
768
769
770               if (appRef.isEnabled() && definedMBean.isEnabled() ) {
771                   if ((definedMBean.getObjectType()).equals(USER_DEFINED_TYPE)) {
772                       actionObjName = registerAction(ruleEvent,actionMBeanName,
773                                                      definedMBean,false,null);
774                   } else {
775                       // system defined, need to explictly load
776
actionObjName = registerAction(ruleEvent,actionMBeanName,
777                                                      definedMBean,true,null);
778                   }
779                   //update the binding
780
ruleInstance.setAction((Object JavaDoc)actionObjName);
781                   _logger.log(Level.INFO,"smgt.successaddaction",
782                                new Object JavaDoc[]{ruleName,actionMBeanName});
783               } else {
784                   /* action is disabled, but rule is active; Add a default mail
785                    * alert
786                    */

787                   //alertAction = registerAlertAction(ruleEvent, actionMBeanName,
788
// ruleName, null);
789
_logger.log(Level.WARNING,"sgmt.ruleactiondisabled",
790                               new Object JavaDoc[]{ruleName,actionMBeanName});
791                   //update the binding
792
ruleInstance.setState(Rule.INACTIVE);
793               }
794            } else {
795                //log error, invalid action MBean provided for this rule
796
_logger.log(Level.SEVERE, "smgt.invalid_action", new Object JavaDoc[]{
797                            ruleName, actionMBeanName});
798                //config error
799
}
800         } catch (ConfigException ex) {
801             _logger.log(Level.INFO, "config_error", ex);
802         } catch (InstanceNotFoundException JavaDoc ex) {
803             //log it,
804
_logger.log(Level.INFO, "smgt.error_reg_action", new Object JavaDoc[]{
805                         ruleName, actionMBeanName});
806             //registerAlertAction(ruleEvent, actionMBeanName, ruleName, null);
807
} catch (MalformedObjectNameException JavaDoc ex) {
808             _logger.log(Level.WARNING, "sgmt.error_reg_action", new Object JavaDoc[]{
809                         ruleName, actionMBeanName});
810         } catch (RuntimeOperationsException JavaDoc ex) {
811             //log it, actionMBean is not a listener type, add to inactive rules
812
_logger.log(Level.WARNING, "smgt.error_reg_action", new Object JavaDoc[]{
813                         ruleName,actionMBeanName});
814             //registerAlertAction(ruleEvent, actionMBeanName, ruleName, null);
815
} catch (RuntimeException JavaDoc ex) {
816             /*
817              *log it, as thrown from customRegistration, add to inactive rules
818              */

819             _logger.log(Level.WARNING, "smgt.error_reg_action", new Object JavaDoc[] {
820                         ruleName, actionMBeanName});
821            //registerAlertAction(ruleEvent, actionMBeanName, ruleName, null);
822
}
823    }
824
825 }
826
Popular Tags