ctop/containermap.go

87 lines
1.7 KiB
Go
Raw Normal View History

2016-12-30 22:17:46 +00:00
package main
import (
"os"
2016-12-30 22:17:46 +00:00
"strings"
"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
host := os.Getenv("DOCKER_HOST")
if host == "" {
host = "unix:///var/run/docker.sock"
}
client, err := docker.NewClient(host)
if err != nil {
panic(err)
}
cm := &ContainerMap{
client: client,
2016-12-30 22:17:46 +00:00
containers: make(map[string]*Container),
sortField: SortFields[0],
2016-12-30 22:17:46 +00:00
}
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
sortField string
}
func (cm *ContainerMap) Refresh() {
opts := docker.ListContainersOptions{
Filters: filters,
}
containers, err := cm.client.ListContainers(opts)
if err != nil {
panic(err)
}
for _, c := range containers {
if _, ok := cm.containers[c.ID[:12]]; ok == false {
cm.Add(c)
}
}
}
2016-12-30 22:17:46 +00:00
// Return number of containers/rows
func (cm *ContainerMap) Len() uint {
return uint(len(cm.containers))
}
func (cm *ContainerMap) Add(c docker.APIContainers) {
id := c.ID[:12]
name := strings.Replace(c.Names[0], "/", "", 1) // use primary container name
cm.containers[id] = &Container{
id: id,
name: name,
2016-12-30 22:17:46 +00:00
done: make(chan bool),
stats: make(chan *docker.Stats),
widgets: NewWidgets(id, name),
2016-12-30 22:17:46 +00:00
reader: &StatReader{},
}
cm.containers[id].Collect(cm.client)
2016-12-30 22:17:46 +00:00
}
// Get a single container, by ID
func (cm *ContainerMap) Get(id string) *Container {
return cm.containers[id]
}
// Return array of all containers
func (cm *ContainerMap) All() []*Container {
var containers []*Container
for _, c := range cm.containers {
containers = append(containers, c)
}
return containers
}