github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/qemu/list_instances.go (about) 1 package qemu 2 3 import ( 4 "fmt" 5 "os" 6 "strconv" 7 "syscall" 8 9 "github.com/sirupsen/logrus" 10 "github.com/emc-advanced-dev/pkg/errors" 11 "github.com/solo-io/unik/pkg/types" 12 ) 13 14 func (p *QemuProvider) ListInstances() ([]*types.Instance, error) { 15 if len(p.state.GetInstances()) < 1 { 16 return []*types.Instance{}, nil 17 } 18 19 var instances []*types.Instance 20 for _, instance := range p.state.GetInstances() { 21 pid, err := strconv.Atoi(instance.Id) 22 if err != nil { 23 logrus.WithField("instance", instance).Warn("invalid pid - removing instance") 24 p.state.RemoveInstance(instance) 25 continue 26 } 27 if err := detectInstance(pid); err != nil { 28 logrus.WithField("instance", instance).Debug("Instance is not running; removing") 29 p.state.RemoveInstance(instance) 30 continue 31 } 32 instances = append(instances, instance) 33 } 34 35 return instances, nil 36 } 37 38 func detectInstance(pid int) error { 39 process, err := os.FindProcess(pid) 40 if err != nil { 41 return errors.New("Failed to find process", err) 42 } 43 if err := process.Signal(syscall.Signal(0)); err != nil { 44 return errors.New(fmt.Sprintf("process.Signal on pid %d returned", pid), err) 45 } 46 return nil 47 }