Skip to content

Commit

Permalink
Socketio modification (IceWhaleTech#771)
Browse files Browse the repository at this point in the history
  • Loading branch information
LinkLeong authored Dec 20, 2022
1 parent c6d89f9 commit cd79e51
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 237 deletions.
2 changes: 1 addition & 1 deletion cmd/migration-tool/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func init() {
sqliteDB = sqlite.GetDb(dbFlag)
// gredis.GetRedisConn(config.RedisInfo),

service.MyService = service.NewService(sqliteDB, "")
service.MyService = service.NewService(sqliteDB, "", nil)
}

func main() {
Expand Down
12 changes: 7 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/IceWhaleTech/CasaOS-Common/model"
"github.com/IceWhaleTech/CasaOS-Common/utils/constants"
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/IceWhaleTech/CasaOS/model/notify"
"github.com/IceWhaleTech/CasaOS/pkg/cache"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/sqlite"
Expand All @@ -21,6 +20,7 @@ import (
"github.com/IceWhaleTech/CasaOS/service"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/coreos/go-systemd/daemon"
"github.com/gin-gonic/gin"
"go.uber.org/zap"

"github.com/robfig/cron"
Expand Down Expand Up @@ -53,7 +53,7 @@ func init() {
sqliteDB = sqlite.GetDb(*dbFlag)
// gredis.GetRedisConn(config.RedisInfo),

service.MyService = service.NewService(sqliteDB, config.CommonInfo.RuntimePath)
service.MyService = service.NewService(sqliteDB, config.CommonInfo.RuntimePath, route.SocketIo())

service.Cache = cache.Init()

Expand All @@ -74,15 +74,17 @@ func init() {
// @name Authorization
// @BasePath /v1
func main() {
service.NotifyMsg = make(chan notify.Message, 10)
if *versionFlag {
return
}
go route.SocketInit(service.NotifyMsg)
// model.Setup()
// gredis.Setup()

r := route.InitRouter()
defer service.SocketServer.Close()
r.GET("/v1/socketio/*any", gin.WrapH(service.SocketServer))
r.POST("/v1/socketio/*any", gin.WrapH(service.SocketServer))

// service.SyncTask(sqliteDB)
cron2 := cron.New()
// every day execution
Expand All @@ -108,7 +110,7 @@ func main() {
if err != nil {
panic(err)
}
routers := []string{"sys", "port", "file", "folder", "batch", "image", "samba", "notify"}
routers := []string{"sys", "port", "file", "folder", "batch", "image", "samba", "notify", "socketio"}
for _, v := range routers {
err = service.MyService.Gateway().CreateRoute(&model.Route{
Path: "/v1/" + v,
Expand Down
44 changes: 12 additions & 32 deletions route/periodical.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,37 +22,6 @@ import (
"github.com/IceWhaleTech/CasaOS/service"
)

func SendNetINfoBySocket() {
netList := service.MyService.System().GetNetInfo()
newNet := []model.IOCountersStat{}
nets := service.MyService.System().GetNet(true)
for _, n := range netList {
for _, netCardName := range nets {
if n.Name == netCardName {
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
item.State = strings.TrimSpace(service.MyService.System().GetNetState(n.Name))
item.Time = time.Now().Unix()
newNet = append(newNet, item)
break
}
}
}
service.MyService.Notify().SendNetInfoBySocket(newNet)
}

func SendCPUBySocket() {
cpu := service.MyService.System().GetCpuPercent()
num := service.MyService.System().GetCpuCoreNum()
cpuData := make(map[string]interface{})
cpuData["percent"] = cpu
cpuData["num"] = num
service.MyService.Notify().SendCPUInfoBySocket(cpuData)
}

func SendMemBySocket() {
service.MyService.Notify().SendMemInfoBySocket(service.MyService.System().GetMemInfo())
}

func SendAllHardwareStatusBySocket() {
netList := service.MyService.System().GetNetInfo()
newNet := []model.IOCountersStat{}
Expand Down Expand Up @@ -89,7 +58,18 @@ func SendAllHardwareStatusBySocket() {

memInfo := service.MyService.System().GetMemInfo()

service.MyService.Notify().SendAllHardwareStatusBySocket(memInfo, cpuData, newNet)
body := make(map[string]interface{})

body["sys_mem"] = memInfo

body["sys_cpu"] = cpuData

body["sys_net"] = newNet
systemTempMap := service.MyService.Notify().GetSystemTempMap()
for k, v := range systemTempMap {
body[k] = v
}
service.MyService.Notify().SendNotify("sys_hardware_status", body)
}

// func MonitoryUSB() {
Expand Down
1 change: 1 addition & 0 deletions route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func InitRouter() *gin.Engine {
v1FolderGroup.PUT("/name", v1.RenamePath)
v1FolderGroup.GET("", v1.DirPath) ///file/dirpath
v1FolderGroup.POST("", v1.MkdirAll) ///file/mkdir
v1FolderGroup.GET("/size", v1.GetSize)
}
v1BatchGroup := v1Group.Group("/batch")
v1BatchGroup.Use()
Expand Down
76 changes: 40 additions & 36 deletions route/socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,48 +11,52 @@
package route

import (
"strconv"
"time"

"github.com/IceWhaleTech/CasaOS-Common/utils/port"
"github.com/IceWhaleTech/CasaOS/model/notify"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/IceWhaleTech/CasaOS/service"
f "github.com/ambelovsky/gosf"
socketio "github.com/googollee/go-socket.io"
"go.uber.org/zap"
)

func SocketInit(msg chan notify.Message) {
// set socket port
socketPort := 0
if len(config.ServerInfo.SocketPort) == 0 {
socketPort, _ = port.GetAvailablePort("tcp")
config.ServerInfo.SocketPort = strconv.Itoa(socketPort)
config.Cfg.Section("server").Key("SocketPort").SetValue(strconv.Itoa(socketPort))
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
} else {
socketPort, _ = strconv.Atoi(config.ServerInfo.SocketPort)
if !port.IsPortAvailable(socketPort, "tcp") {
socketPort, _ := port.GetAvailablePort("tcp")
config.ServerInfo.SocketPort = strconv.Itoa(socketPort)
config.Cfg.Section("server").Key("SocketPort").SetValue(strconv.Itoa(socketPort))
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
}

f.OnConnect(func(c *f.Client, request *f.Request) {
func SocketIo() *socketio.Server {
server := socketio.NewServer(nil)
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
logger.Info("connected", zap.Any("id", s.ID()))
s.Join("public")
service.ClientCount += 1
return nil
})
f.OnDisconnect(func(c *f.Client, request *f.Request) {
service.ClientCount -= 1

server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
logger.Info("notice", zap.Any("msg", msg))
s.Emit("reply", "have "+msg)
})
go func(msg chan notify.Message) {
for v := range msg {
f.Broadcast("", v.Path, &v.Msg)
time.Sleep(time.Millisecond * 100)
}
}(msg)

f.Startup(map[string]interface{}{
"port": socketPort,
// server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
// s.SetContext(msg)
// return "recv " + msg
// })

// server.OnEvent("/", "bye", func(s socketio.Conn) string {
// last := s.Context().(string)
// s.Emit("bye", last)
// s.Close()
// return last
// })

server.OnError("/", func(s socketio.Conn, e error) {
logger.Error("meet error", zap.Any("error", e))
})

server.OnDisconnect("/", func(s socketio.Conn, reason string) {
service.ClientCount -= 1
logger.Info("closed", zap.Any("reason", reason))
})

go func() {
if err := server.Serve(); err != nil {
logger.Error("error when trying to listen socketio ", zap.Any("error", err))
}
}()
return server
}
13 changes: 12 additions & 1 deletion route/v1/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ func GetDownloadFile(c *gin.Context) {
func GetDownloadSingleFile(c *gin.Context) {
filePath := c.Query("path")
if len(filePath) == 0 {
c.JSON(service.ClientCount, model.Result{
c.JSON(common_err.CLIENT_ERROR, model.Result{
Success: common_err.INVALID_PARAMS,
Message: common_err.GetMsg(common_err.INVALID_PARAMS),
})
Expand Down Expand Up @@ -649,3 +649,14 @@ func DeleteOperateFileOrDir(c *gin.Context) {
go service.MyService.Notify().SendFileOperateNotify(true)
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
func GetSize(c *gin.Context) {
json := make(map[string]string)
c.ShouldBind(&json)
path := json["path"]
size, err := file.GetFileOrDirSize(path)
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
}
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: size})
}
5 changes: 2 additions & 3 deletions route/v1/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,10 @@ func GetSystemProxy(c *gin.Context) {

func PutSystemState(c *gin.Context) {
state := c.Param("state")
if state == "off" {
if strings.ToLower(state) == "off" {
service.MyService.System().SystemShutdown()
} else if state == "restart" {
} else if strings.ToLower(state) == "restart" {
service.MyService.System().SystemReboot()

}
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: "The operation will be completed shortly."})
}
Expand Down
Loading

0 comments on commit cd79e51

Please sign in to comment.