// EmitTriggers puts one or more triggers into pending trigger queues of the
// specified jobs.
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,
				})
			}
		}
	})
}
495289
func (r *RequestBuilder) FromTrigger(t *internal.Trigger) {
	switch p := t.Payload.(type) {
	case *internal.Trigger_Cron:
		r.FromCronTrigger(p.Cron)
	case *internal.Trigger_Webui:
		r.FromWebUITrigger(p.Webui)
	case *internal.Trigger_Noop:
		r.FromNoopTrigger(p.Noop)
	case *internal.Trigger_Gitiles:
		r.FromGitilesTrigger(p.Gitiles)
	case *internal.Trigger_Buildbucket:
		r.FromBuildbucketTrigger(p.Buildbucket)
	default:
		r.DebugLog("Unrecognized trigger payload of type %T, ignoring", p)
	}
}
137788
func (c *Core) emitMetrics(stopCh chan struct{}) {
	emitTimer := time.Tick(time.Second)
	writeTimer := time.Tick(c.counters.syncInterval)

	for {
		select {
		case <-emitTimer:
			c.metricsMutex.Lock()
			if c.expiration != nil {
				c.expiration.emitMetrics()
			}
			c.metricsMutex.Unlock()

		case <-writeTimer:
			if c.perfStandby {
				syncCounter(c)
			} else {
				err := c.saveCurrentRequestCounters(context.Background(), time.Now())
				if err != nil {
					c.logger.Error("writing request counters to barrier", "err", err)
				}
			}

		case <-stopCh:
			return
		}
	}
}
410852
func (db *DB) triggerPullSubscriptions(bin uint8) {
	db.pullTriggersMu.RLock()
	triggers, ok := db.pullTriggers[bin]
	db.pullTriggersMu.RUnlock()
	if !ok {
		return
	}

	for _, t := range triggers {
		select {
		case t <- struct{}{}:
		default:
		}
	}
}
985101
func (e *engineImpl) execEnqueueTriggersTask(c context.Context, tqTask proto.Message) error {
	msg := tqTask.(*internal.EnqueueTriggersTask)

	c = logging.SetField(c, "JobID", msg.JobId)

	logTriggers := func() {
		for _, t := range msg.Triggers {
			logging.Infof(c, "  %s (emitted by %q, inv %d)", t.Id, t.JobId, t.InvocationId)
		}
	}

	// Don't even bother if the job is paused or disabled. Note that if the job
	// became inactive after this check, the triage will get rid of pending
	// triggers itself. Thus the check here is just an optimization.
	job, err := e.getJob(c, msg.JobId)
	if err != nil {
		logging.WithError(err).Errorf(c, "Failed to grab Job entity")
		return err // transient error getting the job
	}
	if job == nil || !job.Enabled || job.Paused {
		logging.Warningf(c, "Discarding the following triggers since the job is inactive")
		logTriggers()
		return nil
	}

	logging.Infof(c, "Adding the following triggers to the pending triggers set")
	logTriggers()
	if err := pendingTriggersSet(c, msg.JobId).Add(c, msg.Triggers); err != nil {
		logging.WithError(err).Errorf(c, "Failed to update pending triggers set")
		return err
	}

	return e.kickTriageNow(c, msg.JobId)
}
415075
func (tm *Timer) Trigger() {
	tm.mu.Lock()
	defer tm.mu.Unlock()
	if tm.running {
		tm.msg <- timerTrigger
	}
}
519355
func mergeBuildTriggers(dst, src []buildv1.BuildTriggerPolicy) []buildv1.BuildTriggerPolicy {
	var result []buildv1.BuildTriggerPolicy
	for _, current := range dst {
		if findBuildTrigger(src, current) != -1 {
			result = append(result, current)
		}
	}
	for _, current := range src {
		if findBuildTrigger(result, current) == -1 {
			result = append(result, current)
		}
	}
	return result
}
750385
func calculateDeploymentConfigTriggers(dc *appsv1.DeploymentConfig) []triggerapi.ObjectFieldTrigger {
	var triggers []triggerapi.ObjectFieldTrigger
	for _, t := range dc.Spec.Triggers {
		addedTriggers := calculateDeploymentConfigTrigger(t, dc)
		triggers = append(triggers, addedTriggers...)
	}
	return triggers
}
1294431
func (s *TestRepositoryTriggersInput) SetTriggers(v []*RepositoryTrigger) *TestRepositoryTriggersInput {
	s.Triggers = v
	return s
}
1046545
func (m *Metrics) emitRuntimeStats() {
	// Export number of Goroutines
	numRoutines := runtime.NumGoroutine()
	m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines))

	// Export memory stats
	var stats runtime.MemStats
	runtime.ReadMemStats(&stats)
	m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc))
	m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys))
	m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs))
	m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees))
	m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects))
	m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs))
	m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC))

	// Export info about the last few GC runs
	num := stats.NumGC

	// Handle wrap around
	if num < m.lastNumGC {
		m.lastNumGC = 0
	}

	// Ensure we don't scan more than 256
	if num-m.lastNumGC >= 256 {
		m.lastNumGC = num - 255
	}

	for i := m.lastNumGC; i < num; i++ {
		pause := stats.PauseNs[i%256]
		m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause))
	}
	m.lastNumGC = num
}
500135
func NewCmdTriggers(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewTriggersOptions(streams)
	cmd := &cobra.Command{
		Use:     "triggers RESOURCE/NAME [--from-config|--from-image|--from-github|--from-webhook] [--auto|--manual]",
		Short:   "Update the triggers on one or more objects",
		Long:    triggersLong,
		Example: fmt.Sprintf(triggersExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			kcmdutil.CheckErr(o.Complete(f, cmd, args))
			kcmdutil.CheckErr(o.Validate())
			kcmdutil.CheckErr(o.Run())
		},
	}
	usage := "to use to edit the resource"
	kcmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
	cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on")
	cmd.Flags().BoolVar(&o.All, "all", o.All, "If true, select all resources in the namespace of the specified resource types")
	cmd.Flags().BoolVar(&o.Remove, "remove", o.Remove, "If true, remove the specified trigger(s).")
	cmd.Flags().BoolVar(&o.RemoveAll, "remove-all", o.RemoveAll, "If true, remove all triggers.")
	cmd.Flags().BoolVar(&o.Auto, "auto", o.Auto, "If true, enable all triggers, or just the specified trigger")
	cmd.Flags().BoolVar(&o.Manual, "manual", o.Manual, "If true, set all triggers to manual, or just the specified trigger")
	cmd.Flags().BoolVar(&o.Local, "local", o.Local, "If true, set image will NOT contact api-server but run locally.")
	cmd.Flags().BoolVar(&o.FromConfig, "from-config", o.FromConfig, "If set, configuration changes will result in a change")
	cmd.Flags().StringVarP(&o.ContainerNames, "containers", "c", o.ContainerNames, "Comma delimited list of container names this trigger applies to on deployments; defaults to the name of the only container")
	cmd.Flags().StringVar(&o.FromImage, "from-image", o.FromImage, "An image stream tag to trigger off of")
	o.FromGitHub = cmd.Flags().Bool("from-github", false, "If true, a GitHub webhook - a secret value will be generated automatically")
	o.FromWebHook = cmd.Flags().Bool("from-webhook", false, "If true, a generic webhook - a secret value will be generated automatically")
	o.FromWebHookAllowEnv = cmd.Flags().Bool("from-webhook-allow-env", false, "If true, a generic webhook which can provide environment variables - a secret value will be generated automatically")
	o.FromGitLab = cmd.Flags().Bool("from-gitlab", false, "If true, a GitLab webhook - a secret value will be generated automatically")
	o.FromBitbucket = cmd.Flags().Bool("from-bitbucket", false, "If true, a Bitbucket webhook - a secret value will be generated automatically")

	o.PrintFlags.AddFlags(cmd)
	kcmdutil.AddDryRunFlag(cmd)

	return cmd
}
74153
func EmitEvent(c context.Context, e *api.Event) error {
	ev := Events{}
	ev.Emit(e)
	return ev.Flush(c)
}
960667
func (db *DB) triggerPushSubscriptions() {
	db.pushTriggersMu.RLock()
	triggers := db.pushTriggers
	db.pushTriggersMu.RUnlock()

	for _, t := range triggers {
		select {
		case t <- struct{}{}:
		default:
		}
	}
}
1372799
func DeploymentConfigHasTrigger(config *appsv1.DeploymentConfig) TriggeredByFunc {
	return func(container *corev1.Container) (TemplateImage, bool) {
		for _, trigger := range config.Spec.Triggers {
			params := trigger.ImageChangeParams
			if params == nil {
				continue
			}
			for _, name := range params.ContainerNames {
				if container.Name == name {
					if len(params.From.Name) == 0 {
						continue
					}
					from := params.From
					if len(from.Namespace) == 0 {
						from.Namespace = config.Namespace
					}
					return TemplateImage{
						Image: container.Image,
						From:  &from,
					}, true
				}
			}
		}
		return TemplateImage{}, false
	}
}
429698
func emitRows(rows []string) string {
	
	qb422016 := qt422016.AcquireByteBuffer()
	
	writeemitRows(qb422016, rows)
	
	qs422016 := string(qb422016.B)
	
	qt422016.ReleaseByteBuffer(qb422016)
	
	return qs422016

}
877551
func (s *DashPackage) SetPeriodTriggers(v []*string) *DashPackage {
	s.PeriodTriggers = v
	return s
}
283883
func (g *BuildGenerator) updateImageTriggers(ctx context.Context, bc *buildv1.BuildConfig, from, triggeredBy *corev1.ObjectReference) error {
	var requestTrigger *buildv1.ImageChangeTrigger
	if from != nil {
		requestTrigger = findImageChangeTrigger(bc, from)
	}
	if requestTrigger != nil && triggeredBy != nil && requestTrigger.LastTriggeredImageID == triggeredBy.Name {
		klog.V(2).Infof("Aborting imageid triggered build for BuildConfig %s/%s with imageid %s because the BuildConfig already matches this imageid", bc.Namespace, bc.Name, triggeredBy.Name)
		return fmt.Errorf("build config %s/%s has already instantiated a build for imageid %s", bc.Namespace, bc.Name, triggeredBy.Name)
	}
	// Update last triggered image id for all image change triggers
	for _, trigger := range bc.Spec.Triggers {
		if trigger.Type != buildv1.ImageChangeBuildTriggerType {
			continue
		}
		// Use the requested image id for the trigger that caused the build, otherwise resolve to the latest
		if triggeredBy != nil && trigger.ImageChange == requestTrigger {
			trigger.ImageChange.LastTriggeredImageID = triggeredBy.Name
			continue
		}

		triggerImageRef := trigger.ImageChange.From
		if triggerImageRef == nil {
			triggerImageRef = buildutil.GetInputReference(bc.Spec.Strategy)
		}
		if triggerImageRef == nil {
			klog.Warningf("Could not get ImageStream reference for default ImageChangeTrigger on BuildConfig %s/%s", bc.Namespace, bc.Name)
			continue
		}
		image, err := g.resolveImageStreamReference(ctx, *triggerImageRef, bc.Namespace)
		if err != nil {
			// If the trigger is for the strategy from ref, return an error
			if trigger.ImageChange.From == nil {
				return err
			}
			// Otherwise, warn that an error occurred, but continue
			klog.Warningf("Could not resolve trigger reference for build config %s/%s: %#v", bc.Namespace, bc.Name, triggerImageRef)
		}
		trigger.ImageChange.LastTriggeredImageID = image
	}
	return nil
}