balaji | 10 Feb 06:43
Picon
Favicon

Performance counters are not working under linux mono platform

Hi,

Does anyone know why Performance counters return zero value in the code
below when executing under linux mono platform.

                  (OR)

How to get a process performance counters like CPU,Memory,Thread
count,Handle Count and other resource utilization of a machine,when the
process is running in a remote machine?

 The code below works with MS Visual Studio under Windows but simply won't
work with Mono 2.10.5 under linux i.e performance counter values are
zero.why?

/* This uses remoting */
/ * Run this application in the remote machine where the actual
 * 
 */
#define DEBUG_PERFORMANCE

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{

    static string BuildVersion = "Build Version: Beta Date:30th Jan 2012";
// build version
    static void Main(string[] args)
    {
        StartPerformance();
    }

    static void StartPerformance()
    {
        Console.WriteLine("Performance Server started ...");
        Console.WriteLine(BuildVersion);
        Console.WriteLine("American Megatrends Inc.");
        Console.WriteLine("Copy right (c) 2011-2012");

        TcpChannel tcpChannel = new TcpChannel(9998);
        ChannelServices.RegisterChannel(tcpChannel);

        Type commonInterfaceType = Type.GetType("Performance");

       
RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,
                                        "PerformanceRegister",
WellKnownObjectMode.SingleCall);

        System.Console.WriteLine("Press ENTER to quit");
        System.Console.ReadLine();        
    }   
}

public interface PerformanceInterface
{
    string []GetPerformanceStatus();    // returns the Mem, CPU, thread
count, handle count
    int GetProcessID();              // process ID
    void SetConfiguration(bool mem, bool cpu, bool page, bool nic,
                                       bool thread, bool handle,
                                       String processName,
                                       String machineName, bool isPerform);
// set the parameters
    void StopPerformanceMonitoring();
}

public class Performance : MarshalByRefObject, PerformanceInterface
{
    private static PerformanceCounter cpuCounter = null;
    private static PerformanceCounter ramCounter = null;
    private static PerformanceCounter pageCounter = null;
    private static PerformanceCounter threadCountCounter = null;
    private static PerformanceCounter handleCountCounter = null;
    private static PerformanceCounter[] nicCounters = null;

    private static bool Mem = false;
    private static bool Cpu = false;
    private static bool Page = false;
    private static bool Nic = false;
    private static bool HandleCount = false;
    private static bool ThreadCount = false;
    private static bool IsPerform = false;
    private static String MachineName = String.Empty;
    private static String ProcessName = String.Empty;
    private static bool IsIntialized = false;

    public string[] GetPerformanceStatus()
    {
        Process ReqProcess;
        string[] result = new string[6];

        if (!IsIntialized)                           // not yet initailized
            return null;

#if DEBUG_PERFORMANCE
        Console.WriteLine("In Get PerformanceStatus()");
#endif

        try
        {
            String CPUStr = String.Empty, MEMStr = String.Empty,
                    PAGEStr = String.Empty, NICStr = String.Empty,
                    THREADStr = String.Empty, HANDLEStr = String.Empty;

            // log data here
            ReqProcess = CurrentlyRunning(ProcessName);
            if (ReqProcess != null)
            {
                if (Cpu && cpuCounter != null)
                {
                    //  CPUStr = String.Format("{0:##0}",
cpuCounter.NextValue());
                    System.TimeSpan CPULoad = (DateTime.Now -
ReqProcess.StartTime);
                    CPUStr = String.Format("{0:##0}",
((ReqProcess.TotalProcessorTime.TotalMilliseconds /
                       CPULoad.TotalMilliseconds) * 100));
                }
                if (Mem && ramCounter != null)  // similar to
ReqProcess.WorkingSet64
                    MEMStr = String.Format("{0}", ramCounter.NextValue() /
1024);  // mem usage in K
                if (Page)
                    PAGEStr = String.Format("{0:##0}",
pageCounter.NextValue());
                if (ThreadCount && threadCountCounter != null)
                    THREADStr = String.Format("{0:##0}",
threadCountCounter.NextValue());
                if (HandleCount && handleCountCounter != null)
                    HANDLEStr = String.Format("{0:##0}",
handleCountCounter.NextValue());

                if (Nic)
                    for (int i = 0; i < nicCounters.Length; i++)
                    {
                        NICStr += String.Format(" {0:####0 }",
nicCounters[i].NextValue() / 1024);
                    }
                result[0] = CPUStr;
                result[1] = MEMStr;
                result[2] = PAGEStr;
                result[3] = NICStr;
                result[4] = THREADStr;
                result[5] = HANDLEStr;

#if DEBUG_PERFORMANCE
                Console.WriteLine("Data:"+result);
#endif
                return result;
            }
#if DEBUG_PERFORMANCE
            else
                Console.WriteLine("The process '{0}' is not running",
ProcessName);
#endif
        }
        catch (Exception ex)
        {
            System.Console.WriteLine("Exception:" + ex.ToString());          
        }
        return null;
    }
    /* Returns the process id of the given process */
    public int GetProcessID()
    {
        Process ReqProcess;
        ReqProcess = CurrentlyRunning(ProcessName);
        if(ReqProcess != null)
            return ReqProcess.Id;
        return 0;
    }
    public void SetConfiguration(bool mem, bool cpu, bool page, bool nic,
                                       bool thread, bool handle,
                                       String processName,
                                       String machineName, bool isPerform)
    {
        System.Console.WriteLine("Set the configurations from the test
automation tool.");
        Mem = mem;
        Cpu = cpu;
        Page = page;
        Nic = nic;
        ThreadCount = thread;
        HandleCount = handle;
        IsPerform = isPerform;
        ProcessName = processName;
        MachineName = machineName;
        InitCounters();
    }
    /* Initialise the performance counters */
    private void InitCounters()
    {        
        Process ReqProcess;
        Console.WriteLine("Intializing performance counters ...");
        try
        {                 /* machine specific information */

            if (Page)
                pageCounter = new PerformanceCounter
                                        ("Paging File", "% Usage", "_Total",
MachineName);
            if (Nic)
                nicCounters = GetNICCounters();

            GC.GetTotalMemory(true);                            // how much
GC total use 
            if (ProcessName.Length == 0)
                Console.WriteLine("Process name empty");

            ReqProcess = CurrentlyRunning(ProcessName);

            if (ReqProcess != null)                             // Process
specific information
            {
                                                                // Refresh
the current process property values.
                ReqProcess.Refresh();

                if (Mem)
                    ramCounter = new PerformanceCounter("Process",
                                                        "Working Set",
ReqProcess.ProcessName);
                if (Cpu)
                {
                    if (ReqProcess.ProcessName.Length == 0)
                        Console.WriteLine(String.Format("Process name is
empty under [Performance] in .ini"));
                    else
                        cpuCounter = new PerformanceCounter("Process",
                                                            "% Processor
Time", ReqProcess.ProcessName);
                }
                if (ThreadCount)           // number of threads of this
process
                {
                    if (ReqProcess.ProcessName.Length == 0)
                        Console.WriteLine(String.Format("Process name is
empty under [Performance] in .ini"));
                    else
                        threadCountCounter = new
PerformanceCounter("Process",
                                                                "Thread
Count", ReqProcess.ProcessName);
                }
                if (HandleCount)           // number of handles of this
process
                {
                    if (ReqProcess.ProcessName.Length == 0)
                        Console.WriteLine(String.Format("Process name is
empty under [Performance] in .ini"));
                    else
                        handleCountCounter = new
PerformanceCounter("Process",
                                                               "Handle
Count", ReqProcess.ProcessName);
                }
            }
            else
                Console.WriteLine("The process '{0}' is not running",
ProcessName);
        }
        catch (Exception ex)
        {
            Console.WriteLine(
                 (String.Format("Unable to access computer '{0}'\r\nPlease
check spelling and verify this computer is connected to the network",
                 MachineName)));
        }
        IsIntialized = true;
    }
    // create a Performance Counter for each network interface
    private PerformanceCounter[] GetNICCounters()
    {
        string[] nics = GetNICInstances(MachineName);
        List<PerformanceCounter> nicCounters = new
List<PerformanceCounter>();
        foreach (string nicInstance in nics)
        {
            nicCounters.Add(new PerformanceCounter("Network Interface",
"Bytes Total/sec", nicInstance, MachineName));
        }
        return nicCounters.ToArray();
    }
    // machine can have multiple nic cards (and laptops usually have wifi &
wired) 
    // don't want to get into figuring out which one to show, just get all
    // can enumerate network card other ways (System.Net.NetworkInformation) 

    // PerformanceCounters can return string[] of available network
interfaces
    private string[] GetNICInstances(string machineName)
    {
        string filter = "MS TCP Loopback interface";
        List<string> nics = new List<string>();
        PerformanceCounterCategory category = new
PerformanceCounterCategory("Network Interface", machineName);
        if (category.GetInstanceNames() != null)
        {
            foreach (string nic in category.GetInstanceNames())
            {
                if (!nic.Equals(filter,
StringComparison.InvariantCultureIgnoreCase))
                { nics.Add(nic); }
            }
        }
        return nics.ToArray();
    }
    /* Check the given process is running, 
       * returns null if not running
       * */
    private Process CurrentlyRunning(string sProcessName)
    {
        //get a list of all running processes on current system
        Process[] Processes = Process.GetProcesses();

        //Iterate to every process to check if it is out required process
        foreach (Process SingleProcess in Processes)
        {
            if (SingleProcess.ProcessName.Contains(sProcessName))
            {
                //process found 
                return SingleProcess;
            }
        }
        //Process not found
        return null;
    }
    // close the performance monitoring
    public void StopPerformanceMonitoring()
    {
        IsIntialized = false;
        DisposeCounters();
    }
    // called in Form.Closing or explicitely by StopPerformance()
    public void DisposeCounters()
    {
        IsIntialized = false;
        Console.WriteLine("Called Dispose Counter");
        try
        {
            // dispose of the counters
            if (cpuCounter != null)
            {
                cpuCounter.Dispose();
                cpuCounter = null;
            }
            if (ramCounter != null)
            {
                ramCounter.Dispose();
                ramCounter = null;
            }
            if (pageCounter != null)
            {
                pageCounter.Dispose();
                pageCounter = null;
            }
            if (threadCountCounter != null)
            {
                threadCountCounter.Dispose();
                threadCountCounter = null;
            }
            if (handleCountCounter != null)
            {
                handleCountCounter.Dispose();
                handleCountCounter = null;
            }
            if (nicCounters != null)
            {
                foreach (PerformanceCounter counter in nicCounters)
                {
                    counter.Dispose();                  
                }
                nicCounters = null;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot dispose counters {0}", ex.ToString());
        }
        finally
        {
            PerformanceCounter.CloseSharedResources();
        }
    }       
}

Thanks for any help,

Balaji T

--
View this message in context: http://mono.1490590.n4.nabble.com/Performance-counters-are-not-working-under-linux-mono-platform-tp4375403p4375403.html
Sent from the Mono - Dev mailing list archive at Nabble.com.

Gmane