sshd.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package sshd
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. mqtt "github.com/eclipse/paho.mqtt.golang"
  10. "hnyfkj.com.cn/rtu/linux/baseapp"
  11. "hnyfkj.com.cn/rtu/linux/netmgrd"
  12. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  13. "hnyfkj.com.cn/rtu/linux/utils/shell"
  14. "hnyfkj.com.cn/rtu/linux/utils/singletask"
  15. )
  16. const MODULE_NAME = "YFKJ_SSHD"
  17. var (
  18. coupler *MQTTCoupler
  19. )
  20. const (
  21. MqttQos1 byte = 1 //// 消息至少送达一次
  22. FastInterval = 1 * time.Second //// 快速检测时间间隔
  23. SlowInterval = 5 * time.Second //// 慢速检测时间间隔
  24. ExecutorCheckInterval = 2 * time.Second // 执行器回收检测
  25. ExecutorTimeout = 6 * time.Second // 执行器超时时间
  26. )
  27. var (
  28. ErrBrokerAddressEmpty = errors.New("mqtt server address is empty")
  29. ErrIMEINotAvailable = errors.New("device imei is not available")
  30. )
  31. type MQTTCoupler struct {
  32. ctx context.Context
  33. cancel context.CancelFunc
  34. broker, username, password string
  35. client mqtt.Client /// MQTT客户端
  36. isConnected atomic.Bool /// 标记是否已连接MQTT的Broker服务
  37. imei string // 设备唯一标识
  38. subTopic string // 订阅指令主题:/yfkj/device/rpc/imei/cmd
  39. pubTopic string // 发布应答主题:/yfkj/device/rpc/imei/ack
  40. ///////// 本地执行器, 允许多客户端, 同一客户端串行的执行指令
  41. executorMap map[string]*clientExecutor
  42. executorMapMu sync.Mutex
  43. // 注册本地的远程方法, 连接成功后用于让客户端能够主动下发指令
  44. registerRpcMeths *singletask.OnceTask // 注册方法, 单实例
  45. }
  46. type executorState int
  47. const (
  48. execIdle executorState = iota // 空闲状态时, 可安全回收
  49. execRunning // 正在执行时, 不允许回收
  50. execClosing // 表明执行器正在关闭中..
  51. )
  52. type clientExecutor struct {
  53. id string /////////////////// 客户端唯一ID
  54. executor *shell.Executor /////////////////// 本地的执行器
  55. mu sync.Mutex /////////////////// 同ID串行执行
  56. lastPing time.Time /////////////////// 用于超时回收
  57. state executorState /////////////////// 执行器的状态
  58. }
  59. func ModuleInit(mqttBroker, mqttUsername, mqttPassword string) bool {
  60. if mqttBroker == "" {
  61. baseapp.Logger.Errorf("[%s] 初始化远程运维模块失败: %v!!", MODULE_NAME, ErrBrokerAddressEmpty)
  62. return false
  63. }
  64. ctx, cancel := context.WithCancel(context.Background())
  65. coupler = &MQTTCoupler{
  66. ctx: ctx,
  67. cancel: cancel,
  68. broker: mqttBroker,
  69. username: mqttUsername,
  70. password: mqttPassword,
  71. executorMap: make(map[string]*clientExecutor),
  72. registerRpcMeths: &singletask.OnceTask{},
  73. }
  74. if err := coupler.init2(); err != nil {
  75. baseapp.Logger.Errorf("[%s] 初始化远程运维模块失败: %v!!", MODULE_NAME, err)
  76. return false
  77. }
  78. go coupler.startExecutorReaper(ExecutorCheckInterval, ExecutorTimeout)
  79. go coupler.keepOnline()
  80. return true
  81. }
  82. func ModuleExit() {
  83. if coupler != nil {
  84. coupler.cancel()
  85. }
  86. }
  87. func (c *MQTTCoupler) init2() error {
  88. c.imei = netmgrd.GetIMEI()
  89. if c.imei == netmgrd.ErrUnknownModemTypeMsg || c.imei == "" {
  90. return ErrIMEINotAvailable
  91. }
  92. template := "/yfkj/device/rpc/imei"
  93. c.subTopic = strings.ReplaceAll(template+"/cmd", "imei", c.imei)
  94. c.pubTopic = strings.ReplaceAll(template+"/ack", "imei", c.imei)
  95. opts := mqtt.NewClientOptions().
  96. AddBroker(c.broker).
  97. SetUsername(c.username).SetPassword(c.password).
  98. SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
  99. SetKeepAlive(10*time.Second).SetPingTimeout(5*time.Second). // Ping心跳间隔, 超时时间
  100. SetOrderMatters(false). /*离线遗愿消息*/ SetWill(c.pubTopic, string(`{"jsonrpc": "2.0", "method": "logout"}`), MqttQos1, false)
  101. opts.OnConnect = func(client mqtt.Client) {
  102. if !c.isConnected.Swap(true) {
  103. baseapp.Logger.Infof("[%s] MQTT Broker连接成功", MODULE_NAME)
  104. }
  105. }
  106. opts.OnConnectionLost = func(client mqtt.Client, err error) {
  107. if c.isConnected.Swap(false) {
  108. baseapp.Logger.Warnf("[%s] MQTT Broker连接丢失: %v!", MODULE_NAME, err)
  109. }
  110. }
  111. c.client = mqtt.NewClient(opts)
  112. return nil
  113. }
  114. func (c *MQTTCoupler) keepOnline() {
  115. t := time.NewTimer(FastInterval)
  116. defer t.Stop()
  117. for {
  118. select {
  119. case <-c.ctx.Done():
  120. return
  121. case <-t.C:
  122. t.Reset(c.tick())
  123. } // end select
  124. } // end for
  125. }
  126. func (c *MQTTCoupler) tick() time.Duration {
  127. if c.isConnected.Load() {
  128. return FastInterval
  129. }
  130. if err := c.connect(); err != nil {
  131. baseapp.Logger.Errorf("[%s] MQTT Broker连接失败: %v!!", MODULE_NAME, err)
  132. } else { // 注册本地的RPC方法, 供远端调用, 单实例运行
  133. c.registerRpcMeths.Run(c.instRPCMethods, true)
  134. }
  135. return SlowInterval
  136. }
  137. func (c *MQTTCoupler) connect() error {
  138. if c.client.IsConnected() {
  139. return nil
  140. }
  141. token := c.client.Connect()
  142. select {
  143. case <-c.ctx.Done():
  144. return nil
  145. case <-token.Done():
  146. }
  147. return token.Error()
  148. }
  149. func (c *MQTTCoupler) instRPCMethods() {
  150. t := time.NewTicker(time.Second)
  151. defer t.Stop()
  152. for {
  153. if !c.isConnected.Load() || c.ctx.Err() != nil {
  154. return
  155. }
  156. token := c.client.Subscribe(c.subTopic, MqttQos1, c.handleRequests)
  157. select {
  158. case <-c.ctx.Done():
  159. return
  160. case <-token.Done():
  161. }
  162. if token.Error() == nil {
  163. baseapp.Logger.Infof("[%s] 本地RPC方法已注册, 等待远端调用...", MODULE_NAME)
  164. break
  165. }
  166. select {
  167. case <-c.ctx.Done():
  168. return
  169. case <-t.C:
  170. continue
  171. }
  172. }
  173. }
  174. func (c *MQTTCoupler) handleRequests(client mqtt.Client, msg mqtt.Message) {
  175. go c.execOneCmd(msg)
  176. }
  177. func (c *MQTTCoupler) execOneCmd(msg mqtt.Message) {
  178. str := string(msg.Payload())
  179. baseapp.Logger.Infof("[%s] 收到一个RPC请求: %s", MODULE_NAME, str)
  180. var resp *jsonrpc2.Response // 预先定义一个空的应答
  181. var clientID string // 该客户端的|唯一标识|
  182. var ce *clientExecutor // 该客户端的本地执行器
  183. var exists bool // 判断执行器是否已存在
  184. req, err := jsonrpc2.ParseRequest(str)
  185. if err != nil || req.ID == nil /* 不接受通知类型的消息 */ {
  186. resp = jsonrpc2.BuildError(nil, jsonrpc2.ErrParse, "")
  187. goto retp
  188. }
  189. clientID, err = extractClientID(req.Params)
  190. if err != nil {
  191. resp = jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, err.Error())
  192. goto retp
  193. }
  194. c.executorMapMu.Lock()
  195. ce, exists = c.executorMap[clientID]
  196. if !exists {
  197. if len(c.executorMap) >= 3 {
  198. c.executorMapMu.Unlock()
  199. resp = jsonrpc2.BuildError(req, -32000, "connection refused: server has reached maximum client capacity (3/3)")
  200. goto retp
  201. }
  202. ce = &clientExecutor{
  203. id: clientID,
  204. executor: shell.NewExecutor(),
  205. state: execIdle,
  206. }
  207. c.executorMap[clientID] = ce
  208. }
  209. c.executorMapMu.Unlock()
  210. ce.mu.Lock()
  211. ce.lastPing = time.Now()
  212. ce.mu.Unlock()
  213. switch req.Method {
  214. // Call-1: 心跳, 链路检测,"ping-pong"测试
  215. case "executor.ping":
  216. resp = buildResp(req, "pong", nil)
  217. goto retp
  218. // Call-2:在本地shell中执行远程下发的指令
  219. case "executor.exec":
  220. ce.mu.Lock()
  221. params, err := extractShellExecuteParams(req.Params)
  222. if err != nil {
  223. ce.mu.Unlock()
  224. resp = jsonrpc2.BuildError(req, jsonrpc2.ErrParse, err.Error())
  225. goto retp
  226. }
  227. if ce.state == execClosing {
  228. ce.mu.Unlock()
  229. resp = jsonrpc2.BuildError(req, -32001, "executor closed")
  230. goto retp
  231. }
  232. if ce.state == execRunning {
  233. ce.mu.Unlock()
  234. resp = jsonrpc2.BuildError(req, -32002, "executor busy")
  235. goto retp
  236. }
  237. ce.state = execRunning
  238. ce.mu.Unlock()
  239. result, err := ce.executor.Exec(params) // 本地执行用户指令
  240. ce.mu.Lock()
  241. if ce.state != execClosing {
  242. ce.state = execIdle
  243. ce.lastPing = time.Now()
  244. }
  245. ce.mu.Unlock()
  246. resp = buildResp(req, result, err)
  247. goto retp
  248. // Call-3:中断本地shell的执行,等价Ctrl+C
  249. case "executor.interrupt":
  250. ce.mu.Lock()
  251. running := (ce.state == execRunning)
  252. ce.mu.Unlock()
  253. if !running {
  254. resp = jsonrpc2.BuildError(req, -32003, "no running command")
  255. goto retp
  256. }
  257. err := ce.executor.Interrupt()
  258. resp = buildResp(req, "interrupted", err)
  259. goto retp
  260. // Call-4:客户端安全退出, 释放本地的执行器
  261. case "executor.close":
  262. err := ce.handleClose()
  263. c.executorMapMu.Lock()
  264. delete(c.executorMap, clientID)
  265. c.executorMapMu.Unlock()
  266. resp = buildResp(req, "closed", err)
  267. goto retp
  268. // Call-?:无效, 远端调用了还不支持的-方法
  269. default:
  270. resp = jsonrpc2.BuildError(req, jsonrpc2.ErrMethodNotFound, "")
  271. goto retp
  272. }
  273. retp:
  274. text, err := resp.String()
  275. if err != nil {
  276. baseapp.Logger.Errorf("[%s] 转换RPC应答失败: %v!!", MODULE_NAME, err)
  277. return
  278. }
  279. token := c.client.Publish(c.pubTopic, MqttQos1, false, text)
  280. select {
  281. case <-c.ctx.Done():
  282. return
  283. case <-token.Done():
  284. }
  285. if err := token.Error(); err != nil {
  286. baseapp.Logger.Errorf("[%s] 发送RPC应答失败: %v!!", MODULE_NAME, err)
  287. }
  288. baseapp.Logger.Infof("[%s] 发送一个RPC应答, 报文内容: %s", MODULE_NAME, text)
  289. }
  290. func (c *MQTTCoupler) startExecutorReaper(interval, timeout time.Duration) {
  291. ticker := time.NewTicker(interval)
  292. defer ticker.Stop()
  293. for {
  294. select {
  295. case <-c.ctx.Done():
  296. return
  297. case <-ticker.C:
  298. c.executorMapMu.Lock()
  299. for id, ce := range c.executorMap {
  300. ce.mu.Lock()
  301. expired := time.Since(ce.lastPing) > timeout
  302. idle := (ce.state == execIdle)
  303. ce.mu.Unlock()
  304. if expired && idle { // 超时且状态空闲时则回收
  305. ce.handleClose() //// 该函数不能阻塞, 否则锁
  306. delete(c.executorMap, id)
  307. } // end if
  308. } // end for2
  309. c.executorMapMu.Unlock()
  310. } // end select
  311. } ////// end for1
  312. }
  313. func (ce *clientExecutor) handleClose() error {
  314. needInterrupt := false
  315. ce.mu.Lock()
  316. switch ce.state {
  317. case execIdle:
  318. ce.state = execClosing
  319. case execRunning:
  320. ce.state = execClosing
  321. needInterrupt = true
  322. case execClosing:
  323. ce.mu.Unlock()
  324. return nil
  325. }
  326. ce.mu.Unlock()
  327. var err error
  328. if needInterrupt {
  329. err = ce.executor.Interrupt() // 发送"Ctrl+C"
  330. }
  331. return err
  332. }