agent.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package nginx
  2. import (
  3. "errors"
  4. "github.com/astaxie/beego/logs"
  5. "log"
  6. "nginx-ui/server/models"
  7. "nginx-ui/server/modules/agent_server"
  8. "path/filepath"
  9. "time"
  10. )
  11. // AgentInstance 远程,agent代理
  12. type AgentInstance struct {
  13. nginx *models.Nginx
  14. client *agent_server.WsClient
  15. LastResult string
  16. }
  17. func (n *AgentInstance) SetNginx(nginx *models.Nginx) {
  18. log.Println("SetNginx:", nginx)
  19. n.nginx = nginx
  20. c, ok := agent_server.AgentHub.FindClient(n.nginx.Token)
  21. if !ok {
  22. return
  23. }
  24. n.client = c
  25. data := &models.AgentData{
  26. Data: nginx,
  27. Type: models.NginxUpdateType,
  28. }
  29. res, err := c.Send(data, 10*time.Second)
  30. if err != nil {
  31. logs.Error("send agent data err: %v\n", err)
  32. }
  33. logs.Info("SetNginx: %v\n", res)
  34. }
  35. // Connect 连接到nginx实例客户端,检查客户端是否可用
  36. func (n *AgentInstance) Connect() error {
  37. return nil
  38. }
  39. // Run RemoteInstance 这里应该要处理session断开的流程吧
  40. func (n *AgentInstance) Run(cmd string) (string, error) {
  41. logs.Info("Run: ", cmd)
  42. if n.client == nil {
  43. return "", errors.New("agent not online")
  44. }
  45. data := &models.AgentData{
  46. Data: &models.AgentCMD{
  47. Cmd: cmd,
  48. },
  49. Type: models.AgentCmdType,
  50. }
  51. res, err := n.client.Send(data, 10*time.Second)
  52. if err != nil {
  53. return "", err
  54. }
  55. if !res.Success {
  56. return "", errors.New(res.Msg)
  57. }
  58. n.LastResult = res.ReadStringData()
  59. logger.Printf("out: %v", n.LastResult)
  60. return n.LastResult, err
  61. }
  62. func (n *AgentInstance) Close(onlySession bool) {
  63. log.Printf("agent clone,skip")
  64. }
  65. // SendFile RemoteInstance 这里应该要处理session断开的流程吧
  66. func (n *AgentInstance) SendFile(src string, remote string) error {
  67. logs.Info("SendFile: ", src, remote)
  68. if n.client == nil {
  69. return errors.New("agent not online")
  70. }
  71. data := &models.AgentData{
  72. Data: &models.AgentSendFile{
  73. FileName: filepath.Base(src),
  74. Dst: remote,
  75. },
  76. Type: models.SendFileType,
  77. }
  78. res, err := n.client.Send(data, 120*time.Second)
  79. if err != nil {
  80. return err
  81. }
  82. if !res.Success {
  83. return errors.New(res.Msg)
  84. }
  85. logger.Printf("out: %v", n.LastResult)
  86. return nil
  87. }