package main import ( "io/ioutil" "fmt" "bufio" "os" "github.com/pkg/errors" "bytes" ) type Container interface { FindCgroupPaths(path string)(cgroupPaths []string, err error) } func FindCgroupPaths(paths []string)(cgroupPaths []string, err error){ var auxCgroupPaths []string for _, path := range paths { auxCgroupPaths, _ = FindCgroupPath(path) for _, auxCgroupPath := range auxCgroupPaths{ cgroupPaths = append(cgroupPaths, auxCgroupPath) } } return } func FindCgroupPath(path string)(cgroupPaths []string, err error){ dir, err := ioutil.ReadDir(path) if err != nil { fmt.Printf("ERROR - FindCgroupPaths - root path is not present - %v \n", err) } for _, f := range dir { if f.IsDir(){ fmt.Printf("INFO - FindCgroupPaths - Add new cgroup path - %v \n", fmt.Sprint(cgroupFreezerMesosPath, f.Name())) cgroupPaths = append(cgroupPaths, fmt.Sprint(cgroupFreezerMesosPath, f.Name())) } } return } func GetProcessFromCgroupPaths(paths []string)(cgroupPaths []string, err error){ var auxProcessContainer []string for _, path := range paths { auxProcessContainer, _ = GetProcessFromCgroupPath(path) ppidCOnatiner, _ := PpidOfContainer(auxProcessContainer) cgroupPaths = append(cgroupPaths, ppidCOnatiner) } return } func GetProcessFromCgroupPath(path string)(process []string, err error){ fmt.Printf("INFO - GetProcessFromCgroupPaths - Path: %v \n", path) file, err := os.Open(path + "/cgroup.procs") if err != nil { fmt.Printf("ERROR - GetProcessFromCgroupPath - %v \n", err) return } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) for scanner.Scan() { err = scanner.Err() if err == nil { fmt.Printf("INFO - GetProcessFromCgroupPath - Container Pid: %v \n", scanner.Text()) process = append(process, scanner.Text()) } } return } func PpidOfContainer(tasksContainer []string)(ppidCOntainer string, err error){ for _, task := range tasksContainer { ppid, err := getPPID(task) if err == nil { if isPpidContainer(ppid, tasksContainer) { fmt.Printf("INFO - isPpidContainer - Ppid of container: %v \n", task) return task, err } } } fmt.Printf("ERROR - PpidOfContainer- Not find Ppid in container with process: %v \n", tasksContainer) return "", errors.New("Not find Ppid") } func isPpidContainer(pid string, tasks []string)(bool){ for _, task := range tasks { if pid == task { return false } } return true } func getPPID(task string)(ppid string, err error){ file, err := os.Open(fmt.Sprintf("/proc/%s/stat", task)) if err != nil { fmt.Printf("ERROR - getPPID - %v \n", err) return ppid, err } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { fmt.Printf("ERROR - getPPID - %v \n", err) return ppid, err } _, err = fmt.Fscan(bytes.NewBuffer(data), &ppid, &ppid, &ppid, &ppid) fmt.Printf("INFO - getPPID - Ppid of task: %v PPid: %v \n", task, ppid) return ppid, err }