// processEvent processes the event by retrieving the right monitor handler.
328674
func (e *EventServer) processEvent(ctx context.Context, eventInfo *common.EventInfo) (err error) {

	if e.registerer == nil {
		return fmt.Errorf("No registered handlers")
	}

	f, err := e.registerer.GetHandler(eventInfo.PUType, eventInfo.EventType)
	if err != nil {
		return fmt.Errorf("Handler not found: %s", err)
	}

	return f(ctx, eventInfo)
}
1307542
func (w *watchCache) processEvent(event watch.Event, resourceVersion uint64, updateFunc func(*storeElement) error) error {
	key, err := w.keyFunc(event.Object)
	if err != nil {
		return fmt.Errorf("couldn't compute key: %v", err)
	}
	elem := &storeElement{Key: key, Object: event.Object}
	elem.Labels, elem.Fields, err = w.getAttrsFunc(event.Object)
	if err != nil {
		return err
	}

	watchCacheEvent := &watchCacheEvent{
		Type:            event.Type,
		Object:          elem.Object,
		ObjLabels:       elem.Labels,
		ObjFields:       elem.Fields,
		Key:             key,
		ResourceVersion: resourceVersion,
	}

	if err := func() error {
		// TODO: We should consider moving this lock below after the watchCacheEvent
		// is created. In such situation, the only problematic scenario is Replace(
		// happening after getting object from store and before acquiring a lock.
		// Maybe introduce another lock for this purpose.
		w.Lock()
		defer w.Unlock()

		previous, exists, err := w.store.Get(elem)
		if err != nil {
			return err
		}
		if exists {
			previousElem := previous.(*storeElement)
			watchCacheEvent.PrevObject = previousElem.Object
			watchCacheEvent.PrevObjLabels = previousElem.Labels
			watchCacheEvent.PrevObjFields = previousElem.Fields
		}

		w.updateCache(watchCacheEvent)
		w.resourceVersion = resourceVersion
		defer w.cond.Broadcast()

		return updateFunc(elem)
	}(); err != nil {
		return err
	}

	// Avoid calling event handler under lock.
	// This is safe as long as there is at most one call to processEvent in flight
	// at any point in time.
	if w.eventHandler != nil {
		w.eventHandler(watchCacheEvent)
	}
	return nil
}
1258676
func processServiceLBEvent(netPlugin *plugin.NetPlugin, svcLBCfg *mastercfg.CfgServiceLBState, isDelete bool) error {
	var err error
	portSpecList := []core.PortSpec{}
	portSpec := core.PortSpec{}

	serviceID := svcLBCfg.ID

	log.Infof("Recevied Process Service load balancer event {%v}", svcLBCfg)

	//create portspect list from state.
	//Ports format: servicePort:ProviderPort:Protocol
	for _, port := range svcLBCfg.Ports {

		portInfo := strings.Split(port, ":")
		if len(portInfo) != 3 {
			return errors.New("invalid Port Format")
		}
		svcPort := portInfo[0]
		provPort := portInfo[1]
		portSpec.Protocol = portInfo[2]

		sPort, _ := strconv.ParseUint(svcPort, 10, 16)
		portSpec.SvcPort = uint16(sPort)

		pPort, _ := strconv.ParseUint(provPort, 10, 16)
		portSpec.ProvPort = uint16(pPort)

		portSpecList = append(portSpecList, portSpec)
	}

	spec := &core.ServiceSpec{
		IPAddress: svcLBCfg.IPAddress,
		Ports:     portSpecList,
	}

	operStr := ""
	if isDelete {
		err = netPlugin.DeleteServiceLB(serviceID, spec)
		operStr = "delete"
	} else {
		err = netPlugin.AddServiceLB(serviceID, spec)
		operStr = "create"
	}
	if err != nil {
		log.Errorf("Service Load Balancer %s failed.Error:%s", operStr, err)
		return err
	}
	log.Infof("Service Load Balancer %s succeeded", operStr)

	return nil
}
897554
func (b *BoxLayout) HandleEvent(ev tcell.Event) bool {
	switch ev.(type) {
	case *EventWidgetContent:
		// This can only have come from one of our children.
		b.changed = true
		b.PostEventWidgetContent(b)
		return true
	}
	for _, c := range b.cells {
		if c.widget.HandleEvent(ev) {
			return true
		}
	}
	return false
}
928096
func (s *Simulator) scheduleEvent(e event) {
	if !e.eta.After(s.Now) {
		panic("event's ETA should be in the future")
	}
	heap.Push(&s.events, e)
}
851368
func (client *DockerClient) monitorEvents(monitorId int64, uri string, callback EventCallback) {
	err := client.sendRequestCallback("GET", uri, nil, nil, func(resp *http.Response) error {
		decoder := json.NewDecoder(resp.Body)
		client.monitorLock.RLock()
		_, toContinue := client.monitors[monitorId]
		client.monitorLock.RUnlock()
		for toContinue {
			var event Event
			if err := decoder.Decode(&event); err != nil {
				return err
			}
			callback(event, nil)
			client.monitorLock.RLock()
			_, toContinue = client.monitors[monitorId]
			client.monitorLock.RUnlock()
		}
		return nil
	}, nil, true)
	if err != nil && err != io.EOF {
		callback(Event{}, err)
	}
}
671260
func (b *serverBuilder) GetEventHandler(event ServerBuildEvents) *ServerBuildEventHandler {
	if handler, ok := b.buildEventHandlers[event]; ok {
		return &handler
	}
	return nil
}
80953
func (c *InputField) HandleEvent(event termbox.Event) bool {
	if event.Key == termbox.KeyBackspace || event.Key == termbox.KeyBackspace2 {
		if c.cursor+len(c.value) > 0 {
			crs := len(c.value)
			if c.cursor < 0 {
				crs = c.cursor + len(c.value)
			}
			c.value = c.value[:crs-1] + c.value[crs:]
			//c.value = c.value[:len(c.value)-1]
		}
	} else if event.Key == termbox.KeyArrowLeft {
		if c.cursor+len(c.value) > 0 {
			c.cursor--
		}
	} else if event.Key == termbox.KeyArrowRight {
		if c.cursor < 0 {
			c.cursor++
		}
	} else if event.Key == termbox.KeyCtrlU {
		// Ctrl+U Clears the Input (before the cursor)
		c.value = c.value[c.cursor+len(c.value):]
	} else {
		// Get the rune to add to our value. Space and Tab are special cases where
		// we can't use the event's rune directly
		var ch string
		switch event.Key {
		case termbox.KeySpace:
			ch = " "
		case termbox.KeyTab:
			ch = "\t"
		case termbox.KeyEnter:
			if c.multiline {
				ch = "\n"
			}
		default:
			if KeyIsAlphaNumeric(event) || KeyIsSymbol(event) {
				ch = string(event.Ch)
			}
		}

		// TODO: Handle newlines
		if c.cursor+len(c.value) == 0 {
			c.value = string(ch) + c.value
		} else if c.cursor == 0 {
			c.value = c.value + string(ch)
		} else {
			strPt1 := c.value[:(len(c.value) + c.cursor)]
			strPt2 := c.value[(len(c.value) + c.cursor):]
			c.value = strPt1 + string(ch) + strPt2
		}
	}
	return true
}
1310835
func (rs Rules) HandleEvent(ctx context.Context, e *executor.Event) error {
	return Rule(rs.Eval).HandleEvent(ctx, e)
}
766113
func processBgpEvent(netPlugin *plugin.NetPlugin, opts core.InstanceInfo, hostID string, isDelete bool) error {
	var err error

	if opts.HostLabel != hostID {
		log.Debugf("Ignoring Bgp Event on this host")
		return err
	}

	operStr := ""
	if isDelete {
		err = netPlugin.DeleteBgp(hostID)
		operStr = "delete"
	} else {
		err = netPlugin.AddBgp(hostID)
		operStr = "create"
	}
	if err != nil {
		log.Errorf("Bgp operation %s failed. Error: %s", operStr, err)
	} else {
		log.Infof("Bgp operation %s succeeded", operStr)
	}

	return err
}
751534
func ControlEvent(v interface{}) *Event {
	event := NewEvent(v)
	event.Control = true
	return event
}
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)
	}
}
130671
func (h *EventHandler) HandleEvent(ctx context.Context, event eh.Event) error {
	h.inbox <- event
	return nil
}
10420
func BeginEvent(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "beginEvent", Listener: listener}
}
1123181
func (deallocator *Deallocator) processNewEvent(ctx context.Context, event events.Event) (bool, error) {
	switch typedEvent := event.(type) {
	case api.EventDeleteTask:
		serviceID := typedEvent.Task.ServiceID

		if serviceWithCount, present := deallocator.services[serviceID]; present {
			if serviceWithCount.taskCount <= 1 {
				delete(deallocator.services, serviceID)
				return deallocator.processService(ctx, serviceWithCount.service)
			}
			serviceWithCount.taskCount--
		}

		return false, nil
	case api.EventUpdateService:
		return deallocator.processService(ctx, typedEvent.Service)
	case api.EventUpdateNetwork:
		return deallocator.processNetwork(ctx, nil, typedEvent.Network, nil)
	default:
		return false, nil
	}
}
493904
func (c *Client) SendEvent(event Event, opts ...interface{}) (res StatusMessageRes, err error) {
	return c.SendEvents([]Event{event}, opts...)
}
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
}