//AddServiceTemplate  adds a service template to the system. Returns the id of the template added
542027
func (f *Facade) AddServiceTemplate(ctx datastore.Context, serviceTemplate servicetemplate.ServiceTemplate, reloadLogstashConfig bool) (string, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.AddServiceTemplate"))
	alog := f.auditLogger.Message(ctx, "Adding Service Template").
		Action(audit.Add).Type(serviceTemplate.GetType())
	logger := plog.WithFields(logrus.Fields{
		"template":       serviceTemplate.Name,
		"reloadlogstash": reloadLogstashConfig,
	})
	store := f.templateStore
	hash, err := serviceTemplate.Hash()
	if err != nil {
		return "", alog.Error(err)
	}
	serviceTemplate.ID = hash
	alog = alog.Entity(&serviceTemplate)
	// Look up the template by ID
	if st, err := store.Get(ctx, hash); err != nil && !datastore.IsErrNoSuchEntity(err) {
		logger.WithError(err).WithField("hash", hash).Error("Could not look up service template by hash")
		return "", alog.Error(err)
	} else if st != nil {
		logger.Info("Not replacing existing template")
		alog.Succeeded()
		return hash, nil
	}
	// Look up the template by md5 hash
	logger = logger.WithField("hash", hash)
	if tid, err := f.getServiceTemplateByMD5Sum(ctx, hash); err != nil {
		logger.WithError(err).Error("Could not verify existance of template by md5sum")
		alog.Succeeded()
		return "", nil
	} else if tid != "" {
		logger.WithField("tid", tid).Info("Not replacing existing template")
		alog.Succeeded()
		return tid, nil
	}
	// Add the template to the database
	if err := store.Put(ctx, serviceTemplate); err != nil {
		logger.WithError(err).Error("Could not add template")
		return "", alog.Error(err)
	}

	if err := f.UpdateLogFilters(ctx, &serviceTemplate); err != nil {
		logger.WithError(err).Error("Could not add/update logfilters for template")
		return "", alog.Error(err)
	}

	logger.WithField("templateid", serviceTemplate.ID).Info("Added template")
	// This takes a while so don't block the main thread
	if reloadLogstashConfig {
		go LogstashContainerReloader(ctx, f)
	}
	return hash, alog.Error(err)
}
1322408
func (loader *TemplateLoader) Template(name string) (tmpl Template, err error) {
	runtimeLoader := loader.runtimeLoader.Load().(*templateRuntime)
	return runtimeLoader.TemplateLang(name, "")
}
1323892
func (a *Agent) AddService(service *structs.NodeService, chkTypes []*structs.CheckType, persist bool, token string, source configSource) error {
	a.stateLock.Lock()
	defer a.stateLock.Unlock()
	return a.addServiceLocked(service, chkTypes, persist, token, source)
}
115414
func (tdhf TemplateDecoratorHookFunc) DecorateTemplate(serviceName string,
	lambdaResourceName string,
	lambdaResource gocf.LambdaFunction,
	resourceMetadata map[string]interface{},
	S3Bucket string,
	S3Key string,
	buildID string,
	template *gocf.Template,
	context map[string]interface{},
	logger *logrus.Logger) error {
	return tdhf(serviceName,
		lambdaResourceName,
		lambdaResource,
		resourceMetadata,
		S3Bucket,
		S3Key,
		buildID,
		template,
		context,
		logger)
}
969116
func (s *TemplatesService) ApplyTemplate(accountID string, templateIdentifier string, domainIdentifier string) (*templateResponse, error) {
	path := versioned(fmt.Sprintf("%v/templates/%v", domainPath(accountID, domainIdentifier), templateIdentifier))
	templateResponse := &templateResponse{}

	resp, err := s.client.post(path, nil, nil)
	if err != nil {
		return nil, err
	}

	templateResponse.HttpResponse = resp
	return templateResponse, nil
}
417326
func (mg *MailgunImpl) AddTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error {
	r := newHTTPRequest(generateApiUrl(mg, templatesEndpoint) + "/" + templateName + "/versions")
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.APIKey())

	payload := newUrlEncodedPayload()
	payload.addValue("template", version.Template)

	if version.Tag != "" {
		payload.addValue("tag", string(version.Tag))
	}
	if version.Engine != "" {
		payload.addValue("engine", string(version.Engine))
	}
	if version.Comment != "" {
		payload.addValue("comment", version.Comment)
	}
	if version.Active {
		payload.addValue("active", boolToString(version.Active))
	}

	var resp templateResp
	if err := postResponseFromJSON(ctx, r, payload, &resp); err != nil {
		return err
	}
	*version = resp.Item.Version
	return nil
}
781739
func (a *api) CompileServiceTemplate(config CompileTemplateConfig) (*template.ServiceTemplate, error) {
	st, err := template.BuildFromPath(config.Dir)
	if err != nil {
		return nil, err
	}

	var mapImageNames func(*servicedefinition.ServiceDefinition)
	mapImageNames = func(svc *servicedefinition.ServiceDefinition) {
		if imageID, found := config.Map[svc.ImageID]; found {
			svc.ImageID = imageID
		}
		for i := range svc.Services {
			mapImageNames(&svc.Services[i])
		}
	}
	for idx := range st.Services {
		mapImageNames(&st.Services[idx])
	}
	return st, nil
}
735233
func (tf *TemplateFunctions) AddTo(dest template.FuncMap, secretStore fi.SecretStore) (err error) {
	dest["EtcdScheme"] = tf.EtcdScheme
	dest["SharedVPC"] = tf.SharedVPC
	dest["ToJSON"] = tf.ToJSON
	dest["UseBootstrapTokens"] = tf.modelContext.UseBootstrapTokens
	dest["UseEtcdTLS"] = tf.modelContext.UseEtcdTLS
	// Remember that we may be on a different arch from the target.  Hard-code for now.
	dest["Arch"] = func() string { return "amd64" }
	dest["replace"] = func(s, find, replace string) string {
		return strings.Replace(s, find, replace, -1)
	}
	dest["join"] = func(a []string, sep string) string {
		return strings.Join(a, sep)
	}

	dest["ClusterName"] = tf.modelContext.ClusterName
	dest["HasTag"] = tf.HasTag
	dest["WithDefaultBool"] = func(v *bool, defaultValue bool) bool {
		if v != nil {
			return *v
		}
		return defaultValue
	}

	dest["GetInstanceGroup"] = tf.GetInstanceGroup
	dest["CloudTags"] = tf.modelContext.CloudTagsForInstanceGroup
	dest["KubeDNS"] = func() *kops.KubeDNSConfig {
		return tf.cluster.Spec.KubeDNS
	}

	dest["DnsControllerArgv"] = tf.DnsControllerArgv
	dest["ExternalDnsArgv"] = tf.ExternalDnsArgv

	// TODO: Only for GCE?
	dest["EncodeGCELabel"] = gce.EncodeGCELabel
	dest["Region"] = func() string {
		return tf.region
	}

	dest["ProxyEnv"] = tf.ProxyEnv

	dest["DO_TOKEN"] = func() string {
		return os.Getenv("DIGITALOCEAN_ACCESS_TOKEN")
	}

	if featureflag.Spotinst.Enabled() {
		if creds, err := spotinst.LoadCredentials(); err == nil {
			dest["SpotinstToken"] = func() string { return creds.Token }
			dest["SpotinstAccount"] = func() string { return creds.Account }
		}
	}

	if tf.cluster.Spec.Networking != nil && tf.cluster.Spec.Networking.Flannel != nil {
		flannelBackendType := tf.cluster.Spec.Networking.Flannel.Backend
		if flannelBackendType == "" {
			glog.Warningf("Defaulting flannel backend to udp (not a recommended configuration)")
			flannelBackendType = "udp"
		}
		dest["FlannelBackendType"] = func() string { return flannelBackendType }
	}

	if tf.cluster.Spec.Networking != nil && tf.cluster.Spec.Networking.Weave != nil {
		weavesecretString := ""
		weavesecret, _ := secretStore.Secret("weavepassword")
		if weavesecret != nil {
			weavesecretString, err = weavesecret.AsString()
			if err != nil {
				return err
			}
			glog.V(4).Info("Weave secret function successfully registered")
		}

		dest["WeaveSecret"] = func() string { return weavesecretString }
	}

	return nil
}
841929
func (s *TemplateService) UpdateTemplate(p *UpdateTemplateParams) (*UpdateTemplateResponse, error) {
	resp, err := s.cs.newRequest("updateTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

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

	return &r, nil
}
1088132
func (a *api) GetServiceTemplate(id string) (*template.ServiceTemplate, error) {
	client, err := a.connectMaster()
	if err != nil {
		return nil, err
	}

	templateMap, err := client.GetServiceTemplates()
	if err != nil {
		return nil, err
	}

	if _, ok := templateMap[id]; !ok {
		return nil, fmt.Errorf("unable to find template by id: %s", id)
	}
	t := templateMap[id]
	t.ID = id

	return &t, nil
}
1029734
func (proxier *Proxier) addServiceOnPort(service proxy.ServicePortName, protocol v1.Protocol, proxyPort int, timeout time.Duration) (*ServiceInfo, error) {
	proxier.mu.Lock()
	defer proxier.mu.Unlock()
	return proxier.addServiceOnPortInternal(service, protocol, proxyPort, timeout)
}
1144730
func (s *Service) NewTemplate(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
	}

	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
	}

	ids := idgen.UUID{}
	tid, err := ids.Generate()
	if err != nil {
		msg := fmt.Sprintf("Error creating template ID for dashboard %d: %v", id, err)
		Error(w, http.StatusInternalServerError, msg, s.Logger)
		return
	}
	template.ID = chronograf.TemplateID(tid)

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

	res := newTemplateResponse(dash.ID, template)
	encodeJSON(w, http.StatusOK, res, s.Logger)
}
1164655
func (c *ServicedCli) initTemplate() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "template",
		Usage:       "Administers templates",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:         "list",
				Usage:        "Lists all templates",
				Description:  "serviced template list [TEMPLATEID]",
				BashComplete: c.printTemplatesFirst,
				Action:       c.cmdTemplateList,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "verbose, v",
						Usage: "Show JSON format",
					},
					cli.StringFlag{
						Name:  "show-fields",
						Value: "TemplateID,Name,Description",
						Usage: "Comma-delimited list describing which fields to display",
					},
				},
			}, {
				Name:        "add",
				Usage:       "Add a new template",
				Description: "serviced template add FILE",
				Action:      c.cmdTemplateAdd,
			}, {
				Name:         "remove",
				ShortName:    "rm",
				Usage:        "Remove an existing template",
				Description:  "serviced template remove TEMPLATEID ...",
				BashComplete: c.printTemplatesAll,
				Action:       c.cmdTemplateRemove,
			}, {
				Name:         "deploy",
				Usage:        "Deploys a template's services to a pool",
				Description:  "serviced template deploy TEMPLATEID POOLID DEPLOYMENTID",
				BashComplete: c.printTemplateDeploy,
				Action:       c.cmdTemplateDeploy,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "manual-assign-ips",
						Usage: "Manually assign IP addresses",
					},
				},
			}, {
				Name:        "compile",
				Usage:       "Convert a directory of service definitions into a template",
				Description: "serviced template compile PATH",
				Action:      c.cmdTemplateCompile,
				Flags: []cli.Flag{
					cli.GenericFlag{
						Name:  "map",
						Value: &api.ImageMap{},
						Usage: "Map a given image name to another (e.g. -map zenoss/zenoss5x:latest,quay.io/zenoss-core:alpha2)",
					},
				},
			},
		},
	})
}
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
}
1093560
func (c *Client) GetServiceTemplates() (map[string]servicetemplate.ServiceTemplate, error) {
	response := map[string]servicetemplate.ServiceTemplate{}
	if err := c.call("GetServiceTemplates", empty, &response); err != nil {
		return nil, err
	}
	return response, nil
}
1177243
func (f *Facade) getServiceTemplateByMD5Sum(ctx datastore.Context, md5Sum string) (string, error) {
	store := f.templateStore
	templates, err := store.GetServiceTemplates(ctx)
	if err != nil {
		plog.WithError(err).Error("Could not get service templates")
		return "", err
	}
	for _, t := range templates {
		logger := plog.WithFields(logrus.Fields{
			"templateid": t.ID,
			"template":   t.Name,
		})
		hash, err := t.Hash()
		if err != nil {
			logger.WithError(err).Error("Could not get md5sum for template")
			return "", err
		}
		if md5Sum == hash {
			return t.ID, nil
		}
	}
	return "", nil
}
1291060
func (context *BaseServiceContext) InitServiceContext(service Service) {
	context.InitBaseContext()
	context.service = service
	context.method = nil
	context.isMissingMethod = false
	context.byRef = false
}