// handleDestroyEvent handles destroy events from Docker. It generated a "Destroy event"
426416
func (d *DockerMonitor) handleDestroyEvent(ctx context.Context, event *events.Message) error {

	puID, err := puIDFromDockerID(event.ID)
	if err != nil {
		return err
	}
	runtime := policy.NewPURuntimeWithDefaults()
	runtime.SetOptions(runtime.Options())

	err = d.config.Policy.HandlePUEvent(ctx, puID, tevents.EventDestroy, runtime)
	if err != nil {
		zap.L().Error("Failed to handle delete event",
			zap.Error(err),
		)
	}

	if err := d.netcls.DeleteCgroup(puID); err != nil {
		zap.L().Warn("Failed to clean netcls group",
			zap.String("puID", puID),
			zap.Error(err),
		)
	}

	return nil
}
1350124
func (eh resumedEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*Resumed); ok {
		eh(s, t)
	}
}
1106012
func (eh guildDeleteEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*GuildDelete); ok {
		eh(s, t)
	}
}
215755
func (h *Handler) HandleEvent(e *events.Event) {
	f := fmtPool.Get().(*formatter)
	f.buffer.Reset()
	f.emitter.Reset(&f.buffer)

	f.level = "INFO"
	f.time = e.Time
	f.message = e.Message
	f.data.args = e.Args
	f.info.Source = e.Source
	f.info.Program = h.Program
	f.info.Pid = h.Pid

	if e.Debug {
		f.level = "DEBUG"
	}

	for _, a := range e.Args {
		if err, ok := a.Value.(error); ok {
			f.level = "ERROR"
			f.info.Errors = append(f.info.Errors, makeEventError(err))
		}
	}

	(objconv.Encoder{Emitter: &f.emitter}).Encode(f.value)
	f.buffer.WriteByte('\n')

	h.mutex.Lock()
	h.Output.Write(f.buffer.b)
	h.mutex.Unlock()

	f.info.Source = ""
	f.info.Errors = f.info.Errors[:0]
	fmtPool.Put(f)
}
443266
func (ed *Dispatcher) HandleDisconnectEvent(e esdispatcher.Event) {
	evt := e.(*DisconnectEvent)

	if ed.connection == nil {
		evt.Errch <- errors.New("connection already closed")
		return
	}

	logger.Debug("Closing connection due to disconnect event...")

	ed.connection.Close()
	ed.connection = nil
	ed.setConnectedPeer(nil)

	evt.Errch <- nil
}
737863
func (d *MessagingAdapter) HandleEvent(e Event) {
	handleIf(d.flowcontroller, e)

	switch e.Type() {

	case EConnectionInit:
		d.connection = endpointDelegator{
			EConnectionRemoteOpen, EConnectionRemoteClose, EConnectionLocalOpen, EConnectionLocalClose,
			MConnectionOpening, MConnectionOpened, MConnectionClosing, MConnectionClosed,
			MConnectionError,
			func(e Event) Endpoint { return e.Connection() },
			d,
		}
		d.session = endpointDelegator{
			ESessionRemoteOpen, ESessionRemoteClose, ESessionLocalOpen, ESessionLocalClose,
			MSessionOpening, MSessionOpened, MSessionClosing, MSessionClosed,
			MSessionError,
			func(e Event) Endpoint { return e.Session() },
			d,
		}
		d.link = endpointDelegator{
			ELinkRemoteOpen, ELinkRemoteClose, ELinkLocalOpen, ELinkLocalClose,
			MLinkOpening, MLinkOpened, MLinkClosing, MLinkClosed,
			MLinkError,
			func(e Event) Endpoint { return e.Link() },
			d,
		}
		if d.Prefetch > 0 {
			d.flowcontroller = flowcontroller{window: d.Prefetch, drained: 0}
		}
		d.mhandler.HandleMessagingEvent(MStart, e)

	case EConnectionRemoteOpen:

		d.connection.HandleEvent(e)

	case EConnectionRemoteClose:
		d.connection.HandleEvent(e)
		e.Connection().Transport().CloseTail()

	case EConnectionLocalOpen, EConnectionLocalClose:
		d.connection.HandleEvent(e)

	case ESessionRemoteOpen, ESessionRemoteClose, ESessionLocalOpen, ESessionLocalClose:
		d.session.HandleEvent(e)

	case ELinkRemoteOpen:
		e.Link().Source().Copy(e.Link().RemoteSource())
		e.Link().Target().Copy(e.Link().RemoteTarget())
		d.link.HandleEvent(e)

	case ELinkRemoteClose, ELinkLocalOpen, ELinkLocalClose:
		d.link.HandleEvent(e)

	case ELinkFlow:
		if e.Link().IsSender() && e.Link().Credit() > 0 {
			d.mhandler.HandleMessagingEvent(MSendable, e)
		}

	case EDelivery:
		if e.Delivery().Link().IsReceiver() {
			d.incoming(e)
		} else {
			d.outgoing(e)
		}

	case ETransportTailClosed:
		if !e.Connection().State().RemoteClosed() { // Unexpected transport closed
			e.Transport().CloseHead() // Complete transport close, no connection close expected
		}

	case ETransportClosed:
		d.mhandler.HandleMessagingEvent(MDisconnected, e)
	}
}
1183945
func (k *k8sWatcher) handleEvent(event watch.Event) {
	var pod client.Pod
	if err := json.Unmarshal([]byte(event.Object), &pod); err != nil {
		log.Log("K8s Watcher: Couldnt unmarshal event object from pod")
		return
	}

	switch event.Type {
	case watch.Modified:
		// Pod was modified

		k.RLock()
		cache := k.pods[pod.Metadata.Name]
		k.RUnlock()

		// service could have been added, edited or removed.
		var results []*registry.Result

		if pod.Status.Phase == podRunning {
			results = k.buildPodResults(&pod, cache)
		} else {
			// passing in cache might not return all results
			results = k.buildPodResults(&pod, nil)
		}

		for _, result := range results {
			// pod isnt running
			if pod.Status.Phase != podRunning {
				result.Action = "delete"
			}
			k.next <- result
		}

		k.Lock()
		k.pods[pod.Metadata.Name] = &pod
		k.Unlock()
		return

	case watch.Deleted:
		// Pod was deleted
		// passing in cache might not return all results
		results := k.buildPodResults(&pod, nil)

		for _, result := range results {
			result.Action = "delete"
			k.next <- result
		}

		k.Lock()
		delete(k.pods, pod.Metadata.Name)
		k.Unlock()
		return
	}

}
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
}
196939
func (h *Handler) HandleEvent(e *events.Event) {
	buf := bufferPool.Get().(*buffer)
	buf.b = buf.b[:0]
	buf.b = append(buf.b, h.Prefix...)

	if fmt := h.TimeFormat; len(fmt) != 0 {
		loc := h.TimeLocation
		if loc == nil {
			loc = time.Local
		}
		buf.b = e.Time.In(loc).AppendFormat(buf.b, fmt)
		buf.b = append(buf.b, " - "...)
	}

	if len(e.Source) != 0 {
		buf.b = append(buf.b, e.Source...)
		buf.b = append(buf.b, " - "...)
	}

	buf.b = append(buf.b, e.Message...)
	buf.b = append(buf.b, '\n')

	if h.EnableArgs {
		hasError := false

		for _, a := range e.Args {
			if _, ok := a.Value.(error); ok {
				hasError = true
			} else {
				buf.b = append(buf.b, '\t')
				buf.b = append(buf.b, a.Name...)
				buf.b = append(buf.b, ':', ' ')
				fmt.Fprintf(buf, "%v\n", a.Value)
			}
		}

		if hasError {
			fmt.Fprint(buf, "\terrors:\n")

			for _, a := range e.Args {
				if err, ok := a.Value.(error); ok {
					fmt.Fprintf(buf, "\t\t- %+v\n", err)
				}
			}
		}
	}

	h.mutex.Lock()
	h.Output.Write(buf.b)
	h.mutex.Unlock()
	bufferPool.Put(buf)
}
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)
	}
}
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}
			}
		}
	}
}
1347211
func (ed *Dispatcher) HandleStopEvent(e esdispatcher.Event) {
	// Remove all registrations and close the associated event channels
	// so that the client is notified that the registration has been removed
	ed.clearConnectionRegistration()
	if ed.peerMonitorDone != nil {
		close(ed.peerMonitorDone)
		ed.peerMonitorDone = nil
	}

	ed.Dispatcher.HandleStopEvent(e)
}
31265
func (s *DirectMessageService) EventsDestroy(id string) (*http.Response, error) {
	params := struct {
		ID string `url:"id,omitempty"`
	}{id}
	apiError := new(APIError)
	resp, err := s.sling.New().Delete("events/destroy.json").QueryStruct(params).Receive(nil, apiError)
	return resp, relevantError(err, *apiError)
}
1011778
func (p *Parser) handleEvent(rawEvent []string) *event.Event {
	normalizer := normalizer.Parser{}
	if len(rawEvent) == 0 {
		return nil
	}
	firstLine := rawEvent[0]

	// First, try to parse the prefix
	match, suffix, generalMeta := parsePrefix(p.pgPrefixRegex, firstLine)
	if !match {
		// Note: this may be noisy when debug logging is turned on, since the
		// postgres general log contains lots of other statements as well.
		logrus.WithField("line", firstLine).Debug("Log line prefix didn't match expected format")
		return nil
	}

	ev := &event.Event{
		Data: make(map[string]interface{}, 0),
	}

	addFieldsToEvent(generalMeta, ev)

	// Now, parse the slow query header
	match, query, slowQueryMeta := parsePrefix(slowQueryHeaderRegex, suffix)

	if !match {
		logrus.WithField("line", firstLine).Debug("didn't find slow query header, skipping line")
		return nil
	}

	if rawDuration, ok := slowQueryMeta["duration"]; ok {
		duration, _ := strconv.ParseFloat(rawDuration, 64)
		ev.Data["duration"] = duration
	} else {
		logrus.WithField("query", query).Debug("Failed to find query duration in log line")
	}

	// Finally, concatenate the remaining text to form the query, and attempt to
	// normalize it.
	for _, line := range rawEvent[1:] {
		query += " " + strings.TrimLeft(line, " \t")
	}
	normalizedQuery := normalizer.NormalizeQuery(query)

	ev.Data["query"] = query
	ev.Data["normalized_query"] = normalizedQuery
	if len(normalizer.LastTables) > 0 {
		ev.Data["tables"] = strings.Join(normalizer.LastTables, " ")
	}
	if len(normalizer.LastComments) > 0 {
		ev.Data["comments"] = "/* " + strings.Join(normalizer.LastComments, " */ /* ") + " */"
	}

	return ev
}
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}
		}
	}
}
1192855
func (rtm *RTM) handleRawEvent(rawEvent json.RawMessage) string {
	event := &Event{}
	err := json.Unmarshal(rawEvent, event)
	if err != nil {
		rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}}
		return ""
	}

	switch event.Type {
	case rtmEventTypeAck:
		rtm.handleAck(rawEvent)
	case rtmEventTypeHello:
		rtm.IncomingEvents <- RTMEvent{"hello", &HelloEvent{}}
	case rtmEventTypePong:
		rtm.handlePong(rawEvent)
	case rtmEventTypeGoodbye:
		// just return the event type up for goodbye, will be handled by caller.
	case rtmEventTypeDesktopNotification:
		rtm.Debugln("Received desktop notification, ignoring")
	default:
		rtm.handleEvent(event.Type, rawEvent)
	}

	return event.Type
}
683371
func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
	c, err := daemon.GetContainer(id)
	if c == nil || err != nil {
		return fmt.Errorf("no such container: %s", id)
	}

	switch e {
	case libcontainerdtypes.EventOOM:
		// StateOOM is Linux specific and should never be hit on Windows
		if runtime.GOOS == "windows" {
			return errors.New("received StateOOM from libcontainerd on Windows. This should never happen")
		}

		c.Lock()
		defer c.Unlock()
		daemon.updateHealthMonitor(c)
		if err := c.CheckpointTo(daemon.containersReplica); err != nil {
			return err
		}

		daemon.LogContainerEvent(c, "oom")
	case libcontainerdtypes.EventExit:
		if int(ei.Pid) == c.Pid {
			c.Lock()
			_, _, err := daemon.containerd.DeleteTask(context.Background(), c.ID)
			if err != nil {
				logrus.WithError(err).Warnf("failed to delete container %s from containerd", c.ID)
			}

			c.StreamConfig.Wait()
			c.Reset(false)

			exitStatus := container.ExitStatus{
				ExitCode:  int(ei.ExitCode),
				ExitedAt:  ei.ExitedAt,
				OOMKilled: ei.OOMKilled,
			}
			restart, wait, err := c.RestartManager().ShouldRestart(ei.ExitCode, daemon.IsShuttingDown() || c.HasBeenManuallyStopped, time.Since(c.StartedAt))
			if err == nil && restart {
				c.RestartCount++
				c.SetRestarting(&exitStatus)
			} else {
				if ei.Error != nil {
					c.SetError(ei.Error)
				}
				c.SetStopped(&exitStatus)
				defer daemon.autoRemove(c)
			}
			defer c.Unlock() // needs to be called before autoRemove

			// cancel healthcheck here, they will be automatically
			// restarted if/when the container is started again
			daemon.stopHealthchecks(c)
			attributes := map[string]string{
				"exitCode": strconv.Itoa(int(ei.ExitCode)),
			}
			daemon.LogContainerEventWithAttributes(c, "die", attributes)
			daemon.Cleanup(c)
			daemon.setStateCounter(c)
			cpErr := c.CheckpointTo(daemon.containersReplica)

			if err == nil && restart {
				go func() {
					err := <-wait
					if err == nil {
						// daemon.netController is initialized when daemon is restoring containers.
						// But containerStart will use daemon.netController segment.
						// So to avoid panic at startup process, here must wait util daemon restore done.
						daemon.waitForStartupDone()
						if err = daemon.containerStart(c, "", "", false); err != nil {
							logrus.Debugf("failed to restart container: %+v", err)
						}
					}
					if err != nil {
						c.Lock()
						c.SetStopped(&exitStatus)
						daemon.setStateCounter(c)
						c.CheckpointTo(daemon.containersReplica)
						c.Unlock()
						defer daemon.autoRemove(c)
						if err != restartmanager.ErrRestartCanceled {
							logrus.Errorf("restartmanger wait error: %+v", err)
						}
					}
				}()
			}

			return cpErr
		}

		if execConfig := c.ExecCommands.Get(ei.ProcessID); execConfig != nil {
			ec := int(ei.ExitCode)
			execConfig.Lock()
			defer execConfig.Unlock()
			execConfig.ExitCode = &ec
			execConfig.Running = false
			execConfig.StreamConfig.Wait()
			if err := execConfig.CloseStreams(); err != nil {
				logrus.Errorf("failed to cleanup exec %s streams: %s", c.ID, err)
			}

			// remove the exec command from the container's store only and not the
			// daemon's store so that the exec command can be inspected.
			c.ExecCommands.Delete(execConfig.ID, execConfig.Pid)
			attributes := map[string]string{
				"execID":   execConfig.ID,
				"exitCode": strconv.Itoa(ec),
			}
			daemon.LogContainerEventWithAttributes(c, "exec_die", attributes)
		} else {
			logrus.WithFields(logrus.Fields{
				"container": c.ID,
				"exec-id":   ei.ProcessID,
				"exec-pid":  ei.Pid,
			}).Warn("Ignoring Exit Event, no such exec command found")
		}
	case libcontainerdtypes.EventStart:
		c.Lock()
		defer c.Unlock()

		// This is here to handle start not generated by docker
		if !c.Running {
			c.SetRunning(int(ei.Pid), false)
			c.HasBeenManuallyStopped = false
			c.HasBeenStartedBefore = true
			daemon.setStateCounter(c)

			daemon.initHealthMonitor(c)

			if err := c.CheckpointTo(daemon.containersReplica); err != nil {
				return err
			}
			daemon.LogContainerEvent(c, "start")
		}

	case libcontainerdtypes.EventPaused:
		c.Lock()
		defer c.Unlock()

		if !c.Paused {
			c.Paused = true
			daemon.setStateCounter(c)
			daemon.updateHealthMonitor(c)
			if err := c.CheckpointTo(daemon.containersReplica); err != nil {
				return err
			}
			daemon.LogContainerEvent(c, "pause")
		}
	case libcontainerdtypes.EventResumed:
		c.Lock()
		defer c.Unlock()

		if c.Paused {
			c.Paused = false
			daemon.setStateCounter(c)
			daemon.updateHealthMonitor(c)

			if err := c.CheckpointTo(daemon.containersReplica); err != nil {
				return err
			}
			daemon.LogContainerEvent(c, "unpause")
		}
	}
	return nil
}