// process device events and asynchronous errors
// (implements XpcEventHandler)
975759
func (d *device) HandleXpcEvent(event xpc.Dict, err error) {
	if err != nil {
		log.Println("error:", err)
		return
	}

	id := event.MustGetInt("kCBMsgId")
	args := event.MustGetDict("kCBMsgArgs")
	//log.Printf(">> %d, %v", id, args)

	switch id {
	case // device event
		6,  // StateChanged
		16, // AdvertisingStarted
		17, // AdvertisingStopped
		18: // ServiceAdded
		d.rspc <- message{id: id, args: args}

	case
		19, // ReadRequest
		20, // WriteRequest
		21, // Subscribe
		22, // Unubscribe
		23: // Confirmation
		d.respondToRequest(id, args)

	case peripheralDiscovered:
		xa := args.MustGetDict("kCBMsgArgAdvertisementData")
		if len(xa) == 0 {
			return
		}
		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
		a := &Advertisement{
			LocalName:        xa.GetString("kCBAdvDataLocalName", args.GetString("kCBMsgArgName", "")),
			TxPowerLevel:     xa.GetInt("kCBAdvDataTxPowerLevel", 0),
			ManufacturerData: xa.GetBytes("kCBAdvDataManufacturerData", nil),
		}

		rssi := args.MustGetInt("kCBMsgArgRssi")

		if xu, ok := xa["kCBAdvDataServiceUUIDs"]; ok {
			for _, xs := range xu.(xpc.Array) {
				s := UUID{reverse(xs.([]byte))}
				a.Services = append(a.Services, s)
			}
		}
		if xsds, ok := xa["kCBAdvDataServiceData"]; ok {
			xsd := xsds.(xpc.Array)
			for i := 0; i < len(xsd); i += 2 {
				sd := ServiceData{
					UUID: UUID{xsd[i].([]byte)},
					Data: xsd[i+1].([]byte),
				}
				a.ServiceData = append(a.ServiceData, sd)
			}
		}
		if d.peripheralDiscovered != nil {
			go d.peripheralDiscovered(&peripheral{id: xpc.UUID(u.b), d: d}, a, rssi)
		}

	case peripheralConnected:
		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
		p := &peripheral{
			id:    xpc.UUID(u.b),
			d:     d,
			reqc:  make(chan message),
			rspc:  make(chan message),
			quitc: make(chan struct{}),
			sub:   newSubscriber(),
		}
		d.plistmu.Lock()
		d.plist[u.String()] = p
		d.plistmu.Unlock()
		go p.loop()

		if d.peripheralConnected != nil {
			go d.peripheralConnected(p, nil)
		}

	case peripheralDisconnected:
		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
		d.plistmu.Lock()
		p := d.plist[u.String()]
		delete(d.plist, u.String())
		d.plistmu.Unlock()
		if d.peripheralDisconnected != nil {
			d.peripheralDisconnected(p, nil) // TODO: Get Result as error?
		}
		close(p.quitc)

	case // Peripheral events
		rssiRead,
		serviceDiscovered,
		includedServicesDiscovered,
		characteristicsDiscovered,
		characteristicRead,
		characteristicWritten,
		notificationValueSet,
		descriptorsDiscovered,
		descriptorRead,
		descriptorWritten:

		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
		d.plistmu.Lock()
		p := d.plist[u.String()]
		d.plistmu.Unlock()
		p.rspc <- message{id: id, args: args}

	default:
		log.Printf("Unhandled event: %#v", event)
	}
}
851204
func WaitEventTimeout(timeout int) Event {
	var cevent CEvent
	_event := (*C.SDL_Event)(unsafe.Pointer(&cevent))
	ok := int(C.SDL_WaitEventTimeout(_event, C.int(timeout)))
	if ok == 0 {
		return nil
	}
	return goEvent(&cevent)
}
260617
func _() {
	var _ Event = (*Absolute)(nil)        // assert *Absolute implements Event
	var _ Event = (*FAbsolute)(nil)       // assert *FAbsolute implements Event
	var _ Event = (*Gauge)(nil)           // assert *Gauge implements Event
	var _ Event = (*FGauge)(nil)          // assert *FGauge implements Event
	var _ Event = (*GaugeDelta)(nil)      // assert *GaugeDelta implements Event
	var _ Event = (*FGaugeDelta)(nil)     // assert *FGaugeDelta implements Event
	var _ Event = (*Increment)(nil)       // assert *Increment implements Event
	var _ Event = (*PrecisionTiming)(nil) // assert *PrecisionTiming implements Event
	var _ Event = (*Timing)(nil)          // assert *Timing implements Event
	var _ Event = (*Total)(nil)           // assert *Total implements Event
}
201665
func (a *Application) QueueEvent(event tcell.Event) *Application {
	a.events <- event
	return a
}
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)
	}
}
94361
func (e *Executor) ProcessEvent(id string, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
	switch et {
	case libcontainerdtypes.EventExit:
		deleteTaskAndContainer(context.Background(), e.client, id, nil)
		return e.exitHandler.HandleExitEvent(ei.ContainerID)
	}
	return nil
}
180896
func AsyncEvents(e EventStream) EventStream {
	s := &asyncEventStream{
		e:      e,
		events: make(chan Event, 100),
	}
	go s.start()
	return s
}
995338
func (a *CellView) HandleEvent(e tcell.Event) bool {
	if a.model == nil {
		return false
	}
	switch e := e.(type) {
	case *tcell.EventKey:
		switch e.Key() {
		case tcell.KeyUp, tcell.KeyCtrlP:
			a.keyUp()
			return true
		case tcell.KeyDown, tcell.KeyCtrlN:
			a.keyDown()
			return true
		case tcell.KeyRight, tcell.KeyCtrlF:
			a.keyRight()
			return true
		case tcell.KeyLeft, tcell.KeyCtrlB:
			a.keyLeft()
			return true
		case tcell.KeyPgDn:
			a.keyPgDn()
			return true
		case tcell.KeyPgUp:
			a.keyPgUp()
			return true
		case tcell.KeyEnd:
			a.keyEnd()
			return true
		case tcell.KeyHome:
			a.keyHome()
			return true
		}
	}
	return false
}
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
}
645670
func (b *bufferedBackend) processEvents(events []*auditinternal.Event) {
	if len(events) == 0 {
		return
	}

	// TODO(audit): Should control the number of active goroutines
	// if one goroutine takes 5 seconds to finish, the number of goroutines can be 5 * defaultBatchThrottleQPS
	if b.throttle != nil {
		b.throttle.Accept()
	}

	if b.asyncDelegate {
		b.wg.Add(1)
		go func() {
			defer b.wg.Done()
			defer runtime.HandleCrash()

			// Execute the real processing in a goroutine to keep it from blocking.
			// This lets the batching routine continue draining the queue immediately.
			b.delegateBackend.ProcessEvents(events...)
		}()
	} else {
		func() {
			defer runtime.HandleCrash()

			// Execute the real processing in a goroutine to keep it from blocking.
			// This lets the batching routine continue draining the queue immediately.
			b.delegateBackend.ProcessEvents(events...)
		}()
	}
}
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)
}
1352464
func (f *processState) Process(event Event) {
	switch event.Name {
	// Ready event means Teleport has started successfully.
	case TeleportReadyEvent:
		atomic.StoreInt64(&f.currentState, stateOK)
		f.process.Infof("Detected that service started and joined the cluster successfully.")
	// If a degraded event was received, always change the state to degraded.
	case TeleportDegradedEvent:
		atomic.StoreInt64(&f.currentState, stateDegraded)
		f.process.Infof("Detected Teleport is running in a degraded state.")
	// If the current state is degraded, and a OK event has been
	// received, change the state to recovering. If the current state is
	// recovering and a OK events is received, if it's been longer
	// than the recovery time (2 time the server keep alive ttl), change
	// state to OK.
	case TeleportOKEvent:
		switch atomic.LoadInt64(&f.currentState) {
		case stateDegraded:
			atomic.StoreInt64(&f.currentState, stateRecovering)
			f.recoveryTime = f.process.Clock.Now()
			f.process.Infof("Teleport is recovering from a degraded state.")
		case stateRecovering:
			if f.process.Clock.Now().Sub(f.recoveryTime) > defaults.ServerKeepAliveTTL*2 {
				atomic.StoreInt64(&f.currentState, stateOK)
				f.process.Infof("Teleport has recovered from a degraded state.")
			}
		}
	}
}
1116704
func (ag *Agent) handleDockerEvents(events <-chan events.Message, errs <-chan error) {

	for {
		select {
		case err := <-errs:
			if err != nil && err == io.EOF {
				log.Errorf("Closing the events channel. Err: %+v", err)
				return
			}
			if err != nil && err != io.EOF {
				log.Errorf("Received error from docker events. Err: %+v", err)
			}
		case event := <-events:
			log.Debugf("Received Docker event: {%#v}\n", event)
			// process events only when LB services exist.
			if !ag.lbServiceExist() {
				continue
			}
			switch event.Status {
			case "start":
				endpointUpdReq := &master.UpdateEndpointRequest{}
				defaultHeaders := map[string]string{"User-Agent": "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"}
				cli, err := dockerclient.NewClient("unix:///var/run/docker.sock", "v1.21", nil, defaultHeaders)
				if err != nil {
					panic(err)
				}

				containerInfo, err := cli.ContainerInspect(context.Background(), event.ID)

				if err != nil {
					log.Errorf("Container Inspect failed :%s", err)
					break
				}

				if event.ID != "" {
					labelMap := getLabelsFromContainerInspect(&containerInfo)
					containerTenant := getTenantFromContainerInspect(&containerInfo)
					networkName, ipAddress, err := getEpNetworkInfoFromContainerInspect(&containerInfo)
					if err != nil {
						log.Errorf("Error getting container network info for %v.Err:%s", event.ID, err)
					}
					endpoint := getEndpointFromContainerInspect(&containerInfo)

					if ipAddress != "" {
						//Create provider info
						endpointUpdReq.IPAddress = ipAddress
						endpointUpdReq.ContainerID = event.ID
						endpointUpdReq.Tenant = containerTenant
						endpointUpdReq.Network = networkName
						endpointUpdReq.Event = "start"
						endpointUpdReq.EndpointID = endpoint
						endpointUpdReq.EPCommonName = containerInfo.Name
						endpointUpdReq.Labels = make(map[string]string)

						for k, v := range labelMap {
							endpointUpdReq.Labels[k] = v
						}
					}

					var epUpdResp master.UpdateEndpointResponse

					log.Infof("Sending Endpoint update request to master: {%+v}", endpointUpdReq)

					err = cluster.MasterPostReq("/plugin/updateEndpoint", endpointUpdReq, &epUpdResp)
					if err != nil {
						log.Errorf("Event: 'start' , Http error posting endpoint update, Error:%s", err)
					}
				} else {
					log.Errorf("Unable to fetch container labels for container %s ", event.ID)
				}
			case "die":
				endpointUpdReq := &master.UpdateEndpointRequest{}
				endpointUpdReq.ContainerID = event.ID
				endpointUpdReq.Event = "die"
				var epUpdResp master.UpdateEndpointResponse
				log.Infof("Sending Endpoint update request to master: {%+v} on container delete", endpointUpdReq)
				err := cluster.MasterPostReq("/plugin/updateEndpoint", endpointUpdReq, &epUpdResp)
				if err != nil {
					log.Errorf("Event:'die' Http error posting endpoint update, Error:%s", err)
				}
			}
		}
	}
}
1342357
func (c *Callbacks) OnCUserMessageAchievementEvent(fn func(*dota.CUserMessageAchievementEvent) error) {
	c.onCUserMessageAchievementEvent = append(c.onCUserMessageAchievementEvent, fn)
}
1262777
func (d *DockerMonitor) eventProcessors(ctx context.Context) {

	for i := 0; i < d.numberOfQueues; i++ {
		go func(i int) {
			for {
				select {
				case event := <-d.eventnotifications[i]:
					if f, ok := d.handlers[Event(event.Action)]; ok {
						if err := f(ctx, event); err != nil {
							zap.L().Error("Unable to handle docker event",
								zap.String("action", event.Action),
								zap.Error(err),
							)
						}
						continue
					}
				case <-ctx.Done():
					return
				}
			}
		}(i)
	}
}
412509
func (a *Agent) shouldProcessUserEvent(msg *UserEvent) bool {
	// Check the version
	if msg.Version > userEventMaxVersion {
		a.logger.Printf("[WARN] agent: Event version %d may have unsupported features (%s)",
			msg.Version, msg.Name)
	}

	// Apply the filters
	if msg.NodeFilter != "" {
		re, err := regexp.Compile(msg.NodeFilter)
		if err != nil {
			a.logger.Printf("[ERR] agent: Failed to parse node filter '%s' for event '%s': %v",
				msg.NodeFilter, msg.Name, err)
			return false
		}
		if !re.MatchString(a.config.NodeName) {
			return false
		}
	}

	if msg.ServiceFilter != "" {
		re, err := regexp.Compile(msg.ServiceFilter)
		if err != nil {
			a.logger.Printf("[ERR] agent: Failed to parse service filter '%s' for event '%s': %v",
				msg.ServiceFilter, msg.Name, err)
			return false
		}

		var tagRe *regexp.Regexp
		if msg.TagFilter != "" {
			re, err := regexp.Compile(msg.TagFilter)
			if err != nil {
				a.logger.Printf("[ERR] agent: Failed to parse tag filter '%s' for event '%s': %v",
					msg.TagFilter, msg.Name, err)
				return false
			}
			tagRe = re
		}

		// Scan for a match
		services := a.State.Services()
		found := false
	OUTER:
		for name, info := range services {
			// Check the service name
			if !re.MatchString(name) {
				continue
			}
			if tagRe == nil {
				found = true
				break
			}

			// Look for a matching tag
			for _, tag := range info.Tags {
				if !tagRe.MatchString(tag) {
					continue
				}
				found = true
				break OUTER
			}
		}

		// No matching services
		if !found {
			return false
		}
	}
	return true
}
671586
func processEventQueue(xu *xgbutil.XUtil, pingBefore, pingAfter chan struct{}) {
	for !Empty(xu) {
		if Quitting(xu) {
			return
		}

		// We send the ping *before* the next event is dequeued.
		// This is so the queue doesn't present a misrepresentation of which
		// events haven't been processed yet.
		if pingBefore != nil && pingAfter != nil {
			pingBefore <- struct{}{}
		}
		ev, err := Dequeue(xu)

		// If we gobbled up an error, send it to the error event handler
		// and move on the next event/error.
		if err != nil {
			ErrorHandlerGet(xu)(err)
			if pingBefore != nil && pingAfter != nil {
				pingAfter <- struct{}{}
			}
			continue
		}

		// We know there isn't an error. If there isn't an event either,
		// then there's a bug somewhere.
		if ev == nil {
			xgbutil.Logger.Fatal("BUG: Expected an event but got nil.")
		}

		hooks := getHooks(xu)
		for _, hook := range hooks {
			if !hook.Run(xu, ev) {
				goto END
			}
		}

		switch event := ev.(type) {
		case xproto.KeyPressEvent:
			e := KeyPressEvent{&event}

			// If we're redirecting key events, this is the place to do it!
			if wid := RedirectKeyGet(xu); wid > 0 {
				e.Event = wid
			}

			xu.TimeSet(e.Time)
			runCallbacks(xu, e, KeyPress, e.Event)
		case xproto.KeyReleaseEvent:
			e := KeyReleaseEvent{&event}

			// If we're redirecting key events, this is the place to do it!
			if wid := RedirectKeyGet(xu); wid > 0 {
				e.Event = wid
			}

			xu.TimeSet(e.Time)
			runCallbacks(xu, e, KeyRelease, e.Event)
		case xproto.ButtonPressEvent:
			e := ButtonPressEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, ButtonPress, e.Event)
		case xproto.ButtonReleaseEvent:
			e := ButtonReleaseEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, ButtonRelease, e.Event)
		case xproto.MotionNotifyEvent:
			e := MotionNotifyEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, MotionNotify, e.Event)
		case xproto.EnterNotifyEvent:
			e := EnterNotifyEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, EnterNotify, e.Event)
		case xproto.LeaveNotifyEvent:
			e := LeaveNotifyEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, LeaveNotify, e.Event)
		case xproto.FocusInEvent:
			e := FocusInEvent{&event}
			runCallbacks(xu, e, FocusIn, e.Event)
		case xproto.FocusOutEvent:
			e := FocusOutEvent{&event}
			runCallbacks(xu, e, FocusOut, e.Event)
		case xproto.KeymapNotifyEvent:
			e := KeymapNotifyEvent{&event}
			runCallbacks(xu, e, KeymapNotify, NoWindow)
		case xproto.ExposeEvent:
			e := ExposeEvent{&event}
			runCallbacks(xu, e, Expose, e.Window)
		case xproto.GraphicsExposureEvent:
			e := GraphicsExposureEvent{&event}
			runCallbacks(xu, e, GraphicsExposure, xproto.Window(e.Drawable))
		case xproto.NoExposureEvent:
			e := NoExposureEvent{&event}
			runCallbacks(xu, e, NoExposure, xproto.Window(e.Drawable))
		case xproto.VisibilityNotifyEvent:
			e := VisibilityNotifyEvent{&event}
			runCallbacks(xu, e, VisibilityNotify, e.Window)
		case xproto.CreateNotifyEvent:
			e := CreateNotifyEvent{&event}
			runCallbacks(xu, e, CreateNotify, e.Parent)
		case xproto.DestroyNotifyEvent:
			e := DestroyNotifyEvent{&event}
			runCallbacks(xu, e, DestroyNotify, e.Window)
		case xproto.UnmapNotifyEvent:
			e := UnmapNotifyEvent{&event}
			runCallbacks(xu, e, UnmapNotify, e.Window)
		case xproto.MapNotifyEvent:
			e := MapNotifyEvent{&event}
			runCallbacks(xu, e, MapNotify, e.Event)
		case xproto.MapRequestEvent:
			e := MapRequestEvent{&event}
			runCallbacks(xu, e, MapRequest, e.Window)
			runCallbacks(xu, e, MapRequest, e.Parent)
		case xproto.ReparentNotifyEvent:
			e := ReparentNotifyEvent{&event}
			runCallbacks(xu, e, ReparentNotify, e.Window)
		case xproto.ConfigureNotifyEvent:
			e := ConfigureNotifyEvent{&event}
			runCallbacks(xu, e, ConfigureNotify, e.Window)
		case xproto.ConfigureRequestEvent:
			e := ConfigureRequestEvent{&event}
			runCallbacks(xu, e, ConfigureRequest, e.Window)
			runCallbacks(xu, e, ConfigureRequest, e.Parent)
		case xproto.GravityNotifyEvent:
			e := GravityNotifyEvent{&event}
			runCallbacks(xu, e, GravityNotify, e.Window)
		case xproto.ResizeRequestEvent:
			e := ResizeRequestEvent{&event}
			runCallbacks(xu, e, ResizeRequest, e.Window)
		case xproto.CirculateNotifyEvent:
			e := CirculateNotifyEvent{&event}
			runCallbacks(xu, e, CirculateNotify, e.Window)
		case xproto.CirculateRequestEvent:
			e := CirculateRequestEvent{&event}
			runCallbacks(xu, e, CirculateRequest, e.Window)
		case xproto.PropertyNotifyEvent:
			e := PropertyNotifyEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, PropertyNotify, e.Window)
		case xproto.SelectionClearEvent:
			e := SelectionClearEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, SelectionClear, e.Owner)
		case xproto.SelectionRequestEvent:
			e := SelectionRequestEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, SelectionRequest, e.Requestor)
		case xproto.SelectionNotifyEvent:
			e := SelectionNotifyEvent{&event}
			xu.TimeSet(e.Time)
			runCallbacks(xu, e, SelectionNotify, e.Requestor)
		case xproto.ColormapNotifyEvent:
			e := ColormapNotifyEvent{&event}
			runCallbacks(xu, e, ColormapNotify, e.Window)
		case xproto.ClientMessageEvent:
			e := ClientMessageEvent{&event}
			runCallbacks(xu, e, ClientMessage, e.Window)
		case xproto.MappingNotifyEvent:
			e := MappingNotifyEvent{&event}
			runCallbacks(xu, e, MappingNotify, NoWindow)
		case shape.NotifyEvent:
			e := ShapeNotifyEvent{&event}
			runCallbacks(xu, e, ShapeNotify, e.AffectedWindow)
		default:
			if event != nil {
				xgbutil.Logger.Printf("ERROR: UNSUPPORTED EVENT TYPE: %T",
					event)
			}
		}

	END:

		if pingBefore != nil && pingAfter != nil {
			pingAfter <- struct{}{}
		}
	}
}