github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/state/container.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package state 5 6 import ( 7 "github.com/juju/mgo/v3/bson" 8 "github.com/juju/mgo/v3/txn" 9 10 "github.com/juju/juju/core/container" 11 ) 12 13 // machineContainers holds the machine ids of all the containers belonging to a parent machine. 14 // All machines have an associated container ref doc, regardless of whether they host any containers. 15 type machineContainers struct { 16 DocID string `bson:"_id"` 17 Id string `bson:"machineid"` 18 ModelUUID string `bson:"model-uuid"` 19 Children []string `bson:",omitempty"` 20 } 21 22 func addChildToContainerRefOp(mb modelBackend, parentId string, childId string) txn.Op { 23 return txn.Op{ 24 C: containerRefsC, 25 Id: mb.docID(parentId), 26 Assert: txn.DocExists, 27 Update: bson.D{{"$addToSet", bson.D{{"children", childId}}}}, 28 } 29 } 30 31 func insertNewContainerRefOp(mb modelBackend, machineId string, children ...string) txn.Op { 32 return txn.Op{ 33 C: containerRefsC, 34 Id: mb.docID(machineId), 35 Assert: txn.DocMissing, 36 Insert: &machineContainers{ 37 Id: machineId, 38 Children: children, 39 }, 40 } 41 } 42 43 // removeContainerRefOps returns the txn.Op's necessary to remove a machine container record. 44 // These include removing the record itself and updating the host machine's children property. 45 func removeContainerRefOps(mb modelBackend, machineId string) []txn.Op { 46 removeRefOp := txn.Op{ 47 C: containerRefsC, 48 Id: mb.docID(machineId), 49 Assert: txn.DocExists, 50 Remove: true, 51 } 52 // If the machine is a container, figure out its parent host. 53 parentId := container.ParentId(machineId) 54 if parentId == "" { 55 return []txn.Op{removeRefOp} 56 } 57 removeParentRefOp := txn.Op{ 58 C: containerRefsC, 59 Id: mb.docID(parentId), 60 Assert: txn.DocExists, 61 Update: bson.D{{"$pull", bson.D{{"children", machineId}}}}, 62 } 63 return []txn.Op{removeRefOp, removeParentRefOp} 64 }