terra-farm/go-xen-api-client

Get Xen Server Cpu Metrics

vanaraj-az opened this issue · 3 comments

How to get vm cpu core metrics?

Something like this should do it:

import (
    "fmt"
    xenAPI "github.com/amfranz/go-xen-api-client"
)

func main() {
    var err error

    // credentials - you should really pull these from a
    // config file or something
    xenUser := "root"
    xenPass := "yourXenPassword"

    // hostname - you should be dynamically generating
    // this or using a configured value like credentials
    hostName := "your.xen.server"

    // xapi version you wish to use
    apiVersion := "1.0"

    // originator to send with login
    originator := "myApp"

    // name-label of the VM in question, your app should
    // get this dynamically or through config as well
    vmNameLabel := "your.vm.name.label"

    // you will need to create a client object
    var xenClient *xenAPI.Client
    xenClient, err = xenAPI.NewClient("https://"+hostName, nil)
    if err != nil {
        fmt.Println("Error instantiating client:", err.Error())
        return
    }

    // then you need to get yourself a login session
    var session xenAPI.SessionRef
    session, err = xapiClient.Session.LoginWithPassword(
        xenUser, xenPass, apiVersion, originator)
    if err != nil {
        fmt.Println("Error logging in:", err.Error())
        return
    }

    // Get the VM ref
    var vm xenAPI.VMRef
    vm, err = xenClient.VM.GetByNameLabel(session, vmNameLabel)
    if err != nil {
        fmt.Println("Error getting VMRef:", err.Error())
        return
    }

    // honestly at this point you have two choices:  grab individual
    // bits of information like this:
    var vCPUMax int
    vCPUMax, err = xenClient.VM.GetVCPUsMax(session, vm)
    if err != nil {
        fmt.Println("Error getting vCPUsMax:", err.Error())
        return
    }
    fmt.Println("vCPUsMax:", vCPUMax)

    // or, if going for more than a single piece of data, just grab the
    // entire record:
    var vmRec xenAPI.VMRecord
    vmRec, err := xenClient.VM.GetRecord(session, vm)
    if err != nil {
        fmt.Println("Error getting record:", err.Error())
        return
    }
    fmt.Printf("vCPUs: %d startup / %d max\n", 
        vmRec.VCPUsAtStartup, vmRec.VCPUsMax)
}

Note that some metrics (like vCPU counts) are easier to get than others. Last I went looking for a way to pull usage % details through xapi, all I was xentop (commandline) and snmp as the only alternatives to monitoring these metrics from the VMs themselves.

This is probably worth bookmarking: http://xapi-project.github.io/xen-api/

I need to connect my local xen server and collect the metrics. Is it Possible?

@vanaraj-az see the example above. Just make sure that you update the import statement and replace amfranz with ringods.