Update back to service format

This commit is contained in:
link 2023-03-17 07:00:50 +00:00
parent 26c7cb8e63
commit 62bf650544
7 changed files with 265 additions and 363 deletions

View File

@ -1,67 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-24 17:36:00
* @LastEditors: LinkLeong
* @LastEditTime: 2022-09-05 11:24:27
* @FilePath: /CasaOS/cmd/migration-tool/migration-034-035.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package main
import (
"os"
interfaces "github.com/IceWhaleTech/CasaOS-Common"
"github.com/IceWhaleTech/CasaOS-Common/utils/version"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
)
type migrationTool struct{}
func (u *migrationTool) IsMigrationNeeded() (bool, error) {
majorVersion, minorVersion, patchVersion, err := version.DetectLegacyVersion()
if err != nil {
if err == version.ErrLegacyVersionNotFound {
return false, nil
}
return false, err
}
if majorVersion > 0 {
return false, nil
}
if minorVersion > 4 {
return false, nil
}
if minorVersion == 4 && patchVersion != 2 {
return false, nil
}
_logger.Info("Migration is needed for a CasaOS version 0.4.2 ")
return true, nil
}
func (u *migrationTool) PreMigrate() error {
return nil
}
func (u *migrationTool) Migrate() error {
_logger.Info("Migration is started for a CasaOS version 0.4.2 ")
command.OnlyExec("systemctl stop rclone.service")
os.Remove("/usr/lib/systemd/system/rclone.service")
command.OnlyExec("systemctl daemon-reload")
return nil
}
func (u *migrationTool) PostMigrate() error {
return nil
}
func NewMigrationDummy() interfaces.MigrationTool {
return &migrationTool{}
}

View File

@ -0,0 +1,27 @@
package main
import (
interfaces "github.com/IceWhaleTech/CasaOS-Common"
)
type migrationTool struct{}
func (u *migrationTool) IsMigrationNeeded() (bool, error) {
return false, nil
}
func (u *migrationTool) PreMigrate() error {
return nil
}
func (u *migrationTool) Migrate() error {
return nil
}
func (u *migrationTool) PostMigrate() error {
return nil
}
func NewMigrationDummy() interfaces.MigrationTool {
return &migrationTool{}
}

11
main.go
View File

@ -81,10 +81,10 @@ func init() {
route.InitFunction() route.InitFunction()
///// ///
// service.MountLists = make(map[string]*mountlib.MountPoint) // service.MountLists = make(map[string]*mountlib.MountPoint)
// configfile.Install() // configfile.Install()
// service.MyService.Storage().CheckAndMountAll() service.MyService.Storage().CheckAndMountAll()
} }
// @title casaOS API // @title casaOS API
@ -146,9 +146,9 @@ func main() {
"/v1/image", "/v1/image",
"/v1/samba", "/v1/samba",
"/v1/notify", "/v1/notify",
// "/v1/driver", "/v1/driver",
// "/v1/cloud", "/v1/cloud",
// "/v1/recover", "/v1/recover",
"/v1/other", "/v1/other",
route.V2APIPath, route.V2APIPath,
route.V2DocPath, route.V2DocPath,
@ -167,6 +167,7 @@ func main() {
} }
var events []message_bus.EventType var events []message_bus.EventType
events = append(events, message_bus.EventType{Name: "casaos:system:utilization", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}}) events = append(events, message_bus.EventType{Name: "casaos:system:utilization", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}})
events = append(events, message_bus.EventType{Name: "casaos:file:recover", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}})
events = append(events, message_bus.EventType{Name: "casaos:file:operate", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}}) events = append(events, message_bus.EventType{Name: "casaos:file:operate", SourceID: common.SERVICENAME, PropertyTypeList: []message_bus.PropertyType{}})
// register at message bus // register at message bus
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {

View File

@ -1,7 +1,15 @@
package httper package httper
import ( import (
"encoding/json"
"fmt"
"net"
"net/http"
"time" "time"
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/go-resty/resty/v2"
"go.uber.org/zap"
) )
type MountList struct { type MountList struct {
@ -36,126 +44,127 @@ type RemotesResult struct {
var UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" var UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
var DefaultTimeout = time.Second * 30 var DefaultTimeout = time.Second * 30
// func NewRestyClient() *resty.Client { func NewRestyClient() *resty.Client {
// unixSocket := "/var/run/rclone/rclone.sock" unixSocket := "/var/run/rclone/rclone.sock"
// transport := http.Transport{ transport := http.Transport{
// Dial: func(_, _ string) (net.Conn, error) { Dial: func(_, _ string) (net.Conn, error) {
// return net.Dial("unix", unixSocket) return net.Dial("unix", unixSocket)
// }, },
// } }
// client := resty.New() client := resty.New()
// client.SetTransport(&transport).SetBaseURL("http://localhost") client.SetTransport(&transport).SetBaseURL("http://localhost")
// client.SetRetryCount(3).SetRetryWaitTime(5*time.Second).SetTimeout(DefaultTimeout).SetHeader("User-Agent", UserAgent) client.SetRetryCount(3).SetRetryWaitTime(5*time.Second).SetTimeout(DefaultTimeout).SetHeader("User-Agent", UserAgent)
// return client return client
// } }
// func GetMountList() (MountList, error) { func GetMountList() (MountList, error) {
// var result MountList var result MountList
// res, err := NewRestyClient().R().Post("/mount/listmounts") res, err := NewRestyClient().R().Post("/mount/listmounts")
// if err != nil { if err != nil {
// return result, err return result, err
// } }
// if res.StatusCode() != 200 { if res.StatusCode() != 200 {
// return result, fmt.Errorf("get mount list failed") return result, fmt.Errorf("get mount list failed")
// } }
// json.Unmarshal(res.Body(), &result) json.Unmarshal(res.Body(), &result)
// for i := 0; i < len(result.MountPoints); i++ { for i := 0; i < len(result.MountPoints); i++ {
// result.MountPoints[i].Fs = result.MountPoints[i].Fs[:len(result.MountPoints[i].Fs)-1] result.MountPoints[i].Fs = result.MountPoints[i].Fs[:len(result.MountPoints[i].Fs)-1]
// } }
// return result, err return result, err
// } }
//
// func Mount(mountPoint string, fs string) error {
// res, err := NewRestyClient().R().SetFormData(map[string]string{
// "mountPoint": mountPoint,
// "fs": fs,
// "mountOpt": `{"AllowOther": true}`,
// }).Post("/mount/mount")
// if err != nil {
// return err
// }
// if res.StatusCode() != 200 {
// return fmt.Errorf("mount failed")
// }
// logger.Info("mount then", zap.Any("res", res.Body()))
// return nil
// }
// func Unmount(mountPoint string) error {
// res, err := NewRestyClient().R().SetFormData(map[string]string{
// "mountPoint": mountPoint,
// }).Post("/mount/unmount")
// if err != nil {
// logger.Error("when unmount", zap.Error(err))
// return err
// }
// if res.StatusCode() != 200 {
// logger.Error("then unmount failed", zap.Any("res", res.Body()))
// return fmt.Errorf("unmount failed")
// }
// logger.Info("unmount then", zap.Any("res", res.Body()))
// return nil
// }
// func CreateConfig(data map[string]string, name, t string) error { func Mount(mountPoint string, fs string) error {
// data["config_is_local"] = "false" res, err := NewRestyClient().R().SetFormData(map[string]string{
// dataStr, _ := json.Marshal(data) "mountPoint": mountPoint,
// res, err := NewRestyClient().R().SetFormData(map[string]string{ "fs": fs,
// "name": name, "mountOpt": `{"AllowOther": true}`,
// "parameters": string(dataStr), }).Post("/mount/mount")
// "type": t, if err != nil {
// }).Post("/config/create") return err
// logger.Info("when create config then", zap.Any("res", res.Body())) }
// if err != nil { if res.StatusCode() != 200 {
// return err return fmt.Errorf("mount failed")
// } }
// if res.StatusCode() != 200 { logger.Info("mount then", zap.Any("res", res.Body()))
// return fmt.Errorf("create config failed") return nil
// } }
func Unmount(mountPoint string) error {
res, err := NewRestyClient().R().SetFormData(map[string]string{
"mountPoint": mountPoint,
}).Post("/mount/unmount")
if err != nil {
logger.Error("when unmount", zap.Error(err))
return err
}
if res.StatusCode() != 200 {
logger.Error("then unmount failed", zap.Any("res", res.Body()))
return fmt.Errorf("unmount failed")
}
// return nil logger.Info("unmount then", zap.Any("res", res.Body()))
// } return nil
}
// func GetConfigByName(name string) (map[string]string, error) { func CreateConfig(data map[string]string, name, t string) error {
data["config_is_local"] = "false"
dataStr, _ := json.Marshal(data)
res, err := NewRestyClient().R().SetFormData(map[string]string{
"name": name,
"parameters": string(dataStr),
"type": t,
}).Post("/config/create")
logger.Info("when create config then", zap.Any("res", res.Body()))
if err != nil {
return err
}
if res.StatusCode() != 200 {
return fmt.Errorf("create config failed")
}
// res, err := NewRestyClient().R().SetFormData(map[string]string{ return nil
// "name": name, }
// }).Post("/config/get")
// if err != nil {
// return nil, err
// }
// if res.StatusCode() != 200 {
// return nil, fmt.Errorf("create config failed")
// }
// var result map[string]string
// json.Unmarshal(res.Body(), &result)
// return result, nil
// }
// func GetAllConfigName() (RemotesResult, error) {
// var result RemotesResult
// res, err := NewRestyClient().R().SetFormData(map[string]string{}).Post("/config/listremotes")
// if err != nil {
// return result, err
// }
// if res.StatusCode() != 200 {
// return result, fmt.Errorf("get config failed")
// }
// json.Unmarshal(res.Body(), &result) func GetConfigByName(name string) (map[string]string, error) {
// return result, nil
// } res, err := NewRestyClient().R().SetFormData(map[string]string{
// func DeleteConfigByName(name string) error { "name": name,
// res, err := NewRestyClient().R().SetFormData(map[string]string{ }).Post("/config/get")
// "name": name, if err != nil {
// }).Post("/config/delete") return nil, err
// if err != nil { }
// return err if res.StatusCode() != 200 {
// } return nil, fmt.Errorf("create config failed")
// if res.StatusCode() != 200 { }
// return fmt.Errorf("delete config failed") var result map[string]string
// } json.Unmarshal(res.Body(), &result)
// return nil return result, nil
// } }
func GetAllConfigName() (RemotesResult, error) {
var result RemotesResult
res, err := NewRestyClient().R().SetFormData(map[string]string{}).Post("/config/listremotes")
if err != nil {
return result, err
}
if res.StatusCode() != 200 {
return result, fmt.Errorf("get config failed")
}
json.Unmarshal(res.Body(), &result)
return result, nil
}
func DeleteConfigByName(name string) error {
res, err := NewRestyClient().R().SetFormData(map[string]string{
"name": name,
}).Post("/config/delete")
if err != nil {
return err
}
if res.StatusCode() != 200 {
return fmt.Errorf("delete config failed")
}
return nil
}

View File

@ -1,16 +1,17 @@
package v1 package v1
import ( import (
"os"
"strings" "strings"
"github.com/IceWhaleTech/CasaOS-Common/model" "github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/IceWhaleTech/CasaOS-Common/utils/common_err"
"github.com/IceWhaleTech/CasaOS/drivers/dropbox" "github.com/IceWhaleTech/CasaOS/drivers/dropbox"
"github.com/IceWhaleTech/CasaOS/drivers/google_drive" "github.com/IceWhaleTech/CasaOS/drivers/google_drive"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
"github.com/IceWhaleTech/CasaOS/pkg/utils/httper" "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap"
) )
func ListStorages(c *gin.Context) { func ListStorages(c *gin.Context) {
@ -39,14 +40,18 @@ func ListStorages(c *gin.Context) {
} }
for i := 0; i < len(r.MountPoints); i++ { for i := 0; i < len(r.MountPoints); i++ {
t := service.MyService.Storage().GetAttributeValueByName(r.MountPoints[i].Fs, "type") dataMap, err := service.MyService.Storage().GetConfigByName(r.MountPoints[i].Fs)
if t == "drive" { if err != nil {
logger.Error("GetConfigByName", zap.Any("err", err))
continue
}
if dataMap["type"] == "drive" {
r.MountPoints[i].Icon = google_drive.ICONURL r.MountPoints[i].Icon = google_drive.ICONURL
} }
if t == "dropbox" { if dataMap["type"] == "dropbox" {
r.MountPoints[i].Icon = dropbox.ICONURL r.MountPoints[i].Icon = dropbox.ICONURL
} }
r.MountPoints[i].Name = service.MyService.Storage().GetAttributeValueByName(r.MountPoints[i].Fs, "username") r.MountPoints[i].Name = dataMap["username"]
} }
list := []httper.MountPoint{} list := []httper.MountPoint{}
@ -76,8 +81,21 @@ func UmountStorage(c *gin.Context) {
return return
} }
service.MyService.Storage().DeleteConfigByName(strings.ReplaceAll(mountPoint, "/mnt/", "")) service.MyService.Storage().DeleteConfigByName(strings.ReplaceAll(mountPoint, "/mnt/", ""))
if fs, err := os.ReadDir(mountPoint); err == nil && len(fs) == 0 {
os.RemoveAll(mountPoint)
}
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: "success"}) c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: "success"})
} }
func GetStorage(c *gin.Context) {
// idStr := c.Query("id")
// id, err := strconv.Atoi(idStr)
// if err != nil {
// c.JSON(common_err.SUCCESS, model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.CLIENT_ERROR), Data: err.Error()})
// return
// }
// storage, err := service.MyService.Storage().GetStorageById(uint(id))
// if err != nil {
// c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
// return
// }
// c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: storage})
}

View File

@ -56,7 +56,7 @@ func GetRecoverStorage(c *gin.Context) {
service.MyService.Notify().SendNotify("casaos:file:recover", notify) service.MyService.Notify().SendNotify("casaos:file:recover", notify)
return return
} }
dmap := make(map[string]interface{}) dmap := make(map[string]string)
dmap["username"] = username dmap["username"] = username
configs, err := service.MyService.Storage().GetConfig() configs, err := service.MyService.Storage().GetConfig()
if err != nil { if err != nil {
@ -68,17 +68,16 @@ func GetRecoverStorage(c *gin.Context) {
return return
} }
for _, v := range configs.Remotes { for _, v := range configs.Remotes {
t := service.MyService.Storage().GetAttributeValueByName(v, "type") cf, err := service.MyService.Storage().GetConfigByName(v)
username := service.MyService.Storage().GetAttributeValueByName(v, "username")
if err != nil { if err != nil {
logger.Error("then get config by name error: ", zap.Error(err), zap.Any("name", v)) logger.Error("then get config by name error: ", zap.Error(err), zap.Any("name", v))
continue continue
} }
if t == "drive" && username == dmap["username"] { if cf["type"] == "drive" && cf["username"] == dmap["username"] {
c.String(200, `<p>The same configuration has been added</p><script>window.close()</script>`) c.String(200, `<p>The same configuration has been added</p><script>window.close()</script>`)
err := service.MyService.Storage().CheckAndMountByName(v) err := service.MyService.Storage().CheckAndMountByName(v)
if err != nil { if err != nil {
logger.Error("check and mount by name error: ", zap.Error(err), zap.Any("name", username)) logger.Error("check and mount by name error: ", zap.Error(err), zap.Any("name", cf["username"]))
} }
notify["status"] = "warn" notify["status"] = "warn"
notify["message"] = "The same configuration has been added" notify["message"] = "The same configuration has been added"
@ -100,10 +99,11 @@ func GetRecoverStorage(c *gin.Context) {
dmap["mount_point"] = "/mnt/" + username dmap["mount_point"] = "/mnt/" + username
dmap["token"] = `{"access_token":"` + google_drive.AccessToken + `","token_type":"Bearer","refresh_token":"` + google_drive.RefreshToken + `","expiry":"` + currentDate + `T` + currentTime.Add(time.Hour*1).Add(time.Minute*50).Format("15:04:05") + `Z"}` dmap["token"] = `{"access_token":"` + google_drive.AccessToken + `","token_type":"Bearer","refresh_token":"` + google_drive.RefreshToken + `","expiry":"` + currentDate + `T` + currentTime.Add(time.Hour*1).Add(time.Minute*50).Format("15:04:05") + `Z"}`
service.MyService.Storage().CreateConfig(dmap, username, "drive") service.MyService.Storage().CreateConfig(dmap, username, "drive")
service.MyService.Storage().MountStorage("/mnt/"+username, username) service.MyService.Storage().MountStorage("/mnt/"+username, username+":")
notify := make(map[string]interface{}) notify := make(map[string]interface{})
notify["status"] = "success" notify["status"] = "success"
notify["message"] = "Success" notify["message"] = "Success"
notify["driver"] = "GoogleDrive"
service.MyService.Notify().SendNotify("casaos:file:recover", notify) service.MyService.Notify().SendNotify("casaos:file:recover", notify)
} else if t == "Dropbox" { } else if t == "Dropbox" {
add := dropbox.Addition{} add := dropbox.Addition{}
@ -139,7 +139,7 @@ func GetRecoverStorage(c *gin.Context) {
service.MyService.Notify().SendNotify("casaos:file:recover", notify) service.MyService.Notify().SendNotify("casaos:file:recover", notify)
return return
} }
dmap := make(map[string]interface{}) dmap := make(map[string]string)
dmap["username"] = username dmap["username"] = username
configs, err := service.MyService.Storage().GetConfig() configs, err := service.MyService.Storage().GetConfig()
@ -152,18 +152,16 @@ func GetRecoverStorage(c *gin.Context) {
return return
} }
for _, v := range configs.Remotes { for _, v := range configs.Remotes {
cf, err := service.MyService.Storage().GetConfigByName(v)
t := service.MyService.Storage().GetAttributeValueByName(v, "type")
username := service.MyService.Storage().GetAttributeValueByName(v, "username")
if err != nil { if err != nil {
logger.Error("then get config by name error: ", zap.Error(err), zap.Any("name", v)) logger.Error("then get config by name error: ", zap.Error(err), zap.Any("name", v))
continue continue
} }
if t == "dropbox" && username == dmap["username"] { if cf["type"] == "dropbox" && cf["username"] == dmap["username"] {
c.String(200, `<p>The same configuration has been added</p><script>window.close()</script>`) c.String(200, `<p>The same configuration has been added</p><script>window.close()</script>`)
err := service.MyService.Storage().CheckAndMountByName(v) err := service.MyService.Storage().CheckAndMountByName(v)
if err != nil { if err != nil {
logger.Error("check and mount by name error: ", zap.Error(err), zap.Any("name", username)) logger.Error("check and mount by name error: ", zap.Error(err), zap.Any("name", cf["username"]))
} }
notify["status"] = "warn" notify["status"] = "warn"
@ -195,12 +193,12 @@ func GetRecoverStorage(c *gin.Context) {
// return // return
// } // }
service.MyService.Storage().CreateConfig(dmap, username, "dropbox") service.MyService.Storage().CreateConfig(dmap, username, "dropbox")
service.MyService.Storage().MountStorage("/mnt/"+username, username) service.MyService.Storage().MountStorage("/mnt/"+username, username+":")
notify["status"] = "success" notify["status"] = "success"
notify["message"] = "Success" notify["message"] = "Success"
notify["driver"] = "Dropbox"
service.MyService.Notify().SendNotify("casaos:file:recover", notify) service.MyService.Notify().SendNotify("casaos:file:recover", notify)
} }
c.String(200, `<p>Just close the page</p><script>window.close()</script>`) c.String(200, `<p>Just close the page</p><script>window.close()</script>`)

View File

@ -1,199 +1,115 @@
package service package service
import ( import (
"context" "io/ioutil"
"errors"
"log"
"os"
"runtime"
"sync"
"time"
"github.com/IceWhaleTech/CasaOS-Common/utils/file"
"github.com/IceWhaleTech/CasaOS-Common/utils/logger" "github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/IceWhaleTech/CasaOS/pkg/mount" "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
"github.com/IceWhaleTech/CasaOS/pkg/utils/httper" "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
_ "github.com/rclone/rclone/backend/all"
"github.com/rclone/rclone/cmd/mountlib"
"github.com/rclone/rclone/fs"
rconfig "github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/vfs/vfscommon"
"go.uber.org/zap" "go.uber.org/zap"
) )
type StorageService interface { type StorageService interface {
MountStorage(mountPoint, fs string) error MountStorage(mountPoint, fs string) error
UnmountStorage(mountPoint string) error UnmountStorage(mountPoint string) error
UnmountAllStorage()
GetStorages() (httper.MountList, error) GetStorages() (httper.MountList, error)
CreateConfig(data rc.Params, name string, t string) error CreateConfig(data map[string]string, name string, t string) error
CheckAndMountByName(name string) error CheckAndMountByName(name string) error
CheckAndMountAll() error CheckAndMountAll() error
GetConfigByName(name string) []string GetConfigByName(name string) (map[string]string, error)
GetAttributeValueByName(name, key string) string DeleteConfigByName(name string) error
DeleteConfigByName(name string)
GetConfig() (httper.RemotesResult, error) GetConfig() (httper.RemotesResult, error)
} }
type storageStruct struct { type storageStruct struct {
} }
var MountLists map[string]*mountlib.MountPoint func (s *storageStruct) MountStorage(mountPoint, fs string) error {
var mountMu sync.Mutex
func (s *storageStruct) MountStorage(mountPoint, deviceName string) error {
file.IsNotExistMkDir(mountPoint) file.IsNotExistMkDir(mountPoint)
mountMu.Lock() return httper.Mount(mountPoint, fs)
defer mountMu.Unlock()
currentFS, err := fs.NewFs(context.TODO(), deviceName+":")
if err != nil {
logger.Error("when CheckAndMountAll then", zap.Error(err))
return err
}
mountOptin := mountlib.Options{
MaxReadAhead: 128 * 1024,
AttrTimeout: 1 * time.Second,
DaemonWait: 60 * time.Second,
NoAppleDouble: true,
NoAppleXattr: false,
AsyncRead: true,
AllowOther: true,
}
vfsOpt := vfscommon.Options{
NoModTime: false,
NoChecksum: false,
NoSeek: false,
DirCacheTime: 5 * 60 * time.Second,
PollInterval: time.Minute,
ReadOnly: false,
Umask: 18,
UID: 0,
GID: 0,
DirPerms: os.FileMode(0777),
FilePerms: os.FileMode(0666),
CacheMode: 3,
CacheMaxAge: 3600 * time.Second,
CachePollInterval: 60 * time.Second,
ChunkSize: 128 * fs.Mebi,
ChunkSizeLimit: -1,
CacheMaxSize: -1,
CaseInsensitive: runtime.GOOS == "windows" || runtime.GOOS == "darwin", // default to true on Windows and Mac, false otherwise
WriteWait: 1000 * time.Millisecond,
ReadWait: 20 * time.Millisecond,
WriteBack: 5 * time.Second,
ReadAhead: 0 * fs.Mebi,
UsedIsSize: false,
DiskSpaceTotalSize: -1,
}
mnt := mountlib.NewMountPoint(mount.MountFn, mountPoint, currentFS, &mountOptin, &vfsOpt)
_, err = mnt.Mount()
if err != nil {
logger.Error("when CheckAndMountAll then", zap.Error(err))
return err
}
go func() {
if err = mnt.Wait(); err != nil {
log.Printf("unmount FAILED: %v", err)
return
}
mountMu.Lock()
defer mountMu.Unlock()
delete(MountLists, mountPoint)
}()
MountLists[mountPoint] = mnt
return nil
} }
func (s *storageStruct) UnmountStorage(mountPoint string) error { func (s *storageStruct) UnmountStorage(mountPoint string) error {
err := httper.Unmount(mountPoint)
if err == nil {
dir, _ := ioutil.ReadDir(mountPoint)
err := MountLists[mountPoint].Unmount() if len(dir) == 0 {
if err != nil { file.RMDir(mountPoint)
logger.Error("when umount then", zap.Error(err))
return err
}
return nil
}
func (s *storageStruct) UnmountAllStorage() {
for _, v := range MountLists {
err := v.Unmount()
if err != nil {
logger.Error("when umount then", zap.Error(err))
} }
return nil
} }
}
func (s *storageStruct) GetStorages() (httper.MountList, error) {
ls := httper.MountList{}
list := []httper.MountPoints{}
for _, v := range MountLists {
list = append(list, httper.MountPoints{
MountPoint: v.MountPoint,
Fs: v.Fs.Name(),
})
}
ls.MountPoints = list
return ls, nil
// return httper.GetMountList()
}
func (s *storageStruct) CreateConfig(data rc.Params, name string, t string) error {
_, err := rconfig.CreateRemote(context.Background(), name, t, data, rconfig.UpdateRemoteOpt{State: "*oauth-islocal,teamdrive,,", NonInteractive: true})
return err return err
} }
func (s *storageStruct) CheckAndMountByName(name string) error { func (s *storageStruct) GetStorages() (httper.MountList, error) {
return httper.GetMountList()
mountPoint, found := rconfig.LoadedData().GetValue(name, "mount_point") }
if !found && len(mountPoint) == 0 { func (s *storageStruct) CreateConfig(data map[string]string, name string, t string) error {
logger.Error("when CheckAndMountAll then mountpint is empty", zap.String("mountPoint", mountPoint), zap.String("fs", name)) httper.CreateConfig(data, name, t)
return errors.New("mountpoint is empty") return nil
} }
return MyService.Storage().MountStorage(mountPoint, name) func (s *storageStruct) CheckAndMountByName(name string) error {
storages, _ := MyService.Storage().GetStorages()
currentRemote, _ := httper.GetConfigByName(name)
mountPoint := currentRemote["mount_point"]
isMount := false
for _, v := range storages.MountPoints {
if v.MountPoint == mountPoint {
isMount = true
break
}
}
if !isMount {
return MyService.Storage().MountStorage(mountPoint, name+":")
}
return nil
} }
func (s *storageStruct) CheckAndMountAll() error { func (s *storageStruct) CheckAndMountAll() error {
section := rconfig.LoadedData().GetSectionList() storages, err := MyService.Storage().GetStorages()
if err != nil {
return err
}
logger.Info("when CheckAndMountAll storages", zap.Any("storages", storages))
section, err := httper.GetAllConfigName()
if err != nil {
return err
}
logger.Info("when CheckAndMountAll section", zap.Any("section", section)) logger.Info("when CheckAndMountAll section", zap.Any("section", section))
for _, v := range section { for _, v := range section.Remotes {
command.OnlyExec("umount /mnt/" + v) currentRemote, _ := httper.GetConfigByName(v)
mountPoint, found := rconfig.LoadedData().GetValue(v, "mount_point") mountPoint := currentRemote["mount_point"]
if len(mountPoint) == 0 {
if !found && len(mountPoint) == 0 {
logger.Info("when CheckAndMountAll then mountpint is empty", zap.String("mountPoint", mountPoint), zap.String("fs", v))
continue continue
} }
err := MyService.Storage().MountStorage(mountPoint, v) isMount := false
if err != nil { for _, v := range storages.MountPoints {
logger.Error("when CheckAndMountAll then", zap.Error(err)) if v.MountPoint == mountPoint {
return err isMount = true
break
}
}
if !isMount {
logger.Info("when CheckAndMountAll MountStorage", zap.String("mountPoint", mountPoint), zap.String("fs", v))
err := MyService.Storage().MountStorage(mountPoint, v+":")
if err != nil {
logger.Error("when CheckAndMountAll then", zap.String("mountPoint", mountPoint), zap.String("fs", v), zap.Error(err))
}
} }
} }
return nil return nil
} }
func (s *storageStruct) GetConfigByName(name string) []string { func (s *storageStruct) GetConfigByName(name string) (map[string]string, error) {
return rconfig.LoadedData().GetKeyList(name) return httper.GetConfigByName(name)
} }
func (s *storageStruct) DeleteConfigByName(name string) error {
func (s *storageStruct) GetAttributeValueByName(name, key string) string { return httper.DeleteConfigByName(name)
value, found := rconfig.LoadedData().GetValue(name, key)
if !found {
return ""
}
return value
}
func (s *storageStruct) DeleteConfigByName(name string) {
rconfig.DeleteRemote(name)
} }
func (s *storageStruct) GetConfig() (httper.RemotesResult, error) { func (s *storageStruct) GetConfig() (httper.RemotesResult, error) {
//TODO: check data section, err := httper.GetAllConfigName()
// section, err := httper.GetAllConfigName() if err != nil {
// if err != nil { return httper.RemotesResult{}, err
// return httper.RemotesResult{}, err }
// } return section, nil
// return section, nil
return httper.RemotesResult{}, nil
} }
func NewStorageService() StorageService { func NewStorageService() StorageService {
return &storageStruct{} return &storageStruct{}