server.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. package server
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/binder/function"
  20. "github.com/lf-edge/ekuiper/internal/binder/io"
  21. "github.com/lf-edge/ekuiper/internal/binder/meta"
  22. "github.com/lf-edge/ekuiper/internal/conf"
  23. "github.com/lf-edge/ekuiper/internal/pkg/store"
  24. "github.com/lf-edge/ekuiper/internal/processor"
  25. "github.com/lf-edge/ekuiper/internal/topo/connection/factory"
  26. "net/http"
  27. "os"
  28. "os/signal"
  29. "path/filepath"
  30. "sort"
  31. "syscall"
  32. "time"
  33. )
  34. var (
  35. logger = conf.Log
  36. startTimeStamp int64
  37. version = ""
  38. ruleProcessor *processor.RuleProcessor
  39. streamProcessor *processor.StreamProcessor
  40. rulesetProcessor *processor.RulesetProcessor
  41. )
  42. // Create path if mount an empty dir. For edgeX, all the folders must be created priorly
  43. func createPaths() {
  44. dataDir, err := conf.GetDataLoc()
  45. if err != nil {
  46. panic(err)
  47. }
  48. dirs := []string{"uploads", "sources", "sinks", "functions", "services", "services/schemas", "connections"}
  49. for _, v := range dirs {
  50. // Create dir if not exist
  51. realDir := filepath.Join(dataDir, v)
  52. if _, err := os.Stat(realDir); os.IsNotExist(err) {
  53. if err := os.MkdirAll(realDir, os.ModePerm); err != nil {
  54. fmt.Printf("Failed to create dir %s: %v", realDir, err)
  55. }
  56. }
  57. }
  58. files := []string{"connections/connection.yaml"}
  59. for _, v := range files {
  60. // Create dir if not exist
  61. realFile := filepath.Join(dataDir, v)
  62. if _, err := os.Stat(realFile); os.IsNotExist(err) {
  63. if _, err := os.Create(realFile); err != nil {
  64. fmt.Printf("Failed to create file %s: %v", realFile, err)
  65. }
  66. }
  67. }
  68. }
  69. func StartUp(Version, LoadFileType string) {
  70. version = Version
  71. conf.LoadFileType = LoadFileType
  72. startTimeStamp = time.Now().Unix()
  73. createPaths()
  74. conf.InitConf()
  75. factory.InitClientsFactory()
  76. err := store.SetupWithKuiperConfig(conf.Config)
  77. if err != nil {
  78. panic(err)
  79. }
  80. ruleProcessor = processor.NewRuleProcessor()
  81. streamProcessor = processor.NewStreamProcessor()
  82. rulesetProcessor = processor.NewRulesetProcessor(ruleProcessor, streamProcessor)
  83. initRuleset()
  84. // register all extensions
  85. for k, v := range components {
  86. logger.Infof("register component %s", k)
  87. v.register()
  88. }
  89. // Bind the source, function, sink
  90. sort.Sort(entries)
  91. err = function.Initialize(entries)
  92. if err != nil {
  93. panic(err)
  94. }
  95. err = io.Initialize(entries)
  96. if err != nil {
  97. panic(err)
  98. }
  99. meta.Bind()
  100. registry = &RuleRegistry{internal: make(map[string]*RuleState)}
  101. //Start lookup tables
  102. streamProcessor.RecoverLookupTable()
  103. //Start rules
  104. if rules, err := ruleProcessor.GetAllRules(); err != nil {
  105. logger.Infof("Start rules error: %s", err)
  106. } else {
  107. logger.Info("Starting rules")
  108. var reply string
  109. for _, name := range rules {
  110. rule, err := ruleProcessor.GetRuleById(name)
  111. if err != nil {
  112. logger.Error(err)
  113. continue
  114. }
  115. //err = server.StartRule(rule, &reply)
  116. reply = recoverRule(rule)
  117. if 0 != len(reply) {
  118. logger.Info(reply)
  119. }
  120. }
  121. }
  122. //Start rest service
  123. srvRest := createRestServer(conf.Config.Basic.RestIp, conf.Config.Basic.RestPort, conf.Config.Basic.Authentication)
  124. go func() {
  125. var err error
  126. if conf.Config.Basic.RestTls == nil {
  127. err = srvRest.ListenAndServe()
  128. } else {
  129. err = srvRest.ListenAndServeTLS(conf.Config.Basic.RestTls.Certfile, conf.Config.Basic.RestTls.Keyfile)
  130. }
  131. if err != nil && err != http.ErrServerClosed {
  132. logger.Errorf("Error serving rest service: %s", err)
  133. }
  134. }()
  135. // Start extend services
  136. for k, v := range servers {
  137. logger.Infof("start service %s", k)
  138. v.serve()
  139. }
  140. //Startup message
  141. restHttpType := "http"
  142. if conf.Config.Basic.RestTls != nil {
  143. restHttpType = "https"
  144. }
  145. msg := fmt.Sprintf("Serving kuiper (version - %s) on port %d, and restful api on %s://%s:%d. \n", Version, conf.Config.Basic.Port, restHttpType, conf.Config.Basic.RestIp, conf.Config.Basic.RestPort)
  146. logger.Info(msg)
  147. fmt.Printf(msg)
  148. //Stop the services
  149. sigint := make(chan os.Signal, 1)
  150. signal.Notify(sigint, os.Interrupt, syscall.SIGTERM)
  151. <-sigint
  152. if err = srvRest.Shutdown(context.TODO()); err != nil {
  153. logger.Errorf("rest server shutdown error: %v", err)
  154. }
  155. logger.Info("rest server successfully shutdown.")
  156. // close extend services
  157. for k, v := range servers {
  158. logger.Infof("close service %s", k)
  159. v.close()
  160. }
  161. os.Exit(0)
  162. }
  163. func initRuleset() error {
  164. loc, err := conf.GetDataLoc()
  165. if err != nil {
  166. return err
  167. }
  168. signalFile := filepath.Join(loc, "initialized")
  169. if _, err := os.Stat(signalFile); errors.Is(err, os.ErrNotExist) {
  170. defer os.Create(signalFile)
  171. content, err := os.ReadFile(filepath.Join(loc, "init.json"))
  172. if err != nil {
  173. conf.Log.Infof("fail to read init file: %v", err)
  174. return nil
  175. }
  176. conf.Log.Infof("start to initialize ruleset")
  177. _, counts, err := rulesetProcessor.Import(content)
  178. conf.Log.Infof("initialzie %d streams, %d tables and %d rules", counts[0], counts[1], counts[2])
  179. }
  180. return nil
  181. }