func pollEnvoyReadiness()

in agent/agent.go [453:549]


func pollEnvoyReadiness(conf config.AgentConfig) error {
	tick := time.NewTicker(time.Duration(conf.AgentPollEnvoyReadinessInterval) * time.Second)
	defer tick.Stop()

	var after <-chan time.Time
	if conf.AgentPollEnvoyReadinessTimeout > 0 {
		timer := time.NewTimer(time.Duration(conf.AgentPollEnvoyReadinessTimeout) * time.Second)
		after = timer.C
		defer timer.Stop()
	}

	// one-off request path
	if conf.AgentPollEnvoyReadinessInterval == 0 || conf.AgentPollEnvoyReadinessTimeout == 0 {
		httpClient, err := client.CreateHttpClientForAgentServer(conf)
		if err != nil {
			log.Errorf("Failed to create AppNet Agent HTTP client %v", err)
			return err
		}

		req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1%s", config.AGENT_STATUS_ENDPOINT_URL), nil)
		if err != nil {
			log.Errorf("Failed to create request: (%v) %v", req, err)
			return err
		}

		res, err := httpClient.Do(req)

		if err != nil {
			log.Errorf("Request failed %v", err)
			return err
		}

		body, err := ioutil.ReadAll(res.Body)
		defer res.Body.Close()

		status := healthcheck.HealthStatus{}

		err = json.Unmarshal(body, &status)
		if err != nil {
			log.Errorf("Failed to unmarshal response: [%s] %v", string(body), err)
			return err
		}

		log.Debugf("Envoy is %s", status.HealthStatus)
		if status.HealthStatus != healthcheck.Healthy {
			return fmt.Errorf("Envoy is not healthy: %v", status.HealthStatus)
		}

		return nil
	}

	// polling request path
	log.Debugf("Polling at interval of %ds with timeout of %ds", conf.AgentPollEnvoyReadinessInterval, conf.AgentPollEnvoyReadinessTimeout)
	for {
		select {
		case <-tick.C:
			httpClient, err := client.CreateHttpClientForAgentServer(conf)
			if err != nil {
				log.Errorf("Failed to create IPC HTTP client %v", err)
				continue
			}

			req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://127.0.0.1%s", config.AGENT_STATUS_ENDPOINT_URL), nil)
			if err != nil {
				log.Errorf("Failed to create request: (%v) %v", req, err)
				continue
			}

			res, err := httpClient.Do(req)
			if err != nil {
				log.Errorf("Request failed %v", err)
				continue
			}

			body, err := ioutil.ReadAll(res.Body)
			defer res.Body.Close()

			status := healthcheck.HealthStatus{}

			err = json.Unmarshal(body, &status)
			if err != nil {
				log.Errorf("Failed to unmarshal response: [%s] %v", string(body), err)
				continue
			}

			log.Debugf("Envoy is %s", status.HealthStatus)
			if status.HealthStatus == healthcheck.Healthy {
				return nil
			}

			// if unhealthy continue ticking
		case <-after:
			log.Debugf("Timed out after %v", conf.AgentPollEnvoyReadinessTimeout)
			return fmt.Errorf("Timed out after %v", conf.AgentPollEnvoyReadinessTimeout)
		}
	}
}