17
"github.com/containers/common/libnetwork/types"
18
"github.com/containers/podman/v5/libpod/define"
19
"github.com/containers/storage/pkg/fileutils"
20
"github.com/sirupsen/logrus"
21
bolt "go.etcd.io/bbolt"
24
// BoltState is a state implementation backed by a Bolt DB
25
type BoltState struct {
32
// A brief description of the format of the BoltDB state:
33
// At the top level, the following buckets are created:
34
// - idRegistryBkt: Maps ID to Name for containers and pods.
35
// Used to ensure container and pod IDs are globally unique.
36
// - nameRegistryBkt: Maps Name to ID for containers and pods.
37
// Used to ensure container and pod names are globally unique.
38
// - ctrBkt: Contains a sub-bucket for each container in the state.
39
// Each sub-bucket has config and state keys holding the container's JSON
40
// encoded configuration and state (respectively), an optional netNS key
41
// containing the path to the container's network namespace, a dependencies
42
// bucket containing the container's dependencies, and an optional pod key
43
// containing the ID of the pod the container is joined to.
44
// After updates to include exec sessions, may also include an exec bucket
45
// with the IDs of exec sessions currently in use by the container.
46
// - allCtrsBkt: Map of ID to name containing only containers. Used for
47
// container lookup operations.
48
// - podBkt: Contains a sub-bucket for each pod in the state.
49
// Each sub-bucket has config and state keys holding the pod's JSON encoded
50
// configuration and state, plus a containers sub bucket holding the IDs of
51
// containers in the pod.
52
// - allPodsBkt: Map of ID to name containing only pods. Used for pod lookup
54
// - execBkt: Map of exec session ID to container ID - used for resolving
55
// exec session IDs to the containers that hold the exec session.
56
// - networksBkt: Contains all network names as key with their options json
58
// - aliasesBkt - Deprecated, use the networksBkt. Used to contain a bucket
59
// for each CNI network which contain a map of network alias (an extra name
60
// for containers in DNS) to the ID of the container holding the alias.
61
// Aliases must be unique per-network, and cannot conflict with names
62
// registered in nameRegistryBkt.
63
// - runtimeConfigBkt: Contains configuration of the libpod instance that
64
// initially created the database. This must match for any further instances
65
// that access the database, to ensure that state mismatches with
66
// containers/storage do not occur.
67
// - exitCodeBucket/exitCodeTimeStampBucket: (#14559) exit codes must be part
68
// of the database to resolve a previous race condition when one process waits
69
// for the exit file to be written and another process removes it along with
70
// the container during auto-removal. The same race would happen trying to
71
// read the exit code from the containers bucket. Hence, exit codes go into
72
// their own bucket. To avoid the rather expensive JSON (un)marshalling, we
73
// have two buckets: one for the exit codes, the other for the timestamps.
75
// NewBoltState creates a new bolt-backed state database
76
func NewBoltState(path string, runtime *Runtime) (State, error) {
77
logrus.Info("Using boltdb as database backend")
78
state := new(BoltState)
80
state.runtime = runtime
82
logrus.Debugf("Initializing boltdb state at %s", path)
84
// BoltDB is deprecated and, as of Podman 5.0, we no longer allow the
85
// creation of new Bolt states.
86
// If the DB does not already exist, error out.
87
// To continue testing in CI, allow creation iff an undocumented env
89
if os.Getenv("CI_DESIRED_DATABASE") != "boltdb" {
90
if err := fileutils.Exists(path); err != nil && errors.Is(err, fs.ErrNotExist) {
91
return nil, fmt.Errorf("the BoltDB backend has been deprecated, no new BoltDB databases can be created: %w", define.ErrInvalidArg)
94
logrus.Debugf("Allowing deprecated database backend due to CI_DESIRED_DATABASE.")
97
db, err := bolt.Open(path, 0600, nil)
99
return nil, fmt.Errorf("opening database %s: %w", path, err)
101
// Everywhere else, we use s.deferredCloseDBCon(db) to ensure the state's DB
102
// mutex is also unlocked.
103
// However, here, the mutex has not been locked, since we just created
104
// the DB connection, and it hasn't left this function yet - no risk of
105
// concurrent access.
106
// As such, just a db.Close() is fine here.
109
createBuckets := [][]byte{
121
exitCodeTimeStampBkt,
125
// Does the DB need an update?
127
err = db.View(func(tx *bolt.Tx) error {
128
for _, bkt := range createBuckets {
129
if test := tx.Bucket(bkt); test == nil {
137
return nil, fmt.Errorf("checking DB schema: %w", err)
145
// Ensure schema is properly created in DB
146
err = db.Update(func(tx *bolt.Tx) error {
147
for _, bkt := range createBuckets {
148
if _, err := tx.CreateBucketIfNotExists(bkt); err != nil {
149
return fmt.Errorf("creating bucket %s: %w", string(bkt), err)
155
return nil, fmt.Errorf("creating buckets for DB: %w", err)
163
// Close closes the state and prevents further use
164
func (s *BoltState) Close() error {
169
// Refresh clears container and pod states after a reboot
170
func (s *BoltState) Refresh() error {
172
return define.ErrDBClosed
175
db, err := s.getDBCon()
179
defer s.deferredCloseDBCon(db)
181
err = db.Update(func(tx *bolt.Tx) error {
182
idBucket, err := getIDBucket(tx)
187
namesBucket, err := getNamesBucket(tx)
192
ctrsBucket, err := getCtrBucket(tx)
197
podsBucket, err := getPodBucket(tx)
202
allVolsBucket, err := getAllVolsBucket(tx)
207
volBucket, err := getVolBucket(tx)
212
execBucket, err := getExecBucket(tx)
217
exitCodeBucket, err := getExitCodeBucket(tx)
222
timeStampBucket, err := getExitCodeTimeStampBucket(tx)
227
// Clear all exec exit codes
228
toRemoveExitCodes := []string{}
229
err = exitCodeBucket.ForEach(func(id, _ []byte) error {
230
toRemoveExitCodes = append(toRemoveExitCodes, string(id))
234
return fmt.Errorf("reading exit codes bucket: %w", err)
236
for _, id := range toRemoveExitCodes {
237
if err := exitCodeBucket.Delete([]byte(id)); err != nil {
238
return fmt.Errorf("removing exit code for ID %s: %w", id, err)
242
toRemoveTimeStamps := []string{}
243
err = timeStampBucket.ForEach(func(id, _ []byte) error {
244
toRemoveTimeStamps = append(toRemoveTimeStamps, string(id))
248
return fmt.Errorf("reading timestamps bucket: %w", err)
250
for _, id := range toRemoveTimeStamps {
251
if err := timeStampBucket.Delete([]byte(id)); err != nil {
252
return fmt.Errorf("removing timestamp for ID %s: %w", id, err)
256
// Iterate through all IDs. Check if they are containers.
257
// If they are, unmarshal their state, and then clear
258
// PID, mountpoint, and state for all of them
259
// Then save the modified state
260
// Also clear all network namespaces
261
toRemoveIDs := []string{}
262
err = idBucket.ForEach(func(id, name []byte) error {
263
ctrBkt := ctrsBucket.Bucket(id)
266
podBkt := podsBucket.Bucket(id)
268
// This is neither a pod nor a container
269
// Something is seriously wrong, but
270
// continue on and try to clean up the
271
// state and become consistent.
272
// Just note what needs to be removed
273
// for now - ForEach says you shouldn't
274
// remove things from the table during
276
logrus.Errorf("Database issue: dangling ID %s found (not a pod or container) - removing", string(id))
277
toRemoveIDs = append(toRemoveIDs, string(id))
282
stateBytes := podBkt.Get(stateKey)
283
if stateBytes == nil {
284
return fmt.Errorf("pod %s missing state key: %w", string(id), define.ErrInternal)
287
state := new(podState)
289
if err := json.Unmarshal(stateBytes, state); err != nil {
290
return fmt.Errorf("unmarshalling state for pod %s: %w", string(id), err)
296
newStateBytes, err := json.Marshal(state)
298
return fmt.Errorf("marshalling modified state for pod %s: %w", string(id), err)
301
if err := podBkt.Put(stateKey, newStateBytes); err != nil {
302
return fmt.Errorf("updating state for pod %s in DB: %w", string(id), err)
305
// It's not a container, nothing to do
309
// First, delete the network namespace
310
if err := ctrBkt.Delete(netNSKey); err != nil {
311
return fmt.Errorf("removing network namespace for container %s: %w", string(id), err)
314
stateBytes := ctrBkt.Get(stateKey)
315
if stateBytes == nil {
316
// Badly formatted container bucket
317
return fmt.Errorf("container %s missing state in DB: %w", string(id), define.ErrInternal)
320
state := new(ContainerState)
322
if err := json.Unmarshal(stateBytes, state); err != nil {
323
return fmt.Errorf("unmarshalling state for container %s: %w", string(id), err)
326
resetContainerState(state)
328
newStateBytes, err := json.Marshal(state)
330
return fmt.Errorf("marshalling modified state for container %s: %w", string(id), err)
333
if err := ctrBkt.Put(stateKey, newStateBytes); err != nil {
334
return fmt.Errorf("updating state for container %s in DB: %w", string(id), err)
337
// Delete all exec sessions, if there are any
338
ctrExecBkt := ctrBkt.Bucket(execBkt)
339
if ctrExecBkt != nil {
340
// Can't delete in a ForEach, so build a list of
341
// what to remove then remove.
342
toRemove := []string{}
343
err = ctrExecBkt.ForEach(func(id, unused []byte) error {
344
toRemove = append(toRemove, string(id))
350
for _, execID := range toRemove {
351
if err := ctrExecBkt.Delete([]byte(execID)); err != nil {
352
return fmt.Errorf("removing exec session %s from container %s: %w", execID, string(id), err)
363
// Remove dangling IDs.
364
for _, id := range toRemoveIDs {
365
// Look up the ID to see if we also have a dangling name
367
name := idBucket.Get([]byte(id))
369
if testID := namesBucket.Get(name); testID != nil {
370
logrus.Infof("Found dangling name %s (ID %s) in database", string(name), id)
371
if err := namesBucket.Delete(name); err != nil {
372
return fmt.Errorf("removing dangling name %s (ID %s) from database: %w", string(name), id, err)
376
if err := idBucket.Delete([]byte(id)); err != nil {
377
return fmt.Errorf("removing dangling ID %s from database: %w", id, err)
381
// Now refresh volumes
382
err = allVolsBucket.ForEach(func(id, name []byte) error {
383
dbVol := volBucket.Bucket(id)
385
return fmt.Errorf("inconsistency in state - volume %s is in all volumes bucket but volume not found: %w", string(id), define.ErrInternal)
389
volStateBytes := dbVol.Get(stateKey)
390
if volStateBytes == nil {
391
// If the volume doesn't have a state, nothing to do
395
oldState := new(VolumeState)
397
if err := json.Unmarshal(volStateBytes, oldState); err != nil {
398
return fmt.Errorf("unmarshalling state for volume %s: %w", string(id), err)
401
resetVolumeState(oldState)
403
newState, err := json.Marshal(oldState)
405
return fmt.Errorf("marshalling state for volume %s: %w", string(id), err)
408
if err := dbVol.Put(stateKey, newState); err != nil {
409
return fmt.Errorf("storing new state for volume %s: %w", string(id), err)
418
// Now refresh exec sessions
419
// We want to remove them all, but for-each can't modify buckets
420
// So we have to make a list of what to operate on, then do the
422
toRemoveExec := []string{}
423
err = execBucket.ForEach(func(id, unused []byte) error {
424
toRemoveExec = append(toRemoveExec, string(id))
431
for _, execSession := range toRemoveExec {
432
if err := execBucket.Delete([]byte(execSession)); err != nil {
433
return fmt.Errorf("deleting exec session %s registry from database: %w", execSession, err)
442
// GetDBConfig retrieves runtime configuration fields that were created when
443
// the database was first initialized
444
func (s *BoltState) GetDBConfig() (*DBConfig, error) {
446
return nil, define.ErrDBClosed
451
db, err := s.getDBCon()
455
defer s.deferredCloseDBCon(db)
457
err = db.View(func(tx *bolt.Tx) error {
458
configBucket, err := getRuntimeConfigBucket(tx)
463
// Some of these may be nil
464
// When we convert to string, Go will coerce them to ""
465
// That's probably fine - we could raise an error if the key is
466
// missing, but just not including it is also OK.
467
libpodRoot := configBucket.Get(staticDirKey)
468
libpodTmp := configBucket.Get(tmpDirKey)
469
storageRoot := configBucket.Get(graphRootKey)
470
storageTmp := configBucket.Get(runRootKey)
471
graphDriver := configBucket.Get(graphDriverKey)
472
volumePath := configBucket.Get(volPathKey)
474
cfg.LibpodRoot = string(libpodRoot)
475
cfg.LibpodTmp = string(libpodTmp)
476
cfg.StorageRoot = string(storageRoot)
477
cfg.StorageTmp = string(storageTmp)
478
cfg.GraphDriver = string(graphDriver)
479
cfg.VolumePath = string(volumePath)
490
// ValidateDBConfig validates paths in the given runtime against the database
491
func (s *BoltState) ValidateDBConfig(runtime *Runtime) error {
493
return define.ErrDBClosed
496
db, err := s.getDBCon()
500
defer s.deferredCloseDBCon(db)
502
// Check runtime configuration
503
if err := checkRuntimeConfig(db, runtime); err != nil {
510
// GetContainerName returns the name associated with a given ID.
511
// Returns ErrNoSuchCtr if the ID does not exist.
512
func (s *BoltState) GetContainerName(id string) (string, error) {
514
return "", define.ErrEmptyID
518
return "", define.ErrDBClosed
521
idBytes := []byte(id)
523
db, err := s.getDBCon()
527
defer s.deferredCloseDBCon(db)
531
err = db.View(func(tx *bolt.Tx) error {
532
idBkt, err := getIDBucket(tx)
537
ctrsBkt, err := getCtrBucket(tx)
542
nameBytes := idBkt.Get(idBytes)
543
if nameBytes == nil {
544
return define.ErrNoSuchCtr
547
ctrExists := ctrsBkt.Bucket(idBytes)
548
if ctrExists == nil {
549
return define.ErrNoSuchCtr
552
name = string(nameBytes)
562
// GetPodName returns the name associated with a given ID.
563
// Returns ErrNoSuchPod if the ID does not exist.
564
func (s *BoltState) GetPodName(id string) (string, error) {
566
return "", define.ErrEmptyID
570
return "", define.ErrDBClosed
573
idBytes := []byte(id)
575
db, err := s.getDBCon()
579
defer s.deferredCloseDBCon(db)
583
err = db.View(func(tx *bolt.Tx) error {
584
idBkt, err := getIDBucket(tx)
589
podBkt, err := getPodBucket(tx)
594
nameBytes := idBkt.Get(idBytes)
595
if nameBytes == nil {
596
return define.ErrNoSuchPod
599
podExists := podBkt.Bucket(idBytes)
600
if podExists == nil {
601
return define.ErrNoSuchPod
604
name = string(nameBytes)
614
// Container retrieves a single container from the state by its full ID
615
func (s *BoltState) Container(id string) (*Container, error) {
617
return nil, define.ErrEmptyID
621
return nil, define.ErrDBClosed
626
ctr := new(Container)
627
ctr.config = new(ContainerConfig)
628
ctr.state = new(ContainerState)
630
db, err := s.getDBCon()
634
defer s.deferredCloseDBCon(db)
636
err = db.View(func(tx *bolt.Tx) error {
637
ctrBucket, err := getCtrBucket(tx)
642
return s.getContainerFromDB(ctrID, ctr, ctrBucket, false)
651
// LookupContainerID retrieves a container ID from the state by full or unique
653
func (s *BoltState) LookupContainerID(idOrName string) (string, error) {
655
return "", define.ErrEmptyID
659
return "", define.ErrDBClosed
662
db, err := s.getDBCon()
666
defer s.deferredCloseDBCon(db)
669
err = db.View(func(tx *bolt.Tx) error {
670
ctrBucket, err := getCtrBucket(tx)
675
namesBucket, err := getNamesBucket(tx)
680
fullID, err := s.lookupContainerID(idOrName, ctrBucket, namesBucket)
693
// LookupContainer retrieves a container from the state by full or unique
695
func (s *BoltState) LookupContainer(idOrName string) (*Container, error) {
697
return nil, define.ErrEmptyID
701
return nil, define.ErrDBClosed
704
ctr := new(Container)
705
ctr.config = new(ContainerConfig)
706
ctr.state = new(ContainerState)
708
db, err := s.getDBCon()
712
defer s.deferredCloseDBCon(db)
714
err = db.View(func(tx *bolt.Tx) error {
715
ctrBucket, err := getCtrBucket(tx)
720
namesBucket, err := getNamesBucket(tx)
725
id, err := s.lookupContainerID(idOrName, ctrBucket, namesBucket)
730
return s.getContainerFromDB(id, ctr, ctrBucket, false)
739
// HasContainer checks if a container is present in the state
740
func (s *BoltState) HasContainer(id string) (bool, error) {
742
return false, define.ErrEmptyID
746
return false, define.ErrDBClosed
751
db, err := s.getDBCon()
755
defer s.deferredCloseDBCon(db)
759
err = db.View(func(tx *bolt.Tx) error {
760
ctrBucket, err := getCtrBucket(tx)
765
ctrDB := ctrBucket.Bucket(ctrID)
779
// AddContainer adds a container to the state
780
// The container being added cannot belong to a pod
781
func (s *BoltState) AddContainer(ctr *Container) error {
783
return define.ErrDBClosed
787
return define.ErrCtrRemoved
790
if ctr.config.Pod != "" {
791
return fmt.Errorf("cannot add a container that belongs to a pod with AddContainer - use AddContainerToPod: %w", define.ErrInvalidArg)
794
return s.addContainer(ctr, nil)
797
// RemoveContainer removes a container from the state
798
// Only removes containers not in pods - for containers that are a member of a
799
// pod, use RemoveContainerFromPod
800
func (s *BoltState) RemoveContainer(ctr *Container) error {
802
return define.ErrDBClosed
805
if ctr.config.Pod != "" {
806
return fmt.Errorf("container %s is part of a pod, use RemoveContainerFromPod instead: %w", ctr.ID(), define.ErrPodExists)
809
db, err := s.getDBCon()
813
defer s.deferredCloseDBCon(db)
815
err = db.Update(func(tx *bolt.Tx) error {
816
return s.removeContainer(ctr, nil, tx)
821
// UpdateContainer updates a container's state from the database
822
func (s *BoltState) UpdateContainer(ctr *Container) error {
824
return define.ErrDBClosed
828
return define.ErrCtrRemoved
831
ctrID := []byte(ctr.ID())
833
db, err := s.getDBCon()
837
defer s.deferredCloseDBCon(db)
839
return db.View(func(tx *bolt.Tx) error {
840
ctrBucket, err := getCtrBucket(tx)
844
return s.getContainerStateDB(ctrID, ctr, ctrBucket)
848
// SaveContainer saves a container's current state in the database
849
func (s *BoltState) SaveContainer(ctr *Container) error {
851
return define.ErrDBClosed
855
return define.ErrCtrRemoved
858
stateJSON, err := json.Marshal(ctr.state)
860
return fmt.Errorf("marshalling container %s state to JSON: %w", ctr.ID(), err)
862
netNSPath := ctr.state.NetNS
864
ctrID := []byte(ctr.ID())
866
db, err := s.getDBCon()
870
defer s.deferredCloseDBCon(db)
872
err = db.Update(func(tx *bolt.Tx) error {
873
ctrBucket, err := getCtrBucket(tx)
878
ctrToSave := ctrBucket.Bucket(ctrID)
879
if ctrToSave == nil {
881
return fmt.Errorf("container %s does not exist in DB: %w", ctr.ID(), define.ErrNoSuchCtr)
885
if err := ctrToSave.Put(stateKey, stateJSON); err != nil {
886
return fmt.Errorf("updating container %s state in DB: %w", ctr.ID(), err)
890
// Delete the existing network namespace
891
if err := ctrToSave.Delete(netNSKey); err != nil {
892
return fmt.Errorf("removing network namespace path for container %s in DB: %w", ctr.ID(), err)
901
// ContainerInUse checks if other containers depend on the given container
902
// It returns a slice of the IDs of the containers depending on the given
903
// container. If the slice is empty, no containers depend on the given container
904
func (s *BoltState) ContainerInUse(ctr *Container) ([]string, error) {
906
return nil, define.ErrDBClosed
910
return nil, define.ErrCtrRemoved
913
depCtrs := []string{}
915
db, err := s.getDBCon()
919
defer s.deferredCloseDBCon(db)
921
err = db.View(func(tx *bolt.Tx) error {
922
ctrBucket, err := getCtrBucket(tx)
927
ctrDB := ctrBucket.Bucket([]byte(ctr.ID()))
930
return fmt.Errorf("no container with ID %q found in DB: %w", ctr.ID(), define.ErrNoSuchCtr)
933
dependsBkt := ctrDB.Bucket(dependenciesBkt)
934
if dependsBkt == nil {
935
return fmt.Errorf("container %s has no dependencies bucket: %w", ctr.ID(), define.ErrInternal)
938
// Iterate through and add dependencies
939
err = dependsBkt.ForEach(func(id, value []byte) error {
940
depCtrs = append(depCtrs, string(id))
957
// AllContainers retrieves all the containers in the database
958
// If `loadState` is set, the containers' state will be loaded as well.
959
func (s *BoltState) AllContainers(loadState bool) ([]*Container, error) {
961
return nil, define.ErrDBClosed
964
ctrs := []*Container{}
966
db, err := s.getDBCon()
970
defer s.deferredCloseDBCon(db)
972
err = db.View(func(tx *bolt.Tx) error {
973
allCtrsBucket, err := getAllCtrsBucket(tx)
978
ctrBucket, err := getCtrBucket(tx)
983
return allCtrsBucket.ForEach(func(id, name []byte) error {
984
// If performance becomes an issue, this check can be
985
// removed. But the error messages that come back will
986
// be much less helpful.
987
ctrExists := ctrBucket.Bucket(id)
988
if ctrExists == nil {
989
return fmt.Errorf("state is inconsistent - container ID %s in all containers, but container not found: %w", string(id), define.ErrInternal)
992
ctr := new(Container)
993
ctr.config = new(ContainerConfig)
994
ctr.state = new(ContainerState)
996
if err := s.getContainerFromDB(id, ctr, ctrBucket, loadState); err != nil {
997
logrus.Errorf("Error retrieving container from database: %v", err)
999
ctrs = append(ctrs, ctr)
1012
// GetNetworks returns the networks this container is a part of.
1013
func (s *BoltState) GetNetworks(ctr *Container) (map[string]types.PerNetworkOptions, error) {
1015
return nil, define.ErrDBClosed
1019
return nil, define.ErrCtrRemoved
1022
// if the network mode is not bridge return no networks
1023
if !ctr.config.NetMode.IsBridge() {
1027
ctrID := []byte(ctr.ID())
1029
db, err := s.getDBCon()
1033
defer s.deferredCloseDBCon(db)
1035
networks := make(map[string]types.PerNetworkOptions)
1039
err = db.View(func(tx *bolt.Tx) error {
1040
ctrBucket, err := getCtrBucket(tx)
1045
dbCtr := ctrBucket.Bucket(ctrID)
1048
return fmt.Errorf("container %s does not exist in database: %w", ctr.ID(), define.ErrNoSuchCtr)
1051
ctrNetworkBkt := dbCtr.Bucket(networksBkt)
1052
if ctrNetworkBkt == nil {
1053
// convert if needed
1058
return ctrNetworkBkt.ForEach(func(network, v []byte) error {
1059
opts := types.PerNetworkOptions{}
1060
if err := json.Unmarshal(v, &opts); err != nil {
1061
// special case for backwards compat
1062
// earlier version used the container id as value so we set a
1063
// special error to indicate the we have to migrate the db
1064
if !bytes.Equal(v, ctrID) {
1069
networks[string(network)] = opts
1077
err = db.Update(func(tx *bolt.Tx) error {
1078
ctrBucket, err := getCtrBucket(tx)
1083
dbCtr := ctrBucket.Bucket(ctrID)
1086
return fmt.Errorf("container %s does not exist in database: %w", ctr.ID(), define.ErrNoSuchCtr)
1089
var networkList []string
1091
ctrNetworkBkt := dbCtr.Bucket(networksBkt)
1092
if ctrNetworkBkt == nil {
1093
ctrNetworkBkt, err = dbCtr.CreateBucket(networksBkt)
1095
return fmt.Errorf("creating networks bucket for container %s: %w", ctr.ID(), err)
1097
// the container has no networks in the db lookup config and write to the db
1098
networkList = ctr.config.NetworksDeprecated
1099
// if there are no networks we have to add the default
1100
if len(networkList) == 0 {
1101
networkList = []string{ctr.runtime.config.Network.DefaultNetwork}
1104
err = ctrNetworkBkt.ForEach(func(network, v []byte) error {
1105
networkList = append(networkList, string(network))
1113
// the container has no networks in the db lookup config and write to the db
1114
for i, network := range networkList {
1116
if ctr.state.NetInterfaceDescriptions != nil {
1117
eth, exists := ctr.state.NetInterfaceDescriptions.getInterfaceByName(network)
1119
return fmt.Errorf("no network interface name for container %s on network %s", ctr.config.ID, network)
1123
intName = fmt.Sprintf("eth%d", i)
1125
getAliases := func(network string) []string {
1126
var aliases []string
1127
ctrAliasesBkt := dbCtr.Bucket(aliasesBkt)
1128
if ctrAliasesBkt == nil {
1131
netAliasesBkt := ctrAliasesBkt.Bucket([]byte(network))
1132
if netAliasesBkt == nil {
1133
// No aliases for this specific network.
1137
// let's ignore the error here there is nothing we can do
1138
_ = netAliasesBkt.ForEach(func(alias, v []byte) error {
1139
aliases = append(aliases, string(alias))
1142
// also add the short container id as alias
1146
netOpts := &types.PerNetworkOptions{
1147
InterfaceName: intName,
1148
// we have to add the short id as alias for docker compat
1149
Aliases: append(getAliases(network), ctr.config.ID[:12]),
1151
// only set the static ip/mac on the first network
1153
if ctr.config.StaticIP != nil {
1154
netOpts.StaticIPs = []net.IP{ctr.config.StaticIP}
1156
netOpts.StaticMAC = ctr.config.StaticMAC
1159
optsBytes, err := json.Marshal(netOpts)
1163
// insert into network map because we need to return this
1164
networks[network] = *netOpts
1166
err = ctrNetworkBkt.Put([]byte(network), optsBytes)
1178
return networks, nil
1181
// NetworkConnect adds the given container to the given network. If aliases are
1182
// specified, those will be added to the given network.
1183
func (s *BoltState) NetworkConnect(ctr *Container, network string, opts types.PerNetworkOptions) error {
1184
return s.networkModify(ctr, network, opts, true)
1187
// NetworkModify will allow you to set new options on an existing connected network
1188
func (s *BoltState) NetworkModify(ctr *Container, network string, opts types.PerNetworkOptions) error {
1189
return s.networkModify(ctr, network, opts, false)
1192
// networkModify allows you to modify or add a new network, to add a new network use the new bool
1193
func (s *BoltState) networkModify(ctr *Container, network string, opts types.PerNetworkOptions, new bool) error {
1195
return define.ErrDBClosed
1199
return define.ErrCtrRemoved
1203
return fmt.Errorf("network names must not be empty: %w", define.ErrInvalidArg)
1206
optBytes, err := json.Marshal(opts)
1208
return fmt.Errorf("marshalling network options JSON for container %s: %w", ctr.ID(), err)
1211
ctrID := []byte(ctr.ID())
1213
db, err := s.getDBCon()
1217
defer s.deferredCloseDBCon(db)
1219
return db.Update(func(tx *bolt.Tx) error {
1220
ctrBucket, err := getCtrBucket(tx)
1225
dbCtr := ctrBucket.Bucket(ctrID)
1228
return fmt.Errorf("container %s does not exist in database: %w", ctr.ID(), define.ErrNoSuchCtr)
1231
ctrNetworksBkt := dbCtr.Bucket(networksBkt)
1232
if ctrNetworksBkt == nil {
1233
return fmt.Errorf("container %s does not have a network bucket: %w", ctr.ID(), define.ErrNoSuchNetwork)
1235
netConnected := ctrNetworksBkt.Get([]byte(network))
1237
if new && netConnected != nil {
1238
return fmt.Errorf("container %s is already connected to network %q: %w", ctr.ID(), network, define.ErrNetworkConnected)
1239
} else if !new && netConnected == nil {
1240
return fmt.Errorf("container %s is not connected to network %q: %w", ctr.ID(), network, define.ErrNoSuchNetwork)
1243
// Modify/Add the network
1244
if err := ctrNetworksBkt.Put([]byte(network), optBytes); err != nil {
1245
return fmt.Errorf("adding container %s to network %s in DB: %w", ctr.ID(), network, err)
1252
// NetworkDisconnect disconnects the container from the given network, also
1253
// removing any aliases in the network.
1254
func (s *BoltState) NetworkDisconnect(ctr *Container, network string) error {
1256
return define.ErrDBClosed
1260
return define.ErrCtrRemoved
1264
return fmt.Errorf("network names must not be empty: %w", define.ErrInvalidArg)
1267
ctrID := []byte(ctr.ID())
1269
db, err := s.getDBCon()
1273
defer s.deferredCloseDBCon(db)
1275
return db.Update(func(tx *bolt.Tx) error {
1276
ctrBucket, err := getCtrBucket(tx)
1281
dbCtr := ctrBucket.Bucket(ctrID)
1284
return fmt.Errorf("container %s does not exist in database: %w", ctr.ID(), define.ErrNoSuchCtr)
1287
ctrAliasesBkt := dbCtr.Bucket(aliasesBkt)
1288
ctrNetworksBkt := dbCtr.Bucket(networksBkt)
1289
if ctrNetworksBkt == nil {
1290
return fmt.Errorf("container %s is not connected to any networks, so cannot disconnect: %w", ctr.ID(), define.ErrNoSuchNetwork)
1292
netConnected := ctrNetworksBkt.Get([]byte(network))
1293
if netConnected == nil {
1294
return fmt.Errorf("container %s is not connected to network %q: %w", ctr.ID(), network, define.ErrNoSuchNetwork)
1297
if err := ctrNetworksBkt.Delete([]byte(network)); err != nil {
1298
return fmt.Errorf("removing container %s from network %s: %w", ctr.ID(), network, err)
1301
if ctrAliasesBkt != nil {
1302
bktExists := ctrAliasesBkt.Bucket([]byte(network))
1303
if bktExists == nil {
1307
if err := ctrAliasesBkt.DeleteBucket([]byte(network)); err != nil {
1308
return fmt.Errorf("removing container %s network aliases for network %s: %w", ctr.ID(), network, err)
1316
// GetContainerConfig returns a container config from the database by full ID
1317
func (s *BoltState) GetContainerConfig(id string) (*ContainerConfig, error) {
1319
return nil, define.ErrEmptyID
1323
return nil, define.ErrDBClosed
1326
config := new(ContainerConfig)
1328
db, err := s.getDBCon()
1332
defer s.deferredCloseDBCon(db)
1334
err = db.View(func(tx *bolt.Tx) error {
1335
ctrBucket, err := getCtrBucket(tx)
1340
return s.getContainerConfigFromDB([]byte(id), config, ctrBucket)
1349
// AddContainerExitCode adds the exit code for the specified container to the database.
1350
func (s *BoltState) AddContainerExitCode(id string, exitCode int32) error {
1352
return define.ErrEmptyID
1356
return define.ErrDBClosed
1359
db, err := s.getDBCon()
1363
defer s.deferredCloseDBCon(db)
1366
rawExitCode := []byte(strconv.Itoa(int(exitCode)))
1367
rawTimeStamp, err := time.Now().MarshalText()
1369
return fmt.Errorf("marshalling exit-code time stamp: %w", err)
1372
return db.Update(func(tx *bolt.Tx) error {
1373
exitCodeBucket, err := getExitCodeBucket(tx)
1377
timeStampBucket, err := getExitCodeTimeStampBucket(tx)
1382
if err := exitCodeBucket.Put(rawID, rawExitCode); err != nil {
1383
return fmt.Errorf("adding exit code of container %s to DB: %w", id, err)
1385
if err := timeStampBucket.Put(rawID, rawTimeStamp); err != nil {
1386
if rmErr := exitCodeBucket.Delete(rawID); rmErr != nil {
1387
logrus.Errorf("Removing exit code of container %s from DB: %v", id, rmErr)
1389
return fmt.Errorf("adding exit-code time stamp of container %s to DB: %w", id, err)
1396
// GetContainerExitCode returns the exit code for the specified container.
1397
func (s *BoltState) GetContainerExitCode(id string) (int32, error) {
1399
return -1, define.ErrEmptyID
1403
return -1, define.ErrDBClosed
1406
db, err := s.getDBCon()
1410
defer s.deferredCloseDBCon(db)
1414
return result, db.View(func(tx *bolt.Tx) error {
1415
exitCodeBucket, err := getExitCodeBucket(tx)
1420
rawExitCode := exitCodeBucket.Get(rawID)
1421
if rawExitCode == nil {
1422
return fmt.Errorf("getting exit code of container %s from DB: %w", id, define.ErrNoSuchExitCode)
1425
exitCode, err := strconv.Atoi(string(rawExitCode))
1427
return fmt.Errorf("converting raw exit code %v of container %s: %w", rawExitCode, id, err)
1430
result = int32(exitCode)
1435
// GetContainerExitCodeTimeStamp returns the time stamp when the exit code of
1436
// the specified container was added to the database.
1437
func (s *BoltState) GetContainerExitCodeTimeStamp(id string) (*time.Time, error) {
1439
return nil, define.ErrEmptyID
1443
return nil, define.ErrDBClosed
1446
db, err := s.getDBCon()
1450
defer s.deferredCloseDBCon(db)
1453
var result time.Time
1454
return &result, db.View(func(tx *bolt.Tx) error {
1455
timeStampBucket, err := getExitCodeTimeStampBucket(tx)
1460
rawTimeStamp := timeStampBucket.Get(rawID)
1461
if rawTimeStamp == nil {
1462
return fmt.Errorf("getting exit-code time stamp of container %s from DB: %w", id, define.ErrNoSuchExitCode)
1465
if err := result.UnmarshalText(rawTimeStamp); err != nil {
1466
return fmt.Errorf("converting raw time stamp %v of container %s from DB: %w", rawTimeStamp, id, err)
1473
// PruneContainerExitCodes removes exit codes older than 5 minutes unless the associated
1474
// container still exists.
1475
func (s *BoltState) PruneContainerExitCodes() error {
1477
return define.ErrDBClosed
1480
db, err := s.getDBCon()
1484
defer s.deferredCloseDBCon(db)
1486
toRemoveIDs := []string{}
1488
threshold := time.Minute * 5
1489
err = db.View(func(tx *bolt.Tx) error {
1490
timeStampBucket, err := getExitCodeTimeStampBucket(tx)
1495
ctrsBucket, err := getCtrBucket(tx)
1500
return timeStampBucket.ForEach(func(rawID, rawTimeStamp []byte) error {
1501
if ctrsBucket.Bucket(rawID) != nil {
1502
// If the container still exists, don't prune
1503
// its exit code since we may still need it.
1506
var timeStamp time.Time
1507
if err := timeStamp.UnmarshalText(rawTimeStamp); err != nil {
1508
return fmt.Errorf("converting raw time stamp %v of container %s from DB: %w", rawTimeStamp, string(rawID), err)
1510
if time.Since(timeStamp) > threshold {
1511
toRemoveIDs = append(toRemoveIDs, string(rawID))
1517
return fmt.Errorf("reading exit codes to prune: %w", err)
1520
if len(toRemoveIDs) > 0 {
1521
err = db.Update(func(tx *bolt.Tx) error {
1522
exitCodeBucket, err := getExitCodeBucket(tx)
1526
timeStampBucket, err := getExitCodeTimeStampBucket(tx)
1532
for _, id := range toRemoveIDs {
1534
if err := exitCodeBucket.Delete(rawID); err != nil {
1535
if finalErr != nil {
1536
logrus.Error(finalErr)
1538
finalErr = fmt.Errorf("removing exit code of container %s from DB: %w", id, err)
1540
if err := timeStampBucket.Delete(rawID); err != nil {
1541
if finalErr != nil {
1542
logrus.Error(finalErr)
1544
finalErr = fmt.Errorf("removing exit code timestamp of container %s from DB: %w", id, err)
1551
return fmt.Errorf("pruning exit codes: %w", err)
1558
// AddExecSession adds an exec session to the state.
1559
func (s *BoltState) AddExecSession(ctr *Container, session *ExecSession) error {
1561
return define.ErrDBClosed
1565
return define.ErrCtrRemoved
1568
db, err := s.getDBCon()
1572
defer s.deferredCloseDBCon(db)
1574
ctrID := []byte(ctr.ID())
1575
sessionID := []byte(session.ID())
1577
err = db.Update(func(tx *bolt.Tx) error {
1578
execBucket, err := getExecBucket(tx)
1582
ctrBucket, err := getCtrBucket(tx)
1587
dbCtr := ctrBucket.Bucket(ctrID)
1590
return fmt.Errorf("container %s is not present in the database: %w", ctr.ID(), define.ErrNoSuchCtr)
1593
ctrExecSessionBucket, err := dbCtr.CreateBucketIfNotExists(execBkt)
1595
return fmt.Errorf("creating exec sessions bucket for container %s: %w", ctr.ID(), err)
1598
execExists := execBucket.Get(sessionID)
1599
if execExists != nil {
1600
return fmt.Errorf("an exec session with ID %s already exists: %w", session.ID(), define.ErrExecSessionExists)
1603
if err := execBucket.Put(sessionID, ctrID); err != nil {
1604
return fmt.Errorf("adding exec session %s to DB: %w", session.ID(), err)
1607
if err := ctrExecSessionBucket.Put(sessionID, ctrID); err != nil {
1608
return fmt.Errorf("adding exec session %s to container %s in DB: %w", session.ID(), ctr.ID(), err)
1616
// GetExecSession returns the ID of the container an exec session is associated
1618
func (s *BoltState) GetExecSession(id string) (string, error) {
1620
return "", define.ErrDBClosed
1624
return "", define.ErrEmptyID
1627
db, err := s.getDBCon()
1631
defer s.deferredCloseDBCon(db)
1634
err = db.View(func(tx *bolt.Tx) error {
1635
execBucket, err := getExecBucket(tx)
1640
ctr := execBucket.Get([]byte(id))
1642
return fmt.Errorf("no exec session with ID %s found: %w", id, define.ErrNoSuchExecSession)
1650
// RemoveExecSession removes references to the given exec session in the
1652
func (s *BoltState) RemoveExecSession(session *ExecSession) error {
1654
return define.ErrDBClosed
1657
db, err := s.getDBCon()
1661
defer s.deferredCloseDBCon(db)
1663
sessionID := []byte(session.ID())
1664
containerID := []byte(session.ContainerID())
1665
err = db.Update(func(tx *bolt.Tx) error {
1666
execBucket, err := getExecBucket(tx)
1670
ctrBucket, err := getCtrBucket(tx)
1675
sessionExists := execBucket.Get(sessionID)
1676
if sessionExists == nil {
1677
return define.ErrNoSuchExecSession
1679
// Check that container ID matches
1680
if string(sessionExists) != session.ContainerID() {
1681
return fmt.Errorf("database inconsistency: exec session %s points to container %s in state but %s in database: %w", session.ID(), session.ContainerID(), string(sessionExists), define.ErrInternal)
1684
if err := execBucket.Delete(sessionID); err != nil {
1685
return fmt.Errorf("removing exec session %s from database: %w", session.ID(), err)
1688
dbCtr := ctrBucket.Bucket(containerID)
1690
// State is inconsistent. We refer to a container that
1691
// is no longer in the state.
1692
// Return without error, to attempt to recover.
1696
ctrExecBucket := dbCtr.Bucket(execBkt)
1697
if ctrExecBucket == nil {
1698
// Again, state is inconsistent. We should have an exec
1699
// bucket, and it should have this session.
1700
// Again, nothing we can do, so proceed and try to
1705
ctrSessionExists := ctrExecBucket.Get(sessionID)
1706
if ctrSessionExists != nil {
1707
if err := ctrExecBucket.Delete(sessionID); err != nil {
1708
return fmt.Errorf("removing exec session %s from container %s in database: %w", session.ID(), session.ContainerID(), err)
1717
// GetContainerExecSessions retrieves the IDs of all exec sessions running in a
1718
// container that the database is aware of (IE, were added via AddExecSession).
1719
func (s *BoltState) GetContainerExecSessions(ctr *Container) ([]string, error) {
1721
return nil, define.ErrDBClosed
1725
return nil, define.ErrCtrRemoved
1728
db, err := s.getDBCon()
1732
defer s.deferredCloseDBCon(db)
1734
ctrID := []byte(ctr.ID())
1735
sessions := []string{}
1736
err = db.View(func(tx *bolt.Tx) error {
1737
ctrBucket, err := getCtrBucket(tx)
1742
dbCtr := ctrBucket.Bucket(ctrID)
1745
return define.ErrNoSuchCtr
1748
ctrExecSessions := dbCtr.Bucket(execBkt)
1749
if ctrExecSessions == nil {
1753
return ctrExecSessions.ForEach(func(id, unused []byte) error {
1754
sessions = append(sessions, string(id))
1762
return sessions, nil
1765
// RemoveContainerExecSessions removes all exec sessions attached to a given
1767
func (s *BoltState) RemoveContainerExecSessions(ctr *Container) error {
1769
return define.ErrDBClosed
1773
return define.ErrCtrRemoved
1776
db, err := s.getDBCon()
1780
defer s.deferredCloseDBCon(db)
1782
ctrID := []byte(ctr.ID())
1783
sessions := []string{}
1785
err = db.Update(func(tx *bolt.Tx) error {
1786
execBucket, err := getExecBucket(tx)
1790
ctrBucket, err := getCtrBucket(tx)
1795
dbCtr := ctrBucket.Bucket(ctrID)
1798
return define.ErrNoSuchCtr
1801
ctrExecSessions := dbCtr.Bucket(execBkt)
1802
if ctrExecSessions == nil {
1806
err = ctrExecSessions.ForEach(func(id, unused []byte) error {
1807
sessions = append(sessions, string(id))
1814
for _, session := range sessions {
1815
if err := ctrExecSessions.Delete([]byte(session)); err != nil {
1816
return fmt.Errorf("removing container %s exec session %s from database: %w", ctr.ID(), session, err)
1818
// Check if the session exists in the global table
1819
// before removing. It should, but in cases where the DB
1820
// has become inconsistent, we should try and proceed
1821
// so we can recover.
1822
sessionExists := execBucket.Get([]byte(session))
1823
if sessionExists == nil {
1826
if string(sessionExists) != ctr.ID() {
1827
return fmt.Errorf("database mismatch: exec session %s is associated with containers %s and %s: %w", session, ctr.ID(), string(sessionExists), define.ErrInternal)
1829
if err := execBucket.Delete([]byte(session)); err != nil {
1830
return fmt.Errorf("removing container %s exec session %s from exec sessions: %w", ctr.ID(), session, err)
1839
// RewriteContainerConfig rewrites a container's configuration.
1840
// WARNING: This function is DANGEROUS. Do not use without reading the full
1841
// comment on this function in state.go.
1842
func (s *BoltState) RewriteContainerConfig(ctr *Container, newCfg *ContainerConfig) error {
1844
return define.ErrDBClosed
1848
return define.ErrCtrRemoved
1851
newCfgJSON, err := json.Marshal(newCfg)
1853
return fmt.Errorf("marshalling new configuration JSON for container %s: %w", ctr.ID(), err)
1856
db, err := s.getDBCon()
1860
defer s.deferredCloseDBCon(db)
1862
err = db.Update(func(tx *bolt.Tx) error {
1863
ctrBkt, err := getCtrBucket(tx)
1868
ctrDB := ctrBkt.Bucket([]byte(ctr.ID()))
1871
return fmt.Errorf("no container with ID %q found in DB: %w", ctr.ID(), define.ErrNoSuchCtr)
1874
if err := ctrDB.Put(configKey, newCfgJSON); err != nil {
1875
return fmt.Errorf("updating container %s config JSON: %w", ctr.ID(), err)
1883
// SafeRewriteContainerConfig rewrites a container's configuration in a more
1884
// limited fashion than RewriteContainerConfig. It is marked as safe to use
1885
// under most circumstances, unlike RewriteContainerConfig.
1886
// DO NOT USE TO: Change container dependencies, change pod membership, change
1887
// locks, change container ID.
1888
func (s *BoltState) SafeRewriteContainerConfig(ctr *Container, oldName, newName string, newCfg *ContainerConfig) error {
1890
return define.ErrDBClosed
1894
return define.ErrCtrRemoved
1897
if newName != "" && newCfg.Name != newName {
1898
return fmt.Errorf("new name %s for container %s must match name in given container config: %w", newName, ctr.ID(), define.ErrInvalidArg)
1900
if newName != "" && oldName == "" {
1901
return fmt.Errorf("must provide old name for container if a new name is given: %w", define.ErrInvalidArg)
1904
newCfgJSON, err := json.Marshal(newCfg)
1906
return fmt.Errorf("marshalling new configuration JSON for container %s: %w", ctr.ID(), err)
1909
db, err := s.getDBCon()
1913
defer s.deferredCloseDBCon(db)
1915
err = db.Update(func(tx *bolt.Tx) error {
1917
idBkt, err := getIDBucket(tx)
1921
namesBkt, err := getNamesBucket(tx)
1925
allCtrsBkt, err := getAllCtrsBucket(tx)
1931
if exists := namesBkt.Get([]byte(newName)); exists != nil {
1932
if string(exists) == ctr.ID() {
1933
// Name already associated with the ID
1934
// of this container. No need for a
1938
return fmt.Errorf("name %s already in use, cannot rename container %s: %w", newName, ctr.ID(), define.ErrCtrExists)
1943
// We do have to remove the old name. The other
1944
// buckets are ID-indexed so we just need to
1945
// overwrite the values there.
1946
if err := namesBkt.Delete([]byte(oldName)); err != nil {
1947
return fmt.Errorf("deleting container %s old name from DB for rename: %w", ctr.ID(), err)
1949
if err := idBkt.Put([]byte(ctr.ID()), []byte(newName)); err != nil {
1950
return fmt.Errorf("renaming container %s in ID bucket in DB: %w", ctr.ID(), err)
1952
if err := namesBkt.Put([]byte(newName), []byte(ctr.ID())); err != nil {
1953
return fmt.Errorf("adding new name %s for container %s in DB: %w", newName, ctr.ID(), err)
1955
if err := allCtrsBkt.Put([]byte(ctr.ID()), []byte(newName)); err != nil {
1956
return fmt.Errorf("renaming container %s in all containers bucket in DB: %w", ctr.ID(), err)
1958
if ctr.config.Pod != "" {
1959
podsBkt, err := getPodBucket(tx)
1963
podBkt := podsBkt.Bucket([]byte(ctr.config.Pod))
1965
return fmt.Errorf("bucket for pod %s does not exist: %w", ctr.config.Pod, define.ErrInternal)
1967
podCtrBkt := podBkt.Bucket(containersBkt)
1968
if podCtrBkt == nil {
1969
return fmt.Errorf("pod %s does not have a containers bucket: %w", ctr.config.Pod, define.ErrInternal)
1971
if err := podCtrBkt.Put([]byte(ctr.ID()), []byte(newName)); err != nil {
1972
return fmt.Errorf("renaming container %s in pod %s members bucket: %w", ctr.ID(), ctr.config.Pod, err)
1978
ctrBkt, err := getCtrBucket(tx)
1983
ctrDB := ctrBkt.Bucket([]byte(ctr.ID()))
1986
return fmt.Errorf("no container with ID %q found in DB: %w", ctr.ID(), define.ErrNoSuchCtr)
1989
if err := ctrDB.Put(configKey, newCfgJSON); err != nil {
1990
return fmt.Errorf("updating container %s config JSON: %w", ctr.ID(), err)
1998
// RewritePodConfig rewrites a pod's configuration.
1999
// WARNING: This function is DANGEROUS. Do not use without reading the full
2000
// comment on this function in state.go.
2001
func (s *BoltState) RewritePodConfig(pod *Pod, newCfg *PodConfig) error {
2003
return define.ErrDBClosed
2007
return define.ErrPodRemoved
2010
newCfgJSON, err := json.Marshal(newCfg)
2012
return fmt.Errorf("marshalling new configuration JSON for pod %s: %w", pod.ID(), err)
2015
db, err := s.getDBCon()
2019
defer s.deferredCloseDBCon(db)
2021
err = db.Update(func(tx *bolt.Tx) error {
2022
podBkt, err := getPodBucket(tx)
2027
podDB := podBkt.Bucket([]byte(pod.ID()))
2030
return fmt.Errorf("no pod with ID %s found in DB: %w", pod.ID(), define.ErrNoSuchPod)
2033
if err := podDB.Put(configKey, newCfgJSON); err != nil {
2034
return fmt.Errorf("updating pod %s config JSON: %w", pod.ID(), err)
2042
// RewriteVolumeConfig rewrites a volume's configuration.
2043
// WARNING: This function is DANGEROUS. Do not use without reading the full
2044
// comment on this function in state.go.
2045
func (s *BoltState) RewriteVolumeConfig(volume *Volume, newCfg *VolumeConfig) error {
2047
return define.ErrDBClosed
2051
return define.ErrVolumeRemoved
2054
newCfgJSON, err := json.Marshal(newCfg)
2056
return fmt.Errorf("marshalling new configuration JSON for volume %q: %w", volume.Name(), err)
2059
db, err := s.getDBCon()
2063
defer s.deferredCloseDBCon(db)
2065
err = db.Update(func(tx *bolt.Tx) error {
2066
volBkt, err := getVolBucket(tx)
2071
volDB := volBkt.Bucket([]byte(volume.Name()))
2073
volume.valid = false
2074
return fmt.Errorf("no volume with name %q found in DB: %w", volume.Name(), define.ErrNoSuchVolume)
2077
if err := volDB.Put(configKey, newCfgJSON); err != nil {
2078
return fmt.Errorf("updating volume %q config JSON: %w", volume.Name(), err)
2086
// Pod retrieves a pod given its full ID
2087
func (s *BoltState) Pod(id string) (*Pod, error) {
2089
return nil, define.ErrEmptyID
2093
return nil, define.ErrDBClosed
2099
pod.config = new(PodConfig)
2100
pod.state = new(podState)
2102
db, err := s.getDBCon()
2106
defer s.deferredCloseDBCon(db)
2108
err = db.View(func(tx *bolt.Tx) error {
2109
podBkt, err := getPodBucket(tx)
2114
return s.getPodFromDB(podID, pod, podBkt)
2123
// LookupPod retrieves a pod from full or unique partial ID or name
2124
func (s *BoltState) LookupPod(idOrName string) (*Pod, error) {
2126
return nil, define.ErrEmptyID
2130
return nil, define.ErrDBClosed
2134
pod.config = new(PodConfig)
2135
pod.state = new(podState)
2137
db, err := s.getDBCon()
2141
defer s.deferredCloseDBCon(db)
2143
err = db.View(func(tx *bolt.Tx) error {
2144
podBkt, err := getPodBucket(tx)
2149
namesBkt, err := getNamesBucket(tx)
2154
// First, check if the ID given was the actual pod ID
2156
podExists := podBkt.Bucket([]byte(idOrName))
2157
if podExists != nil {
2158
// A full pod ID was given.
2159
id = []byte(idOrName)
2160
return s.getPodFromDB(id, pod, podBkt)
2163
// Next, check if the full name was given
2165
fullID := namesBkt.Get([]byte(idOrName))
2167
// The name exists and maps to an ID.
2168
// However, we aren't yet sure if the ID is a pod.
2169
podExists = podBkt.Bucket(fullID)
2170
if podExists != nil {
2171
// A pod bucket matching the full ID was found.
2172
return s.getPodFromDB(fullID, pod, podBkt)
2174
// Don't error if we have a name match but it's not a
2175
// pod - there's a chance we have a pod with an ID
2176
// starting with those characters.
2177
// However, so we can return a good error, note whether
2178
// this is a container.
2181
// They did not give us a full pod name or ID.
2182
// Search for partial ID matches.
2184
err = podBkt.ForEach(func(checkID, checkName []byte) error {
2185
if strings.HasPrefix(string(checkID), idOrName) {
2187
return fmt.Errorf("more than one result for ID or name %s: %w", idOrName, define.ErrPodExists)
2199
return fmt.Errorf("%s is a container, not a pod: %w", idOrName, define.ErrNoSuchPod)
2201
return fmt.Errorf("no pod with name or ID %s found: %w", idOrName, define.ErrNoSuchPod)
2204
// We might have found a container ID, but it's OK
2205
// We'll just fail in getPodFromDB with ErrNoSuchPod
2206
return s.getPodFromDB(id, pod, podBkt)
2215
// HasPod checks if a pod with the given ID exists in the state
2216
func (s *BoltState) HasPod(id string) (bool, error) {
2218
return false, define.ErrEmptyID
2222
return false, define.ErrDBClosed
2229
db, err := s.getDBCon()
2233
defer s.deferredCloseDBCon(db)
2235
err = db.View(func(tx *bolt.Tx) error {
2236
podBkt, err := getPodBucket(tx)
2241
podDB := podBkt.Bucket(podID)
2255
// PodHasContainer checks if the given pod has a container with the given ID
2256
func (s *BoltState) PodHasContainer(pod *Pod, id string) (bool, error) {
2258
return false, define.ErrEmptyID
2262
return false, define.ErrDBClosed
2266
return false, define.ErrPodRemoved
2270
podID := []byte(pod.ID())
2274
db, err := s.getDBCon()
2278
defer s.deferredCloseDBCon(db)
2280
err = db.View(func(tx *bolt.Tx) error {
2281
podBkt, err := getPodBucket(tx)
2287
podDB := podBkt.Bucket(podID)
2290
return fmt.Errorf("pod %s not found in database: %w", pod.ID(), define.ErrNoSuchPod)
2293
// Get pod containers bucket
2294
podCtrs := podDB.Bucket(containersBkt)
2296
return fmt.Errorf("pod %s missing containers bucket in DB: %w", pod.ID(), define.ErrInternal)
2299
ctr := podCtrs.Get(ctrID)
2313
// PodContainersByID returns the IDs of all containers present in the given pod
2314
func (s *BoltState) PodContainersByID(pod *Pod) ([]string, error) {
2316
return nil, define.ErrDBClosed
2320
return nil, define.ErrPodRemoved
2323
podID := []byte(pod.ID())
2327
db, err := s.getDBCon()
2331
defer s.deferredCloseDBCon(db)
2333
err = db.View(func(tx *bolt.Tx) error {
2334
podBkt, err := getPodBucket(tx)
2340
podDB := podBkt.Bucket(podID)
2343
return fmt.Errorf("pod %s not found in database: %w", pod.ID(), define.ErrNoSuchPod)
2346
// Get pod containers bucket
2347
podCtrs := podDB.Bucket(containersBkt)
2349
return fmt.Errorf("pod %s missing containers bucket in DB: %w", pod.ID(), define.ErrInternal)
2352
// Iterate through all containers in the pod
2353
err = podCtrs.ForEach(func(id, val []byte) error {
2354
ctrs = append(ctrs, string(id))
2371
// PodContainers returns all the containers present in the given pod
2372
func (s *BoltState) PodContainers(pod *Pod) ([]*Container, error) {
2374
return nil, define.ErrDBClosed
2378
return nil, define.ErrPodRemoved
2381
podID := []byte(pod.ID())
2383
ctrs := []*Container{}
2385
db, err := s.getDBCon()
2389
defer s.deferredCloseDBCon(db)
2391
err = db.View(func(tx *bolt.Tx) error {
2392
podBkt, err := getPodBucket(tx)
2397
ctrBkt, err := getCtrBucket(tx)
2403
podDB := podBkt.Bucket(podID)
2406
return fmt.Errorf("pod %s not found in database: %w", pod.ID(), define.ErrNoSuchPod)
2409
// Get pod containers bucket
2410
podCtrs := podDB.Bucket(containersBkt)
2412
return fmt.Errorf("pod %s missing containers bucket in DB: %w", pod.ID(), define.ErrInternal)
2415
// Iterate through all containers in the pod
2416
err = podCtrs.ForEach(func(id, val []byte) error {
2417
newCtr := new(Container)
2418
newCtr.config = new(ContainerConfig)
2419
newCtr.state = new(ContainerState)
2420
ctrs = append(ctrs, newCtr)
2422
return s.getContainerFromDB(id, newCtr, ctrBkt, false)
2437
// AddVolume adds the given volume to the state. It also adds ctrDepID to
2438
// the sub bucket holding the container dependencies that this volume has
2439
func (s *BoltState) AddVolume(volume *Volume) error {
2441
return define.ErrDBClosed
2445
return define.ErrVolumeRemoved
2448
volName := []byte(volume.Name())
2450
volConfigJSON, err := json.Marshal(volume.config)
2452
return fmt.Errorf("marshalling volume %s config to JSON: %w", volume.Name(), err)
2455
// Volume state is allowed to not exist
2456
var volStateJSON []byte
2457
if volume.state != nil {
2458
volStateJSON, err = json.Marshal(volume.state)
2460
return fmt.Errorf("marshalling volume %s state to JSON: %w", volume.Name(), err)
2464
db, err := s.getDBCon()
2468
defer s.deferredCloseDBCon(db)
2470
err = db.Update(func(tx *bolt.Tx) error {
2471
volBkt, err := getVolBucket(tx)
2476
allVolsBkt, err := getAllVolsBucket(tx)
2481
volCtrsBkt, err := getVolumeContainersBucket(tx)
2486
// Check if we already have a volume with the given name
2487
volExists := allVolsBkt.Get(volName)
2488
if volExists != nil {
2489
return fmt.Errorf("name %s is in use: %w", volume.Name(), define.ErrVolumeExists)
2492
// We are good to add the volume
2493
// Make a bucket for it
2494
newVol, err := volBkt.CreateBucket(volName)
2496
return fmt.Errorf("creating bucket for volume %s: %w", volume.Name(), err)
2499
// Make a subbucket for the containers using the volume. Dependent container IDs will be addedremoved to
2500
// this bucket in addcontainer/removeContainer
2501
if _, err := newVol.CreateBucket(volDependenciesBkt); err != nil {
2502
return fmt.Errorf("creating bucket for containers using volume %s: %w", volume.Name(), err)
2505
if err := newVol.Put(configKey, volConfigJSON); err != nil {
2506
return fmt.Errorf("storing volume %s configuration in DB: %w", volume.Name(), err)
2509
if volStateJSON != nil {
2510
if err := newVol.Put(stateKey, volStateJSON); err != nil {
2511
return fmt.Errorf("storing volume %s state in DB: %w", volume.Name(), err)
2515
if volume.config.StorageID != "" {
2516
if err := volCtrsBkt.Put([]byte(volume.config.StorageID), volName); err != nil {
2517
return fmt.Errorf("storing volume %s container ID in DB: %w", volume.Name(), err)
2521
if err := allVolsBkt.Put(volName, volName); err != nil {
2522
return fmt.Errorf("storing volume %s in all volumes bucket in DB: %w", volume.Name(), err)
2530
// RemoveVolume removes the given volume from the state
2531
func (s *BoltState) RemoveVolume(volume *Volume) error {
2533
return define.ErrDBClosed
2536
volName := []byte(volume.Name())
2538
db, err := s.getDBCon()
2542
defer s.deferredCloseDBCon(db)
2544
err = db.Update(func(tx *bolt.Tx) error {
2545
volBkt, err := getVolBucket(tx)
2550
allVolsBkt, err := getAllVolsBucket(tx)
2555
ctrBkt, err := getCtrBucket(tx)
2560
volCtrIDBkt, err := getVolumeContainersBucket(tx)
2565
// Check if the volume exists
2566
volDB := volBkt.Bucket(volName)
2568
volume.valid = false
2569
return fmt.Errorf("volume %s does not exist in DB: %w", volume.Name(), define.ErrNoSuchVolume)
2572
// Check if volume is not being used by any container
2573
// This should never be nil
2574
// But if it is, we can assume that no containers are using
2576
volCtrsBkt := volDB.Bucket(volDependenciesBkt)
2577
if volCtrsBkt != nil {
2579
err = volCtrsBkt.ForEach(func(id, value []byte) error {
2580
// Alright, this is ugly.
2581
// But we need it to work around the change in
2582
// volume dependency handling, to make sure that
2583
// older Podman versions don't cause DB
2585
// Look up all dependencies and see that they
2586
// still exist before appending.
2587
ctrExists := ctrBkt.Bucket(id)
2588
if ctrExists == nil {
2592
deps = append(deps, string(id))
2596
return fmt.Errorf("getting list of dependencies from dependencies bucket for volumes %q: %w", volume.Name(), err)
2599
return fmt.Errorf("volume %s is being used by container(s) %s: %w", volume.Name(), strings.Join(deps, ","), define.ErrVolumeBeingUsed)
2603
// volume is ready for removal
2604
// Let's kick it out
2605
if err := allVolsBkt.Delete(volName); err != nil {
2606
return fmt.Errorf("removing volume %s from all volumes bucket in DB: %w", volume.Name(), err)
2608
if err := volBkt.DeleteBucket(volName); err != nil {
2609
return fmt.Errorf("removing volume %s from DB: %w", volume.Name(), err)
2611
if volume.config.StorageID != "" {
2612
if err := volCtrIDBkt.Delete([]byte(volume.config.StorageID)); err != nil {
2613
return fmt.Errorf("removing volume %s container ID from DB: %w", volume.Name(), err)
2622
// UpdateVolume updates the volume's state from the database.
2623
func (s *BoltState) UpdateVolume(volume *Volume) error {
2625
return define.ErrDBClosed
2629
return define.ErrVolumeRemoved
2632
newState := new(VolumeState)
2633
volumeName := []byte(volume.Name())
2635
db, err := s.getDBCon()
2639
defer s.deferredCloseDBCon(db)
2641
err = db.View(func(tx *bolt.Tx) error {
2642
volBucket, err := getVolBucket(tx)
2647
volToUpdate := volBucket.Bucket(volumeName)
2648
if volToUpdate == nil {
2649
volume.valid = false
2650
return fmt.Errorf("no volume with name %s found in database: %w", volume.Name(), define.ErrNoSuchVolume)
2653
stateBytes := volToUpdate.Get(stateKey)
2654
if stateBytes == nil {
2655
// Having no state is valid.
2656
// Return nil, use the empty state.
2660
if err := json.Unmarshal(stateBytes, newState); err != nil {
2661
return fmt.Errorf("unmarshalling volume %s state: %w", volume.Name(), err)
2670
volume.state = newState
2675
// SaveVolume saves the volume's state to the database.
2676
func (s *BoltState) SaveVolume(volume *Volume) error {
2678
return define.ErrDBClosed
2682
return define.ErrVolumeRemoved
2685
volumeName := []byte(volume.Name())
2687
var newStateJSON []byte
2688
if volume.state != nil {
2689
stateJSON, err := json.Marshal(volume.state)
2691
return fmt.Errorf("marshalling volume %s state to JSON: %w", volume.Name(), err)
2693
newStateJSON = stateJSON
2696
db, err := s.getDBCon()
2700
defer s.deferredCloseDBCon(db)
2702
err = db.Update(func(tx *bolt.Tx) error {
2703
volBucket, err := getVolBucket(tx)
2708
volToUpdate := volBucket.Bucket(volumeName)
2709
if volToUpdate == nil {
2710
volume.valid = false
2711
return fmt.Errorf("no volume with name %s found in database: %w", volume.Name(), define.ErrNoSuchVolume)
2714
return volToUpdate.Put(stateKey, newStateJSON)
2719
// AllVolumes returns all volumes present in the state
2720
func (s *BoltState) AllVolumes() ([]*Volume, error) {
2722
return nil, define.ErrDBClosed
2725
volumes := []*Volume{}
2727
db, err := s.getDBCon()
2731
defer s.deferredCloseDBCon(db)
2733
err = db.View(func(tx *bolt.Tx) error {
2734
allVolsBucket, err := getAllVolsBucket(tx)
2739
volBucket, err := getVolBucket(tx)
2743
err = allVolsBucket.ForEach(func(id, name []byte) error {
2744
volExists := volBucket.Bucket(id)
2745
// This check can be removed if performance becomes an
2746
// issue, but much less helpful errors will be produced
2747
if volExists == nil {
2748
return fmt.Errorf("inconsistency in state - volume %s is in all volumes bucket but volume not found: %w", string(id), define.ErrInternal)
2751
volume := new(Volume)
2752
volume.config = new(VolumeConfig)
2753
volume.state = new(VolumeState)
2755
if err := s.getVolumeFromDB(id, volume, volBucket); err != nil {
2756
if !errors.Is(err, define.ErrNSMismatch) {
2757
logrus.Errorf("Retrieving volume %s from the database: %v", string(id), err)
2760
volumes = append(volumes, volume)
2774
// Volume retrieves a volume from full name
2775
func (s *BoltState) Volume(name string) (*Volume, error) {
2777
return nil, define.ErrEmptyID
2781
return nil, define.ErrDBClosed
2784
volName := []byte(name)
2786
volume := new(Volume)
2787
volume.config = new(VolumeConfig)
2788
volume.state = new(VolumeState)
2790
db, err := s.getDBCon()
2794
defer s.deferredCloseDBCon(db)
2796
err = db.View(func(tx *bolt.Tx) error {
2797
volBkt, err := getVolBucket(tx)
2802
return s.getVolumeFromDB(volName, volume, volBkt)
2811
// LookupVolume locates a volume from a partial name.
2812
func (s *BoltState) LookupVolume(name string) (*Volume, error) {
2814
return nil, define.ErrEmptyID
2818
return nil, define.ErrDBClosed
2821
volName := []byte(name)
2823
volume := new(Volume)
2824
volume.config = new(VolumeConfig)
2825
volume.state = new(VolumeState)
2827
db, err := s.getDBCon()
2831
defer s.deferredCloseDBCon(db)
2833
err = db.View(func(tx *bolt.Tx) error {
2834
volBkt, err := getVolBucket(tx)
2839
allVolsBkt, err := getAllVolsBucket(tx)
2844
// Check for exact match on name
2845
volDB := volBkt.Bucket(volName)
2847
return s.getVolumeFromDB(volName, volume, volBkt)
2850
// No exact match. Search all names.
2852
err = allVolsBkt.ForEach(func(checkName, checkName2 []byte) error {
2853
if strings.HasPrefix(string(checkName), name) {
2855
return fmt.Errorf("more than one result for volume name %q: %w", name, define.ErrVolumeExists)
2867
return fmt.Errorf("no volume with name %q found: %w", name, define.ErrNoSuchVolume)
2870
return s.getVolumeFromDB(volName, volume, volBkt)
2879
// HasVolume returns true if the given volume exists in the state, otherwise it returns false
2880
func (s *BoltState) HasVolume(name string) (bool, error) {
2882
return false, define.ErrEmptyID
2886
return false, define.ErrDBClosed
2889
volName := []byte(name)
2893
db, err := s.getDBCon()
2897
defer s.deferredCloseDBCon(db)
2899
err = db.View(func(tx *bolt.Tx) error {
2900
volBkt, err := getVolBucket(tx)
2905
volDB := volBkt.Bucket(volName)
2919
// VolumeInUse checks if any container is using the volume
2920
// It returns a slice of the IDs of the containers using the given
2921
// volume. If the slice is empty, no containers use the given volume
2922
func (s *BoltState) VolumeInUse(volume *Volume) ([]string, error) {
2924
return nil, define.ErrDBClosed
2928
return nil, define.ErrVolumeRemoved
2931
depCtrs := []string{}
2933
db, err := s.getDBCon()
2937
defer s.deferredCloseDBCon(db)
2939
err = db.View(func(tx *bolt.Tx) error {
2940
volBucket, err := getVolBucket(tx)
2945
ctrBucket, err := getCtrBucket(tx)
2950
volDB := volBucket.Bucket([]byte(volume.Name()))
2952
volume.valid = false
2953
return fmt.Errorf("no volume with name %s found in DB: %w", volume.Name(), define.ErrNoSuchVolume)
2956
dependsBkt := volDB.Bucket(volDependenciesBkt)
2957
if dependsBkt == nil {
2958
return fmt.Errorf("volume %s has no dependencies bucket: %w", volume.Name(), define.ErrInternal)
2961
// Iterate through and add dependencies
2962
err = dependsBkt.ForEach(func(id, value []byte) error {
2963
// Look up all dependencies and see that they
2964
// still exist before appending.
2965
ctrExists := ctrBucket.Bucket(id)
2966
if ctrExists == nil {
2970
depCtrs = append(depCtrs, string(id))
2987
// AddPod adds the given pod to the state.
2988
func (s *BoltState) AddPod(pod *Pod) error {
2990
return define.ErrDBClosed
2994
return define.ErrPodRemoved
2997
podID := []byte(pod.ID())
2998
podName := []byte(pod.Name())
3000
podConfigJSON, err := json.Marshal(pod.config)
3002
return fmt.Errorf("marshalling pod %s config to JSON: %w", pod.ID(), err)
3005
podStateJSON, err := json.Marshal(pod.state)
3007
return fmt.Errorf("marshalling pod %s state to JSON: %w", pod.ID(), err)
3010
db, err := s.getDBCon()
3014
defer s.deferredCloseDBCon(db)
3016
err = db.Update(func(tx *bolt.Tx) error {
3017
podBkt, err := getPodBucket(tx)
3022
allPodsBkt, err := getAllPodsBucket(tx)
3027
idsBkt, err := getIDBucket(tx)
3032
namesBkt, err := getNamesBucket(tx)
3037
// Check if we already have something with the given ID and name
3038
idExist := idsBkt.Get(podID)
3040
err = define.ErrPodExists
3041
if allPodsBkt.Get(idExist) == nil {
3042
err = define.ErrCtrExists
3044
return fmt.Errorf("ID \"%s\" is in use: %w", pod.ID(), err)
3046
nameExist := namesBkt.Get(podName)
3047
if nameExist != nil {
3048
err = define.ErrPodExists
3049
if allPodsBkt.Get(nameExist) == nil {
3050
err = define.ErrCtrExists
3052
return fmt.Errorf("name \"%s\" is in use: %w", pod.Name(), err)
3055
// We are good to add the pod
3056
// Make a bucket for it
3057
newPod, err := podBkt.CreateBucket(podID)
3059
return fmt.Errorf("creating bucket for pod %s: %w", pod.ID(), err)
3062
// Make a subbucket for pod containers
3063
if _, err := newPod.CreateBucket(containersBkt); err != nil {
3064
return fmt.Errorf("creating bucket for pod %s containers: %w", pod.ID(), err)
3067
if err := newPod.Put(configKey, podConfigJSON); err != nil {
3068
return fmt.Errorf("storing pod %s configuration in DB: %w", pod.ID(), err)
3071
if err := newPod.Put(stateKey, podStateJSON); err != nil {
3072
return fmt.Errorf("storing pod %s state JSON in DB: %w", pod.ID(), err)
3075
// Add us to the ID and names buckets
3076
if err := idsBkt.Put(podID, podName); err != nil {
3077
return fmt.Errorf("storing pod %s ID in DB: %w", pod.ID(), err)
3079
if err := namesBkt.Put(podName, podID); err != nil {
3080
return fmt.Errorf("storing pod %s name in DB: %w", pod.Name(), err)
3082
if err := allPodsBkt.Put(podID, podName); err != nil {
3083
return fmt.Errorf("storing pod %s in all pods bucket in DB: %w", pod.ID(), err)
3095
// RemovePod removes the given pod from the state
3096
// Only empty pods can be removed
3097
func (s *BoltState) RemovePod(pod *Pod) error {
3099
return define.ErrDBClosed
3103
return define.ErrPodRemoved
3106
podID := []byte(pod.ID())
3107
podName := []byte(pod.Name())
3109
db, err := s.getDBCon()
3113
defer s.deferredCloseDBCon(db)
3115
err = db.Update(func(tx *bolt.Tx) error {
3116
podBkt, err := getPodBucket(tx)
3121
allPodsBkt, err := getAllPodsBucket(tx)
3126
idsBkt, err := getIDBucket(tx)
3131
namesBkt, err := getNamesBucket(tx)
3136
// Check if the pod exists
3137
podDB := podBkt.Bucket(podID)
3140
return fmt.Errorf("pod %s does not exist in DB: %w", pod.ID(), define.ErrNoSuchPod)
3143
// Check if pod is empty
3144
// This should never be nil
3145
// But if it is, we can assume there are no containers in the
3147
// So let's eject the malformed pod without error.
3148
podCtrsBkt := podDB.Bucket(containersBkt)
3149
if podCtrsBkt != nil {
3150
cursor := podCtrsBkt.Cursor()
3151
if id, _ := cursor.First(); id != nil {
3152
return fmt.Errorf("pod %s is not empty: %w", pod.ID(), define.ErrCtrExists)
3156
// Pod is empty, and ready for removal
3157
// Let's kick it out
3158
if err := idsBkt.Delete(podID); err != nil {
3159
return fmt.Errorf("removing pod %s ID from DB: %w", pod.ID(), err)
3161
if err := namesBkt.Delete(podName); err != nil {
3162
return fmt.Errorf("removing pod %s name (%s) from DB: %w", pod.ID(), pod.Name(), err)
3164
if err := allPodsBkt.Delete(podID); err != nil {
3165
return fmt.Errorf("removing pod %s ID from all pods bucket in DB: %w", pod.ID(), err)
3167
if err := podBkt.DeleteBucket(podID); err != nil {
3168
return fmt.Errorf("removing pod %s from DB: %w", pod.ID(), err)
3180
// RemovePodContainers removes all containers in a pod
3181
func (s *BoltState) RemovePodContainers(pod *Pod) error {
3183
return define.ErrDBClosed
3187
return define.ErrPodRemoved
3190
podID := []byte(pod.ID())
3192
db, err := s.getDBCon()
3196
defer s.deferredCloseDBCon(db)
3198
err = db.Update(func(tx *bolt.Tx) error {
3199
podBkt, err := getPodBucket(tx)
3204
ctrBkt, err := getCtrBucket(tx)
3209
allCtrsBkt, err := getAllCtrsBucket(tx)
3214
idsBkt, err := getIDBucket(tx)
3219
namesBkt, err := getNamesBucket(tx)
3224
// Check if the pod exists
3225
podDB := podBkt.Bucket(podID)
3228
return fmt.Errorf("pod %s does not exist in DB: %w", pod.ID(), define.ErrNoSuchPod)
3231
podCtrsBkt := podDB.Bucket(containersBkt)
3232
if podCtrsBkt == nil {
3233
return fmt.Errorf("pod %s does not have a containers bucket: %w", pod.ID(), define.ErrInternal)
3236
// Traverse all containers in the pod with a cursor
3237
// for-each has issues with data mutation
3238
err = podCtrsBkt.ForEach(func(id, name []byte) error {
3239
// Get the container so we can check dependencies
3240
ctr := ctrBkt.Bucket(id)
3242
// This should never happen
3243
// State is inconsistent
3244
return fmt.Errorf("pod %s referenced nonexistent container %s: %w", pod.ID(), string(id), define.ErrNoSuchCtr)
3246
ctrDeps := ctr.Bucket(dependenciesBkt)
3247
// This should never be nil, but if it is, we're
3248
// removing it anyways, so continue if it is
3250
err = ctrDeps.ForEach(func(depID, name []byte) error {
3251
exists := podCtrsBkt.Get(depID)
3253
return fmt.Errorf("container %s has dependency %s outside of pod %s: %w", string(id), string(depID), pod.ID(), define.ErrCtrExists)
3262
// Dependencies are set, we're clear to remove
3264
if err := ctrBkt.DeleteBucket(id); err != nil {
3265
return fmt.Errorf("deleting container %s from DB: %w", string(id), define.ErrInternal)
3268
if err := idsBkt.Delete(id); err != nil {
3269
return fmt.Errorf("deleting container %s ID in DB: %w", string(id), err)
3272
if err := namesBkt.Delete(name); err != nil {
3273
return fmt.Errorf("deleting container %s name in DB: %w", string(id), err)
3276
if err := allCtrsBkt.Delete(id); err != nil {
3277
return fmt.Errorf("deleting container %s ID from all containers bucket in DB: %w", string(id), err)
3286
// Delete and recreate the bucket to empty it
3287
if err := podDB.DeleteBucket(containersBkt); err != nil {
3288
return fmt.Errorf("removing pod %s containers bucket: %w", pod.ID(), err)
3290
if _, err := podDB.CreateBucket(containersBkt); err != nil {
3291
return fmt.Errorf("recreating pod %s containers bucket: %w", pod.ID(), err)
3303
// AddContainerToPod adds the given container to an existing pod
3304
// The container will be added to the state and the pod
3305
func (s *BoltState) AddContainerToPod(pod *Pod, ctr *Container) error {
3307
return define.ErrDBClosed
3311
return define.ErrPodRemoved
3315
return define.ErrCtrRemoved
3318
if ctr.config.Pod != pod.ID() {
3319
return fmt.Errorf("container %s is not part of pod %s: %w", ctr.ID(), pod.ID(), define.ErrNoSuchCtr)
3322
return s.addContainer(ctr, pod)
3325
// RemoveContainerFromPod removes a container from an existing pod
3326
// The container will also be removed from the state
3327
func (s *BoltState) RemoveContainerFromPod(pod *Pod, ctr *Container) error {
3329
return define.ErrDBClosed
3333
return define.ErrPodRemoved
3336
if ctr.config.Pod == "" {
3337
return fmt.Errorf("container %s is not part of a pod, use RemoveContainer instead: %w", ctr.ID(), define.ErrNoSuchPod)
3340
if ctr.config.Pod != pod.ID() {
3341
return fmt.Errorf("container %s is not part of pod %s: %w", ctr.ID(), pod.ID(), define.ErrInvalidArg)
3344
db, err := s.getDBCon()
3348
defer s.deferredCloseDBCon(db)
3350
err = db.Update(func(tx *bolt.Tx) error {
3351
return s.removeContainer(ctr, pod, tx)
3356
// UpdatePod updates a pod's state from the database
3357
func (s *BoltState) UpdatePod(pod *Pod) error {
3359
return define.ErrDBClosed
3363
return define.ErrPodRemoved
3366
newState := new(podState)
3368
db, err := s.getDBCon()
3372
defer s.deferredCloseDBCon(db)
3374
podID := []byte(pod.ID())
3376
err = db.View(func(tx *bolt.Tx) error {
3377
podBkt, err := getPodBucket(tx)
3382
podDB := podBkt.Bucket(podID)
3385
return fmt.Errorf("no pod with ID %s found in database: %w", pod.ID(), define.ErrNoSuchPod)
3388
// Get the pod state JSON
3389
podStateBytes := podDB.Get(stateKey)
3390
if podStateBytes == nil {
3391
return fmt.Errorf("pod %s is missing state key in DB: %w", pod.ID(), define.ErrInternal)
3394
if err := json.Unmarshal(podStateBytes, newState); err != nil {
3395
return fmt.Errorf("unmarshalling pod %s state JSON: %w", pod.ID(), err)
3404
pod.state = newState
3409
// SavePod saves a pod's state to the database
3410
func (s *BoltState) SavePod(pod *Pod) error {
3412
return define.ErrDBClosed
3416
return define.ErrPodRemoved
3419
stateJSON, err := json.Marshal(pod.state)
3421
return fmt.Errorf("marshalling pod %s state to JSON: %w", pod.ID(), err)
3424
db, err := s.getDBCon()
3428
defer s.deferredCloseDBCon(db)
3430
podID := []byte(pod.ID())
3432
err = db.Update(func(tx *bolt.Tx) error {
3433
podBkt, err := getPodBucket(tx)
3438
podDB := podBkt.Bucket(podID)
3441
return fmt.Errorf("no pod with ID %s found in database: %w", pod.ID(), define.ErrNoSuchPod)
3444
// Set the pod state JSON
3445
if err := podDB.Put(stateKey, stateJSON); err != nil {
3446
return fmt.Errorf("updating pod %s state in database: %w", pod.ID(), err)
3458
// AllPods returns all pods present in the state
3459
func (s *BoltState) AllPods() ([]*Pod, error) {
3461
return nil, define.ErrDBClosed
3466
db, err := s.getDBCon()
3470
defer s.deferredCloseDBCon(db)
3472
err = db.View(func(tx *bolt.Tx) error {
3473
allPodsBucket, err := getAllPodsBucket(tx)
3478
podBucket, err := getPodBucket(tx)
3483
err = allPodsBucket.ForEach(func(id, name []byte) error {
3484
podExists := podBucket.Bucket(id)
3485
// This check can be removed if performance becomes an
3486
// issue, but much less helpful errors will be produced
3487
if podExists == nil {
3488
return fmt.Errorf("inconsistency in state - pod %s is in all pods bucket but pod not found: %w", string(id), define.ErrInternal)
3492
pod.config = new(PodConfig)
3493
pod.state = new(podState)
3495
if err := s.getPodFromDB(id, pod, podBucket); err != nil {
3496
if !errors.Is(err, define.ErrNSMismatch) {
3497
logrus.Errorf("Retrieving pod %s from the database: %v", string(id), err)
3500
pods = append(pods, pod)
3514
// ContainerIDIsVolume checks if the given c/storage container ID is used as
3515
// backing storage for a volume.
3516
func (s *BoltState) ContainerIDIsVolume(id string) (bool, error) {
3518
return false, define.ErrDBClosed
3523
db, err := s.getDBCon()
3527
defer s.deferredCloseDBCon(db)
3529
err = db.View(func(tx *bolt.Tx) error {
3530
volCtrsBkt, err := getVolumeContainersBucket(tx)
3535
volName := volCtrsBkt.Get([]byte(id))