// CmdServiceDetach handles service detach UI
429382
func (cli *NetworkCli) CmdServiceDetach(chain string, args ...string) error {
	cmd := cli.Subcmd(chain, "detach", "CONTAINER SERVICE", "Removes a container from service backend", false)
	cmd.Require(flag.Min, 2)
	err := cmd.ParseFlags(args, true)
	if err != nil {
		return err
	}

	sn, nn := parseServiceName(cmd.Arg(1))
	containerID, err := lookupContainerID(cli, cmd.Arg(0))
	if err != nil {
		return err
	}

	sandboxID, err := lookupSandboxID(cli, containerID)
	if err != nil {
		return err
	}

	serviceID, err := lookupServiceID(cli, nn, sn)
	if err != nil {
		return err
	}

	_, _, err = readBody(cli.call("DELETE", "/services/"+serviceID+"/backend/"+sandboxID, nil, nil))
	if err != nil {
		return err
	}
	return nil
}
1048199
func (f *Facade) validateServiceDeployment(ctx datastore.Context, parentID string, sd *servicedefinition.ServiceDefinition) ([]service.Service, error) {
	store := f.serviceStore
	parent, err := store.Get(ctx, parentID)
	if err != nil {
		glog.Errorf("Could not get parent service %s: %s", parentID, err)
		return nil, err
	}
	// recursively create services
	var deployServices func(*service.Service, *servicedefinition.ServiceDefinition) ([]service.Service, error)
	deployServices = func(parent *service.Service, sd *servicedefinition.ServiceDefinition) ([]service.Service, error) {
		var svcs []service.Service
		svc, err := service.BuildService(*sd, parent.ID, parent.PoolID, int(service.SVCStop), parent.DeploymentID)
		if err != nil {
			glog.Errorf("Could not create service %s: %s", sd.Name, err)
			return nil, err
		}
		// Evaluate templated endpoints
		if err = f.evaluateEndpointTemplates(ctx, svc); err != nil {
			return nil, err
		}

		svcs = append(svcs, *svc)
		for _, sdSvc := range sd.Services {
			childsvcs, err := deployServices(svc, &sdSvc)
			if err != nil {
				return nil, err
			}
			svcs = append(svcs, childsvcs...)
		}
		return svcs, nil
	}
	return deployServices(parent, sd)
}
1241033
func NewDetachStorageCommand(new NewEntityDetacherCloserFunc) cmd.Command {
	command := &detachStorageCommand{}
	command.newEntityDetacherCloser = new
	return modelcmd.Wrap(command)
}
192504
func (s *BatchWriteOperationResponse) SetDetachFromIndex(v *BatchDetachFromIndexResponse) *BatchWriteOperationResponse {
	s.DetachFromIndex = v
	return s
}
44808
func (d *driver) VolumeDetach(
	ctx types.Context,
	volumeID string,
	opts *types.VolumeDetachOpts) (*types.Volume, error) {

	vmName := context.MustInstanceID(ctx).ID

	fields := map[string]interface{}{
		"vmName":   vmName,
		"volumeID": volumeID,
	}

	volume, err := d.getVolume(ctx, volumeID,
		types.VolumeAttachmentsRequested)
	if err != nil {
		if _, ok := err.(*types.ErrNotFound); ok {
			return nil, err
		}
		return nil, goof.WithFieldsE(fields,
			"failed to get volume", err)
	}
	if len(volume.Attachments) == 0 {
		return nil, errVolAlreadyDetached
	}

	err = d.detachDisk(ctx, &volumeID, &vmName)
	if err != nil {
		return nil, err
	}

	volume, err = d.getVolume(ctx, volumeID,
		types.VolumeAttachmentsRequested)
	if err != nil {
		return nil, goof.WithFieldsE(fields,
			"failed to get volume", err)
	}
	return volume, nil
}
829412
func (c *ServicedCli) cmdServiceStatus(ctx *cli.Context) {
	var states map[string]map[string]interface{}
	var err error

	//Determine whether to show healthcheck fields and rows based on user input:
	//   By default, we only show individual healthcheck rows if a specific service is requested
	//   However, we will show them if the user explicitly requests the "Healthcheck" or "Healthcheck Status" fields
	showIndividualHealthChecks := false       //whether or not to add rows to the table for individual health checks.
	fieldsToShow := ctx.String("show-fields") //we will modify this if not user-set

	if !ctx.IsSet("show-fields") {
		//only show the appropriate health fields based on arguments
		if len(ctx.Args()) > 0 { //don't show "HC Fail"
			fieldsToShow = strings.Replace(fieldsToShow, "HC Fail,", "", -1)
			fieldsToShow = strings.Replace(fieldsToShow, ",HC Fail", "", -1) //in case it was last in the list
		} else { //don't show "Healthcheck" or "Healthcheck Status"

			fieldsToShow = strings.Replace(fieldsToShow, "Healthcheck Status,", "", -1)
			fieldsToShow = strings.Replace(fieldsToShow, ",Healthcheck Status", "", -1) //in case it was last in the list

			fieldsToShow = strings.Replace(fieldsToShow, "Healthcheck,", "", -1)
			fieldsToShow = strings.Replace(fieldsToShow, ",Healthcheck", "", -1) //in case it was last in the list
		}
	}

	//set showIndividualHealthChecks based on the fields
	showIndividualHealthChecks = strings.Contains(fieldsToShow, "Healthcheck") || strings.Contains(fieldsToShow, "Healthcheck Status")

	if len(ctx.Args()) > 0 {
		svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}
		if states, err = c.driver.GetServiceStatus(svc.ID); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}
	} else {
		if states, err = c.driver.GetServiceStatus(""); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}
	}

	cmdSetTreeCharset(ctx, c.config)

	t := NewTable(fieldsToShow)
	childmap := make(map[string][]string)
	for id, state := range states {
		parent := fmt.Sprintf("%v", state["ParentID"])
		childmap[parent] = append(childmap[parent], id)
	}

	var addRows func(string)
	addRows = func(root string) {
		rows := childmap[root]
		if len(rows) > 0 {
			sort.Strings(rows)
			t.IndentRow()
			defer t.DedentRow()
			for _, rowid := range childmap[root] {
				row := states[rowid]
				if _, ok := row["Healthcheck"]; !ok || showIndividualHealthChecks { //if this is a healthcheck row, only include it if showIndividualHealthChecks is true
					t.AddRow(row)
				}

				nextRoot := rowid
				addRows(nextRoot)
			}
		}
	}
	addRows("")
	t.Padding = 3
	t.Print()
	return
}
558985
func (c *Client) RemoveServiceTemplate(serviceTemplateID string) error {
	if err := c.call("RemoveServiceTemplate", serviceTemplateID, nil); err != nil {
		return err
	}
	return nil

}
300049
func (c *ServicedCli) cmdServiceSetIP(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 3 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	if args[len(args)-1] == "--generate-bash-completion" {
		// CC-892: Disable bash completion after SERVICE_ID because possible matches
		// are unavailable outside the container.
		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 endpointName string
	if len(args) > 1 {
		endpointName = args[1]
	}

	var ipAddress string
	if len(args) > 2 {
		ipAddress = args[2]
	}

	if ctx.Int("port") < 1 {
		fmt.Printf("Please specify the valid port number.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	if ctx.String("proto") == "" {
		fmt.Printf("Please specify port protocol.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	cfg := api.IPConfig{
		ServiceID:    svc.ID,
		IPAddress:    ipAddress,
		Port:         uint16(ctx.Int("port")),
		Proto:        ctx.String("proto"),
		EndpointName: endpointName,
	}

	if err := c.driver.SetIP(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	}
	return
}
1079430
func (_m *Facade) ScheduleServiceBatch(_a0 datastore.Context, _a1 []*servicestatemanager.CancellableService, _a2 string, _a3 service.DesiredState) ([]string, error) {
	ret := _m.Called(_a0, _a1, _a2, _a3)

	var r0 []string
	if rf, ok := ret.Get(0).(func(datastore.Context, []*servicestatemanager.CancellableService, string, service.DesiredState) []string); ok {
		r0 = rf(_a0, _a1, _a2, _a3)
	} else {
		r0 = ret.Get(0).([]string)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(datastore.Context, []*servicestatemanager.CancellableService, string, service.DesiredState) error); ok {
		r1 = rf(_a0, _a1, _a2, _a3)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1355705
func (_m *API) ExecAttach(ctx context.Context, execID string, detach bool, tty bool) (io.ReadCloser, error) {
	ret := _m.Called(ctx, execID, detach, tty)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, string, bool, bool) io.ReadCloser); ok {
		r0 = rf(ctx, execID, detach, tty)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, string, bool, bool) error); ok {
		r1 = rf(ctx, execID, detach, tty)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1046755
func deleteServiceLB(ctx *cli.Context) {
	if len(ctx.Args()) != 1 {
		errExit(ctx, exitHelp, "Service name required", true)
	}

	serviceName := ctx.Args()[0]
	tenantName := ctx.String("tenant")
	if len(tenantName) == 0 {
		tenantName = "default"
	}
	fmt.Printf("Deleting Service  %s,%s\n", serviceName, tenantName)

	errCheck(ctx, getClient(ctx).ServiceLBDelete(tenantName, serviceName))
}
422999
func (c *ServicedCli) cmdSnapshotRemove(ctx *cli.Context) {

	args := ctx.Args()
	force := ctx.Bool("force")

	snapshotsToDelete := []string{}

	if len(args) > 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "remove")
		return
	}

	if len(args) == 0 {
		// user wants to delete all snapshots, but check for -f first
		if !force {
			fmt.Printf("Incorrect Usage.\nUse\n   serviced snapshot remove -f\nto delete all snapshots, or\n   serviced snapshot remove -h\nfor help with this command.\n")
			return
		} else {
			//delete all snapshots
			snapshots, err := c.driver.GetSnapshots()
			if err != nil {
				fmt.Fprintln(os.Stderr, err)
				return
			}
			for _, snapshot := range snapshots {
				snapshotsToDelete = append(snapshotsToDelete, snapshot.SnapshotID)
			}
		}
	} else if len(args) == 1 {
		//Delete the snapshot specified in the argument
		snapshotsToDelete = []string{args[0]}
	} else {
		//Find the snapshot with the given tag and service
		if snapshot, err := c.driver.GetSnapshotByServiceIDAndTag(args[0], args[1]); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		} else if snapshot != "" {
			snapshotsToDelete = []string{snapshot}
		}
	}

	if len(snapshotsToDelete) == 0 {
		fmt.Println("No matching snapshots found.")
		return
	}

	//Delete the chosen snapshots
	for _, id := range snapshotsToDelete {
		if err := c.driver.RemoveSnapshot(id); err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else {
			fmt.Println(id)
		}
	}
}
159576
func (d *Daemon) CheckServiceTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
	return func(c *check.C) (interface{}, check.CommentInterface) {
		tasks := d.GetServiceTasks(c, service)
		return len(tasks), nil
	}
}
772888
func (c *ServicedCli) cmdHealthCheck(ctx *cli.Context) error {
	if ctx.Bool("help") {
		return nil
	}

	if results, err := c.driver.ServicedHealthCheck(ctx.Args()); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return c.exit(2)
	} else {

		exitStatus := 0
		t := NewTable("Service Name,Container Name,Container ID,Health Check,Status")
		t.Padding = 2
		for _, serviceHealth := range results {
			for _, status := range serviceHealth.HealthStatuses {
				if status.Status != "passed" {
					exitStatus = 1
				}
				if serviceHealth.ContainerID == "" {
					serviceHealth.ContainerID = "<none>"
				}

				t.AddRow(map[string]interface{}{
					"Service Name":   serviceHealth.ServiceName,
					"Container Name": serviceHealth.ContainerName,
					"Container ID":   serviceHealth.ContainerID[:min(12, len(serviceHealth.ContainerID))],
					"Health Check":   status.Name,
					"Status":         getCombinedStatus(status.Status, status.Failure),
				})
			}
		}
		t.Print()
		return c.exit(exitStatus)
	}
}
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)
		}
	}
}
598630
func (i *Handle) DelService(s *Service) error {
	return i.doCmd(s, nil, ipvsCmdDelService)
}
1085530
func performServiceCommand(command string) error {
	var err error
	switch command {
	case "install":
		err = installService()

	case "remove":
		err = removeService()

	case "start":
		err = startService()

	case "stop":
		err = controlService(svc.Stop, svc.Stopped)

	default:
		err = fmt.Errorf("invalid service command [%s]", command)
	}

	return err
}