sshd.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. netmgrd.ModemInit()
  89. c.imei = netmgrd.GetIMEI()
  90. if c.imei == netmgrd.ErrUnknownModemTypeMsg || c.imei == "" {
  91. return ErrIMEINotAvailable
  92. }
  93. netmgrd.ModemExit()
  94. template := "/yfkj/device/rpc/imei"
  95. c.subTopic = strings.ReplaceAll(template+"/cmd", "imei", c.imei)
  96. c.pubTopic = strings.ReplaceAll(template+"/ack", "imei", c.imei)
  97. opts := mqtt.NewClientOptions().
  98. AddBroker(c.broker).
  99. SetUsername(c.username).SetPassword(c.password).
  100. SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
  101. SetKeepAlive(10*time.Second).SetPingTimeout(5*time.Second). // Ping心跳间隔, 超时时间
  102. SetOrderMatters(false). /*离线遗愿消息*/ SetWill(c.pubTopic, string(`{"jsonrpc": "2.0", "method": "logout"}`), MqttQos1, false)
  103. opts.OnConnect = func(client mqtt.Client) {
  104. if !c.isConnected.Swap(true) {
  105. baseapp.Logger.Infof("[%s] MQTT Broker连接成功", MODULE_NAME)
  106. }
  107. }
  108. opts.OnConnectionLost = func(client mqtt.Client, err error) {
  109. if c.isConnected.Swap(false) {
  110. baseapp.Logger.Warnf("[%s] MQTT Broker连接丢失: %v!", MODULE_NAME, err)
  111. }
  112. }
  113. c.client = mqtt.NewClient(opts)
  114. return nil
  115. }
  116. func (c *MQTTCoupler) keepOnline() {
  117. t := time.NewTimer(FastInterval)
  118. defer t.Stop()
  119. for {
  120. select {
  121. case <-c.ctx.Done():
  122. return
  123. case <-t.C:
  124. t.Reset(c.tick())
  125. } // end select
  126. } // end for
  127. }
  128. func (c *MQTTCoupler) tick() time.Duration {
  129. if c.isConnected.Load() {
  130. return FastInterval
  131. }
  132. if err := c.connect(); err != nil {
  133. baseapp.Logger.Errorf("[%s] MQTT Broker连接失败: %v!!", MODULE_NAME, err)
  134. } else { // 注册本地的RPC方法, 供远端调用, 单实例运行
  135. c.registerRpcMeths.Run(c.instRPCMethods, true)
  136. }
  137. return SlowInterval
  138. }
  139. func (c *MQTTCoupler) connect() error {
  140. if c.client.IsConnected() {
  141. return nil
  142. }
  143. token := c.client.Connect()
  144. select {
  145. case <-c.ctx.Done():
  146. return nil
  147. case <-token.Done():
  148. }
  149. return token.Error()
  150. }
  151. func (c *MQTTCoupler) instRPCMethods() {
  152. t := time.NewTicker(time.Second)
  153. defer t.Stop()
  154. for {
  155. if !c.isConnected.Load() || c.ctx.Err() != nil {
  156. return
  157. }
  158. token := c.client.Subscribe(c.subTopic, MqttQos1, c.handleRequests)
  159. select {
  160. case <-c.ctx.Done():
  161. return
  162. case <-token.Done():
  163. }
  164. if token.Error() == nil {
  165. baseapp.Logger.Infof("[%s] 本地RPC方法已注册, 等待远端调用...", MODULE_NAME)
  166. break
  167. }
  168. select {
  169. case <-c.ctx.Done():
  170. return
  171. case <-t.C:
  172. continue
  173. }
  174. }
  175. }
  176. func (c *MQTTCoupler) handleRequests(client mqtt.Client, msg mqtt.Message) {
  177. go c.execOneCmd(msg)
  178. }
  179. func (c *MQTTCoupler) execOneCmd(msg mqtt.Message) {
  180. str := string(msg.Payload())
  181. baseapp.Logger.Infof("[%s] 收到一个RPC请求: %s", MODULE_NAME, str)
  182. var resp *jsonrpc2.Response // 预先定义一个空的应答
  183. var clientID string // 该客户端的|唯一标识|
  184. var ce *clientExecutor // 该客户端的本地执行器
  185. var exists bool // 判断执行器是否已存在
  186. req, err := jsonrpc2.ParseRequest(str)
  187. if err != nil || req.ID == nil /* 不接受通知类型的消息 */ {
  188. resp = jsonrpc2.BuildError(nil, jsonrpc2.ErrParse, "")
  189. goto retp
  190. }
  191. clientID, err = extractClientID(req.Params)
  192. if err != nil {
  193. resp = jsonrpc2.BuildError(req, jsonrpc2.ErrInvalidParams, err.Error())
  194. goto retp
  195. }
  196. c.executorMapMu.Lock()
  197. ce, exists = c.executorMap[clientID]
  198. if !exists {
  199. if len(c.executorMap) >= 3 {
  200. c.executorMapMu.Unlock()
  201. resp = jsonrpc2.BuildError(req, -32000, "connection refused: server has reached maximum client capacity (3/3)")
  202. goto retp
  203. }
  204. ce = &clientExecutor{
  205. id: clientID,
  206. executor: shell.NewExecutor(),
  207. state: execIdle,
  208. }
  209. c.executorMap[clientID] = ce
  210. }
  211. c.executorMapMu.Unlock()
  212. ce.mu.Lock()
  213. ce.lastPing = time.Now()
  214. ce.mu.Unlock()
  215. switch req.Method {
  216. // Call-1: 心跳, 链路检测,"ping-pong"测试
  217. case "executor.ping":
  218. resp = buildResp(req, "pong", nil)
  219. goto retp
  220. // Call-2:在本地shell中执行远程下发的指令
  221. case "executor.exec":
  222. ce.mu.Lock()
  223. params, err := extractShellExecuteParams(req.Params)
  224. if err != nil {
  225. ce.mu.Unlock()
  226. resp = jsonrpc2.BuildError(req, jsonrpc2.ErrParse, err.Error())
  227. goto retp
  228. }
  229. if ce.state == execClosing {
  230. ce.mu.Unlock()
  231. resp = jsonrpc2.BuildError(req, -32001, "executor closed")
  232. goto retp
  233. }
  234. if ce.state == execRunning {
  235. ce.mu.Unlock()
  236. resp = jsonrpc2.BuildError(req, -32002, "executor busy")
  237. goto retp
  238. }
  239. ce.state = execRunning
  240. ce.mu.Unlock()
  241. result, err := ce.executor.Exec(params) // 本地执行用户指令
  242. ce.mu.Lock()
  243. if ce.state != execClosing {
  244. ce.state = execIdle
  245. ce.lastPing = time.Now()
  246. }
  247. ce.mu.Unlock()
  248. resp = buildResp(req, result, err)
  249. goto retp
  250. // Call-3:中断本地shell的执行,等价Ctrl+C
  251. case "executor.interrupt":
  252. ce.mu.Lock()
  253. running := (ce.state == execRunning)
  254. ce.mu.Unlock()
  255. if !running {
  256. resp = jsonrpc2.BuildError(req, -32003, "no running command")
  257. goto retp
  258. }
  259. err := ce.executor.Interrupt()
  260. resp = buildResp(req, "interrupted", err)
  261. goto retp
  262. // Call-4:客户端安全退出, 释放本地的执行器
  263. case "executor.close":
  264. err := ce.handleClose()
  265. c.executorMapMu.Lock()
  266. delete(c.executorMap, clientID)
  267. c.executorMapMu.Unlock()
  268. resp = buildResp(req, "closed", err)
  269. goto retp
  270. // Call-?:无效, 远端调用了还不支持的-方法
  271. default:
  272. resp = jsonrpc2.BuildError(req, jsonrpc2.ErrMethodNotFound, "")
  273. goto retp
  274. }
  275. retp:
  276. text, err := resp.String()
  277. if err != nil {
  278. baseapp.Logger.Errorf("[%s] 转换RPC应答失败: %v!!", MODULE_NAME, err)
  279. return
  280. }
  281. token := c.client.Publish(c.pubTopic, MqttQos1, false, text)
  282. select {
  283. case <-c.ctx.Done():
  284. return
  285. case <-token.Done():
  286. }
  287. if err := token.Error(); err != nil {
  288. baseapp.Logger.Errorf("[%s] 发送RPC应答失败: %v!!", MODULE_NAME, err)
  289. }
  290. baseapp.Logger.Infof("[%s] 发送一个RPC应答, 报文内容: %s", MODULE_NAME, text)
  291. }
  292. func (c *MQTTCoupler) startExecutorReaper(interval, timeout time.Duration) {
  293. ticker := time.NewTicker(interval)
  294. defer ticker.Stop()
  295. for {
  296. select {
  297. case <-c.ctx.Done():
  298. return
  299. case <-ticker.C:
  300. c.executorMapMu.Lock()
  301. for id, ce := range c.executorMap {
  302. ce.mu.Lock()
  303. expired := time.Since(ce.lastPing) > timeout
  304. idle := (ce.state == execIdle)
  305. ce.mu.Unlock()
  306. if expired && idle { // 超时且状态空闲时则回收
  307. ce.handleClose() //// 该函数不能阻塞, 否则锁
  308. delete(c.executorMap, id)
  309. } // end if
  310. } // end for2
  311. c.executorMapMu.Unlock()
  312. } // end select
  313. } ////// end for1
  314. }
  315. func (ce *clientExecutor) handleClose() error {
  316. needInterrupt := false
  317. ce.mu.Lock()
  318. switch ce.state {
  319. case execIdle:
  320. ce.state = execClosing
  321. case execRunning:
  322. ce.state = execClosing
  323. needInterrupt = true
  324. case execClosing:
  325. ce.mu.Unlock()
  326. return nil
  327. }
  328. ce.mu.Unlock()
  329. var err error
  330. if needInterrupt {
  331. err = ce.executor.Interrupt() // 发送"Ctrl+C"
  332. }
  333. return err
  334. }