prome_init.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //go:build prometheus || !core
  15. // +build prometheus !core
  16. package server
  17. import (
  18. "context"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/prometheus/client_golang/prometheus/promhttp"
  22. "net/http"
  23. "time"
  24. )
  25. func init() {
  26. servers["prometheus"] = promeComp{}
  27. }
  28. type promeComp struct {
  29. s *http.Server
  30. }
  31. func (p promeComp) serve() {
  32. //Start prometheus service
  33. if conf.Config.Basic.Prometheus {
  34. portPrometheus := conf.Config.Basic.PrometheusPort
  35. if portPrometheus <= 0 {
  36. logger.Fatal("Miss configuration prometheusPort")
  37. }
  38. mux := http.NewServeMux()
  39. mux.Handle("/metrics", promhttp.Handler())
  40. srvPrometheus := &http.Server{
  41. Addr: fmt.Sprintf("0.0.0.0:%d", portPrometheus),
  42. WriteTimeout: time.Second * 15,
  43. ReadTimeout: time.Second * 15,
  44. IdleTimeout: time.Second * 60,
  45. Handler: mux,
  46. }
  47. go func() {
  48. if err := srvPrometheus.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  49. logger.Fatal("Listen prometheus error: ", err)
  50. }
  51. }()
  52. p.s = srvPrometheus
  53. msg := fmt.Sprintf("Serving prometheus metrics on port http://localhost:%d/metrics", portPrometheus)
  54. logger.Infof(msg)
  55. fmt.Println(msg)
  56. }
  57. }
  58. func (p promeComp) close() {
  59. if p.s != nil {
  60. if err := p.s.Shutdown(context.TODO()); err != nil {
  61. logger.Errorf("prometheus server shutdown error: %v", err)
  62. }
  63. logger.Info("prometheus server successfully shutdown.")
  64. }
  65. }