From 15d5299997269563a8cbe01066aa8b9f4de1cbad Mon Sep 17 00:00:00 2001 From: Asim Date: Sat, 5 Dec 2015 19:25:36 +0000 Subject: [PATCH] Add a ping function --- cmd/cmd.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/cmd/cmd.go b/cmd/cmd.go index 6fb669fd..a675537e 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,13 +1,19 @@ package cmd import ( + "bytes" + "encoding/json" "flag" "fmt" "io" + "math/rand" + "net/http" "os" + "runtime" "strings" "text/tabwriter" "text/template" + "time" "github.com/codegangsta/cli" "github.com/micro/go-micro/broker" @@ -15,6 +21,7 @@ import ( "github.com/micro/go-micro/registry" "github.com/micro/go-micro/server" "github.com/micro/go-micro/transport" + "github.com/pborman/uuid" ) var ( @@ -85,6 +92,12 @@ var ( Usage: "Comma-separated list of transport addresses", }, + cli.BoolFlag{ + Name: "disable_ping", + EnvVar: "MICRO_DISABLE_PING", + Usage: "Disable ping", + }, + // logging flags cli.BoolFlag{ Name: "logtostderr", @@ -129,6 +142,57 @@ var ( } ) +func init() { + rand.Seed(time.Now().Unix()) +} + +// ping informs micro-services about this thing +func ping() { + type Ping struct { + Id string + Timestamp int64 + Product string + Version string + Arch string + Os string + } + + p := Ping{ + Id: uuid.NewUUID().String(), + Product: "go-micro", + Version: "latest", + Arch: runtime.GOARCH, + Os: runtime.GOOS, + } + + buf := bytes.NewBuffer(nil) + cl := &http.Client{} + + fn := func() { + p.Timestamp = time.Now().Unix() + b, err := json.Marshal(p) + if err != nil { + return + } + buf.Reset() + buf.Write(b) + rsp, err := cl.Post("https://micro-services.co/_ping", "application/json", buf) + if err != nil { + return + } + rsp.Body.Close() + } + + // don't ping unless this thing has lived for 30 seconds + time.Sleep(time.Second * 30) + + // only ping every 24 hours, be non invasive + for { + fn() + time.Sleep(time.Hour * 24) + } +} + func Setup(c *cli.Context) error { os.Args = os.Args[:1] @@ -176,6 +240,10 @@ func Setup(c *cli.Context) error { client.DefaultClient = client.NewClient() + if !c.Bool("disable_ping") { + go ping() + } + return nil }