// Emit invokes all attached listeners with the provided event.
174877
func (r *record) Emit(ev Event, b []byte) {
	// This looks absolutely _horrible_. It'd be better in C. Anyway, the idea
	// is that we have a list of unsafe pointers, which is stored in the list
	// which is an atomic pointer itself. We can swap the pointer held at each
	// address in the list, so _that_ address needs to be loaded atomically.
	// This means we need to actually load the data from the address at
	// offset X from the start of the array underlying the slice.
	//
	// The cost of the atomic loading makes 5-10% slower, but allows us to
	// atomically insert and remove listeners in many cases.

	list := r.getUnsafeList()
	for i := 0; i < len(list); i++ {
		addr := uintptr(unsafe.Pointer(&list[i]))
		value := atomic.LoadPointer(*(**unsafe.Pointer)(unsafe.Pointer(&addr)))
		if value != nil {
			(*(*Listener)(value)).Handle(ev, b)
		}
	}
}
1353156
func NewEmitter(listen chan Event, emit EmitFunc) Emitter {
	return &emitter{
		listenChan: listen,
		emit:       emit,
		stop:       make(chan struct{}),
		started:    false,
	}
}
682105
func (l *AuditLog) EmitAuditEvent(event Event, fields EventFields) error {
	// If an external logger has been set, use it as the emitter, otherwise
	// fallback to the local disk based emitter.
	var emitAuditEvent func(event Event, fields EventFields) error
	if l.ExternalLog != nil {
		emitAuditEvent = l.ExternalLog.EmitAuditEvent
	} else {
		emitAuditEvent = l.localLog.EmitAuditEvent
	}

	// Emit the event. If it fails for any reason a Prometheus counter is
	// incremented.
	err := emitAuditEvent(event, fields)
	if err != nil {
		auditFailedEmit.Inc()
		return trace.Wrap(err)
	}

	return nil
}
191156
func (l *lexer) emit(t TokenType) {
	l.tokens <- Token{
		Type: t,
		Text: l.input[l.start:l.pos],
	}
	l.start = l.pos
}
832414
func (e *EBus) Emit(event string, data interface{}) {
	go func() {
		log.Debugf("emmiting event `%s`", event)

		if topic, ok := e.eventList[event]; ok {
			log.Debug("found listeners for event " + event)

			for el := topic.Front(); el != nil; el = el.Next() {
				fn := el.Value.(EvHandler)
				fn(data)
			}
		} else {
			log.Debugf("listeners for event %s not found", event)
		}
	}()
}
1180341
func (s *SessionRegistry) emitSessionLeaveEvent(party *party) {
	sessionLeaveEvent := events.EventFields{
		events.EventType:       events.SessionLeaveEvent,
		events.SessionEventID:  party.id.String(),
		events.EventUser:       party.user,
		events.SessionServerID: party.serverID,
		events.EventNamespace:  s.srv.GetNamespace(),
	}

	// Emit session leave event to Audit Log.
	party.s.recorder.GetAuditLog().EmitAuditEvent(events.SessionLeave, sessionLeaveEvent)

	// Notify all members of the party that a new member has left over the
	// "x-teleport-event" channel.
	for _, p := range s.getParties(party.s) {
		eventPayload, err := json.Marshal(sessionLeaveEvent)
		if err != nil {
			s.log.Warnf("Unable to marshal %v for %v: %v.", events.SessionJoinEvent, p.sconn.RemoteAddr(), err)
			continue
		}
		_, _, err = p.sconn.SendRequest(teleport.SessionEvent, false, eventPayload)
		if err != nil {
			s.log.Warnf("Unable to send %v to %v: %v.", events.SessionJoinEvent, p.sconn.RemoteAddr(), err)
			continue
		}
		s.log.Debugf("Sent %v to %v.", events.SessionJoinEvent, p.sconn.RemoteAddr())
	}
}
188116
func (l *Forwarder) EmitAuditEvent(event Event, fields EventFields) error {
	err := UpdateEventFields(event, fields, l.Clock, l.UID)
	if err != nil {
		return trace.Wrap(err)
	}
	data, err := json.Marshal(fields)
	if err != nil {
		return trace.Wrap(err)
	}
	chunks := []*SessionChunk{
		{
			EventType: event.Name,
			Data:      data,
			Time:      time.Now().UTC().UnixNano(),
		},
	}
	return l.PostSessionSlice(SessionSlice{
		Namespace: l.Namespace,
		SessionID: string(l.SessionID),
		Version:   V3,
		Chunks:    chunks,
	})
}
17240
func (self *TimedRotatingFileHandler) Emit(record *LogRecord) error {
	return self.RolloverEmit(self, record)
}
417067
func (c *Client) Emit(data string) {
	c.writeMu.Lock()
	c.conn.WriteMessage(ws.TextMessage, []byte(data))
	c.writeMu.Unlock()
}
187048
func (ms *MetricSender) Send(ev events.Event) error {
	return ms.eventEmitter.Emit(ev)
}
1096505
func (b *BuildSource) Emit(args *[]string) ([]byte, error) {
	b.g.PrintHeader("qbg", args)

	if b.InlineInterfaces {
		tmpl := template.New("plugin")
		tmpl, err := tmpl.Parse(pluginTemplate)
		if err != nil {
			return nil, err
		}

		var dsKeyType string
		if b.UseDatastoreWrapper {
			dsKeyType = "datastore.Key"
		} else {
			dsKeyType = "*datastore.Key"
		}

		buf := bytes.NewBufferString("")
		err = tmpl.Execute(buf, map[string]string{
			"DSKeyType": dsKeyType,
		})
		if err != nil {
			return nil, err
		}

		b.g.Printf(buf.String())
	}

	for _, st := range b.Structs {
		err := st.emit(b.g)
		if err != nil {
			return nil, err
		}
	}

	return b.g.Format()
}
130392
func (b *eventListenerSupport) fire(message string) {
	b.Lock()
	defer b.Unlock()
	for substr, listeners := range b.listeners {
		if strings.Contains(message, substr) {
			for _, listener := range listeners {
				listener <- message
			}
		}
	}
}
517060
func EmitEvent(event EventName, info interface{}) {
	eventHooks.Range(func(k, v interface{}) bool {
		err := v.(EventHook)(event, info)
		if err != nil {
			log.Printf("error on '%s' hook: %v", k.(string), err)
		}
		return true
	})
}
490646
func (w *writer) emit(op InstOp) {
	if w.counting {
		w.count++
		if opcodeBacktracks(op) {
			w.trackcount++
		}
		return
	}
	w.emitted[w.curpos] = int(op)
	w.curpos++
}
840562
func (l *FormatWriterPlain) Emit(logger *Logger, level int, message string, extra Map) {
	sb := bufPool.Get()
	defer bufPool.Put(sb)

	flags := logger.Flags()

	// if time is being logged, handle time as soon as possible
	if flags&(Ltimestamp|Ltai64n) != 0 {
		t := time.Now()
		if flags&Ltai64n != 0 {
			writeTimeTAI64N(sb, &t, flags)
		} else {
			writeTime(sb, &t, flags)
		}
		sb.WriteByte(' ')
	}

	if flags&Llevel != 0 {
		switch level {
		case -1:
			sb.WriteString(`DEBUG `)
		case 1:
			sb.WriteString(`FATAL `)
		default:
			sb.WriteString(`INFO  `)
		}
	}

	if flags&(Lshortfile|Llongfile) != 0 {
		_, file, line, ok := runtime.Caller(3)
		if !ok {
			file = "???"
			line = 0
		}

		if flags&Lshortfile != 0 {
			short := file
			for i := len(file) - 1; i > 0; i-- {
				if file[i] == '/' {
					short = file[i+1:]
					break
				}
			}
			file = short
		}

		sb.WriteString(file)
		sb.WriteByte(':')
		sb.AppendIntWidth(line, 0)
		sb.WriteByte(' ')
	}

	encodeStringPlain(sb, message)

	if extra != nil && len(extra) > 0 {
		sb.WriteByte(' ')
		if flags&Lsort != 0 {
			extra.sortedWriteBuf(sb)
		} else {
			extra.unsortedWriteBuf(sb)
		}
	}

	sb.WriteByte('\n')
	sb.WriteTo(logger)
}
964324
func (l *lexer) emit(t tokenType) {
	l.tokens <- token{
		t,
		l.input[l.start:l.pos],
		l.lineNum(),
		l.columnNum(),
	}
	l.start = l.pos
}
297796
func emit(final bool) error {
	if !enabled {
		return fmt.Errorf("telemetry not enabled")
	}

	// some metrics are updated/set at time of emission
	setEmitTimeMetrics()

	// ensure only one update happens at a time;
	// skip update if previous one still in progress
	updateMu.Lock()
	if updating {
		updateMu.Unlock()
		log.Println("[NOTICE] Skipping this telemetry update because previous one is still working")
		return nil
	}
	updating = true
	updateMu.Unlock()
	defer func() {
		updateMu.Lock()
		updating = false
		updateMu.Unlock()
	}()

	// terminate any pending update if this is the last one
	if final {
		stopUpdateTimer()
	}

	payloadBytes, err := makePayloadAndResetBuffer()
	if err != nil {
		return err
	}

	// this will hold the server's reply
	var reply Response

	// transmit the payload - use a loop to retry in case of failure
	for i := 0; i < 4; i++ {
		if i > 0 && err != nil {
			// don't hammer the server; first failure might have been
			// a fluke, but back off more after that
			log.Printf("[WARNING] Sending telemetry (attempt %d): %v - backing off and retrying", i, err)
			time.Sleep(time.Duration((i+1)*(i+1)*(i+1)) * time.Second)
		}

		// send it
		var resp *http.Response
		resp, err = httpClient.Post(endpoint+instanceUUID.String(), "application/json", bytes.NewReader(payloadBytes))
		if err != nil {
			continue
		}

		// check for any special-case response codes
		if resp.StatusCode == http.StatusGone {
			// the endpoint has been deprecated and is no longer servicing clients
			err = fmt.Errorf("telemetry server replied with HTTP %d; upgrade required", resp.StatusCode)
			if clen := resp.Header.Get("Content-Length"); clen != "0" && clen != "" {
				bodyBytes, readErr := ioutil.ReadAll(resp.Body)
				if readErr != nil {
					log.Printf("[ERROR] Reading response body from server: %v", readErr)
				}
				err = fmt.Errorf("%v - %s", err, bodyBytes)
			}
			resp.Body.Close()
			reply.Stop = true
			break
		}
		if resp.StatusCode == http.StatusUnavailableForLegalReasons {
			// the endpoint is unavailable, at least to this client, for legal reasons (!)
			err = fmt.Errorf("telemetry server replied with HTTP %d %s: please consult the project website and developers for guidance", resp.StatusCode, resp.Status)
			if clen := resp.Header.Get("Content-Length"); clen != "0" && clen != "" {
				bodyBytes, readErr := ioutil.ReadAll(resp.Body)
				if readErr != nil {
					log.Printf("[ERROR] Reading response body from server: %v", readErr)
				}
				err = fmt.Errorf("%v - %s", err, bodyBytes)
			}
			resp.Body.Close()
			reply.Stop = true
			break
		}

		// okay, ensure we can interpret the response
		if ct := resp.Header.Get("Content-Type"); (resp.StatusCode < 300 || resp.StatusCode >= 400) &&
			!strings.Contains(ct, "json") {
			err = fmt.Errorf("telemetry server replied with unknown content-type: '%s' and HTTP %s", ct, resp.Status)
			resp.Body.Close()
			continue
		}

		// read the response body
		err = json.NewDecoder(resp.Body).Decode(&reply)
		resp.Body.Close() // close response body as soon as we're done with it
		if err != nil {
			continue
		}

		// update the list of enabled/disabled keys, if any
		for _, key := range reply.EnableKeys {
			disabledMetricsMu.Lock()
			// only re-enable this metric if it is temporarily disabled
			if temp, ok := disabledMetrics[key]; ok && temp {
				delete(disabledMetrics, key)
			}
			disabledMetricsMu.Unlock()
		}
		for _, key := range reply.DisableKeys {
			disabledMetricsMu.Lock()
			disabledMetrics[key] = true // all remotely-disabled keys are "temporarily" disabled
			disabledMetricsMu.Unlock()
		}

		// make sure we didn't send the update too soon; if so,
		// just wait and try again -- this is a special case of
		// error that we handle differently, as you can see
		if resp.StatusCode == http.StatusTooManyRequests {
			if reply.NextUpdate <= 0 {
				raStr := resp.Header.Get("Retry-After")
				if ra, err := strconv.Atoi(raStr); err == nil {
					reply.NextUpdate = time.Duration(ra) * time.Second
				}
			}
			if !final {
				log.Printf("[NOTICE] Sending telemetry: we were too early; waiting %s before trying again", reply.NextUpdate)
				time.Sleep(reply.NextUpdate)
				continue
			}
		} else if resp.StatusCode >= 400 {
			err = fmt.Errorf("telemetry server returned status code %d", resp.StatusCode)
			continue
		}

		break
	}
	if err == nil && !final {
		// (remember, if there was an error, we return it
		// below, so it WILL get logged if it's supposed to)
		log.Println("[INFO] Sending telemetry: success")
	}

	// even if there was an error after all retries, we should
	// schedule the next update using our default update
	// interval because the server might be healthy later

	// ensure we won't slam the telemetry server; add a little variance
	if reply.NextUpdate < 1*time.Second {
		reply.NextUpdate = defaultUpdateInterval + time.Duration(rand.Int63n(int64(1*time.Minute)))
	}

	// schedule the next update (if this wasn't the last one and
	// if the remote server didn't tell us to stop sending)
	if !final && !reply.Stop {
		updateTimerMu.Lock()
		updateTimer = time.AfterFunc(reply.NextUpdate, func() {
			logEmit(false)
		})
		updateTimerMu.Unlock()
	}

	return err
}