Example #1
0
// Start checks the modules for the following interfaces and registers and/or starts:
//   Startable:
//   health.Checker:
//   Endpoint: Register the handler function of the Endpoint in the http service at prefix
func (s *Service) Start() error {
	el := protocol.NewErrorList("service: errors occured while starting: ")

	if s.healthEndpoint != "" {
		loggerService.WithField("healthEndpoint", s.healthEndpoint).Info("Health endpoint")
		s.webserver.Handle(s.healthEndpoint, http.HandlerFunc(health.StatusHandler))
	} else {
		loggerService.Info("Health endpoint disabled")
	}

	if s.metricsEndpoint != "" {
		loggerService.WithField("metricsEndpoint", s.metricsEndpoint).Info("Metrics endpoint")
		s.webserver.Handle(s.metricsEndpoint, http.HandlerFunc(metrics.HttpHandler))
	} else {
		loggerService.Info("Metrics endpoint disabled")
	}

	for _, module := range s.modules {
		name := reflect.TypeOf(module).String()
		if startable, ok := module.(Startable); ok {
			loggerService.WithFields(log.Fields{
				"name": name,
			}).Info("Starting module")

			if err := startable.Start(); err != nil {
				loggerService.WithFields(log.Fields{
					"name": name,
					"err":  err,
				}).Error("Error while starting module")
				el.Add(err)
			}
		}
		if checker, ok := module.(health.Checker); ok && s.healthEndpoint != "" {
			loggerService.WithField("name", name).Info("Registering module as Health-Checker")
			health.RegisterPeriodicThresholdFunc(name, s.healthFrequency, s.healthThreshold, health.CheckFunc(checker.Check))
		}
		if endpoint, ok := module.(Endpoint); ok {
			prefix := endpoint.GetPrefix()
			loggerService.WithFields(log.Fields{
				"name":   name,
				"prefix": prefix,
			}).Info("Registering module as Endpoint")
			s.webserver.Handle(prefix, endpoint)
		}
	}
	return el.ErrorOrNil()
}
Example #2
0
// Stop stops the registered modules in the required order
func (s *Service) Stop() error {
	var stopables []Stopable

	for _, module := range s.modules {
		if stopable, ok := module.(Stopable); ok {
			stopables = append(stopables, stopable)
		}
	}

	stopOrder := make([]int, len(stopables))

	if s.router.Cluster() == nil {
		for i := 1; i < len(stopables); i++ {
			stopOrder[i] = len(stopables) - i
		}
	} else {
		stopOrder[0] = 1
		for i := 1; i < len(stopables)-1; i++ {
			stopOrder[i] = len(stopables) - i
		}
		stopOrder[len(stopables)-1] = 0
	}

	loggerService.WithField("stopOrder", stopOrder).Debug("Stopping modules in this order relative to registration")

	errors := protocol.NewErrorList("stopping errors: ")
	for _, order := range stopOrder {
		module := stopables[order]
		name := reflect.TypeOf(module).String()
		loggerService.WithFields(log.Fields{
			"name":  name,
			"order": order,
		}).Info("Stopping module")
		if err := module.Stop(); err != nil {
			errors.Add(err)
		}
	}

	if err := errors.ErrorOrNil(); err != nil {
		return fmt.Errorf("service: errors while stopping modules: %s", err)
	}

	return nil
}