// newTrigger returns implementation of trigger.
174330
func newTrigger(pthLkp map[string]*watched) trigger {
	return &fen{
		pthLkp: pthLkp,
		cf:     newCfen(),
	}
}
935341
func (s *RepositoryTriggerExecutionFailure) SetTrigger(v string) *RepositoryTriggerExecutionFailure {
	s.Trigger = &v
	return s
}
570554
func canTrigger(
	config *appsapi.DeploymentConfig,
	rn corev1client.ReplicationControllersGetter,
	force bool,
) (bool, []appsapi.DeploymentCause, error) {

	decoded, err := decodeFromLatestDeployment(config, rn)
	if err != nil {
		return false, nil, err
	}

	ictCount, resolved, canTriggerByImageChange := 0, 0, false
	var causes []appsapi.DeploymentCause

	for _, t := range config.Spec.Triggers {
		if t.Type != appsapi.DeploymentTriggerOnImageChange {
			continue
		}
		ictCount++

		// If the image is yet to be resolved then we cannot process this trigger.
		lastTriggered := t.ImageChangeParams.LastTriggeredImage
		if len(lastTriggered) == 0 {
			continue
		}
		resolved++

		// Non-automatic triggers should not be able to trigger deployments.
		if !t.ImageChangeParams.Automatic {
			continue
		}

		// We need stronger checks in order to validate that this template
		// change is an image change. Look at the deserialized config's
		// triggers and compare with the present trigger. Initial deployments
		// should always trigger - there is no previous config to use for the
		// comparison. Also configs with new/updated triggers should always trigger.
		if config.Status.LatestVersion == 0 || hasUpdatedTriggers(*config, *decoded) || triggeredByDifferentImage(*t.ImageChangeParams, *decoded) {
			canTriggerByImageChange = true
		}

		if !canTriggerByImageChange {
			continue
		}

		causes = append(causes, appsapi.DeploymentCause{
			Type: appsapi.DeploymentTriggerOnImageChange,
			ImageTrigger: &appsapi.DeploymentCauseImageTrigger{
				From: core.ObjectReference{
					Name:      t.ImageChangeParams.From.Name,
					Namespace: t.ImageChangeParams.From.Namespace,
					Kind:      "ImageStreamTag",
				},
			},
		})
	}

	if ictCount != resolved {
		err = errors.NewBadRequest(fmt.Sprintf("cannot trigger a deployment for %q because it contains unresolved images", config.Name))
		return false, nil, err
	}

	if force {
		return true, []appsapi.DeploymentCause{{Type: appsapi.DeploymentTriggerManual}}, nil
	}

	canTriggerByConfigChange := false
	externalConfig := &appsv1.DeploymentConfig{}
	if err := legacyscheme.Scheme.Convert(config, externalConfig, nil); err != nil {
		return false, nil, err
	}
	if appsutil.HasChangeTrigger(externalConfig) && // Our deployment config has a config change trigger
		len(causes) == 0 && // and no other trigger has triggered.
		(config.Status.LatestVersion == 0 || // Either it's the initial deployment
			!helper.Semantic.DeepEqual(config.Spec.Template, decoded.Spec.Template)) /* or a config change happened so we need to trigger */ {

		canTriggerByConfigChange = true
		causes = []appsapi.DeploymentCause{{Type: appsapi.DeploymentTriggerOnConfigChange}}
	}

	return canTriggerByConfigChange || canTriggerByImageChange, causes, nil
}
562796
func HasChangeTrigger(config *appsv1.DeploymentConfig) bool {
	for _, trigger := range config.Spec.Triggers {
		if trigger.Type == appsv1.DeploymentTriggerOnConfigChange {
			return true
		}
	}
	return false
}
262412
func NewTextHandler(t *template.Template, output TextOutput) *TextHandler {
	return &TextHandler{template: t, output: output}
}
1127981
func (self *Service) ListTriggers() (TriggerListResponse, error) {
	url := "service/" + self.Uuid + "/trigger/"
	request := "GET"
	//Empty Body Request
	body := []byte(`{}`)
	var response TriggerListResponse
	var finalResponse TriggerListResponse

	data, err := TutumCall(url, request, body)
	if err != nil {
		return response, err
	}

	err = json.Unmarshal(data, &response)
	if err != nil {
		return response, err
	}

	finalResponse = response

Loop:
	for {
		if response.Meta.Next != "" {
			var nextResponse TriggerListResponse
			data, err := TutumCall(response.Meta.Next[8:], request, body)
			if err != nil {
				return nextResponse, err
			}
			err = json.Unmarshal(data, &nextResponse)
			if err != nil {
				return nextResponse, err
			}
			finalResponse.Objects = append(finalResponse.Objects, nextResponse.Objects...)
			response = nextResponse

		} else {
			break Loop
		}
	}

	return finalResponse, nil
}
636458
func (s *PutRepositoryTriggersInput) SetTriggers(v []*RepositoryTrigger) *PutRepositoryTriggersInput {
	s.Triggers = v
	return s
}
1314162
func NewTracker(parentCtx context.Context, logger hclog.Logger, alloc *structs.Allocation,
	allocUpdates *cstructs.AllocListener, consulClient cconsul.ConsulServiceAPI,
	minHealthyTime time.Duration, useChecks bool) *Tracker {

	// Do not create a named sub-logger as the hook controlling
	// this struct should pass in an appropriately named
	// sub-logger.
	t := &Tracker{
		healthy:        make(chan bool, 1),
		allocStopped:   make(chan struct{}),
		alloc:          alloc,
		tg:             alloc.Job.LookupTaskGroup(alloc.TaskGroup),
		minHealthyTime: minHealthyTime,
		useChecks:      useChecks,
		allocUpdates:   allocUpdates,
		consulClient:   consulClient,
		logger:         logger,
	}

	t.taskHealth = make(map[string]*taskHealthState, len(t.tg.Tasks))
	for _, task := range t.tg.Tasks {
		t.taskHealth[task.Name] = &taskHealthState{task: task}
	}

	for _, task := range t.tg.Tasks {
		for _, s := range task.Services {
			t.consulCheckCount += len(s.Checks)
		}
	}

	t.ctx, t.cancelFn = context.WithCancel(parentCtx)
	return t
}
198760
func (w *fakeWatcher) TriggerEvent(op fsnotify.Op, filename string) {
	w.eventHandler(fsnotify.Event{Op: op, Name: filename})
}
1189137
func trigger(c context.Context, t tasks.Task, q *datastore.Query) error {
	tasks := make([]*tq.Task, 0)
	newPayload := payloadFactory(t)
	addTask := func(k *datastore.Key) {
		tasks = append(tasks, &tq.Task{
			Payload: newPayload(k.StringID()),
		})
	}
	if err := datastore.Run(c, q, addTask); err != nil {
		return errors.Annotate(err, "failed to fetch keys").Err()
	}
	logging.Debugf(c, "scheduling %d tasks", len(tasks))
	if err := getDispatcher(c).AddTask(c, tasks...); err != nil {
		return errors.Annotate(err, "failed to schedule tasks").Err()
	}
	return nil
}
225166
func (sm *StateMachine) Trigger(name string, value Stater, tx *gorm.DB, notes ...string) error {
	var (
		newTx    *gorm.DB
		stateWas = value.GetState()
	)

	if tx != nil {
		newTx = tx.New()
	}

	if stateWas == "" {
		stateWas = sm.initialState
		value.SetState(sm.initialState)
	}

	if event := sm.events[name]; event != nil {
		var matchedTransitions []*EventTransition
		for _, transition := range event.transitions {
			var validFrom = len(transition.froms) == 0
			if len(transition.froms) > 0 {
				for _, from := range transition.froms {
					if from == stateWas {
						validFrom = true
					}
				}
			}

			if validFrom {
				matchedTransitions = append(matchedTransitions, transition)
			}
		}

		if len(matchedTransitions) == 1 {
			transition := matchedTransitions[0]

			// State: exit
			if state, ok := sm.states[stateWas]; ok {
				for _, exit := range state.exits {
					if err := exit(value, newTx); err != nil {
						return err
					}
				}
			}

			// Transition: before
			for _, before := range transition.befores {
				if err := before(value, newTx); err != nil {
					return err
				}
			}

			value.SetState(transition.to)

			// State: enter
			if state, ok := sm.states[transition.to]; ok {
				for _, enter := range state.enters {
					if err := enter(value, newTx); err != nil {
						value.SetState(stateWas)
						return err
					}
				}
			}

			// Transition: after
			for _, after := range transition.afters {
				if err := after(value, newTx); err != nil {
					value.SetState(stateWas)
					return err
				}
			}

			if newTx != nil {
				scope := newTx.NewScope(value)
				log := StateChangeLog{
					ReferTable: scope.TableName(),
					ReferID:    GenerateReferenceKey(value, tx),
					From:       stateWas,
					To:         transition.to,
					Note:       strings.Join(notes, ""),
				}
				return newTx.Save(&log).Error
			}

			return nil
		}
	}
	return fmt.Errorf("failed to perform event %s from state %s", name, stateWas)
}
496779
func (e *engineImpl) EmitTriggers(c context.Context, perJob map[*Job][]*internal.Trigger) error {
	// Make sure the caller has permissions to add triggers to all jobs.
	jobs := make([]*Job, 0, len(perJob))
	for j := range perJob {
		jobs = append(jobs, j)
	}
	switch filtered, err := e.filterForRole(c, jobs, acl.Triggerer); {
	case err != nil:
		return errors.Annotate(err, "transient error when checking Triggerer role").Err()
	case len(filtered) != len(jobs):
		return ErrNoPermission // some jobs are not triggerable
	}

	// Actually trigger.
	return parallel.FanOutIn(func(tasks chan<- func() error) {
		for job, triggers := range perJob {
			jobID := job.JobID
			triggers := triggers
			tasks <- func() error {
				return e.execEnqueueTriggersTask(c, &internal.EnqueueTriggersTask{
					JobId:    jobID,
					Triggers: triggers,
				})
			}
		}
	})
}
1174854
func (m *Memberlist) triggerFunc(stagger time.Duration, C <-chan time.Time, stop <-chan struct{}, f func()) {
	// Use a random stagger to avoid syncronizing
	randStagger := time.Duration(uint64(rand.Int63()) % uint64(stagger))
	select {
	case <-time.After(randStagger):
	case <-stop:
		return
	}
	for {
		select {
		case <-C:
			f()
		case <-stop:
			return
		}
	}
}
782384
func NewTrivialRecorder(processName string) *TrivialRecorder {
	return &TrivialRecorder{
		processName: processName,
		tags:        make(map[string]string),
	}
}
64732
func (op *triageOp) processTriggers(c context.Context, job *Job) (*dsset.PopOp, error) {
	popOp, err := op.triggersSet.BeginPop(c, op.triggersList)
	if err != nil {
		op.debugErrLog(c, err, "Failed to pop from pending triggers set")
		return nil, err
	}

	// Filter out all triggers already popped by some other transaction.
	triggers := make([]*internal.Trigger, 0, len(op.readyTriggers))
	for _, t := range op.readyTriggers {
		if popOp.CanPop(t.Id) {
			triggers = append(triggers, t)
		}
	}
	op.debugInfoLog(c, "Triggers available in this txn: %d", len(triggers))

	// If the job is paused or disabled, just pop all triggers without starting
	// anything. Note: there's a best-effort shortcut for ignoring triggers
	// for paused jobs in execEnqueueTriggersTask.
	if len(triggers) != 0 {
		if job.Paused || !job.Enabled {
			op.debugInfoLog(c, "The job is inactive, clearing the pending triggers queue")
			for _, t := range triggers {
				popOp.Pop(t.Id)
			}
			return popOp, nil
		}
	}

	// Keep the set of pending triggers bounded, to avoid total meltdown caused
	// by slow triage transactions.
	if len(triggers) > op.maxAllowedTriggers {
		dropping := len(triggers) - op.maxAllowedTriggers
		op.debugErrLog(c, nil, "Too many pending triggers (>%d), dropping %d oldest", op.maxAllowedTriggers, dropping)
		for i := 0; i < dropping; i++ {
			popOp.Pop(triggers[i].Id)
		}
		triggers = triggers[dropping:]
	}

	// Ask the policy to convert triggers into invocations. Note that triggers is
	// not the only input to the triggering policy, so we call it on each triage,
	// even if there's no pending triggers.
	op.debugInfoLog(c, "Invoking the triggering policy function")
	out := op.triggeringPolicy(c, job, triggers)
	op.debugInfoLog(c, "The policy requested %d new invocations", len(out.Requests))

	// Actually pop all consumed triggers and start the corresponding invocations.
	// Note that this modifies job.ActiveInvocations list.
	if len(out.Requests) != 0 {
		consumed := 0
		for _, r := range out.Requests {
			for _, t := range r.IncomingTriggers {
				popOp.Pop(t.Id)
			}
			consumed += len(r.IncomingTriggers)
		}
		if err := op.enqueueInvocations(c, job, out.Requests); err != nil {
			op.debugErrLog(c, err, "Failed to enqueue some invocations")
			return nil, err
		}
		op.debugInfoLog(c, "New invocations enqueued, consumed %d triggers", consumed)
	}

	return popOp, nil
}
279082
func (s *TriggerConfig) SetTriggerEvents(v []*string) *TriggerConfig {
	s.TriggerEvents = v
	return s
}
1254224
func Trigger(trigger string, args ...interface{}) {
	tl.Lock()
	priorities, exists := triggers[trigger]
	tl.Unlock()

	if exists {
		for p := 0; p <= 100; p++ {
			for _, f := range priorities[p] {
				params := make([]reflect.Value, len(args))
				for idx := range args {
					params[idx] = reflect.ValueOf(args[idx])
				}
				reflect.ValueOf(f).Call(params)
			}
		}
	}

	// fire off subscriptions for all events
	if trigger != "*" {
		Trigger("*", args...)
	}
}