system.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. IsServiceRunning(name string) bool
  50. GetCPUTemperature() int
  51. GetCPUPower() map[string]string
  52. }
  53. type systemService struct {
  54. }
  55. func (s *systemService) UpdateUSBAutoMount(state string) {
  56. config.ServerInfo.USBAutoMount = state
  57. config.Cfg.Section("server").Key("USBAutoMount").SetValue(state)
  58. config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
  59. }
  60. func (c *systemService) MkdirAll(path string) (int, error) {
  61. _, err := os.Stat(path)
  62. if err == nil {
  63. return common_err.DIR_ALREADY_EXISTS, nil
  64. } else {
  65. if os.IsNotExist(err) {
  66. os.MkdirAll(path, os.ModePerm)
  67. return common_err.SUCCESS, nil
  68. } else if strings.Contains(err.Error(), ": not a directory") {
  69. return common_err.FILE_OR_DIR_EXISTS, err
  70. }
  71. }
  72. return common_err.SERVICE_ERROR, err
  73. }
  74. func (c *systemService) RenameFile(oldF, newF string) (int, error) {
  75. _, err := os.Stat(newF)
  76. if err == nil {
  77. return common_err.DIR_ALREADY_EXISTS, nil
  78. } else {
  79. if os.IsNotExist(err) {
  80. err := os.Rename(oldF, newF)
  81. if err != nil {
  82. return common_err.SERVICE_ERROR, err
  83. }
  84. return common_err.SUCCESS, nil
  85. }
  86. }
  87. return common_err.SERVICE_ERROR, err
  88. }
  89. func (c *systemService) CreateFile(path string) (int, error) {
  90. _, err := os.Stat(path)
  91. if err == nil {
  92. return common_err.FILE_OR_DIR_EXISTS, nil
  93. } else {
  94. if os.IsNotExist(err) {
  95. file.CreateFile(path)
  96. return common_err.SUCCESS, nil
  97. }
  98. }
  99. return common_err.SERVICE_ERROR, err
  100. }
  101. func (c *systemService) GetDeviceTree() string {
  102. return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDeviceTree")
  103. }
  104. func (c *systemService) GetSysInfo() host.InfoStat {
  105. info, _ := host.Info()
  106. return *info
  107. }
  108. func (c *systemService) GetDiskInfo() *disk.UsageStat {
  109. path := "/"
  110. if runtime.GOOS == "windows" {
  111. path = "C:"
  112. }
  113. diskInfo, _ := disk.Usage(path)
  114. diskInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.UsedPercent), 64)
  115. diskInfo.InodesUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.InodesUsedPercent), 64)
  116. return diskInfo
  117. }
  118. func (c *systemService) GetNetState(name string) string {
  119. return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;CatNetCardState " + name)
  120. }
  121. func (c *systemService) GetDirPathOne(path string) (m model.Path) {
  122. f, err := os.Stat(path)
  123. if err != nil {
  124. return
  125. }
  126. m.IsDir = f.IsDir()
  127. m.Name = f.Name()
  128. m.Path = path
  129. m.Size = f.Size()
  130. m.Date = f.ModTime()
  131. return
  132. }
  133. func (c *systemService) GetDirPath(path string) []model.Path {
  134. if path == "/DATA" {
  135. sysType := runtime.GOOS
  136. if sysType == "windows" {
  137. path = "C:\\CasaOS\\DATA"
  138. }
  139. if sysType == "darwin" {
  140. path = "./CasaOS/DATA"
  141. }
  142. }
  143. ls, _ := ioutil.ReadDir(path)
  144. dirs := []model.Path{}
  145. if len(path) > 0 {
  146. for _, l := range ls {
  147. filePath := filepath.Join(path, l.Name())
  148. link, err := filepath.EvalSymlinks(filePath)
  149. if err != nil {
  150. link = filePath
  151. }
  152. temp := model.Path{Name: l.Name(), Path: filePath, IsDir: l.IsDir(), Date: l.ModTime(), Size: l.Size()}
  153. if filePath != link {
  154. file, _ := os.Stat(link)
  155. temp.IsDir = file.IsDir()
  156. }
  157. dirs = append(dirs, temp)
  158. }
  159. } else {
  160. dirs = append(dirs, model.Path{Name: "DATA", Path: "/DATA/", IsDir: true, Date: time.Now()})
  161. }
  162. return dirs
  163. }
  164. func (c *systemService) GetCpuInfo() []cpu.InfoStat {
  165. info, _ := cpu.Info()
  166. return info
  167. }
  168. func (c *systemService) GetMemInfo() map[string]interface{} {
  169. memInfo, _ := mem.VirtualMemory()
  170. memInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", memInfo.UsedPercent), 64)
  171. memData := make(map[string]interface{})
  172. memData["total"] = memInfo.Total
  173. memData["available"] = memInfo.Available
  174. memData["used"] = memInfo.Used
  175. memData["free"] = memInfo.Free
  176. memData["usedPercent"] = memInfo.UsedPercent
  177. return memData
  178. }
  179. func (c *systemService) GetCpuPercent() float64 {
  180. percent, _ := cpu.Percent(0, false)
  181. value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", percent[0]), 64)
  182. return value
  183. }
  184. func (c *systemService) GetCpuCoreNum() int {
  185. count, _ := cpu.Counts(false)
  186. return count
  187. }
  188. func (c *systemService) GetNetInfo() []net.IOCountersStat {
  189. parts, _ := net.IOCounters(true)
  190. return parts
  191. }
  192. func (c *systemService) GetNet(physics bool) []string {
  193. t := "1"
  194. if physics {
  195. t = "2"
  196. }
  197. return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetNetCard " + t)
  198. }
  199. func (s *systemService) UpdateSystemVersion(version string) {
  200. if file.Exists(config.AppInfo.LogPath + "/upgrade.log") {
  201. os.Remove(config.AppInfo.LogPath + "/upgrade.log")
  202. }
  203. file.CreateFile(config.AppInfo.LogPath + "/upgrade.log")
  204. //go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/LinkLeong/casaos-alpha/main/update.sh | bash")
  205. go command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/update.sh | bash")
  206. //s.log.Error(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version)
  207. //s.log.Error(command2.ExecResultStr(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version))
  208. }
  209. func (s *systemService) UpdateAssist() {
  210. command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/assist.sh")
  211. }
  212. func (s *systemService) GetTimeZone() string {
  213. return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetTimeZone")
  214. }
  215. func (s *systemService) ExecUSBAutoMountShell(state string) {
  216. if state == "False" {
  217. command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Stop_Auto")
  218. } else {
  219. command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Start_Auto")
  220. }
  221. }
  222. func (s *systemService) GetSystemConfigDebug() []string {
  223. return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetSysInfo")
  224. }
  225. func (s *systemService) UpAppOrderFile(str, id string) {
  226. file.WriteToPath([]byte(str), config.AppInfo.DBPath+"/"+id, "app_order.json")
  227. }
  228. func (s *systemService) GetAppOrderFile(id string) []byte {
  229. return file.ReadFullFile(config.AppInfo.UserDataPath + "/" + id + "/app_order.json")
  230. }
  231. func (s *systemService) UpSystemPort(port string) {
  232. if len(port) > 0 && port != config.ServerInfo.HttpPort {
  233. config.Cfg.Section("server").Key("HttpPort").SetValue(port)
  234. config.ServerInfo.HttpPort = port
  235. }
  236. config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
  237. }
  238. func (s *systemService) GetCasaOSLogs(lineNumber int) string {
  239. file, err := os.Open(filepath.Join(config.AppInfo.LogPath, fmt.Sprintf("%s.%s",
  240. config.AppInfo.LogSaveName,
  241. config.AppInfo.LogFileExt,
  242. )))
  243. if err != nil {
  244. return err.Error()
  245. }
  246. defer file.Close()
  247. content, err := ioutil.ReadAll(file)
  248. if err != nil {
  249. return err.Error()
  250. }
  251. return string(content)
  252. }
  253. func GetDeviceAllIP() []string {
  254. var address []string
  255. addrs, err := net2.InterfaceAddrs()
  256. if err != nil {
  257. return address
  258. }
  259. for _, a := range addrs {
  260. if ipNet, ok := a.(*net2.IPNet); ok && !ipNet.IP.IsLoopback() {
  261. if ipNet.IP.To16() != nil {
  262. address = append(address, ipNet.IP.String())
  263. }
  264. }
  265. }
  266. return address
  267. }
  268. func (s *systemService) IsServiceRunning(name string) bool {
  269. status := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;CheckServiceStatus smbd")
  270. return strings.TrimSpace(status) == "running"
  271. }
  272. func (s *systemService) GetCPUTemperature() int {
  273. outPut := ""
  274. if file.Exists("/sys/class/thermal/thermal_zone0/temp") {
  275. outPut = string(file.ReadFullFile("/sys/class/thermal/thermal_zone0/temp"))
  276. } else if file.Exists("/sys/class/hwmon/hwmon0/temp1_input") {
  277. outPut = string(file.ReadFullFile("/sys/class/hwmon/hwmon0/temp1_input"))
  278. } else {
  279. outPut = "0"
  280. }
  281. celsius, _ := strconv.Atoi(strings.TrimSpace(outPut))
  282. if celsius > 1000 {
  283. celsius = celsius / 1000
  284. }
  285. return celsius
  286. }
  287. func (s *systemService) GetCPUPower() map[string]string {
  288. data := make(map[string]string, 2)
  289. data["timestamp"] = strconv.FormatInt(time.Now().Unix(), 10)
  290. if file.Exists("/sys/class/powercap/intel-rapl/intel-rapl:0/energy_uj") {
  291. data["value"] = strings.TrimSpace(string(file.ReadFullFile("/sys/class/powercap/intel-rapl/intel-rapl:0/energy_uj")))
  292. } else {
  293. data["value"] = "0"
  294. }
  295. return data
  296. }
  297. func NewSystemService() SystemService {
  298. return &systemService{}
  299. }