system.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package service
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. net2 "net"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/IceWhaleTech/CasaOS/model"
  13. "github.com/IceWhaleTech/CasaOS/pkg/config"
  14. command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
  15. "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
  16. "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
  17. "github.com/shirou/gopsutil/v3/cpu"
  18. "github.com/shirou/gopsutil/v3/disk"
  19. "github.com/shirou/gopsutil/v3/host"
  20. "github.com/shirou/gopsutil/v3/mem"
  21. "github.com/shirou/gopsutil/v3/net"
  22. )
  23. type SystemService interface {
  24. UpdateSystemVersion(version string)
  25. GetSystemConfigDebug() []string
  26. GetCasaOSLogs(lineNumber int) string
  27. UpdateAssist()
  28. UpSystemPort(port string)
  29. GetTimeZone() string
  30. UpdateUSBAutoMount(state string)
  31. ExecUSBAutoMountShell(state string)
  32. UpAppOrderFile(str, id string)
  33. GetAppOrderFile(id string) []byte
  34. GetNet(physics bool) []string
  35. GetNetInfo() []net.IOCountersStat
  36. GetCpuCoreNum() int
  37. GetCpuPercent() float64
  38. GetMemInfo() map[string]interface{}
  39. GetCpuInfo() []cpu.InfoStat
  40. GetDirPath(path string) []model.Path
  41. GetDirPathOne(path string) (m model.Path)
  42. GetNetState(name string) string
  43. GetDiskInfo() *disk.UsageStat
  44. GetSysInfo() host.InfoStat
  45. GetDeviceTree() string
  46. CreateFile(path string) (int, error)
  47. RenameFile(oldF, newF string) (int, error)
  48. MkdirAll(path string) (int, error)
  49. }
  50. type systemService struct {
  51. }
  52. func (s *systemService) UpdateUSBAutoMount(state string) {
  53. config.ServerInfo.USBAutoMount = state
  54. config.Cfg.Section("server").Key("USBAutoMount").SetValue(state)
  55. config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
  56. }
  57. func (c *systemService) MkdirAll(path string) (int, error) {
  58. _, err := os.Stat(path)
  59. if err == nil {
  60. return common_err.DIR_ALREADY_EXISTS, nil
  61. } else {
  62. if os.IsNotExist(err) {
  63. os.MkdirAll(path, os.ModePerm)
  64. return common_err.SUCCESS, nil
  65. } else if strings.Contains(err.Error(), ": not a directory") {
  66. return common_err.FILE_OR_DIR_EXISTS, err
  67. }
  68. }
  69. return common_err.SERVICE_ERROR, err
  70. }
  71. func (c *systemService) RenameFile(oldF, newF string) (int, error) {
  72. _, err := os.Stat(newF)
  73. if err == nil {
  74. return common_err.DIR_ALREADY_EXISTS, nil
  75. } else {
  76. if os.IsNotExist(err) {
  77. err := os.Rename(oldF, newF)
  78. if err != nil {
  79. return common_err.SERVICE_ERROR, err
  80. }
  81. return common_err.SUCCESS, nil
  82. }
  83. }
  84. return common_err.SERVICE_ERROR, err
  85. }
  86. func (c *systemService) CreateFile(path string) (int, error) {
  87. _, err := os.Stat(path)
  88. if err == nil {
  89. return common_err.FILE_OR_DIR_EXISTS, nil
  90. } else {
  91. if os.IsNotExist(err) {
  92. file.CreateFile(path)
  93. return common_err.SUCCESS, nil
  94. }
  95. }
  96. return common_err.SERVICE_ERROR, err
  97. }
  98. func (c *systemService) GetDeviceTree() string {
  99. return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDeviceTree")
  100. }
  101. func (c *systemService) GetSysInfo() host.InfoStat {
  102. info, _ := host.Info()
  103. return *info
  104. }
  105. func (c *systemService) GetDiskInfo() *disk.UsageStat {
  106. path := "/"
  107. if runtime.GOOS == "windows" {
  108. path = "C:"
  109. }
  110. diskInfo, _ := disk.Usage(path)
  111. diskInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.UsedPercent), 64)
  112. diskInfo.InodesUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.InodesUsedPercent), 64)
  113. return diskInfo
  114. }
  115. func (c *systemService) GetNetState(name string) string {
  116. return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;CatNetCardState " + name)
  117. }
  118. func (c *systemService) GetDirPathOne(path string) (m model.Path) {
  119. f, err := os.Stat(path)
  120. if err != nil {
  121. return
  122. }
  123. m.IsDir = f.IsDir()
  124. m.Name = f.Name()
  125. m.Path = path
  126. m.Size = f.Size()
  127. m.Date = f.ModTime()
  128. return
  129. }
  130. func (c *systemService) GetDirPath(path string) []model.Path {
  131. if path == "/DATA" {
  132. sysType := runtime.GOOS
  133. if sysType == "windows" {
  134. path = "C:\\CasaOS\\DATA"
  135. }
  136. if sysType == "darwin" {
  137. path = "./CasaOS/DATA"
  138. }
  139. }
  140. ls, _ := ioutil.ReadDir(path)
  141. dirs := []model.Path{}
  142. if len(path) > 0 {
  143. for _, l := range ls {
  144. filePath := filepath.Join(path, l.Name())
  145. link, err := filepath.EvalSymlinks(filePath)
  146. if err != nil {
  147. link = filePath
  148. }
  149. temp := model.Path{Name: l.Name(), Path: filePath, IsDir: l.IsDir(), Date: l.ModTime(), Size: l.Size()}
  150. if filePath != link {
  151. file, _ := os.Stat(link)
  152. temp.IsDir = file.IsDir()
  153. }
  154. dirs = append(dirs, temp)
  155. }
  156. } else {
  157. dirs = append(dirs, model.Path{Name: "DATA", Path: "/DATA/", IsDir: true, Date: time.Now()})
  158. }
  159. return dirs
  160. }
  161. func (c *systemService) GetCpuInfo() []cpu.InfoStat {
  162. info, _ := cpu.Info()
  163. return info
  164. }
  165. func (c *systemService) GetMemInfo() map[string]interface{} {
  166. memInfo, _ := mem.VirtualMemory()
  167. memInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", memInfo.UsedPercent), 64)
  168. memData := make(map[string]interface{})
  169. memData["total"] = memInfo.Total
  170. memData["available"] = memInfo.Available
  171. memData["used"] = memInfo.Used
  172. memData["free"] = memInfo.Free
  173. memData["usedPercent"] = memInfo.UsedPercent
  174. return memData
  175. }
  176. func (c *systemService) GetCpuPercent() float64 {
  177. percent, _ := cpu.Percent(0, false)
  178. value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", percent[0]), 64)
  179. return value
  180. }
  181. func (c *systemService) GetCpuCoreNum() int {
  182. count, _ := cpu.Counts(false)
  183. return count
  184. }
  185. func (c *systemService) GetNetInfo() []net.IOCountersStat {
  186. parts, _ := net.IOCounters(true)
  187. return parts
  188. }
  189. func (c *systemService) GetNet(physics bool) []string {
  190. t := "1"
  191. if physics {
  192. t = "2"
  193. }
  194. return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetNetCard " + t)
  195. }
  196. func (s *systemService) UpdateSystemVersion(version string) {
  197. if file.Exists(config.AppInfo.LogPath + "/upgrade.log") {
  198. os.Remove(config.AppInfo.LogPath + "/upgrade.log")
  199. }
  200. file.CreateFile(config.AppInfo.LogPath + "/upgrade.log")
  201. //go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/LinkLeong/casaos-alpha/main/update.sh | bash")
  202. go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/update.sh | bash")
  203. //s.log.Error(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version)
  204. //s.log.Error(command2.ExecResultStr(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version))
  205. }
  206. func (s *systemService) UpdateAssist() {
  207. command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/assist.sh")
  208. }
  209. func (s *systemService) GetTimeZone() string {
  210. return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetTimeZone")
  211. }
  212. func (s *systemService) ExecUSBAutoMountShell(state string) {
  213. if state == "False" {
  214. command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Remove_File")
  215. } else {
  216. command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Move_File")
  217. }
  218. }
  219. func (s *systemService) GetSystemConfigDebug() []string {
  220. return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetSysInfo")
  221. }
  222. func (s *systemService) UpAppOrderFile(str, id string) {
  223. file.WriteToPath([]byte(str), config.AppInfo.DBPath+"/"+id, "app_order.json")
  224. }
  225. func (s *systemService) GetAppOrderFile(id string) []byte {
  226. return file.ReadFullFile(config.AppInfo.UserDataPath + "/" + id + "/app_order.json")
  227. }
  228. func (s *systemService) UpSystemPort(port string) {
  229. if len(port) > 0 && port != config.ServerInfo.HttpPort {
  230. config.Cfg.Section("server").Key("HttpPort").SetValue(port)
  231. config.ServerInfo.HttpPort = port
  232. }
  233. config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
  234. }
  235. func (s *systemService) GetCasaOSLogs(lineNumber int) string {
  236. file, err := os.Open(filepath.Join(config.AppInfo.LogPath, fmt.Sprintf("%s.%s",
  237. config.AppInfo.LogSaveName,
  238. config.AppInfo.LogFileExt,
  239. )))
  240. if err != nil {
  241. return err.Error()
  242. }
  243. defer file.Close()
  244. content, err := ioutil.ReadAll(file)
  245. if err != nil {
  246. return err.Error()
  247. }
  248. return string(content)
  249. }
  250. func GetDeviceAllIP() []string {
  251. var address []string
  252. addrs, err := net2.InterfaceAddrs()
  253. if err != nil {
  254. return address
  255. }
  256. for _, a := range addrs {
  257. if ipNet, ok := a.(*net2.IPNet); ok && !ipNet.IP.IsLoopback() {
  258. if ipNet.IP.To16() != nil {
  259. address = append(address, ipNet.IP.String())
  260. }
  261. }
  262. }
  263. return address
  264. }
  265. func NewSystemService() SystemService {
  266. return &systemService{}
  267. }