View Javadoc
1   /*
2    * Copyright (c) 2006-2007 Hyperic, Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.miloss.fgsms.osagent;
17  
18  import org.hyperic.sigar.Sigar;
19  import org.hyperic.sigar.SigarProxy;
20  import org.hyperic.sigar.SigarException;
21  import org.hyperic.sigar.ProcCredName;
22  import org.hyperic.sigar.ProcMem;
23  import org.hyperic.sigar.ProcTime;
24  import org.hyperic.sigar.ProcState;
25  import org.hyperic.sigar.ProcUtil;
26  
27  import java.util.ArrayList;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.text.SimpleDateFormat;
31  import java.util.*;
32  import java.util.logging.Level;
33  import java.util.logging.Logger;
34  import org.miloss.fgsms.common.Utility;
35  import org.miloss.fgsms.services.interfaces.common.ProcessPerformanceData;
36  import org.hyperic.sigar.*;
37  import org.hyperic.sigar.cmd.Shell;
38  
39  
40  /**
41   * Show process status.
42   */
43  public class Ps extends SigarCommandBase implements Closable {
44  
45      public Ps(Shell shell) {
46          super(shell);
47      }
48  
49      public Ps() {
50          super();
51      }
52  
53  
54      public boolean isPidCompleter() {
55          return true;
56      }
57  
58      public static List getInfo(SigarProxy sigar, long pid)
59              throws SigarException {
60  
61          ProcState state = sigar.getProcState(pid);
62          ProcTime time = null;
63          String unknown = "???";
64  
65          List info = new ArrayList();
66          info.add(String.valueOf(pid));
67  
68          try {
69              ProcCredName cred = sigar.getProcCredName(pid);
70              info.add(cred.getUser());
71          } catch (SigarException e) {
72              info.add(unknown);
73          }
74  
75          try {
76              time = sigar.getProcTime(pid);
77              info.add(getStartTime(time.getStartTime()));
78          } catch (SigarException e) {
79              info.add(unknown);
80          }
81  
82          try {
83              ProcMem mem = sigar.getProcMem(pid);
84              info.add(Sigar.formatSize(mem.getSize()));
85              info.add(Sigar.formatSize(mem.getRss()));
86              info.add(Sigar.formatSize(mem.getShare()));
87          } catch (SigarException e) {
88              info.add(unknown);
89          }
90  
91          info.add(String.valueOf(state.getState()));
92  
93          if (time != null) {
94              info.add(getCpuTime(time));
95          } else {
96              info.add(unknown);
97          }
98  
99          String name = ProcUtil.getDescription(sigar, pid);
100         info.add(name);
101 
102         return info;
103     }
104 
105 
106     public List<String> runningProcesses() throws SigarException {
107         List<String> ret = new ArrayList<String>();
108         long[] pids = this.proxy.getProcList();
109         //   ProcState state = sigar.getProcState(pid);
110         //   ProcTime time = null;
111         //  String unknown = "???";
112 
113         for (int i = 0; i < pids.length; i++) {
114             /*String user = "";
115              String group = "";
116              try {
117              ProcCredName cred = sigar.getProcCredName(pids[i]);
118              user = cred.getUser();
119              group = cred.getGroup();
120              } catch (Exception e) {
121              }*/
122             try {
123                 String name = ProcUtil.getDescription(sigar, pids[i]);
124                 if (!Utility.stringIsNullOrEmpty(name)) {
125                     ret.add(name);
126                 }
127             } catch (Exception ex) {
128             }
129         }
130         return ret;
131     }
132 
133     public static String getCpuTime(long total) {
134         long t = total / 1000;
135         return t / 60 + ":" + t % 60;
136     }
137 
138     public static String getCpuTime(ProcTime time) {
139         return getCpuTime(time.getTotal());
140     }
141 
142     private static String getStartTime(long time) {
143         if (time == 0) {
144             return "00:00";
145         }
146         long timeNow = System.currentTimeMillis();
147         String fmt = "MMMd";
148 
149         if ((timeNow - time) < ((60 * 60 * 24) * 1000)) {
150             fmt = "HH:mm";
151         }
152 
153         return new SimpleDateFormat(fmt).format(new Date(time));
154     }
155 
156     public long GetSystemBootTimeInMS() {
157         try {
158             double timesincebootupinseconds = sigar.getUptime().getUptime();
159             long l = (long) (timesincebootupinseconds * 1000);
160             return l;
161 
162         } catch (SigarException e) {
163             return System.currentTimeMillis();
164         }
165 
166     }
167 
168     public double GetCurrentCPUUsage() throws SigarException {
169         CpuPerc c = sigar.getCpuPerc();
170         return ((1 - c.getIdle()) * 100.0);
171         /*
172          * while (true) {
173          *
174          * System.out.println("cpu idel " + c.getIdle()*100);
175          * System.out.println("cpu sys " + c.getSys()*100);
176          * System.out.println("cpu user " + c.getUser()*100);
177          * System.out.println("cpu combo " + c.getCombined()*100);
178          * System.out.println("cpu wait " + c.getWait()*100); try {
179          * Thread.sleep(1000); } catch (InterruptedException ex) {
180          * Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex); } }
181          *
182          * /* CpuTimer t = new CpuTimer(sigar); System.out.println("cpu usages
183          * " + t.getCpuUsage()); t.start();
184          *
185          * t.stop();
186          *
187          * System.out.println("cpu usages " + t.getCpuUsage());
188          * System.out.println("cpu usages " + t.getCpuUsage());
189          * System.out.println("idle " + sigar.getCpu().getIdle());
190          * System.out.println("irq " + sigar.getCpu().getIrq());
191          * System.out.println("nice " + sigar.getCpu().getNice());
192          * System.out.println("softirq " + sigar.getCpu().getSoftIrq());
193          * System.out.println("stolen " + sigar.getCpu().getStolen());
194          * System.out.println("isys " + sigar.getCpu().getSys());
195          * System.out.println("total " + sigar.getCpu().getTotal());
196          * System.out.println("user " + sigar.getCpu().getUser());
197          * System.out.println("wait " + sigar.getCpu().getWait());
198          *
199          *
200          *
201          *
202          * return 0;
203          */
204     }
205 
206     public long CurrentThreadCount() throws SigarException {
207         return sigar.getProcStat().getThreads();
208     }
209   
210     ProcessPerformanceData GetProcessData(List<Long> pids) {
211         ProcessPerformanceData ppd = new ProcessPerformanceData();
212         long theads = 0;
213         long memb = 0;
214         double cpu = 0;
215         long files = 0;
216         if (pids.isEmpty()) {
217             ppd.setOperationalstatus(false);
218             ppd.setStatusmessage("Stopped");
219             return ppd;
220         }
221         ppd.setOperationalstatus(true);
222         long startTimeinseconds = 0;
223         double systemuptime = 0;
224         for (int i = 0; i < pids.size(); i++) {
225 
226             try {
227 
228                 ProcCpu cpu2 = sigar.getProcCpu(pids.get(i));
229                 long time = cpu2.getTotal();
230                 Thread.sleep(1000);
231                 cpu2 = sigar.getProcCpu(pids.get(i));
232                 time = cpu2.getTotal() - time;  //time spend in the last second on this process in ms
233                 float p = (float) ((float) (time) / 1000F) * 100;
234                 p = p / GetCPUCores();
235                 if (p < 0) {
236                     p = 0;
237                 }
238                 cpu += p;
239 
240 
241             } catch (Exception ex) {
242                 //            Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
243             }
244             try {
245                 files += (sigar.getProcFd(pids.get(i)).getTotal());
246             } catch (SigarException ex) {
247                 //      Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
248             }
249             try {
250                 systemuptime = sigar.getUptime().getUptime();
251             } catch (SigarException ex) {
252                 //       Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
253             }
254             try {
255                 startTimeinseconds = sigar.getProcCpu(pids.get(i)).getStartTime();
256             } catch (SigarException ex) {
257                 //         Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
258             }
259 
260             //   System.out.println(startTimeinseconds);
261             //  System.out.println(systemuptime);
262             try {
263                 ProcState state = sigar.getProcState(pids.get(i));
264                 char sta = state.getState();
265                 String stastr = "" + sta;
266                 ppd.setStatusmessage(stastr);
267             } catch (SigarException ex) {
268                 //         Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
269             }
270             try {
271                 //ProcTime time = null;
272                 //String unknown = "???";
273                  /*
274                  * try { ProcCredName cred = sigar.getProcCredName(pids.get(i));
275                  * info.add(cred.getUser()); } catch (SigarException e) {
276                  * info.add(unknown); }
277                  *
278                  * try { time = sigar.getProcTime(pids.get(i));
279                  * info.add(getStartTime(time.getStartTime())); } catch
280                  * (SigarException e) { info.add(unknown); }
281                  */
282                 theads += (sigar.getProcState(pids.get(i)).getThreads());
283             } catch (SigarException ex) {
284                 //         Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
285             }
286             try {
287                 ProcMem mem = sigar.getProcMem(pids.get(i));
288                 memb += (mem.getSize());
289 
290             } catch (SigarException e) {
291             }
292 
293             //  info.add(String.valueOf(state.getState()));
294 /*
295              * if (time != null) { info.add(getCpuTime(time)); } else {
296              * info.add(unknown); }
297              *
298              * String name = ProcUtil.getDescription(sigar, pids.get(i));
299              * info.add(name);
300              */
301         }
302         GregorianCalendar gcal = new GregorianCalendar();
303         if (startTimeinseconds > 0) {
304             gcal.setTimeInMillis(System.currentTimeMillis() - (startTimeinseconds * 1000));
305         }
306         if (systemuptime > 0) {
307             gcal.setTimeInMillis(System.currentTimeMillis() - (new Double(systemuptime).longValue() * 1000));
308         }
309         try {
310             ppd.setStartedAt((gcal));
311         } catch (Exception ex) {
312             //       Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
313         }
314         ppd.setPercentusedCPU(cpu);
315         ppd.setOpenFileHandles(files);
316         ppd.setBytesusedMemory(memb);
317         ppd.setNumberofActiveThreads(theads);
318         return ppd;
319     }
320 
321     public int GetCPUCores() {
322         int cores = 0;
323         try {
324             org.hyperic.sigar.CpuInfo[] c = sigar.getCpuInfoList();
325             if (c == null) {
326                 return 1;
327             }
328             if (c.length > 0) {
329                 cores = c[0].getTotalCores();
330             }
331             //     for (int i = 0; i < c.length; i++) {
332             //cores += (c[i].getTotalCores());
333             // }
334         } catch (SigarException ex) {
335             Logger.getLogger(Ps.class.getName()).log(Level.SEVERE, null, ex);
336         }
337         return cores;
338     }
339 
340     @Override
341     public void close() throws Exception {
342         if (sigar != null) {
343             sigar.close();
344             sigar = null;
345         }
346     }
347     @Override
348     protected void finalize() throws Throwable
349     {
350         
351           if (sigar != null) {
352               System.out.println("WARN,. finalize called without closing sigar first"+ this.getClass().getCanonicalName());
353             sigar.close();
354         }
355         super.finalize();
356     }
357 }