// preparedQueryCreate makes a new prepared query.
498184
func (s *HTTPServer) preparedQueryCreate(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.PreparedQueryRequest{
		Op: structs.PreparedQueryCreate,
	}
	s.parseDC(req, &args.Datacenter)
	s.parseToken(req, &args.Token)
	if err := decodeBody(req, &args.Query, nil); err != nil {
		resp.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(resp, "Request decode failed: %v", err)
		return nil, nil
	}

	var reply string
	if err := s.agent.RPC("PreparedQuery.Apply", &args, &reply); err != nil {
		return nil, err
	}
	return preparedQueryCreateResponse{reply}, nil
}
531190
func (s *GroupDetail) SetCreateDate(v time.Time) *GroupDetail {
	s.CreateDate = &v
	return s
}
17438
func (s *LoginProfile) SetCreateDate(v time.Time) *LoginProfile {
	s.CreateDate = &v
	return s
}
202561
func (s *ServiceSpecificCredentialMetadata) SetCreateDate(v time.Time) *ServiceSpecificCredentialMetadata {
	s.CreateDate = &v
	return s
}
988203
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
	return c.prepare(context.Background(), query)
}
780450
func (s *Store) PreparedQuerySet(idx uint64, query *structs.PreparedQuery) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	if err := s.preparedQuerySetTxn(tx, idx, query); err != nil {
		return err
	}

	tx.Commit()
	return nil
}
403598
func (s *HTTPServer) preparedQuerySpecificOptions(resp http.ResponseWriter, req *http.Request) interface{} {
	path := req.URL.Path
	switch {
	case strings.HasSuffix(path, "/execute"):
		resp.Header().Add("Allow", strings.Join([]string{"OPTIONS", "GET"}, ","))
		return resp

	case strings.HasSuffix(path, "/explain"):
		resp.Header().Add("Allow", strings.Join([]string{"OPTIONS", "GET"}, ","))
		return resp

	default:
		resp.Header().Add("Allow", strings.Join([]string{"OPTIONS", "GET", "PUT", "DELETE"}, ","))
		return resp
	}
}
154307
func (namespaceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	// on create, status is active
	namespace := obj.(*api.Namespace)
	namespace.Status = api.NamespaceStatus{
		Phase: api.NamespaceActive,
	}
	// on create, we require the kubernetes value
	// we cannot use this in defaults conversion because we let it get removed over life of object
	hasKubeFinalizer := false
	for i := range namespace.Spec.Finalizers {
		if namespace.Spec.Finalizers[i] == api.FinalizerKubernetes {
			hasKubeFinalizer = true
			break
		}
	}
	if !hasKubeFinalizer {
		if len(namespace.Spec.Finalizers) == 0 {
			namespace.Spec.Finalizers = []api.FinalizerName{api.FinalizerKubernetes}
		} else {
			namespace.Spec.Finalizers = append(namespace.Spec.Finalizers, api.FinalizerKubernetes)
		}
	}
}
285542
func (jobStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	job := obj.(*batch.Job)
	job.Status = batch.JobStatus{}

	if !utilfeature.DefaultFeatureGate.Enabled(features.TTLAfterFinished) {
		job.Spec.TTLSecondsAfterFinished = nil
	}

	pod.DropDisabledTemplateFields(&job.Spec.Template, nil)
}
458167
func (d *DNSServer) preparedQueryLookup(cfg *dnsConfig, network, datacenter, query string, remoteAddr net.Addr, req, resp *dns.Msg, maxRecursionLevel int) {
	// Execute the prepared query.
	args := structs.PreparedQueryExecuteRequest{
		Datacenter:    datacenter,
		QueryIDOrName: query,
		QueryOptions: structs.QueryOptions{
			Token:      d.agent.tokens.UserToken(),
			AllowStale: cfg.AllowStale,
			MaxAge:     cfg.CacheMaxAge,
		},

		// Always pass the local agent through. In the DNS interface, there
		// is no provision for passing additional query parameters, so we
		// send the local agent's data through to allow distance sorting
		// relative to ourself on the server side.
		Agent: structs.QuerySource{
			Datacenter: d.agent.config.Datacenter,
			Segment:    d.agent.config.SegmentName,
			Node:       d.agent.config.NodeName,
		},
	}

	subnet := ednsSubnetForRequest(req)

	if subnet != nil {
		args.Source.Ip = subnet.Address.String()
	} else {
		switch v := remoteAddr.(type) {
		case *net.UDPAddr:
			args.Source.Ip = v.IP.String()
		case *net.TCPAddr:
			args.Source.Ip = v.IP.String()
		case *net.IPAddr:
			args.Source.Ip = v.IP.String()
		}
	}

	out, err := d.lookupPreparedQuery(cfg, args)

	// If they give a bogus query name, treat that as a name error,
	// not a full on server error. We have to use a string compare
	// here since the RPC layer loses the type information.
	if err != nil && err.Error() == consul.ErrQueryNotFound.Error() {
		d.addSOA(cfg, resp)
		resp.SetRcode(req, dns.RcodeNameError)
		return
	} else if err != nil {
		resp.SetRcode(req, dns.RcodeServerFailure)
		return
	}

	// TODO (slackpad) - What's a safe limit we can set here? It seems like
	// with dup filtering done at this level we need to get everything to
	// match the previous behavior. We can optimize by pushing more filtering
	// into the query execution, but for now I think we need to get the full
	// response. We could also choose a large arbitrary number that will
	// likely work in practice, like 10*maxUDPAnswerLimit which should help
	// reduce bandwidth if there are thousands of nodes available.

	// Determine the TTL. The parse should never fail since we vet it when
	// the query is created, but we check anyway. If the query didn't
	// specify a TTL then we will try to use the agent's service-specific
	// TTL configs.
	var ttl time.Duration
	if out.DNS.TTL != "" {
		var err error
		ttl, err = time.ParseDuration(out.DNS.TTL)
		if err != nil {
			d.logger.Printf("[WARN] dns: Failed to parse TTL '%s' for prepared query '%s', ignoring", out.DNS.TTL, query)
		}
	} else {
		ttl, _ = cfg.GetTTLForService(out.Service)
	}

	// If we have no nodes, return not found!
	if len(out.Nodes) == 0 {
		d.addSOA(cfg, resp)
		resp.SetRcode(req, dns.RcodeNameError)
		return
	}

	// Add various responses depending on the request.
	qType := req.Question[0].Qtype
	if qType == dns.TypeSRV {
		d.serviceSRVRecords(cfg, out.Datacenter, out.Nodes, req, resp, ttl, maxRecursionLevel)
	} else {
		d.serviceNodeRecords(cfg, out.Datacenter, out.Nodes, req, resp, ttl, maxRecursionLevel)
	}

	d.trimDNSResponse(cfg, network, req, resp)

	// If the answer is empty and the response isn't truncated, return not found
	if len(resp.Answer) == 0 && !resp.Truncated {
		d.addSOA(cfg, resp)
		return
	}
}
102586
func (s *ServiceSummary) SetCreateDate(v time.Time) *ServiceSummary {
	s.CreateDate = &v
	return s
}
936855
func (persistentvolumeStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	pv := obj.(*api.PersistentVolume)
	pv.Status = api.PersistentVolumeStatus{}

	pvutil.DropDisabledFields(&pv.Spec, nil)
}
644280
func (m *Sqlbridge) parseCreate() (*SqlCreate, error) {

	req := NewSqlCreate()
	m.Next() // Consume CREATE token
	req.Raw = m.l.RawInput()

	if m.Cur().T == lex.TokenOr {
		m.Next() // Consume OR
		if m.Next().T != lex.TokenReplace {
			return nil, m.ErrMsg("Expected CREATE OR REPLACE")
		}
		req.OrReplace = true
	}
	// CREATE {DATABASE|SCHEMA|TABLE|VIEW|SOURCE|CONTINUOUSVIEW} <identity>
	switch m.Cur().T {
	case lex.TokenTable, lex.TokenSource, lex.TokenDatabase, lex.TokenSchema:
		req.Tok = m.Next()
	case lex.TokenView, lex.TokenContinuousView:
		req.Tok = m.Next()
		if m.Cur().T != lex.TokenIdentity {
			return nil, m.ErrMsg("Expected CREATE [OR REPLACE] {VIEW|CONTINIOUSVIEW} <identity> AS <select_stmt>")
		}
		req.Identity = m.Next().V

		// Grab remainder which will be SELECT (we have already lexed AS)
		selSQL, _ := m.l.Remainder()

		if m.Next().T != lex.TokenAs {
			return nil, m.ErrMsg("Expected CREATE [OR REPLACE] {VIEW|CONTINIOUSVIEW} <identity> AS <select_stmt>")
		}
		if m.Cur().T != lex.TokenSelect {
			return nil, m.ErrMsg("Expected CREATE [OR REPLACE] {VIEW|CONTINIOUSVIEW} <identity> AS <select_stmt>")
		}

		sel, err := ParseSqlSelect(selSQL)
		if err != nil {
			return nil, err
		}
		req.Select = sel
		return req, nil
	default:
		return nil, m.ErrMsg("Expected view, table, source, schema, database, continuousview for CREATE got")
	}

	// [IF NOT EXISTS]
	if m.Cur().T == lex.TokenIf {
		m.Next() // Consume IF
		if m.Next().T != lex.TokenNegate {
			return nil, m.ErrMsg("Expected CREATE {TABLE|SCHEMA|DATABASE} IF NOT EXISTS <identity>")
		}
		if m.Next().T != lex.TokenExists {
			return nil, m.ErrMsg("Expected CREATE {TABLE|SCHEMA|DATABASE} IF NOT EXISTS <identity>")
		}
		req.IfNotExists = true
	}

	switch m.Cur().T {
	case lex.TokenTable, lex.TokenIdentity:
		req.Identity = m.Next().V
	default:
		return nil, m.ErrMsg("Expected identity after CREATE (TABLE|VIEW|SOURCE|SCHEMA|DATABASE) ")
	}

	switch req.Tok.T {
	case lex.TokenTable:
		discardComments(m)
		if m.Cur().T != lex.TokenLeftParenthesis {
			return nil, m.ErrMsg("Expected (cols) ")
		}
		m.Next() // consume paren

		// list of columns comma separated
		cols, err := m.parseCreateCols()
		if err != nil {
			u.Error(err)
			return nil, err
		}
		req.Cols = cols

		// ENGINE
		discardComments(m)
		if strings.ToLower(m.Cur().V) != "engine" {
			return nil, m.ErrMsg("Expected (cols) ENGINE ... ")
		}
		engine, err := ParseWith(m.SqlTokenPager)
		if err != nil {
			return nil, err
		}
		req.Engine = engine
	case lex.TokenSource:
		// just with
	case lex.TokenSchema:
		// just with for now
	default:
		return nil, fmt.Errorf("not implemented %v", req.Tok.V)
	}

	// WITH
	discardComments(m)
	with, err := ParseWith(m.SqlTokenPager)
	if err != nil {
		return nil, err
	}
	req.With = with

	return req, nil
}
95395
func (s *Store) preparedQuerySetTxn(tx *memdb.Txn, idx uint64, query *structs.PreparedQuery) error {
	// Check that the ID is set.
	if query.ID == "" {
		return ErrMissingQueryID
	}

	// Check for an existing query.
	wrapped, err := tx.First("prepared-queries", "id", query.ID)
	if err != nil {
		return fmt.Errorf("failed prepared query lookup: %s", err)
	}
	existing := toPreparedQuery(wrapped)

	// Set the indexes.
	if existing != nil {
		query.CreateIndex = existing.CreateIndex
		query.ModifyIndex = idx
	} else {
		query.CreateIndex = idx
		query.ModifyIndex = idx
	}

	// Verify that the query name doesn't already exist, or that we are
	// updating the same instance that has this name. If this is a template
	// and the name is empty then we make sure there's not an empty template
	// already registered.
	if query.Name != "" {
		wrapped, err := tx.First("prepared-queries", "name", query.Name)
		if err != nil {
			return fmt.Errorf("failed prepared query lookup: %s", err)
		}
		other := toPreparedQuery(wrapped)
		if other != nil && (existing == nil || existing.ID != other.ID) {
			return fmt.Errorf("name '%s' aliases an existing query name", query.Name)
		}
	} else if prepared_query.IsTemplate(query) {
		wrapped, err := tx.First("prepared-queries", "template", query.Name)
		if err != nil {
			return fmt.Errorf("failed prepared query lookup: %s", err)
		}
		other := toPreparedQuery(wrapped)
		if other != nil && (existing == nil || existing.ID != other.ID) {
			return fmt.Errorf("a query template with an empty name already exists")
		}
	}

	// Verify that the name doesn't alias any existing ID. We allow queries
	// to be looked up by ID *or* name so we don't want anyone to try to
	// register a query with a name equal to some other query's ID in an
	// attempt to hijack it. We also look up by ID *then* name in order to
	// prevent this, but it seems prudent to prevent these types of rogue
	// queries from ever making it into the state store. Note that we have
	// to see if the name looks like a UUID before checking since the UUID
	// index will complain if we look up something that's not formatted
	// like one.
	if isUUID(query.Name) {
		wrapped, err := tx.First("prepared-queries", "id", query.Name)
		if err != nil {
			return fmt.Errorf("failed prepared query lookup: %s", err)
		}
		if wrapped != nil {
			return fmt.Errorf("name '%s' aliases an existing query ID", query.Name)
		}
	}

	// Verify that the session exists.
	if query.Session != "" {
		sess, err := tx.First("sessions", "id", query.Session)
		if err != nil {
			return fmt.Errorf("failed session lookup: %s", err)
		}
		if sess == nil {
			return fmt.Errorf("invalid session %#v", query.Session)
		}
	}

	// We do not verify the service here, nor the token, if any. These are
	// checked at execute time and not doing integrity checking on them
	// helps avoid bootstrapping chicken and egg problems.

	// If this is a template, compile it, otherwise leave the compiled
	// template field nil.
	var ct *prepared_query.CompiledTemplate
	if prepared_query.IsTemplate(query) {
		var err error
		ct, err = prepared_query.Compile(query)
		if err != nil {
			return fmt.Errorf("failed compiling template: %s", err)
		}
	}

	// Insert the wrapped query.
	if err := tx.Insert("prepared-queries", &queryWrapper{query, ct}); err != nil {
		return fmt.Errorf("failed inserting prepared query: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"prepared-queries", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}
1149725
func (resourcequotaStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	resourcequota := obj.(*api.ResourceQuota)
	resourcequota.Status = api.ResourceQuotaStatus{}
	resourcequotautil.DropDisabledFields(&resourcequota.Spec, nil)
}
728273
func preparedQueriesTableSchema() *memdb.TableSchema {
	return &memdb.TableSchema{
		Name: "prepared-queries",
		Indexes: map[string]*memdb.IndexSchema{
			"id": &memdb.IndexSchema{
				Name:         "id",
				AllowMissing: false,
				Unique:       true,
				Indexer: &memdb.UUIDFieldIndex{
					Field: "ID",
				},
			},
			"name": &memdb.IndexSchema{
				Name:         "name",
				AllowMissing: true,
				Unique:       true,
				Indexer: &memdb.StringFieldIndex{
					Field:     "Name",
					Lowercase: true,
				},
			},
			"template": &memdb.IndexSchema{
				Name:         "template",
				AllowMissing: true,
				Unique:       true,
				Indexer:      &PreparedQueryIndex{},
			},
			"session": &memdb.IndexSchema{
				Name:         "session",
				AllowMissing: true,
				Unique:       false,
				Indexer: &memdb.UUIDFieldIndex{
					Field: "Session",
				},
			},
		},
	}
}
602396
func (podStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	pod := obj.(*api.Pod)
	pod.Status = api.PodStatus{
		Phase:    api.PodPending,
		QOSClass: qos.GetPodQOS(pod),
	}

	podutil.DropDisabledPodFields(pod, nil)
}