ctop/containermap.go

68 lines
1.3 KiB
Go
Raw Normal View History

2016-12-30 22:17:46 +00:00
package main
import (
"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 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 {
cm.containers[id] = NewContainer(c)
cm.containers[id].Collect(cm.client)
}
}
}
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 {
var containers []*Container
for _, c := range cm.containers {
containers = append(containers, c)
}
2017-01-06 13:49:22 +00:00
SortContainers(GlobalConfig["sortField"], containers)
2016-12-30 22:17:46 +00:00
return containers
}