CasaOS - A simple, easy-to-use, elegant open-source Personal Cloud system.
remove disk and test common package
LinkLeong8113f51cf7aa
diff --git a/common/notify.go b/common/notify.goindex c36cea0..82d3394 100644--- a/common/notify.go+++ b/common/notify.go@@ -13,12 +13,12 @@ import (const (CasaOSURLFilename = "casaos.url"- APICasaOSNotify = "/v1/notiry"+ APICasaOSNotify = "/v1/notify")type NotifyService interface {SendNotify(path string, message map[string]interface{}) error- SendSystemNotify(message map[string]interface{}) error+ SendSystemStatusNotify(message map[string]interface{}) error}type notifyService struct {address string@@ -26,7 +26,7 @@ type notifyService struct {func (n *notifyService) SendNotify(path string, message map[string]interface{}) error {- url := strings.TrimSuffix(n.address, "/") + "/" + APICasaOSNotify + "/" + path+ url := strings.TrimSuffix(n.address, "/") + APICasaOSNotify + "/" + pathbody, err := json.Marshal(message)if err != nil {return err@@ -42,9 +42,13 @@ func (n *notifyService) SendNotify(path string, message map[string]interface{})return nil}-func (n *notifyService) SendSystemNotify(message map[string]interface{}) error {- url := strings.TrimSuffix(n.address, "/") + "/" + APICasaOSNotify+// disk: "sys_disk":{"size":56866869248,"avail":5855485952,"health":true,"used":48099700736}+// usb: "sys_usb":[{"name": "sdc","size": 7747397632,"model": "DataTraveler_2.0","avail": 7714418688,"children": null}]+func (n *notifyService) SendSystemStatusNotify(message map[string]interface{}) error {++ url := strings.TrimSuffix(n.address, "/") + APICasaOSNotify + "/system_status"+ fmt.Println(url)body, err := json.Marshal(message)if err != nil {return errdiff --git a/common/notify_test.go b/common/notify_test.gonew file mode 100644index 0000000..1e9c543--- /dev/null+++ b/common/notify_test.go@@ -0,0 +1,29 @@+package common++import "testing"++func TestSendNotify(t *testing.T) {+ notify, err := NewNotifyService("/var/run/casaos")+ if err != nil {+ t.Fatal(err)+ }+ err = notify.SendNotify("test", map[string]interface{}{+ "test": "test",+ })+ if err != nil {+ t.Fatal(err)+ }+}++func TestSendSystemStatusNotify(t *testing.T) {+ notify, err := NewNotifyService("/var/run/casaos")+ if err != nil {+ t.Fatal(err)+ }+ err = notify.SendSystemStatusNotify(map[string]interface{}{+ "sys_usb": `[{"name": "sdc","size": 7747397632,"model": "DataTraveler_2.0","avail": 7714418688,"children": null}]`,+ })+ if err != nil {+ t.Fatal(err)+ }+}diff --git a/go.mod b/go.modindex 6209c3e..cfcc59b 100644--- a/go.mod+++ b/go.mod@@ -34,7 +34,6 @@ require (github.com/morikuni/aec v1.0.0 // indirectgithub.com/opencontainers/image-spec v1.0.2 // indirectgithub.com/patrickmn/go-cache v2.1.0+incompatible- github.com/pilebones/go-udev v0.9.0github.com/pkg/errors v0.9.1github.com/robfig/cron v1.2.0github.com/satori/go.uuid v1.2.0diff --git a/go.sum b/go.sumindex 9e68d0e..49a1770 100644--- a/go.sum+++ b/go.sum@@ -814,8 +814,6 @@ github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOgithub.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=github.com/pierrec/lz4/v4 v4.1.2 h1:qvY3YFXRQE/XB8MlLzJH7mSzBs74eA2gg52YTk6jUPM=github.com/pierrec/lz4/v4 v4.1.2/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=-github.com/pilebones/go-udev v0.9.0 h1:N1uEO/SxUwtIctc0WLU0t69JeBxIYEYnj8lT/Nabl9Q=-github.com/pilebones/go-udev v0.9.0/go.mod h1:T2eI2tUSK0hA2WS5QLjXJUfQkluZQu+18Cqvem3CaXI=github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=diff --git a/main.go b/main.goindex 6ff7af8..f02afca 100644--- a/main.go+++ b/main.go@@ -80,7 +80,6 @@ func main() {return}go route.SocketInit(service.NotifyMsg)- go route.MonitoryUSB()//model.Setup()//gredis.Setup()@@ -110,7 +109,7 @@ func main() {if err != nil {panic(err)}- routers := []string{"sys", "apps", "container", "app-categories", "port", "file", "folder", "batch", "image", "disks", "storage", "samba", "notify"}+ routers := []string{"sys", "apps", "container", "app-categories", "port", "file", "folder", "batch", "image", "samba", "notify"}for _, v := range routers {err = service.MyService.Gateway().CreateRoute(&common.Route{Path: "/v1/" + v,diff --git a/model/disk.go b/model/disk.godeleted file mode 100644index 75d3bc5..0000000--- a/model/disk.go+++ /dev/null@@ -1,98 +0,0 @@-/*- * @Author: LinkLeong [email protected]- * @Date: 2022-07-13 10:43:45- * @LastEditors: LinkLeong- * @LastEditTime: 2022-08-03 14:45:35- * @FilePath: /CasaOS/model/disk.go- * @Description:- * @Website: https://www.casaos.io- * Copyright (c) 2022 by icewhale, All Rights Reserved.- */-package model--type LSBLKModel struct {- Name string `json:"name"`- FsType string `json:"fstype"`- Size uint64 `json:"size"`- FSSize string `json:"fssize"`- Path string `json:"path"`- Model string `json:"model"` //设备标识符- RM bool `json:"rm"` //是否为可移动设备- RO bool `json:"ro"` //是否为只读设备- State string `json:"state"`- PhySec int `json:"phy-sec"` //物理扇区大小- Type string `json:"type"`- Vendor string `json:"vendor"` //供应商- Rev string `json:"rev"` //修订版本- FSAvail string `json:"fsavail"` //可用空间- FSUse string `json:"fsuse%"` //已用百分比- MountPoint string `json:"mountpoint"`- Format string `json:"format"`- Health string `json:"health"`- HotPlug bool `json:"hotplug"`- UUID string `json:"uuid"`- FSUsed string `json:"fsused"`- Temperature int `json:"temperature"`- Tran string `json:"tran"`- MinIO uint64 `json:"min-io"`- UsedPercent float64 `json:"used_percent"`- Serial string `json:"serial"`- Children []LSBLKModel `json:"children"`- SubSystems string `json:"subsystems"`- Label string `json:"label"`- //详情特有- StartSector uint64 `json:"start_sector,omitempty"`- Rota bool `json:"rota"` //true(hhd) false(ssd)- DiskType string `json:"disk_type"`- EndSector uint64 `json:"end_sector,omitempty"`-}--type Drive struct {- Name string `json:"name"`- Size uint64 `json:"size"`- Model string `json:"model"`- Health string `json:"health"`- Temperature int `json:"temperature"`- DiskType string `json:"disk_type"`- NeedFormat bool `json:"need_format"`- Serial string `json:"serial"`- Path string `json:"path"`- ChildrenNumber int `json:"children_number"`-}--type DriveUSB struct {- Name string `json:"name"`- Size uint64 `json:"size"`- Model string `json:"model"`- Avail uint64 `json:"avail"`- Children []USBChildren `json:"children"`-}-type USBChildren struct {- Name string `json:"name"`- Size uint64 `json:"size"`- Avail uint64 `json:"avail"`- MountPoint string `json:"mount_point"`-}--type Storage struct {- MountPoint string `json:"mount_point"`- Size string `json:"size"`- Avail string `json:"avail"` //可用空间- Type string `json:"type"`- Path string `json:"path"`- DriveName string `json:"drive_name"`- Label string `json:"label"`-}-type Storages struct {- DiskName string `json:"disk_name"`- Size uint64 `json:"size"`- Path string `json:"path"`- Children []Storage `json:"children"`-}--type Summary struct {- Size uint64 `json:"size"`- Avail uint64 `json:"avail"` //可用空间- Health bool `json:"health"`- Used uint64 `json:"used"`-}diff --git a/model/docker.go b/model/docker.goindex a083319..20b68cc 100644--- a/model/docker.go+++ b/model/docker.go@@ -16,3 +16,7 @@ type DockerStatsModel struct {Data interface{} `json:"data"`Previous interface{} `json:"previous"`}++type DeckerDaemonModel struct {+ Graph string `json:"graph"`+}diff --git a/model/receive/app.go b/model/receive/app.godeleted file mode 100644index 3ccae50..0000000--- a/model/receive/app.go+++ /dev/null@@ -1 +0,0 @@-package receivediff --git a/pkg/sqlite/db.go b/pkg/sqlite/db.goindex 819da65..e5d7595 100644--- a/pkg/sqlite/db.go+++ b/pkg/sqlite/db.go@@ -43,7 +43,7 @@ func GetDb(dbPath string) *gorm.DB {}gdb = db- err = db.AutoMigrate(&model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.SharesDBModel{}, model2.ConnectionsDBModel{})+ err = db.AutoMigrate(&model2.AppNotify{}, &model2.AppListDBModel{}, model2.SharesDBModel{}, model2.ConnectionsDBModel{})db.Exec("DROP TABLE IF EXISTS o_application")db.Exec("DROP TABLE IF EXISTS o_friend")db.Exec("DROP TABLE IF EXISTS o_person_download")diff --git a/route/init.go b/route/init.goindex e2d09c7..a35de29 100644--- a/route/init.go+++ b/route/init.go@@ -3,65 +3,19 @@ package routeimport ("fmt""os"- "strconv""strings""time"- "github.com/IceWhaleTech/CasaOS/pkg/config""github.com/IceWhaleTech/CasaOS/pkg/samba"- "github.com/IceWhaleTech/CasaOS/pkg/utils/command""github.com/IceWhaleTech/CasaOS/pkg/utils/file""github.com/IceWhaleTech/CasaOS/pkg/utils/loger""github.com/IceWhaleTech/CasaOS/service"- model2 "github.com/IceWhaleTech/CasaOS/service/model""go.uber.org/zap")func InitFunction() {- CheckSerialDiskMount()go InitNetworkMount()}--func CheckSerialDiskMount() {- // check mount point- dbList := service.MyService.Disk().GetSerialAll()-- list := service.MyService.Disk().LSBLK(true)- mountPoint := make(map[string]string, len(dbList))- //remount- for _, v := range dbList {- mountPoint[v.UUID] = v.MountPoint- }- for _, v := range list {- command.ExecEnabledSMART(v.Path)- if v.Children != nil {- for _, h := range v.Children {- //if len(h.MountPoint) == 0 && len(v.Children) == 1 && h.FsType == "ext4" {- if m, ok := mountPoint[h.UUID]; ok {- //mount point check- volume := m- if !file.CheckNotExist(m) {- for i := 0; file.CheckNotExist(volume); i++ {- volume = m + strconv.Itoa(i+1)- }- }- service.MyService.Disk().MountDisk(h.Path, volume)- if volume != m {- ms := model2.SerialDisk{}- ms.UUID = v.UUID- ms.MountPoint = volume- service.MyService.Disk().UpdateMountPoint(ms)- }-- }- //}- }- }- }- service.MyService.Disk().RemoveLSBLKCache()- command.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;AutoRemoveUnuseDir")-}-func InitNetworkMount() {time.Sleep(time.Second * 10)connections := service.MyService.Connections().GetConnectionsList()diff --git a/route/periodical.go b/route/periodical.goindex 6fbdd74..7d12ca2 100644--- a/route/periodical.go+++ b/route/periodical.go@@ -14,20 +14,12 @@package routeimport (- "os"- "os/signal"- "reflect"- "strconv""strings"- "syscall""time""unsafe""github.com/IceWhaleTech/CasaOS/model"- "github.com/IceWhaleTech/CasaOS/pkg/utils/loger""github.com/IceWhaleTech/CasaOS/service"- "github.com/pilebones/go-udev/netlink"- "go.uber.org/zap")func SendNetINfoBySocket() {@@ -61,104 +53,6 @@ func SendMemBySocket() {service.MyService.Notify().SendMemInfoBySocket(service.MyService.System().GetMemInfo())}-func SendDiskBySocket() {- list := service.MyService.Disk().LSBLK(true)-- summary := model.Summary{}- healthy := true- findSystem := 0-- for i := 0; i < len(list); i++ {- if len(list[i].Children) > 0 && findSystem == 0 {-- for j := 0; j < len(list[i].Children); j++ {-- if len(list[i].Children[j].Children) > 0 {- for _, v := range list[i].Children[j].Children {- if v.MountPoint == "/" {- s, _ := strconv.ParseUint(v.FSSize, 10, 64)- a, _ := strconv.ParseUint(v.FSAvail, 10, 64)- u, _ := strconv.ParseUint(v.FSUsed, 10, 64)- summary.Size += s- summary.Avail += a- summary.Used += u- findSystem = 1- break- }- }- } else {- if list[i].Children[j].MountPoint == "/" {- s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)- a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)- u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 10, 64)- summary.Size += s- summary.Avail += a- summary.Used += u- findSystem = 1- break- }- }- }-- }- if findSystem == 1 {- findSystem += 1- continue- }- if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {- temp := service.MyService.Disk().SmartCTL(list[i].Path)- if reflect.DeepEqual(temp, model.SmartctlA{}) {- healthy = true- } else {- healthy = temp.SmartStatus.Passed- }-- //list[i].Temperature = temp.Temperature.Current-- if len(list[i].Children) > 0 {- for _, v := range list[i].Children {- s, _ := strconv.ParseUint(v.FSSize, 10, 64)- a, _ := strconv.ParseUint(v.FSAvail, 10, 64)- u, _ := strconv.ParseUint(v.FSUsed, 10, 64)- summary.Size += s- summary.Avail += a- summary.Used += u- }- }-- }- }-- summary.Health = healthy- service.MyService.Notify().SendDiskInfoBySocket(summary)-}--func SendUSBBySocket() {- usbList := service.MyService.Disk().LSBLK(false)- usb := []model.DriveUSB{}- for _, v := range usbList {- if v.Tran == "usb" {- isMount := false- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Name- temp.Size = v.Size- for _, child := range v.Children {- if len(child.MountPoint) > 0 {- isMount = true- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- temp.Avail += avail-- }- }- if isMount {- usb = append(usb, temp)- }- }- }- service.MyService.Notify().SendUSBInfoBySocket(usb)-}-func SendAllHardwareStatusBySocket() {netList := service.MyService.System().GetNetInfo()@@ -183,131 +77,44 @@ func SendAllHardwareStatusBySocket() {cpuData["temperature"] = service.MyService.System().GetCPUTemperature()cpuData["power"] = service.MyService.System().GetCPUPower()- list := service.MyService.Disk().LSBLK(true)-- summary := model.Summary{}- healthy := true- findSystem := 0-- for i := 0; i < len(list); i++ {- if len(list[i].Children) > 0 && findSystem == 0 {-- for j := 0; j < len(list[i].Children); j++ {-- if len(list[i].Children[j].Children) > 0 {- for _, v := range list[i].Children[j].Children {- if v.MountPoint == "/" {- s, _ := strconv.ParseUint(v.FSSize, 10, 64)- a, _ := strconv.ParseUint(v.FSAvail, 10, 64)- u, _ := strconv.ParseUint(v.FSUsed, 10, 64)- summary.Size += s- summary.Avail += a- summary.Used += u- findSystem = 1- break- }- }- } else {- if list[i].Children[j].MountPoint == "/" {- s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)- a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)- u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 10, 64)- summary.Size += s- summary.Avail += a- summary.Used += u- findSystem = 1- break- }- }- }-- }- if findSystem == 1 {- findSystem += 1- continue- }- if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {- temp := service.MyService.Disk().SmartCTL(list[i].Path)- if reflect.DeepEqual(temp, model.SmartctlA{}) {- healthy = true- } else {- healthy = temp.SmartStatus.Passed- }- if len(list[i].Children) > 0 {- for _, v := range list[i].Children {- s, _ := strconv.ParseUint(v.FSSize, 10, 64)- a, _ := strconv.ParseUint(v.FSAvail, 10, 64)- u, _ := strconv.ParseUint(v.FSUsed, 10, 64)- summary.Size += s- summary.Avail += a- summary.Used += u- }- }-- }- }-- summary.Health = healthy-- usbList := service.MyService.Disk().LSBLK(false)- usb := []model.DriveUSB{}- for _, v := range usbList {- if v.Tran == "usb" {- isMount := false- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Name- temp.Size = v.Size- for _, child := range v.Children {- if len(child.MountPoint) > 0 {- isMount = true- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- temp.Avail += avail- }- }- if isMount {- usb = append(usb, temp)- }-- }- }memInfo := service.MyService.System().GetMemInfo()- service.MyService.Notify().SendAllHardwareStatusBySocket(summary, usb, memInfo, cpuData, newNet)+ service.MyService.Notify().SendAllHardwareStatusBySocket(memInfo, cpuData, newNet)}-func MonitoryUSB() {- var matcher netlink.Matcher-- conn := new(netlink.UEventConn)- if err := conn.Connect(netlink.UdevEvent); err != nil {- loger.Error("udev err", zap.Any("Unable to connect to Netlink Kobject UEvent socket", err))- }- defer conn.Close()-- queue := make(chan netlink.UEvent)- errors := make(chan error)- quit := conn.Monitor(queue, errors, matcher)- signals := make(chan os.Signal, 1)- signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)- go func() {- <-signals- close(quit)- os.Exit(0)- }()-- for {- select {- case uevent := <-queue:- if uevent.Env["DEVTYPE"] == "disk" {- time.Sleep(time.Microsecond * 500)- SendUSBBySocket()- continue- }- case err := <-errors:- loger.Error("udev err", zap.Any("err", err))- }- }--}+// func MonitoryUSB() {+// var matcher netlink.Matcher++// conn := new(netlink.UEventConn)+// if err := conn.Connect(netlink.UdevEvent); err != nil {+// loger.Error("udev err", zap.Any("Unable to connect to Netlink Kobject UEvent socket", err))+// }+// defer conn.Close()++// queue := make(chan netlink.UEvent)+// errors := make(chan error)+// quit := conn.Monitor(queue, errors, matcher)++// signals := make(chan os.Signal, 1)+// signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)+// go func() {+// <-signals+// close(quit)+// os.Exit(0)+// }()++// for {+// select {+// case uevent := <-queue:+// if uevent.Env["DEVTYPE"] == "disk" {+// time.Sleep(time.Microsecond * 500)+// SendUSBBySocket()+// continue+// }+// case err := <-errors:+// loger.Error("udev err", zap.Any("err", err))+// }+// }++// }diff --git a/route/route.go b/route/route.goindex 0bfcbfc..110fd69 100644--- a/route/route.go+++ b/route/route.go@@ -1,7 +1,7 @@package routeimport (- jwt2 "github.com/IceWhaleTech/CasaOS-Common/utils/jwt"+ "github.com/IceWhaleTech/CasaOS-Common/utils/jwt""github.com/IceWhaleTech/CasaOS/middleware""github.com/IceWhaleTech/CasaOS/pkg/config"v1 "github.com/IceWhaleTech/CasaOS/route/v1"@@ -45,7 +45,7 @@ func InitRouter() *gin.Engine {})v1Group := r.Group("/v1")- v1Group.Use(jwt2.JWT())+ v1Group.Use(jwt.ExceptLocalhost()){// v1UsersGroup := v1Group.Group("/users")// v1UsersGroup.Use()@@ -79,6 +79,7 @@ func InitRouter() *gin.Engine {v1ContainerGroup := v1Group.Group("/container")v1ContainerGroup.Use(){+v1ContainerGroup.GET("", v1.MyAppList) ///my/listv1ContainerGroup.GET("/usage", v1.AppUsageList)v1ContainerGroup.GET("/:id", v1.ContainerUpdateInfo) ///update/:id/info@@ -99,6 +100,8 @@ func InitRouter() *gin.Engine {v1ContainerGroup.PUT("/:id/latest", v1.PutAppUpdate)//Not usedv1ContainerGroup.POST("/share", v1.ShareAppFile)+ v1ContainerGroup.GET("/info", v1.GetcontainerInfo)+ v1ContainerGroup.PUT("/info", v1.PutcontainerInfo)}v1AppCategoriesGroup := v1Group.Group("/app-categories")@@ -185,42 +188,6 @@ func InitRouter() *gin.Engine {{v1ImageGroup.GET("", v1.GetFileImage)}-- v1DisksGroup := v1Group.Group("/disks")- v1DisksGroup.Use()- {- //v1DiskGroup.GET("/check", v1.GetDiskCheck) //delete- //v1DisksGroup.GET("", v1.GetDiskInfo)-- //v1DisksGroup.POST("", v1.PostMountDisk)- v1DisksGroup.GET("", v1.GetDiskList)- v1DisksGroup.GET("/usb", v1.GetDisksUSBList)- v1DisksGroup.DELETE("/usb", v1.DeleteDiskUSB)- v1DisksGroup.DELETE("", v1.DeleteDisksUmount)- // //format storage- // v1DiskGroup.POST("/format", v1.PostDiskFormat)-- // //mount SATA disk- // v1DiskGroup.POST("/mount", v1.PostMountDisk)-- // //umount sata disk- // v1DiskGroup.POST("/umount", v1.PostDiskUmount)-- //v1DiskGroup.GET("/type", v1.FormatDiskType)//delete-- v1DisksGroup.DELETE("/part", v1.RemovePartition) //disk/delpart- }-- v1StorageGroup := v1Group.Group("/storage")- v1StorageGroup.Use()- {- v1StorageGroup.POST("", v1.PostDiskAddPartition)-- v1StorageGroup.PUT("", v1.PostDiskFormat)-- v1StorageGroup.DELETE("", v1.PostDiskUmount)- v1StorageGroup.GET("", v1.GetStorageList)- }v1SambaGroup := v1Group.Group("/samba")v1SambaGroup.Use(){@@ -243,9 +210,9 @@ func InitRouter() *gin.Engine {v1NotifyGroup := v1Group.Group("/notify")v1NotifyGroup.Use(){- v1NotifyGroup.POST("/:path", v1.PostNotifyMssage)+ v1NotifyGroup.POST("/:path", v1.PostNotifyMessage)//merge to system- v1NotifyGroup.POST("", v1.PostSystemNotyfiy)+ v1NotifyGroup.POST("/system_status", v1.PostSystemStatusNotify)}}return rdiff --git a/route/v1/app.go b/route/v1/app.goindex 1a9f278..cc2ee00 100644--- a/route/v1/app.go+++ b/route/v1/app.go@@ -2,10 +2,12 @@ package v1import ("encoding/json"+ "fmt""io/ioutil""strconv""github.com/IceWhaleTech/CasaOS/model"+ "github.com/IceWhaleTech/CasaOS/pkg/utils/command""github.com/IceWhaleTech/CasaOS/pkg/utils/common_err""github.com/IceWhaleTech/CasaOS/pkg/utils/file"@@ -262,3 +264,54 @@ func ShareAppFile(c *gin.Context) {content := service.MyService.Casa().ShareAppFile(str)c.JSON(common_err.SUCCESS, json.RawMessage(content))}++func GetcontainerInfo(c *gin.Context) {+ // info, err := service.MyService.Docker().GetDockerInfo()+ // if err != nil {+ // c.JSON(common_err.SERVICE_ERROR, &model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})+ // return+ // }+ daemon := model.DeckerDaemonModel{}+ data := make(map[string]interface{}, 1)+ data["docker_root_dir"] = ""+ if file.Exists("/etc/docker/daemon.json") {+ byteResult := file.ReadFullFile("/etc/docker/daemon.json")+ err := json.Unmarshal(byteResult, &daemon)+ if err != nil {+ c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err.Error()})+ return+ }+ data["docker_root_dir"] = daemon.Graph+ }+ c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})+}+func PutcontainerInfo(c *gin.Context) {+ js := make(map[string]interface{})+ err := c.BindJSON(&js)+ if err != nil {+ c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err.Error()})+ return+ }+ dockerRootDir := js["docker_root_dir"].(string)+ daemon := model.DeckerDaemonModel{}+ if file.Exists("/etc/docker/daemon.json") {+ byteResult := file.ReadFullFile("/etc/docker/daemon.json")+ err := json.Unmarshal(byteResult, &daemon)+ if err != nil {+ c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err.Error()})+ return+ }+ }+ if !file.Exists(dockerRootDir) {+ c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS), Data: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})+ return+ }+ daemon.Graph = dockerRootDir+ byteMode, _ := json.Marshal(daemon)+ file.WriteToPath(byteMode, "/etc/docker", "daemon.json")++ fmt.Println(command.ExecResultStr("systemctl daemon-reload"))+ fmt.Println(command.ExecResultStr("systemctl restart docker"))++ c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: js})+}diff --git a/route/v1/disk.go b/route/v1/disk.godeleted file mode 100644index e72e3ff..0000000--- a/route/v1/disk.go+++ /dev/null@@ -1,622 +0,0 @@-package v1--import (- "fmt"- "net/http"- "path/filepath"- "reflect"- "strconv"- "strings"- "time"-- "github.com/IceWhaleTech/CasaOS/model"- "github.com/IceWhaleTech/CasaOS/model/notify"- "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"- "github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"- "github.com/IceWhaleTech/CasaOS/pkg/utils/file"-- "github.com/IceWhaleTech/CasaOS-Common/utils/jwt"- "github.com/IceWhaleTech/CasaOS/service"- model2 "github.com/IceWhaleTech/CasaOS/service/model"- "github.com/gin-gonic/gin"- "github.com/shirou/gopsutil/v3/disk"-)--var diskMap = make(map[string]string)--// @Summary disk list-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Success 200 {string} string "ok"-// @Router /disk/list [get]-func GetDiskList(c *gin.Context) {- path := c.Query("path")- if len(path) > 0 {- m := service.MyService.Disk().GetDiskInfo(path)- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m})- return- }- t := c.DefaultQuery("type", "")- list := service.MyService.Disk().LSBLK(false)- if t == "usb" {- data := []model.DriveUSB{}- for _, v := range list {- if v.Tran == "usb" {- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Name- temp.Size = v.Size- for _, child := range v.Children {- if len(child.MountPoint) > 0 {- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- temp.Avail += avail- }- }- data = append(data, temp)- }- }- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})- return- }-- dbList := service.MyService.Disk().GetSerialAll()- part := make(map[string]int64, len(dbList))- for _, v := range dbList {- part[v.MountPoint] = v.CreatedAt- }- findSystem := 0-- disks := []model.Drive{}- storage := []model.Storage{}- avail := []model.Drive{}- for i := 0; i < len(list); i++ {- disk := model.Drive{}- if list[i].Rota {- disk.DiskType = "HDD"- } else {- disk.DiskType = "SSD"- }- disk.Serial = list[i].Serial- disk.Name = list[i].Name- disk.Size = list[i].Size- disk.Path = list[i].Path- disk.Model = list[i].Model- disk.ChildrenNumber = len(list[i].Children)- if len(list[i].Children) > 0 && findSystem == 0 {- for j := 0; j < len(list[i].Children); j++ {- if len(list[i].Children[j].Children) > 0 {- for _, v := range list[i].Children[j].Children {- if v.MountPoint == "/" {- stor := model.Storage{}- stor.MountPoint = v.MountPoint- stor.Size = v.FSSize- stor.Avail = v.FSAvail- stor.Path = v.Path- stor.Type = v.FsType- stor.DriveName = "System"- disk.Model = "System"- if strings.Contains(v.SubSystems, "mmc") {- disk.DiskType = "MMC"- } else if strings.Contains(v.SubSystems, "usb") {- disk.DiskType = "USB"- }- disk.Health = "true"-- disks = append(disks, disk)- storage = append(storage, stor)- findSystem = 1- break- }- }- } else {- if list[i].Children[j].MountPoint == "/" {- stor := model.Storage{}- stor.MountPoint = list[i].Children[j].MountPoint- stor.Size = list[i].Children[j].FSSize- stor.Avail = list[i].Children[j].FSAvail- stor.Path = list[i].Children[j].Path- stor.Type = list[i].Children[j].FsType- stor.DriveName = "System"- disk.Model = "System"- if strings.Contains(list[i].Children[j].SubSystems, "mmc") {- disk.DiskType = "MMC"- } else if strings.Contains(list[i].Children[j].SubSystems, "usb") {- disk.DiskType = "USB"- }- disk.Health = "true"-- disks = append(disks, disk)- storage = append(storage, stor)- findSystem = 1- break- }- }-- }- }- if findSystem == 1 {- findSystem += 1- continue- }-- if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {- temp := service.MyService.Disk().SmartCTL(list[i].Path)- if reflect.DeepEqual(temp, model.SmartctlA{}) {- temp.SmartStatus.Passed = true- }- isAvail := true- for _, v := range list[i].Children {- if v.MountPoint != "" {- stor := model.Storage{}- stor.MountPoint = v.MountPoint- stor.Size = v.FSSize- stor.Avail = v.FSAvail- stor.Path = v.Path- stor.Type = v.FsType- stor.DriveName = list[i].Name- storage = append(storage, stor)- isAvail = false- }- }-- if isAvail {- //if len(list[i].Children) == 1 && list[i].Children[0].FsType == "ext4" {- disk.NeedFormat = false- avail = append(avail, disk)- // } else {- // disk.NeedFormat = true- // avail = append(avail, disk)- // }- }-- disk.Temperature = temp.Temperature.Current- disk.Health = strconv.FormatBool(temp.SmartStatus.Passed)-- disks = append(disks, disk)- }- }- data := make(map[string]interface{}, 3)- data["drive"] = disks- data["storage"] = storage- data["avail"] = avail-- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})-}--// @Summary disk list-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Success 200 {string} string "ok"-// @Router /disk/list [get]-func GetDisksUSBList(c *gin.Context) {- list := service.MyService.Disk().LSBLK(false)- data := []model.DriveUSB{}- for _, v := range list {- if v.Tran == "usb" {- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Label- if temp.Name == "" {- temp.Name = v.Name- }- temp.Size = v.Size- children := []model.USBChildren{}- for _, child := range v.Children {-- if len(child.MountPoint) > 0 {- tempChildren := model.USBChildren{}- tempChildren.MountPoint = child.MountPoint- tempChildren.Size, _ = strconv.ParseUint(child.FSSize, 10, 64)- tempChildren.Avail, _ = strconv.ParseUint(child.FSAvail, 10, 64)- tempChildren.Name = child.Label- if len(tempChildren.Name) == 0 {- tempChildren.Name = filepath.Base(child.MountPoint)- }- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- children = append(children, tempChildren)- temp.Avail += avail- }- }-- temp.Children = children- data = append(data, temp)- }- }- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})--}--func DeleteDisksUmount(c *gin.Context) {- js := make(map[string]string)- c.ShouldBind(&js)-- path := js["path"]- pwd := js["password"]-- if len(path) == 0 {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})- return- }- token := c.GetHeader("Authorization")- if len(token) == 0 {- token = c.Query("token")- }- claims, err := jwt.ParseToken(token, true)- if err != nil {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})- return- }-- if encryption.GetMD5ByStr(pwd) != claims.Password {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})- return- }-- if _, ok := diskMap[path]; ok {- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)})- return- }-- diskInfo := service.MyService.Disk().GetDiskInfo(path)- for _, v := range diskInfo.Children {- service.MyService.Disk().UmountPointAndRemoveDir(v.Path)- //delete data- service.MyService.Disk().DeleteMountPoint(v.Path, v.MountPoint)-- service.MyService.Shares().DeleteShareByPath(v.MountPoint)- }-- service.MyService.Disk().RemoveLSBLKCache()-- //send notify to client- msg := notify.StorageMessage{}- msg.Action = "REMOVED"- msg.Path = path- msg.Volume = ""- msg.Size = 0- msg.Type = ""- service.MyService.Notify().SendStorageBySocket(msg)- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: path})-}--func DeleteDiskUSB(c *gin.Context) {- js := make(map[string]string)- c.ShouldBind(&js)- mountPoint := js["mount_point"]- if file.CheckNotExist(mountPoint) {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.DIR_NOT_EXISTS, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})- return- }- service.MyService.Disk().UmountUSB(mountPoint)- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: mountPoint})-}--// @Summary get disk list-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Success 200 {string} string "ok"-// @Router /disk/lists [get]-func GetPlugInDisks(c *gin.Context) {-- list := service.MyService.Disk().LSBLK(true)- var result []*disk.UsageStat- for _, item := range list {- result = append(result, service.MyService.Disk().GetDiskInfoByPath(item.Path))- }- c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: result})-}--// @Summary disk detail-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Param path query string true "for example /dev/sda"-// @Success 200 {string} string "ok"-// @Router /disk/info [get]-func GetDiskInfo(c *gin.Context) {- path := c.Query("path")- if len(path) == 0 {- c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})- }- m := service.MyService.Disk().GetDiskInfo(path)- c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m})-}--// @Summary 获取支持的格式-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Success 200 {string} string "ok"-// @Router /disk/type [get]-func FormatDiskType(c *gin.Context) {- var strArr = [4]string{"fat32", "ntfs", "ext4", "exfat"}- c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: strArr})--}--// @Summary 删除分区-// @Produce application/json-// @Accept multipart/form-data-// @Tags disk-// @Security ApiKeyAuth-// @Param path formData string true "磁盘路径 例如/dev/sda1"-// @Success 200 {string} string "ok"-// @Router /disk/delpart [delete]-func RemovePartition(c *gin.Context) {- js := make(map[string]string)- c.ShouldBind(&js)- path := js["path"]-- if len(path) == 0 {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})- }- var p = path[:len(path)-1]- var n = path[len(path)-1:]- service.MyService.Disk().DelPartition(p, n)- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})-}--// @Summary add storage-// @Produce application/json-// @Accept multipart/form-data-// @Tags disk-// @Security ApiKeyAuth-// @Param path formData string true "disk path e.g. /dev/sda"-// @Param serial formData string true "serial"-// @Param name formData string true "name"-// @Param format formData bool true "need format(true)"-// @Success 200 {string} string "ok"-// @Router /disk/storage [post]-func PostDiskAddPartition(c *gin.Context) {-- js := make(map[string]interface{})- c.ShouldBind(&js)- path := js["path"].(string)- name := js["name"].(string)- format := js["format"].(bool)-- if len(path) == 0 {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})- return- }- if _, ok := diskMap[path]; ok {- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)})- return- }-- //diskInfo := service.MyService.Disk().GetDiskInfo(path)-- // if !file.CheckNotExist("/DATA/" + name) {- // // /mnt/name exist- // c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.NAME_NOT_AVAILABLE, Message: common_err.GetMsg(common_err.NAME_NOT_AVAILABLE)})- // return- // }- diskMap[path] = "busying"- currentDisk := service.MyService.Disk().GetDiskInfo(path)- if format {- // format := service.MyService.Disk().FormatDisk(path+"1", "ext4")- // if len(format) == 0 {- // delete(diskMap, path)- // c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FORMAT_ERROR, Message: common_err.GetMsg(common_err.FORMAT_ERROR)})- // return- // }- service.MyService.Disk().AddPartition(path)- }-- // formatBool := true- // for formatBool {- // currentDisk = service.MyService.Disk().GetDiskInfo(path)- // if len(currentDisk.Children) > 0 {- // formatBool = false- // break- // }- // time.Sleep(time.Second)- // }- currentDisk = service.MyService.Disk().GetDiskInfo(path)- // if len(currentDisk.Children) != 1 {- // c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)})- // return- // }- fmt.Println(name)- if len(name) == 0 {- name = "Storage"- }- fmt.Println(name)- for i := 0; i < len(currentDisk.Children); i++ {- childrenName := currentDisk.Children[i].Label- if len(childrenName) == 0 {- //childrenName = name + "_" + currentDisk.Children[i].Name- childrenName = name + "_" + strconv.Itoa(i+1)- }- mountPath := "/DATA/" + childrenName- if !file.CheckNotExist(mountPath) {- ls := service.MyService.System().GetDirPath(mountPath)- if len(ls) > 0 {- // exist- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.NAME_NOT_AVAILABLE, Message: common_err.GetMsg(common_err.NAME_NOT_AVAILABLE)})- return- }- }- m := model2.SerialDisk{}- m.MountPoint = mountPath- m.Path = currentDisk.Children[i].Path- m.UUID = currentDisk.Children[i].UUID- m.State = 0- m.CreatedAt = time.Now().Unix()- service.MyService.Disk().SaveMountPoint(m)- //mount dir- service.MyService.Disk().MountDisk(currentDisk.Children[i].Path, mountPath)- }-- service.MyService.Disk().RemoveLSBLKCache()-- delete(diskMap, path)-- //send notify to client- msg := notify.StorageMessage{}- msg.Action = "ADDED"- msg.Path = currentDisk.Children[0].Path- msg.Volume = "/DATA/"- msg.Size = currentDisk.Children[0].Size- msg.Type = currentDisk.Children[0].Tran- service.MyService.Notify().SendStorageBySocket(msg)-- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})-}--// @Param pwd formData string true "user password"-// @Param volume formData string true "mount point"-// @Success 200 {string} string "ok"-// @Router /disk/format [post]-func PostDiskFormat(c *gin.Context) {- js := make(map[string]string)- c.ShouldBind(&js)- path := js["path"]- t := "ext4"- pwd := js["password"]- volume := js["volume"]- token := c.GetHeader("Authorization")- if len(token) == 0 {- token = c.Query("token")- }- claims, err := jwt.ParseToken(token, true)- if err != nil {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})- return- }-- if encryption.GetMD5ByStr(pwd) != claims.Password {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})- return- }-- if len(path) == 0 || len(t) == 0 {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})- return- }- if _, ok := diskMap[path]; ok {- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)})- return- }- diskMap[path] = "busying"- service.MyService.Disk().UmountPointAndRemoveDir(path)- format := service.MyService.Disk().FormatDisk(path, t)- if len(format) == 0 {- delete(diskMap, path)- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FORMAT_ERROR, Message: common_err.GetMsg(common_err.FORMAT_ERROR)})- return- }- service.MyService.Disk().MountDisk(path, volume)- service.MyService.Disk().RemoveLSBLKCache()- delete(diskMap, path)- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})-}--// @Summary remove mount point-// @Produce application/json-// @Accept multipart/form-data-// @Tags disk-// @Security ApiKeyAuth-// @Param path formData string true "e.g. /dev/sda1"-// @Param mount_point formData string true "e.g. /mnt/volume1"-// @Param pwd formData string true "user password"-// @Success 200 {string} string "ok"-// @Router /disk/umount [post]-func PostDiskUmount(c *gin.Context) {- js := make(map[string]string)- c.ShouldBind(&js)-- path := js["path"]- mountPoint := js["volume"]- pwd := js["password"]-- if len(path) == 0 || len(mountPoint) == 0 {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})- return- }- token := c.GetHeader("Authorization")- if len(token) == 0 {- token = c.Query("token")- }- claims, err := jwt.ParseToken(token, true)- if err != nil {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})- return- }-- if encryption.GetMD5ByStr(pwd) != claims.Password {- c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})- return- }-- if _, ok := diskMap[path]; ok {- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)})- return- }-- service.MyService.Disk().UmountPointAndRemoveDir(path)- //delete data- service.MyService.Disk().DeleteMountPoint(path, mountPoint)- service.MyService.Disk().RemoveLSBLKCache()-- //send notify to client- msg := notify.StorageMessage{}- msg.Action = "REMOVED"- msg.Path = path- msg.Volume = mountPoint- msg.Size = 0- msg.Type = ""- service.MyService.Notify().SendStorageBySocket(msg)- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})-}--// @Summary confirm delete disk-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Param id path string true "id"-// @Success 200 {string} string "ok"-// @Router /disk/remove/{id} [delete]-func DeleteDisk(c *gin.Context) {- id := c.Param("id")- service.MyService.Disk().DeleteMount(id)- c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})-}--// @Summary check mount point-// @Produce application/json-// @Accept application/json-// @Tags disk-// @Security ApiKeyAuth-// @Success 200 {string} string "ok"-// @Router /disk/init [get]-func GetDiskCheck(c *gin.Context) {-- dbList := service.MyService.Disk().GetSerialAll()- list := service.MyService.Disk().LSBLK(true)-- mapList := make(map[string]string)-- for _, v := range list {- mapList[v.Serial] = "1"- }-- for _, v := range dbList {- if _, ok := mapList[v.UUID]; !ok {- //disk undefind- c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: "disk undefind"})- return- }- }-- c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})-}diff --git a/route/v1/file.go b/route/v1/file.goindex 0b2dbc7..548ee4a 100644--- a/route/v1/file.go+++ b/route/v1/file.go@@ -236,33 +236,8 @@ func DirPath(c *gin.Context) {info[i].Type = "application"}}- } else if path == "/DATA" {- disk := make(map[string]string)- lsblk := service.MyService.Disk().LSBLK(true)- for _, v := range lsblk {- if len(v.Children) > 0 {- t := v.Tran- for _, c := range v.Children {- if len(c.Children) > 0 {- for _, gc := range c.Children {- if len(gc.MountPoint) > 0 {- disk[gc.MountPoint] = t- }- }- }- if len(c.MountPoint) > 0 {- disk[c.MountPoint] = t- }- }-- }- }- for i := 0; i < len(info); i++ {- if v, ok := disk[info[i].Path]; ok {- info[i].Type = v- }- }}+for i := 0; i < len(info); i++ {if v, ok := sharesMap[info[i].Path]; ok {ex := make(map[string]interface{})diff --git a/route/v1/notiry.go b/route/v1/notiry.goindex 54e86fd..eef2a1b 100644--- a/route/v1/notiry.go+++ b/route/v1/notiry.go@@ -7,14 +7,15 @@ import ("github.com/gin-gonic/gin")-func PostNotifyMssage(c *gin.Context) {+func PostNotifyMessage(c *gin.Context) {path := c.Param("path")message := make(map[string]interface{})c.ShouldBind(&message)service.MyService.Notify().SendNotify(path, message)c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})}-func PostSystemNotyfiy(c *gin.Context) {++func PostSystemStatusNotify(c *gin.Context) {message := make(map[string]interface{})c.ShouldBind(&message)service.MyService.Notify().SettingSystemTempData(message)diff --git a/route/v1/storage.go b/route/v1/storage.godeleted file mode 100644index b6bb3e3..0000000--- a/route/v1/storage.go+++ /dev/null@@ -1,109 +0,0 @@-/*- * @Author: LinkLeong [email protected]- * @Date: 2022-07-11 16:02:29- * @LastEditors: LinkLeong- * @LastEditTime: 2022-08-17 19:14:50- * @FilePath: /CasaOS/route/v1/storage.go- * @Description:- * @Website: https://www.casaos.io- * Copyright (c) 2022 by icewhale, All Rights Reserved.- */-package v1--import (- "path/filepath"- "reflect"-- "github.com/IceWhaleTech/CasaOS/model"- "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"- "github.com/IceWhaleTech/CasaOS/service"- "github.com/gin-gonic/gin"-)--func GetStorageList(c *gin.Context) {- system := c.Query("system")- storages := []model.Storages{}- disks := service.MyService.Disk().LSBLK(false)- diskNumber := 1- children := 1- findSystem := 0- for _, d := range disks {- if d.Tran != "usb" {- tempSystemDisk := false- children = 1- tempDisk := model.Storages{- DiskName: d.Model,- Path: d.Path,- Size: d.Size,- }-- storageArr := []model.Storage{}- temp := service.MyService.Disk().SmartCTL(d.Path)- if reflect.DeepEqual(temp, model.SmartctlA{}) {- temp.SmartStatus.Passed = true- }- for _, v := range d.Children {- if v.MountPoint != "" {- if findSystem == 0 {- if v.MountPoint == "/" {- tempDisk.DiskName = "System"- findSystem = 1- tempSystemDisk = true- }- if len(v.Children) > 0 {- for _, c := range v.Children {- if c.MountPoint == "/" {- tempDisk.DiskName = "System"- findSystem = 1- tempSystemDisk = true- break- }- }- }- }-- stor := model.Storage{}- stor.MountPoint = v.MountPoint- stor.Size = v.FSSize- stor.Avail = v.FSAvail- stor.Path = v.Path- stor.Type = v.FsType- stor.DriveName = v.Name- if len(v.Label) == 0 {- if stor.MountPoint == "/" {- stor.Label = "System"- } else {- stor.Label = filepath.Base(stor.MountPoint)- }-- children += 1- } else {- stor.Label = v.Label- }- storageArr = append(storageArr, stor)- }- }-- if len(storageArr) > 0 {- if tempSystemDisk && len(system) > 0 {- tempStorageArr := []model.Storage{}- for i := 0; i < len(storageArr); i++ {- if storageArr[i].MountPoint != "/boot/efi" && storageArr[i].Type != "swap" {- tempStorageArr = append(tempStorageArr, storageArr[i])- }- }- tempDisk.Children = tempStorageArr- storages = append(storages, tempDisk)- diskNumber += 1- } else if !tempSystemDisk {- tempDisk.Children = storageArr- storages = append(storages, tempDisk)- diskNumber += 1- }-- }- }- }-- c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: storages})-}diff --git a/route/v1/system.go b/route/v1/system.goindex 9f908d2..29fbcf2 100644--- a/route/v1/system.go+++ b/route/v1/system.go@@ -7,7 +7,6 @@ import ("io/ioutil""net/http""os"- "reflect""strconv""strings""time"@@ -16,14 +15,12 @@ import ("github.com/IceWhaleTech/CasaOS/model""github.com/IceWhaleTech/CasaOS/pkg/config""github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"- "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port""github.com/IceWhaleTech/CasaOS/pkg/utils/version""github.com/IceWhaleTech/CasaOS/service"model2 "github.com/IceWhaleTech/CasaOS/service/model""github.com/IceWhaleTech/CasaOS/types""github.com/gin-gonic/gin"- "go.uber.org/zap")// @Summary check version@@ -79,7 +76,7 @@ func GetCasaOSErrorLogs(c *gin.Context) {c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: service.MyService.System().GetCasaOSLogs(line)})}-//系统配置+// 系统配置func GetSystemConfigDebug(c *gin.Context) {array := service.MyService.System().GetSystemConfigDebug()disk := service.MyService.System().GetDiskInfo()@@ -185,31 +182,6 @@ func PutSystemUSBAutoMount(c *gin.Context) {service.MyService.System().UpdateUSBAutoMount("False")service.MyService.System().ExecUSBAutoMountShell("False")}- go func() {- usbList := service.MyService.Disk().LSBLK(false)- usb := []model.DriveUSB{}- for _, v := range usbList {- if v.Tran == "usb" {- isMount := false- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Name- temp.Size = v.Size- for _, child := range v.Children {- if len(child.MountPoint) > 0 {- isMount = true- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- temp.Avail += avail-- }- }- if isMount {- usb = append(usb, temp)- }- }- }- service.MyService.Notify().SendUSBInfoBySocket(usb)- }()c.JSON(common_err.SUCCESS,model.Result{Success: common_err.SUCCESS,@@ -229,31 +201,6 @@ func GetSystemUSBAutoMount(c *gin.Context) {if config.ServerInfo.USBAutoMount == "False" {state = "False"}- go func() {- usbList := service.MyService.Disk().LSBLK(false)- usb := []model.DriveUSB{}- for _, v := range usbList {- if v.Tran == "usb" {- isMount := false- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Name- temp.Size = v.Size- for _, child := range v.Children {- if len(child.MountPoint) > 0 {- isMount = true- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- temp.Avail += avail-- }- }- if isMount {- usb = append(usb, temp)- }- }- }- service.MyService.Notify().SendUSBInfoBySocket(usb)- }()c.JSON(common_err.SUCCESS,model.Result{Success: common_err.SUCCESS,@@ -324,98 +271,6 @@ func GetSystemHardwareInfo(c *gin.Context) {// @Router /sys/utilization [get]func GetSystemUtilization(c *gin.Context) {var data = make(map[string]interface{}, 6)-- list := service.MyService.Disk().LSBLK(true)-- summary := model.Summary{}- healthy := true- findSystem := 0-- for i := 0; i < len(list); i++ {- if len(list[i].Children) > 0 && findSystem == 0 {-- for j := 0; j < len(list[i].Children); j++ {-- if len(list[i].Children[j].Children) > 0 {- for _, v := range list[i].Children[j].Children {- if v.MountPoint == "/" {- s, _ := strconv.ParseUint(v.FSSize, 10, 64)- a, _ := strconv.ParseUint(v.FSAvail, 10, 64)- u, _ := strconv.ParseUint(v.FSUsed, 10, 64)- loger.Info("disk info", zap.Any("/ total:", s))- loger.Info("disk path", zap.Any("path", v.Path))- summary.Size += s- summary.Avail += a- summary.Used += u- findSystem = 1- break- }- }- } else {- if list[i].Children[j].MountPoint == "/" {- s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)- a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)- u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 10, 64)- loger.Info("disk info", zap.Any("/ total:", s))- loger.Info("disk path", zap.Any("path", list[i].Path))- summary.Size += s- summary.Avail += a- summary.Used += u- findSystem = 1- break- }- }- }-- }- if findSystem == 1 {- findSystem += 1- continue- }- if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {- temp := service.MyService.Disk().SmartCTL(list[i].Path)- if reflect.DeepEqual(temp, model.SmartctlA{}) {- healthy = true- } else {- healthy = temp.SmartStatus.Passed- }- if len(list[i].Children) > 0 {- for _, v := range list[i].Children {- s, _ := strconv.ParseUint(v.FSSize, 10, 64)- a, _ := strconv.ParseUint(v.FSAvail, 10, 64)- u, _ := strconv.ParseUint(v.FSUsed, 10, 64)- loger.Info("disk info", zap.Any("/ total:", s))- loger.Info("disk path", zap.Any("path", list[i].Path))- summary.Size += s- summary.Avail += a- summary.Used += u- }- }-- }- }-- summary.Health = healthy- data["disk"] = summary- usbList := service.MyService.Disk().LSBLK(false)- usb := []model.DriveUSB{}- for _, v := range usbList {- if v.Tran == "usb" {- temp := model.DriveUSB{}- temp.Model = v.Model- temp.Name = v.Name- temp.Size = v.Size-- for _, child := range v.Children {- if len(child.MountPoint) > 0 {- avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)- temp.Avail += avail- }- }- usb = append(usb, temp)- }- }- data["usb"] = usbcpu := service.MyService.System().GetCpuPercent()num := service.MyService.System().GetCpuCoreNum()cpuData := make(map[string]interface{})diff --git a/service/disk.go b/service/disk.godeleted file mode 100644index dfe8219..0000000--- a/service/disk.go+++ /dev/null@@ -1,285 +0,0 @@-package service--import (- json2 "encoding/json"- "fmt"- "reflect"- "strconv"- "strings"- "time"-- "github.com/IceWhaleTech/CasaOS/model"- "github.com/IceWhaleTech/CasaOS/pkg/config"- command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command"- "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"- model2 "github.com/IceWhaleTech/CasaOS/service/model"- "github.com/shirou/gopsutil/v3/disk"- "github.com/tidwall/gjson"- "go.uber.org/zap"- "gorm.io/gorm"-)--type DiskService interface {- GetPlugInDisk() []string- LSBLK(isUseCache bool) []model.LSBLKModel- SmartCTL(path string) model.SmartctlA- FormatDisk(path, format string) []string- UmountPointAndRemoveDir(path string) []string- GetDiskInfo(path string) model.LSBLKModel- DelPartition(path, num string) string- AddPartition(path string) string- GetDiskInfoByPath(path string) *disk.UsageStat- MountDisk(path, volume string)- GetSerialAll() []model2.SerialDisk- SaveMountPoint(m model2.SerialDisk)- DeleteMountPoint(path, mountPoint string)- DeleteMount(id string)- UpdateMountPoint(m model2.SerialDisk)- RemoveLSBLKCache()- UmountUSB(path string)-}-type diskService struct {- db *gorm.DB-}--func (d *diskService) RemoveLSBLKCache() {- key := "system_lsblk"- Cache.Delete(key)-}-func (d *diskService) UmountUSB(path string) {- r := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;UDEVILUmount " + path)- fmt.Println(r)-}-func (d *diskService) SmartCTL(path string) model.SmartctlA {-- key := "system_smart_" + path- if result, ok := Cache.Get(key); ok {-- res, ok := result.(model.SmartctlA)- if ok {- return res- }- }- var m model.SmartctlA- str := command2.ExecSmartCTLByPath(path)- if str == nil {- loger.Error("failed to exec shell ", zap.Any("err", "smartctl exec error"))- Cache.Add(key, m, time.Minute*10)- return m- }-- err := json2.Unmarshal([]byte(str), &m)- if err != nil {- loger.Error("Failed to unmarshal json", zap.Any("err", err))- }- if !reflect.DeepEqual(m, model.SmartctlA{}) {- Cache.Add(key, m, time.Hour*24)- }- return m-}--//通过脚本获取外挂磁盘-func (d *diskService) GetPlugInDisk() []string {- return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetPlugInDisk")-}--//格式化硬盘-func (d *diskService) FormatDisk(path, format string) []string {- r := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;FormatDisk " + path + " " + format)- return r-}--//移除挂载点,删除目录-func (d *diskService) UmountPointAndRemoveDir(path string) []string {- r := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;UMountPorintAndRemoveDir " + path)- return r-}--//删除分区-func (d *diskService) DelPartition(path, num string) string {- r := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;DelPartition " + path + " " + num)- fmt.Println(r)- return ""-}--//part-func (d *diskService) AddPartition(path string) string {- command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;AddPartition " + path)- return ""-}--func (d *diskService) AddAllPartition(path string) {--}--//获取硬盘详情-func (d *diskService) GetDiskInfoByPath(path string) *disk.UsageStat {- diskInfo, err := disk.Usage(path + "1")-- if err != nil {- fmt.Println(err)- }- diskInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.UsedPercent), 64)- diskInfo.InodesUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.InodesUsedPercent), 64)- return diskInfo-}--//get disk details-func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {- key := "system_lsblk"- var n []model.LSBLKModel-- if result, ok := Cache.Get(key); ok && isUseCache {-- res, ok := result.([]model.LSBLKModel)- if ok {- return res- }- }-- str := command2.ExecLSBLK()- if str == nil {- loger.Error("Failed to exec shell", zap.Any("err", "lsblk exec error"))- return nil- }- var m []model.LSBLKModel- err := json2.Unmarshal([]byte(gjson.Get(string(str), "blockdevices").String()), &m)- if err != nil {- loger.Error("Failed to unmarshal json", zap.Any("err", err))- }-- var c []model.LSBLKModel-- var fsused uint64-- var health = true- for _, i := range m {- if i.Type != "loop" && !i.RO {- fsused = 0- for _, child := range i.Children {- if child.RM {- child.Health = strings.TrimSpace(command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDiskHealthState " + child.Path))- if strings.ToLower(strings.TrimSpace(child.State)) != "ok" {- health = false- }- f, _ := strconv.ParseUint(child.FSUsed, 10, 64)- fsused += f- } else {- health = false- }- c = append(c, child)- }- //i.Format = strings.TrimSpace(command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDiskType " + i.Path))- if health {- i.Health = "OK"- }- i.FSUsed = strconv.FormatUint(fsused, 10)- i.Children = c- if fsused > 0 {- i.UsedPercent, err = strconv.ParseFloat(fmt.Sprintf("%.4f", float64(fsused)/float64(i.Size)), 64)- if err != nil {- loger.Error("Failed to parse float", zap.Any("err", err))- }- }- n = append(n, i)- health = true- c = []model.LSBLKModel{}- fsused = 0- }- }- if len(n) > 0 {- Cache.Add(key, n, time.Second*100)- }- return n-}--func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {- str := command2.ExecLSBLKByPath(path)- if str == nil {- loger.Error("Failed to exec shell", zap.Any("err", "lsblk exec error"))- return model.LSBLKModel{}- }-- var ml []model.LSBLKModel- err := json2.Unmarshal([]byte(gjson.Get(string(str), "blockdevices").String()), &ml)- if err != nil {- loger.Error("Failed to unmarshal json", zap.Any("err", err))- return model.LSBLKModel{}- }-- m := model.LSBLKModel{}- if len(ml) > 0 {- m = ml[0]- }- return m- // 下面为计算是否可以继续分区的部分,暂时不需要- chiArr := make(map[string]string)- chiList := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetPartitionSectors " + m.Path)- if len(chiList) == 0 {- loger.Error("chiList length error", zap.Any("err", "chiList length error"))- }- for i := 0; i < len(chiList); i++ {- tempArr := strings.Split(chiList[i], ",")- chiArr[tempArr[0]] = chiList[i]- }- var maxSector uint64 = 0- for i := 0; i < len(m.Children); i++ {- tempArr := strings.Split(chiArr[m.Children[i].Path], ",")- m.Children[i].StartSector, _ = strconv.ParseUint(tempArr[1], 10, 64)- m.Children[i].EndSector, _ = strconv.ParseUint(tempArr[2], 10, 64)- if m.Children[i].EndSector > maxSector {- maxSector = m.Children[i].EndSector- }-- }- diskEndSector := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDiskSizeAndSectors " + m.Path)-- if len(diskEndSector) < 2 {- loger.Error("diskEndSector length error", zap.Any("err", "diskEndSector length error"))- }- diskEndSectorInt, _ := strconv.ParseUint(diskEndSector[len(diskEndSector)-1], 10, 64)- if (diskEndSectorInt-maxSector)*m.MinIO/1024/1024 > 100 {- //添加可以分区情况- p := model.LSBLKModel{}- p.Path = "可以添加"- m.Children = append(m.Children, p)- }- return m-}--func (d *diskService) MountDisk(path, volume string) {- //fmt.Println("source " + config.AppInfo.ShellPath + "/helper.sh ;do_mount " + path + " " + volume)- r := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;do_mount " + path + " " + volume)- fmt.Println(r)-}--func (d *diskService) SaveMountPoint(m model2.SerialDisk) {- d.db.Where("uuid = ?", m.UUID).Delete(&model2.SerialDisk{})- d.db.Create(&m)-}--func (d *diskService) UpdateMountPoint(m model2.SerialDisk) {- d.db.Model(&model2.SerialDisk{}).Where("uui = ?", m.UUID).Update("mount_point", m.MountPoint)-}--func (d *diskService) DeleteMount(id string) {-- d.db.Delete(&model2.SerialDisk{}).Where("id = ?", id)-}--func (d *diskService) DeleteMountPoint(path, mountPoint string) {-- d.db.Where("path = ? AND mount_point = ?", path, mountPoint).Delete(&model2.SerialDisk{})-- command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;do_umount " + path)-}--func (d *diskService) GetSerialAll() []model2.SerialDisk {- var m []model2.SerialDisk- d.db.Find(&m)- return m-}--func NewDiskService(db *gorm.DB) DiskService {- return &diskService{db: db}-}diff --git a/service/docker.go b/service/docker.goindex 9fe885f..812fb8a 100644--- a/service/docker.go+++ b/service/docker.go@@ -59,6 +59,7 @@ type DockerService interface {DockerImageInfo(image string) (types.ImageInspect, error)GetNetWorkNameByNetWorkID(id string) (string, error)ContainerExecShell(container_id string) string+ GetDockerInfo() (types.Info, error)}type dockerService struct {@@ -94,7 +95,7 @@ func (ds *dockerService) ContainerExecShell(container_id string) string {return exec.ID}-//创建默认网络+// 创建默认网络func DockerNetwork() {cli, _ := client2.NewClientWithOpts(client2.FromEnv)@@ -109,7 +110,7 @@ func DockerNetwork() {cli.NetworkCreate(context.Background(), docker.NETWORKNAME, types.NetworkCreate{})}-//根据网络id获取网络名+// 根据网络id获取网络名func (ds *dockerService) GetNetWorkNameByNetWorkID(id string) (string, error) {cli, _ := client2.NewClientWithOpts(client2.FromEnv)defer cli.Close()@@ -122,7 +123,7 @@ func (ds *dockerService) GetNetWorkNameByNetWorkID(id string) (string, error) {return "", err}-//拉取镜像+// 拉取镜像func DockerPull() {cli, _ := client2.NewClientWithOpts(client2.FromEnv)@@ -141,7 +142,7 @@ func DockerPull() {}-//拉取镜像+// 拉取镜像func DockerEx() {cli, _ := client2.NewClientWithOpts(client2.FromEnv)@@ -292,7 +293,7 @@ func DockerLogs() {//正式内容-//检查镜像是否存在+// 检查镜像是否存在func (ds *dockerService) IsExistImage(imageName string) bool {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -311,7 +312,7 @@ func (ds *dockerService) IsExistImage(imageName string) bool {return false}-//安装镜像+// 安装镜像func (ds *dockerService) DockerPullImage(imageName string, icon, name string) error {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -365,12 +366,12 @@ func (ds *dockerService) DockerContainerCopyCreate(info *types.ContainerJSON) (creturn container.ID, err}-//param imageName 镜像名称-//param containerDbId 数据库的id-//param port 容器内部主端口-//param mapPort 容器主端口映射到外部的端口-//param tcp 容器其他tcp端口-//param udp 容器其他udp端口+// param imageName 镜像名称+// param containerDbId 数据库的id+// param port 容器内部主端口+// param mapPort 容器主端口映射到外部的端口+// param tcp 容器其他tcp端口+// param udp 容器其他udp端口func (ds *dockerService) DockerContainerCreate(m model.CustomizationPostData, id string) (containerId string, err error) {if len(m.NetworkModel) == 0 {m.NetworkModel = "bridge"@@ -581,7 +582,7 @@ func (ds *dockerService) DockerContainerCreate(m model.CustomizationPostData, idreturn containerDb.ID, err}-//删除容器+// 删除容器func (ds *dockerService) DockerContainerRemove(name string, update bool) error {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -605,7 +606,7 @@ func (ds *dockerService) DockerContainerRemove(name string, update bool) error {return err}-//删除镜像+// 删除镜像func (ds *dockerService) DockerImageRemove(name string) error {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -653,7 +654,7 @@ Loop:return err}-//停止镜像+// 停止镜像func (ds *dockerService) DockerContainerStop(id string) error {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -664,7 +665,7 @@ func (ds *dockerService) DockerContainerStop(id string) error {return err}-//启动容器+// 启动容器func (ds *dockerService) DockerContainerStart(name string) error {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -675,7 +676,7 @@ func (ds *dockerService) DockerContainerStart(name string) error {return err}-//查看日志+// 查看日志func (ds *dockerService) DockerContainerLog(name string) (string, error) {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -714,7 +715,7 @@ func DockerContainerStats1() error {return nil}-//获取容器状态+// 获取容器状态func (ds *dockerService) DockerContainerStats(name string) (string, error) {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -733,7 +734,7 @@ func (ds *dockerService) DockerContainerStats(name string) (string, error) {return string(sts), nil}-//备份容器+// 备份容器func (ds *dockerService) DockerContainerCommit(name string) {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -778,7 +779,7 @@ func (ds *dockerService) DockerListByImage(image, version string) (*types.Contaireturn &containers[0], nil}-//获取容器详情+// 获取容器详情func (ds *dockerService) DockerContainerInfo(name string) (*types.ContainerJSON, error) {cli, err := client2.NewClientWithOpts(client2.FromEnv)@@ -793,13 +794,13 @@ func (ds *dockerService) DockerContainerInfo(name string) (*types.ContainerJSON,return &d, nil}-//更新容器-//param shares cpu优先级-//param containerDbId 数据库的id-//param port 容器内部主端口-//param mapPort 容器主端口映射到外部的端口-//param tcp 容器其他tcp端口-//param udp 容器其他udp端口+// 更新容器+// param shares cpu优先级+// param containerDbId 数据库的id+// param port 容器内部主端口+// param mapPort 容器主端口映射到外部的端口+// param tcp 容器其他tcp端口+// param udp 容器其他udp端口func (ds *dockerService) DockerContainerUpdate(m model.CustomizationPostData, id string) (err error) {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -834,9 +835,9 @@ func (ds *dockerService) DockerContainerUpdate(m model.CustomizationPostData, idreturn}-//更新容器名称-//param name 容器名称-//param id 老的容器名称+// 更新容器名称+// param name 容器名称+// param id 老的容器名称func (ds *dockerService) DockerContainerUpdateName(name, id string) (err error) {cli, err := client2.NewClientWithOpts(client2.FromEnv)if err != nil {@@ -851,7 +852,7 @@ func (ds *dockerService) DockerContainerUpdateName(name, id string) (err error)return}-//获取网络列表+// 获取网络列表func (ds *dockerService) DockerNetworkModelList() []types.NetworkResource {cli, _ := client2.NewClientWithOpts(client2.FromEnv)@@ -863,6 +864,17 @@ func NewDockerService() DockerService {return &dockerService{rootDir: command2.ExecResultStr(`source ./shell/helper.sh ;GetDockerRootDir`)}}+func (ds *dockerService) GetDockerInfo() (types.Info, error) {+ cli, err := client2.NewClientWithOpts(client2.FromEnv)+ if err != nil {+ return types.Info{}, err+ }+ defer cli.Close()++ return cli.Info(context.Background())++}+// ---------------------------------------test------------------------------------//func ServiceCreate() {// cli, err := client2.NewClientWithOpts(client2.FromEnv)diff --git a/service/model/o_disk.go b/service/model/o_disk.godeleted file mode 100644index 1121e87..0000000--- a/service/model/o_disk.go+++ /dev/null@@ -1,25 +0,0 @@-/*- * @Author: LinkLeong [email protected]- * @Date: 2021-12-07 17:14:41- * @LastEditors: LinkLeong- * @LastEditTime: 2022-08-17 18:46:43- * @FilePath: /CasaOS/service/model/o_disk.go- * @Description:- * @Website: https://www.casaos.io- * Copyright (c) 2022 by icewhale, All Rights Reserved.- */-package model--//SerialAdvanced Technology Attachment (STAT)-type SerialDisk struct {- Id uint `gorm:"column:id;primary_key" json:"id"`- UUID string `json:"uuid"`- Path string `json:"path"`- State int `json:"state"`- MountPoint string `json:"mount_point"`- CreatedAt int64 `json:"created_at"`-}--func (p *SerialDisk) TableName() string {- return "o_disk"-}diff --git a/service/notify.go b/service/notify.goindex fe93d83..05d3162 100644--- a/service/notify.go+++ b/service/notify.go@@ -31,11 +31,9 @@ type NotifyServer interface {SendNetInfoBySocket(netList []model2.IOCountersStat)SendCPUInfoBySocket(cpu map[string]interface{})SendMemInfoBySocket(mem map[string]interface{})- SendUSBInfoBySocket(list []model2.DriveUSB)- SendDiskInfoBySocket(disk model2.Summary)SendFileOperateNotify(nowSend bool)SendInstallAppBySocket(app notify.Application)- SendAllHardwareStatusBySocket(disk model2.Summary, list []model2.DriveUSB, mem map[string]interface{}, cpu map[string]interface{}, netList []model2.IOCountersStat)+ SendAllHardwareStatusBySocket(mem map[string]interface{}, cpu map[string]interface{}, netList []model2.IOCountersStat)SendStorageBySocket(message notify.StorageMessage)SendNotify(path string, message map[string]interface{})SettingSystemTempData(message map[string]interface{})@@ -81,7 +79,7 @@ func (i *notifyServer) SendStorageBySocket(message notify.StorageMessage) {NotifyMsg <- notify}-func (i *notifyServer) SendAllHardwareStatusBySocket(disk model2.Summary, list []model2.DriveUSB, mem map[string]interface{}, cpu map[string]interface{}, netList []model2.IOCountersStat) {+func (i *notifyServer) SendAllHardwareStatusBySocket(mem map[string]interface{}, cpu map[string]interface{}, netList []model2.IOCountersStat) {body := make(map[string]interface{})@@ -263,38 +261,6 @@ func (i *notifyServer) SendFileOperateNotify(nowSend bool) {}-func (i *notifyServer) SendDiskInfoBySocket(disk model2.Summary) {- body := make(map[string]interface{})- body["data"] = disk-- msg := gosf.Message{}- msg.Body = body- msg.Success = true- msg.Text = "sys_disk"-- notify := notify.Message{}- notify.Path = "sys_disk"- notify.Msg = msg-- NotifyMsg <- notify-}--func (i *notifyServer) SendUSBInfoBySocket(list []model2.DriveUSB) {- body := make(map[string]interface{})- body["data"] = list-- msg := gosf.Message{}- msg.Body = body- msg.Success = true- msg.Text = "sys_usb"-- notify := notify.Message{}- notify.Path = "sys_usb"- notify.Msg = msg-- NotifyMsg <- notify-}-func (i *notifyServer) SendMemInfoBySocket(mem map[string]interface{}) {body := make(map[string]interface{})body["data"] = memdiff --git a/service/service.go b/service/service.goindex 16594b9..e2164c0 100644--- a/service/service.go+++ b/service/service.go@@ -30,7 +30,6 @@ type Repository interface {//User() UserServiceDocker() DockerServiceCasa() CasaService- Disk() DiskServiceNotify() NotifyServerRely() RelyServiceSystem() SystemService@@ -51,7 +50,6 @@ func NewService(db *gorm.DB, RuntimePath string) Repository {app: NewAppService(db),docker: NewDockerService(),casa: NewCasaService(),- disk: NewDiskService(db),notify: NewNotifyService(db),rely: NewRelyService(db),system: NewSystemService(),@@ -65,7 +63,6 @@ type store struct {app AppServicedocker DockerServicecasa CasaService- disk DiskServicenotify NotifyServerrely RelyServicesystem SystemService@@ -107,7 +104,3 @@ func (c *store) Docker() DockerService {func (c *store) Casa() CasaService {return c.casa}--func (c *store) Disk() DiskService {- return c.disk-}