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

101 lines
2.1 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
}
2015-07-22 00:41:58 +02:00
for i, container := range containers {
stale, err := client.IsContainerStale(container)
if err != nil {
return err
}
2015-07-22 00:41:58 +02:00
containers[i].Stale = stale
}
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-22 00:41:58 +02:00
if err := client.StopContainer(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() {
2015-07-22 00:41:58 +02:00
if err := client.RenameContainer(container, randName()); err != nil {
2015-07-21 00:54:18 +02:00
return err
}
}
2015-07-22 00:41:58 +02:00
if err := client.StartContainer(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)
}