// ensureTemplateInstance ensures the existence of a TemplateInstance object
// (this causes the template instance controller to instantiate the template in
// the namespace).
162542
func (b *Broker) ensureTemplateInstance(u user.Info, namespace string, brokerTemplateInstance *templateapiv1.BrokerTemplateInstance, instanceID string, template *templateapiv1.Template, secret *kapiv1.Secret, didWork *bool) (*templateapiv1.TemplateInstance, *api.Response) {
	klog.V(4).Infof("Template service broker: ensureTemplateInstance")

	extra := map[string]templateapiv1.ExtraValue{}
	for k, v := range u.GetExtra() {
		extra[k] = templateapiv1.ExtraValue(v)
	}

	blockOwnerDeletion := true
	templateInstance := &templateapiv1.TemplateInstance{
		ObjectMeta: metav1.ObjectMeta{
			Name: instanceID,
			Annotations: map[string]string{
				api.OpenServiceBrokerInstanceExternalID: instanceID,
			},
			OwnerReferences: []metav1.OwnerReference{
				{
					APIVersion:         templateapiv1.SchemeGroupVersion.String(),
					Kind:               "BrokerTemplateInstance",
					Name:               brokerTemplateInstance.Name,
					UID:                brokerTemplateInstance.UID,
					BlockOwnerDeletion: &blockOwnerDeletion,
				},
			},
		},
		Spec: templateapiv1.TemplateInstanceSpec{
			Template: *template,
			Secret:   &kapiv1.LocalObjectReference{Name: secret.Name},
			Requester: &templateapiv1.TemplateInstanceRequester{
				Username: u.GetName(),
				UID:      u.GetUID(),
				Groups:   u.GetGroups(),
				Extra:    extra,
			},
		},
	}

	if err := util.Authorize(b.kc.AuthorizationV1().SubjectAccessReviews(), u, &authorizationv1.ResourceAttributes{
		Namespace: namespace,
		Verb:      "create",
		Group:     templateapiv1.GroupName,
		Resource:  "templateinstances",
		Name:      instanceID,
	}); err != nil {
		return nil, api.Forbidden(err)
	}

	createdTemplateInstance, err := b.templateclient.TemplateInstances(namespace).Create(templateInstance)
	if err == nil {
		*didWork = true
		return createdTemplateInstance, nil
	}

	if kerrors.IsAlreadyExists(err) {
		if err := util.Authorize(b.kc.AuthorizationV1().SubjectAccessReviews(), u, &authorizationv1.ResourceAttributes{
			Namespace: namespace,
			Verb:      "get",
			Group:     templateapiv1.GroupName,
			Resource:  "templateinstances",
			Name:      templateInstance.Name,
		}); err != nil {
			return nil, api.Forbidden(err)
		}

		existingTemplateInstance, err := b.templateclient.TemplateInstances(namespace).Get(templateInstance.Name, metav1.GetOptions{})
		if err == nil && reflect.DeepEqual(templateInstance.Spec, existingTemplateInstance.Spec) {
			return existingTemplateInstance, nil
		}

		return nil, api.NewResponse(http.StatusConflict, api.ProvisionResponse{}, nil)
	}

	if kerrors.IsForbidden(err) {
		return nil, api.Forbidden(err)
	}
	return nil, api.InternalServerError(err)
}
308818
func (b *Broker) ensureBrokerTemplateInstanceUIDs(u user.Info, namespace string, brokerTemplateInstance *templateapiv1.BrokerTemplateInstance, secret *kapiv1.Secret, templateInstance *templateapiv1.TemplateInstance, didWork *bool) (*templateapiv1.BrokerTemplateInstance, *api.Response) {
	klog.V(4).Infof("Template service broker: ensureBrokerTemplateInstanceUIDs")

	// end users are not expected to have access to BrokerTemplateInstance
	// objects; SAR on the TemplateInstance instead.
	if err := util.Authorize(b.kc.AuthorizationV1().SubjectAccessReviews(), u, &authorizationv1.ResourceAttributes{
		Namespace: namespace,
		Verb:      "update",
		Group:     templateapiv1.GroupName,
		Resource:  "templateinstances",
		Name:      brokerTemplateInstance.Spec.TemplateInstance.Name,
	}); err != nil {
		return nil, api.Forbidden(err)
	}

	err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
		brokerTemplateInstance.Spec.Secret.UID = secret.UID
		brokerTemplateInstance.Spec.TemplateInstance.UID = templateInstance.UID

		newBrokerTemplateInstance, err := b.templateclient.BrokerTemplateInstances().Update(brokerTemplateInstance)
		switch {
		case err == nil:
			brokerTemplateInstance = newBrokerTemplateInstance

		case kerrors.IsConflict(err):
			var getErr error
			brokerTemplateInstance, getErr = b.templateclient.BrokerTemplateInstances().Get(brokerTemplateInstance.Name, metav1.GetOptions{})
			if getErr != nil {
				err = getErr
			}
		}
		return err
	})
	switch {
	case err == nil:
		*didWork = true
		return brokerTemplateInstance, nil
	case kerrors.IsConflict(err):
		return nil, api.NewResponse(http.StatusUnprocessableEntity, &api.ConcurrencyError, nil)
	}
	return nil, api.InternalServerError(err)
}
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
}
579746
func ValidateTemplateInstance(templateInstance *templateapi.TemplateInstance) (allErrs field.ErrorList) {
	allErrs = validation.ValidateObjectMeta(&templateInstance.ObjectMeta, true, ValidateTemplateInstanceName, field.NewPath("metadata"))

	// Allow the nested template name and namespace to be empty.  If not empty,
	// the fields should pass validation.
	templateCopy := templateInstance.Spec.Template.DeepCopy()
	if templateCopy.Name == "" {
		templateCopy.Name = "dummy"
	}
	if templateCopy.Namespace == "" {
		templateCopy.Namespace = "dummy"
	}
	for _, err := range ValidateTemplate(templateCopy) {
		err.Field = "spec.template." + err.Field
		allErrs = append(allErrs, err)
	}
	if templateInstance.Spec.Secret != nil {
		if templateInstance.Spec.Secret.Name != "" {
			for _, msg := range validation.ValidateSecretName(templateInstance.Spec.Secret.Name, false) {
				allErrs = append(allErrs, field.Invalid(field.NewPath("spec.secret.name"), templateInstance.Spec.Secret.Name, msg))
			}
		} else {
			allErrs = append(allErrs, field.Required(field.NewPath("spec.secret.name"), ""))
		}
	}
	if templateInstance.Spec.Requester == nil {
		allErrs = append(allErrs, field.Required(field.NewPath("spec.requester"), ""))
	} else if templateInstance.Spec.Requester.Username == "" {
		allErrs = append(allErrs, field.Required(field.NewPath("spec.requester.username"), ""))
	}
	return
}
304573
func (r DynamicRender) Instance(name string, data interface{}) render.Render {
	builder, ok := r[name]
	if !ok {
		panic(fmt.Sprintf("Dynamic template with name %s not found", name))
	}
	return render.HTML{
		Template: builder.buildTemplate(),
		Data:     data,
	}
}
630685
func ValidTemplateRequest(template *chronograf.Template) error {
	switch template.Type {
	default:
		return fmt.Errorf("unknown template type %s", template.Type)
	case "constant", "csv", "fieldKeys", "tagKeys", "tagValues", "measurements", "databases", "map", "influxql", "text":
	}

	for _, v := range template.Values {
		switch v.Type {
		default:
			return fmt.Errorf("unknown template variable type %s", v.Type)
		case "csv", "map", "fieldKey", "tagKey", "tagValue", "measurement", "database", "constant", "influxql":
		}

		if template.Type == "map" && v.Key == "" {
			return fmt.Errorf("templates of type 'map' require a 'key'")
		}
	}

	if template.Type == "influxql" && template.Query == nil {
		return fmt.Errorf("no query set for template of type 'influxql'")
	}

	return nil
}
847809
func (b *Broker) ensureSecret(u user.Info, namespace string, brokerTemplateInstance *templateapiv1.BrokerTemplateInstance, instanceID string, preq *api.ProvisionRequest, template *templateapiv1.Template, didWork *bool) (*kapiv1.Secret, *api.Response) {
	klog.V(4).Infof("Template service broker: ensureSecret")

	blockOwnerDeletion := true
	secret := &kapiv1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name: instanceID,
			OwnerReferences: []metav1.OwnerReference{
				{
					APIVersion:         templateapiv1.SchemeGroupVersion.String(),
					Kind:               "BrokerTemplateInstance",
					Name:               brokerTemplateInstance.Name,
					UID:                brokerTemplateInstance.UID,
					BlockOwnerDeletion: &blockOwnerDeletion,
				},
			},
		},
		Data: map[string][]byte{},
	}

	// allow empty string values for non-generated parameters.
	// empty string values will be ignored for generated parameter
	for k, v := range preq.Parameters {
		for _, param := range template.Parameters {
			if param.Name == k && ((len(v) == 0 && param.Generate == "") || len(v) != 0) {
				secret.Data[k] = []byte(v)
			}
		}
	}
	if err := util.Authorize(b.kc.AuthorizationV1().SubjectAccessReviews(), u, &authorizationv1.ResourceAttributes{
		Namespace: namespace,
		Verb:      "create",
		Group:     kapiv1.GroupName,
		Resource:  "secrets",
		Name:      secret.Name,
	}); err != nil {
		return nil, api.Forbidden(err)
	}

	createdSec, err := b.kc.CoreV1().Secrets(namespace).Create(secret)
	if err == nil {
		*didWork = true
		return createdSec, nil
	}

	if kerrors.IsAlreadyExists(err) {
		if err := util.Authorize(b.kc.AuthorizationV1().SubjectAccessReviews(), u, &authorizationv1.ResourceAttributes{
			Namespace: namespace,
			Verb:      "get",
			Group:     kapiv1.GroupName,
			Resource:  "secrets",
			Name:      secret.Name,
		}); err != nil {
			return nil, api.Forbidden(err)
		}

		existingSec, err := b.kc.CoreV1().Secrets(namespace).Get(secret.Name, metav1.GetOptions{})
		if err == nil && reflect.DeepEqual(secret.Data, existingSec.Data) {
			return existingSec, nil
		}

		return nil, api.NewResponse(http.StatusConflict, api.ProvisionResponse{}, nil)
	}

	if kerrors.IsForbidden(err) {
		return nil, api.Forbidden(err)
	}
	return nil, api.InternalServerError(err)
}
297219
func (a *ArgType) ExecuteTemplate(tt TemplateType, name string, sub string, obj interface{}) error {
	var err error

	// setup generated
	if a.Generated == nil {
		a.Generated = []TBuf{}
	}

	// create store
	v := TBuf{
		TemplateType: tt,
		Name:         name,
		Subname:      sub,
		Buf:          new(bytes.Buffer),
	}

	// build template name
	loaderType := ""
	if tt != XOTemplate {
		if a.LoaderType == "oci8" || a.LoaderType == "ora" {
			// force oracle for oci8 since the oracle driver doesn't recognize
			// 'oracle' as valid protocol
			loaderType = "oracle."
		} else {
			loaderType = a.LoaderType + "."
		}
	}
	templateName := fmt.Sprintf("%s%s.go.tpl", loaderType, tt)

	// execute template
	err = a.TemplateSet().Execute(v.Buf, templateName, obj)
	if err != nil {
		return err
	}

	a.Generated = append(a.Generated, v)
	return nil
}
626853
func (c *FakeTemplateInstances) Get(name string, options v1.GetOptions) (result *template.TemplateInstance, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(templateinstancesResource, c.ns, name), &template.TemplateInstance{})

	if obj == nil {
		return nil, err
	}
	return obj.(*template.TemplateInstance), err
}
36659
func Convert_template_TemplateInstanceRequester_To_v1_TemplateInstanceRequester(in *template.TemplateInstanceRequester, out *v1.TemplateInstanceRequester, s conversion.Scope) error {
	return autoConvert_template_TemplateInstanceRequester_To_v1_TemplateInstanceRequester(in, out, s)
}
56122
func serviceFromTemplate(template *templateapiv1.Template) *api.Service {
	metadata := make(map[string]interface{})
	for srcname, dstname := range annotationMap {
		if value, ok := template.Annotations[srcname]; ok {
			metadata[dstname] = value
		}
	}

	properties := map[string]*jsschema.Schema{}
	paramOrdering := []string{}
	required := []string{}
	for _, param := range template.Parameters {
		properties[param.Name] = &jsschema.Schema{
			Title:       param.DisplayName,
			Description: param.Description,
			Default:     param.Value,
			Type:        []jsschema.PrimitiveType{jsschema.StringType},
		}
		if param.Required && param.Generate == "" {
			required = append(required, param.Name)
		}
		paramOrdering = append(paramOrdering, param.Name)
	}

	bindable := strings.ToLower(template.Annotations[templateapi.BindableAnnotation]) != "false"

	plan := api.Plan{
		ID:          string(template.UID), // TODO: this should be a unique value
		Name:        "default",
		Description: "Default plan",
		Free:        true,
		Bindable:    bindable,
		Schemas: api.Schema{
			ServiceInstance: api.ServiceInstances{
				Create: map[string]*jsschema.Schema{
					"parameters": {
						SchemaRef:  jsschema.SchemaURL,
						Type:       []jsschema.PrimitiveType{jsschema.ObjectType},
						Properties: properties,
						Required:   required,
					},
				},
			},
			ServiceBinding: api.ServiceBindings{
				Create: map[string]*jsschema.Schema{
					"parameters": {
						SchemaRef:  jsschema.SchemaURL,
						Type:       []jsschema.PrimitiveType{jsschema.ObjectType},
						Properties: map[string]*jsschema.Schema{},
						Required:   []string{},
					},
				},
			},
		},
	}

	// This metadata ensures the template parameters are displayed in the
	// service catalog in the same order as they are defined in the template.
	plan.Metadata = make(map[string]interface{})
	plan.Metadata["schemas"] = api.ParameterSchemas{
		ServiceInstance: api.ParameterSchema{
			Create: api.OpenShiftMetadata{
				OpenShiftFormDefinition: paramOrdering,
			},
		},
	}

	description := template.Annotations["description"]
	if description == "" {
		description = noDescriptionProvided
	}

	return &api.Service{
		Name:        template.Name,
		ID:          string(template.UID),
		Description: description,
		Tags:        strings.Split(template.Annotations["tags"], ","),
		Bindable:    bindable,
		Metadata:    metadata,
		Plans:       []api.Plan{plan},
	}
}
573963
func (widgetSetting QorWidgetSetting) GetTemplate() string {
	if widget := GetWidget(widgetSetting.GetSerializableArgumentKind()); widget != nil {
		for _, value := range widget.Templates {
			if value == widgetSetting.Template {
				return value
			}
		}

		// return first value of defined widget templates
		for _, value := range widget.Templates {
			return value
		}
	}
	return ""
}
884822
func (s *UpdateCustomVerificationEmailTemplateInput) SetTemplateSubject(v string) *UpdateCustomVerificationEmailTemplateInput {
	s.TemplateSubject = &v
	return s
}
101880
func newTemplates(c *TemplateClient, namespace string) *templates {
	return &templates{
		client: c.RESTClient(),
		ns:     namespace,
	}
}
892677
func handleTemplates(fn TemplateData) httprouter.Handle {
	return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
		// Check if template exists
		var name = p.ByName("page") + ".html"
		if templates.Lookup(name) == nil {
			rw.WriteHeader(http.StatusNotFound)
			return
		}

		// Get data
		var d interface{}
		var err error
		if fn != nil {
			if d, err = fn(name, r, p); err != nil {
				astilog.Errorf("%s while retrieving data for template %s", err, name)
				rw.WriteHeader(http.StatusInternalServerError)
				return
			}
		}

		// Execute template
		if err = templates.ExecuteTemplate(rw, name, d); err != nil {
			astilog.Errorf("%s while handling template %s", err, name)
			rw.WriteHeader(http.StatusInternalServerError)
			return
		}
	}
}
1167951
func Convert_v1_TemplateInstanceCondition_To_template_TemplateInstanceCondition(in *v1.TemplateInstanceCondition, out *template.TemplateInstanceCondition, s conversion.Scope) error {
	return autoConvert_v1_TemplateInstanceCondition_To_template_TemplateInstanceCondition(in, out, s)
}
1237355
func ParseCSVToTemplatedInstances(filepath string, hasHeaders bool, template *DenseInstances) (instances *DenseInstances, err error) {
	// Open the file
	f, err := os.Open(filepath)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return ParseCSVToTemplatedInstancesFromReader(f, hasHeaders, template)
}