// ====== service operations
967073
func (s *ScanService) create(req *restful.Request, resp *restful.Response) {
	// TODO (m0sth8): Check permissions
	raw := &scan.Scan{}

	if err := req.ReadEntity(raw); err != nil {
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusBadRequest, services.WrongEntityErr)
		return
	}
	u := filters.GetUser(req)

	mgr := s.Manager()
	defer mgr.Close()

	// TODO (m0sth8): check project and target permissions for this user

	// validations
	project, err := mgr.Projects.GetById(raw.Project)
	if err != nil {
		resp.WriteServiceError(http.StatusBadRequest,
			services.NewBadReq("project not found"))
		return
	}

	target, err := mgr.Targets.GetById(raw.Target)
	if err != nil {
		if mgr.IsNotFound(err) {
			resp.WriteServiceError(http.StatusBadRequest,
				services.NewBadReq("target not found"))
			return
		}
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
		return
	}
	if target.Project != project.Id {
		resp.WriteServiceError(http.StatusBadRequest,
			services.NewBadReq("this target is not from this project"))
		return
	}

	planObj, err := mgr.Plans.GetById(raw.Plan)
	if err != nil {
		if mgr.IsNotFound(err) {
			resp.WriteServiceError(http.StatusBadRequest,
				services.NewBadReq("plan not found"))
			return
		}
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
		return
	}
	if planObj.TargetType != target.Type {
		resp.WriteServiceError(http.StatusBadRequest,
			services.NewBadReq("target.type and plan.targetType is not compatible"))
		return
	}

	sc := &scan.Scan{
		Status:  scan.StatusCreated,
		Owner:   u.Id,
		Plan:    raw.Plan,
		Project: project.Id,
		Target:  target.Id,
		Conf: scan.ScanConf{
			Target: target.Addr(),
		},
		Sessions: []*scan.Session{},
	}
	now := time.Now().UTC()
	// Add session from plans workflow steps
	for _, step := range planObj.Workflow {
		plugin, err := mgr.Plugins.GetByName(step.Plugin)
		if err != nil {
			if mgr.IsNotFound(err) {
				resp.WriteServiceError(http.StatusBadRequest,
					services.NewBadReq(fmt.Sprintf("plugin %s is not found", step.Plugin)))
				return
			}
			logrus.Error(stackerr.Wrap(err))
			resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
			return
		}
		// TODO (m0sth8): extract template execution
		if step.Conf != nil {
			if command := step.Conf.CommandArgs; command != "" {
				t, err := template.New("").Parse(command)
				if err != nil {
					logrus.Error(stackerr.Wrap(err))
					resp.WriteServiceError(http.StatusInternalServerError, services.NewAppErr("Wrong command args template"))
					return
				}
				buf := bytes.NewBuffer(nil)
				err = t.Execute(buf, sc.Conf)
				if err != nil {
					logrus.Error(stackerr.Wrap(err))
					resp.WriteServiceError(http.StatusInternalServerError, services.NewAppErr("Wrong command args template"))
					return
				}
				step.Conf.CommandArgs = buf.String()
			}
			if formData := step.Conf.FormData; formData != "" {
				t, err := template.New("").Parse(formData)
				if err != nil {
					logrus.Error(stackerr.Wrap(err))
					resp.WriteServiceError(http.StatusInternalServerError, services.NewAppErr("Wrong form data template"))
					return
				}
				buf := bytes.NewBuffer(nil)
				err = t.Execute(buf, sc.Conf)
				if err != nil {
					logrus.Error(stackerr.Wrap(err))
					resp.WriteServiceError(http.StatusInternalServerError, services.NewAppErr("Wrong form data template"))
					return
				}
				step.Conf.FormData = buf.String()
			}
			if target := step.Conf.Target; target == "" {
				step.Conf.Target = sc.Conf.Target
			}
		} else {
			step.Conf = &plan.Conf{
				Target: sc.Conf.Target,
			}
		}

		sess := scan.Session{
			Id:     mgr.NewId(),
			Step:   step,
			Plugin: plugin.Id,
			Status: scan.StatusCreated,
			Dates: scan.Dates{
				Created: &now,
				Updated: &now,
			},
		}
		sc.Sessions = append(sc.Sessions, &sess)
	}

	obj, err := mgr.Scans.Create(sc)
	if err != nil {
		logrus.Error(stackerr.Wrap(err))
		resp.WriteServiceError(http.StatusInternalServerError, services.DbErr)
		return
	}
	// put scan to queue
	s.Scheduler().AddScan(obj)
	if _, err := mgr.Feed.AddScan(obj); err != nil {
		logrus.Error(stackerr.Wrap(err))
	}

	resp.WriteHeader(http.StatusCreated)
	resp.WriteEntity(obj)
}
57192
func (s *Store) RemoveService(service string) error {
	// Serialize command.
	cmd, err := json.Marshal(&removeServiceCommand{Service: service})
	if err != nil {
		return err
	}

	if _, err := s.raftApply(removeServiceCommandType, cmd); err != nil {
		return err
	}
	return nil
}
433854
func (s *LocalSupervisor) ServiceCount() int {
	s.Lock()
	defer s.Unlock()
	return len(s.services)
}
959172
func (ctrl *PersistentVolumeController) scheduleOperation(operationName string, operation func() error) {
	klog.V(4).Infof("scheduleOperation[%s]", operationName)

	// Poke test code that an operation is just about to get started.
	if ctrl.preOperationHook != nil {
		ctrl.preOperationHook(operationName)
	}

	err := ctrl.runningOperations.Run(operationName, operation)
	if err != nil {
		switch {
		case goroutinemap.IsAlreadyExists(err):
			klog.V(4).Infof("operation %q is already running, skipping", operationName)
		case exponentialbackoff.IsExponentialBackoff(err):
			klog.V(4).Infof("operation %q postponed due to exponential backoff", operationName)
		default:
			klog.Errorf("error scheduling operation %q: %v", operationName, err)
		}
	}
}
583547
func (d *DockerDiscovery) Services() []service.Service {
	d.RLock()
	defer d.RUnlock()

	svcList := make([]service.Service, len(d.services))

	for i, svc := range d.services {
		svcList[i] = *svc
	}

	return svcList
}
944218
func (mh MultiHandle) ServiceGenerator() ServiceGenerator {
	msg := make(MultiServiceGenerator, 0, len(mh))
	for _, h := range mh {
		if sg := h.ServiceGenerator(); sg != nil {
			msg = append(msg, sg)
		}
	}
	return msg
}
1333314
func (a *Application) ServiceInfo() (CloudService, error) {
	svc, err := a.st.CloudService(a.Name())
	if err != nil {
		return CloudService{}, errors.Trace(err)
	}
	return *svc, nil
}
496822
func ServiceWithCommand(cmd []string) ServiceSpecOpt {
	return func(spec *swarmtypes.ServiceSpec) {
		ensureContainerSpec(spec)
		spec.TaskTemplate.ContainerSpec.Command = cmd
	}
}
358919
func (c *Client) GetServices(ctx context.Context) (map[string]string, error) {
	var services map[string]string

	req, err := c.NewRequest("GET", servicesPath, nil, nil)
	if err != nil {
		return nil, err
	}

	if err := c.Do(ctx, req, &services); err != nil {
		return nil, err
	}

	return services, err
}
1373645
func (c *ServicedCli) cmdServiceAction(ctx *cli.Context) error {
	// verify args
	args := ctx.Args()
	if len(args) < 1 {
		if !ctx.Bool("help") {
			fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		}
		cli.ShowSubcommandHelp(ctx)
		c.exit(1)
		return nil
	}

	// Bash completion
	if args[len(args)-1] == "--generate-bash-completion" {
		// CC-892
		// if a tab is pressed after serviced service SERVICE_ID and the
		// service is found
		if len(args) == 2 {
			svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
			if err == nil {
				actions := c.serviceActions(svc.ID)
				fmt.Println(strings.Join(actions, "\n"))
			} else {
				c.exit(1)
			}
		}
		return c.exit(0)
	}

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

	switch len(args) {
	case 1:
		actions := c.serviceActions(svc.ID)
		if len(actions) > 0 {
			fmt.Println(strings.Join(actions, "\n"))
		} else {
			fmt.Fprintln(os.Stderr, "no actions found")
			c.exit(1)
		}
	default:
		if instanceID < 0 {
			instanceID = 0
		}
		action := ""
		argv := []string{}
		if len(args) > 1 {
			action = args[1]
			argv = args[2:]
		}

		if err := c.driver.SendDockerAction(svc.ID, instanceID, action, argv); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
		}
	}

	return fmt.Errorf("serviced service action")
}
453762
func (c *ServicedCli) initService() {

	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "service",
		Usage:       "Administers services",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:         "list",
				Usage:        "Lists all services",
				Description:  "serviced service list [SERVICEID]",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceList,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "verbose, v",
						Usage: "Show JSON format",
					},
					cli.BoolFlag{
						Name:  "ascii, a",
						Usage: "use ascii characters for service tree (env SERVICED_TREE_ASCII=1 will default to ascii)",
					},
					cli.StringFlag{
						Name:  "format",
						Value: "",
						Usage: "format the output using the given go template",
					},
					cli.StringFlag{
						Name:  "show-fields",
						Value: "Name,ServiceID,Inst,ImageID,Pool,DState,Launch,DepID",
						Usage: "Comma-delimited list describing which fields to display",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:        "status",
				Usage:       "Displays the status of deployed services",
				Description: "serviced service status { SERVICEID | SERVICENAME | [POOL/]...PARENTNAME.../SERVICENAME }",
				Action:      c.cmdServiceStatus,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "ascii, a",
						Usage: "use ascii characters for service tree (env SERVICED_TREE_ASCII=1 will default to ascii)",
					},
					cli.StringFlag{
						Name:  "show-fields",
						Value: "Name,ServiceID,Status,HC Fail,Healthcheck,Healthcheck Status,Uptime,RAM,Cur/Max/Avg,Hostname,InSync,DockerID",
						Usage: "Comma-delimited list describing which fields to display",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:        "add",
				Usage:       "Adds a new service",
				Description: "serviced service add NAME IMAGEID COMMAND",
				Action:      c.cmdServiceAdd,
				Flags: []cli.Flag{
					cli.GenericFlag{
						Name:  "p",
						Value: &api.PortMap{},
						Usage: "Expose a port for this service (e.g. -p tcp:3306:mysql)",
					},
					cli.GenericFlag{
						Name:  "q",
						Value: &api.PortMap{},
						Usage: "Map a remote service port (e.g. -q tcp:3306:mysql)",
					},
					cli.StringFlag{
						Name:  "parent-id",
						Value: "",
						Usage: "Parent service ID for which this service relates",
					},
				},
			}, {
				Name:        "clone",
				Usage:       "Clones a new service",
				Description: "serviced service clone { SERVICEID | SERVICENAME | [DEPLOYMENTID/]...PARENTNAME.../SERVICENAME }",
				Action:      c.cmdServiceClone,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "suffix",
						Value: "",
						Usage: "name to append to service name, volumes, endpoints",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "remove",
				ShortName:    "rm",
				Usage:        "Removes an existing service",
				Description:  "serviced service remove SERVICEID",
				BashComplete: c.printServicesAll,
				Action:       c.cmdServiceRemove,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "edit",
				Usage:        "Edits an existing service in a text editor",
				Description:  "serviced service edit SERVICEID",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceEdit,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "editor, e",
						Value: os.Getenv("EDITOR"),
						Usage: "Editor used to update the service definition",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "assign-ip",
				Usage:        "Assigns an IP address to a service's endpoints requiring an explicit IP address",
				Description:  "serviced service assign-ip SERVICEID [IPADDRESS]",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceAssignIP,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "start",
				Usage:        "Starts one or more services",
				Description:  "serviced service start SERVICEID ...",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceStart,
				Flags: []cli.Flag{
					cli.BoolTFlag{
						Name:  "auto-launch",
						Usage: "Recursively schedules child services",
					},
					cli.BoolFlag{
						Name:  "sync, s",
						Usage: "Schedules services synchronously",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "restart",
				Usage:        "Restarts one or more services",
				Description:  "serviced service restart { SERVICEID | INSTANCEID } ...",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceRestart,
				Flags: []cli.Flag{
					cli.BoolTFlag{
						Name:  "auto-launch",
						Usage: "Recursively schedules child services",
					},
					cli.BoolFlag{
						Name:  "sync, s",
						Usage: "Schedules services synchronously",
					},
					cli.BoolFlag{
						Name:  "rebalance",
						Usage: "Stops all instances before restarting them, instead of performing a rolling restart",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "stop",
				Usage:        "Stops one or more services",
				Description:  "serviced service stop SERVICEID ...",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceStop,
				Flags: []cli.Flag{
					cli.BoolTFlag{
						Name:  "auto-launch",
						Usage: "Recursively schedules child services",
					},
					cli.BoolFlag{
						Name:  "sync, s",
						Usage: "Schedules services synchronously",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "pause",
				Usage:        "Pauses one or more services",
				Description:  "serviced service pause SERVICEID ...",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServicePause,
				Flags: []cli.Flag{
					cli.BoolTFlag{
						Name:  "auto-launch",
						Usage: "Recursively schedules child services",
					},
					cli.BoolFlag{
						Name:  "sync, s",
						Usage: "Schedules services synchronously",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "shell",
				Usage:        "Starts a service instance",
				Description:  "serviced service shell SERVICEID [COMMAND]",
				BashComplete: c.printServicesFirst,
				Before:       c.cmdServiceShell,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "saveas, s",
						Value: "",
						Usage: "saves the service instance with the given name",
					},
					cli.BoolFlag{
						Name:  "interactive, i",
						Usage: "runs the service instance as a tty",
					},
					cli.StringSliceFlag{
						Name:  "mount",
						Value: &cli.StringSlice{},
						Usage: "bind mount: HOST_PATH[,CONTAINER_PATH]",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "run",
				Usage:        "Runs a service command in a service instance",
				Description:  "serviced service run SERVICEID COMMAND [ARGS]",
				BashComplete: c.printServiceRun,
				Before:       c.cmdServiceRun,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "interactive, i",
						Usage: "runs the service instance as a tty",
					},
					cli.BoolFlag{
						Name:  "logtostderr",
						Usage: "enable/disable detailed serviced run logging (false by default)",
					},
					cli.BoolTFlag{
						Name:  "logstash",
						Usage: "enable/disable log stash (true by default)",
					},
					cli.StringFlag{
						Name:  "logstash-settle-time",
						Value: "5s",
						Usage: "time duration to wait for logstash to flush log messages before closing",
					},
					cli.StringSliceFlag{
						Name:  "mount",
						Value: &cli.StringSlice{},
						Usage: "bind mount: HOST_PATH[,CONTAINER_PATH]",
					},
					cli.StringFlag{
						Name:  "user",
						Value: "",
						Usage: "container username used to run command",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "attach",
				Usage:        "Run an arbitrary command in a running service container",
				Description:  "serviced service attach { SERVICEID | SERVICENAME | DEPLOYMENTID/...PARENTNAME.../SERVICENAME/INSTANCE } [COMMAND]",
				BashComplete: c.printServicesFirst,
				Before:       c.cmdServiceAttach,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "action",
				Usage:        "Run a predefined action in a running service container",
				Description:  "serviced service action { SERVICEID | SERVICENAME | DEPLOYMENTID/...PARENTNAME.../SERVICENAME/INSTANCE } ACTION",
				BashComplete: c.printServicesFirst,
				Before:       c.cmdServiceAction,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "logs",
				Usage:        "Output the logs of a running service container - calls docker logs",
				Description:  "serviced service logs { SERVICEID | SERVICENAME | DEPLOYMENTID/...PARENTNAME.../SERVICENAME/INSTANCE }",
				BashComplete: c.printServicesFirst,
				Before:       c.cmdServiceLogs,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "list-snapshots",
				Usage:        "Lists the snapshots for a service",
				Description:  "serviced service list-snapshots SERVICEID",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceListSnapshots,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "show-tags, t",
						Usage: "shows the tags associated with each snapshot",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "snapshot",
				Usage:        "Takes a snapshot of the service",
				Description:  "serviced service snapshot SERVICEID",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceSnapshot,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "description, d",
						Value: "",
						Usage: "a description of the snapshot",
					},
					cli.StringFlag{
						Name:  "tag, t",
						Value: "",
						Usage: "a unique tag for the snapshot",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:         "endpoints",
				Usage:        "List the endpoints defined for the service",
				Description:  "serviced service endpoints SERVICEID",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceEndpoints,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "imports, i",
						Usage: "include only imported endpoints",
					},
					cli.BoolFlag{
						Name:  "all, a",
						Usage: "include all endpoints (imports and exports)",
					},
					cli.BoolFlag{
						Name:  "verify, v",
						Usage: "verify endpoints",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			}, {
				Name:        "public-endpoints",
				Usage:       "Manage public endpoints for a service",
				Description: "serviced service public-endpoints",
				Subcommands: []cli.Command{
					{
						Name:        "list",
						Usage:       "Lists public endpoints for a service",
						Description: "serviced service public-endpoints list [SERVICEID] [ENDPOINTNAME]",
						Action:      c.cmdPublicEndpointsListAll,
						Flags: []cli.Flag{
							cli.BoolFlag{
								Name:  "ascii, a",
								Usage: "use ascii characters for service tree (env SERVICED_TREE_ASCII=1 will default to ascii)",
							},
							cli.BoolFlag{
								Name:  "ports",
								Usage: "Show port public endpoints",
							},
							cli.BoolFlag{
								Name:  "vhosts",
								Usage: "Show vhost public endpoints",
							},
							cli.StringFlag{
								Name:  "show-fields",
								Value: "Service,ServiceID,Endpoint,Type,Protocol,Name,Enabled",
								Usage: "Comma-delimited list describing which fields to display",
							},
							cli.BoolFlag{
								Name:  "verbose, v",
								Usage: "Show JSON format",
							},
							cli.BoolFlag{
								Name:  "no-prefix-match, np",
								Usage: "Make SERVICEID matches on name strict 'ends with' matches",
							},
						},
					},
					{
						Name:        "port",
						Usage:       "Manages port public endpoints for a service",
						Description: "serviced service public-endpoints port",
						Subcommands: []cli.Command{
							{
								Name:        "list",
								Usage:       "List port public endpoints for a service",
								Description: "serviced service public-endpoints port list [SERVICEID] [ENDPOINTNAME]",
								Action:      c.cmdPublicEndpointsPortList,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "ascii, a",
										Usage: "use ascii characters for service tree (env SERVICED_TREE_ASCII=1 will default to ascii)",
									},
									cli.StringFlag{
										Name:  "show-fields",
										Value: "Service,ServiceID,Endpoint,Type,Protocol,Name,Enabled",
										Usage: "Comma-delimited list describing which fields to display",
									},
									cli.BoolFlag{
										Name:  "verbose, v",
										Usage: "Show JSON format",
									},
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
							{
								Name:        "add",
								Usage:       "Add a port public endpoint to a service",
								Description: "serviced service public-endpoints port add <SERVICEID> <ENDPOINTNAME> <PORTADDR> <PROTOCOL> <ENABLED>",
								Action:      c.cmdPublicEndpointsPortAdd,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "restart, r",
										Usage: "Restart the service after adding the port if the service is currently running",
									},
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
							{
								Name:        "remove",
								ShortName:   "rm",
								Usage:       "Remove a port public endpoint from a service",
								Description: "serviced service public-endpoints port remove <SERVICEID> <ENDPOINTNAME> <PORTADDR>",
								Action:      c.cmdPublicEndpointsPortRemove,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
							{
								Name:        "enable",
								Usage:       "Enable/Disable a port public endpoint for a service",
								Description: "serviced service public-endpoints port enable <SERVICEID> <ENDPOINTNAME> <PORTADDR> true|false",
								Action:      c.cmdPublicEndpointsPortEnable,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
						},
					},
					{
						Name:        "vhost",
						Usage:       "Manages vhost public endpoints for a service",
						Description: "serviced service public-endpoints vhost",
						Subcommands: []cli.Command{
							{
								Name:        "list",
								Usage:       "List vhost public endpoints for a service",
								Description: "serviced service public-endpoints vhost list [SERVICEID] [ENDPOINTNAME]",
								Action:      c.cmdPublicEndpointsVHostList,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "ascii, a",
										Usage: "use ascii characters for service tree (env SERVICED_TREE_ASCII=1 will default to ascii)",
									},
									cli.StringFlag{
										Name:  "show-fields",
										Value: "Service,ServiceID,Endpoint,Type,Protocol,Name,Enabled",
										Usage: "Comma-delimited list describing which fields to display",
									},
									cli.BoolFlag{
										Name:  "verbose, v",
										Usage: "Show JSON format",
									},
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
							{
								Name:        "add",
								Usage:       "Add a vhost public endpoint to a service",
								Description: "serviced service public-endpoints vhost add <SERVICEID> <ENDPOINTNAME> <VHOST> <ENABLED>",
								Action:      c.cmdPublicEndpointsVHostAdd,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
							{
								Name:        "remove",
								ShortName:   "rm",
								Usage:       "Remove a vhost public endpoint from a service",
								Description: "serviced service public-endpoints vhost remove <SERVICEID> <ENDPOINTNAME> <VHOST>",
								Action:      c.cmdPublicEndpointsVHostRemove,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
							{
								Name:        "enable",
								Usage:       "Enable/Disable a vhost public endpoint for a service",
								Description: "serviced service public-endpoints vhost enable <SERVICEID> <ENDPOINTNAME> <VHOST> true|false",
								Action:      c.cmdPublicEndpointsVHostEnable,
								Flags: []cli.Flag{
									cli.BoolFlag{
										Name:  "no-prefix-match, np",
										Usage: "Make SERVICEID matches on name strict 'ends with' matches",
									},
								},
							},
						},
					},
				},
			},
			{
				Name:         "clear-emergency",
				Usage:        "Clears the 'emergency shutdown' state for a service and all child services",
				Description:  "serviced service clear-emergency { SERVICEID | SERVICENAME | DEPLOYMENTID/...PARENTNAME.../SERVICENAME }",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceClearEmergency,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			},
			{
				Name:         "remove-ip",
				Usage:        "Remove the IP assignment of a service's endpoints",
				Description:  "serviced service remove-ip <SERVICEID> <ENDPOINTNAME>",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceRemoveIP,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			},
			{
				Name:         "set-ip",
				Usage:        "Setting an IP address to a service's endpoints requiring an explicit IP address. If ip is not provided it does an automatic assignment",
				Description:  "serviced service set-ip <SERVICEID> <ENDPOINTNAME> [ADDRESS] [--port=PORT] [--proto=PROTOCOL]",
				BashComplete: c.printServicesFirst,
				Action:       c.cmdServiceSetIP,
				Flags: []cli.Flag{
					cli.IntFlag{
						Name:  "port",
						Usage: "determine the port your service will use",
					},
					cli.StringFlag{
						Name:  "proto",
						Usage: "determine the port protocol your service will use",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			},
			{
				Name:        "tune",
				Usage:       "Adjust instance count, RAM commitment, or RAM threshold for a service",
				Description: "serviced service tune SERVICEID",
				Action:      c.cmdServiceTune,
				Flags: []cli.Flag{
					cli.IntFlag{
						Name:  "instances",
						Usage: "Instance count for this service",
					},
					cli.StringFlag{
						Name:  "ramCommitment",
						Usage: "RAM Commitment for this service",
					},
					cli.StringFlag{
						Name:  "ramThreshold",
						Usage: "RAM Threshold for this service",
					},
					cli.BoolFlag{
						Name:  "no-prefix-match, np",
						Usage: "Make SERVICEID matches on name strict 'ends with' matches",
					},
				},
			},
			{
				Name:        "config",
				Usage:       "Manage config files for services",
				Description: "serviced service config",
				Subcommands: []cli.Command{
					{
						Name:        "list",
						Usage:       "List all config files for a given service, or the contents of one named file",
						Description: "serviced service config list SERVICEID [FILENAME]",
						Action:      c.cmdServiceConfigList,
						Flags: []cli.Flag{
							cli.BoolFlag{
								Name:  "no-prefix-match, np",
								Usage: "Make SERVICEID matches on name strict 'ends with' matches",
							},
						},
					},
					{
						Name:        "edit",
						Usage:       "Edit one config file for a given service",
						Description: "serviced service config edit SERVICEID FILENAME",
						Action:      c.cmdServiceConfigEdit,
						Flags: []cli.Flag{
							cli.StringFlag{
								Name:  "editor, e",
								Value: os.Getenv("EDITOR"),
								Usage: "Editor used to update the config file",
							},
							cli.BoolFlag{
								Name:  "no-prefix-match, np",
								Usage: "Make SERVICEID matches on name strict 'ends with' matches",
							},
						},
					},
				},
			},
			{
				Name:        "variable",
				Usage:       "Manage service config variables",
				Description: "serviced service variable",
				Subcommands: []cli.Command{
					{
						Name:        "list",
						Usage:       "List one or all config variables and their values for a given service",
						Description: "serviced service variable list SERVICEID",
						Action:      c.cmdServiceVariableList,
                                                Flags: []cli.Flag{
                                                        cli.BoolFlag{
                                                                Name:  "no-prefix-match, np",
                                                                Usage: "Make SERVICEID matches on name strict 'ends with' matches",
                                                        },
                                                },
					},
					{
						Name:        "get",
						Usage:       "Find the value of a config variable for a service",
						Description: "serviced service variable get SERVICEID VARIABLE",
						Action:      c.cmdServiceVariableGet,
                                                Flags: []cli.Flag{
                                                        cli.BoolFlag{
                                                                Name:  "no-prefix-match, np",
                                                                Usage: "Make SERVICEID matches on name strict 'ends with' matches",
                                                        },
                                                },
					},
					{
						Name:        "set",
						Usage:       "Add or update one variable's value for a given service",
						Description: "serviced service variable set SERVICEID VARIABLE VALUE",
						Action:      c.cmdServiceVariableSet,
                                                Flags: []cli.Flag{
                                                        cli.BoolFlag{
                                                                Name:  "no-prefix-match, np",
                                                                Usage: "Make SERVICEID matches on name strict 'ends with' matches",
                                                        },
                                                },
					},
					{
						Name:        "unset",
						Usage:       "Remove a variable from a given service",
						Description: "serviced service variable unset SERVICEID VARIABLE",
						Action:      c.cmdServiceVariableUnset,
                                                Flags: []cli.Flag{
                                                        cli.BoolFlag{
                                                                Name:  "no-prefix-match, np",
                                                                Usage: "Make SERVICEID matches on name strict 'ends with' matches",
                                                        },
                                                },
					},
				},
			},
		},
	})
}
556967
func (c *Catalog) Service(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error) {
	var tags []string
	if tag != "" {
		tags = []string{tag}
	}
	return c.service(service, tags, q, false)
}
70933
func (s *ServiceBroker) LastOperation(instanceID string) (brokerapi.LastOperation, error) {
	return brokerapi.LastOperation{}, errors.New("something is wrong. this service is not currently asynchronous")
}
1012519
func (_m *State) GetServices() []types.Service {
	ret := _m.Called()

	var r0 []types.Service
	if rf, ok := ret.Get(0).(func() []types.Service); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]types.Service)
		}
	}

	return r0
}
621950
func (s *Snapshot) Services(node string) (memdb.ResultIterator, error) {
	iter, err := s.tx.Get("services", "node", node)
	if err != nil {
		return nil, err
	}
	return iter, nil
}
425797
func (c *ServiceClient) commit(ops *operations) {
	select {
	case c.opCh <- ops:
	case <-c.shutdownCh:
	}
}
783667
func (b *Remote) Operation(ctx context.Context, op *backend.Operation) (*backend.RunningOperation, error) {
	// Get the remote workspace name.
	name := op.Workspace
	switch {
	case op.Workspace == backend.DefaultStateName:
		name = b.workspace
	case b.prefix != "" && !strings.HasPrefix(op.Workspace, b.prefix):
		name = b.prefix + op.Workspace
	}

	// Retrieve the workspace for this operation.
	w, err := b.client.Workspaces.Read(ctx, b.organization, name)
	if err != nil {
		switch err {
		case context.Canceled:
			return nil, err
		case tfe.ErrResourceNotFound:
			return nil, fmt.Errorf(
				"workspace %s not found\n\n"+
					"The configured \"remote\" backend returns '404 Not Found' errors for resources\n"+
					"that do not exist, as well as for resources that a user doesn't have access\n"+
					"to. When the resource does exists, please check the rights for the used token.",
				name,
			)
		default:
			return nil, fmt.Errorf(
				"%s\n\n"+
					"The configured \"remote\" backend encountered an unexpected error. Sometimes\n"+
					"this is caused by network connection problems, in which case you could retr\n"+
					"the command. If the issue persists please open a support ticket to get help\n"+
					"resolving the problem.",
				err,
			)
		}
	}

	// Check if we need to use the local backend to run the operation.
	if b.forceLocal || !w.Operations {
		return b.local.Operation(ctx, op)
	}

	// Set the remote workspace name.
	op.Workspace = w.Name

	// Determine the function to call for our operation
	var f func(context.Context, context.Context, *backend.Operation, *tfe.Workspace) (*tfe.Run, error)
	switch op.Type {
	case backend.OperationTypePlan:
		f = b.opPlan
	case backend.OperationTypeApply:
		f = b.opApply
	default:
		return nil, fmt.Errorf(
			"\n\nThe \"remote\" backend does not support the %q operation.", op.Type)
	}

	// Lock
	b.opLock.Lock()

	// Build our running operation
	// the runninCtx is only used to block until the operation returns.
	runningCtx, done := context.WithCancel(context.Background())
	runningOp := &backend.RunningOperation{
		Context:   runningCtx,
		PlanEmpty: true,
	}

	// stopCtx wraps the context passed in, and is used to signal a graceful Stop.
	stopCtx, stop := context.WithCancel(ctx)
	runningOp.Stop = stop

	// cancelCtx is used to cancel the operation immediately, usually
	// indicating that the process is exiting.
	cancelCtx, cancel := context.WithCancel(context.Background())
	runningOp.Cancel = cancel

	// Do it.
	go func() {
		defer done()
		defer stop()
		defer cancel()

		defer b.opLock.Unlock()

		r, opErr := f(stopCtx, cancelCtx, op, w)
		if opErr != nil && opErr != context.Canceled {
			b.ReportResult(runningOp, opErr)
			return
		}

		if r == nil && opErr == context.Canceled {
			runningOp.Result = backend.OperationFailure
			return
		}

		if r != nil {
			// Retrieve the run to get its current status.
			r, err := b.client.Runs.Read(cancelCtx, r.ID)
			if err != nil {
				b.ReportResult(runningOp, generalError("Failed to retrieve run", err))
				return
			}

			// Record if there are any changes.
			runningOp.PlanEmpty = !r.HasChanges

			if opErr == context.Canceled {
				if err := b.cancel(cancelCtx, op, r); err != nil {
					b.ReportResult(runningOp, generalError("Failed to retrieve run", err))
					return
				}
			}

			if r.Status == tfe.RunCanceled || r.Status == tfe.RunErrored {
				runningOp.Result = backend.OperationFailure
			}
		}
	}()

	// Return the running operation.
	return runningOp, nil
}