server.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Copyright 2022-2023 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. "net/http"
  20. "os"
  21. "os/signal"
  22. "path/filepath"
  23. "sort"
  24. "syscall"
  25. "time"
  26. "go.uber.org/automaxprocs/maxprocs"
  27. "github.com/lf-edge/ekuiper/internal/binder/function"
  28. "github.com/lf-edge/ekuiper/internal/binder/io"
  29. "github.com/lf-edge/ekuiper/internal/binder/meta"
  30. "github.com/lf-edge/ekuiper/internal/conf"
  31. "github.com/lf-edge/ekuiper/internal/keyedstate"
  32. meta2 "github.com/lf-edge/ekuiper/internal/meta"
  33. "github.com/lf-edge/ekuiper/internal/pkg/store"
  34. "github.com/lf-edge/ekuiper/internal/processor"
  35. "github.com/lf-edge/ekuiper/internal/topo/connection/factory"
  36. "github.com/lf-edge/ekuiper/internal/topo/rule"
  37. "github.com/lf-edge/ekuiper/pkg/ast"
  38. "github.com/lf-edge/ekuiper/pkg/cast"
  39. )
  40. var (
  41. logger = conf.Log
  42. startTimeStamp int64
  43. version = ""
  44. ruleProcessor *processor.RuleProcessor
  45. streamProcessor *processor.StreamProcessor
  46. rulesetProcessor *processor.RulesetProcessor
  47. ruleMigrationProcessor *RuleMigrationProcessor
  48. )
  49. // Create path if mount an empty dir. For edgeX, all the folders must be created priorly
  50. func createPaths() {
  51. dataDir, err := conf.GetDataLoc()
  52. if err != nil {
  53. panic(err)
  54. }
  55. dirs := []string{"uploads", "sources", "sinks", "functions", "services", "services/schemas", "connections"}
  56. for _, v := range dirs {
  57. // Create dir if not exist
  58. realDir := filepath.Join(dataDir, v)
  59. if _, err := os.Stat(realDir); os.IsNotExist(err) {
  60. if err := os.MkdirAll(realDir, os.ModePerm); err != nil {
  61. fmt.Printf("Failed to create dir %s: %v", realDir, err)
  62. }
  63. }
  64. }
  65. files := []string{"connections/connection.yaml"}
  66. for _, v := range files {
  67. // Create dir if not exist
  68. realFile := filepath.Join(dataDir, v)
  69. if _, err := os.Stat(realFile); os.IsNotExist(err) {
  70. if _, err := os.Create(realFile); err != nil {
  71. fmt.Printf("Failed to create file %s: %v", realFile, err)
  72. }
  73. }
  74. }
  75. }
  76. func StartUp(Version string) {
  77. version = Version
  78. startTimeStamp = time.Now().Unix()
  79. createPaths()
  80. conf.InitConf()
  81. factory.InitClientsFactory()
  82. undo, _ := maxprocs.Set(maxprocs.Logger(conf.Log.Infof))
  83. defer undo()
  84. err := store.SetupWithKuiperConfig(conf.Config)
  85. if err != nil {
  86. panic(err)
  87. }
  88. keyedstate.InitKeyedStateKV()
  89. meta2.InitYamlConfigManager()
  90. ruleProcessor = processor.NewRuleProcessor()
  91. streamProcessor = processor.NewStreamProcessor()
  92. rulesetProcessor = processor.NewRulesetProcessor(ruleProcessor, streamProcessor)
  93. ruleMigrationProcessor = NewRuleMigrationProcessor(ruleProcessor, streamProcessor)
  94. // register all extensions
  95. for k, v := range components {
  96. logger.Infof("register component %s", k)
  97. v.register()
  98. }
  99. // Bind the source, function, sink
  100. sort.Sort(entries)
  101. err = function.Initialize(entries)
  102. if err != nil {
  103. panic(err)
  104. }
  105. err = io.Initialize(entries)
  106. if err != nil {
  107. panic(err)
  108. }
  109. meta.Bind()
  110. initRuleset()
  111. registry = &RuleRegistry{internal: make(map[string]*rule.RuleState)}
  112. // Start lookup tables
  113. streamProcessor.RecoverLookupTable()
  114. // Start rules
  115. if rules, err := ruleProcessor.GetAllRules(); err != nil {
  116. logger.Infof("Start rules error: %s", err)
  117. } else {
  118. logger.Info("Starting rules")
  119. var reply string
  120. for _, name := range rules {
  121. rule, err := ruleProcessor.GetRuleById(name)
  122. if err != nil {
  123. logger.Error(err)
  124. continue
  125. }
  126. // err = server.StartRule(rule, &reply)
  127. reply = recoverRule(rule)
  128. if 0 != len(reply) {
  129. logger.Info(reply)
  130. }
  131. }
  132. }
  133. // Start rest service
  134. srvRest := createRestServer(conf.Config.Basic.RestIp, conf.Config.Basic.RestPort, conf.Config.Basic.Authentication)
  135. go func() {
  136. var err error
  137. if conf.Config.Basic.RestTls == nil {
  138. err = srvRest.ListenAndServe()
  139. } else {
  140. err = srvRest.ListenAndServeTLS(conf.Config.Basic.RestTls.Certfile, conf.Config.Basic.RestTls.Keyfile)
  141. }
  142. if err != nil && err != http.ErrServerClosed {
  143. logger.Errorf("Error serving rest service: %s", err)
  144. }
  145. }()
  146. // Start extend services
  147. for k, v := range servers {
  148. logger.Infof("start service %s", k)
  149. v.serve()
  150. }
  151. // Startup message
  152. restHttpType := "http"
  153. if conf.Config.Basic.RestTls != nil {
  154. restHttpType = "https"
  155. }
  156. msg := fmt.Sprintf("Serving kuiper (version - %s) on port %d, and restful api on %s://%s.", Version, conf.Config.Basic.Port, restHttpType, cast.JoinHostPortInt(conf.Config.Basic.RestIp, conf.Config.Basic.RestPort))
  157. logger.Info(msg)
  158. fmt.Println(msg)
  159. // Stop the services
  160. sigint := make(chan os.Signal, 1)
  161. signal.Notify(sigint, os.Interrupt, syscall.SIGTERM)
  162. <-sigint
  163. if err = srvRest.Shutdown(context.TODO()); err != nil {
  164. logger.Errorf("rest server shutdown error: %v", err)
  165. }
  166. logger.Info("rest server successfully shutdown.")
  167. // close extend services
  168. for k, v := range servers {
  169. logger.Infof("close service %s", k)
  170. v.close()
  171. }
  172. os.Exit(0)
  173. }
  174. func initRuleset() error {
  175. loc, err := conf.GetDataLoc()
  176. if err != nil {
  177. return err
  178. }
  179. signalFile := filepath.Join(loc, "initialized")
  180. if _, err := os.Stat(signalFile); errors.Is(err, os.ErrNotExist) {
  181. defer os.Create(signalFile)
  182. content, err := os.ReadFile(filepath.Join(loc, "init.json"))
  183. if err != nil {
  184. conf.Log.Errorf("fail to read init file: %v", err)
  185. return nil
  186. }
  187. conf.Log.Infof("start to initialize ruleset")
  188. _, counts, err := rulesetProcessor.Import(content)
  189. if err != nil {
  190. conf.Log.Errorf("fail to import ruleset: %v", err)
  191. return nil
  192. }
  193. conf.Log.Infof("initialzie %d streams, %d tables and %d rules", counts[0], counts[1], counts[2])
  194. }
  195. return nil
  196. }
  197. func resetAllRules() error {
  198. rules, err := ruleProcessor.GetAllRules()
  199. if err != nil {
  200. return err
  201. }
  202. for _, name := range rules {
  203. _ = deleteRule(name)
  204. _, err := ruleProcessor.ExecDrop(name)
  205. if err != nil {
  206. logger.Warnf("delete rule: %s with error %v", name, err)
  207. continue
  208. }
  209. }
  210. return nil
  211. }
  212. func resetAllStreams() error {
  213. allStreams, err := streamProcessor.GetAll()
  214. if err != nil {
  215. return err
  216. }
  217. Streams := allStreams["streams"]
  218. Tables := allStreams["tables"]
  219. for name := range Streams {
  220. _, err2 := streamProcessor.DropStream(name, ast.TypeStream)
  221. if err2 != nil {
  222. logger.Warnf("streamProcessor DropStream %s error: %v", name, err2)
  223. continue
  224. }
  225. }
  226. for name := range Tables {
  227. _, err2 := streamProcessor.DropStream(name, ast.TypeTable)
  228. if err2 != nil {
  229. logger.Warnf("streamProcessor DropTable %s error: %v", name, err2)
  230. continue
  231. }
  232. }
  233. return nil
  234. }