ctop/containermap.go

108 lines
2.2 KiB
Go
Raw Normal View History

2016-12-30 22:17:46 +00:00
package main
import (
2017-01-12 19:24:12 +00:00
"sort"
"strings"
2017-01-12 19:24:12 +00:00
"github.com/bcicen/ctop/collector"
2017-02-07 03:33:09 +00:00
"github.com/bcicen/ctop/config"
"github.com/bcicen/ctop/widgets"
2016-12-30 22:17:46 +00:00
"github.com/fsouza/go-dockerclient"
)
func NewContainerMap() *ContainerMap {
// init docker client
client, err := docker.NewClient(config.GetVal("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{All: true}
containers, err := cm.client.ListContainers(opts)
if err != nil {
panic(err)
}
// add new containers
states := make(map[string]string)
for _, c := range containers {
id = c.ID[:12]
states[id] = c.State
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,
collect: collector.NewDocker(cm.client, id),
widgets: widgets.NewCompact(id, name),
}
}
}
var removeIDs []string
for id, c := range cm.containers {
// mark stale internal containers
if _, ok := states[id]; ok == false {
removeIDs = append(removeIDs, id)
continue
}
2017-02-03 23:33:13 +00:00
c.SetState(states[id])
}
// remove dead containers
cm.Del(removeIDs...)
}
// 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]
}
// Remove one or more containers
func (cm *ContainerMap) Del(ids ...string) {
for _, id := range ids {
delete(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
2016-12-30 22:17:46 +00:00
for _, c := range cm.containers {
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
}