// handleUserEvent is called when a user event broadcast is
// received. Returns if the message should be rebroadcast.
435758
func (s *Serf) handleUserEvent(eventMsg *messageUserEvent) bool {
	// Witness a potentially newer time
	s.eventClock.Witness(eventMsg.LTime)

	s.eventLock.Lock()
	defer s.eventLock.Unlock()

	// Ignore if it is before our minimum event time
	if eventMsg.LTime < s.eventMinTime {
		return false
	}

	// Check if this message is too old
	curTime := s.eventClock.Time()
	if curTime > LamportTime(len(s.eventBuffer)) &&
		eventMsg.LTime < curTime-LamportTime(len(s.eventBuffer)) {
		s.logger.Printf(
			"[WARN] serf: received old event %s from time %d (current: %d)",
			eventMsg.Name,
			eventMsg.LTime,
			s.eventClock.Time())
		return false
	}

	// Check if we've already seen this
	idx := eventMsg.LTime % LamportTime(len(s.eventBuffer))
	seen := s.eventBuffer[idx]
	userEvent := userEvent{Name: eventMsg.Name, Payload: eventMsg.Payload}
	if seen != nil && seen.LTime == eventMsg.LTime {
		for _, previous := range seen.Events {
			if previous.Equals(&userEvent) {
				return false
			}
		}
	} else {
		seen = &userEvents{LTime: eventMsg.LTime}
		s.eventBuffer[idx] = seen
	}

	// Add to recent events
	seen.Events = append(seen.Events, userEvent)

	// Update some metrics
	metrics.IncrCounter([]string{"serf", "events"}, 1)
	metrics.IncrCounter([]string{"serf", "events", eventMsg.Name}, 1)

	if s.config.EventCh != nil {
		s.config.EventCh <- UserEvent{
			LTime:    eventMsg.LTime,
			Name:     eventMsg.Name,
			Payload:  eventMsg.Payload,
			Coalesce: eventMsg.CC,
		}
	}
	return true
}
495625
func (a *Agent) UserEvents() []*UserEvent {
	n := len(a.eventBuf)
	out := make([]*UserEvent, n)
	a.eventLock.RLock()
	defer a.eventLock.RUnlock()

	// Check if the buffer is full
	if a.eventBuf[a.eventIndex] != nil {
		if a.eventIndex == 0 {
			copy(out, a.eventBuf)
		} else {
			copy(out, a.eventBuf[a.eventIndex:])
			copy(out[n-a.eventIndex:], a.eventBuf[:a.eventIndex])
		}
	} else {
		// We haven't filled the buffer yet
		copy(out, a.eventBuf[:a.eventIndex])
		out = out[:a.eventIndex]
	}
	return out
}
790123
func (w *Watcher) handleEvent(data []byte) {
	buf := bytes.NewBuffer(data)
	msg := &cnMsg{}
	hdr := &procEventHeader{}

	binary.Read(buf, byteOrder, msg)
	binary.Read(buf, byteOrder, hdr)

	switch hdr.What {
	case PROC_EVENT_FORK:
		event := &forkProcEvent{}
		binary.Read(buf, byteOrder, event)
		ppid := int(event.ParentTgid)
		pid := int(event.ChildTgid)

		if w.isWatching(ppid, PROC_EVENT_EXEC) {
			// follow forks
			watch, _ := w.watches[ppid]
			w.Watch(pid, watch.flags)
		}

		if w.isWatching(ppid, PROC_EVENT_FORK) {
			w.Fork <- &ProcEventFork{ParentPid: ppid, ChildPid: pid}
		}
	case PROC_EVENT_EXEC:
		event := &execProcEvent{}
		binary.Read(buf, byteOrder, event)
		pid := int(event.ProcessTgid)

		if w.isWatching(pid, PROC_EVENT_EXEC) {
			w.Exec <- &ProcEventExec{Pid: pid}
		}
	case PROC_EVENT_EXIT:
		event := &exitProcEvent{}
		binary.Read(buf, byteOrder, event)
		pid := int(event.ProcessTgid)

		if w.isWatching(pid, PROC_EVENT_EXIT) {
			w.RemoveWatch(pid)
			w.Exit <- &ProcEventExit{Pid: pid}
		}
	}
}
1120519
func (c *Collector) handleEvent(event events.Event) {
	switch event.(type) {
	case api.EventNode:
		c.handleNodeEvent(event)
	case api.EventTask:
		c.handleTaskEvent(event)
	case api.EventService:
		c.handleServiceEvent(event)
	case api.EventNetwork:
		c.handleNetworkEvent(event)
	case api.EventSecret:
		c.handleSecretsEvent(event)
	case api.EventConfig:
		c.handleConfigsEvent(event)
	}
}
769544
func (menu *Menu) HandleEvent(reply CommandResponse) {
	for _, item := range menu.Items {
		if reply.Event.CommandID == item.CommandID {
			Log.Print("Menu(", menu.TargetID, "):: Handling Event", item.CommandID, "::Handled With Flags", reply.Event.EventFlags, "With Type", item.Type)
			handler, ok := menu.ReplyHandlers[item.CommandID]
			if ok {
				handler(reply, item)
			} else {
				item.HandleEvent()
			}
			return
		}
	}
}
684315
func (m *Memberlist) handleUser(buf []byte, from net.Addr) {
	d := m.config.Delegate
	if d != nil {
		d.NotifyMsg(buf)
	}
}
1223275
func (c *DropMenu) HandleEvent(event termbox.Event) bool {
	moveUp := (event.Key == termbox.KeyArrowUp || (c.menu.vimMode && event.Ch == 'k'))
	moveDown := (event.Key == termbox.KeyArrowDown || (c.menu.vimMode && event.Ch == 'j'))
	if c.menuSelected {
		selIdx := c.menu.GetSelectedIndex()
		if (moveUp && selIdx == 0) || (moveDown && selIdx == (len(c.menu.options)-1)) {
			c.menuSelected = false
		} else {
			if c.menu.HandleEvent(event) {
				if c.menu.IsDone() {
					c.HideMenu()
				}
				return true
			}
		}
	} else {
		c.ShowMenu()
		return true
	}
	return false
}
1179151
func handleMemberEvent(logger *log.Logger, fn routerFn, areaID types.AreaID, e serf.Event) {
	me, ok := e.(serf.MemberEvent)
	if !ok {
		logger.Printf("[ERR] consul: Bad event type %#v", e)
		return
	}

	for _, m := range me.Members {
		ok, parts := metadata.IsConsulServer(m)
		if !ok {
			logger.Printf("[WARN]: consul: Non-server %q in server-only area %q",
				m.Name, areaID)
			continue
		}

		if err := fn(areaID, parts); err != nil {
			logger.Printf("[ERR] consul: Failed to process %s event for server %q in area %q: %v",
				me.Type.String(), m.Name, areaID, err)
			continue
		}

		logger.Printf("[INFO] consul: Handled %s event for server %q in area %q",
			me.Type.String(), m.Name, areaID)
	}
}
1371733
func (c *Menu) HandleEvent(event termbox.Event) bool {
	if event.Key == termbox.KeyEnter || event.Key == termbox.KeySpace {
		c.isDone = true
		return true
	}
	currentIdx := c.GetSelectedIndex()
	switch event.Key {
	case termbox.KeyArrowUp:
		c.SelectPrevOption()
	case termbox.KeyArrowDown:
		c.SelectNextOption()
	case termbox.KeyArrowLeft:
		c.SelectPageUpOption()
	case termbox.KeyArrowRight:
		c.SelectPageDownOption()
	}
	if c.vimMode {
		switch event.Ch {
		case 'j':
			c.SelectNextOption()
		case 'k':
			c.SelectPrevOption()
		}
		if event.Key == termbox.KeyCtrlF {
			c.SelectPageDownOption()
		} else if event.Key == termbox.KeyCtrlB {
			c.SelectPageUpOption()
		}
	}
	if c.GetSelectedIndex() != currentIdx {
		return true
	}
	return false
}
1080756
func handleDieEvent(engine *OrcEngine, event *adoc.Event) {
	actor := event.Actor
	if name, ok := actor.Attributes["name"]; ok {
		if pgname, _, instance, _, err := util.ParseContainerName(name); err == nil {
			engine.RLock()
			pgCtrl, ok := engine.pgCtrls[pgname]
			engine.RUnlock()
			if !ok {
				return
			}
			pgCtrl.RLock()
			spec := pgCtrl.spec.Clone()
			pgCtrl.RUnlock()
			if atomic.LoadInt32((*int32)(&pgCtrl.opState)) != PGOpStateUpgrading {
				log.Warnf("got %s event from %s, refresh this instance", event.Status, name)
				pgCtrl.opsChan <- pgOperRefreshInstance{instance, spec}
			}
		}
	}
}
403448
func (a *Agent) ingestUserEvent(msg *UserEvent) {
	// Special handling for internal events
	switch msg.Name {
	case remoteExecName:
		if a.config.DisableRemoteExec {
			a.logger.Printf("[INFO] agent: ignoring remote exec event (%s), disabled.", msg.ID)
		} else {
			go a.handleRemoteExec(msg)
		}
		return
	default:
		a.logger.Printf("[DEBUG] agent: new event: %s (%s)", msg.Name, msg.ID)
	}

	a.eventLock.Lock()
	defer func() {
		a.eventLock.Unlock()
		a.eventNotify.Notify()
	}()

	idx := a.eventIndex
	a.eventBuf[idx] = msg
	a.eventIndex = (idx + 1) % len(a.eventBuf)
}
895475
func (p *Parser) handleEvent(ptp *perThreadParser, rawE []string) (
	map[string]interface{}, time.Time) {
	sq := map[string]interface{}{}
	if len(rawE) == 0 {
		return sq, time.Time{}
	}
	var (
		timeFromComment time.Time
		timeFromSet     int64
		query           = ""
	)
	for _, line := range rawE {
		// parse each line and populate the map of attributes
		if _, mg := reTime.FindStringSubmatchMap(line); mg != nil {
			timeFromComment, _ = httime.Parse(timeFormat, mg["time"])
		} else if _, mg := reOldTime.FindStringSubmatchMap(line); mg != nil {
			timeFromComment, _ = httime.Parse(oldTimeFormat, mg["datetime"])
		} else if reAdminPing.MatchString(line) {
			// this event is an administrative ping and we should
			// ignore the entire event
			logrus.WithFields(logrus.Fields{
				"line":  line,
				"event": rawE,
			}).Debug("readmin ping detected; skipping this event")
			return nil, time.Time{}
		} else if _, mg := reUser.FindStringSubmatchMap(line); mg != nil {
			query = ""
			sq[userKey] = strings.Split(mg["user"], "[")[0]
			sq[clientKey] = strings.TrimSpace(mg["host"])
		} else if _, mg := reQueryStats.FindStringSubmatchMap(line); mg != nil {
			query = ""
			if queryTime, err := strconv.ParseFloat(mg["queryTime"], 64); err == nil {
				sq[queryTimeKey] = queryTime
			}
			if lockTime, err := strconv.ParseFloat(mg["lockTime"], 64); err == nil {
				sq[lockTimeKey] = lockTime
			}
			if rowsSent, err := strconv.Atoi(mg["rowsSent"]); err == nil {
				sq[rowsSentKey] = rowsSent
			}
			if rowsExamined, err := strconv.Atoi(mg["rowsExamined"]); err == nil {
				sq[rowsExaminedKey] = rowsExamined
			}
			if rowsAffected, err := strconv.Atoi(mg["rowsAffected"]); err == nil {
				sq[rowsAffectedKey] = rowsAffected
			}
		} else if _, mg := reTCPQueryStats.FindStringSubmatchMap(line); mg != nil {
			query = ""
			if queryTime, err := strconv.ParseFloat(mg["queryTime"], 64); err == nil {
				sq[queryTimeKey] = queryTime
			}
		} else if _, mg := reServStats.FindStringSubmatchMap(line); mg != nil {
			query = ""
			if bytesSent, err := strconv.Atoi(mg["bytesSent"]); err == nil {
				sq[bytesSentKey] = bytesSent
			}
			if tmpTables, err := strconv.Atoi(mg["tmpTables"]); err == nil {
				sq[tmpTablesKey] = tmpTables
			}
			if tmpDiskTables, err := strconv.Atoi(mg["tmpDiskTables"]); err == nil {
				sq[tmpDiskTablesKey] = tmpDiskTables
			}
			if tmpTableSizes, err := strconv.Atoi(mg["tmpTableSizes"]); err == nil {
				sq[tmpTableSizesKey] = tmpTableSizes
			}
		} else if _, mg := reInnodbQueryPlan1.FindStringSubmatchMap(line); mg != nil {
			sq[queryCacheHitKey] = mg["query_cache_hit"] == "Yes"
			sq[fullScanKey] = mg["full_scan"] == "Yes"
			sq[fullJoinKey] = mg["full_join"] == "Yes"
			sq[tmpTableKey] = mg["tmp_table"] == "Yes"
			sq[tmpTableOnDiskKey] = mg["tmp_table_on_disk"] == "Yes"
		} else if _, mg := reInnodbQueryPlan2.FindStringSubmatchMap(line); mg != nil {
			sq[fileSortKey] = mg["filesort"] == "Yes"
			sq[fileSortOnDiskKey] = mg["filesort_on_disk"] == "Yes"
			if mergePasses, err := strconv.Atoi(mg["merge_passes"]); err == nil {
				sq[mergePassesKey] = mergePasses
			}
		} else if _, mg := reInnodbUsage1.FindStringSubmatchMap(line); mg != nil {
			if ioROps, err := strconv.Atoi(mg["io_r_ops"]); err == nil {
				sq[ioROpsKey] = ioROps
			}
			if ioRBytes, err := strconv.Atoi(mg["io_r_bytes"]); err == nil {
				sq[ioRBytesKey] = ioRBytes
			}
			if ioRWait, err := strconv.ParseFloat(mg["io_r_wait"], 64); err == nil {
				sq[ioRWaitKey] = ioRWait
			}
		} else if _, mg := reInnodbUsage2.FindStringSubmatchMap(line); mg != nil {
			if recLockWait, err := strconv.ParseFloat(mg["rec_lock_wait"], 64); err == nil {
				sq[recLockWaitKey] = recLockWait
			}
			if queueWait, err := strconv.ParseFloat(mg["queue_wait"], 64); err == nil {
				sq[queueWaitKey] = queueWait
			}
		} else if _, mg := reInnodbUsage3.FindStringSubmatchMap(line); mg != nil {
			if pagesDistinct, err := strconv.Atoi(mg["pages_distinct"]); err == nil {
				sq[pagesDistinctKey] = pagesDistinct
			}
		} else if _, mg := reInnodbTrx.FindStringSubmatchMap(line); mg != nil {
			sq[transactionIDKey] = mg["trxId"]
		} else if match := reUse.FindString(line); match != "" {
			query = ""
			db := strings.TrimPrefix(line, match)
			db = strings.TrimRight(db, ";")
			db = strings.Trim(db, "`")
			sq[databaseKey] = db
			// Use this line as the query/normalized_query unless, if a real query follows it will be replaced.
			sq[queryKey] = strings.TrimRight(line, ";")
			sq[normalizedQueryKey] = sq[queryKey]
		} else if _, mg := reSetTime.FindStringSubmatchMap(line); mg != nil {
			query = ""
			timeFromSet, _ = strconv.ParseInt(mg["unixTime"], 10, 64)
		} else if isMySQLHeaderLine(line) {
			// ignore and skip the header lines
		} else if !strings.HasPrefix(line, "# ") {
			// treat any other line that doesn't start with '# ' as part of the
			// query
			query = query + " " + line
			if strings.HasSuffix(query, ";") {
				q := strings.TrimSpace(strings.TrimSuffix(query, ";"))
				sq[queryKey] = q
				sq[normalizedQueryKey] = ptp.normalizer.NormalizeQuery(q)
				if len(ptp.normalizer.LastTables) > 0 {
					sq[tablesKey] = strings.Join(ptp.normalizer.LastTables, " ")
				}
				if len(ptp.normalizer.LastComments) > 0 {
					sq[commentsKey] = "/* " + strings.Join(ptp.normalizer.LastComments, " */ /* ") + " */"
				}
				sq[statementKey] = ptp.normalizer.LastStatement
				query = ""
			}
		} else {
			// unknown row; log and skip
			logrus.WithFields(logrus.Fields{
				"line": line,
			}).Debug("No regex match for line in the middle of a query. skipping")
		}
	}

	// We always need a timestamp.
	//
	// timeFromComment may include millisecond resolution but doesn't include
	//   time zone.
	// timeFromSet is a UNIX timestamp and thus more reliable, but also (thus)
	//   doesn't contain millisecond resolution.
	//
	// In the best case (we have both), we combine the two; in the worst case (we
	//   have neither) we fall back to "now."
	combinedTime := httime.Now()
	if !timeFromComment.IsZero() && timeFromSet > 0 {
		nanos := time.Duration(timeFromComment.Nanosecond())
		combinedTime = time.Unix(timeFromSet, 0).Add(nanos)
	} else if !timeFromComment.IsZero() {
		combinedTime = timeFromComment // cross our fingers that UTC is ok
	} else if timeFromSet > 0 {
		combinedTime = time.Unix(timeFromSet, 0)
	}

	return sq, combinedTime
}
1107444
func (i *instanceManager) handleEvent(ev *drivers.TaskEvent) {
	// Do not emit that the plugin is shutdown
	if ev.Err != nil && ev.Err == bstructs.ErrPluginShutdown {
		return
	}

	if handler := i.eventHandlerFactory(ev.AllocID, ev.TaskName); handler != nil {
		i.logger.Trace("task event received", "event", ev)
		handler(ev)
		return
	}

	i.logger.Warn("no handler registered for event", "event", ev)
}
468770
func validateUserEventParams(params *UserEvent) error {
	// Validate the inputs
	if params.Name == "" {
		return fmt.Errorf("User event missing name")
	}
	if params.TagFilter != "" && params.ServiceFilter == "" {
		return fmt.Errorf("Cannot provide tag filter without service filter")
	}
	if params.NodeFilter != "" {
		if _, err := regexp.Compile(params.NodeFilter); err != nil {
			return fmt.Errorf("Invalid node filter: %v", err)
		}
	}
	if params.ServiceFilter != "" {
		if _, err := regexp.Compile(params.ServiceFilter); err != nil {
			return fmt.Errorf("Invalid service filter: %v", err)
		}
	}
	if params.TagFilter != "" {
		if _, err := regexp.Compile(params.TagFilter); err != nil {
			return fmt.Errorf("Invalid tag filter: %v", err)
		}
	}
	return nil
}
598481
func (es *eventStream) sendUserEvent(ue serf.UserEvent) error {
	header := responseHeader{
		Seq:   es.seq,
		Error: "",
	}
	rec := userEventRecord{
		Event:    ue.EventType().String(),
		LTime:    ue.LTime,
		Name:     ue.Name,
		Payload:  ue.Payload,
		Coalesce: ue.Coalesce,
	}
	return es.client.Send(&header, &rec)
}
664282
func (eh readyEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*Ready); ok {
		eh(s, t)
	}
}
596483
func handleEvents() {
	for {
		event, ok := <-eventsIn
		if !ok {
			log.Println()
			log.Println("Stopped event handler!")
			break
		}

		bee := GetBee(event.Bee)
		(*bee).LogEvent()

		log.Println()
		log.Println("Event received:", event.Bee, "/", event.Name, "-", GetEventDescriptor(&event).Description)
		for _, v := range event.Options {
			log.Println("\tOptions:", v)
		}

		go func() {
			defer func() {
				if e := recover(); e != nil {
					log.Printf("Fatal chain event: %s %s", e, debug.Stack())
				}
			}()

			execChains(&event)
		}()
	}
}