goc/pkg/server/server.go

80 lines
1.6 KiB
Go
Raw Normal View History

2021-06-10 12:03:47 +00:00
package server
import (
2021-06-24 07:22:24 +00:00
"net/http"
2021-06-10 12:03:47 +00:00
"net/rpc"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
// gocServer represents a goc server
type gocServer struct {
port int
storePath string
upgrader websocket.Upgrader
2021-06-24 07:22:24 +00:00
rpcAgents sync.Map
watchAgents sync.Map
watchCh chan []byte
watchClients sync.Map
2021-06-10 12:03:47 +00:00
}
type gocCliendId string
2021-06-19 08:17:29 +00:00
// gocCoveredAgent represents a covered client
type gocCoveredAgent struct {
2021-06-10 12:03:47 +00:00
Id string `json:"id"`
RemoteIP string `json:"remoteip"`
Hostname string `json:"hostname"`
CmdLine string `json:"cmdline"`
Pid string `json:"pid"`
rpc *rpc.Client `json:"-"`
2021-06-19 08:17:29 +00:00
exitCh chan int `json:"-"`
once sync.Once `json:"-"` // 保护 close(exitCh) 只执行一次
2021-06-10 12:03:47 +00:00
}
2021-06-24 07:22:24 +00:00
// api 客户端,不是 agent
type gocWatchClient struct {
ws *websocket.Conn
exitCh chan int
once sync.Once
}
2021-06-20 13:15:51 +00:00
func RunGocServerUntilExit(host string) {
2021-06-10 12:03:47 +00:00
gs := gocServer{
storePath: "",
upgrader: websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
HandshakeTimeout: 45 * time.Second,
2021-06-24 07:22:24 +00:00
CheckOrigin: func(r *http.Request) bool {
return true
},
2021-06-10 12:03:47 +00:00
},
2021-06-24 07:22:24 +00:00
watchCh: make(chan []byte),
2021-06-10 12:03:47 +00:00
}
r := gin.Default()
v2 := r.Group("/v2")
{
2021-06-17 11:53:00 +00:00
v2.GET("/cover/profile", gs.getProfiles)
2021-06-19 08:17:29 +00:00
v2.DELETE("/cover/profile", gs.resetProfiles)
2021-06-24 07:22:24 +00:00
v2.GET("/rpcagents", gs.listAgents)
v2.GET("/watchagents", nil)
2021-06-10 12:03:47 +00:00
2021-06-24 07:22:24 +00:00
v2.GET("/cover/ws/watch", gs.watchProfileUpdate)
2021-06-10 12:03:47 +00:00
// internal use only
v2.GET("/internal/ws/rpcstream", gs.serveRpcStream)
2021-06-24 07:22:24 +00:00
v2.GET("/internal/ws/watchstream", gs.serveWatchInternalStream)
2021-06-10 12:03:47 +00:00
}
2021-06-24 07:22:24 +00:00
go gs.watchLoop()
2021-06-20 13:15:51 +00:00
r.Run(host)
2021-06-10 12:03:47 +00:00
}