sshd.go 10.0 KB

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