// serviced template remove TEMPLATEID ...
331921
func (c *ServicedCli) cmdTemplateRemove(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "remove")
		return
	}

	for _, id := range args {
		if err := c.driver.RemoveServiceTemplate(id); err != nil {
			fmt.Fprintf(os.Stderr, "%s: %s\n", id, err)
		} else {
			fmt.Println(id)
		}
	}
}
351179
func (c *ServicedCli) printServicesAll(ctx *cli.Context) {
	args := ctx.Args()
	svcs := c.services()

	// If arg is a service don't add to the list
	for _, s := range svcs {
		for _, a := range args {
			if s == a {
				goto next
			}
		}
		fmt.Println(s)
	next:
	}
	return
}
849547
func (s *Server) AddServiceTemplate(serviceTemplate servicetemplate.ServiceTemplate, response *string) error  {
	reloadLogstashConfig := true
	templateID, err := s.f.AddServiceTemplate(s.context(), serviceTemplate, reloadLogstashConfig)
	if err != nil {
		return err
	}
	*response = templateID
	return nil
}
1002523
func (_m *ClientInterface) RemoveServiceTemplate(serviceTemplateID string) error {
	ret := _m.Called(serviceTemplateID)

	var r0 error
	if rf, ok := ret.Get(0).(func(string) error); ok {
		r0 = rf(serviceTemplateID)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
511652
func ServiceGoCode(svc *gen.ServiceMetadata, chars []*gen.CharacteristicMetadata) ([]byte, error) {
	var err error
	var buf bytes.Buffer

	data := ServiceDecl(svc, chars)

	t := template.New("Test Template")

	t, err = t.Parse(ServiceStructTemplate)
	t.Execute(&buf, data)

	return buf.Bytes(), err
}
101124
func Convert_v1_Template_To_template_Template(in *v1.Template, out *template.Template, s conversion.Scope) error {
	return autoConvert_v1_Template_To_template_Template(in, out, s)
}
1202396
func (s *TemplateService) PrepareTemplate(p *PrepareTemplateParams) (*PrepareTemplateResponse, error) {
	resp, err := s.cs.newRequest("prepareTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r PrepareTemplateResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
1169522
func (s *Service) ReplaceTemplate(w http.ResponseWriter, r *http.Request) {
	id, err := paramID("id", r)
	if err != nil {
		Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
		return
	}

	ctx := r.Context()
	dash, err := s.Store.Dashboards(ctx).Get(ctx, chronograf.DashboardID(id))
	if err != nil {
		notFound(w, id, s.Logger)
		return
	}

	tid := httprouter.GetParamFromContext(ctx, "tid")
	pos := -1
	for i, t := range dash.Templates {
		if t.ID == chronograf.TemplateID(tid) {
			pos = i
			break
		}
	}
	if pos == -1 {
		notFound(w, id, s.Logger)
		return
	}

	var template chronograf.Template
	if err := json.NewDecoder(r.Body).Decode(&template); err != nil {
		invalidJSON(w, s.Logger)
		return
	}

	if err := ValidTemplateRequest(&template); err != nil {
		invalidData(w, err, s.Logger)
		return
	}
	template.ID = chronograf.TemplateID(tid)

	dash.Templates[pos] = template
	if err := s.Store.Dashboards(ctx).Update(ctx, dash); err != nil {
		msg := fmt.Sprintf("Error updating template %s in dashboard %d: %v", tid, id, err)
		Error(w, http.StatusInternalServerError, msg, s.Logger)
		return
	}

	res := newTemplateResponse(chronograf.DashboardID(id), template)
	encodeJSON(w, http.StatusOK, res, s.Logger)
}
1276383
func (s *Store) RemoveTemplate(ctx context.Context, name string) error {
	p := s.templatefile(name)

	if err := s.storage.Delete(ctx, p); err != nil {
		return errors.Wrapf(err, "failed to remote template")
	}

	if err := s.rcs.Add(ctx, p); err != nil {
		if errors.Cause(err) == store.ErrGitNotInit {
			return nil
		}
		return errors.Wrapf(err, "failed to add '%s' to git", p)
	}

	if !ctxutil.IsGitCommit(ctx) {
		return nil
	}

	return s.gitCommitAndPush(ctx, name)
}
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
}
1311792
func (c *Command) HelpTemplate() string {
	if c.helpTemplate != "" {
		return c.helpTemplate
	}

	if c.HasParent() {
		return c.parent.HelpTemplate()
	}
	return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}

{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
}
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)
		}
	}
}
1278344
func (c *ServicedCli) cmdTemplateCompile(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "compile")
		return
	}

	cfg := api.CompileTemplateConfig{
		Dir: args[0],
		Map: *ctx.Generic("map").(*api.ImageMap),
	}

	if template, err := c.driver.CompileServiceTemplate(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if template == nil {
		fmt.Fprintln(os.Stderr, "received nil template")
	} else {
		cmd := fmt.Sprintf("cd %s && git rev-parse HEAD", args[0])
		commit, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			commit = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git config --get remote.origin.url", args[0])
		repo, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			repo = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git rev-parse --abbrev-ref HEAD", args[0])
		branch, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			branch = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git describe --always", args[0])
		tag, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			tag = []byte("unknown")
		}
		templateVersion := map[string]string{
			"repo":   strings.Trim(string(repo), "\n"),
			"branch": strings.Trim(string(branch), "\n"),
			"tag":    strings.Trim(string(tag), "\n"),
			"commit": strings.Trim(string(commit), "\n"),
		}
		mTemplate := metaTemplate{*template, servicedversion.GetVersion(), templateVersion}
		jsonTemplate, err := json.MarshalIndent(mTemplate, " ", "  ")
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal template: %s\n", err)
		} else {
			fmt.Println(string(jsonTemplate))
		}
	}
}
628486
func (c *ServicedCli) initHost() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "host",
		Usage:       "Administers host data",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:         "list",
				Usage:        "Lists all hosts",
				Description:  "serviced host list [SERVICEID]",
				BashComplete: c.printHostsFirst,
				Action:       c.cmdHostList,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "verbose, v",
						Usage: "Show JSON format",
					},
					cli.StringFlag{
						Name:  "show-fields",
						Value: "ID,Auth,Pool,Name,Addr,RPCPort,Cores,RAM,Cur/Max/Avg,Network,Release",
						Usage: "Comma-delimited list describing which fields to display",
					},
				},
			}, {
				Name:         "add",
				Usage:        "Adds a new host",
				Description:  "serviced host add HOST:PORT RESOURCE_POOL",
				BashComplete: c.printHostAdd,
				Action:       c.cmdHostAdd,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "memory",
						Value: "",
						Usage: "Memory to allocate on this host, e.g. 20G, 50%",
					},
					cli.StringFlag{
						Name:  "nat-address",
						Value: "",
						Usage: "The HOST:PORT of the NAT for this delegate",
					},
					cli.StringFlag{
						Name:  "key-file, k",
						Value: "",
						Usage: "Name of the output host key file",
					},
					cli.BoolFlag{
						Name:  "register, r",
						Usage: "Register delegate keys on the host via ssh",
					},
				},
			}, {
				Name:         "add-private",
				ShortName:    "addme",
				Usage:        "Adds a new host and register via common key",
				Description:  "serviced host add HOST:PORT RESOURCE_POOL",
				BashComplete: c.printHostAddPrivate,
				Action:       c.cmdHostAddPrivate,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "memory",
						Value: "",
						Usage: "Memory to allocate on this host, e.g. 20G, 50%",
					},
					cli.StringFlag{
						Name:  "nat-address",
						Value: "",
						Usage: "The HOST:PORT of the NAT for this delegate",
					},
				},
			}, {
				Name:         "remove",
				ShortName:    "rm",
				Usage:        "Removes an existing host",
				Description:  "serviced host remove HOSTID ...",
				BashComplete: c.printHostsAll,
				Action:       c.cmdHostRemove,
			}, {
				Name:        "register",
				Usage:       "Set the authentication keys to use for this host. When KEYSFILE is -, read from stdin.",
				Description: "serviced host register KEYSFILE",
				Action:      c.cmdHostRegister,
			}, {
				Name:         "set-memory",
				Usage:        "Set the memory allocation for a specific host",
				Description:  "serviced host set-memory HOSTID ALLOCATION",
				BashComplete: c.printHostsAll,
				Action:       c.cmdHostSetMemory,
			},
		},
	})
}
1096758
func (f *Facade) RemoveServiceTemplate(ctx datastore.Context, id string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.RemoveServiceTemplate"))
	alog := f.auditLogger.Message(ctx, "Removing Service Template").
		Action(audit.Remove).ID(id).Type(servicetemplate.GetType())
	_, err := f.templateStore.Get(ctx, id)
	logger := plog.WithFields(logrus.Fields{
		"templateid": id,
	})
	if err != nil {
		logger.WithError(err).Error("Unable to find template")
		return alog.Error(fmt.Errorf("Unable to find template: %s", id))
	}

	// CC-3673 - LogFilters are NOT removed to avoid breaking any deployed services that might be using those filters

	logger.Info("Removed template")
	if err := f.templateStore.Delete(ctx, id); err != nil {
		return alog.Error(err)
	}

	go LogstashContainerReloader(ctx, f)
	alog.Succeeded()
	return nil
}
411921
func (c *ServicedCli) printHostAddPrivate(ctx *cli.Context) {
	var output []string

	args := ctx.Args()
	switch len(args) {
	case 1:
		output = c.pools()
	}
	fmt.Println(strings.Join(output, "\n"))
}
1256202
func (c *ServicedCli) printTemplateDeploy(ctx *cli.Context) {
	var output []string

	switch len(ctx.Args()) {
	case 0:
		output = c.templates()
	case 1:
		output = c.pools()
	}

	for _, o := range output {
		fmt.Println(o)
	}
}