invoker.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. HostFingerprint: c.machineID, // 调用者主机指纹
  55. Cmd: cmd,
  56. Timeout: int(shell.DefaultTimeout / time.Second),
  57. },
  58. }
  59. timeout := getCmdTimeoutByPrefix(cmd)
  60. if timeout > 0 {
  61. params.Timeout = timeout
  62. }
  63. exrs := shell.ExecuteResult{}
  64. resp, err := c.doCmd(rpc_exec, params)
  65. if err != nil {
  66. return &exrs, err
  67. }
  68. if resp.Error != nil { ////////////////// 错误应答
  69. exrs.ExitCode = int(resp.Error.Code)
  70. exrs.Stderr = resp.Error.Message
  71. } else if len(resp.Result) > 0 { //////// 正确应答
  72. if err := json.Unmarshal(resp.Result, &exrs); err != nil {
  73. exrs.ExitCode = 1
  74. exrs.Stderr = err.Error()
  75. }
  76. }
  77. return &exrs, nil
  78. }
  79. // 中断执行
  80. func (c *MQTTCoupler) stop() (*jsonrpc2.Response, error) {
  81. params := struct {
  82. ClientID string `json:"client_id"`
  83. }{
  84. ClientID: c.clientID,
  85. }
  86. return c.doCmd(rpc_stop, params)
  87. }
  88. // 关闭退出
  89. func (c *MQTTCoupler) quit() (*jsonrpc2.Response, error) {
  90. params := struct {
  91. ClientID string `json:"client_id"`
  92. }{
  93. ClientID: c.clientID,
  94. }
  95. return c.doCmd(rpc_quit, params)
  96. }