func update(watcher client.Watcher, space *Namespace) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() res, err := watcher.Next(ctx) if err != nil { if err != context.DeadlineExceeded { log.Errorf("watcher next failed, err[%v]", err) } return } node := res.Node if node == nil { log.Errorf("node is nil") return } if node.Dir { log.Infof("node is dir") return } service, url, err := parsePath(node.Key, space.name) if err != nil { log.Errorf("parse path failed, err[%v]", err) return } log.Infof("%s %s %s", res.Action, service, url) switch res.Action { case "set", "update": space.updateEndpoint(service, url) case "delete": space.deleteEndpoint(service, url) case "expire": space.expireEndpoint(service, url) } }
func parsePath(path string, namespace string) (service, url string, err error) { dir := watchDir(namespace) if !strings.HasPrefix(path, dir) { log.Errorf("%s has not perfix %s", path, dir) return "", "", errors.New("prefix is wrong") } names := strings.Split(path[len(dir):], "/") if len(names) != 2 { log.Errorf("%s split wrong", path[len(dir):]) return "", "", errors.New("path split wrong") } return names[0], names[1], nil }
func (p *pinger) offline() error { _, err := p.api.Delete(context.Background(), p.path, &client.DeleteOptions{}) if err != nil { log.Errorf("%s heartbeat offline failed, err[%v]", p.path, err) return err } log.Infof("%s heartbeat offline success", p.path) return nil }
func TestLog(t *testing.T) { //log.SetFlag(log.StdFlags | log.MsecFlag | log.ShortFileFlag | log.FuncNameFlag) //log.SetFileOutput("./test.log", 1024, 2) log.Fatalf("test %d %s", 1, "hello") log.Errorf("test %d", 1) log.Warnf("test %d", 1) log.Infof("test %d", 1) log.Debugf("test %d", 1) }
func (p *pinger) online() error { opts := &client.SetOptions{TTL: p.ttl} _, err := p.api.Set(context.Background(), p.path, "online", opts) if err != nil { log.Errorf("%s heartbeat ping failed, err[%v]", p.path, err) return err } log.Infof("%s heartbeat ping success", p.path) return nil }
func WatchChildren(conn *zk.Conn, zkPath string, onChange func(children []string)) { CreateRecursive(conn, zkPath, "", 0, DefaultDirACLs()) for { children, _, ch, err := conn.ChildrenW(zkPath) if err != nil { log.Errorf("watch children path error, path:%s, err:%v", zkPath, err) continue } onChange(children) select { case <-ch: } } }