You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package monkey
import (
"fmt"
"os/exec"
"strings"
"github.com/spf13/cast"
)
type DockerContainer struct {
ID string `json:"id"`
Name string `json:"name"`
Device string `json:"device"`
}
// 根据任务id获取关联容器由于后续可能支持一个任务绑定多个设备执行所以返回数组
func GetTaskFromDocker(task_id int) []DockerContainer {
var list []DockerContainer
cmd := exec.Command("docker", "ps")
output, err := cmd.Output()
if err != nil {
fmt.Println(err)
return list
}
lines := strings.Split(string(output), "\n")
for i, line := range lines {
if i == 0 {
continue // skip header line
}
fields := strings.Fields(line)
if len(fields) >= 7 {
// fmt.Printf("Container ID: %s, Name: %s\n", fields[0], fields[len(fields)-1])
var c DockerContainer
c.ID = fields[0]
c.Name = fields[len(fields)-1]
_strs := strings.Split(c.Name, "_")
c.Device = _strs[len(_strs)-1]
if strings.Contains(c.Name, "monkey_task_"+cast.ToString(task_id)+"_") {
list = append(list, c)
}
}
}
return list
}
func StopDockerContainer(container_name string) bool {
cmd := exec.Command("docker", "stop", "-t", "0", container_name)
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("[docker] Error stopping container:", err)
return true
}
fmt.Println("[docker] Container stopped successfully:", string(out))
return true
}