main.go 7.0 KB

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