// agentPipeReader reads agent events from the agentPipe and distributes to all listeners
163030
func (m *Monitor) agentPipeReader(ctx context.Context, agentPipe io.Reader) {
	log.Info("Beginning to read cilium agent events")
	defer log.Info("Stopped reading cilium agent events")

	for !isCtxDone(ctx) {
		meta, p := payload.Meta{}, payload.Payload{}
		err := payload.ReadMetaPayload(agentPipe, &meta, &p)
		switch {
		// this captures the case where we are shutting down and main closes the
		// pipe socket
		case isCtxDone(ctx):
			return

		case err == io.EOF || err == io.ErrUnexpectedEOF:
			log.Fatal("Agent pipe unexpectedly closed, shutting down")

		case err != nil:
			log.WithError(err).Fatal("Unable to read cilium agent events from pipe")
		}

		m.send(&p)
	}
}
166408
func (iface *Intface) agent() {
	//  Create agent instance to pass around
	agent := new_agent()

	//  Send first beacon immediately
	ping_at := time.Now()

	poller := zmq.NewPoller()
	poller.Add(agent.pipe, zmq.POLLIN)
	poller.Add(agent.udp, zmq.POLLIN)

	bcast := &net.UDPAddr{Port: PING_PORT_NUMBER, IP: net.IPv4bcast}
	for {
		timeout := ping_at.Add(time.Millisecond).Sub(time.Now())
		if timeout < 0 {
			timeout = 0
		}
		polled, err := poller.Poll(timeout)
		if err != nil {
			break
		}

		for _, item := range polled {
			switch socket := item.Socket; socket {
			case agent.pipe:
				//  If we had activity on the pipe, go handle the control
				//  message. Current code never sends control messages.
				agent.control_message()

			case agent.udp:
				//  If we had input on the UDP socket, go process that
				agent.handle_beacon()
			}
		}

		//  If we passed the 1-second mark, broadcast our beacon
		now := time.Now()
		if now.After(ping_at) {
			agent.conn.WriteTo(agent.uuid_bytes, bcast)
			ping_at = now.Add(PING_INTERVAL)
		}
		//  Delete and report any expired peers
		for _, peer := range agent.peers {
			agent.reap_peer(peer)
		}
	}
}
512487
func (md *RootMetadataV2) IsReader(
	_ context.Context, user keybase1.UID, deviceKey kbfscrypto.CryptPublicKey,
	_ TeamMembershipChecker, _ ExtraMetadata,
	_ keybase1.OfflineAvailability) (bool, error) {
	switch md.ID.Type() {
	case tlf.Public:
		return true, nil
	case tlf.Private:
		return md.RKeys.IsReader(user, deviceKey), nil
	case tlf.SingleTeam:
		// There are no read-only users of single-team TLFs.
		return false, nil
	default:
		panic(fmt.Sprintf("Unexpected TLF type: %s", md.ID.Type()))
	}
}
129096
func (env *azureEnviron) AgentMirror() (simplestreams.CloudSpec, error) {
	return simplestreams.CloudSpec{
		Region: env.location,
		// The endpoints published in simplestreams
		// data are the storage endpoints.
		Endpoint: fmt.Sprintf("https://%s/", env.storageEndpoint),
	}, nil
}
951370
func AgentConf(info AgentInfo, renderer shell.Renderer) common.Conf {
	conf := common.Conf{
		Desc:          fmt.Sprintf("juju agent for %s", info.name),
		ExecStart:     info.cmd(renderer),
		Logfile:       info.logFile(renderer),
		Env:           osenv.FeatureFlags(),
		Timeout:       agentServiceTimeout,
		ServiceBinary: info.jujud(renderer),
		ServiceArgs:   info.execArgs(renderer),
	}

	switch info.Kind {
	case AgentKindMachine:
		conf.Limit = map[string]string{
			"nofile": "64000",
		}
	case AgentKindUnit:
		conf.Desc = "juju unit agent for " + info.ID
	}

	return conf
}
53552
func (h Handle) IsReader(user keybase1.UserOrTeamID) bool {
	if h.TypeForKeying() == TeamKeying {
		panic("Can't call Handle.IsReader() for a single team TLF")
	}
	return h.TypeForKeying() == PublicKeying ||
		h.findUserInList(user, h.Readers) ||
		h.IsWriter(user)
}
139686
func (self *FSock) readEvents() {
	for {
		select {
		case <-self.stopReadEvents:
			return
		default: // Unlock waiting here
		}
		hdr, body, err := self.readEvent()
		if err != nil {
			self.errReadEvents <- err
			return
		}
		if strings.Contains(hdr, "api/response") {
			self.cmdChan <- body
		} else if strings.Contains(hdr, "command/reply") {
			self.cmdChan <- headerVal(hdr, "Reply-Text")
		} else if body != "" { // We got a body, could be event, try dispatching it
			self.dispatchEvent(body)
		}
	}
}
1148004
func (a *ACL) AllowAgentRead() bool {
	switch {
	case a.management:
		return true
	case a.agent == PolicyWrite:
		return true
	case a.agent == PolicyRead:
		return true
	default:
		return false
	}
}
432422
func NewAgentClient(ctx context.Context, sock string, enableYamux bool) (*AgentClient, error) {
	grpcAddr, parsedAddr, err := parse(sock)
	if err != nil {
		return nil, err
	}
	dialOpts := []grpc.DialOption{grpc.WithInsecure(), grpc.WithBlock()}
	dialOpts = append(dialOpts, grpc.WithDialer(agentDialer(parsedAddr, enableYamux)))

	var tracer opentracing.Tracer

	span := opentracing.SpanFromContext(ctx)

	// If the context contains a trace span, trace all client comms
	if span != nil {
		tracer = span.Tracer()

		dialOpts = append(dialOpts,
			grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracer)))
		dialOpts = append(dialOpts,
			grpc.WithStreamInterceptor(otgrpc.OpenTracingStreamClientInterceptor(tracer)))
	}

	ctx, cancel := context.WithTimeout(ctx, defaultDialTimeout)
	defer cancel()
	conn, err := grpc.DialContext(ctx, grpcAddr, dialOpts...)
	if err != nil {
		return nil, err
	}

	return &AgentClient{
		AgentServiceClient: agentgrpc.NewAgentServiceClient(conn),
		HealthClient:       agentgrpc.NewHealthClient(conn),
		conn:               conn,
	}, nil
}
1269145
func (a *Application) AgentPresence() (bool, error) {
	pwatcher := a.st.workers.presenceWatcher()
	return pwatcher.Alive(a.globalKey())
}
866462
func (mr *MockConnectorMockRecorder) AgentBroadcastTarget(collective, agent interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AgentBroadcastTarget", reflect.TypeOf((*MockConnector)(nil).AgentBroadcastTarget), collective, agent)
}
1017919
func agentServiceWatch(params map[string]interface{}) (WatcherFunc, error) {
	// We don't support consistency modes since it's agent local data

	var serviceID string
	if err := assignValue(params, "service_id", &serviceID); err != nil {
		return nil, err
	}

	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		agent := p.client.Agent()
		opts := makeQueryOptionsWithContext(p, false)
		defer p.cancelFunc()

		svc, _, err := agent.Service(serviceID, &opts)
		if err != nil {
			return nil, nil, err
		}

		// Return string ContentHash since we don't have Raft indexes to block on.
		return WaitHashVal(svc.ContentHash), svc, err
	}
	return fn, nil
}
438679
func (c *connections) Agents() []string {
	agents := set.NewStrings()
	for _, value := range c.values {
		agents.Add(value.Agent)
	}
	return agents.Values()
}
1026436
func NewEventPipeline(streams ...EventStream) EventStream {
	switch len(streams) {
	case 0:
		return nil
	case 1:
		return streams[0]
	default:
	}

	streams[0].Subscribe(streams[1])

	return struct {
		EventWriter
		EventEmitter
	}{
		streams[0],
		NewEventPipeline(streams[1:]...),
	}

}
840685
func ForwardToAgent(client *ssh.Client, keyring Agent) error {
	channels := client.HandleChannelOpen(channelType)
	if channels == nil {
		return errors.New("agent: already have handler for " + channelType)
	}

	go func() {
		for ch := range channels {
			channel, reqs, err := ch.Accept()
			if err != nil {
				continue
			}
			go ssh.DiscardRequests(reqs)
			go func() {
				ServeAgent(keyring, channel)
				channel.Close()
			}()
		}
	}()
	return nil
}
525719
func pipe() (io.ReadCloser, io.WriteCloser) {
	w := &pipeWriter{
		consumed: make(chan struct{}),
		provided: make(chan struct{}),
		closed:   make(chan struct{}),
	}
	r := &pipeReader{
		w:      w,
		closed: make(chan struct{}),
	}
	w.r = r
	return r, w
}
887574
func ReadTools(dataDir string, vers version.Binary) (*coretools.Tools, error) {
	dir := SharedToolsDir(dataDir, vers)
	toolsData, err := ioutil.ReadFile(path.Join(dir, toolsFile))
	if err != nil {
		return nil, fmt.Errorf("cannot read agent metadata in directory %v: %v", dir, err)
	}
	var tools coretools.Tools
	if err := json.Unmarshal(toolsData, &tools); err != nil {
		return nil, fmt.Errorf("invalid agent metadata in directory %q: %v", dir, err)
	}
	return &tools, nil
}