// HTTP GET /:version/events?query
//
// Query fields:
//	'from'  : time filter in RFC3339 format
//	'to'    : time filter in RFC3339 format
//  ...     : other fields are passed directly to the audit backend
541743
func (s *APIServer) searchEvents(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) {
	var err error
	to := time.Now().In(time.UTC)
	from := to.AddDate(0, -1, 0) // one month ago
	query := r.URL.Query()
	// parse 'to' and 'from' params:
	fromStr := query.Get("from")
	if fromStr != "" {
		from, err = time.Parse(time.RFC3339, fromStr)
		if err != nil {
			return nil, trace.BadParameter("from")
		}
	}
	toStr := query.Get("to")
	if toStr != "" {
		to, err = time.Parse(time.RFC3339, toStr)
		if err != nil {
			return nil, trace.BadParameter("to")
		}
	}
	var limit int
	limitStr := query.Get("limit")
	if limitStr != "" {
		limit, err = strconv.Atoi(limitStr)
		if err != nil {
			return nil, trace.BadParameter("failed to parse limit: %q", limit)
		}
	}
	// remove 'to', 'from' and 'limit' fields, passing the rest of the query unmodified
	// to whatever pluggable search is implemented by the backend
	query.Del("to")
	query.Del("from")
	query.Del("limit")
	eventsList, err := auth.SearchEvents(from, to, query.Encode(), limit)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return eventsList, nil
}
77418
func (c *Client) ListAppUsageEventsByQuery(query url.Values) ([]AppUsageEvent, error) {
	var appUsageEvents []AppUsageEvent
	requestURL := fmt.Sprintf("/v2/app_usage_events?%s", query.Encode())
	for {
		var appUsageEventsResponse AppUsageEventsResponse
		r := c.NewRequest("GET", requestURL)
		resp, err := c.DoRequest(r)
		if err != nil {
			return nil, errors.Wrap(err, "error requesting events")
		}
		defer resp.Body.Close()
		if err := json.NewDecoder(resp.Body).Decode(&appUsageEventsResponse); err != nil {
			return nil, errors.Wrap(err, "error unmarshaling events")
		}
		for _, e := range appUsageEventsResponse.Resources {
			e.Entity.GUID = e.Meta.Guid
			e.Entity.CreatedAt = e.Meta.CreatedAt
			e.Entity.c = c
			appUsageEvents = append(appUsageEvents, e.Entity)
		}
		requestURL = appUsageEventsResponse.NextURL
		if requestURL == "" {
			break
		}
	}
	return appUsageEvents, nil
}
733437
func RFC3339DateInFutureBy(d time.Duration) schema.SchemaValidateFunc {
	return func(i interface{}, k string) (warnings []string, errors []error) {
		v, ok := i.(string)
		if !ok {
			errors = append(errors, fmt.Errorf("expected type of %q to be string", k))
			return
		}

		t, err := date.ParseTime(time.RFC3339, v)
		if err != nil {
			errors = append(errors, fmt.Errorf("%q has the invalid RFC3339 date format %q: %+v", k, i, err))
			return
		}

		if time.Until(t) < d {
			errors = append(errors, fmt.Errorf("%q is %q and should be at least %q in the future", k, i, d))
		}

		return warnings, errors
	}
}
1262999
func Query(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
	var col, q string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "q", &q) {
		return
	}
	var qJson interface{}
	if err := json.Unmarshal([]byte(q), &qJson); err != nil {
		http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
		return
	}
	dbcol := HttpDB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	// Evaluate the query
	queryResult := make(map[int]struct{})
	if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
		http.Error(w, fmt.Sprint(err), 400)
		return
	}
	// Construct array of result
	resultDocs := make(map[string]interface{}, len(queryResult))
	counter := 0
	for docID := range queryResult {
		doc, _ := dbcol.Read(docID)
		if doc != nil {
			resultDocs[strconv.Itoa(docID)] = doc
			counter++
		}
	}
	// Serialize the array
	resp, err := json.Marshal(resultDocs)
	if err != nil {
		http.Error(w, fmt.Sprintf("Server error: query returned invalid structure"), 500)
		return
	}
	w.Write([]byte(string(resp)))
}
1275887
func (api *KrakenApi) Query(method string, data map[string]string) (interface{}, error) {
	values := url.Values{}
	for key, value := range data {
		values.Set(key, value)
	}

	// Check if method is public or private
	if isStringInSlice(method, publicMethods) {
		return api.queryPublic(method, values, nil)
	} else if isStringInSlice(method, privateMethods) {
		return api.queryPrivate(method, values, nil)
	}

	return nil, fmt.Errorf("Method '%s' is not valid", method)
}
420831
func (c *ComparativeTime) Parse(query string) error {
	if len(query) <= 2 {
		return errors.New("qstring: Invalid Timestamp Query")
	}

	c.Operator = parseOperator(query)

	// if no operator was provided and we defaulted to an equality operator
	if !strings.HasPrefix(query, c.Operator) {
		query = fmt.Sprintf("=%s", query)
	}

	var err error
	c.Time, err = time.Parse(time.RFC3339, query[len(c.Operator):])
	if err != nil {
		return err
	}

	return nil
}
717638
func URLQuery(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if c.Env == nil {
			c.Env = make(map[interface{}]interface{})
		}
		c.Env[URLQueryKey] = r.URL.Query()

		h.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
126357
func (t *TimeSeries) Query(ctx context.Context, query chronograf.Query) (chronograf.Response, error) {
	return t.QueryF(ctx, query)
}
996952
func checkIfEventSatisfiesRequest(request *Request, event *Event) bool {
	startTime := request.StartTime
	endTime := request.EndTime
	eventTime := event.Timestamp
	if !startTime.IsZero() {
		if startTime.After(eventTime) {
			return false
		}
	}
	if !endTime.IsZero() {
		if endTime.Before(eventTime) {
			return false
		}
	}
	if !request.EventType[event.EventType] {
		return false
	}
	return true
}
680669
func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error) {
	l.Debugf("SearchSessionEvents(%v, %v, %v)", fromUTC, toUTC, limit)

	if l.ExternalLog != nil {
		return l.ExternalLog.SearchSessionEvents(fromUTC, toUTC, limit)
	}
	return l.localLog.SearchSessionEvents(fromUTC, toUTC, limit)
}
646411
func (client *DockerClient) EventsSince(filters string, since time.Duration, until ...time.Duration) ([]Event, error) {
	if client.isSwarm {
		return nil, fmt.Errorf("Swarm doesn't support the events polling mode.")
	}

	v := url.Values{}
	if filters != "" {
		v.Set("filters", filters)
	}
	now := time.Now()
	v.Set("since", fmt.Sprintf("%d", tsFromNow(now, since)))
	if len(until) > 0 {
		v.Set("until", fmt.Sprintf("%d", tsFromNow(now, until[0])))
	}
	uri := fmt.Sprintf("events?%s", v.Encode())

	events := make([]Event, 0)
	err := client.sendRequestCallback("GET", uri, nil, nil, func(resp *http.Response) error {
		var event Event
		var cbErr error
		decoder := json.NewDecoder(resp.Body)
		for ; cbErr == nil; cbErr = decoder.Decode(&event) {
			// Not sure about why there will be an empty event first
			if cbErr == nil && event.Status != "" {
				events = append(events, event)
			}
		}
		if cbErr != io.EOF {
			return cbErr
		}
		return nil
	}, nil)
	return events, err
}
814581
func (c *Client) SearchEvents(from, to time.Time, query string, limit int) ([]events.EventFields, error) {
	q, err := url.ParseQuery(query)
	if err != nil {
		return nil, trace.BadParameter("query")
	}
	q.Set("from", from.Format(time.RFC3339))
	q.Set("to", to.Format(time.RFC3339))
	q.Set("limit", fmt.Sprintf("%v", limit))
	response, err := c.Get(c.Endpoint("events"), q)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	retval := make([]events.EventFields, 0)
	if err := json.Unmarshal(response.Bytes(), &retval); err != nil {
		return nil, trace.Wrap(err)
	}
	return retval, nil
}
794112
func (p *QueryEventParser) Parse(raw *RawV4Event) (Event, error) {
	query := &QueryEvent{
		Event: raw,
	}

	type fixedBodyStruct struct {
		ThreadId           uint32
		Duration           uint32
		DatabaseNameLength uint8
		ErrorCode          uint16
		StatusLength       uint16
	}

	fixed := fixedBodyStruct{}

	_, err := readLittleEndian(raw.FixedLengthData(), &fixed)
	if err != nil {
		return raw, errors.Wrap(err, "Failed to read fixed body")
	}

	query.threadId = fixed.ThreadId
	query.duration = fixed.Duration
	query.errorCode = mysql_proto.ErrorCode_Type(fixed.ErrorCode)

	data := raw.VariableLengthData()

	dbNameEnd := int(fixed.StatusLength) + int(fixed.DatabaseNameLength)
	if dbNameEnd+1 > len(data) {
		return raw, errors.Newf("Invalid message length")
	}

	query.statusBytes = data[:fixed.StatusLength]

	query.databaseName = data[fixed.StatusLength:dbNameEnd]

	query.query = data[dbNameEnd+1:]

	err = p.parseStatus(query)
	if err != nil {
		return raw, err
	}

	return query, nil
}
1203796
func Filter(key, value string) RequestOptions {
	return func(req *http.Request) {
		q := req.URL.Query()
		q.Add(key, value)
		req.URL.RawQuery = strings.Replace(q.Encode(), "%2B", "+", 1)
	}
}
1097349
func (r *FastHttpRequest) GetForm() (url.Values, error) {
	if !r.FormParsed {
		r.form = url.Values{}
		r.Original.PostArgs().VisitAll(func(key, value []byte) {
			r.query.Set(string(key), string(value))
		})
		r.FormParsed = true
	}
	return r.form, nil
}
312890
func (s *HTTPServer) EventList(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Parse the query options, since we simulate a blocking query
	var b structs.QueryOptions
	if parseWait(resp, req, &b) {
		return nil, nil
	}

	// Fetch the ACL token, if any.
	var token string
	s.parseToken(req, &token)
	acl, err := s.agent.resolveToken(token)
	if err != nil {
		return nil, err
	}

	// Look for a name filter
	var nameFilter string
	if filt := req.URL.Query().Get("name"); filt != "" {
		nameFilter = filt
	}

	// Lots of this logic is borrowed from consul/rpc.go:blockingQuery
	// However we cannot use that directly since this code has some
	// slight semantics differences...
	var timeout <-chan time.Time
	var notifyCh chan struct{}

	// Fast path non-blocking
	if b.MinQueryIndex == 0 {
		goto RUN_QUERY
	}

	// Restrict the max query time
	if b.MaxQueryTime > maxQueryTime {
		b.MaxQueryTime = maxQueryTime
	}

	// Ensure a time limit is set if we have an index
	if b.MinQueryIndex > 0 && b.MaxQueryTime == 0 {
		b.MaxQueryTime = maxQueryTime
	}

	// Setup a query timeout
	if b.MaxQueryTime > 0 {
		timeout = time.After(b.MaxQueryTime)
	}

	// Setup a notification channel for changes
SETUP_NOTIFY:
	if b.MinQueryIndex > 0 {
		notifyCh = make(chan struct{}, 1)
		s.agent.eventNotify.Wait(notifyCh)
		defer s.agent.eventNotify.Clear(notifyCh)
	}

RUN_QUERY:
	// Get the recent events
	events := s.agent.UserEvents()

	// Filter the events using the ACL, if present
	if acl != nil {
		for i := 0; i < len(events); i++ {
			name := events[i].Name
			if acl.EventRead(name) {
				continue
			}
			s.agent.logger.Printf("[DEBUG] agent: dropping event %q from result due to ACLs", name)
			events = append(events[:i], events[i+1:]...)
			i--
		}
	}

	// Filter the events if requested
	if nameFilter != "" {
		for i := 0; i < len(events); i++ {
			if events[i].Name != nameFilter {
				events = append(events[:i], events[i+1:]...)
				i--
			}
		}
	}

	// Determine the index
	var index uint64
	if len(events) == 0 {
		// Return a non-zero index to prevent a hot query loop. This
		// can be caused by a watch for example when there is no matching
		// events.
		index = 1
	} else {
		last := events[len(events)-1]
		index = uuidToUint64(last.ID)
	}
	setIndex(resp, index)

	// Check for exact match on the query value. Because
	// the index value is not monotonic, we just ensure it is
	// not an exact match.
	if index > 0 && index == b.MinQueryIndex {
		select {
		case <-notifyCh:
			goto SETUP_NOTIFY
		case <-timeout:
		}
	}
	return events, nil
}
818754
func query(v interface{}) string {
	var buf bytes.Buffer
	writeQuery(&buf, reflect.TypeOf(v), false)
	return buf.String()
}