小花狸監控之Mongodb

壹頁書發表於2015-03-23
MongoDB監控內容
1.副本集狀態
2.記憶體使用和對映情況
3.5秒內增、刪、改、查請求的平均值.


$GOLANG/src/probe/module/Host.go

package module

import (
    "io/ioutil"
    "net"
    "os/exec"
    "strconv"
    "strings"
    "syscall"
    "time"
)

type Disk struct {
    Name string `json:name`
    All  uint64 `json:all`
    Used uint64 `json:used`
    Free uint64 `json:free`
}


func (this *Disk) DiskUsage() {
    fs := syscall.Statfs_t{}
    err := syscall.Statfs(this.Name, &fs)
    if err != nil {
        this.All = 0
        this.Free = 0
        this.Used = 0
    }
    this.All = fs.Blocks * uint64(fs.Bsize)
    this.Free = fs.Bavail * uint64(fs.Bsize)
    this.Used = this.All - fs.Bfree*uint64(fs.Bsize)
}

type Memory struct {
    AllMemory  uint64 `json:allmemory`
    UsedMemory uint64 `json:usedmemory`
    FreeMemory uint64 `json:freememory`
}

func (this *Memory) MemoryUsage() {
    cmd := exec.Command("/bin/bash", "-c", `free -m | awk 'NR==3 {print $3"TAB"$4}'`)
    stdout, _ := cmd.StdoutPipe()
    cmd.Start()
    bytes, _ := ioutil.ReadAll(stdout)
    data := strings.Split(string(bytes), "TAB")
    this.UsedMemory, _ = strconv.ParseUint(data[0], 10, 64)
    this.FreeMemory, _ = strconv.ParseUint(strings.Trim(data[1], "\n"), 10, 64)
    this.AllMemory = this.UsedMemory + this.FreeMemory
}

type Host struct {
    Ip     string
    Root   Disk `json:root`
    Data   Disk `json:data`
    Dbdata Disk `json:dbdata`
    Memory
    Cpu
    Ts time.Time `json:ts`
}

func GetHostAddr() string {
    addrs, _ := net.InterfaceAddrs()
    for _, addr := range addrs {
        ip := addr.String()
        if !strings.HasPrefix(ip, "127") && !strings.HasPrefix(ip, "192") && !strings.HasSuffix(ip, "128") && !strings.HasSuffix(ip, "64") {
            return ip[0:strings.LastIndex(ip, "/")]
        }
    }
    return "127.0.0.1"
}

func (this *Host) HostUsage() {
    this.Ip = GetHostAddr()
    this.MemoryUsage()
    this.Root.DiskUsage()
    this.Data.DiskUsage()
    this.Dbdata.DiskUsage()
    this.Cpu.CpuUsage()
}

type Cpu struct {
    CpuIdle float64
}

func (this *Cpu) CpuUsage() {
    cmd := exec.Command("/bin/bash", "-c", `top -b -n 1 | grep Cpu | awk -F"," '{print $4}' | sed 's/%id//g;s/^ //g'`)
    stdout, _ := cmd.StdoutPipe()
    cmd.Start()
    bytes, _ := ioutil.ReadAll(stdout)
    cpuidle, _ := strconv.ParseFloat(strings.Trim(string(bytes), "\n"), 64)
    this.CpuIdle = cpuidle
}

func NewHost(host *Host) {
    host.Root = Disk{Name: "/"}    
    host.Data = Disk{Name: "/data"}
    host.Dbdata = Disk{Name: "/dbdata"}
    host.Ts = time.Now()
    host.HostUsage()
}

$GOLANG/src/probe/module/Mongo.go

package module

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "strconv"
    "time"
)

type Member struct {
    Id         string
    Name       string
    Health     string
    StateStr   string
    Uptime     string
    OptimeDate string
}
type MongoInfo struct {
    Set                string
    Date               string
    MyState            string
    Members            [3]*Member
    Ok                 string
    Host               Host
    Insert             int64
    Query              int64
    Update             int64
    Delete             int64
    Getmore            int64
    Command            int64
    Res                int64
    Virtual            int64
    Mapped             int64
    CurrentConnections int64
    BytesIn            int64
    BytesOut           int64
    NumRequests        int64
}

func GetMongodbInfo(user string, password string, port string) *MongoInfo {
    mongoinfo := &MongoInfo{}
    NewHost(&mongoinfo.Host)
    session, _ := mgo.Dial(GetHostAddr() + ":" + port)
    defer session.Close()
    session.Login(&mgo.Credential{Username: user, Password: password})
    var rsStatus = &bson.M{}
    session.Run("replSetGetStatus", rsStatus)
    mongoinfo.Set = (*rsStatus)["set"].(string)
    mongoinfo.Date = (*rsStatus)["date"].(time.Time).Format("2006-01-02 15:04:05")
    mongoinfo.MyState = strconv.FormatInt(int64((*rsStatus)["myState"].(int)), 10)
    mongoinfo.Ok = strconv.FormatInt(int64((*rsStatus)["ok"].(float64)), 10)
    members := (*rsStatus)["members"].([]interface{})
    var i int = 0
    for _, v := range members {
        val := v.(bson.M)
        member := &Member{}
        member.Id = strconv.Itoa(val["_id"].(int))
        member.Name = val["name"].(string)
        member.Health = strconv.FormatInt(int64(val["health"].(float64)), 10)
        member.StateStr = val["stateStr"].(string)
        member.Uptime = strconv.Itoa(val["uptime"].(int))
        member.OptimeDate = val["optimeDate"].(time.Time).Format("2006-01-02 15:04:05")
        mongoinfo.Members[i] = member
        i++
    }

    var serverStatus = &bson.M{}
    session.Run("serverStatus", serverStatus)
    mongoinfo.Res = int64((*serverStatus)["mem"].(bson.M)["resident"].(int))
    mongoinfo.Virtual = int64((*serverStatus)["mem"].(bson.M)["virtual"].(int))
    mongoinfo.Mapped = int64((*serverStatus)["mem"].(bson.M)["mapped"].(int))
    mongoinfo.CurrentConnections = int64((*serverStatus)["connections"].(bson.M)["current"].(int))

    sInsert := (*serverStatus)["opcounters"].(bson.M)["insert"].(int)
    sQuery := (*serverStatus)["opcounters"].(bson.M)["query"].(int)
    sUpdate := (*serverStatus)["opcounters"].(bson.M)["update"].(int)
    sDelete := (*serverStatus)["opcounters"].(bson.M)["delete"].(int)
    sGetmore := (*serverStatus)["opcounters"].(bson.M)["getmore"].(int)
    sCommand := (*serverStatus)["opcounters"].(bson.M)["command"].(int)
    sBytesin := (*serverStatus)["network"].(bson.M)["bytesIn"].(int)
    sBytesout := (*serverStatus)["network"].(bson.M)["bytesOut"].(int)
    sNumRequests := (*serverStatus)["network"].(bson.M)["numRequests"].(int)

    time.Sleep(5 * time.Second)
    
    session.Run("serverStatus", serverStatus)
    eInsert := (*serverStatus)["opcounters"].(bson.M)["insert"].(int)
    eQuery := (*serverStatus)["opcounters"].(bson.M)["query"].(int)
    eUpdate := (*serverStatus)["opcounters"].(bson.M)["update"].(int)
    eDelete := (*serverStatus)["opcounters"].(bson.M)["delete"].(int)
    eGetmore := (*serverStatus)["opcounters"].(bson.M)["getmore"].(int)
    eCommand := (*serverStatus)["opcounters"].(bson.M)["command"].(int)
    eBytesin := (*serverStatus)["network"].(bson.M)["bytesIn"].(int)
    eBytesout := (*serverStatus)["network"].(bson.M)["bytesOut"].(int)
    eNumRequests := (*serverStatus)["network"].(bson.M)["numRequests"].(int)

    mongoinfo.Insert = int64((eInsert - sInsert) / 5)
    mongoinfo.Query = int64((eQuery - sQuery) / 5)
    mongoinfo.Update = int64((eUpdate - sUpdate) / 5)
    mongoinfo.Delete = int64((eDelete - sDelete) / 5)
    mongoinfo.Getmore = int64((eGetmore - sGetmore) / 5)
    mongoinfo.Command = int64((eCommand - sCommand) / 5)
    mongoinfo.BytesIn = int64((eBytesin - sBytesin) / 5)
    mongoinfo.BytesOut = int64((eBytesout - sBytesout) / 5)
    mongoinfo.NumRequests = int64((eNumRequests - sNumRequests) / 5)

    return mongoinfo
}


結果:
{
    "Set": "rs", 
    "Date": "2015-03-23 14:07:13", 
    "MyState": "1", 
    "Members": [
        {
            "Id": "0", 
            "Name": "182.118.29.56:27017", 
            "Health": "1", 
            "StateStr": "PRIMARY", 
            "Uptime": "16090", 
            "OptimeDate": "2015-03-23 11:09:09"
        }, 
        {
            "Id": "1", 
            "Name": "182.118.29.58:27017", 
            "Health": "1", 
            "StateStr": "SECONDARY", 
            "Uptime": "16090", 
            "OptimeDate": "2015-03-23 11:09:09"
        }, 
        {
            "Id": "2", 
            "Name": "182.118.29.59:27017", 
            "Health": "1", 
            "StateStr": "SECONDARY", 
            "Uptime": "16066", 
            "OptimeDate": "2015-03-23 11:09:09"
        }
    ], 
    "Ok": "1", 
    "Host": {
        "Ip": "182.118.29.56", 
        "Root": {
            "Name": "/", 
            "All": 21137846272, 
            "Used": 3767271424, 
            "Free": 16296833024
        }, 
        "Data": {
            "Name": "/data", 
            "All": 0, 
            "Used": 0, 
            "Free": 0
        }, 
        "Dbdata": {
            "Name": "/dbdata", 
            "All": 0, 
            "Used": 0, 
            "Free": 0
        }, 
        "AllMemory": 7863, 
        "UsedMemory": 678, 
        "FreeMemory": 7185, 
        "CpuIdle": 99.3, 
        "Ts": "2015-03-23T14:07:13.371090641+08:00"
    }, 
    "Insert": 0, 
    "Query": 0, 
    "Update": 0, 
    "Delete": 0, 
    "Getmore": 0, 
    "Command": 2, 
    "Res": 124, 
    "Virtual": 71333, 
    "Mapped": 35279, 
    "CurrentConnections": 6, 
    "BytesIn": 322, 
    "BytesOut": 2504, 
    "NumRequests": 2
}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1470440/,如需轉載,請註明出處,否則將追究法律責任。

相關文章