main.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "path/filepath"
  8. "time"
  9. "github.com/IceWhaleTech/CasaOS-Common/model"
  10. "github.com/IceWhaleTech/CasaOS-Common/utils/constants"
  11. "github.com/IceWhaleTech/CasaOS-Common/utils/logger"
  12. "github.com/IceWhaleTech/CasaOS/pkg/cache"
  13. "github.com/IceWhaleTech/CasaOS/pkg/config"
  14. "github.com/IceWhaleTech/CasaOS/pkg/sqlite"
  15. "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
  16. "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
  17. "github.com/IceWhaleTech/CasaOS/route"
  18. "github.com/IceWhaleTech/CasaOS/service"
  19. "github.com/IceWhaleTech/CasaOS/types"
  20. "github.com/coreos/go-systemd/daemon"
  21. "github.com/gin-gonic/gin"
  22. "go.uber.org/zap"
  23. "github.com/robfig/cron"
  24. "gorm.io/gorm"
  25. )
  26. const LOCALHOST = "127.0.0.1"
  27. var sqliteDB *gorm.DB
  28. var (
  29. commit = "private build"
  30. date = "private build"
  31. configFlag = flag.String("c", "", "config address")
  32. dbFlag = flag.String("db", "", "db path")
  33. versionFlag = flag.Bool("v", false, "version")
  34. )
  35. func init() {
  36. flag.Parse()
  37. if *versionFlag {
  38. fmt.Println("v" + types.CURRENTVERSION)
  39. return
  40. }
  41. println("git commit:", commit)
  42. println("build date:", date)
  43. config.InitSetup(*configFlag)
  44. logger.LogInit(config.AppInfo.LogPath, config.AppInfo.LogSaveName, config.AppInfo.LogFileExt)
  45. if len(*dbFlag) == 0 {
  46. *dbFlag = config.AppInfo.DBPath + "/db"
  47. }
  48. sqliteDB = sqlite.GetDb(*dbFlag)
  49. // gredis.GetRedisConn(config.RedisInfo),
  50. service.MyService = service.NewService(sqliteDB, config.CommonInfo.RuntimePath, route.SocketIo())
  51. service.Cache = cache.Init()
  52. service.GetCPUThermalZone()
  53. route.InitFunction()
  54. }
  55. // @title casaOS API
  56. // @version 1.0.0
  57. // @contact.name lauren.pan
  58. // @contact.url https://www.zimaboard.com
  59. // @contact.email lauren.pan@icewhale.org
  60. // @description casaOS v1版本api
  61. // @host 192.168.2.217:8089
  62. // @securityDefinitions.apikey ApiKeyAuth
  63. // @in header
  64. // @name Authorization
  65. // @BasePath /v1
  66. func main() {
  67. if *versionFlag {
  68. return
  69. }
  70. // model.Setup()
  71. // gredis.Setup()
  72. r := route.InitRouter()
  73. defer service.SocketServer.Close()
  74. r.GET("/v1/socketio/*any", gin.WrapH(service.SocketServer))
  75. r.POST("/v1/socketio/*any", gin.WrapH(service.SocketServer))
  76. // service.SyncTask(sqliteDB)
  77. cron2 := cron.New()
  78. // every day execution
  79. err := cron2.AddFunc("0/5 * * * * *", func() {
  80. if service.ClientCount > 0 {
  81. // route.SendNetINfoBySocket()
  82. // route.SendCPUBySocket()
  83. // route.SendMemBySocket()
  84. // route.SendDiskBySocket()
  85. // route.SendUSBBySocket()
  86. route.SendAllHardwareStatusBySocket()
  87. }
  88. })
  89. if err != nil {
  90. fmt.Println(err)
  91. }
  92. cron2.Start()
  93. defer cron2.Stop()
  94. listener, err := net.Listen("tcp", net.JoinHostPort(LOCALHOST, "0"))
  95. if err != nil {
  96. panic(err)
  97. }
  98. routers := []string{"sys", "port", "file", "folder", "batch", "image", "samba", "notify", "socketio"}
  99. for _, v := range routers {
  100. err = service.MyService.Gateway().CreateRoute(&model.Route{
  101. Path: "/v1/" + v,
  102. Target: "http://" + listener.Addr().String(),
  103. })
  104. if err != nil {
  105. fmt.Println("err", err)
  106. panic(err)
  107. }
  108. }
  109. go func() {
  110. time.Sleep(time.Second * 2)
  111. // v0.3.6
  112. if config.ServerInfo.HttpPort != "" {
  113. changePort := model.ChangePortRequest{}
  114. changePort.Port = config.ServerInfo.HttpPort
  115. err := service.MyService.Gateway().ChangePort(&changePort)
  116. if err == nil {
  117. config.Cfg.Section("server").Key("HttpPort").SetValue("")
  118. config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
  119. }
  120. }
  121. }()
  122. urlFilePath := filepath.Join(config.CommonInfo.RuntimePath, "casaos.url")
  123. if err := file.CreateFileAndWriteContent(urlFilePath, "http://"+listener.Addr().String()); err != nil {
  124. logger.Error("error when creating address file", zap.Error(err),
  125. zap.Any("address", listener.Addr().String()),
  126. zap.Any("filepath", urlFilePath),
  127. )
  128. }
  129. // run any script that needs to be executed
  130. scriptDirectory := filepath.Join(constants.DefaultConfigPath, "start.d")
  131. command.ExecuteScripts(scriptDirectory)
  132. if supported, err := daemon.SdNotify(false, daemon.SdNotifyReady); err != nil {
  133. logger.Error("Failed to notify systemd that casaos main service is ready", zap.Any("error", err))
  134. } else if supported {
  135. logger.Info("Notified systemd that casaos main service is ready")
  136. } else {
  137. logger.Info("This process is not running as a systemd service.")
  138. }
  139. s := &http.Server{
  140. Handler: r,
  141. ReadHeaderTimeout: 5 * time.Second, // fix G112: Potential slowloris attack (see https://github.com/securego/gosec)
  142. }
  143. logger.Info("CasaOS main service is listening...", zap.Any("address", listener.Addr().String()))
  144. 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)
  145. if err != nil {
  146. panic(err)
  147. }
  148. }