system.go 8.9 KB

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