func Start() { if !g.Config().Http.Enabled { return } addr := g.Config().Http.Listen if addr == "" { return } s := &http.Server{ Addr: addr, MaxHeaderBytes: 1 << 30, } log.Println("http listening", addr) log.Fatalln(s.ListenAndServe()) }
func heartbeat() { agentDirs, err := ListAgentDirs() if err != nil { return } hostname, err := utils.Hostname(g.Config().Hostname) if err != nil { return } heartbeatRequest := BuildHeartbeatRequest(hostname, agentDirs) if g.Config().Debug { log.Println("====>>>>") log.Println(heartbeatRequest) } bs, err := json.Marshal(heartbeatRequest) if err != nil { log.Println("encode heartbeat request fail", err) return } url := fmt.Sprintf("http://%s/heartbeat", g.Config().Server) httpRequest := httplib.Post(url).SetTimeout(time.Second*10, time.Minute) httpRequest.Body(bs) httpResponse, err := httpRequest.Bytes() if err != nil { log.Printf("curl %s fail %v", url, err) return } var heartbeatResponse model.HeartbeatResponse err = json.Unmarshal(httpResponse, &heartbeatResponse) if err != nil { log.Println("decode heartbeat response fail", err) return } if g.Config().Debug { log.Println("<<<<====") log.Println(heartbeatResponse) } HandleHeartbeatResponse(&heartbeatResponse) }
func SleepRandomDuration() { ns := int64(g.Config().Interval) * 1000000000 // 以当前时间为随机数种子,如果所有ops-updater在同一时间启动,系统时间是相同的,那么随机种子就是一样的 // 问题不大,批量ssh去启动ops-updater的话也是一个顺次的过程 r := rand.New(rand.NewSource(time.Now().UnixNano())) d := time.Duration(r.Int63n(ns)) * time.Nanosecond time.Sleep(d) }
func Heartbeat() { SleepRandomDuration() for { heartbeat() d := time.Duration(g.Config().Interval) * time.Second time.Sleep(d) } }
func configCommonRoutes() { http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) }) http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(g.VERSION)) }) http.HandleFunc("/workdir", func(w http.ResponseWriter, r *http.Request) { RenderDataJson(w, file.SelfDir()) }) http.HandleFunc("/config/reload", func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.RemoteAddr, "127.0.0.1") { err := g.ParseConfig(g.ConfigFile) AutoRender(w, g.Config(), err) } else { w.Write([]byte("no privilege")) } }) }