org.hyperic.sigar.Sigar Java Examples

The following examples show how to use org.hyperic.sigar.Sigar. 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 File: SigarProcessManager.java    From kkFileViewOfficeEdit with 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 File: NodeDiagnosisManager.java    From onos with 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 #3
Source File: MachineStatsChecker.java    From micro-server with 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 #4
Source File: PerfMonMetricsCreatorImplTest.java    From perfmon-agent with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with 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 #6
Source File: sigar.java    From sigar-system_runtime with 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 File: sigar.java    From sigar-system_runtime with 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 #8
Source File: sigar.java    From sigar-system_runtime with 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 #9
Source File: SigarProcessManager.java    From kkFileView with 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 #10
Source File: ReadingInstancesFactory.java    From ats-framework with 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 #11
Source File: NodeMetricsManager.java    From onos with 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 #12
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testProcessNextCommand() throws Exception {
    System.out.println("processNextCommand");
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), DatagramChannel.open());
    boolean expResult = false;
    boolean result = instance.processNextCommand();
    assertEquals(expResult, result);
}
 
Example #13
Source File: SigarProcessManager.java    From kkFileViewOfficeEdit with 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
Source File: AbstractMemMetricTest.java    From perfmon-agent with 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 #15
Source File: MetricParamsSigarTest.java    From perfmon-agent with 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 #16
Source File: MetricParamsSigarTest.java    From perfmon-agent with 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 #17
Source File: NetworkIOMetricTest.java    From perfmon-agent with 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 #18
Source File: AbstractPerfMonMetricTest.java    From perfmon-agent with 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());
}
 
Example #19
Source File: PerfMonMetricsServiceTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public final void testGetMetric() {
    String metricType = "cpu";
    SigarProxy sigarProxy = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar metricParams = MetricParamsSigar.createFromString("idle", sigarProxy);

    AbstractPerfMonMetric metric = service.getMetric(metricType, metricParams, sigarProxy, false);

    assertNotNull(metric);
    assertEquals(CPUTotalMetric.class, metric.getClass());
    System.out.println(metric.getClass());
}
 
Example #20
Source File: DiskIOMetricTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Test of getValue method, of class DiskIOMetric.
 */
public void testGetValue() throws Exception {
    System.out.println("getValue");
    StringBuffer res = new StringBuffer();
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar metricParams = MetricParamsSigar.createFromString("used", sigar);

    DiskIOMetric instance = new DiskIOMetric(sigar, metricParams);
    instance.getValue(res);
    System.err.println(res.toString());
}
 
Example #21
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testProcessCommand_udp_transmitter() throws IOException {
    System.out.println("UDP transmitter");
    String cmd = "udp-transmitter:localhost:3333:cpu\tmemory\ttcp\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(cmd);
    instance.processNextCommand();
}
 
Example #22
Source File: DiskIOMetricTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testGetValue_reads() throws Exception {
    System.out.println("getValue_r");
    StringBuffer res = new StringBuffer();
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    DiskIOMetric instance = new DiskIOMetric(sigar, MetricParamsSigar.createFromString("reads", sigar));
    instance.getValue(res);
    assertTrue(res.toString().length() != 0);
    System.out.println(res.toString());
    res = new StringBuffer();

    instance.getValue(res);
    assertTrue(res.toString().length() != 0);
    System.out.println(res.toString());
}
 
Example #23
Source File: DiskIOMetricTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testGetValue_all() throws Exception {
    System.out.println("getValue");
    SigarProxy sigar = SigarProxyCache.newInstance(new Sigar(), 500);
    for (int n = 0; n < DiskIOMetric.types.length; n++) {
        DiskIOMetric instance = new DiskIOMetric(sigar, MetricParamsSigar.createFromString(DiskIOMetric.types[n], sigar));
        StringBuffer res = new StringBuffer();
        instance.getValue(res);
        System.out.println(DiskIOMetric.types[n] + "=" + res.toString());
        Thread.sleep(100);
        res = new StringBuffer();
        instance.getValue(res);
        System.out.println(DiskIOMetric.types[n] + "=" + res.toString());
    }
}
 
Example #24
Source File: PerfMonMetricsCreatorImplTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
/**
 * 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 testGetMetricProvider() {
    PerfMonMetricsCreatorImpl getter = new PerfMonMetricsCreatorImpl();
    System.out.println("createMetric");
    String metricType = "cpu";
    String metricParams = "idle";
    SigarProxy sigarProxy = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar metricParamsSigar = MetricParamsSigar.createFromString(metricParams, sigarProxy);
    Class expResult = CPUTotalMetric.class;
    AbstractPerfMonMetric result = getter.getMetricProvider(metricType, metricParamsSigar, sigarProxy, false);
    assertEquals(expResult, result.getClass());
}
 
Example #25
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testProcessCommand_single_metrics() throws IOException {
    System.out.println("processCommand");
    String toString = "metrics-single:cpu\tmemory\ttcp\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();
}
 
Example #26
Source File: PerfMonMetricsCreatorImplTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public final void testNoExec() {
    PerfMonMetricsCreatorImpl getter = new PerfMonMetricsCreatorImpl();
    System.out.println("no-exec");
    String metricType = "exec";
    String metricParams = "";
    SigarProxy sigarProxy = SigarProxyCache.newInstance(new Sigar(), 500);
    MetricParamsSigar metricParamsSigar = MetricParamsSigar.createFromString(metricParams, sigarProxy);
    AbstractPerfMonMetric result = getter.getMetricProvider(metricType, metricParamsSigar, sigarProxy, true);
    assertNotNull(result);
    assertEquals(InvalidPerfMonMetric.class, result.getClass());
}
 
Example #27
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testSendMetrics() throws IOException {
    System.out.println("sendMetrics");
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), DatagramChannel.open());
    instance.getMetricsLine();
}
 
Example #28
Source File: PerfMonMetricGetterTest.java    From perfmon-agent with Apache License 2.0 5 votes vote down vote up
public void testAddCommandString() throws IOException {
    System.out.println("addCommandString");
    String byteBufferToString = "";
    PerfMonMetricGetter instance = new PerfMonMetricGetter(
            SigarProxyCache.newInstance(new Sigar(), 500),
            new PerfMonWorker(), DatagramChannel.open());
    instance.addCommandString(byteBufferToString);
}
 
Example #29
Source File: SigarProcesses.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #30
Source File: SigarStats.java    From micro-server with 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();
}