server.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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, LoadFileType string) {
  77. version = Version
  78. conf.LoadFileType = LoadFileType
  79. startTimeStamp = time.Now().Unix()
  80. createPaths()
  81. conf.InitConf()
  82. factory.InitClientsFactory()
  83. undo, _ := maxprocs.Set(maxprocs.Logger(conf.Log.Infof))
  84. defer undo()
  85. err := store.SetupWithKuiperConfig(conf.Config)
  86. if err != nil {
  87. panic(err)
  88. }
  89. keyedstate.InitKeyedStateKV()
  90. meta2.InitYamlConfigManager()
  91. ruleProcessor = processor.NewRuleProcessor()
  92. streamProcessor = processor.NewStreamProcessor()
  93. rulesetProcessor = processor.NewRulesetProcessor(ruleProcessor, streamProcessor)
  94. ruleMigrationProcessor = NewRuleMigrationProcessor(ruleProcessor, streamProcessor)
  95. // register all extensions
  96. for k, v := range components {
  97. logger.Infof("register component %s", k)
  98. v.register()
  99. }
  100. // Bind the source, function, sink
  101. sort.Sort(entries)
  102. err = function.Initialize(entries)
  103. if err != nil {
  104. panic(err)
  105. }
  106. err = io.Initialize(entries)
  107. if err != nil {
  108. panic(err)
  109. }
  110. meta.Bind()
  111. initRuleset()
  112. registry = &RuleRegistry{internal: make(map[string]*rule.RuleState)}
  113. // Start lookup tables
  114. streamProcessor.RecoverLookupTable()
  115. // Start rules
  116. if rules, err := ruleProcessor.GetAllRules(); err != nil {
  117. logger.Infof("Start rules error: %s", err)
  118. } else {
  119. logger.Info("Starting rules")
  120. var reply string
  121. for _, name := range rules {
  122. rule, err := ruleProcessor.GetRuleById(name)
  123. if err != nil {
  124. logger.Error(err)
  125. continue
  126. }
  127. // err = server.StartRule(rule, &reply)
  128. reply = recoverRule(rule)
  129. if 0 != len(reply) {
  130. logger.Info(reply)
  131. }
  132. }
  133. }
  134. // Start rest service
  135. srvRest := createRestServer(conf.Config.Basic.RestIp, conf.Config.Basic.RestPort, conf.Config.Basic.Authentication)
  136. go func() {
  137. var err error
  138. if conf.Config.Basic.RestTls == nil {
  139. err = srvRest.ListenAndServe()
  140. } else {
  141. err = srvRest.ListenAndServeTLS(conf.Config.Basic.RestTls.Certfile, conf.Config.Basic.RestTls.Keyfile)
  142. }
  143. if err != nil && err != http.ErrServerClosed {
  144. logger.Errorf("Error serving rest service: %s", err)
  145. }
  146. }()
  147. // Start extend services
  148. for k, v := range servers {
  149. logger.Infof("start service %s", k)
  150. v.serve()
  151. }
  152. // Startup message
  153. restHttpType := "http"
  154. if conf.Config.Basic.RestTls != nil {
  155. restHttpType = "https"
  156. }
  157. 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))
  158. logger.Info(msg)
  159. fmt.Println(msg)
  160. // Stop the services
  161. sigint := make(chan os.Signal, 1)
  162. signal.Notify(sigint, os.Interrupt, syscall.SIGTERM)
  163. <-sigint
  164. if err = srvRest.Shutdown(context.TODO()); err != nil {
  165. logger.Errorf("rest server shutdown error: %v", err)
  166. }
  167. logger.Info("rest server successfully shutdown.")
  168. // close extend services
  169. for k, v := range servers {
  170. logger.Infof("close service %s", k)
  171. v.close()
  172. }
  173. os.Exit(0)
  174. }
  175. func initRuleset() error {
  176. loc, err := conf.GetDataLoc()
  177. if err != nil {
  178. return err
  179. }
  180. signalFile := filepath.Join(loc, "initialized")
  181. if _, err := os.Stat(signalFile); errors.Is(err, os.ErrNotExist) {
  182. defer os.Create(signalFile)
  183. content, err := os.ReadFile(filepath.Join(loc, "init.json"))
  184. if err != nil {
  185. conf.Log.Errorf("fail to read init file: %v", err)
  186. return nil
  187. }
  188. conf.Log.Infof("start to initialize ruleset")
  189. _, counts, err := rulesetProcessor.Import(content)
  190. if err != nil {
  191. conf.Log.Errorf("fail to import ruleset: %v", err)
  192. return nil
  193. }
  194. conf.Log.Infof("initialzie %d streams, %d tables and %d rules", counts[0], counts[1], counts[2])
  195. }
  196. return nil
  197. }
  198. func resetAllRules() error {
  199. rules, err := ruleProcessor.GetAllRules()
  200. if err != nil {
  201. return err
  202. }
  203. for _, name := range rules {
  204. _ = deleteRule(name)
  205. _, err := ruleProcessor.ExecDrop(name)
  206. if err != nil {
  207. logger.Warnf("delete rule: %s with error %v", name, err)
  208. continue
  209. }
  210. }
  211. return nil
  212. }
  213. func resetAllStreams() error {
  214. allStreams, err := streamProcessor.GetAll()
  215. if err != nil {
  216. return err
  217. }
  218. Streams := allStreams["streams"]
  219. Tables := allStreams["tables"]
  220. for name := range Streams {
  221. _, err2 := streamProcessor.DropStream(name, ast.TypeStream)
  222. if err2 != nil {
  223. logger.Warnf("streamProcessor DropStream %s error: %v", name, err2)
  224. continue
  225. }
  226. }
  227. for name := range Tables {
  228. _, err2 := streamProcessor.DropStream(name, ast.TypeTable)
  229. if err2 != nil {
  230. logger.Warnf("streamProcessor DropTable %s error: %v", name, err2)
  231. continue
  232. }
  233. }
  234. return nil
  235. }