golang实现对docker容器心跳监控功能
èªå·±åçgoç¨åºæ¾å°çº¿ä¸æ¬æ¥ç¼è¯æäºè¿å¶æä¸å»å°±è¡å¦ï¼ä½æ¯æçä¸é¢dockerçå¿ï¼æç»è¿æ¯å°å®æ¾å°docker容å¨ä¸è¿è¡èµ·æ¥äºï¼è¿è¡èµ·æ¥ä¹okï¼ä¸ä¸ªæå°å®¹å¨64Mï¼ç»ä¸ç®¡çèµ·æ¥ä¹æ¹ä¾¿ï¼ä½æ¯æ¯ç«æ¯ä¸ªçº¿ä¸é¿é©»ååçæå¡ç¨åºï¼ä¸ä¸è·æäºæä¹åï¼å¦ä½æè½çæ§å®ï¼ç´æ¥ä¸go代ç ,ç½ä¸ä»£ç ï¼ç¥å¾®åäºä¸æ³¨éï¼ä½å®æµè¿ï¼çå®ææï¼
package main import ( "encoding/json" "errors" "flag" "fmt" "io/ioutil" "log" "net" "os" "strings" "time" ) // éåç»æ type Image struct { Created uint64 Id string ParentId string RepoTags []string Size uint64 VirtualSize uint64 } // 容å¨ç»æ type Container struct { Id string `json:"Id"` Names []string `json:"Names"` Image string `json:"Image"` ImageID string `json:"ImageID"` Command string `json:"Command"` Created uint64 `json:"Created"` State string `json:"State"` Status string `json:"Status"` Ports []Port `json:"Ports"` Labels map[string]string `json:"Labels"` HostConfig map[string]string `json:"HostConfig"` NetworkSettings map[string]interface{} `json:"NetworkSettings"` Mounts []Mount `json:"Mounts"` } // docker 端å£æ å° type Port struct { IP string `json:"IP"` PrivatePort int `json:"PrivatePort"` PublicPort int `json:"PublicPort"` Type string `json:"Type"` } // docker æè½½ type Mount struct { Type string `json:"Type"` Source string `json:"Source"` Destination string `json:"Destination"` Mode string `json:"Mode"` RW bool `json:"RW"` Propatation string `json:"Propagation"` } // è¿æ¥å表 var SockAddr = "/var/run//docker.sock" //è¿å¯ä¸æ¯é便åçï¼æ¯dockerå®ç½ææ¡£çå¥æ¥åé»è®¤å¼ï¼å½ç¶å®æ¤è¿ç¨é讯æ¹å¼è¿ætcp,fdçæ¹å¼ï¼åèªé½æéç¨åºæ¯ããã var imagesSock = "GET /images/json HTTP/1.0\r\n\r\n" //docker对å¤çéåapiæä½ var containerSock = "GET /containers/json?all=true HTTP/1.0\r\n\r\n" //docker对å¤ç容å¨æ¥çapi var startContainerSock = "POST /containers/%s/start HTTP/1.0\r\n\r\n" //docker对å¤ç容å¨å¯å¨api // ç½åå var whiteList []string func main() { // 读åå½ä»¤è¡åæ° // ç½ååå表 list := flag.String("list", "", "docker white list to restart, eg: token,explorer") // 轮询çæ¶é´é´éï¼åä½ç§ times := flag.Int64("time", 10, "time interval to set read docker containers [second], default is 10 second") flag.Parse() // 解ælist => whiteList whiteList = strings.Split(*list, ",") //å°æ们å½ä»¤è¡ä¸liståæ°ç容å¨å表解æå°ä»£ç ä¸ log.SetOutput(os.Stdout) log.Println("start docker watching...") log.Printf("Your whiteList: %v\n", *list) log.Printf("Your shedule times: %ds\n", *times) //æ¥ä¸æ¥çè¿ä¸ªfor循ç¯å°±æ¯æ¯éä¸å®æ¶é´çæ§docker容å¨æ¯å¦æ£å¸¸è¿è¡ï¼ä¸æ£å¸¸å°±éæ°å¯å¨å® for { // 轮询docker err := listenDocker() if err != nil { log.Println(err.Error()) } time.Sleep(time.Duration(*times)*time.Second) } } func listenDocker() error { // è·å容å¨å表,æ¿å°ææç容å¨ä¿¡æ¯ containers, err := readContainer() if err != nil { return errors.New("read container error: " + err.Error()) } // åéåç½ååå¿«ï¼æ¬¡æ°å° for _, name := range whiteList { Name: for _, container := range containers { for _, cname := range container.Names { // å¦æå¹éå°ç½åå if cname[1:] == name { // å³å¿ä¸ä¸å®¹å¨ç¶æ log.Printf("id=%s, name=%s, state=%s", container.Id[:12], container.Names, container.Status) if strings.Contains(container.Status, "Exited") { // å¦æåºç°å¼å¸¸éåºç容å¨ï¼å¯å¨å® log.Printf("find container: [%s] has exited, ready to start it. ", name) e := startContainer(container.Id) if e != nil { log.Println("start container error: ", e.Error()) } break Name } } } } } return nil } // è·å unix sock è¿æ¥ func connectDocker() (*net.UnixConn, error) { addr := net.UnixAddr{SockAddr, "unix"} // SockAddr è¿ä¸ªåéçå¼è¢«è®¾å®ä¸ºdockerç/var/run/docker å¥æ¥åè·¯å¾å¼ï¼ä¹å°±æ¯è¯´æ¤å¤å°±æ¯æ¨éä¸dockerçdaemoné讯建ç«çå³é®å¤,å¶ä»å¤ç代ç å°±æ¯äºæ£å¸¸çé»è¾å¤çäº return net.DialUnix("unix", nil, &addr) } // å¯å¨å®¹å¨ func startContainer(id string) error { conn, err := connectDocker() if err != nil { return errors.New("connect error: " + err.Error()) } start := fmt.Sprintf(startContainerSock, id) fmt.Println(start) cmd := []byte(start) code, err := conn.Write(cmd) if err != nil { return err } log.Println("start container response code: ", code) // å¯å¨å®¹å¨çå¾20ç§ï¼é²æ¢æ°æ®éå time.Sleep(20*time.Second) return nil } // è·å容å¨å表 func readContainer() ([]Container, error) { conn, err := connectDocker() //建ç«ä¸ä¸ªunixè¿æ¥,è¿å¶å®æ¯ä¸ä¸ªå³é®ç¹ï¼éè¦ä½ äºè§£unix å¥æ¥å 建ç«è¿æ¥ if err != nil { return nil, errors.New("connect error: " + err.Error()) } _, err = conn.Write([]byte(containerSock)) if err != nil { return nil, err } result, err := ioutil.ReadAll(conn) if err != nil { return nil, err } body := getBody(result) var containers []Container err = json.Unmarshal(body, &containers) if err != nil { return nil, err } log.Println("len of containers: ", len(containers)) if len(containers) == 0 { return nil, errors.New("no containers") } return containers, nil } // è·åéåå表 func readImage(conn *net.UnixConn) ([]Image, error) { _, err := conn.Write([]byte(imagesSock)) if err != nil { return nil, err } result, err := ioutil.ReadAll(conn) if err != nil { return nil, err } body := getBody(result[:]) var images []Image err = json.Unmarshal(body, &images) if err != nil { return nil, err } return images, nil } // ä»è¿åç http ååºä¸æå body func getBody(result []byte) (body []byte) { for i:=0; i<=len(result)-4; i++ { if result[i] == 13 && result[i+1] == 10 && result[i+2] == 13 && result[i+3] == 10 { body = result[i+4:] break } } return } /* error log : 1ãwrite unix @->/var/run/docker.sock: write: broken pipe 建ç«çtcpè¿æ¥ä¸è½å¤ç¨ï¼æ¯æ¬¡æä½é½å»ºç«è¿æ¥ */
使ç¨æ¹æ³
1.ç¼è¯
go build -o main main.go
2.linuxä¸ç´æ¥å½å¯æ§è¡æ件æ§è¡ä¾¿å¯
./main -list="容å¨å称1,容å¨å称2..."
æè·¯åæ:
åæ¥dockerè¿ä¸ªè½¯ä»¶å¯¹å¤æ¯æä¾äºä¸äºåapiç¨æ¥ç®¡ç容å¨çå¢å 该æ¥ç å®æ¹apiææ¡£ ,æ¢ç¶æä¾äºapiäºé£ä¹ä»»ä½è¯è¨é½è½å®ç°å¯¹å¶ç管çæ§å¶åå¨æé¨ç½²äºã
ä½å¶å®è¿éé¢çè¦å¼æç½è¿æ¯æå¾å¤è¯è¦è®²äº
dockerè¿ä¸ªæå¡å·²ç»å·²è¿ç¨çå½¢å¼è¿è¡å¨linuxçç³»ç»ä¸äºï¼ä¸ºä»ä¹æ们è¾å¥dockeræå³çå½ä»¤è½å¤ä¸ä¹äº¤äºï¼è¿å¥½åæ¯ä¸ä¸ªä¹ 以为常çè¡ä¸ºï¼è²ä¼¼çåºå¦æ¤ï¼ä½æ¯è¦ç¥éæ们æ¯å¨ä¸ä¸ä¸ªæ£å¨è¿è¡çè¿ç¨åçé讯ï¼è¥ä»ä¸ä»¥ä¸ºç¶ï¼è¯·æ¥ä»¥ä¸é®ï¼
1.è¿ç¨é´é½æ¯å¦ä½é讯çï¼ è¿ç¨é讯é´æ¹å¼
å¨æç½äºè¿ç¨ä¹é´çé讯æ¹å¼ä¹åï¼ææç½äºdockerçè¿ä¸ªdaemoné讯åçï¼ç¬é´å°±æéäºä¹å对k8管çdockerççæ(èå®è®²åªç¥ékuberneteså¾å¼ºå¤§,å´æ²¡æ³æç½å®æ¯å¦ä½è½å¨æå¢å®¹æç容å¨éç½®,è´è½½ççç),å¥æ¥å(socket) /var/run/docker è¿ä¸ªæ们使ç¨èµ·æ¥ä¸ä¼æ¥è§¦å°ï¼ç解起æ¥å´å¿é¡»æéçå³é®ç¹è¯·å¡å¿äºè§£å®ã
æ»ç»
以ä¸æè¿°æ¯å°ç¼ç»å¤§å®¶ä»ç»çgolangå®ç°å¯¹docker容å¨å¿è·³çæ§åè½,å¸æ对大家ææ帮å©ï¼å¦æ大家æä»»ä½çé®è¯·ç»æçè¨ï¼å°ç¼ä¼åæ¶åå¤å¤§å®¶çãå¨æ¤ä¹é常æ谢大家对èæ¬ä¹å®¶ç½ç«çæ¯æï¼
å¦æä½ è§å¾æ¬æå¯¹ä½ æ帮å©ï¼æ¬¢è¿è½¬è½½ï¼ç¦è¯·æ³¨æåºå¤ï¼è°¢è°¢ï¼