app.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "runtime"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/IceWhaleTech/CasaOS/model"
  13. "github.com/IceWhaleTech/CasaOS/pkg/config"
  14. "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
  15. "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
  16. model2 "github.com/IceWhaleTech/CasaOS/service/model"
  17. "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/api/types/filters"
  19. client2 "github.com/docker/docker/client"
  20. "github.com/pkg/errors"
  21. uuid "github.com/satori/go.uuid"
  22. "go.uber.org/zap"
  23. "gorm.io/gorm"
  24. )
  25. type AppService interface {
  26. GetMyList(index, size int, position bool) (*[]model2.MyAppList, *[]model2.MyAppList)
  27. SaveContainer(m model2.AppListDBModel)
  28. GetUninstallInfo(id string) model2.AppListDBModel
  29. DeleteApp(id string)
  30. GetContainerInfo(id string) (types.Container, error)
  31. GetAppDBInfo(id string) model2.AppListDBModel
  32. UpdateApp(m model2.AppListDBModel)
  33. GetSimpleContainerInfo(id string) (types.Container, error)
  34. DelAppConfigDir(path string)
  35. GetSystemAppList() []types.Container
  36. GetHardwareUsageStream()
  37. GetHardwareUsage() []model.DockerStatsModel
  38. GetAppStats(id string) string
  39. GetAllDBApps() []model2.AppListDBModel
  40. ImportApplications(casaApp bool)
  41. CheckNewImage()
  42. }
  43. type appStruct struct {
  44. db *gorm.DB
  45. }
  46. func (a *appStruct) CheckNewImage() {
  47. list := MyService.Docker().DockerContainerList()
  48. for _, v := range list {
  49. inspect, err := MyService.Docker().DockerImageInfo(strings.Split(v.Image, ":")[0])
  50. if err != nil {
  51. NewVersionApp[v.ID] = inspect.ID
  52. continue
  53. }
  54. if inspect.ID == v.ImageID {
  55. delete(NewVersionApp, v.ID)
  56. continue
  57. }
  58. NewVersionApp[v.ID] = inspect.ID
  59. }
  60. }
  61. func (a *appStruct) ImportApplications(casaApp bool) {
  62. if casaApp {
  63. list := MyService.App().GetAllDBApps()
  64. for _, app := range list {
  65. info, err := MyService.Docker().DockerContainerInfo(app.CustomId)
  66. if err != nil {
  67. MyService.App().DeleteApp(app.CustomId)
  68. continue
  69. }
  70. //info.NetworkSettings
  71. info.Config.Labels["casaos"] = "casaos"
  72. info.Config.Labels["web"] = app.PortMap
  73. info.Config.Labels["icon"] = app.Icon
  74. info.Config.Labels["desc"] = app.Description
  75. info.Config.Labels["index"] = app.Index
  76. info.Config.Labels["custom_id"] = app.CustomId
  77. info.Name = app.Title
  78. container_id, err := MyService.Docker().DockerContainerCopyCreate(info)
  79. if err != nil {
  80. fmt.Println(err)
  81. continue
  82. }
  83. MyService.App().DeleteApp(app.CustomId)
  84. MyService.Docker().DockerContainerStop(app.CustomId)
  85. MyService.Docker().DockerContainerRemove(app.CustomId, false)
  86. MyService.Docker().DockerContainerStart(container_id)
  87. }
  88. } else {
  89. list := MyService.Docker().DockerContainerList()
  90. for _, app := range list {
  91. info, err := MyService.Docker().DockerContainerInfo(app.ID)
  92. if err != nil || info.Config.Labels["casaos"] == "casaos" {
  93. continue
  94. }
  95. info.Config.Labels["casaos"] = "casaos"
  96. info.Config.Labels["web"] = ""
  97. info.Config.Labels["icon"] = ""
  98. info.Config.Labels["desc"] = ""
  99. info.Config.Labels["index"] = ""
  100. info.Config.Labels["custom_id"] = uuid.NewV4().String()
  101. _, err = MyService.Docker().DockerContainerCopyCreate(info)
  102. if err != nil {
  103. continue
  104. }
  105. }
  106. }
  107. // allcontainer := MyService.Docker().DockerContainerList()
  108. // for _, app := range allcontainer {
  109. // info, err := MyService.Docker().DockerContainerInfo(app.ID)
  110. // if err != nil {
  111. // continue
  112. // }
  113. // MyService.Docker().DockerContainerStop(app.ID)
  114. // MyService.Docker().DockerContainerRemove(app.ID, false)
  115. // //info.NetworkSettings
  116. // info.Config.Labels["custom_id"] = uuid.NewV4().String()
  117. // container_id, err := MyService.Docker().DockerContainerCopyCreate(info)
  118. // if err != nil {
  119. // fmt.Println(err)
  120. // continue
  121. // }
  122. // MyService.Docker().DockerContainerStart(container_id)
  123. //}
  124. }
  125. //获取我的应用列表
  126. func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppList, *[]model2.MyAppList) {
  127. cli, err := client2.NewClientWithOpts(client2.FromEnv, client2.WithTimeout(time.Second*5))
  128. if err != nil {
  129. loger.Error("Failed to init client", zap.Any("err", err))
  130. }
  131. defer cli.Close()
  132. // fts := filters.NewArgs()
  133. // fts.Add("label", "casaos=casaos")
  134. //fts.Add("label", "casaos")
  135. //fts.Add("casaos", "casaos")
  136. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
  137. if err != nil {
  138. loger.Error("Failed to get container_list", zap.Any("err", err))
  139. }
  140. //获取本地数据库应用
  141. unTranslation := []model2.MyAppList{}
  142. list := []model2.MyAppList{}
  143. for _, m := range containers {
  144. if m.Labels["casaos"] == "casaos" {
  145. _, newVersion := NewVersionApp[m.ID]
  146. name := strings.ReplaceAll(m.Names[0], "/", "")
  147. icon := m.Labels["icon"]
  148. if len(m.Labels["name"]) > 0 {
  149. name = m.Labels["name"]
  150. }
  151. if m.Labels["origin"] == "system" {
  152. name = strings.Split(m.Image, ":")[0]
  153. if len(strings.Split(name, "/")) > 1 {
  154. icon = "https://icon.casaos.io/main/all/" + strings.Split(name, "/")[1] + ".png"
  155. }
  156. }
  157. list = append(list, model2.MyAppList{
  158. Name: name,
  159. Icon: icon,
  160. State: m.State,
  161. CustomId: m.Labels["custom_id"],
  162. Id: m.ID,
  163. Port: m.Labels["web"],
  164. Index: m.Labels["index"],
  165. //Order: m.Labels["order"],
  166. Image: m.Image,
  167. Latest: newVersion,
  168. //Type: m.Labels["origin"],
  169. //Slogan: m.Slogan,
  170. //Rely: m.Rely,
  171. Host: m.Labels["host"],
  172. Protocol: m.Labels["protocol"],
  173. })
  174. } else {
  175. unTranslation = append(unTranslation, model2.MyAppList{
  176. Name: strings.ReplaceAll(m.Names[0], "/", ""),
  177. Icon: "",
  178. State: m.State,
  179. CustomId: m.ID,
  180. Id: m.ID,
  181. Port: "",
  182. Latest: false,
  183. Host: "",
  184. Protocol: "",
  185. Image: m.Image,
  186. })
  187. }
  188. }
  189. //lMap := make(map[string]interface{})
  190. // for _, dbModel := range lm {
  191. // if position {
  192. // if dbModel.Position {
  193. // lMap[dbModel.ContainerId] = dbModel
  194. // }
  195. // } else {
  196. // lMap[dbModel.ContainerId] = dbModel
  197. // }
  198. // }
  199. // for _, container := range containers {
  200. // if lMap[container.ID] != nil && container.Labels["origin"] != "system" {
  201. // m := lMap[container.ID].(model2.AppListDBModel)
  202. // if len(m.Label) == 0 {
  203. // m.Label = m.Title
  204. // }
  205. // // info, err := cli.ContainerInspect(context.Background(), container.ID)
  206. // // var tm string
  207. // // if err != nil {
  208. // // tm = time.Now().String()
  209. // // } else {
  210. // // tm = info.State.StartedAt
  211. // //}
  212. // list = append(list, model2.MyAppList{
  213. // Name: m.Label,
  214. // Icon: m.Icon,
  215. // State: container.State,
  216. // CustomId: strings.ReplaceAll(container.Names[0], "/", ""),
  217. // Port: m.PortMap,
  218. // Index: m.Index,
  219. // //UpTime: tm,
  220. // Image: m.Image,
  221. // Slogan: m.Slogan,
  222. // //Rely: m.Rely,
  223. // })
  224. // }
  225. // }
  226. return &list, &unTranslation
  227. }
  228. //system application list
  229. func (a *appStruct) GetSystemAppList() []types.Container {
  230. //获取docker应用
  231. cli, err := client2.NewClientWithOpts(client2.FromEnv)
  232. if err != nil {
  233. loger.Error("Failed to init client", zap.Any("err", err))
  234. }
  235. defer cli.Close()
  236. fts := filters.NewArgs()
  237. fts.Add("label", "origin=system")
  238. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts})
  239. if err != nil {
  240. loger.Error("Failed to get container_list", zap.Any("err", err))
  241. }
  242. //获取本地数据库应用
  243. // var lm []model2.AppListDBModel
  244. // a.db.Table(model2.CONTAINERTABLENAME).Select("title,icon,port_map,`index`,container_id,position,label,slogan,image,volumes").Find(&lm)
  245. //list := []model2.MyAppList{}
  246. //lMap := make(map[string]interface{})
  247. // for _, dbModel := range lm {
  248. // lMap[dbModel.ContainerId] = dbModel
  249. // }
  250. return containers
  251. }
  252. func (a *appStruct) GetAllDBApps() []model2.AppListDBModel {
  253. var lm []model2.AppListDBModel
  254. a.db.Table(model2.CONTAINERTABLENAME).Select("custom_id,title,icon,container_id,label,slogan,image,port_map").Find(&lm)
  255. return lm
  256. }
  257. //获取我的应用列表
  258. func (a *appStruct) GetContainerInfo(id string) (types.Container, error) {
  259. //获取docker应用
  260. cli, err := client2.NewClientWithOpts(client2.FromEnv)
  261. if err != nil {
  262. loger.Error("Failed to init client", zap.Any("err", err))
  263. }
  264. filters := filters.NewArgs()
  265. filters.Add("id", id)
  266. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: filters})
  267. if err != nil {
  268. loger.Error("Failed to get container_list", zap.Any("err", err))
  269. }
  270. if len(containers) > 0 {
  271. return containers[0], nil
  272. }
  273. return types.Container{}, nil
  274. }
  275. func (a *appStruct) GetSimpleContainerInfo(id string) (types.Container, error) {
  276. //获取docker应用
  277. cli, err := client2.NewClientWithOpts(client2.FromEnv)
  278. if err != nil {
  279. return types.Container{}, err
  280. }
  281. defer cli.Close()
  282. filters := filters.NewArgs()
  283. filters.Add("id", id)
  284. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: filters})
  285. if err != nil {
  286. return types.Container{}, err
  287. }
  288. if len(containers) > 0 {
  289. return containers[0], nil
  290. }
  291. return types.Container{}, errors.New("container not existent")
  292. }
  293. //获取我的应用列表
  294. func (a *appStruct) GetAppDBInfo(id string) model2.AppListDBModel {
  295. var m model2.AppListDBModel
  296. a.db.Table(model2.CONTAINERTABLENAME).Where("custom_id = ?", id).First(&m)
  297. return m
  298. }
  299. //根据容器id获取镜像名称
  300. func (a *appStruct) GetUninstallInfo(id string) model2.AppListDBModel {
  301. var m model2.AppListDBModel
  302. a.db.Table(model2.CONTAINERTABLENAME).Select("image,version,enable_upnp,ports,envs,volumes,origin").Where("custom_id = ?", id).First(&m)
  303. return m
  304. }
  305. //创建容器成功后保存容器
  306. func (a *appStruct) SaveContainer(m model2.AppListDBModel) {
  307. a.db.Table(model2.CONTAINERTABLENAME).Create(&m)
  308. }
  309. func (a *appStruct) UpdateApp(m model2.AppListDBModel) {
  310. a.db.Table(model2.CONTAINERTABLENAME).Save(&m)
  311. }
  312. func (a *appStruct) DelAppConfigDir(path string) {
  313. command.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;DelAppConfigDir " + path)
  314. }
  315. func (a *appStruct) DeleteApp(id string) {
  316. a.db.Table(model2.CONTAINERTABLENAME).Where("custom_id = ?", id).Delete(&model2.AppListDBModel{})
  317. }
  318. var dataStats sync.Map
  319. var isFinish bool = false
  320. func (a *appStruct) GetAppStats(id string) string {
  321. cli, err := client2.NewClientWithOpts(client2.FromEnv)
  322. if err != nil {
  323. return ""
  324. }
  325. defer cli.Close()
  326. con, err := cli.ContainerStats(context.Background(), id, false)
  327. if err != nil {
  328. return err.Error()
  329. }
  330. defer con.Body.Close()
  331. c, _ := ioutil.ReadAll(con.Body)
  332. return string(c)
  333. }
  334. func (a *appStruct) GetHardwareUsage() []model.DockerStatsModel {
  335. stream := true
  336. for !isFinish {
  337. if stream {
  338. stream = false
  339. go func() {
  340. a.GetHardwareUsageStream()
  341. }()
  342. }
  343. runtime.Gosched()
  344. }
  345. list := []model.DockerStatsModel{}
  346. dataStats.Range(func(key, value interface{}) bool {
  347. list = append(list, value.(model.DockerStatsModel))
  348. return true
  349. })
  350. return list
  351. }
  352. func (a *appStruct) GetHardwareUsageStream() {
  353. cli, err := client2.NewClientWithOpts(client2.FromEnv)
  354. if err != nil {
  355. return
  356. }
  357. defer cli.Close()
  358. ctx := context.Background()
  359. ctx, cancel := context.WithCancel(ctx)
  360. fts := filters.NewArgs()
  361. fts.Add("label", "casaos=casaos")
  362. //fts.Add("status", "running")
  363. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts})
  364. if err != nil {
  365. loger.Error("Failed to get container_list", zap.Any("err", err))
  366. }
  367. for i := 0; i < 100; i++ {
  368. if i%10 == 0 {
  369. containers, err = cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts})
  370. if err != nil {
  371. loger.Error("Failed to get container_list", zap.Any("err", err))
  372. continue
  373. }
  374. }
  375. if config.CasaOSGlobalVariables.AppChange {
  376. config.CasaOSGlobalVariables.AppChange = false
  377. dataStats.Range(func(key, value interface{}) bool {
  378. dataStats.Delete(key)
  379. return true
  380. })
  381. }
  382. var temp sync.Map
  383. var wg sync.WaitGroup
  384. for _, v := range containers {
  385. if v.State != "running" {
  386. continue
  387. }
  388. wg.Add(1)
  389. go func(v types.Container, i int) {
  390. defer wg.Done()
  391. stats, err := cli.ContainerStatsOneShot(ctx, v.ID)
  392. if err != nil {
  393. return
  394. }
  395. decode := json.NewDecoder(stats.Body)
  396. var data interface{}
  397. if err := decode.Decode(&data); err == io.EOF {
  398. return
  399. }
  400. m, _ := dataStats.Load(v.ID)
  401. dockerStats := model.DockerStatsModel{}
  402. if m != nil {
  403. dockerStats.Previous = m.(model.DockerStatsModel).Data
  404. }
  405. dockerStats.Data = data
  406. dockerStats.Icon = v.Labels["icon"]
  407. dockerStats.Title = strings.ReplaceAll(v.Names[0], "/", "")
  408. // @tiger - 不建议直接把依赖的数据结构封装返回。
  409. // 如果依赖的数据结构有变化,应该在这里适配或者保存,这样更加对客户端负责
  410. temp.Store(v.ID, dockerStats)
  411. if i == 99 {
  412. stats.Body.Close()
  413. }
  414. }(v, i)
  415. }
  416. wg.Wait()
  417. dataStats = temp
  418. isFinish = true
  419. time.Sleep(time.Second * 1)
  420. }
  421. isFinish = false
  422. cancel()
  423. }
  424. func NewAppService(db *gorm.DB) AppService {
  425. return &appStruct{db: db}
  426. }