summaryrefslogtreecommitdiff
path: root/libpod/runtime_renumber.go
blob: b27b5f1a8be3210701c409a5116ef0ae4ea40275 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package libpod

import (
	"path/filepath"

	"github.com/containers/storage"
	"github.com/pkg/errors"
)

// RenumberLocks reassigns lock numbers for all containers, pods, and volumes in
// the state.
// It renders the runtime it is called on, and all container/pod/volume structs
// from that runtime, unusable, and requires that a new runtime be initialized
// after it is called.
func (r *Runtime) RenumberLocks() error {
	r.lock.Lock()
	locked := true
	defer func() {
		if locked {
			r.lock.Unlock()
		}
	}()

	runtimeAliveLock := filepath.Join(r.config.TmpDir, "alive.lck")
	aliveLock, err := storage.GetLockfile(runtimeAliveLock)
	if err != nil {
		return errors.Wrapf(err, "error acquiring runtime init lock")
	}
	aliveLock.Lock()
	// It's OK to defer until Shutdown() has run, so no need to check locked
	defer aliveLock.Unlock()

	// Start off by deallocating all locks
	if err := r.lockManager.FreeAllLocks(); err != nil {
		return err
	}

	allCtrs, err := r.state.AllContainers()
	if err != nil {
		return err
	}
	for _, ctr := range allCtrs {
		lock, err := r.lockManager.AllocateLock()
		if err != nil {
			return errors.Wrapf(err, "error allocating lock for container %s", ctr.ID())
		}

		ctr.config.LockID = lock.ID()

		// Write the new lock ID
		if err := r.state.RewriteContainerConfig(ctr, ctr.config); err != nil {
			return err
		}
	}
	allPods, err := r.state.AllPods()
	if err != nil {
		return err
	}
	for _, pod := range allPods {
		lock, err := r.lockManager.AllocateLock()
		if err != nil {
			return errors.Wrapf(err, "error allocating lock for pod %s", pod.ID())
		}

		pod.config.LockID = lock.ID()

		// Write the new lock ID
		if err := r.state.RewritePodConfig(pod, pod.config); err != nil {
			return err
		}
	}

	r.lock.Unlock()
	locked = false

	return r.Shutdown(false)
}