Example #1
0
func ListServices(c *cli.Context) ([]byte, error) {
	var rsp []*registry.Service
	var err error

	if p := c.GlobalString("proxy_address"); len(p) > 0 {
		if err := get(p+"/registry", &rsp); err != nil {
			return nil, err
		}
	} else {
		rsp, err = (*cmd.DefaultOptions().Registry).ListServices()
		if err != nil {
			return nil, err
		}
	}

	sort.Sort(sortedServices{rsp})

	var services []string

	for _, service := range rsp {
		services = append(services, service.Name)
	}

	return []byte(strings.Join(services, "\n")), nil
}
Example #2
0
func web(ctx *cli.Context) {
	opts := []gweb.Option{
		gweb.Name("go.micro.web.discovery"),
		gweb.Handler(whandler.Router()),
	}

	opts = append(opts, helper.WebOpts(ctx)...)

	templateDir := "discovery/templates"
	if dir := ctx.GlobalString("html_dir"); len(dir) > 0 {
		templateDir = dir
	}

	whandler.Init(
		templateDir,
		proto.NewDiscoveryClient("go.micro.srv.discovery", *cmd.DefaultOptions().Client),
		proto2.NewRegistryClient("go.micro.srv.discovery", *cmd.DefaultOptions().Client),
	)

	service := gweb.NewService(opts...)

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #3
0
func DeregisterService(c *cli.Context, args []string) ([]byte, error) {
	if len(args) == 0 {
		return nil, errors.New("require service definition")
	}

	req := strings.Join(args, " ")

	if p := c.GlobalString("proxy_address"); len(p) > 0 {
		if err := del(p+"/registry", []byte(req), nil); err != nil {
			return nil, err
		}
		return []byte("ok"), nil
	}

	var service *registry.Service

	d := json.NewDecoder(strings.NewReader(req))
	d.UseNumber()

	if err := d.Decode(&service); err != nil {
		return nil, err
	}

	if err := (*cmd.DefaultOptions().Registry).Deregister(service); err != nil {
		return nil, err
	}

	return []byte("ok"), nil
}
Example #4
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.discovery"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
		micro.BeforeStart(discovery.Start),
		micro.AfterStop(discovery.Stop),
	)

	service.Server().Subscribe(
		service.Server().NewSubscriber(
			discovery.HeartbeatTopic,
			discovery.Default.ProcessHeartbeat,
		),
	)

	service.Server().Subscribe(
		service.Server().NewSubscriber(
			discovery.WatchTopic,
			discovery.Default.ProcessResult,
		),
	)

	proto.RegisterDiscoveryHandler(service.Server(), new(handler.Discovery))
	proto2.RegisterRegistryHandler(service.Server(), new(handler.Registry))

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #5
0
func (r *router) Init(ctx *cli.Context) error {
	// TODO: Make this more configurable and add more sources
	var conf config.Config

	if c := ctx.String("config_source"); len(c) == 0 && r.opts.Config == nil {
		return errors.New("config source must be defined")
	} else if len(c) > 0 {
		var source config.Source

		switch c {
		case "platform":
			source = config.NewSource()
		case "file":
			fileName := DefaultFile

			parts := strings.Split(c, ":")

			if len(parts) > 1 {
				fileName = parts[1]
			}

			source = file.NewSource(config.SourceName(fileName))
		default:
			return errors.New("Unknown config source " + c)
		}

		conf = config.NewConfig(config.WithSource(source))
	} else {
		conf = r.opts.Config
	}

	go r.run(conf)

	return nil
}
Example #6
0
func QueryService(c *cli.Context, args []string) ([]byte, error) {
	if len(args) < 2 {
		return nil, errors.New("require service and method")
	}

	var req, service, method string
	service = args[0]
	method = args[1]

	if len(args) > 2 {
		req = strings.Join(args[2:], " ")
	}

	// empty request
	if len(req) == 0 {
		req = `{}`
	}

	var request map[string]interface{}
	var response json.RawMessage

	if p := c.GlobalString("proxy_address"); len(p) > 0 {
		request = map[string]interface{}{
			"service": service,
			"method":  method,
			"request": req,
		}

		b, err := json.Marshal(request)
		if err != nil {
			return nil, err
		}

		if err := post(p+"/rpc", b, &response); err != nil {
			return nil, err
		}

	} else {
		d := json.NewDecoder(strings.NewReader(req))
		d.UseNumber()

		if err := d.Decode(&request); err != nil {
			return nil, err
		}

		creq := (*cmd.DefaultOptions().Client).NewJsonRequest(service, method, request)
		err := (*cmd.DefaultOptions().Client).Call(context.Background(), creq, &response)
		if err != nil {
			return nil, fmt.Errorf("error calling %s.%s: %v\n", service, method, err)
		}
	}

	var out bytes.Buffer
	defer out.Reset()
	if err := json.Indent(&out, response, "", "\t"); err != nil {
		return nil, err
	}
	return out.Bytes(), nil
}
Example #7
0
func getService(c *cli.Context) {
	rsp, err := command.GetService(c, c.Args())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(rsp))
}
Example #8
0
func queryHealth(c *cli.Context) {
	rsp, err := command.QueryHealth(c, c.Args())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(rsp))
}
Example #9
0
func getService(c *cli.Context) {
	if !c.Args().Present() {
		fmt.Println("Service required")
		return
	}
	service, err := (*cmd.DefaultOptions().Registry).GetService(c.Args().First())
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	if len(service) == 0 {
		fmt.Println("Service not found")
		return
	}

	fmt.Printf("service  %s\n", service[0].Name)
	for _, serv := range service {
		fmt.Println("\nversion ", serv.Version)
		fmt.Println("\nId\tAddress\tPort\tMetadata")
		for _, node := range serv.Nodes {
			var meta []string
			for k, v := range node.Metadata {
				meta = append(meta, k+"="+v)
			}
			fmt.Printf("%s\t%s\t%d\t%s\n", node.Id, node.Address, node.Port, strings.Join(meta, ","))
		}
	}

	for _, e := range service[0].Endpoints {
		var request, response string
		var meta []string
		for k, v := range e.Metadata {
			meta = append(meta, k+"="+v)
		}
		if e.Request != nil && len(e.Request.Values) > 0 {
			request = "{\n"
			for _, v := range e.Request.Values {
				request += formatEndpoint(v, 0)
			}
			request += "}"
		} else {
			request = "{}"
		}
		if e.Response != nil && len(e.Response.Values) > 0 {
			response = "{\n"
			for _, v := range e.Response.Values {
				response += formatEndpoint(v, 0)
			}
			response += "}"
		} else {
			response = "{}"
		}
		fmt.Printf("\nEndpoint: %s\nMetadata: %s\n", e.Name, strings.Join(meta, ","))
		fmt.Printf("Request: %s\n\nResponse: %s\n", request, response)
	}
}
Example #10
0
File: slack.go Project: Zerak/micro
func (p *slackInput) Init(ctx *cli.Context) error {
	debug := ctx.Bool("slack_debug")
	token := ctx.String("slack_token")

	if len(token) == 0 {
		return errors.New("missing slack token")
	}

	p.debug = debug
	p.token = token

	return nil
}
Example #11
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.auth"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.GlobalString("database_url")) > 0 {
		mysql.Url = ctx.GlobalString("database_url")
	}

	// register account handler
	account.RegisterAccountHandler(service.Server(), new(handler.Account))
	// register oauth2 handler
	oauth2.RegisterOauth2Handler(service.Server(), new(handler.Oauth2))

	// initialise database
	if err := db.Init(); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #12
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.trace"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.GlobalString("database_url")) > 0 {
		mysql.Url = ctx.GlobalString("database_url")
	}

	proto.RegisterTraceHandler(service.Server(), new(handler.Trace))

	service.Server().Subscribe(
		service.Server().NewSubscriber(trace.TraceTopic, trace.ProcessSpan),
	)

	if err := db.Init(); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #13
0
// TODO: stream via HTTP
func streamService(c *cli.Context) {
	if len(c.Args()) < 2 {
		fmt.Println("require service and method")
		return
	}
	service := c.Args()[0]
	method := c.Args()[1]
	var request map[string]interface{}
	json.Unmarshal([]byte(strings.Join(c.Args()[2:], " ")), &request)
	req := (*cmd.DefaultOptions().Client).NewJsonRequest(service, method, request)
	stream, err := (*cmd.DefaultOptions().Client).Stream(context.Background(), req)
	if err != nil {
		fmt.Printf("error calling %s.%s: %v\n", service, method, err)
		return
	}

	if err := stream.Send(request); err != nil {
		fmt.Printf("error sending to %s.%s: %v\n", service, method, err)
		return
	}

	for {
		var response map[string]interface{}
		if err := stream.Recv(&response); err != nil {
			fmt.Printf("error receiving from %s.%s: %v\n", service, method, err)
			return
		}

		b, _ := json.MarshalIndent(response, "", "\t")
		fmt.Println(string(b))

		// artificial delay
		time.Sleep(time.Millisecond * 10)
	}
}
Example #14
0
File: db.go Project: micro/platform
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.db"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.String("database_service_namespace")) > 0 {
		db.DBServiceNamespace = ctx.String("database_service_namespace")
	}

	proto.RegisterDBHandler(service.Server(), new(handler.DB))

	if err := db.Init(service.Client().Options().Selector); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #15
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.config"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.GlobalString("database_url")) > 0 {
		mysql.Url = ctx.GlobalString("database_url")
	}

	proto.RegisterConfigHandler(service.Server(), new(handler.Config))

	// subcriber to watches
	service.Server().Subscribe(service.Server().NewSubscriber(config.WatchTopic, config.Watcher))

	if err := config.Init(); err != nil {
		log.Fatal(err)
	}

	if err := db.Init(); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #16
0
func deregisterService(c *cli.Context) {
	if len(c.Args()) != 1 {
		fmt.Println("require service definition")
		return
	}
	var service *registry.Service
	if err := json.Unmarshal([]byte(c.Args().First()), &service); err != nil {
		fmt.Println(err.Error())
		return
	}
	if err := (*cmd.DefaultOptions().Registry).Deregister(service); err != nil {
		fmt.Println(err.Error())
		return
	}
}
Example #17
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.monitor"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
		micro.BeforeStart(func() error {
			monitor.DefaultMonitor.Run()
			return nil
		}),
	)

	// healthchecks
	service.Server().Subscribe(
		service.Server().NewSubscriber(
			monitor.HealthCheckTopic,
			monitor.DefaultMonitor.ProcessHealthCheck,
		),
	)

	// status
	service.Server().Subscribe(
		service.Server().NewSubscriber(
			monitor.StatusTopic,
			monitor.DefaultMonitor.ProcessStatus,
		),
	)

	// stats
	service.Server().Subscribe(
		service.Server().NewSubscriber(
			monitor.StatsTopic,
			monitor.DefaultMonitor.ProcessStats,
		),
	)

	proto.RegisterMonitorHandler(service.Server(), new(handler.Monitor))

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #18
0
func runClient(service micro.Service, c *cli.Context) {
	// Create new greeter client
	greeter := greeterProto.NewGreeterClient("greeter", service.Client())

	name := "World"

	if flagName := c.String("name"); flagName != "" {
		name = flagName
	}

	// Call the greeter
	rsp, err := greeter.Hello(context.TODO(), &greeterProto.HelloRequest{Name: name})
	if err != nil {
		fmt.Println(err)
		return
	}

	// Print response
	fmt.Println(rsp.Greeting)
}
Example #19
0
func (h *hipchatInput) Init(ctx *cli.Context) error {
	username := ctx.String("hipchat_username")
	password := ctx.String("hipchat_password")
	server := ctx.String("hipchat_server")
	debug := ctx.Bool("hipchat_debug")

	if len(username) == 0 {
		return errors.New("require username")
	}

	if len(password) == 0 {
		return errors.New("require password")
	}

	if len(server) == 0 {
		return errors.New("require server")
	}

	h.username = username
	h.password = password
	h.server = server
	h.debug = debug

	return nil
}
Example #20
0
func TLSConfig(ctx *cli.Context) (*tls.Config, error) {
	cert := ctx.GlobalString("tls_cert_file")
	key := ctx.GlobalString("tls_key_file")
	ca := ctx.GlobalString("tls_client_ca_file")

	if len(cert) > 0 && len(key) > 0 {
		certs, err := tls.LoadX509KeyPair(cert, key)
		if err != nil {
			return nil, err
		}

		if len(ca) > 0 {
			caCert, err := ioutil.ReadFile(ca)
			if err != nil {
				return nil, err
			}

			caCertPool := x509.NewCertPool()
			caCertPool.AppendCertsFromPEM(caCert)

			return &tls.Config{
				Certificates: []tls.Certificate{certs},
				ClientCAs:    caCertPool,
				ClientAuth:   tls.RequireAndVerifyClientCert,
			}, nil
		}

		return &tls.Config{
			Certificates: []tls.Certificate{certs},
		}, nil
	}

	return nil, errors.New("TLS certificate and key files not specified")
}
Example #21
0
func listServices(c *cli.Context) {
	var rsp []*registry.Service
	var err error

	if p := c.GlobalString("proxy_address"); len(p) > 0 {
		if err := get(p+"/registry", &rsp); err != nil {
			fmt.Println(err.Error())
			return
		}
	} else {
		rsp, err = (*cmd.DefaultOptions().Registry).ListServices()
		if err != nil {
			fmt.Println(err.Error())
			return
		}
	}

	ss := sortedServices{rsp}
	sort.Sort(ss)

	for _, service := range ss.services {
		fmt.Println(service.Name)
	}
}
Example #22
0
func queryHealth(c *cli.Context) {
	if !c.Args().Present() {
		fmt.Println("require service name")
		return
	}
	service, err := (*cmd.DefaultOptions().Registry).GetService(c.Args().First())
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	if service == nil || len(service) == 0 {
		fmt.Println("Service not found")
		return
	}
	req := (*cmd.DefaultOptions().Client).NewRequest(service[0].Name, "Debug.Health", &proto.HealthRequest{})
	fmt.Printf("service  %s\n\n", service[0].Name)
	for _, serv := range service {
		fmt.Println("\nversion ", serv.Version)
		fmt.Println("\nnode\t\taddress:port\t\tstatus")
		for _, node := range serv.Nodes {
			address := node.Address
			if node.Port > 0 {
				address = fmt.Sprintf("%s:%d", address, node.Port)
			}
			rsp := &proto.HealthResponse{}
			err := (*cmd.DefaultOptions().Client).CallRemote(context.Background(), address, req, rsp)
			var status string
			if err != nil {
				status = err.Error()
			} else {
				status = rsp.Status
			}
			fmt.Printf("%s\t\t%s:%d\t\t%s\n", node.Id, node.Address, node.Port, status)
		}
	}
}
Example #23
0
func queryService(c *cli.Context) {
	if len(c.Args()) < 2 {
		fmt.Println("require service and method")
		return
	}
	service := c.Args()[0]
	method := c.Args()[1]
	var request map[string]interface{}
	var response map[string]interface{}
	json.Unmarshal([]byte(strings.Join(c.Args()[2:], " ")), &request)
	req := (*cmd.DefaultOptions().Client).NewJsonRequest(service, method, request)
	err := (*cmd.DefaultOptions().Client).Call(context.Background(), req, &response)
	if err != nil {
		fmt.Printf("error calling %s.%s: %v\n", service, method, err)
		return
	}
	b, _ := json.MarshalIndent(response, "", "\t")
	fmt.Println(string(b))
}
Example #24
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.event"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.GlobalString("database_url")) > 0 {
		mysql.Url = ctx.GlobalString("database_url")
	}

	proto.RegisterEventHandler(service.Server(), new(handler.Event))

	service.Server().Subscribe(
		service.Server().NewSubscriber(
			"micro.event.record",
			event.Process,
			server.SubscriberQueue("event-srv"),
		),
	)

	// For watchers
	service.Server().Subscribe(
		service.Server().NewSubscriber(
			"micro.event.record",
			event.Stream,
		),
	)

	if err := db.Init(); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #25
0
File: kv.go Project: micro/platform
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.kv"),
		micro.Version("latest"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
		micro.Flags(),
	)

	opts := []kv.Option{
		kv.Client(service.Client()),
		kv.Server(service.Server()),
	}

	if len(ctx.String("namespace")) > 0 {
		opts = append(opts, kv.Namespace(ctx.String("namespace")))
	}

	keyval := kv.NewKV(opts...)
	defer keyval.Close()

	service.Server().Init(server.WrapHandler(func(fn server.HandlerFunc) server.HandlerFunc {
		return func(ctx context.Context, req server.Request, rsp interface{}) error {
			ctx = kv.NewContext(ctx, keyval)
			return fn(ctx, req, rsp)
		}
	}))

	proto.RegisterStoreHandler(service.Server(), new(handler.Store))

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #26
0
func srv(ctx *cli.Context) {
	service := micro.NewService(
		micro.Name("go.micro.srv.router"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	if len(ctx.GlobalString("database_url")) > 0 {
		mysql.Url = ctx.GlobalString("database_url")
	}

	router.Init(service)

	proto.RegisterRouterHandler(service.Server(), new(handler.Router))
	label.RegisterLabelHandler(service.Server(), new(handler.Label))
	rule.RegisterRuleHandler(service.Server(), new(handler.Rule))

	// subcriber to stats
	service.Server().Subscribe(
		service.Server().NewSubscriber(
			router.StatsTopic,
			router.ProcessStats,
		),
	)

	// initialise database
	if err := db.Init(); err != nil {
		log.Fatal(err)
	}

	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
Example #27
0
func deregisterService(c *cli.Context) {
	if len(c.Args()) != 1 {
		fmt.Println("require service definition")
		return
	}

	if p := c.GlobalString("proxy_address"); len(p) > 0 {
		if err := del(p+"/registry", []byte(c.Args().First()), nil); err != nil {
			fmt.Println(err.Error())
		}
		return
	}

	var service *registry.Service
	if err := json.Unmarshal([]byte(c.Args().First()), &service); err != nil {
		fmt.Println(err.Error())
		return
	}
	if err := (*cmd.DefaultOptions().Registry).Deregister(service); err != nil {
		fmt.Println(err.Error())
		return
	}
}
Example #28
0
func GetService(c *cli.Context, args []string) ([]byte, error) {
	if len(args) == 0 {
		return nil, errors.New("service requested")
	}

	var output []string
	var service []*registry.Service
	var err error

	if p := c.GlobalString("proxy_address"); len(p) > 0 {
		if err := get(p+"/registry?service="+args[0], &service); err != nil {
			return nil, err
		}
	} else {
		service, err = (*cmd.DefaultOptions().Registry).GetService(args[0])
	}

	if err != nil {
		return nil, err
	}

	if len(service) == 0 {
		return nil, errors.New("Service not found")
	}

	output = append(output, "service  "+service[0].Name)

	for _, serv := range service {
		output = append(output, "\nversion "+serv.Version)
		output = append(output, "\nId\tAddress\tPort\tMetadata")
		for _, node := range serv.Nodes {
			var meta []string
			for k, v := range node.Metadata {
				meta = append(meta, k+"="+v)
			}
			output = append(output, fmt.Sprintf("%s\t%s\t%d\t%s", node.Id, node.Address, node.Port, strings.Join(meta, ",")))
		}
	}

	for _, e := range service[0].Endpoints {
		var request, response string
		var meta []string
		for k, v := range e.Metadata {
			meta = append(meta, k+"="+v)
		}
		if e.Request != nil && len(e.Request.Values) > 0 {
			request = "{\n"
			for _, v := range e.Request.Values {
				request += formatEndpoint(v, 0)
			}
			request += "}"
		} else {
			request = "{}"
		}
		if e.Response != nil && len(e.Response.Values) > 0 {
			response = "{\n"
			for _, v := range e.Response.Values {
				response += formatEndpoint(v, 0)
			}
			response += "}"
		} else {
			response = "{}"
		}

		output = append(output, fmt.Sprintf("\nEndpoint: %s\nMetadata: %s\n", e.Name, strings.Join(meta, ",")))
		output = append(output, fmt.Sprintf("Request: %s\n\nResponse: %s\n", request, response))
	}

	return []byte(strings.Join(output, "\n")), nil
}
Example #29
0
func QueryHealth(c *cli.Context, args []string) ([]byte, error) {
	if len(args) == 0 {
		return nil, errors.New("require service name")
	}

	service, err := (*cmd.DefaultOptions().Registry).GetService(args[0])
	if err != nil {
		return nil, err
	}

	if service == nil || len(service) == 0 {
		return nil, errors.New("Service not found")
	}

	req := (*cmd.DefaultOptions().Client).NewRequest(service[0].Name, "Debug.Health", &proto.HealthRequest{})

	var output []string

	// print things
	output = append(output, "service  "+service[0].Name)

	for _, serv := range service {
		// print things
		output = append(output, "\nversion "+serv.Version)
		output = append(output, "\nnode\t\taddress:port\t\tstatus")

		// query health for every node
		for _, node := range serv.Nodes {
			address := node.Address
			if node.Port > 0 {
				address = fmt.Sprintf("%s:%d", address, node.Port)
			}
			rsp := &proto.HealthResponse{}

			var err error

			if p := c.GlobalString("proxy_address"); len(p) > 0 {
				// call using proxy
				request := map[string]interface{}{
					"service": service[0].Name,
					"method":  "Debug.Health",
					"address": address,
				}

				b, err := json.Marshal(request)
				if err != nil {
					return nil, err
				}

				if err := post(p+"/rpc", b, &rsp); err != nil {
					return nil, err
				}
			} else {
				// call using client
				err = (*cmd.DefaultOptions().Client).CallRemote(context.Background(), address, req, rsp)
			}

			var status string
			if err != nil {
				status = err.Error()
			} else {
				status = rsp.Status
			}
			output = append(output, fmt.Sprintf("%s\t\t%s:%d\t\t%s", node.Id, node.Address, node.Port, status))
		}
	}

	return []byte(strings.Join(output, "\n")), nil
}
Example #30
0
func run(ctx *cli.Context) {
	// Parse flags
	if len(ctx.String("inputs")) == 0 {
		log.Println("[bot] no inputs specified")
		os.Exit(1)
	}

	inputs := strings.Split(ctx.String("inputs"), ",")
	if len(inputs) == 0 {
		log.Println("[bot] no inputs specified")
		os.Exit(1)
	}

	ios := make(map[string]input.Input)
	cmds := make(map[string]command.Command)

	// create built in commands
	for pattern, cmd := range commands {
		cmds[pattern] = cmd(ctx)
	}

	// take other commands
	for pattern, cmd := range command.Commands {
		if c, ok := cmds[pattern]; ok {
			log.Printf("[bot] command %s already registered for pattern %s\n", c.String(), pattern)
			continue
		}
		// register command
		cmds[pattern] = cmd
	}

	// Parse inputs
	for _, io := range inputs {
		i, ok := input.Inputs[io]
		if !ok {
			log.Printf("[bot] input %s not found\n", i)
			os.Exit(1)
		}
		ios[io] = i
	}

	// Start bot
	b := newBot(ctx, ios, cmds)

	if err := b.start(); err != nil {
		log.Println("error starting bot", err)
		os.Exit(1)
	}

	// setup service
	service := micro.NewService(
		micro.Name("go.micro.bot"),
		micro.RegisterTTL(
			time.Duration(ctx.GlobalInt("register_ttl"))*time.Second,
		),
		micro.RegisterInterval(
			time.Duration(ctx.GlobalInt("register_interval"))*time.Second,
		),
	)

	// Run server
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

	// Stop bot
	if err := b.stop(); err != nil {
		log.Println("error stopping bot", err)
	}
}