// sendMemberEvent is used to send a single member event
425275
func (es *eventStream) sendMemberEvent(me serf.MemberEvent) error {
	members := make([]Member, 0, len(me.Members))
	for _, m := range me.Members {
		sm := Member{
			Name:        m.Name,
			Addr:        m.Addr,
			Port:        m.Port,
			Tags:        m.Tags,
			Status:      m.Status.String(),
			ProtocolMin: m.ProtocolMin,
			ProtocolMax: m.ProtocolMax,
			ProtocolCur: m.ProtocolCur,
			DelegateMin: m.DelegateMin,
			DelegateMax: m.DelegateMax,
			DelegateCur: m.DelegateCur,
		}
		members = append(members, sm)
	}

	header := responseHeader{
		Seq:   es.seq,
		Error: "",
	}
	rec := memberEventRecord{
		Event:   me.String(),
		Members: members,
	}
	return es.client.Send(&header, &rec)
}
1123411
func (client *peerRESTClient) SendEvent(bucket string, targetID, remoteTargetID event.TargetID, eventData event.Event) error {
	args := sendEventRequest{
		TargetID: remoteTargetID,
		Event:    eventData,
	}

	values := make(url.Values)
	values.Set(peerRESTBucket, bucket)

	var reader bytes.Buffer
	err := gob.NewEncoder(&reader).Encode(args)
	if err != nil {
		return err
	}
	respBody, err := client.call(peerRESTMethodSendEvent, values, &reader, -1)
	if err != nil {
		return err
	}

	var eventResp sendEventResp
	defer http.DrainBody(respBody)
	err = gob.NewDecoder(respBody).Decode(&eventResp)

	if err != nil || !eventResp.Success {
		reqInfo := &logger.ReqInfo{BucketName: bucket}
		reqInfo.AppendTags("targetID", targetID.Name)
		reqInfo.AppendTags("event", eventData.EventName.String())
		ctx := logger.SetReqInfo(context.Background(), reqInfo)
		logger.LogIf(ctx, err)
		globalNotificationSys.RemoveRemoteTarget(bucket, targetID)
	}

	return err
}
1169551
func (es *EventSource) SendEvent(id uint64, event string, data interface{}) error {
	switch data.(type) {
	case string:
		es.conn.Write(generateMessage(id, event, data.(string)))
	case []byte:
		es.conn.Write(generateMessage(id, event, string(data.([]byte))))
	case EventData:
		content, err := data.(EventData).Encode()
		if err != nil {
			return err
		}
		es.conn.Write(generateMessage(id, event, string(content)))
	}
	return nil
}
596379
func (s *Streamer) SendString(id, event, data string) {
	dataLen := len(data)
	lfCount := 0

	// We must sent a "data:{data}\n" for each line
	if dataLen > 0 {
		lfCount = strings.Count(data, "\n")
		if lfCount > 0 {
			dataLen += (5 * lfCount) // data:
		}
	}

	p := format(id, event, dataLen)

	// fill in data lines
	start := 0
	ins := len(p) - (2 + dataLen)
	for i := 0; lfCount > 0; i++ {
		if data[i] == '\n' {
			copy(p[ins:], data[start:i])
			ins += i - start
			copy(p[ins:], "\ndata:")
			ins += 6

			start = i + 1
			lfCount--
		}
	}
	copy(p[ins:], data[start:])

	s.event <- p
}
983397
func (d *Driver) PublishEvent(name string, data string) {
	d.Publish(d.Event(name), data)
}
280132
func (e *Eventer) EmitEvent(event *drivers.TaskEvent) error {

	select {
	case <-e.ctx.Done():
		return e.ctx.Err()
	case e.events <- event:
		if e.logger.IsTrace() {
			e.logger.Trace("emitting event", "event", event)
		}
	}
	return nil
}
577032
func (c *cmd) fireEvent() (string, error) {
	// Create the user event payload
	msg := &rExecEvent{
		Prefix:  c.conf.prefix,
		Session: c.sessionID,
	}
	buf, err := json.Marshal(msg)
	if err != nil {
		return "", err
	}

	// Format the user event
	event := c.apiclient.Event()
	params := &api.UserEvent{
		Name:          "_rexec",
		Payload:       buf,
		NodeFilter:    c.conf.node,
		ServiceFilter: c.conf.service,
		TagFilter:     c.conf.tag,
	}

	// Fire the event
	id, _, err := event.Fire(params, nil)
	return id, err
}
743364
func SendEnvelope(envelope *events.Envelope) error {
	if envelopeSender == nil {
		return nil
	}
	return envelopeSender.SendEnvelope(envelope)
}
757655
func sendEvents(target event.Target, eventKeyCh <-chan string, doneCh <-chan struct{}) {
	retryTimer := time.NewTimer(retryInterval)
	defer retryTimer.Stop()

	send := func(eventKey string) bool {
		for {
			err := target.Send(eventKey)
			if err == nil {
				break
			}

			if err != errNotConnected {
				panic(fmt.Errorf("target.Send() failed with '%v'", err))
			}

			retryTimer.Reset(retryInterval)
			select {
			case <-retryTimer.C:
			case <-doneCh:
				return false
			}
		}
		return true
	}

	for {
		select {
		case eventKey, ok := <-eventKeyCh:
			if !ok {
				// closed channel.
				return
			}

			if !send(eventKey) {
				return
			}
		case <-doneCh:
			return
		}
	}
}
841409
func (a *Agent) UserEvent(dc, token string, params *UserEvent) error {
	// Validate the params
	if err := validateUserEventParams(params); err != nil {
		return err
	}

	// Format message
	var err error
	if params.ID, err = uuid.GenerateUUID(); err != nil {
		return fmt.Errorf("UUID generation failed: %v", err)
	}
	params.Version = userEventMaxVersion
	payload, err := encodeMsgPack(&params)
	if err != nil {
		return fmt.Errorf("UserEvent encoding failed: %v", err)
	}

	// Service the event fire over RPC. This ensures that we authorize
	// the request against the token first.
	args := structs.EventFireRequest{
		Datacenter:   dc,
		Name:         params.Name,
		Payload:      payload,
		QueryOptions: structs.QueryOptions{Token: token},
	}

	// Any server can process in the remote DC, since the
	// gossip will take over anyways
	args.AllowStale = true
	var out structs.EventFireResponse
	return a.RPC("Internal.EventFire", &args, &out)
}
1086841
func (mc MongoClient) UpdateEvent(e contract.Event) error {
	var mapped models.Event
	id, err := mapped.FromContract(e, mc)
	if err != nil {
		return err
	}

	mapped.TimestampForUpdate()

	return mc.updateId(db.EventsCollection, id, mapped)
}
561057
func (c *StatsdClient) SendEvents(events map[string]event.Event) error {
	if c.conn == nil {
		return errNotConnected
	}

	var n int
	var stats = make([]string, 0)

	for _, e := range events {
		for _, stat := range e.Stats() {

			stat = c.prefix + strings.Replace(stat, "%HOST%", Hostname, 1)
			_n := n + len(stat) + 1

			if _n > UDPPayloadSize {
				// with this last event, the UDP payload would be too big
				if _, err := fmt.Fprintf(c.conn, strings.Join(stats, "\n")+"\n"); err != nil {
					return err
				}
				// reset payload after flushing, and add the last event
				stats = []string{stat}
				n = len(stat)
				continue
			}

			// can fit more into the current payload
			n = _n
			stats = append(stats, stat)
		}
	}

	if len(stats) != 0 {
		if _, err := fmt.Fprintf(c.conn, strings.Join(stats, "\n")+"\n"); err != nil {
			return err
		}
	}

	return nil
}
493904
func (c *Client) SendEvent(event Event, opts ...interface{}) (res StatusMessageRes, err error) {
	return c.SendEvents([]Event{event}, opts...)
}
1203008
func (s *StdoutClient) SendEvents(events map[string]event.Event) error {
	var n int
	var stats = make([]string, 0)

	for _, e := range events {
		for _, stat := range e.Stats() {

			stat = fmt.Sprintf("%s%s", s.prefix, strings.Replace(stat, "%HOST%", Hostname, 1))
			_n := n + len(stat) + 1

			if _n > UDPPayloadSize {
				// with this last event, the UDP payload would be too big
				if _, err := fmt.Fprintf(s.FD, strings.Join(stats, "\n")); err != nil {
					return err
				}
				// reset payload after flushing, and add the last event
				stats = []string{stat}
				n = len(stat)
				continue
			}

			// can fit more into the current payload
			n = _n
			stats = append(stats, stat)
		}
	}

	if len(stats) != 0 {
		if _, err := fmt.Fprintf(s.FD, strings.Join(stats, "\n")); err != nil {
			return err
		}
	}

	return nil
}
966644
func sendEvents(evtChan chan *dt.ScheduledEvent, interval time.Duration) {
	t := time.NewTicker(time.Minute)
	select {
	case now := <-t.C:
		sendEventsTick(evtChan, now)
		sendEvents(evtChan, interval)
	}
}
835580
func (c *Client) handleEvent(msg []byte) error {
	event := &eventType{}
	err := json.Unmarshal(msg, event)
	if err != nil {
		return err
	}
	//var e interface{}
	switch event.Event {
	case "info":
		i := InfoEvent{}
		err = json.Unmarshal(msg, &i)
		if err != nil {
			return err
		}
		if i.Code == 0 && i.Version != 0 {
			err_open := c.handleOpen()
			if err_open != nil {
				return err_open
			}
		}
		c.listener <- &i
	case "auth":
		a := AuthEvent{}
		err = json.Unmarshal(msg, &a)
		if err != nil {
			return err
		}
		if a.Status != "" && a.Status == "OK" {
			c.Authentication = SuccessfulAuthentication
		} else {
			c.Authentication = RejectedAuthentication
		}
		c.handleAuthAck(&a)
		c.listener <- &a
		return nil
	case "subscribed":
		s := SubscribeEvent{}
		err = json.Unmarshal(msg, &s)
		if err != nil {
			return err
		}
		err = c.subscriptions.activate(s.SubID, s.ChanID)
		if err != nil {
			return err
		}
		c.listener <- &s
		return nil
	case "unsubscribed":
		s := UnsubscribeEvent{}
		err = json.Unmarshal(msg, &s)
		if err != nil {
			return err
		}
		err_rem := c.subscriptions.removeByChannelID(s.ChanID)
		if err_rem != nil {
			return err_rem
		}
		c.listener <- &s
	case "error":
		er := ErrorEvent{}
		err = json.Unmarshal(msg, &er)
		if err != nil {
			return err
		}
		c.listener <- &er
	case "conf":
		ec := ConfEvent{}
		err = json.Unmarshal(msg, &ec)
		if err != nil {
			return err
		}
		c.listener <- &ec
	default:
		c.log.Warningf("unknown event: %s", msg)
	}

	//err = json.Unmarshal(msg, &e)
	//TODO raw message isn't ever published

	return err
}
1284815
func (s *peerRESTServer) SendEventHandler(w http.ResponseWriter, r *http.Request) {
	if !s.IsValid(w, r) {
		s.writeErrorResponse(w, errors.New("Invalid request"))
		return
	}

	ctx := newContext(r, w, "SendEvent")

	vars := mux.Vars(r)
	bucketName := vars[peerRESTBucket]
	if bucketName == "" {
		s.writeErrorResponse(w, errors.New("Bucket name is missing"))
		return
	}
	var eventReq sendEventRequest
	if r.ContentLength <= 0 {
		s.writeErrorResponse(w, errInvalidArgument)
		return
	}

	err := gob.NewDecoder(r.Body).Decode(&eventReq)
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}

	var eventResp sendEventResp
	eventResp.Success = true
	errs := globalNotificationSys.send(bucketName, eventReq.Event, eventReq.TargetID)

	for i := range errs {
		reqInfo := (&logger.ReqInfo{}).AppendTags("Event", eventReq.Event.EventName.String())
		reqInfo.AppendTags("targetName", eventReq.TargetID.Name)
		ctx := logger.SetReqInfo(context.Background(), reqInfo)
		logger.LogIf(ctx, errs[i].Err)

		eventResp.Success = false
		s.writeErrorResponse(w, errs[i].Err)
		return
	}
	logger.LogIf(ctx, gob.NewEncoder(w).Encode(&eventResp))
	w.(http.Flusher).Flush()
}