Java Code Examples for org.hyperic.sigar.Sigar

The following examples show how to use org.hyperic.sigar.Sigar. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: kkFileViewOfficeEdit   Source File: SigarProcessManager.java    License: Apache License 2.0 6 votes vote down vote up
public long findPid(ProcessQuery query) throws IOException {
    Sigar sigar = new Sigar();
    try {
        long[] pids = ProcessFinder.find(sigar, "State.Name.eq=" + query.getCommand());
        for (int i = 0; i < pids.length; i++) {
            String[] arguments = sigar.getProcArgs(pids[i]);
            if (arguments != null && argumentMatches(arguments, query.getArgument())) {
                return pids[i];
            }
        }
        return PID_NOT_FOUND;
    } catch (SigarException sigarException) {
        throw new IOException("findPid failed", sigarException);
    } finally {
        sigar.close();
    }
}
 
Example 2
Source Project: ats-framework   Source File: ReadingInstancesFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static String constructProcessStartCommand(
                                                    Sigar sigar,
                                                    long pid ) {

    StringBuilder startCommand = new StringBuilder();
    try {
        String[] processArgs = sigar.getProcArgs(pid);
        for (String arg : processArgs) {
            startCommand.append(arg);
            startCommand.append(" ");
        }
        return startCommand.toString();
    } catch (SigarException e) {
        // some system processes can not be accessed
        return null;
    }
}
 
Example 3
Source Project: kkFileView   Source File: SigarProcessManager.java    License: Apache License 2.0 6 votes vote down vote up
public long findPid(ProcessQuery query) throws IOException {
    Sigar sigar = new Sigar();
    try {
        long[] pids = ProcessFinder.find(sigar, "State.Name.eq=" + query.getCommand());
        for (int i = 0; i < pids.length; i++) {
            String[] arguments = sigar.getProcArgs(pids[i]);
            if (arguments != null && argumentMatches(arguments, query.getArgument())) {
                return pids[i];
            }
        }
        return PID_NOT_FOUND;
    } catch (SigarException sigarException) {
        throw new IOException("findPid failed", sigarException);
    } finally {
        sigar.close();
    }
}
 
Example 4
Source Project: sigar-system_runtime   Source File: sigar.java    License: MIT License 6 votes vote down vote up
private static void memory() throws SigarException {
    Sigar sigar = new Sigar();
    Mem mem = sigar.getMem();
    // 内存总量
    System.out.println("内存总量:    " + mem.getTotal() / 1024L + "K av");
    // 当前内存使用量
    System.out.println("当前内存使用量:    " + mem.getUsed() / 1024L + "K used");
    // 当前内存剩余量
    System.out.println("当前内存剩余量:    " + mem.getFree() / 1024L + "K free");
    Swap swap = sigar.getSwap();
    // 交换区总量
    System.out.println("交换区总量:    " + swap.getTotal() / 1024L + "K av");
    // 当前交换区使用量
    System.out.println("当前交换区使用量:    " + swap.getUsed() / 1024L + "K used");
    // 当前交换区剩余量
    System.out.println("当前交换区剩余量:    " + swap.getFree() / 1024L + "K free");
}
 
Example 5
Source Project: sigar-system_runtime   Source File: sigar.java    License: MIT License 6 votes vote down vote up
private static void cpu() throws SigarException {
    Sigar sigar = new Sigar();
    
    CpuPerc perc = sigar.getCpuPerc();
    System.out.println("整体cpu的占用情况:");
    System.out.println("空闲率: " + CpuPerc.format(perc.getIdle()));//获取当前cpu的空闲率
    System.out.println("占用率: "+ CpuPerc.format(perc.getCombined()));//获取当前cpu的占用率
    
    
    CpuInfo infos[] = sigar.getCpuInfoList();
    CpuPerc cpuList[] = null;
    cpuList = sigar.getCpuPercList();
    for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
        CpuInfo info = infos[i];
        System.out.println("第" + (i + 1) + "块CPU信息");
        System.out.println("CPU的总量MHz:    " + info.getMhz());// CPU的总量MHz
        System.out.println("CPU生产商:    " + info.getVendor());// 获得CPU的卖主,如:Intel
        System.out.println("CPU类别:    " + info.getModel());// 获得CPU的类别,如:Celeron
        System.out.println("CPU缓存数量:    " + info.getCacheSize());// 缓冲存储器数量
        printCpuPerc(cpuList[i]);
    }
}
 
Example 6
Source Project: sigar-system_runtime   Source File: sigar.java    License: MIT License 6 votes vote down vote up
private static void net() throws Exception {
    Sigar sigar = new Sigar();
    String ifNames[] = sigar.getNetInterfaceList();
    for (int i = 0; i < ifNames.length; i++) {
        String name = ifNames[i];
        NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
        System.out.println("网络设备名:    " + name);// 网络设备名
        System.out.println("IP地址:    " + ifconfig.getAddress());// IP地址
        System.out.println("子网掩码:    " + ifconfig.getNetmask());// 子网掩码
        if ((ifconfig.getFlags() & 1L) <= 0L) {
            System.out.println("!IFF_UP...skipping getNetInterfaceStat");
            continue;
        }
        NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
        
        System.out.println(name + "接收的总包裹数:" + ifstat.getRxPackets());// 接收的总包裹数
        System.out.println(name + "发送的总包裹数:" + ifstat.getTxPackets());// 发送的总包裹数
        System.out.println(name + "接收到的总字节数:" + ifstat.getRxBytes());// 接收到的总字节数
        System.out.println(name + "发送的总字节数:" + ifstat.getTxBytes());// 发送的总字节数
        System.out.println(name + "接收到的错误包数:" + ifstat.getRxErrors());// 接收到的错误包数
        System.out.println(name + "发送数据包时的错误数:" + ifstat.getTxErrors());// 发送数据包时的错误数
        System.out.println(name + "接收时丢弃的包数:" + ifstat.getRxDropped());// 接收时丢弃的包数
        System.out.println(name + "发送时丢弃的包数:" + ifstat.getTxDropped());// 发送时丢弃的包数
    }
}
 
Example 7
Source Project: micro-server   Source File: MachineStatsChecker.java    License: Apache License 2.0 6 votes vote down vote up
public MachineStats getStats(Sigar sigar) {
    CpuStats cpuStats = CpuStats.builder()
                                .build();
    SwapStats swapStats = SwapStats.builder()
                                   .build();
    MemoryStats memoryStats = MemoryStats.builder()
                                         .build();
    try {
        swapStats = getSwapStats(sigar);
        cpuStats = getCpuStats(sigar);
        getMemoryStats(sigar);

    } catch (SigarException | UnsatisfiedLinkError e) {
        logger.error("Error during sigar stats operation", e);
    } finally {
        sigar.close();
    }

    return getMachineStats(swapStats, cpuStats, memoryStats);

}
 
Example 8
Source Project: onos   Source File: NodeDiagnosisManager.java    License: Apache License 2.0 6 votes vote down vote up
@Activate
public void activate() {
    cfgService.registerProperties(getClass());
    bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
    getNodeId();
    sigar = new Sigar();
    scheduleAppDiagnosisPolling();
    scheduleClusterNodeDiagnosisPolling();
    getPid();
    getMemoryThreshold();
    scheduleSdncMemoryDiagnosisPolling();
    scheduleSdncFileDescriptorDiagnosisPolling();
    communicationService.addSubscriber(REBOOT_MSG, new InternalSampleCollector(),
            getPoolThreadExecutor());
    rebootNu = fetchRebootNu(); //to restrict number of reboots , reboot numbers will be saved in file and used
    rebootRetryCount = fetchRetryRebootCount(); // to set maximum limit for reboot retry.
    log.info("Started");
}
 
Example 9
/**
 * Test method for {@link kg.apc.perfmon.metrics.PerfMonMetricsCreatorImpl#getMetricProvider(java.lang.String, kg.apc.perfmon.metrics.MetricParamsSigar, org.hyperic.sigar.SigarProxy)}.
 */
public final void testGetMetricProviderError() {
    Throwable catched = null;
    PerfMonMetricsCreatorImpl getter = new PerfMonMetricsCreatorImpl();
    System.out.println("createMetric");
    String metricType = "not exist";
    String metricParams = "idle";
    SigarProxy sigarProxy = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar metricParamsSigar = MetricParamsSigar.createFromString(metricParams, sigarProxy);
    try {
        AbstractPerfMonMetric result = getter.getMetricProvider(metricType, metricParamsSigar, sigarProxy, false);
    } catch (Throwable e) {
        catched = e;
    }
    assertNotNull(catched);
    assertEquals(RuntimeException.class, catched.getClass());
}
 
Example 10
Source Project: perfmon-agent   Source File: PerfMonMetricGetterTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testProcessCommand() throws IOException {
    System.out.println("processCommand");
    String toString = "test\ntest\nerr\n";
    final DatagramChannel channel = DatagramChannelEmul.open();
    channel.configureBlocking(false);
    final InetSocketAddress inetSocketAddress = new InetSocketAddress(
            "localhost", 4444);
    channel.connect(inetSocketAddress);
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), channel, inetSocketAddress);
    instance.addCommandString(toString);
    instance.processNextCommand();
    instance.processNextCommand();
    try {
        instance.processNextCommand();
        fail();
    } catch (UnsupportedOperationException e) {
    }
}
 
Example 11
Source Project: kkFileViewOfficeEdit   Source File: SigarProcessManager.java    License: Apache License 2.0 5 votes vote down vote up
public void kill(Process process, long pid) throws IOException {
    Sigar sigar = new Sigar();
    try {
        sigar.kill(pid, Sigar.getSigNum("KILL"));
    } catch (SigarException sigarException) {
        throw new IOException("kill failed", sigarException);
    } finally {
        sigar.close();
    }
}
 
Example 12
Source Project: ats-framework   Source File: ReadingInstancesFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static void init(
                         SigarWrapper sigarWrapper,
                         int pollingInterval ) throws UnsupportedReadingException, SigarException {

    /*
     * We need to know the number of CPUs for some readings in some cases. For example
     *      1. Sigar gives average CPU usage in percents.
     *      2. Sigar gives accumulated CPU usage times.
     *      If we have 2 CPUs loaded on 20% and 40%, we will get 30% and 0.60 time usage for 1 second.
     *      We fix that to get get 30% and 0.30 time usage for 1 second.
     */
    getNumberOfCPUs(sigarWrapper);

    // clean up the processes map
    matchedProcessesMap = new HashMap<String, Map<Long, MatchedProcess>>();
    matchedProcessesIds = new HashSet<Long>();
    matchedProcessesIndexes = new HashMap<String, Integer>();
    processesReadingInstanceIdentifiers = new HashSet<String>();

    // On Solaris it takes a significant amount of time (around 1 minute) until Sigar iterates the
    // system processes for first time. We do it here, so the real polls are quick
    Sigar sigar = sigarWrapper.getSigarInstance();
    for (long pid : sigar.getProcList()) {
        try {
            sigar.getProcArgs(pid);
        } catch (SigarException e) {
            // some system processes can not be accessed
        }
    }
}
 
Example 13
Source Project: kkFileView   Source File: SigarProcessManager.java    License: Apache License 2.0 5 votes vote down vote up
public void kill(Process process, long pid) throws IOException {
    Sigar sigar = new Sigar();
    try {
        sigar.kill(pid, Sigar.getSigNum("KILL"));
    } catch (SigarException sigarException) {
        throw new IOException("kill failed", sigarException);
    } finally {
        sigar.close();
    }
}
 
Example 14
/**
 * Generate memory statistics
 * http://casidiablo.net/capturar-informacion-sistema-operativo-java/
 */
public JFreeChart osMemStats() throws IOException, ServletException {
	DefaultPieDataset dataset = new DefaultPieDataset();
	Sigar sigar = new Sigar();
	String title = null;

	try {
		Mem mem = sigar.getMem();
		long max = mem.getRam();
		long available = mem.getFree();
		long total = mem.getTotal();
		long used = mem.getUsed();
		long free = mem.getFree();
		title = "OS memory: " + FormatUtil.formatSize(total);

		log.debug("OS maximun memory: {}", FormatUtil.formatSize(max));
		log.debug("OS available memory: {}", FormatUtil.formatSize(available));
		log.debug("OS free memory: {}", FormatUtil.formatSize(free));
		log.debug("OS used memory: {}", FormatUtil.formatSize(used));
		log.debug("OS total memory: {}", FormatUtil.formatSize(total));

		dataset.setValue("Available (" + FormatUtil.formatSize(free) + ")", free * 100 / total);
		dataset.setValue("Used (" + FormatUtil.formatSize(used) + ")", used * 100 / total);
	} catch (SigarException se) {
		title = "OS memory: " + se.getMessage();
	} catch (UnsatisfiedLinkError ule) {
		title = "OS memory: (missing native libraries)";
	}

	return ChartFactory.createPieChart(title, dataset, true, false, false);
}
 
Example 15
Source Project: micro-server   Source File: SigarStats.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Map<String, String>> get() {
    if (cpuOnly)
        return MapXs.of("cpu-stats", checker.cpuStats(new Sigar())
                                            .toMap());
    MachineStats stats = checker.getStats(new Sigar());
    return stats.toMap();
}
 
Example 16
Source Project: micro-server   Source File: MachineStatsChecker.java    License: Apache License 2.0 5 votes vote down vote up
CpuStats cpuStats(Sigar sigar) {
    try {
        return getCpuStats(sigar);

    } catch (SigarException | UnsatisfiedLinkError e) {
        logger.error("Error during sigar stats operation", e);
    } finally {
        sigar.close();
    }
    return CpuStats.builder()
                   .build();
}
 
Example 17
Source Project: micro-server   Source File: MachineStatsChecker.java    License: Apache License 2.0 5 votes vote down vote up
private SwapStats getSwapStats(Sigar sigar) throws SigarException {
    SwapStats.SwapStatsBuilder swapStats = SwapStats.builder();
    swapStats.pageIn(sigar.getSwap()
                          .getPageIn());
    swapStats.pageOut(sigar.getSwap()
                           .getPageOut());
    swapStats.free(sigar.getSwap()
                        .getFree());
    swapStats.used(sigar.getSwap()
                        .getUsed());
    swapStats.total(sigar.getSwap()
                         .getTotal());
    return swapStats.build();
}
 
Example 18
Source Project: micro-server   Source File: MachineStatsChecker.java    License: Apache License 2.0 5 votes vote down vote up
private CpuStats getCpuStats(Sigar sigar) throws SigarException {
    CpuStats.CpuStatsBuilder cpuStats = CpuStats.builder();
    cpuStats.idlePercentage(sigar.getCpuPerc()
                                 .getIdle());
    cpuStats.totalCores(sigar.getCpuInfoList()[0].getTotalCores());
    cpuStats.model(sigar.getCpuInfoList()[0].getModel());
    cpuStats.mhz(sigar.getCpuInfoList()[0].getMhz());
    cpuStats.loadAverage(sigar.getLoadAverage()[0]);
    return cpuStats.build();
}
 
Example 19
Source Project: micro-server   Source File: MachineStatsChecker.java    License: Apache License 2.0 5 votes vote down vote up
private MemoryStats getMemoryStats(Sigar sigar) throws SigarException {
    MemoryStats.MemoryStatsBuilder memoryStats = MemoryStats.builder();
    memoryStats.total(sigar.getMem()
                           .getTotal());
    memoryStats.actualFree(sigar.getMem()
                                .getActualFree());
    memoryStats.freePercent(sigar.getMem()
                                 .getFreePercent());
    memoryStats.actualUsed(sigar.getMem()
                                .getActualUsed());
    memoryStats.usedPercent(sigar.getMem()
                                 .getUsedPercent());
    return memoryStats.build();
}
 
Example 20
Source Project: micro-server   Source File: StatsResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMachineStats() {
	
	when(machineStatsChecker.getStats((Sigar)anyObject())).thenReturn(mock(MachineStats.class));		
	statsResource.getMachineStats();		
	verify(machineStatsChecker, times(1)).getStats((Sigar)anyObject());
	
}
 
Example 21
Source Project: micro-server   Source File: MachineStatsCheckerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	sigar = mock(Sigar.class);
	swap = mock(Swap.class);
	cpuPerc = mock(CpuPerc.class);
	cpuInfo = mock(CpuInfo.class);
	mem = mock(Mem.class);
	
	machineStatsChecker = new MachineStatsChecker();		
}
 
Example 22
private Set<Integer> getAliveWithSigar(boolean printProcesses) {
    Sigar sigar = new Sigar();
    try {
        long[] pids = new ProcessFinder(sigar).find("State.Name.eq=java,Args.*.re=" + pattern);
        Set<Integer> setOfPids = new HashSet<>();
        for (long pid : pids) {
            setOfPids.add((int) pid);
            if (printProcesses)
                System.out.println("Running java processes matching regex:" + pid);
        }
        return setOfPids;
    } catch (SigarException e) {
        return Collections.emptySet();
    }
}
 
Example 23
private String getDefaultNodeName() {
    try {
        return InetAddress.getLocalHost().getHostName().replace('.', '_') + "_" + new Sigar().getPid();
    } catch (Throwable error) {
        logger.warn("Failed to retrieve hostname or pid to compute node name, will fallback to default value",
                    error);
        return "PA-AGENT_NODE";
    }
}
 
Example 24
@SuppressWarnings("unchecked")
@Override
public ProcessInfo[] getProcesses() throws SigarException {
    Sigar sigar = new Sigar();
    long[] pids = sigar.getProcList();

    List<ProcessInfo> result = new ArrayList<>(pids.length);

    for (int i = 0; i < pids.length; i++) {
        long pid = pids[i];
        try {
            @SuppressWarnings("rawtypes")
            List info = Ps.getInfo(sigar, pid); // Add standard info.
            info.add(sigar.getProcArgs(pid)); // Add also arguments of each process.
            info.add(sigar.getProcCpu(pid).getPercent()); // Add cpu usage (perc.).

            result.add(new ProcessInfo(info));
        } catch (SigarException e) {
            // Ignore it, probably the process does not exist anymore.
            logger.warn("Could not get information for PID " + pid + ": " + e.getMessage());
        }

        // TODO see why sigar.getProcCpu(pid).getPercent()
        // returns '0.0' always.

    }

    return result.toArray(new ProcessInfo[] {});
}
 
Example 25
Source Project: onos   Source File: NodeMetricsManager.java    License: Apache License 2.0 5 votes vote down vote up
@Activate
public void activate(ComponentContext context) {
    appId = coreService
            .registerApplication("org.onosproject.nodemetrics");
    cfgService.registerProperties(getClass());
    metricsExecutor = Executors.newSingleThreadScheduledExecutor(
            Tools.groupedThreads("nodemetrics/pollingStatics",
                    "statistics-executor-%d", log));

    localNodeId = clusterService.getLocalNode().id();
    KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
            .register(KryoNamespaces.API)
            .register(NodeMemoryUsage.class)
            .register(NodeDiskUsage.class)
            .register(NodeCpuUsage.class)
            .register(Units.class);
    memoryStore = storageService.<NodeId, NodeMemoryUsage>eventuallyConsistentMapBuilder()
            .withSerializer(serializer)
            .withTimestampProvider((nodeId, memory) -> clockService.getTimestamp())
            .withName("nodemetrics-memory")
            .build();

    diskStore = storageService.<NodeId, NodeDiskUsage>eventuallyConsistentMapBuilder()
            .withSerializer(serializer)
            .withTimestampProvider((nodeId, disk) -> clockService.getTimestamp())
            .withName("nodemetrics-disk")
            .build();

    cpuStore = storageService.<NodeId, NodeCpuUsage>eventuallyConsistentMapBuilder()
            .withSerializer(serializer)
            .withTimestampProvider((nodeId, cpu) -> clockService.getTimestamp())
            .withName("nodemetrics-cpu")
            .build();
    modified(context);
    sigar = new Sigar();
    pollMetrics();
}
 
Example 26
Source Project: perfmon-agent   Source File: AbstractMemMetricTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of getMetric method, of class AbstractMemMetric.
 */
public void testGetMetric() {
    System.out.println("getMetric");
    StringBuffer res = new StringBuffer();
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar params = new MetricParamsSigar(sigar);
    AbstractMemMetric result = AbstractMemMetric.getMetric(sigar, params);
    assertEquals(params, result.params);
}
 
Example 27
Source Project: perfmon-agent   Source File: MetricParamsSigarTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of createFromString method, of class MetricParamsSigar.
 */
public void testCreateFromString() {
    System.out.println("createFromString");
    String metricParamsStr = "";
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar result = MetricParamsSigar.createFromString(metricParamsStr, sigar);
    assertEquals(-1, result.PID);
}
 
Example 28
Source Project: perfmon-agent   Source File: MetricParamsSigarTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of populateParams method, of class MetricParamsSigar.
 */
public void testPopulateParams() {
    System.out.println("populateParams");
    String token = "";
    List params = new LinkedList();
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar instance = MetricParamsSigar.createFromString("", sigar);
    instance.populateParams(token, params);
}
 
Example 29
Source Project: perfmon-agent   Source File: NetworkIOMetricTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of getValue method, of class NetworkIOMetric.
 */
public void testGetValue() throws Exception {
    System.out.println("getValue");
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    for (int n = 0; n < NetworkIOMetric.types.length; n++) {
        NetworkIOMetric instance = new NetworkIOMetric(sigar, MetricParams.createFromString(NetworkIOMetric.types[n]));
        StringBuffer res = new StringBuffer();
        instance.getValue(res);
        System.out.println(NetworkIOMetric.types[n] + "=" + res.toString());
        Thread.sleep(100);
        res = new StringBuffer();
        instance.getValue(res);
        System.out.println(NetworkIOMetric.types[n] + "=" + res.toString());
    }
}
 
Example 30
Source Project: perfmon-agent   Source File: AbstractPerfMonMetricTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of createMetric method, of class AbstractPerfMonMetric.
 */
public void testCreateMetric() {
    System.out.println("createMetric");
    String metricType = "cpu";
    String metricParams = "idle";
    SigarProxy sigarProxy = SigarProxyCache.newInstance(new Sigar(), 500);
    Class expResult = CPUTotalMetric.class;
    AbstractPerfMonMetric result = AbstractPerfMonMetric.createMetric(metricType, metricParams, sigarProxy, false);
    assertNotNull(result);
    assertEquals(expResult, result.getClass());
}