// Creates a template of a virtual machine. The virtual machine must be in a STOPPED state. A template created from this command is automatically designated as a private template visible to the account that created it.
324868
func (s *TemplateService) CreateTemplate(p *CreateTemplateParams) (*CreateTemplateResponse, error) {
	resp, err := s.cs.newRequest("createTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

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

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

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

	return &r, nil
}
777005
func (f *Facade) DeployTemplate(ctx datastore.Context, poolID string, templateID string, deploymentID string) ([]string, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.DeployTemplate"))
	alog := f.auditLogger.Message(ctx, "Deploying Service Template").
		Action(audit.Deploy).ID(templateID).Type(servicetemplate.GetType()).
		WithFields(logrus.Fields{"poolid": poolID, "deploymentid": deploymentID})
	logger := plog.WithFields(logrus.Fields{
		"poolid":       poolID,
		"templateid":   templateID,
		"deploymentid": deploymentID,
	})
	// add an entry for reporting status
	deployment, err := f.deployments.NewPendingDeployment(deploymentID, templateID, poolID)
	if err != nil {
		return nil, alog.Error(err)
	}
	defer f.deployments.DeletePendingDeployment(deploymentID)

	deployment.UpdateStatus("deploy_loading_template|" + templateID)
	template, err := f.templateStore.Get(ctx, templateID)
	if err != nil {
		logger.WithError(err).Error("Unable to load template")
		return nil, alog.Error(err)
	}

	//check that deployment id does not already exist
	logger = logger.WithField("template", template.Name)
	if svcs, err := f.serviceStore.GetServicesByDeployment(ctx, deploymentID); err != nil {
		logger.WithError(err).Error("Unable to validate deploymentID while deploying")
		return nil, alog.Error(err)
	} else if len(svcs) > 0 {
		return nil, alog.Error(fmt.Errorf("deployment ID %s is already in use", deploymentID))
	}

	//now that we know the template name, set it in the status
	deployment.SetTemplateName(template.Name)

	deployment.UpdateStatus("deploy_loading_resource_pool|" + poolID)
	pool, err := f.GetResourcePool(ctx, poolID)
	if err != nil {
		logger.WithError(err).Error("Unable to load resource pool")
		return nil, alog.Error(err)
	}
	if pool == nil {
		return nil, alog.Error(fmt.Errorf("poolid %s not found", poolID))
	}

	var statusUpdater = func(status string) {
		deployment.UpdateStatus(status)
	}

	tenantIDs := make([]string, len(template.Services))
	for i, sd := range template.Services {
		logger.WithField("servicename", sd.Name).Info("Deploying service")
		tenantID, err := f.deployService(ctx, "", "", deploymentID, poolID, false, sd, statusUpdater)
		if err != nil {
			logger.WithError(err).Error("Could not deploy application")
			return nil, alog.Error(err)
		}
		if err := f.dfs.Create(tenantID); err != nil {
			logger.WithError(err).WithField("tenantid", tenantID).Error("Could not initialize volume for tenant")
			return nil, alog.Error(err)
		}
		tenantIDs[i] = tenantID
	}

	// Update the logstash filters for the deployed services
	if err := f.ReloadLogstashConfig(ctx); err != nil {
		logger.WithError(err).Error("Could not reload logstash configs after deploying")
	}

	alog.Succeeded()
	return tenantIDs, nil
}
161785
func makeTemplateTheOldWay() *cf.Template {
	t := cf.NewTemplate()
	t.Description = "example production infrastructure"
	t.Parameters["DnsName"] = &cf.Parameter{
		Description: "The top level DNS name for the infrastructure",
		Type:        "String",
		Default:     "preview.example.io",
	}

	t.AddResource("ServerLoadBalancer", cf.ElasticLoadBalancingLoadBalancer{
		ConnectionDrainingPolicy: &cf.ElasticLoadBalancingConnectionDrainingPolicy{
			Enabled: cf.Bool(true),
			Timeout: cf.Integer(30),
		},
		CrossZone: cf.Bool(true),
		HealthCheck: &cf.ElasticLoadBalancingHealthCheck{
			HealthyThreshold:   cf.String("2"),
			Interval:           cf.String("60"),
			Target:             cf.String("HTTP:80/"),
			Timeout:            cf.String("5"),
			UnhealthyThreshold: cf.String("2"),
		},
		Listeners: &cf.ElasticLoadBalancingListenerList{
			cf.ElasticLoadBalancingListener{
				InstancePort:     cf.String("8000"),
				InstanceProtocol: cf.String("TCP"),
				LoadBalancerPort: cf.String("443"),
				Protocol:         cf.String("SSL"),
				SSLCertificateId: cf.Join("",
					*cf.String("arn:aws:iam::"),
					*cf.Ref("AWS::AccountID").String(),
					*cf.String(":server-certificate/"),
					*cf.Ref("DnsName").String()).String(),
			},
		},
		Policies: &cf.ElasticLoadBalancingPolicyList{
			cf.ElasticLoadBalancingPolicy{
				PolicyName: cf.String("EnableProxyProtocol"),
				PolicyType: cf.String("ProxyProtocolPolicyType"),
				Attributes: []map[string]interface{}{
					map[string]interface{}{
						"Name":  "ProxyProtocol",
						"Value": "true",
					},
				},
				InstancePorts: []int{8000},
			},
		},
		Subnets: cf.StringList(
			*cf.Ref("VpcSubnetA").String(),
			*cf.Ref("VpcSubnetB").String(),
			*cf.Ref("VpcSubnetC").String(),
		),
		SecurityGroups: cf.StringList(*cf.Ref("LoadBalancerSecurityGroup").String()),
	})

	return t
}
1344590
func (g *Generator) ProcessTemplate(tmplName, tmpl string, data interface{}) error {
	vars := []string{}
	for varName, varValue := range g.vars {
		vars = append(vars, fmt.Sprintf("{{ $%s := %q }}", varName, varValue))
	}

	if len(vars) > 0 {
		tmpl = strings.Join(vars, "\n") + "\n" + tmpl
	}

	t, err := template.New(tmplName).Funcs(g.templateFuncs).Parse(tmpl)
	if err != nil {
		return fmt.Errorf("failed to parse template: %v\n%s", err, tmpl)
	}

	if err := t.Execute(g.body, data); err != nil {
		return fmt.Errorf("failed to execute template: %v", err)
	}

	return nil
}
1116940
func (p *Plugin) templateToProcess(tmp *process.Template) (*Process, error) {
	if tmp.Name == "" {
		return nil, errors.Errorf("cannot create process from template, missing name")
	}
	if tmp.Cmd == "" {
		return nil, errors.Errorf("cannot create process from template, missing command")
	}

	pOptions := &POptions{}
	if tmp.POptions != nil {
		pOptions.args = tmp.POptions.Args
		pOptions.outWriter = func(isSet bool) io.Writer {
			if isSet {
				return os.Stdout
			}
			return nil
		}(tmp.POptions.OutWriter)
		pOptions.errWriter = func(isSet bool) io.Writer {
			if isSet {
				return os.Stderr
			}
			return nil
		}(tmp.POptions.ErrWriter)
		pOptions.detach = tmp.POptions.Detach
		pOptions.restart = tmp.POptions.Restart
		pOptions.runOnStartup = tmp.POptions.RunOnStartup
		pOptions.notifyChan = func(notify bool) chan status.ProcessStatus {
			if notify {
				return make(chan status.ProcessStatus)
			}
			return nil
		}(tmp.POptions.Notify)
		pOptions.autoTerm = tmp.POptions.AutoTerminate
	}

	return &Process{
		log:     p.Log,
		name:    tmp.Name,
		cmd:     tmp.Cmd,
		options: pOptions,
		sh:      &status.Reader{Log: p.Log},
		status: &status.File{
			State: status.Initial,
		},
		cancelChan: make(chan struct{}),
	}, nil
}
691561
func createPipelineTemplateAction(client *gocd.Client, c *cli.Context) (r interface{}, resp *gocd.APIResponse, err error) {
	if c.String("template-name") == "" {
		return nil, nil, NewFlagError("template-name")
	}
	if len(c.StringSlice("stage")) < 1 {
		return nil, nil, errors.New("At least 1 '--stage' must be set")
	}

	stages := []*gocd.Stage{}
	for _, stage := range c.StringSlice("stage") {
		st := gocd.Stage{}
		json.Unmarshal([]byte(stage), &st)

		if err := st.Validate(); err != nil {
			return nil, nil, err
		}
		stages = append(stages, &st)
	}

	return client.PipelineTemplates.Create(context.Background(), c.String("template-name"), stages)
}
1341404
func (c *ServicedCli) templates() (data []string) {
	templates, err := c.driver.GetServiceTemplates()
	if err != nil || templates == nil || len(templates) == 0 {
		return
	}

	data = make([]string, len(templates))
	for i, t := range templates {
		data[i] = t.ID
	}

	return
}
1146756
func (c CloudstackClient) CreateTemplate(options *CreateTemplate) (CreateTemplateResponse, error) {
	var resp CreateTemplateResponse
	params := url.Values{}
	params.Set("displaytext", options.Displaytext)
	params.Set("name", options.Name)
	params.Set("ostypeid", options.Ostypeid)
	if options.Volumeid != "" {
		params.Set("volumeid", options.Volumeid)
	}
	if options.Snapshotid != "" {
		params.Set("snapshotid", options.Snapshotid)
	}

	if options.Isdynamicallyscalable {
		params.Set("isdynamicallyscalable", "true")
	}
	if options.Isextractable {
		params.Set("isextractable", "true")
	}
	if options.Isfeatured {
		params.Set("isfeatured", "true")
	}
	if options.Ispublic {
		params.Set("ispublic", "true")
	}
	if options.Passwordenabled {
		params.Set("passwordenabled", "true")
	}

	response, err := NewRequest(c, "createTemplate", params)
	if err != nil {
		return resp, err
	}

	resp = response.(CreateTemplateResponse)
	return resp, err
}
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))
		}
	}
}
793066
func (r *Reader) WriteTemplate(template *process.Template, permission os.FileMode) error {
	if template == nil {
		return errors.Errorf("provided process template is nil")
	}

	templateData, err := json.Marshal(template)
	if err != nil {
		return errors.Errorf("failed to marshal template %s: %v", template.Name, err)
	}

	templateFile := template.Name + JSONExt
	filePath := filepath.Join(r.path, templateFile)
	err = ioutil.WriteFile(filePath, templateData, permission)
	if err != nil {
		return errors.Errorf("failed to write template %s to file: %v", templateFile, err)
	}

	r.log.Debugf("process template file %s written", templateFile)

	return nil
}
337801
func (s *AutoScaleService) NewCreateAutoScaleVmProfileParams(serviceofferingid string, templateid string, zoneid string) *CreateAutoScaleVmProfileParams {
	p := &CreateAutoScaleVmProfileParams{}
	p.p = make(map[string]interface{})
	p.p["serviceofferingid"] = serviceofferingid
	p.p["templateid"] = templateid
	p.p["zoneid"] = zoneid
	return p
}
252567
func (r *Router) Template(t *template.Template) {
	r.Lock()
	defer r.Unlock()
	r.views = template.Must(t.Clone())
}
434648
func (p *partial) template() (*Template, error) {
	if p.tpl == nil {
		var err error

		p.tpl, err = Parse(p.source)
		if err != nil {
			return nil, err
		}
	}

	return p.tpl, nil
}
23614
func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
	tmpl, err := template.ParseFiles(srcPath)
	if err != nil {
		return NewBuildIfError(err, "Failed to parse template "+srcPath)
	}

	f, err := os.Create(destPath)
	if err != nil {
		return NewBuildIfError(err, "Failed to create  ", "path", destPath)
	}

	err = tmpl.Execute(f, data)
	if err != nil {
		return NewBuildIfError(err, "Failed to Render template "+srcPath)
	}

	err = f.Close()
	if err != nil {
		return NewBuildIfError(err, "Failed to close file stream "+destPath)
	}
	return
}
1322408
func (loader *TemplateLoader) Template(name string) (tmpl Template, err error) {
	runtimeLoader := loader.runtimeLoader.Load().(*templateRuntime)
	return runtimeLoader.TemplateLang(name, "")
}
881497
func NewTemplate() *Template {
	return &Template{
		AWSTemplateFormatVersion: "2010-09-09",
		Mappings:                 map[string]*Mapping{},
		Parameters:               map[string]*Parameter{},
		Resources:                map[string]*Resource{},
		Outputs:                  map[string]*Output{},
		Conditions:               map[string]interface{}{},
	}
}
789639
func prepareTemplates(templatesPath string) *templates.Bundle {
	return &templates.Bundle{
		Loader:          templates.FileSystemLoader(templatesPath),
		DebugMode:       info.IsDevAppServer,
		DefaultTemplate: "base",
		FuncMap: template.FuncMap{
			// Count returns sequential integers in range [0, n] (inclusive).
			"Count": func(n int) []int {
				out := make([]int, n+1)
				for i := range out {
					out[i] = i
				}
				return out
			},
			// Pair combines two args into one map with keys "First" and "Second", to
			// pass pairs to templates (that in golang can accept only one argument).
			"Pair": func(a1, a2 interface{}) map[string]interface{} {
				return map[string]interface{}{
					"First":  a1,
					"Second": a2,
				}
			},
		},
		DefaultArgs: func(c context.Context, e *templates.Extra) (templates.Args, error) {
			loginURL, err := auth.LoginURL(c, e.Request.URL.RequestURI())
			if err != nil {
				return nil, err
			}
			logoutURL, err := auth.LogoutURL(c, e.Request.URL.RequestURI())
			if err != nil {
				return nil, err
			}
			token, err := xsrf.Token(c)
			if err != nil {
				return nil, err
			}
			return templates.Args{
				"AppVersion":  strings.Split(info.VersionID(c), ".")[0],
				"IsAnonymous": auth.CurrentIdentity(c) == "anonymous:anonymous",
				"User":        auth.CurrentUser(c),
				"LoginURL":    loginURL,
				"LogoutURL":   logoutURL,
				"XsrfToken":   token,
				"HandlerDuration": func() time.Duration {
					return clock.Now(c).Sub(startTime(c))
				},
			}, nil
		},
	}
}