// serviced host list [--verbose, -v] [HOSTID]
437393
func (c *ServicedCli) cmdHostList(ctx *cli.Context) {
	if len(ctx.Args()) > 0 {
		hostID := ctx.Args()[0]
		if host, err := c.driver.GetHostWithAuthInfo(hostID); err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else if host == nil {
			fmt.Fprintln(os.Stderr, "host not found")
		} else if jsonHost, err := json.MarshalIndent(host, " ", "  "); err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal host: %s", err)
		} else {
			fmt.Println(string(jsonHost))
		}
		return
	}

	hosts, err := c.driver.GetHostsWithAuthInfo()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	} else if hosts == nil || len(hosts) == 0 {
		fmt.Fprintln(os.Stderr, "no hosts found")
		return
	}

	if ctx.Bool("verbose") {
		if jsonHost, err := json.MarshalIndent(hosts, " ", "  "); err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal host list: %s", err)
		} else {
			fmt.Println(string(jsonHost))
		}
	} else {
		t := NewTable(ctx.String("show-fields"))
		for _, h := range hosts {
			var usage string
			if stats, err := c.driver.GetHostMemory(h.ID); err != nil {
				usage = "--"
			} else {
				usage = fmt.Sprintf("%s / %s / %s", bytefmt.ByteSize(uint64(stats.Last)), bytefmt.ByteSize(uint64(stats.Max)), bytefmt.ByteSize(uint64(stats.Average)))
			}
			t.AddRow(map[string]interface{}{
				"ID":          h.ID,
				"Auth":        h.Authenticated,
				"Pool":        h.PoolID,
				"Name":        h.Name,
				"Addr":        h.IPAddr,
				"RPCPort":     h.RPCPort,
				"Cores":       h.Cores,
				"RAM":         bytefmt.ByteSize(h.TotalRAM()),
				"Cur/Max/Avg": usage,
				"Network":     h.PrivateNetwork,
				"Release":     h.ServiceD.Release,
			})
		}
		t.Padding = 6
		t.Print()
	}
}
1075852
func (c *ServicedCli) cmdServiceStop(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "stop")
		c.exit(1)
		return
	}

	serviceIDs := make([]string, len(args))
	for i, svcID := range args {
		svc, _, err := c.searchForService(svcID, ctx.Bool("no-prefix-match"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}

		serviceIDs[i] = svc.ID
	}

	if affected, err := c.driver.StopService(api.SchedulerConfig{serviceIDs, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	} else if affected == 0 {
		fmt.Println("Service(s) already stopped")
	} else {
		fmt.Printf("Scheduled %d service(s) to stop\n", affected)
	}
	return
}
326115
func (s *HostService) NewListHostsParams() *ListHostsParams {
	p := &ListHostsParams{}
	p.p = make(map[string]interface{})
	return p
}
1143114
func (cli *Client) ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) {
	query := url.Values{}

	if options.Filters.Len() > 0 {
		filterJSON, err := filters.ToJSON(options.Filters)
		if err != nil {
			return nil, err
		}

		query.Set("filters", filterJSON)
	}

	resp, err := cli.get(ctx, "/services", query, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return nil, err
	}

	var services []swarm.Service
	err = json.NewDecoder(resp.body).Decode(&services)
	return services, err
}
835880
func (c *ServicedCli) cmdPoolListIPs(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "list-ips")
		return
	}

	if poolIps, err := c.driver.GetPoolIPs(args[0]); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	} else if poolIps.HostIPs == nil || (len(poolIps.HostIPs) == 0 && len(poolIps.VirtualIPs) == 0) {
		fmt.Fprintln(os.Stderr, "no resource pool IPs found")
		return
	} else if ctx.Bool("verbose") {
		if jsonPoolIP, err := json.MarshalIndent(poolIps.HostIPs, " ", "  "); err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal resource pool IPs: %s", err)
		} else {
			fmt.Println(string(jsonPoolIP))
		}
	} else {
		t := NewTable(ctx.String("show-fields"))
		for _, ip := range poolIps.HostIPs {
			t.AddRow(map[string]interface{}{
				"InterfaceName": ip.InterfaceName,
				"IPAddress":     ip.IPAddress,
				"Type":          "static",
			})
		}
		for _, ip := range poolIps.VirtualIPs {
			t.AddRow(map[string]interface{}{
				"InterfaceName": ip.BindInterface,
				"IPAddress":     ip.IP,
				"Type":          "virtual",
			})
		}
		t.Padding = 6
		t.Print()
	}
}
405164
func (c *ServicedCli) services() (data []string) {
	svcs, err := c.driver.GetAllServiceDetails()
	if err != nil || svcs == nil || len(svcs) == 0 {
		c.exit(1)
		return
	}

	data = make([]string, len(svcs))
	for i, s := range svcs {
		data[i] = s.ID
	}

	return
}
247811
func (c *Client) ListDedicatedHosts(p *ListDedicatedHostsParameter) ([]*DedicatedHost, error) {
	obj, err := c.Request("listDedicatedHosts", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.([]*DedicatedHost), err
}
1124537
func (c *ServicedCli) cmdServiceTune(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "tune")
		c.exit(1)
		return
	}

	svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	service, err := c.driver.GetService(svcDetails.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	// Check the arguments
	if !(ctx.IsSet("instances") || ctx.IsSet("ramCommitment") || ctx.IsSet("ramThreshold")) {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "tune")
		return
	}

	modified := false
	if ctx.IsSet("instances") {
		oldInstanceCount := service.Instances
		newInstanceCount := ctx.Int("instances")
		if oldInstanceCount != newInstanceCount {
			service.Instances = newInstanceCount
			modified = true
		}
	}

	if ctx.IsSet("ramCommitment") {
		oldCommitment := service.RAMCommitment
		newCommitment, err := utils.NewEngNotationFromString(ctx.String("ramCommitment"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}

		if oldCommitment.Value != newCommitment.Value {
			service.RAMCommitment = newCommitment
			modified = true
		}
	}

	if ctx.IsSet("ramThreshold") {
		oldThreshold := uint64(service.RAMThreshold)
		newThreshold := ctx.String("ramThreshold")

		suffix := newThreshold[len(newThreshold)-1:]
		if suffix != "%" {
			fmt.Fprintln(os.Stderr, fmt.Errorf("ramThreshold '%s' does not end with %%", newThreshold))
			c.exit(1)
			return
		}

		percent := newThreshold[:len(newThreshold)-1]
		val, err := strconv.ParseUint(percent, 10, 64)
		if err != nil {
			fmt.Fprintln(os.Stderr, fmt.Errorf("ramThreshold '%s' must be an integer", newThreshold))
			c.exit(1)
			return
		}

		if oldThreshold != val {
			service.RAMThreshold = uint(val)
			modified = true
		}
	}

	if modified {
		if service, err := c.driver.UpdateServiceObj(*service); err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else if service == nil {
			fmt.Fprintln(os.Stderr, "received nil service")
			c.exit(1)
			return
		} else {
			fmt.Println(service.ID)
		}
	} else {
		fmt.Printf("Service already reflects desired configured - no changes made\n\n")
		return
	}

}
1341404
func (c *ServicedCli) templates() (data []string) {
	templates, err := c.driver.GetServiceTemplates()
	if err != nil || templates == nil || len(templates) == 0 {
		return
	}

	data = make([]string, len(templates))
	for i, t := range templates {
		data[i] = t.ID
	}

	return
}
1150213
func (c *ServicedCli) cmdServiceClone(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "clone")
		c.exit(1)
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error searching for service: %s", err)
		c.exit(1)
		return
	}
	serviceID := svc.ID

	if copiedSvc, err := c.driver.CloneService(serviceID, ctx.String("suffix")); err != nil {
		fmt.Fprintf(os.Stderr, "%s: %s\n", serviceID, err)
		c.exit(1)
	} else if copiedSvc == nil {
		fmt.Fprintln(os.Stderr, "received nil service definition")
		c.exit(1)
	} else {
		fmt.Println(copiedSvc.ID)
	}
	return
}
195129
func (c *ServicedCli) cmdMetric(ctx *cli.Context) error {
	args := ctx.Args()
	if len(args) < 2 {
		fmt.Println("Insufficient number of arguments")
		return fmt.Errorf("Insufficient number of arguments")
	}
	metricName := args[0]
	metricValue := args[1]
	message, err := c.driver.PostMetric(metricName, metricValue)
	if err != nil {
		return fmt.Errorf("could not post stats: %s", err)
	}
	return fmt.Errorf(message)
}
1350133
func (s *ServerRPC) ServiceList(ctx context.Context, req *types.ServiceListRequest) (*types.ServiceListResponse, error) {
	services, err := s.daemon.GetServices(req.PodID)
	if err != nil {
		return nil, err
	}

	return &types.ServiceListResponse{
		Services: services,
	}, nil
}
1096261
func (c *ServicedCli) cmdServiceRestart(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "restart")
		c.exit(1)
		return
	}

	var sIds []string
	var instances []struct {
		Service  string
		Instance int
	}

	for _, arg := range args {
		svc, instanceID, err := c.searchForService(arg, ctx.Bool("no-prefix-match"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}

		if instanceID < 0 {
			sIds = append(sIds, svc.ID)
		} else {
			instances = append(instances, struct {
				Service  string
				Instance int
			}{
				svc.ID,
				instanceID,
			})
		}
	}

	// Batch start services
	if len(sIds) > 0 {
		if ctx.Bool("rebalance") {
			if affected, err := c.driver.RebalanceService(api.SchedulerConfig{sIds, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
				fmt.Fprintln(os.Stderr, err)
				c.exit(1)
			} else {
				fmt.Printf("Restarting %d service(s)\n", affected)
			}
		} else {
			if affected, err := c.driver.RestartService(api.SchedulerConfig{sIds, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
				fmt.Fprintln(os.Stderr, err)
				c.exit(1)
			} else {
				fmt.Printf("Restarting %d service(s)\n", affected)
			}
		}
	}

	// Iterate and reschedule any instances specified
	for _, instance := range instances {
		if err := c.driver.StopServiceInstance(instance.Service, instance.Instance); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
		} else {
			fmt.Printf("Restarting instance %s/%d\n", instance.Service, instance.Instance)
		}
	}
	return
}
887460
func (c *ServicedCli) cmdServiceVariableUnset(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "unset")
		return
	}

	svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	service, err := c.driver.GetService(svcDetails.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	key := args[1]
	if service.Context == nil {
		message := fmt.Sprintf("Variable %v not found.", key)
		fmt.Fprintln(os.Stderr, message)
		return
	}

	if _, ok := service.Context[key]; ok {
		delete(service.Context, key)
	} else {
		message := fmt.Sprintf("Variable %s not found.", key)
		fmt.Fprintln(os.Stderr, message)
		return
	}

	if service, err := c.driver.UpdateServiceObj(*service); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if service == nil {
		fmt.Fprintln(os.Stderr, "received nil service")
	} else {
		fmt.Println(service.ID)
	}
}
832773
func (c *ServicedCli) cmdPublicEndpointsVHostRemove(ctx *cli.Context) {
	// Make sure we have each argument.
	if len(ctx.Args()) != 3 {
		cli.ShowCommandHelp(ctx, "remove")
		return
	}

	serviceid := ctx.Args()[0]
	endpointName := ctx.Args()[1]
	vhostName := ctx.Args()[2]

	// We need the serviceid, but they may have provided the service id or name.
	svc, _, err := c.searchForService(serviceid,ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	err = c.driver.RemovePublicEndpointVHost(svc.ID, endpointName, vhostName)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
	} else {
		fmt.Printf("%s\n", vhostName)
	}

	return
}
685475
func (c *ServicedCli) cmdServiceVariableGet(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "get")
		return
	}

	svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	service, err := c.driver.GetService(svcDetails.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	key := args[1]
	if service.Context == nil {
		message := fmt.Sprintf("Variable %v not found.", key)
		fmt.Fprintln(os.Stderr, message)
		return
	}

	if value, found := service.Context[key]; found {
		switch value.(type) {
		case string:
			if vstr, ok := value.(string); ok {
				fmt.Printf("%v\n", vstr)
			}
		case int64:
			if vstr, ok := value.(string); ok {
				fmt.Printf("%v\n", vstr)
			}
		case uint64:
			if vstr, ok := value.(string); ok {
				fmt.Printf("%v\n", vstr)
			}
		}
	} else {
		message := fmt.Sprintf("Variable %v not found.", key)
		fmt.Fprintln(os.Stderr, message)
		return
	}
}
1156966
func (c *ServicedCli) cmdPublicEndpointsListAll(ctx *cli.Context) {
	// If they specify only vhosts/ports, return those.  If they didn't specify
	// either then both are returned.
	cmdPublicEndpointsList(
		c,
		ctx,
		ctx.Bool("vhosts") || (!ctx.Bool("vhosts") && !ctx.Bool("ports")),
		ctx.Bool("ports") || (!ctx.Bool("vhosts") && !ctx.Bool("ports")),
	)
}