// Fire calls all the functions in a given Hooks list. It launches a goroutine
// for each function and then waits for all of them to finish before returning.
// Concurrent calls to Fire() are serialized.
422649
func (h *Hooks) Fire() {
	h.mu.Lock()
	defer h.mu.Unlock()

	wg := sync.WaitGroup{}

	for _, f := range h.funcs {
		wg.Add(1)
		go func(f func()) {
			f()
			wg.Done()
		}(f)
	}
	wg.Wait()
}
291069
func (h HookFunc) Run(e *Event, level Level, message string) {
	h(e, level, message)
}
1211286
func (s *State) Callbacks() []Callback {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return append([]Callback{}, s.callbacks...)
}
1031956
func (cons *LogConsumer) Fire(logrusEntry *logrus.Entry) error {
	// Have Logrus format the log entry
	formattedMessage, err := logrusEntry.String()
	if err != nil {
		return err
	}

	// The formatter adds an unnecessary linefeed, strip it out
	if formattedMessage[len(formattedMessage)-1] == '\n' {
		formattedMessage = formattedMessage[:len(formattedMessage)-1]
	}

	// Set message metadata: level, time and logrus's ad-hoc fields. The fields
	// also contain the plugin-specific log scope.
	metadata := Metadata{}
	metadata.SetValue("Level", []byte(logrusEntry.Level.String()))
	metadata.SetValue("Time", []byte(logrusEntry.Time.String()))
	//  string,    interface{}
	for fieldName, fieldValue := range logrusEntry.Data {
		metadata.SetValue(fieldName, []byte(fmt.Sprintf("%v", fieldValue)))
	}

	// Wrap it in a Gollum message
	msg := NewMessage(cons, []byte(formattedMessage), metadata, LogInternalStreamID)

	// Push it to a channel to allow logging while logging
	// In case Push fails, fallback to stdout.
	result := cons.queue.Push(msg, time.Second)
	if result != MessageQueueOk {
		fmt.Fprintln(logger.FallbackLogDevice, msg.String())
	}

	// Metrics handling from .Write() (TODO: support all message levels?)
	if cons.metric != "" {
		switch logrusEntry.Level {
		case logrus.ErrorLevel:
			cons.metricErrors.Inc(1)

		case logrus.WarnLevel:
			cons.metricWarning.Inc(1)

		case logrus.InfoLevel:
			cons.metricInfo.Inc(1)

		case logrus.DebugLevel:
			cons.metricDebug.Inc(1)
		}
	}

	// Success
	return nil
}
1135239
func (h HandlerFunc) Handle(data json.RawMessage, ctx *apex.Context) (interface{}, error) {
	var event Event

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

	return nil, h(&event, ctx)
}
1350014
func All(asyncs ...Async) Async {
	return &asyncImpl{
		cancel: func() {
			for _, a := range asyncs {
				a.Cancel()
			}
		},
		promise: Promise(func() error {
			errs := make([]error, 0)
			for _, a := range asyncs {
				err := <-a.Result()
				if err != nil {
					errs = append(errs, err)
				}
			}
			if len(errs) > 0 {
				return &GroupError{Errs: errs}
			}
			return nil
		}),
	}
}
730885
function Callbacks( once ) {
        var list = [],
            stack = !once && [],
            fire = function( data ) {
                memory = data;
                fired = true;
                firingIndex = firingStart || 0;
                firingStart = 0;
                firingLength = list.length;
                firing = true;

                for ( ; list && firingIndex < firingLength; firingIndex++ ) {
                    list[ firingIndex ].apply( data[ 0 ], data[ 1 ] );
                }
                firing = false;

                if ( list ) {
                    if ( stack ) {
                        stack.length && fire( stack.shift() );
                    }  else {
                        list = [];
                    }
                }
            },
            self = {
                add: function() {
                    if ( list ) {
                        var start = list.length;
                        (function add ( args ) {
                            $.each( args, function( _, arg ) {
                                var type = $.type( arg );
                                if ( type === 'function' ) {
                                    list.push( arg );
                                } else if ( arg && arg.length &&
                                        type !== 'string' ) {

                                    add( arg );
                                }
                            });
                        })( arguments );

                        if ( firing ) {
                            firingLength = list.length;
                        } else if ( memory ) {
                            firingStart = start;
                            fire( memory );
                        }
                    }
                    return this;
                },

                disable: function() {
                    list = stack = memory = undefined;
                    return this;
                },

                // Lock the list in its current state
                lock: function() {
                    stack = undefined;
                    if ( !memory ) {
                        self.disable();
                    }
                    return this;
                },

                fireWith: function( context, args ) {
                    if ( list && (!fired || stack) ) {
                        args = args || [];
                        args = [ context, args.slice ? args.slice() : args ];
                        if ( firing ) {
                            stack.push( args );
                        } else {
                            fire( args );
                        }
                    }
                    return this;
                },

                fire: function() {
                    self.fireWith( this, arguments );
                    return this;
                }
            },

            fired, firing, firingStart, firingLength, firingIndex, memory;

        return self;
    }
727066
func (ctx *Context) After(hook func()) {
	if ctx.Res.ended.isTrue() { // should not add afterHooks if ctx.Res.ended
		panic(Err.WithMsg(`can't add "after hook" after middleware process ended`))
	}
	ctx.Res.afterHooks = append(ctx.Res.afterHooks, hook)
}
781861
func For(msg string, timeout, interval time.Duration, f func() (bool, error)) error {
	log.Infof("Wait for %s [timeout: %s, interval: %s]", msg, timeout, interval)

	var lastErr string
	timeUp := time.After(timeout)
	for {
		select {
		case <-timeUp:
			return fmt.Errorf("time limit exceeded: last error: %s", lastErr)
		default:
		}

		stop, err := f()
		if stop {
			return nil
		}
		if err != nil {
			lastErr = err.Error()
		}

		time.Sleep(interval)
	}
}
857036
func Handle(iface string, fn func(string, *Client)) {
	handlers.Lock()
	hdlrs, ok := handlers.extpointHandlers[iface]
	if !ok {
		hdlrs = []func(string, *Client){}
	}

	hdlrs = append(hdlrs, fn)
	handlers.extpointHandlers[iface] = hdlrs

	storage.Lock()
	for _, p := range storage.plugins {
		p.activateWait.L.Lock()
		if p.activated() && p.implements(iface) {
			p.handlersRun = false
		}
		p.activateWait.L.Unlock()
	}
	storage.Unlock()

	handlers.Unlock()
}
361193
func (e *Event) Fire(params *UserEvent, q *WriteOptions) (string, *WriteMeta, error) {
	r := e.c.newRequest("PUT", "/v1/event/fire/"+params.Name)
	r.setWriteOptions(q)
	if params.NodeFilter != "" {
		r.params.Set("node", params.NodeFilter)
	}
	if params.ServiceFilter != "" {
		r.params.Set("service", params.ServiceFilter)
	}
	if params.TagFilter != "" {
		r.params.Set("tag", params.TagFilter)
	}
	if params.Payload != nil {
		r.body = bytes.NewReader(params.Payload)
	}

	rtt, resp, err := requireOK(e.c.doRequest(r))
	if err != nil {
		return "", nil, err
	}
	defer resp.Body.Close()

	wm := &WriteMeta{RequestTime: rtt}
	var out UserEvent
	if err := decodeBody(resp, &out); err != nil {
		return "", nil, err
	}
	return out.ID, wm, nil
}
733348
func (f *Function) Call(c context.Context, args ...interface{}) {
	t, err := f.Task(args...)
	if err != nil {
		log.Errorf(c, "%v", err)
		return
	}
	if _, err := taskqueueAdder(c, t, queue); err != nil {
		log.Errorf(c, "delay: taskqueue.Add failed: %v", err)
		return
	}
}
432406
func (c *Context) Flush() error {
	logger.Tracef("flushing from hook context to state")
	// TODO(natefinch): make this a noop and move this code into set.

	if len(c.updates) > 0 {
		var updates []payload.Payload
		for _, pl := range c.updates {
			updates = append(updates, pl)
		}

		res, err := c.api.Track(updates...)
		if err != nil {
			return errors.Trace(err)
		}
		if len(res) > 0 && res[0].Error != nil {
			return errors.Trace(res[0].Error)
		}

		for k, v := range c.updates {
			c.payloads[k] = v
		}
		c.updates = map[string]payload.Payload{}
	}
	return nil
}
1253310
func (hook *GraylogHook) Fire(entry *logrus.Entry) error {
	hook.mu.RLock() // Claim the mutex as a RLock - allowing multiple go routines to log simultaneously
	defer hook.mu.RUnlock()

	var file string
	var line int

	if entry.Caller != nil {
		file = entry.Caller.File
		line = entry.Caller.Line
	}

	newData := make(map[string]interface{})
	for k, v := range entry.Data {
		newData[k] = v
	}

	newEntry := &logrus.Entry{
		Logger:  entry.Logger,
		Data:    newData,
		Time:    entry.Time,
		Level:   entry.Level,
		Caller:  entry.Caller,
		Message: entry.Message,
	}
	gEntry := graylogEntry{newEntry, file, line}

	if hook.synchronous {
		hook.sendEntry(gEntry)
	} else {
		hook.wg.Add(1)
		hook.buf <- gEntry
	}

	return nil
}
914467
func (r RevelHooks) Run() {
	serverLogger.Infof("There is %d hooks need to run ...", len(r))
	sort.Sort(r)
	for i, hook := range r {
		utilLog.Infof("Run the %d hook ...", i+1)
		hook.f()
	}
}
36347
func (hook *InfluxDBHook) Fire(entry *logrus.Entry) (err error) {
	// If passing a "message" field then it will be overridden by the entry Message
	entry.Data["message"] = entry.Message

	measurement := hook.measurement
	if result, ok := getTag(entry.Data, "measurement"); ok {
		measurement = result
	}

	tags := make(map[string]string)
	// Set the level of the entry
	tags["level"] = entry.Level.String()
	// getAndDel and getAndDelRequest are taken from https://github.com/evalphobia/logrus_sentry
	if logger, ok := getTag(entry.Data, "logger"); ok {
		tags["logger"] = logger
	}

	// make a copy of entry.Data
	data := make(map[string]interface{})
	for k, v := range entry.Data {
		data[k] = v
	}

	for _, tag := range hook.tagList {
		if tagValue, ok := getTag(entry.Data, tag); ok {
			tags[tag] = tagValue
			delete(data, tag)
		}
	}

	pt, err := influxdb.NewPoint(measurement, tags, data, entry.Time)
	if err != nil {
		return fmt.Errorf("Fire: %v", err)
	}
	return hook.addPoint(pt)
}
267598
func (sh *Hook) Fire(e *logrus.Entry) error {
	if sh.limiter != nil && !sh.limiter.Allow() {
		// We've hit the configured limit, just ignore.
		return nil
	}

	m := sh.Message
	a := sh.Attachment
	m.AddAttachment(&a)
	a.Fallback = e.Message
	a.Color = sh.LevelColors[e.Level.String()]
	if a.Color == "" {
		a.Color = sh.UnknownColor
	}
	a.Text = e.Message
	for k, v := range e.Data {
		a.NewField(k, fmt.Sprint(v))
	}

	if sh.Async {
		go m.Send(sh.client)
		return nil
	}

	_, err := m.Send(sh.client)
	return err
}