1
0
mirror of https://github.com/containrrr/watchtower.git synced 2024-12-15 09:14:13 +02:00
watchtower/actions/update.go

99 lines
2.0 KiB
Go
Raw Normal View History

2015-07-21 18:04:41 +02:00
package actions
import (
2015-07-21 00:54:18 +02:00
"math/rand"
2015-07-21 18:04:41 +02:00
"github.com/CenturyLinkLabs/watchtower/container"
)
2015-07-21 18:04:41 +02:00
var (
letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
)
2015-07-21 00:54:18 +02:00
2015-07-21 18:04:41 +02:00
func allContainersFilter(container.Container) bool { return true }
2015-07-21 00:54:18 +02:00
2015-07-21 21:37:18 +02:00
func Update(client container.Client) error {
2015-07-21 18:04:41 +02:00
containers, err := client.ListContainers(allContainersFilter)
if err != nil {
return err
}
for i := range containers {
if err := client.RefreshImage(&containers[i]); err != nil {
return err
}
}
2015-07-21 18:04:41 +02:00
containers, err = container.SortByDependencies(containers)
if err != nil {
return err
}
checkDependencies(containers)
// Stop stale containers in reverse order
for i := len(containers) - 1; i >= 0; i-- {
container := containers[i]
2015-07-21 00:54:18 +02:00
if container.IsWatchtower() {
break
}
if container.Stale {
2015-07-21 00:54:18 +02:00
if err := client.Stop(container, 10); err != nil {
return err
}
}
}
// Restart stale containers in sorted order
for _, container := range containers {
if container.Stale {
2015-07-21 00:54:18 +02:00
// Since we can't shutdown a watchtower container immediately, we need to
// start the new one while the old one is still running. This prevents us
// from re-using the same container name so we first rename the current
// instance so that the new one can adopt the old name.
if container.IsWatchtower() {
if err := client.Rename(container, randName()); err != nil {
return err
}
}
if err := client.Start(container); err != nil {
return err
}
}
}
return nil
}
2015-07-21 18:04:41 +02:00
func checkDependencies(containers []container.Container) {
for i, parent := range containers {
if parent.Stale {
continue
}
LinkLoop:
for _, linkName := range parent.Links() {
for _, child := range containers {
if child.Name() == linkName && child.Stale {
containers[i].Stale = true
break LinkLoop
}
}
}
}
}
2015-07-21 00:54:18 +02:00
2015-07-21 18:04:41 +02:00
// Generates a random, 32-character, Docker-compatible container name.
2015-07-21 00:54:18 +02:00
func randName() string {
b := make([]rune, 32)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
2015-07-21 18:04:41 +02:00
2015-07-21 00:54:18 +02:00
return string(b)
}