invoker.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package main
  2. import (
  3. "encoding/json"
  4. "time"
  5. "hnyfkj.com.cn/rtu/linux/utils/jsonrpc2"
  6. "hnyfkj.com.cn/rtu/linux/utils/shell"
  7. )
  8. var (
  9. rpc_ping = "executor.ping"
  10. rpc_exec = "executor.exec"
  11. rpc_stop = "executor.interrupt"
  12. rpc_quit = "executor.close"
  13. )
  14. // 串行执行
  15. func (c *MQTTCoupler) needSerialize(method string) bool {
  16. switch method {
  17. case rpc_ping, rpc_stop:
  18. return false
  19. case rpc_exec, rpc_quit:
  20. return true
  21. default:
  22. return true
  23. }
  24. }
  25. // 超时结束
  26. func (c *MQTTCoupler) needTimeoutEnd(method string) bool {
  27. switch method {
  28. case rpc_exec:
  29. return false
  30. case rpc_ping, rpc_stop, rpc_quit:
  31. return true
  32. default:
  33. return true
  34. }
  35. }
  36. // 心跳检测
  37. func (c *MQTTCoupler) Ping() (jsonrpc2.Response, error) {
  38. params := struct {
  39. ClientID string `json:"client_id"`
  40. }{
  41. ClientID: c.clientID,
  42. }
  43. return c.doCmd(rpc_ping, params)
  44. }
  45. // 执行命令
  46. func (c *MQTTCoupler) Exec(
  47. cmd string) (shell.ExecuteResult, error) {
  48. params := struct {
  49. ClientID string `json:"client_id"`
  50. shell.ExecuteParams
  51. }{
  52. ClientID: c.clientID,
  53. ExecuteParams: shell.ExecuteParams{
  54. Cmd: cmd,
  55. Timeout: int(shell.DefaultTimeout / time.Second),
  56. },
  57. }
  58. timeout := getCmdTimeoutByPrefix(cmd)
  59. if timeout > 0 {
  60. params.Timeout = timeout
  61. }
  62. exrs := shell.ExecuteResult{}
  63. resp, err := c.doCmd(rpc_exec, params)
  64. if err != nil {
  65. return exrs, err
  66. }
  67. if resp.Error != nil { ////////////////// 错误应答
  68. exrs.ExitCode = int(resp.Error.Code)
  69. exrs.Stderr = resp.Error.Message
  70. } else if len(resp.Result) > 0 { //////// 正确应答
  71. if err := json.Unmarshal(resp.Result, &exrs); err != nil {
  72. exrs.ExitCode = 1
  73. exrs.Stderr = err.Error()
  74. }
  75. }
  76. return exrs, nil
  77. }
  78. // 中断执行
  79. func (c *MQTTCoupler) Stop() (jsonrpc2.Response, error) {
  80. params := struct {
  81. ClientID string `json:"client_id"`
  82. }{
  83. ClientID: c.clientID,
  84. }
  85. return c.doCmd(rpc_stop, params)
  86. }
  87. // 关闭退出
  88. func (c *MQTTCoupler) Quit() (jsonrpc2.Response, error) {
  89. params := struct {
  90. ClientID string `json:"client_id"`
  91. }{
  92. ClientID: c.clientID,
  93. }
  94. return c.doCmd(rpc_quit, params)
  95. }