// Use templating to substitute in some info about the service.  Important because
// we won't know the actual Port that the container will bind to, for example.
5715
func (m *Monitor) templateCheckArgs(check *Check, svc *service.Service) string {
	funcMap := template.FuncMap{
		"tcp":       func(p int64) int64 { return svc.PortForServicePort(p, "tcp") },
		"udp":       func(p int64) int64 { return svc.PortForServicePort(p, "udp") },
		"host":      func() string { return m.DefaultCheckHost },
		"container": func() string { return svc.Hostname },
	}

	t, err := template.New("check").Funcs(funcMap).Parse(check.Args)
	if err != nil {
		log.Errorf("Unable to parse check Args: '%s'", check.Args)
		return check.Args
	}

	var output bytes.Buffer
	t.Execute(&output, svc)

	return output.String()
}
84006
func (service *Service) EvaluateHostnameTemplate(gs GetService, fc FindChildService, instanceID int) (err error) {
	err, result := service.evaluateTemplate(gs, fc, instanceID, service.Hostname)
	if err == nil {
		service.Hostname = result
	}
	return
}
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
}
142426
func (_m *FacadeInterface) GetServiceTemplates(ctx datastore.Context) (map[string]servicetemplate.ServiceTemplate, error) {
	ret := _m.Called(ctx)

	var r0 map[string]servicetemplate.ServiceTemplate
	if rf, ok := ret.Get(0).(func(datastore.Context) map[string]servicetemplate.ServiceTemplate); ok {
		r0 = rf(ctx)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(map[string]servicetemplate.ServiceTemplate)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(datastore.Context) error); ok {
		r1 = rf(ctx)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
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)
}
1036813
func (a *api) GetServiceTemplates() ([]template.ServiceTemplate, error) {
	client, err := a.connectMaster()
	if err != nil {
		return nil, err
	}

	templateMap, err := client.GetServiceTemplates()
	if err != nil {
			return nil, err
	}
	templates := make([]template.ServiceTemplate, len(templateMap))
	i := 0
	for id, t := range templateMap {
		t.ID = id
		templates[i] = t
		i++
	}

	return templates, nil
}
131249
func (r *Registry) Template(name string) (Template, bool) {
	for _, t := range r.Templates {
		if t.Node.Name == name {
			return t, true
		}
	}
	return Template{}, false
}
331107
func (dh *Client) Container(containerId string) (containerInfo *docker.ContainerInfo, e error) {
	containerInfo = &docker.ContainerInfo{}
	e = dh.getJSON(dh.Address+"/containers/"+containerId+"/json", containerInfo)
	return containerInfo, e
}
1085192
func Template(runOnStartup bool) POption {
	return func(p *POptions) {
		p.template = true
		p.runOnStartup = runOnStartup
	}
}
441428
func (s *TemplateService) RegisterTemplate(p *RegisterTemplateParams) (*RegisterTemplateResponse, error) {
	resp, err := s.cs.newRequest("registerTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

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

	return &r, nil
}
502289
func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	// iterate rules, to find first one that matches the request path
	for _, rule := range t.Rules {
		if !httpserver.Path(r.URL.Path).Matches(rule.Path) {
			continue
		}

		fpath := r.URL.Path

		// get a buffer from the pool and make a response recorder
		buf := t.BufPool.Get().(*bytes.Buffer)
		buf.Reset()
		defer t.BufPool.Put(buf)

		// only buffer the response when we want to execute a template
		shouldBuf := func(status int, header http.Header) bool {
			// see if this request matches a template extension
			reqExt := path.Ext(fpath)
			for _, ext := range rule.Extensions {
				if reqExt == "" {
					// request has no extension, so check response Content-Type
					ct := mime.TypeByExtension(ext)
					if ct != "" && strings.Contains(header.Get("Content-Type"), ct) {
						return true
					}
				} else if reqExt == ext {
					return true
				}
			}
			return false
		}

		// prepare a buffer to hold the response, if applicable
		rb := httpserver.NewResponseBuffer(buf, w, shouldBuf)

		// pass request up the chain to let another middleware provide us the template
		code, err := t.Next.ServeHTTP(rb, r)
		if !rb.Buffered() || code >= 300 || err != nil {
			return code, err
		}

		// create a new template
		templateName := filepath.Base(fpath)
		tpl := template.New(templateName)

		// set delimiters
		if rule.Delims != [2]string{} {
			tpl.Delims(rule.Delims[0], rule.Delims[1])
		}

		// add custom functions
		tpl.Funcs(httpserver.TemplateFuncs)

		// parse the template
		parsedTpl, err := tpl.Parse(rb.Buffer.String())
		if err != nil {
			return http.StatusInternalServerError, err
		}

		// create execution context for the template template
		ctx := httpserver.NewContextWithHeader(w.Header())
		ctx.Root = t.FileSys
		ctx.Req = r
		ctx.URL = r.URL

		// execute the template
		buf.Reset()
		err = parsedTpl.Execute(buf, ctx)
		if err != nil {
			return http.StatusInternalServerError, err
		}

		// copy the buffered header into the real ResponseWriter
		rb.CopyHeader()

		// set the actual content length now that the template was executed
		w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))

		// delete the headers related to cache
		w.Header().Del("ETag")
		w.Header().Del("Last-Modified")

		// get the modification time in preparation for http.ServeContent
		modTime, _ := time.Parse(http.TimeFormat, w.Header().Get("Last-Modified"))

		// at last, write the rendered template to the response; make sure to use
		// use the proper status code, since ServeContent hard-codes 2xx codes...
		http.ServeContent(rb.StatusCodeWriter(w), r, templateName, modTime, bytes.NewReader(buf.Bytes()))

		return 0, nil
	}

	return t.Next.ServeHTTP(w, r)
}
429331
func Compile(query *structs.PreparedQuery) (*CompiledTemplate, error) {
	// Make sure it's a type we understand.
	if query.Template.Type != structs.QueryTemplateTypeNamePrefixMatch {
		return nil, fmt.Errorf("Bad Template.Type '%s'", query.Template.Type)
	}

	// Start compile.
	ct := &CompiledTemplate{
		trees:           make(map[string]ast.Node),
		removeEmptyTags: query.Template.RemoveEmptyTags,
	}

	// Make a copy of the query to use as the basis for rendering later.
	dup, err := copystructure.Copy(query)
	if err != nil {
		return nil, err
	}
	var ok bool
	ct.query, ok = dup.(*structs.PreparedQuery)
	if !ok {
		return nil, fmt.Errorf("Failed to copy query")
	}

	// Walk over all the string fields in the Service sub-structure and
	// parse them as HIL.
	parse := func(path string, v reflect.Value) error {
		tree, err := hil.Parse(v.String())
		if err != nil {
			return fmt.Errorf("Bad format '%s' in Service%s: %s", v.String(), path, err)
		}

		ct.trees[path] = tree
		return nil
	}
	if err := walk(&ct.query.Service, parse); err != nil {
		return nil, err
	}

	// If they supplied a regexp then compile it.
	if ct.query.Template.Regexp != "" {
		var err error
		ct.re, err = regexp.Compile(ct.query.Template.Regexp)
		if err != nil {
			return nil, fmt.Errorf("Bad Regexp: %s", err)
		}
	}

	// Finally do a test render with the supplied name prefix. This will
	// help catch errors before run time, and this is the most minimal
	// prefix it will be expected to run with. The results might not make
	// sense and create a valid service to lookup, but it should render
	// without any errors.
	if _, err = ct.Render(ct.query.Name, structs.QuerySource{}); err != nil {
		return nil, err
	}

	return ct, nil
}
995636
func (c *Client) PrepareTemplate(p *PrepareTemplateParameter) (*Template, error) {
	obj, err := c.Request("prepareTemplate", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Template), err
}
558985
func (c *Client) RemoveServiceTemplate(serviceTemplateID string) error {
	if err := c.call("RemoveServiceTemplate", serviceTemplateID, nil); err != nil {
		return err
	}
	return nil

}
1253625
func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) {
	var err error
	result := pattern.ReplaceAllStringFunc(template, func(substring string) string {
		matches := pattern.FindStringSubmatch(substring)
		groups := matchGroups(matches, pattern)
		if escaped := groups["escaped"]; escaped != "" {
			return escaped
		}

		substitution := groups["named"]
		if substitution == "" {
			substitution = groups["braced"]
		}

		if substitution == "" {
			err = &InvalidTemplateError{Template: template}
			return ""
		}

		for _, f := range subsFuncs {
			var (
				value   string
				applied bool
			)
			value, applied, err = f(substitution, mapping)
			if err != nil {
				return ""
			}
			if !applied {
				continue
			}
			return value
		}

		value, _ := mapping(substitution)
		return value
	})

	return result, err
}
555527
func (p *Project) Containers(ctx context.Context, filter Filter, services ...string) ([]string, error) {
	containers := []string{}
	var lock sync.Mutex

	err := p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
		wrapper.Do(nil, events.NoEvent, events.NoEvent, func(service Service) error {
			serviceContainers, innerErr := service.Containers(ctx)
			if innerErr != nil {
				return innerErr
			}

			for _, container := range serviceContainers {
				running := container.IsRunning(ctx)
				switch filter.State {
				case Running:
					if !running {
						continue
					}
				case Stopped:
					if running {
						continue
					}
				case AnyState:
					// Don't do a thing
				default:
					// Invalid state filter
					return fmt.Errorf("Invalid container filter: %s", filter.State)
				}
				containerID := container.ID()
				lock.Lock()
				containers = append(containers, containerID)
				lock.Unlock()
			}
			return nil
		})
	}), nil)
	if err != nil {
		return nil, err
	}
	return containers, nil
}
1145443
func Substitute(template string, mapping Mapping) (string, error) {
	return SubstituteWith(template, mapping, defaultPattern, DefaultSubstituteFuncs...)
}