main.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. //go:generate bash -c "mkdir -p codegen && go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen@v1.12.4 -generate types,server,spec -package codegen api/casaos/openapi.yaml > codegen/casaos_api.go"
  2. //go:generate bash -c "mkdir -p codegen/message_bus && go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen@v1.12.4 -generate types,client -package message_bus https://raw.githubusercontent.com/IceWhaleTech/CasaOS-MessageBus/main/api/message_bus/openapi.yaml > codegen/message_bus/api.go"
  3. package main
  4. import (
  5. "context"
  6. _ "embed"
  7. "flag"
  8. "fmt"
  9. "net"
  10. "net/http"
  11. "path/filepath"
  12. "time"
  13. "github.com/IceWhaleTech/CasaOS-Common/model"
  14. "github.com/IceWhaleTech/CasaOS-Common/utils/constants"
  15. "github.com/IceWhaleTech/CasaOS-Common/utils/logger"
  16. util_http "github.com/IceWhaleTech/CasaOS-Common/utils/http"
  17. "github.com/IceWhaleTech/CasaOS/common"
  18. "github.com/IceWhaleTech/CasaOS/pkg/cache"
  19. "github.com/IceWhaleTech/CasaOS/pkg/config"
  20. "github.com/IceWhaleTech/CasaOS/pkg/sqlite"
  21. "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
  22. "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
  23. "github.com/IceWhaleTech/CasaOS/route"
  24. "github.com/IceWhaleTech/CasaOS/service"
  25. "github.com/coreos/go-systemd/daemon"
  26. "go.uber.org/zap"
  27. "github.com/robfig/cron/v3"
  28. "gorm.io/gorm"
  29. )
  30. const LOCALHOST = "127.0.0.1"
  31. var sqliteDB *gorm.DB
  32. var (
  33. commit = "private build"
  34. date = "private build"
  35. //go:embed api/index.html
  36. _docHTML string
  37. //go:embed api/casaos/openapi.yaml
  38. _docYAML string
  39. //go:embed build/sysroot/etc/casaos/casaos.conf.sample
  40. _confSample string
  41. configFlag = flag.String("c", "", "config address")
  42. dbFlag = flag.String("db", "", "db path")
  43. versionFlag = flag.Bool("v", false, "version")
  44. )
  45. func init() {
  46. flag.Parse()
  47. if *versionFlag {
  48. fmt.Println("v" + common.VERSION)
  49. return
  50. }
  51. println("git commit:", commit)
  52. println("build date:", date)
  53. config.InitSetup(*configFlag, _confSample)
  54. logger.LogInit(config.AppInfo.LogPath, config.AppInfo.LogSaveName, config.AppInfo.LogFileExt)
  55. if len(*dbFlag) == 0 {
  56. *dbFlag = config.AppInfo.DBPath + "/db"
  57. }
  58. sqliteDB = sqlite.GetDb(*dbFlag)
  59. // gredis.GetRedisConn(config.RedisInfo),
  60. service.MyService = service.NewService(sqliteDB, config.CommonInfo.RuntimePath)
  61. service.Cache = cache.Init()
  62. service.GetCPUThermalZone()
  63. route.InitFunction()
  64. //service.MyService.System().GenreateSystemEntry()
  65. ///
  66. //service.MountLists = make(map[string]*mountlib.MountPoint)
  67. //configfile.Install()
  68. }
  69. // @title casaOS API
  70. // @version 1.0.0
  71. // @contact.name lauren.pan
  72. // @contact.url https://www.zimaboard.com
  73. // @contact.email lauren.pan@icewhale.org
  74. // @description casaOS v1版本api
  75. // @host 192.168.2.217:8089
  76. // @securityDefinitions.apikey ApiKeyAuth
  77. // @in header
  78. // @name Authorization
  79. // @BasePath /v1
  80. func main() {
  81. if *versionFlag {
  82. return
  83. }
  84. v1Router := route.InitV1Router()
  85. v2Router := route.InitV2Router()
  86. v2DocRouter := route.InitV2DocRouter(_docHTML, _docYAML)
  87. v3File := route.InitFile()
  88. mux := &util_http.HandlerMultiplexer{
  89. HandlerMap: map[string]http.Handler{
  90. "v1": v1Router,
  91. "v2": v2Router,
  92. "v3": v3File,
  93. "doc": v2DocRouter,
  94. },
  95. }
  96. crontab := cron.New(cron.WithSeconds())
  97. if _, err := crontab.AddFunc("@every 5s", route.SendAllHardwareStatusBySocket); err != nil {
  98. logger.Error("add crontab error", zap.Error(err))
  99. }
  100. crontab.Start()
  101. defer crontab.Stop()
  102. listener, err := net.Listen("tcp", net.JoinHostPort(LOCALHOST, "0"))
  103. if err != nil {
  104. panic(err)
  105. }
  106. routers := []string{
  107. "/v1/sys",
  108. "/v1/port",
  109. "/v1/file",
  110. "/v1/folder",
  111. "/v1/batch",
  112. "/v1/image",
  113. "/v1/samba",
  114. "/v1/notify",
  115. "/v1/driver",
  116. "/v1/cloud",
  117. "/v1/recover",
  118. "/v1/other",
  119. "/v1/zt",
  120. "/v1/test",
  121. route.V2APIPath,
  122. route.V2DocPath,
  123. route.V3FilePath,
  124. }
  125. for _, apiPath := range routers {
  126. err = service.MyService.Gateway().CreateRoute(&model.Route{
  127. Path: apiPath,
  128. Target: "http://" + listener.Addr().String(),
  129. })
  130. if err != nil {
  131. fmt.Println("err", err)
  132. panic(err)
  133. }
  134. }
  135. // register at message bus
  136. for i := 0; i < 10; i++ {
  137. response, err := service.MyService.MessageBus().RegisterEventTypesWithResponse(context.Background(), common.EventTypes)
  138. if err != nil {
  139. logger.Error("error when trying to register one or more event types - some event type will not be discoverable", zap.Error(err))
  140. }
  141. if response != nil && response.StatusCode() != http.StatusOK {
  142. logger.Error("error when trying to register one or more event types - some event type will not be discoverable", zap.String("status", response.Status()), zap.String("body", string(response.Body)))
  143. }
  144. if response.StatusCode() == http.StatusOK {
  145. break
  146. }
  147. time.Sleep(time.Second)
  148. }
  149. go func() {
  150. time.Sleep(time.Second * 2)
  151. // v0.3.6
  152. if config.ServerInfo.HttpPort != "" {
  153. changePort := model.ChangePortRequest{}
  154. changePort.Port = config.ServerInfo.HttpPort
  155. err := service.MyService.Gateway().ChangePort(&changePort)
  156. if err == nil {
  157. config.Cfg.Section("server").Key("HttpPort").SetValue("")
  158. config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
  159. }
  160. }
  161. }()
  162. urlFilePath := filepath.Join(config.CommonInfo.RuntimePath, "casaos.url")
  163. if err := file.CreateFileAndWriteContent(urlFilePath, "http://"+listener.Addr().String()); err != nil {
  164. logger.Error("error when creating address file", zap.Error(err),
  165. zap.Any("address", listener.Addr().String()),
  166. zap.Any("filepath", urlFilePath),
  167. )
  168. }
  169. // run any script that needs to be executed
  170. scriptDirectory := filepath.Join(constants.DefaultConfigPath, "start.d")
  171. command.ExecuteScripts(scriptDirectory)
  172. if supported, err := daemon.SdNotify(false, daemon.SdNotifyReady); err != nil {
  173. logger.Error("Failed to notify systemd that casaos main service is ready", zap.Any("error", err))
  174. } else if supported {
  175. logger.Info("Notified systemd that casaos main service is ready")
  176. } else {
  177. logger.Info("This process is not running as a systemd service.")
  178. }
  179. // http.HandleFunc("/v1/file/test", func(w http.ResponseWriter, r *http.Request) {
  180. // //http.ServeFile(w, r, r.URL.Path[1:])
  181. // http.ServeFile(w, r, "/DATA/test.img")
  182. // })
  183. // go http.ListenAndServe(":8081", nil)
  184. s := &http.Server{
  185. Handler: mux,
  186. ReadHeaderTimeout: 5 * time.Second, // fix G112: Potential slowloris attack (see https://github.com/securego/gosec)
  187. }
  188. logger.Info("CasaOS main service is listening...", zap.Any("address", listener.Addr().String()))
  189. // defer service.MyService.Storage().UnmountAllStorage()
  190. err = s.Serve(listener) // not using http.serve() to fix G114: Use of net/http serve function that has no support for setting timeouts (see https://github.com/securego/gosec)
  191. if err != nil {
  192. panic(err)
  193. }
  194. }