server.go 5.5 KB

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