goc/pkg/server/server.go

93 lines
2.2 KiB
Go
Raw Normal View History

2021-09-02 09:48:11 +00:00
/*
Copyright 2021 Qiniu Cloud (qiniu.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
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:33:49 +00:00
watchCh: make(chan []byte, 4096),
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
}