KickJava   Java API By Example, From Geeks To Geeks.

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


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.appserv.server.ServerLifecycle;
26 import com.sun.appserv.server.ServerLifecycleException;
27 import com.sun.enterprise.server.ServerContext;
28
29 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
30 import com.sun.enterprise.config.serverbeans.Config;
31 import com.sun.enterprise.config.serverbeans.ElementProperty;
32 import com.sun.enterprise.config.serverbeans.ManagementRules;
33 import com.sun.enterprise.config.serverbeans.ManagementRule;
34 import com.sun.enterprise.config.serverbeans.Event;
35 import com.sun.enterprise.config.serverbeans.Action;
36 import com.sun.enterprise.config.serverbeans.ServerTags;
37 import com.sun.enterprise.config.ConfigUpdate;
38
39 import com.sun.enterprise.config.ConfigContext;
40 import com.sun.enterprise.config.ConfigException;
41
42 import com.sun.enterprise.admin.AdminContext;
43 import com.sun.enterprise.admin.server.core.AdminService;
44 import com.sun.enterprise.admin.event.AdminEventListenerRegistry;
45 import com.sun.enterprise.admin.event.selfmanagement.ManagementRuleEvent;
46 import com.sun.enterprise.management.selfmanagement.reconfig.ManagementRuleReconfig;
47
48 import javax.management.MBeanServer JavaDoc;
49 import javax.management.InstanceNotFoundException JavaDoc;
50 import javax.management.MalformedObjectNameException JavaDoc;
51
52 //import com.sun.enterprise.admin.selfmanagement.event.Event;
53
import com.sun.enterprise.admin.selfmanagement.event.EventBuilder;
54
55 import java.util.logging.Logger JavaDoc;
56 import java.util.logging.Level JavaDoc;
57 import java.lang.String JavaDoc;
58 import java.util.HashMap JavaDoc;
59 import java.util.Map JavaDoc;
60 import java.util.Set JavaDoc;
61 import com.sun.logging.LogDomains;
62
63 /**
64  * The core class for the self management service. As part of
65  * server startup, it reads in the instance management rules
66  * and sets them up.
67  *
68  * @author Pankaj Jairath
69  */

70 public class SelfManagementService implements ServerLifecycle {
71     
72     static private Logger JavaDoc _logger = LogDomains.getLogger(
73                                             LogDomains.SELF_MANAGEMENT_LOGGER);
74     
75     private static SelfManagementService serviceInstance = null;
76
77     private RuleManager rulesManager = null;
78     
79     private EventBuilder eventBuilder = null;
80     
81     private boolean isServiceEnabled = false;
82     
83               
84     /** Creates a new instance of SelfManagementService */
85     public SelfManagementService() {
86         
87     }
88  
89     /**
90      * Server is initializing subsystems and setting up the runtime environment.
91      * Prepare for the beginning of active use of the public methods of this
92      * subsystem. This method is called before any of the public methods of
93      * this subsystem are utilized.
94      *
95      * @param sc ServerContext the server runtime context.
96      *
97      * @exception IllegalStateException if this subsystem has already been
98      * started
99      * @exception ServerLifecycleException if this subsystem detects a fatal
100      * error that prevents this subsystem from being used
101      */

102     public void onInitialization(ServerContext sc)
103                         throws ServerLifecycleException {
104         /*
105          *would need support from domain.xml management_rules to support
106          *service properties.
107          */

108         final String JavaDoc RULES_MAIL_SMTP_HOST = "mail.smtp.host";
109         final String JavaDoc RULES_ALERT_RECIPIENTS = "rules.recipients";
110                 
111         // initialize the Rules Manager
112
rulesManager = new RuleManager(this);
113         eventBuilder = EventBuilder.getInstance();
114         _logger.log(Level.FINE, "smgt.service_init");
115         
116         String JavaDoc mailSMTPHost = java.lang.System.getProperty(RULES_MAIL_SMTP_HOST);
117         String JavaDoc alertRecip = java.lang.System.getProperty(RULES_ALERT_RECIPIENTS);
118         rulesManager.setMailSMTPHost(mailSMTPHost);
119         rulesManager.setRecipients(alertRecip);
120         serviceInstance = this;
121
122         _logger.log(Level.INFO, "sgmt.service_initialized");
123     }
124
125     /**
126      * Server is starting up applications
127      *
128      * @param sc ServerContext the server runtime context.
129      *
130      * @exception ServerLifecycleException if this subsystem detects a fatal
131      * error that prevents this subsystem from being used
132      */

133     public void onReady(ServerContext sc)
134                         throws ServerLifecycleException {
135                 
136         try {
137             ConfigContext instanceConfigContext = sc.getConfigContext();
138             Config instanceConfig = ServerBeansFactory.getConfigBean(
139                                                          instanceConfigContext);
140             ManagementRules selfManagementRules = instanceConfig.getManagementRules();
141        
142             if ( selfManagementRules != null ) {
143                 if ( selfManagementRules.isEnabled() ) {
144                     _logger.log(Level.INFO, "smgt.service_enabled");
145                     isServiceEnabled = true;
146                     
147                     ManagementRule[] rules = selfManagementRules.getManagementRule();
148                     if (rules != null) {
149                         for (int i = 0; i < rules.length; i++) {
150                             ManagementRule rule = rules[i];
151                             String JavaDoc ruleName = rule.getName();
152                             String JavaDoc ruleDescription = rule.getDescription();
153                         
154                             //check if rule is enabled then obtain event else skip
155
if (rule.isEnabled()) {
156                                // statically read ctx is used
157
addRule(rule,null);
158                            } else {
159                                _logger.log(Level.INFO, "smgt.service_rule_disabled",
160                                        new Object JavaDoc[]{ruleName, ruleDescription});
161                                //addDisabledRule(ruleName, ruleDescription);
162
addDisabledRule(rule);
163                            }
164                        }
165                    } else {
166                         _logger.log(Level.INFO,"smgt.service_no_rules_defined");
167                    }
168                 } else {
169                       _logger.log(Level.INFO,"smgt.service_disabled");
170                 }
171             } else {
172                   _logger.log(Level.INFO, "smgt.service_not_configured");
173             }
174
175             //activate this after the admin backend support is achieved
176
AdminEventListenerRegistry.addEventListener(ManagementRuleEvent.eventType,
177                                                     new ManagementRuleReconfig());
178         } catch (ConfigException ex) {
179             //just log, core can still come up, just warn at severe
180
_logger.log(Level.SEVERE, "smgt.config_error", ex);
181             //throw new ServerLifeCycleException(ex.getMessage(), ex);
182
} catch (Exception JavaDoc ex) {
183             _logger.log(Level.SEVERE, "sgmt.config_error, ex");
184         }
185     }
186
187     /**
188      * Server has complted loading the applications and is ready to serve requests.
189      *
190      * @param sc ServerContext the server runtime context.
191      *
192      * @exception ServerLifecycleException if this subsystem detects a fatal
193      * error that prevents this subsystem from being used
194      */

195     public void onStartup(ServerContext sc) throws ServerLifecycleException {
196         _logger.log(Level.FINE, "smgt.service_onready");
197
198     }
199
200     /**
201      * Server is shutting down applications
202      *
203      * @exception ServerLifecycleException if this subsystem detects a fatal
204      * error that prevents this subsystem from being used
205      */

206     public void onShutdown()
207                         throws ServerLifecycleException {
208         _logger.log(Level.FINE, "smgt.service_ontermination");
209     }
210
211     /**
212      * Server is terminating the subsystems and the runtime environment.
213      * Gracefully terminate the active use of the public methods of this
214      * subsystem. This method should be the last one called on a given
215      * instance of this subsystem.
216      *
217      * @exception ServerLifecycleException if this subsystem detects a fatal
218      * error that prevents this subsystem from being used
219      */

220     public void onTermination()
221                         throws ServerLifecycleException {
222         _logger.log(Level.FINE, "smgt.service_onshutdown");
223     }
224     
225     /**
226      * Checks if the event has been already defined for the management
227      * rules.
228      *
229      * @return Event The existing event or null if no such event exists.
230      */

231     private com.sun.enterprise.admin.selfmanagement.event.Event checkEventExist(
232                                     String JavaDoc type, ElementProperty[] eventProps) {
233         //pass the invocation to the contained core instance
234
com.sun.enterprise.admin.selfmanagement.event.Event event =
235                                rulesManager.checkEventExists(type, eventProps);
236                                                    
237         return event;
238     }
239     
240     /**
241      * Invokes the rule managers add rule to form the runtime binding
242      */

243     public void addRule(ManagementRule rule, ConfigContext ctxToUse) {
244                   
245         String JavaDoc actionMBeanName = null;
246         boolean isSkip = false;
247         String JavaDoc ruleName = rule.getName();
248         String JavaDoc ruleDescription = rule.getDescription();
249         
250         try {
251             final int ATTRIB_COUNT = 3;
252             com.sun.enterprise.config.serverbeans.Event event = null;
253             com.sun.enterprise.admin.selfmanagement.event.Event ruleEvent = null;
254             Map JavaDoc logHandback = new HashMap JavaDoc<String JavaDoc,String JavaDoc>(ATTRIB_COUNT);
255             
256             _logger.log(Level.INFO, "smgt.service_rule_enabled",
257                         new Object JavaDoc[]{ruleName, ruleDescription});
258                         
259             //getEvent
260
event = rule.getEvent();
261             String JavaDoc type = event.getType();
262             String JavaDoc description = event.getDescription();
263                                                              
264             logHandback.put(ServerTags.TYPE, type);
265             logHandback.put(ServerTags.RECORD_EVENT, String.valueOf(event.isRecordEvent()));
266             logHandback.put(ServerTags.LEVEL,event.getLevel());
267             
268             //Properties eventProperities = new Properties();
269

270             ElementProperty[] eventProps = event.getElementProperty();
271                                                       
272             /*activate after dependency support provided*/
273             //Event event = checkEventExists(type, eventProps);
274

275             //EventBuilder eventBuilder = EventBuilder.getInstance();
276
ruleEvent = getEvent(type, eventProps,description, ruleName);
277             if (ruleEvent == null) {
278                 //skip this rule, errorenous event props
279
return ;
280             }
281         
282             Action ruleAction = rule.getAction();
283             if (ruleAction != null) {
284                 actionMBeanName = ruleAction.getActionMbeanName();
285             }
286        
287             // pass the invocation to the contained core instance
288
rulesManager.addRule(ruleName, description, ruleEvent,
289                                  actionMBeanName, logHandback, ctxToUse);
290         } catch (InstanceNotFoundException JavaDoc ex) {
291             _logger.log(Level.INFO, "smgt.internal_error", ex);
292         }
293     }
294
295     /**
296      * Deletes a configured rule
297      *
298      * @param name: Name of the rule to delete
299      *
300      */

301     public void deleteRule(String JavaDoc rule) {
302          //delegate it to the rule manager
303
rulesManager.deleteRule(rule);
304     }
305     
306     /**
307      * Adds to the list of disabled rules
308      */

309     public void addDisabledRule(ManagementRule rule) {
310         //pass the invocation to rule manager
311
String JavaDoc ruleName = rule.getName();
312         String JavaDoc ruleDescription = rule.getDescription();
313         rulesManager.addDisabledRule(ruleName, ruleDescription);
314     
315     }
316     
317     /**
318      * Obtains the configured event
319      *
320      * @return The event instance
321      */

322     private com.sun.enterprise.admin.selfmanagement.event.Event getEvent(
323                                                   String JavaDoc type,
324                                                   ElementProperty[] eventProps,
325                                                   String JavaDoc description,
326                                                   String JavaDoc ruleName) {
327         com.sun.enterprise.admin.selfmanagement.event.Event eventInstance = null;
328         
329         try {
330             eventInstance = eventBuilder.getEvent(type, eventProps, description);
331         } catch( IllegalArgumentException JavaDoc ex) {
332             // some issue with configuring the event props
333
_logger.log(Level.INFO, "smgt.errorenous_event", new Object JavaDoc[]
334                          {ruleName, type});
335         }
336         
337         return eventInstance;
338     }
339     
340     /** Obtain instance to the service */
341     public static SelfManagementService getService() {
342         return serviceInstance;
343     }
344
345     /**
346      * handle Update for parent node - Management Rules
347      *
348      * @param configUpdate for the node
349      */

350     public void handleRulesUpdate(ConfigContext cfgCtx, ConfigUpdate configUp)
351                         throws Exception JavaDoc {
352        Set JavaDoc<String JavaDoc> attributesChg = configUp.getAttributeSet();
353        for (String JavaDoc attribute : attributesChg) {
354            if (attribute.equals(ServerTags.ENABLED)) {
355                String JavaDoc newValue = configUp.getNewValue(attribute);
356                if (isServiceEnabled && newValue.equals("false")) {
357                    _logger.log(Level.INFO,"sgmt.disableservice");
358                    synchronized(this) {
359                        isServiceEnabled = false;
360                        rulesManager.disableService();
361                    }
362                } else if (!isServiceEnabled && newValue.equals("true")) {
363                    _logger.log(Level.INFO,"sgmt.enableservice");
364                    synchronized(this) {
365                        isServiceEnabled = true;
366                        handleEnableService(cfgCtx);
367                    }
368                }
369            }
370        }
371     }
372
373   /**
374    * Handle Action addition
375    *
376    * @param rule - ManagementRule for which action is being added
377    * @param action - Action being added
378    */

379    public void handleActionAdd(ManagementRule rule, ConfigContext ctxToUse)
380                        throws Exception JavaDoc {
381        String JavaDoc ruleName = rule.getName();
382        String JavaDoc description = rule.getDescription();
383        Action actionToAdd = rule.getAction();
384        //Should be the case with validator
385
if (actionToAdd!=null) {
386            String JavaDoc actionName = actionToAdd.getActionMbeanName();
387            //validator?
388
if (isServiceEnabled && rule.isEnabled()) {
389                if (actionName!=null) {
390
391                    rulesManager.addAction(ruleName,actionName,ctxToUse);
392                }
393            } else {
394                _logger.log(Level.INFO, "smgt.erroraddaction_notenabled",
395                            new Object JavaDoc[]{ruleName,actionName});
396            }
397        } else {
398            _logger.log(Level.SEVERE,"smgt.error_add_noactionreceived",
399                        new Object JavaDoc[]{ruleName,description});
400            throw new RuntimeException JavaDoc();
401        }
402    }
403
404    /**
405     * Handle Action upate
406     *
407     * @param rule : ManagementRule element that has been updated
408     * configUp : The set of config changes on the child Action element
409     */

410    public void handleActionUpdate(ManagementRule rule, ConfigUpdate configUp) {
411        //not yet supported
412
}
413
414    /**
415     * Handle ManagementRule update
416     *
417     * @param rule : ManagementRule being updated
418     * configUp : The set of config changes on the rule.
419     */

420    public void handleRuleUpdate(ManagementRule rule, ConfigUpdate configUp,
421                                 ConfigContext ctxToUse)
422                        throws Exception JavaDoc {
423        //pass on to the delegate
424
rulesManager.updateRule(rule, configUp, ctxToUse);
425    }
426
427    /**
428     * handles the management rules being enabled
429     *
430     * @param configCtx The instance config context containing the management
431     * rules
432     */

433    void handleEnableService(ConfigContext configCtx) {
434        try {
435            Config instanceConfig = ServerBeansFactory.getConfigBean(configCtx);
436            ManagementRules selfManagementRules = instanceConfig.getManagementRules();
437            ManagementRule[] rules = selfManagementRules.getManagementRule();
438
439            for (ManagementRule rule : rules) {
440                if (rule.isEnabled()) {
441                    addRule(rule, configCtx);
442                } else {
443                    addDisabledRule(rule);
444                }
445            }
446        } catch (ConfigException ex) {
447            _logger.log(Level.WARNING,"sgmt.error_enableservice", ex);
448        }
449    }
450
451    boolean isServiceEnabled() {
452        return isServiceEnabled;
453    }
454 }
455
Popular Tags