ctop/containermap.go

96 lines
2.0 KiB
Go
Raw Normal View History

2016-12-30 22:17:46 +00:00
package main
import (
2017-01-23 15:00:33 +00:00
"fmt"
"regexp"
2017-01-12 19:24:12 +00:00
"sort"
"strings"
2017-01-12 19:24:12 +00:00
"github.com/bcicen/ctop/collector"
"github.com/bcicen/ctop/widgets"
2016-12-30 22:17:46 +00:00
"github.com/fsouza/go-dockerclient"
)
var filters = map[string][]string{
"status": []string{"running"},
}
2016-12-30 22:17:46 +00:00
func NewContainerMap() *ContainerMap {
// init docker client
2017-01-06 13:49:22 +00:00
client, err := docker.NewClient(GlobalConfig["dockerHost"])
if err != nil {
panic(err)
}
cm := &ContainerMap{
client: client,
2016-12-30 22:17:46 +00:00
containers: make(map[string]*Container),
}
cm.Refresh()
return cm
2016-12-30 22:17:46 +00:00
}
type ContainerMap struct {
client *docker.Client
2016-12-30 22:17:46 +00:00
containers map[string]*Container
}
func (cm *ContainerMap) Refresh() {
var id, name string
opts := docker.ListContainersOptions{
Filters: filters,
}
containers, err := cm.client.ListContainers(opts)
if err != nil {
panic(err)
}
for _, c := range containers {
id = c.ID[:12]
if _, ok := cm.containers[id]; ok == false {
name = strings.Replace(c.Names[0], "/", "", 1) // use primary container name
cm.containers[id] = &Container{
id: id,
name: name,
done: make(chan bool),
collect: collector.NewDocker(cm.client, id),
widgets: widgets.NewCompact(id, name),
}
cm.containers[id].Collect()
}
}
}
// Kill a container by ID
func (cm *ContainerMap) Kill(id string, sig docker.Signal) error {
opts := docker.KillContainerOptions{
ID: id,
Signal: sig,
}
return cm.client.KillContainer(opts)
}
2016-12-30 22:17:46 +00:00
// Return number of containers/rows
func (cm *ContainerMap) Len() uint {
return uint(len(cm.containers))
}
// Get a single container, by ID
func (cm *ContainerMap) Get(id string) *Container {
return cm.containers[id]
}
2017-01-03 17:37:09 +00:00
// Return array of all containers, sorted by field
2016-12-30 22:17:46 +00:00
func (cm *ContainerMap) All() []*Container {
2017-01-12 19:24:12 +00:00
var containers Containers
2017-01-23 15:00:33 +00:00
filter := GlobalConfig["filterStr"]
re := regexp.MustCompile(fmt.Sprintf(".*%s", filter))
2016-12-30 22:17:46 +00:00
for _, c := range cm.containers {
2017-01-23 15:00:33 +00:00
if re.FindAllString(c.name, 1) != nil {
containers = append(containers, c)
}
2016-12-30 22:17:46 +00:00
}
2017-01-23 15:00:33 +00:00
2017-01-12 19:24:12 +00:00
sort.Sort(containers)
2016-12-30 22:17:46 +00:00
return containers
}