// Delete all of the events by the device id (and the readings)
//DeleteEventsByDeviceId(id string) error
// Return a list of events whos creation time is between startTime and endTime
// Limit the number of results by limit
174633
func (c *Client) EventsByCreationTime(startTime, endTime int64, limit int) (events []contract.Event, err error) {
	conn := c.Pool.Get()
	defer conn.Close()

	objects, err := getObjectsByScore(conn, db.EventsCollection+":created", startTime, endTime, limit)
	if err != nil {
		if err != redis.ErrNil {
			return events, err
		}
	}

	events = make([]contract.Event, len(objects))
	err = unmarshalEvents(objects, events)
	if err != nil {
		return events, err
	}

	return events, nil
}
404918
func (s *NuageVSPService) DeleteNuageVspDevice(p *DeleteNuageVspDeviceParams) (*DeleteNuageVspDeviceResponse, error) {
	resp, err := s.cs.newRequest("deleteNuageVspDevice", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteNuageVspDeviceResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
1348795
func (c *Client) DeviceID() (*DeviceIDResponse, error) {
	req := &Request{
		NetworkFunctionApp,
		CommandGetDeviceID,
		&DeviceIDRequest{},
	}
	res := &DeviceIDResponse{}
	return res, c.Send(req, res)
}
295476
func EventAddTimeout(freq int, callback EventTimeoutCallback) (int, error) {
	callbackID := registerCallbackId(callback)

	var err C.virError
	ret := C.virEventAddTimeoutWrapper((C.int)(freq), (C.int)(callbackID), &err)
	if ret == -1 {
		return 0, makeError(&err)
	}

	return int(ret), nil
}
962663
func (a *EventCounter) Events(now time.Time, count int64) int64 {
	for {
		nsSince := now.Sub(a.startingTime).Nanoseconds()
		prevNsSinceStart := atomic.LoadInt64(&a.nsSinceStart)
		if nsSince-prevNsSinceStart >= a.eventDuration.Nanoseconds() {
			//		 Note: There is an accepted race here when we transition states that could cause us to
			//		       rarely miss an event that crosses the threshold.  This is an accepted aspect of
			//		       having a very fast non threshold event
			if atomic.CompareAndSwapInt64(&a.nsSinceStart, prevNsSinceStart, nsSince) {
				atomic.StoreInt64(&a.eventsThisPeriod, 0)
				break
			}
		} else {
			break
		}
	}
	return atomic.AddInt64(&a.eventsThisPeriod, count)
}
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
}
1319709
func (c *Client) DeleteApp(appID string) (*ct.AppDeletion, error) {
	events := make(chan *ct.Event)
	stream, err := c.StreamEvents(ct.StreamEventsOptions{
		AppID:       appID,
		ObjectTypes: []ct.EventType{ct.EventTypeAppDeletion},
	}, events)
	if err != nil {
		return nil, err
	}
	defer stream.Close()

	if err := c.Delete(fmt.Sprintf("/apps/%s", appID), nil); err != nil {
		return nil, err
	}

	select {
	case event, ok := <-events:
		if !ok {
			return nil, stream.Err()
		}
		var e ct.AppDeletionEvent
		if err := json.Unmarshal(event.Data, &e); err != nil {
			return nil, err
		}
		if e.Error != "" {
			return nil, errors.New(e.Error)
		}
		return e.AppDeletion, nil
	case <-time.After(60 * time.Second):
		return nil, errors.New("timed out waiting for app deletion")
	}
}
782848
func (mc MongoClient) EventsForDeviceLimit(id string, limit int) ([]contract.Event, error) {
	return mc.mapEvents(mc.getEventsLimit(bson.M{"device": id}, limit))
}
793125
func ParseEventID(s string) (*EventID, error) {
	parts := strings.Split(s, EventIDDelimiter)
	if len(parts) != 2 && len(parts) != 3 {
		return nil, ErrBadEventID
	}

	root, err := ParseID(parts[0])
	if err != nil {
		return nil, ErrBadEventID
	}

	id, err := ParseID(parts[1])
	if err != nil {
		return nil, ErrBadEventID
	}

	var parent ID
	if len(parts) == 3 {
		i, err := ParseID(parts[2])
		if err != nil {
			return nil, ErrBadEventID
		}
		parent = i
	}

	return &EventID{
		Root:   root,
		ID:     id,
		Parent: parent,
	}, nil
}
19609
func (s *NetworkDeviceService) DeleteNetworkDevice(p *DeleteNetworkDeviceParams) (*DeleteNetworkDeviceResponse, error) {
	resp, err := s.cs.newRequest("deleteNetworkDevice", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteNetworkDeviceResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
145797
func (c *Client) GetDeviceByID(id uint64) (common.Device, error) {
	dev, err := c.protocol.GetDevice(id)
	if err == nil {
		return dev, nil
	}

	var timeout <-chan time.Time
	if c.timeout > 0 {
		timeout = time.After(c.timeout)
	} else {
		timeout = make(<-chan time.Time)
	}

	sub := c.protocol.Subscribe()
	defer func() {
		if err = sub.Close(); err != nil {
			common.Log.Warnf("Failed closing device subscription: %+v", err)
		}
	}()
	events := sub.Events()

	for {
		select {
		case event, ok := <-events:
			if !ok {
				return nil, common.ErrClosed
			}
			switch event := event.(type) {
			case common.EventNewDevice:
				if id == event.Device.ID() {
					return event.Device, nil
				}
			}
		case <-timeout:
			return nil, common.ErrNotFound
		}
	}
}
1140371
func eventCountByDeviceIdHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	vars := mux.Vars(r)
	id, err := url.QueryUnescape(vars["deviceId"])
	ctx := r.Context()

	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Problem unescaping URL: " + err.Error())
		return
	}

	// Check device
	count, err := countEventsByDevice(id, ctx)
	if err != nil {
		LoggingClient.Error(fmt.Sprintf("error checking device %s %v", id, err))
		switch err := err.(type) {
		case *types.ErrServiceClient:
			http.Error(w, err.Error(), err.StatusCode)
			return
		default: //return an error on everything else.
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte(strconv.Itoa(count)))
}
1207131
func (c *Client) DeleteIntervalById(id string) (err error) {
	check, err := c.IntervalById(id)
	if err != nil {
		if err == db.ErrNotFound {
			return nil
		}
		return
	}

	interval := models.NewInterval(check)
	conn := c.Pool.Get()
	defer conn.Close()

	_ = conn.Send("MULTI")
	deleteObject(interval, id, conn)

	_, err = conn.Do("EXEC")

	return err
}
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)
}
990525
func (_m *DBClient) GetDeviceById(id string) (models.Device, error) {
	ret := _m.Called(id)

	var r0 models.Device
	if rf, ok := ret.Get(0).(func(string) models.Device); ok {
		r0 = rf(id)
	} else {
		r0 = ret.Get(0).(models.Device)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string) error); ok {
		r1 = rf(id)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
950296
func (c *Client) DeleteRelease(appID, releaseID string) (*ct.ReleaseDeletion, error) {
	events := make(chan *ct.Event)
	stream, err := c.StreamEvents(ct.StreamEventsOptions{
		AppID:       appID,
		ObjectID:    releaseID,
		ObjectTypes: []ct.EventType{ct.EventTypeReleaseDeletion},
	}, events)
	if err != nil {
		return nil, err
	}
	defer stream.Close()

	if err := c.Delete(fmt.Sprintf("/apps/%s/releases/%s", appID, releaseID), nil); err != nil {
		return nil, err
	}

	select {
	case event, ok := <-events:
		if !ok {
			return nil, stream.Err()
		}
		var e ct.ReleaseDeletionEvent
		if err := json.Unmarshal(event.Data, &e); err != nil {
			return nil, err
		}
		if e.Error != "" {
			return nil, errors.New(e.Error)
		}
		return e.ReleaseDeletion, nil
	case <-time.After(60 * time.Second):
		return nil, errors.New("timed out waiting for release deletion")
	}
}
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
}