adb_command.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package command
  15. import (
  16. "fmt"
  17. "os/exec"
  18. "yunion.io/x/log"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/onecloud/pkg/mcclient"
  21. o "yunion.io/x/onecloud/pkg/webconsole/options"
  22. )
  23. type SAdbShellInfo struct {
  24. HostIp string `json:"host_ip"`
  25. HostPort int `json:"host_port"`
  26. }
  27. func (info SAdbShellInfo) connStr() string {
  28. return fmt.Sprintf("%s:%d", info.HostIp, info.HostPort)
  29. }
  30. type SAdbShellCommand struct {
  31. *BaseCommand
  32. Info *SAdbShellInfo
  33. s *mcclient.ClientSession
  34. }
  35. func NewAdbShellCommand(info *SAdbShellInfo, s *mcclient.ClientSession) (*SAdbShellCommand, error) {
  36. name := o.Options.AdbPath
  37. connStr := info.connStr()
  38. initCmd := exec.Command(name, "connect", connStr)
  39. if err := initCmd.Run(); err != nil {
  40. log.Errorf("adb connect %s fail %s", connStr, err)
  41. return nil, errors.Wrap(err, "connect adb")
  42. }
  43. log.Infof("adb connect %s success!", connStr)
  44. cmd := NewBaseCommand(s, name, "-s", connStr, "shell")
  45. tool := &SAdbShellCommand{
  46. BaseCommand: cmd,
  47. Info: info,
  48. }
  49. return tool, nil
  50. }
  51. func (c *SAdbShellCommand) GetCommand() *exec.Cmd {
  52. return c.BaseCommand.GetCommand()
  53. }
  54. func (c SAdbShellCommand) GetProtocol() string {
  55. return PROTOCOL_TTY
  56. }
  57. func (c *SAdbShellCommand) Cleanup() error {
  58. connStr := c.Info.connStr()
  59. initCmd := exec.Command(o.Options.AdbPath, "disconnect", connStr)
  60. if err := initCmd.Run(); err != nil {
  61. log.Errorf("adb disconnect %s fail %s", connStr, err)
  62. return errors.Wrap(err, "disconnect adb")
  63. }
  64. log.Infof("adb disconnect %s success!", connStr)
  65. return nil
  66. }