// ******************************* INTERVAL ACTIONS **********************************
// Return all the Interval Action(s)
// UnexpectedError - failed to retrieve interval actions from the database
// Sort the interval actions in descending order by ID
490479
func (mc MongoClient) IntervalActions() ([]contract.IntervalAction, error) {
	return mapIntervalActions(mc.getIntervalActions(bson.M{}))
}
769273
func (mc MongoClient) IntervalActionsByIntervalName(name string) ([]contract.IntervalAction, error) {
	return mapIntervalActions(mc.getIntervalActions(bson.M{"interval": name}))
}
635894
func HandleAction(name string, params map[string]interface{}) (results map[string]interface{}, err error) {
	spec, ok := actions.PredefinedActionsSpec[name]
	if !ok {
		return nil, errors.Errorf("unexpected action %s", name)
	}
	if err := spec.ValidateParams(params); err != nil {
		return nil, errors.Errorf("invalid action parameters")
	}

	switch name {
	case actions.JujuRunActionName:
		return handleJujuRunAction(params)
	default:
		return nil, errors.Errorf("unexpected action %s", name)
	}
}
875821
func (q Query) ForEach(action func(interface{})) {
	next := q.Iterate()

	for item, ok := next(); ok; item, ok = next() {
		action(item)
	}
}
700217
func (m *Model) AllActions() ([]Action, error) {
	actionLogger.Tracef("AllActions()")
	actions, closer := m.st.db().GetCollection(actionsC)
	defer closer()

	results := []Action{}
	docs := []actionDoc{}
	err := actions.Find(nil).All(&docs)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot get all actions")
	}
	for _, doc := range docs {
		results = append(results, newAction(m.st, doc))
	}
	return results, nil
}
43844
func (m *Model) Action(id string) (Action, error) {
	actionLogger.Tracef("Action() %q", id)
	st := m.st
	actions, closer := st.db().GetCollection(actionsC)
	defer closer()

	doc := actionDoc{}
	err := actions.FindId(id).One(&doc)
	if err == mgo.ErrNotFound {
		return nil, errors.NotFoundf("action %q", id)
	}
	if err != nil {
		return nil, errors.Annotatef(err, "cannot get action %q", id)
	}
	actionLogger.Tracef("Action() %q found %+v", id, doc)
	return newAction(st, doc), nil
}
672512
func (c *Client) AddIntervalAction(from contract.IntervalAction) (id string, err error) {
	action := models.NewIntervalAction(from)
	if action.ID != "" {
		_, err = uuid.Parse(action.ID)
		if err != nil {
			return "", db.ErrInvalidObjectId
		}
	} else {
		action.ID = uuid.New().String()
	}

	if action.Created == 0 {
		ts := db.MakeTimestamp()
		action.Created = ts
		action.Modified = ts
	}

	data, err := json.Marshal(action)
	if err != nil {
		return "", err
	}

	conn := c.Pool.Get()
	defer conn.Close()

	_ = conn.Send("MULTI")
	addObject(data, action, action.ID, conn)
	_, err = conn.Do("EXEC")

	return action.ID, err
}
462334
func (_m *DBClient) IntervalActionsWithLimit(limit int) ([]models.IntervalAction, error) {
	ret := _m.Called(limit)

	var r0 []models.IntervalAction
	if rf, ok := ret.Get(0).(func(int) []models.IntervalAction); ok {
		r0 = rf(limit)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.IntervalAction)
		}
	}

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

	return r0, r1
}
63836
func (c *Client) Intervals() (intervals []contract.Interval, err error) {
	conn := c.Pool.Get()
	defer conn.Close()

	objects, err := getObjectsByRange(conn, models.IntervalKey, 0, -1)
	if err != nil {
		return []contract.Interval{}, err
	}

	intervals = make([]contract.Interval, len(objects))
	for i, object := range objects {
		err = json.Unmarshal(object, &intervals[i])
		if err != nil {
			return []contract.Interval{}, err
		}
	}

	return intervals, nil
}
760288
func isIntervalStillInUse(s contract.Interval) (bool, error) {
	var intervalActions []contract.IntervalAction

	intervalActions, err := dbClient.IntervalActionsByIntervalName(s.Name)
	if err != nil {
		return false, err
	}
	if len(intervalActions) > 0 {
		return true, nil
	}

	return false, nil
}
1122642
func (c *Client) IntervalActionsWithLimit(limit int) (actions []contract.IntervalAction, err error) {
	conn := c.Pool.Get()
	defer conn.Close()

	objects, err := getObjectsByRange(conn, models.IntervalActionKey, 0, limit-1)
	if err != nil {
		if err != redis.ErrNil {
			return actions, err
		}
	}

	actions = make([]contract.IntervalAction, len(objects))
	for i, object := range objects {
		err = json.Unmarshal(object, &actions[i])
		if err != nil {
			return []contract.IntervalAction{}, err
		}
	}

	return actions, nil
}
1013443
func (mc MongoClient) DeleteIntervalActionById(id string) error {
	return mc.deleteById(db.IntervalAction, id)
}
1062555
func (m *Manager) HistoricalInterval(ctx context.Context) (IntervalList, error) {
	var pm mo.PerformanceManager

	err := m.Properties(ctx, m.Reference(), []string{"historicalInterval"}, &pm)
	if err != nil {
		return nil, err
	}

	return IntervalList(pm.HistoricalInterval), nil
}
586986
func PruneActions(st *State, maxHistoryTime time.Duration, maxHistoryMB int) error {
	err := pruneCollection(st, maxHistoryTime, maxHistoryMB, actionsC, "completed", GoTime)
	return errors.Trace(err)
}
743419
func (m *Monitor) Events(from, to time.Time) EventIntervals {
	samples, events := m.snapshot()
	intervals := filterSamples(samples, from, to)
	events = filterEvents(events, from, to)

	// merge the two sets of inputs
	mustSort := len(intervals) > 0
	for i := range events {
		if i > 0 && events[i-1].At.After(events[i].At) {
			fmt.Printf("ERROR: event %d out of order\n  %#v\n  %#v\n", i, events[i-1], events[i])
		}
		at := events[i].At
		condition := &events[i].Condition
		intervals = append(intervals, &EventInterval{
			From:      at,
			To:        at,
			Condition: condition,
		})
	}
	if mustSort {
		sort.Sort(intervals)
	}
	return intervals
}
395933
func (mod *DevrantBee) Action(action bees.Action) []bees.Placeholder {
	outs := []bees.Placeholder{}

	switch action.Name {
	case "surprise":
		rant, err := mod.client.Surprise()
		if err != nil {
			mod.LogErrorf("Failed to fetch surprise rant: %v", err)
		}

		mod.triggerEvent(rant)

	case "weekly":
		rants, err := mod.client.WeeklyRants()
		if err != nil {
			mod.LogErrorf("Failed to fetch weekly rants: %v", err)
		}

		for _, v := range rants {
			mod.triggerEvent(v)
		}

	case "rant":
		limit := 0
		action.Options.Bind("limit", &limit)

		rants, err := mod.client.Rants("", limit, 0)
		if err != nil {
			mod.LogErrorf("Failed to fetch rants: %v", err)
		}

		for i := range rants {
			mod.triggerEvent(rants[i])
		}

	default:
		panic("Unknown action triggered in " + mod.Name() + ": " + action.Name)
	}

	return outs
}
419751
func intervalActionByTargetHandler(w http.ResponseWriter, r *http.Request) {
	if r.Body != nil {
		defer r.Body.Close()
	}

	// URL parameters
	vars := mux.Vars(r)
	target, err := url.QueryUnescape(vars["target"])
	//Issues un-escaping
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error un-escaping the value descriptor name: " + err.Error())
		return
	}

	switch r.Method {
	case http.MethodGet:
		intervalActions, err := getIntervalActionsByTarget(target)
		if err != nil {
			LoggingClient.Error(err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		encode(intervalActions, w)
		break
	}
}