View Javadoc
1   /**
2    * This Source Code Form is subject to the terms of the Mozilla Public License,
3    * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4    * obtain one at http://mozilla.org/MPL/2.0/.
5    *
6    * If it is not possible or desirable to put the notice in a particular file,
7    * then You may include the notice in a location (such as a LICENSE file in a
8    * relevant directory) where a recipient would be likely to look for such a
9    * notice.
10   *
11   * 
12   */
13  /*  ---------------------------------------------------------------------------
14   *  U.S. Government, Department of the Army
15   *  Army Materiel Command
16   *  Research Development Engineering Command
17   *  Communications Electronics Research Development and Engineering Center
18   *  ---------------------------------------------------------------------------
19   */
20  package org.miloss.fgsms.auxsrv;
21  
22  import java.math.BigInteger;
23  import java.sql.Connection;
24  import java.sql.PreparedStatement;
25  import java.sql.ResultSet;
26  import java.util.GregorianCalendar;
27  import java.util.List;
28  import javax.xml.datatype.DatatypeFactory;
29  import javax.xml.datatype.Duration;
30  import org.apache.log4j.Level;
31  import org.miloss.fgsms.common.Logger;;
32  import org.miloss.fgsms.common.DBSettingsLoader;
33  import org.miloss.fgsms.common.DBUtils;
34  import org.miloss.fgsms.common.Utility;
35  import org.miloss.fgsms.plugins.federation.FederationInterface;
36  import org.miloss.fgsms.services.interfaces.common.PolicyType;
37  import org.miloss.fgsms.services.interfaces.dataaccessservice.QuickStatData;
38  import org.miloss.fgsms.services.interfaces.dataaccessservice.QuickStatWrapper;
39  import org.miloss.fgsms.services.interfaces.policyconfiguration.KeyNameValueEnc;
40  import org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicy;
41  import org.miloss.fgsms.sla.AuxHelper;
42  import org.miloss.fgsms.sla.SLACommon;
43  import org.quartz.JobExecutionContext;
44  import org.quartz.JobExecutionException;
45  
46  /**
47   **Quartz Job that kicks off the UDDI Publisher This job as
48   * well as the UDDI publisher is handled differently from the other fgsms quartz
49   * jobs. It runs every 5 minutes by default, however does no work unless we have
50   * gone past the scheduled interval. This is done so that status information is
51   * correctly displayed.
52   *
53   * @author AO
54   */
55  public class FederationScheduler implements org.quartz.StatefulJob // implements org.jboss.varia.scheduler.Schedulable {
56  {
57  
58       public void UddiScheduler() {
59       }
60       private static Logger log = Logger.getLogger("fgsms.FederationScheduler");
61  
62       public void execute(JobExecutionContext jec) throws JobExecutionException {
63            
64            KeyNameValueEnc enabled = DBSettingsLoader.GetPropertiesFromDB(true, "FederationScheduler", "Enabled");
65            if (enabled == null || enabled.getKeyNameValue() == null || enabled.getKeyNameValue().getPropertyValue() == null
66                    || enabled.getKeyNameValue().getPropertyValue().equalsIgnoreCase("false")) {
67                 //added 5/8/2012 to indicate that the cron job is running, however the required settings are not set for the uddi publisher, sort of sanity check
68                 AuxHelper.TryUpdateStatus(true, "urn:fgsms:FederationScheduler:" + SLACommon.GetHostName(), "Disabled", true, PolicyType.STATUS, AuxHelper.UNSPECIFIED, SLACommon.GetHostName());
69                 return;
70            }
71            AuxHelper.TryUpdateStatus(true, "urn:fgsms:FederationScheduler:" + SLACommon.GetHostName(), "OK", true, PolicyType.STATUS, AuxHelper.UNSPECIFIED, SLACommon.GetHostName());
72  
73            KeyNameValueEnc interval = DBSettingsLoader.GetPropertiesFromDB(true, "FederationScheduler", "Interval");
74            long intinterval = 3600000;
75            if (interval != null) {
76                 try {
77                      intinterval = Long.parseLong(interval.getKeyNameValue().getPropertyValue());
78                      if (intinterval < 300000) {
79                           intinterval = 300000;
80                      }
81                 } catch (Exception ex) {
82                 }
83            }
84  
85            Long lastranat = null;
86            try {
87                 lastranat = (Long) jec.getJobDetail().getJobDataMap().get("lastranat");
88            } catch (Exception ex) {
89            }
90            if (lastranat == null) {
91                 lastranat = (long) 0;
92  
93            }
94  
95            if (lastranat + intinterval < System.currentTimeMillis()) {
96                 log.log(Level.INFO, "========================================================== Federation Job executing...");
97                 try {
98                 // UddiPublisher pub = new UddiPublisher(true);
99                      // if (pub.State) {
100                     List<ServicePolicy> LoadFederationServicePoliciesPooled = SLACommon.LoadFederationServicePoliciesPooled();
101                     for (int i = 0; i < LoadFederationServicePoliciesPooled.size(); i++) {
102                          if (LoadFederationServicePoliciesPooled.get(i).getFederationPolicyCollection() != null) {
103                               for (int k = 0; k < LoadFederationServicePoliciesPooled.get(i).getFederationPolicyCollection().getFederationPolicy().size(); k++) {
104                                    String clazz = LoadFederationServicePoliciesPooled.get(i).getFederationPolicyCollection().getFederationPolicy().get(k).getImplementingClassName();
105                                    FederationInterface newInstance = null;
106                                    try {
107                                         Class<FederationInterface> forName = (Class<FederationInterface>) Class.forName(clazz);
108                                         newInstance = forName.newInstance();
109                                         if (newInstance != null) {
110                                              newInstance.Publish(true, getQuickStatData(LoadFederationServicePoliciesPooled.get(i).getURL(), true), LoadFederationServicePoliciesPooled.get(i), LoadFederationServicePoliciesPooled.get(i).getFederationPolicyCollection().getFederationPolicy().get(k));
111                                         }
112                                    } catch (Exception ex) {
113                                         log.log(Level.FATAL, "unable to load federation plugin! classname=" + clazz, ex);
114                                    }
115 
116                               }
117 
118                          }
119                          // }
120 
121                          AuxHelper.TryUpdateStatus(true, "urn:fgsms:FederationScheduler:" + SLACommon.GetHostName(), "OK", true, PolicyType.STATUS, AuxHelper.UNSPECIFIED, SLACommon.GetHostName());
122                // } else {
123                          //     log.log(Level.ERROR, "uddi publisher state is false, something went wrong");
124                          //     AuxHelper.TryUpdateStatus(false, "urn:fgsms:FederationScheduler:" + SLACommon.getHostName(), "Error - Check Config", true, PolicyType.STATUS, AuxHelper.UNSPECIFIED, SLACommon.getHostName());
125                     }
126                } catch (Exception ex) {
127                     log.log(Level.ERROR, "error caught from uddi publisher", ex);
128                     AuxHelper.TryUpdateStatus(false, "urn:fgsms:FederationScheduler:" + SLACommon.GetHostName(), ex.getMessage(), true, PolicyType.STATUS, AuxHelper.UNSPECIFIED, SLACommon.GetHostName());
129                }
130                jec.getJobDetail().getJobDataMap().put("lastranat", System.currentTimeMillis());
131           } else {
132                //this needs to just update the same timestamp, not set the status
133                //repeat for the other jobs
134                //AuxHelper.TryUpdateStatus(true, "urn:fgsms:FederationScheduler:" + SLACommon.getHostName(), "OK", true, PolicyType.STATUS, AuxHelper.UNSPECIFIED, SLACommon.getHostName());
135           }
136      }
137 
138      private QuickStatWrapper getQuickStatData(String urL, boolean pooled) {
139 
140           PreparedStatement com=null;
141          
142           if (Utility.stringIsNullOrEmpty(urL)) {
143                return null;
144           }
145           Connection con = null;
146           
147           ResultSet rs=null;
148           try {
149                
150                if (pooled) {
151                     con = Utility.getPerformanceDBConnection();
152                } else {
153                     con = Utility.getPerformanceDB_NONPOOLED_Connection();
154                }
155                com = con.prepareStatement("select * from agg2 where uri=? and soapaction=?;");
156                com.setString(1, urL);
157                com.setString(2, "All-Methods");
158                rs = com.executeQuery();
159 
160                QuickStatWrapper w = new QuickStatWrapper();
161                w.setAction("All-Methods");
162 
163                DatatypeFactory df = DatatypeFactory.newInstance();
164                while (rs.next()) {
165 
166                     QuickStatData d = new QuickStatData();
167 
168                     long timerange = rs.getLong("timerange");
169                     d.setTimeInMinutes(BigInteger.valueOf(timerange / 60000));
170                     d.setAvailabilityPercentage(rs.getDouble("avail"));
171                     d.setFailureCount(rs.getLong("failure"));
172                     d.setSuccessCount(rs.getLong("success"));
173                     d.setSLAViolationCount(rs.getLong("sla"));
174                     d.setAverageResponseTime(rs.getLong("avgres"));
175                     if (rs.getLong("mtbf") == -1) {
176                          d.setMTBF(null);
177                     } else {
178                          d.setMTBF(df.newDuration(rs.getLong("mtbf")));
179                     }
180                     d.setMaximumRequestSize(rs.getLong("maxreq"));
181                     d.setMaximumResponseSize(rs.getLong("maxres"));
182                     d.setMaximumResponseTime(rs.getLong("maxresponsetime"));
183                     GregorianCalendar gcal = new GregorianCalendar();
184                     gcal.setTimeInMillis(rs.getLong("timestampepoch"));
185                     d.setUpdatedAt((gcal));
186                     w.getQuickStatData().add(d);
187 
188                }
189 
190                w.setUptime(getUpTime(urL));
191                rs.close();
192                com.close();
193                con.close();
194 
195                return w;
196           } catch (Exception ex) {
197                log.log(Level.WARN, "can't get statistics for " + urL, ex);
198           } finally {
199               DBUtils.safeClose(rs);
200               DBUtils.safeClose(com);
201               DBUtils.safeClose(con);
202           }
203           return null;
204      }
205 
206      private Duration getUpTime(String uri) {
207          Connection con=null;
208          PreparedStatement com=null;
209          ResultSet rs= null;
210           try {
211                con = Utility.getPerformanceDBConnection();
212                com = con.prepareStatement("select * from availability where uri=? order by utcdatetime desc limit 1");
213                com.setString(1, uri);
214                Duration d = null;
215                rs = com.executeQuery();
216                if (rs.next()) {
217                     long changeat = rs.getLong("utcdatetime");
218                     long now = System.currentTimeMillis();
219                     DatatypeFactory f = DatatypeFactory.newInstance();
220                     d = f.newDuration(now - changeat);
221                }
222                
223                if (d != null) {
224                     return d;
225                }
226           } catch (Exception ex) {
227                log.log(Level.ERROR, null, ex);
228           } finally {
229               DBUtils.safeClose(rs);
230               DBUtils.safeClose(com);
231               DBUtils.safeClose(con);
232           }
233           return null;
234      }
235 }