// serviced config
494751
func (c *ServicedCli) cmdConfig(ctx *cli.Context) {
	configValues := c.config.GetConfigValues()

	// build a sorted list of keys
	keys := []string{}
	for key, _ := range(configValues) {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	for _, key := range(keys) {
		entry, _ := configValues[key]
		fmt.Printf("%s=%s\n", entry.Name, entry.Value)
	}
}
7324
func (c *ServicedCli) cmdSetConnTimeout(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "set-conn-timeout")
		return
	}

	connTimeout, err := time.ParseDuration(args[1])
	if err != nil {
		fmt.Fprintf(os.Stderr, "could not parse duration: %s\n", err)
		return
	} else if connTimeout < 0 {
		fmt.Fprintln(os.Stderr, "duration cannot be negative")
		return
	}

	pool, err := c.driver.GetResourcePool(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	} else if pool == nil {
		fmt.Fprintln(os.Stderr, "pool not found")
		return
	}

	pool.ConnectionTimeout = int(connTimeout.Seconds() * 1000)
	if err := c.driver.UpdateResourcePool(*pool); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}
}
976428
func (c *ServicedCli) initLog() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "log",
		Usage:       "Administers logs",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:        "export",
				Usage:       "Exports application log data",
				Description: "serviced log export",
				// TODO: BashComplete: c.printLogExportCompletion,
				Action: c.cmdExportLogs,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "from",
						Value: "",
						Usage: "yyyy.mm.dd",
					},
					cli.StringFlag{
						Name:  "to",
						Value: "",
						Usage: "yyyy.mm.dd",
					},
					cli.StringSliceFlag{
						Name:  "service",
						Value: &cli.StringSlice{},
						Usage: "service ID or name (includes all child services)",
					},
					cli.StringSliceFlag{
						Name:  "file",
						Value: &cli.StringSlice{},
						Usage: "the application log filename",
					},
					cli.StringFlag{
						Name:  "out",
						Value: "",
						Usage: "path to output file",
					},
					cli.BoolFlag{
						Name:  "debug, d",
						Usage: "Show additional diagnostic messages",
					},
					cli.StringFlag{
						Name:  "group-by",
						Value: "container",
						Usage: "Group results either by container, service or day",
					},
					cli.BoolFlag{
						Name:  "no-children, n",
						Usage: "Do not export child services",
					},
				},
			},
		},
	})
}
1333909
func (s *ServerRPC) ServiceDelete(ctx context.Context, req *types.ServiceDelRequest) (*types.ServiceDelResponse, error) {
	err := s.daemon.DeleteService(req.PodID, req.Services)
	if err != nil {
		return nil, err
	}

	return &types.ServiceDelResponse{}, nil
}
82345
func (c *ServicedCli) cmdServiceEndpoints(ctx *cli.Context) {
	nArgs := len(ctx.Args())
	if nArgs < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "endpoints")
		c.exit(1)
		return
	}

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

	var reportExports, reportImports bool
	if ctx.Bool("all") {
		reportImports = true
		reportExports = true
	} else if ctx.Bool("imports") {
		reportImports = true
		reportExports = false
	} else {
		reportImports = false
		reportExports = true
	}

	if endpoints, err := c.driver.GetEndpoints(svc.ID, reportImports, reportExports, ctx.Bool("verify")); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	} else if len(endpoints) == 0 {
		fmt.Fprintf(os.Stderr, "%s - no endpoints defined\n", svc.Name)
		return
	} else {
		hostmap, err := c.driver.GetHostMap()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Unable to get host info, printing host IDs instead of names: %s", err)
			c.exit(1)
		}

		t := NewTable("Name,ServiceID,Endpoint,Purpose,Host,HostIP,HostPort,ContainerID,ContainerIP,ContainerPort")
		t.Padding = 4
		for _, endpoint := range endpoints {
			serviceName := svc.Name
			if svc.Instances > 1 && endpoint.Endpoint.ContainerID != "" {
				serviceName = fmt.Sprintf("%s/%d", serviceName, endpoint.Endpoint.InstanceID)
			}

			host := endpoint.Endpoint.HostID
			hostinfo, ok := hostmap[endpoint.Endpoint.HostID]
			if ok {
				host = hostinfo.Name
			}

			var hostPort string
			if endpoint.Endpoint.HostPort != 0 {
				hostPort = strconv.Itoa(int(endpoint.Endpoint.HostPort))
			}

			t.AddRow(map[string]interface{}{
				"Name":          serviceName,
				"ServiceID":     endpoint.Endpoint.ServiceID,
				"Endpoint":      endpoint.Endpoint.Application,
				"Purpose":       endpoint.Endpoint.Purpose,
				"Host":          host,
				"HostIP":        endpoint.Endpoint.HostIP,
				"HostPort":      hostPort,
				"ContainerID":   fmt.Sprintf("%-12.12s", endpoint.Endpoint.ContainerID),
				"ContainerIP":   endpoint.Endpoint.ContainerIP,
				"ContainerPort": endpoint.Endpoint.ContainerPort,
			})
		}
		t.Print()
	}
	return
}
440624
func (c *ServicedCli) cmdServiceRemoveIP(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "remove-ip")
		c.exit(1)
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}
	serviceID := svc.ID
	endpointName := ctx.Args()[1]

	arguments := []string{serviceID, endpointName}

	if err := c.driver.RemoveIP(arguments); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	}
	return
}
1092230
func (c *ServicedCli) cmdHostAddPrivate(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "add-private")
		os.Exit(1)
	}

	var address utils.URL
	if err := address.Set(args[0]); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	if ip := net.ParseIP(address.Host); ip == nil {
		// Host did not parse, try resolving
		addr, err := net.ResolveTCPAddr("tcp", args[0])
		if err != nil {
			fmt.Printf("Could not resolve %s.\n\n", args[0])
			os.Exit(1)
		}
		address.Host = addr.IP.String()
		if strings.HasPrefix(address.Host, "127.") {
			fmt.Printf("%s must not resolve to a loopback address\n\n", args[0])
			os.Exit(1)
		}
	}

	// Parse/resolve the NAT address, if provided.
	var nat utils.URL
	natString := ctx.String("nat-address")
	if len(natString) > 0 {
		if err := nat.Set(natString); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		if natip := net.ParseIP(nat.Host); natip == nil {
			// NAT did not parse, try resolving
			addr, err := net.ResolveTCPAddr("tcp", natString)
			if err != nil {
				fmt.Printf("Could not resolve nat address (%s): %s\n", natString, err)
				os.Exit(1)
			}
			nat.Host = addr.IP.String()
		}
		if strings.HasPrefix(nat.Host, "127.") {
			fmt.Printf("The nat address %s must not resolve to a loopback address\n", natString)
			os.Exit(1)
		}
	}

	cfg := api.HostConfig{
		Address: &address,
		Nat:     &nat,
		PoolID:  args[1],
		Memory:  ctx.String("memory"),
	}

	host, keyblock, err := c.driver.AddHostPrivate(cfg)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	} else if keyblock == nil {
		fmt.Fprintln(os.Stderr, "received nil key")
		os.Exit(1)
	}

	c.outputCommonKey(host, nat, keyblock)
}
1315643
func (o *Operation) Config() (*configs.Config, tfdiags.Diagnostics) {
	var diags tfdiags.Diagnostics
	config, hclDiags := o.ConfigLoader.LoadConfig(o.ConfigDir)
	diags = diags.Append(hclDiags)
	return config, diags
}
1231734
func (c *ServicedCli) initDocker() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "docker",
		Usage:       "Docker administration commands",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:        "sync",
				Usage:       "serviced docker sync",
				Description: "sync pushes all images to local registry - allows single host to easily be made master for multi-host",
				Action:      c.cmdRegistrySync,
			}, {
				Name:        "reset-registry",
				Usage:       "serviced docker reset-registry",
				Description: "Pulls images from the docker registry and updates the index",
				Action:      c.cmdResetRegistry,
			}, {
				Name:        "migrate-registry",
				Usage:       "serviced docker migrate-registry",
				Description: "Upgrades the docker registry from an older or remote registry",
				Action:      c.cmdMigrateRegistry,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "registry",
						Value: "",
						Usage: "host:port where the registry is running",
					},
					cli.BoolFlag{
						Name:  "override, f",
						Usage: "overrides all existing image records",
					},
				},
			}, {
				Name:        "override",
				Usage:       "Replace an image in the registry with a new image",
				Description: "serviced docker override OLDIMAGE NEWIMAGE",
				Action:      c.cmdDockerOverride,
			},
		},
	})
}
543134
func (a *Agent) ServiceDeregister(serviceID string) error {
	r := a.c.newRequest("PUT", "/v1/agent/service/deregister/"+serviceID)
	_, resp, err := requireOK(a.c.doRequest(r))
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}
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()
	}
}
851521
func (c *ServicedCli) cmdTemplateList(ctx *cli.Context) {
	if len(ctx.Args()) > 0 {
		templateID := ctx.Args()[0]
		if template, err := c.driver.GetServiceTemplate(templateID); err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else if template == nil {
			fmt.Fprintln(os.Stderr, "template not found")
		} else if jsonTemplate, err := json.MarshalIndent(template, " ", "  "); err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal template: %s\n", err)
		} else {
			fmt.Println(string(jsonTemplate))
		}
		return
	}

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

	if ctx.Bool("verbose") {
		if jsonTemplate, err := json.MarshalIndent(templates, " ", "  "); err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal template list: %s\n", err)
		} else {
			fmt.Println(string(jsonTemplate))
		}
	} else {
		t := NewTable(ctx.String("show-fields"))
		t.Padding = 6
		for _, tmp := range templates {
			t.AddRow(map[string]interface{}{
				"TemplateID":  tmp.ID,
				"Name":        tmp.Name,
				"Description": tmp.Description,
			})
		}
		t.Print()
	}
}
47597
func ServicedLogDir() string {
        if config.GetOptions().LogPath != "" {
		return config.GetOptions().LogPath
	} else{
		return os.Getenv("SERVICED_LOG_PATH")
	}
}
174933
func (c *ServicedCli) cmdTemplateDeploy(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 3 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "deploy")
		return
	}

	cfg := api.DeployTemplateConfig{
		ID:              args[0],
		PoolID:          args[1],
		DeploymentID:    args[2],
		ManualAssignIPs: ctx.Bool("manual-assign-ips"),
	}

	fmt.Fprintln(os.Stderr, "Deploying template - please wait...")
	if svcs, err := c.driver.DeployServiceTemplate(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if svcs == nil {
		fmt.Fprintln(os.Stderr, "received nil service definition")
	} else {
		for _, svc := range svcs {
			fmt.Println(svc.ID)
		}
	}
}
1106151
func (c *ServicedCli) Run(args []string) {
	if err := c.app.Run(args); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	}
}
969769
func (c *ServicedCli) cmdRestore(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "restore")
		return
	}

	err := c.driver.Restore(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}
203571
func (c *ServicedCli) initServer() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "server",
		Usage:       "Starts serviced",
		Description: "serviced server",
		Action:      c.cmdServer,
	})
}