What an instance has and a call can change while it lives: disks attached and detached (and their
autoDelete flag), access configs added and deleted, scheduling, the service account and
deletion protection. Each is an operation that holds the instance, and its change lands when the
operation ends; a failed operation leaves the instance as it was.
Attaching is held to what the documentation says of persistent disks: a read-write disk is
attached to one instance at a time, a read-only one to many, and not both; a disk in another zone
is not there. Scheduling and the service account change only a TERMINATED instance, as the
document says of setScheduling.
The boot disk's device name.
22pub(crate) const BOOT_DEVICE: &str = "persistent-disk-0";
The document: "You can attach up to 128 persistent disks" is the mock's limit, as maximumPersistentDisks.
24const MAX_DISKS: usize = 128;
What an operation on an instance changes when it ends.
An operation on an instance (and the disk it uses, if any), which holds both until it ends.
45 fn instance_op(&mut self, zone: &str, name: &str, kind: &str, change: InstChange, disk: Option<String>) -> Response { 46 let id = self.instances[&(zone.to_string(), name.to_string())].id; 47 let effect = Effect::Instance { zone: zone.to_string(), name: name.to_string(), change, disk: disk.clone() }; 48 let after = self.config.generic; 49 let op = self.start_op(Some(zone), kind, ("instances", name.to_string(), id.to_string()), effect, after, None); 50 if let Some(i) = self.instances.get_mut(&(zone.to_string(), name.to_string())) { 51 i.busy = Some(op); 52 } 53 if let Some(d) = disk.and_then(|d| self.disks.get_mut(&(zone.to_string(), d))) { 54 d.busy = Some(op); 55 } 56 json_response(200, &self.op_json(&self.ops[&op])) 57 }
The operation ended: the change lands if it succeeded, and what it held is free.
60 pub(crate) fn instance_changed(&mut self, zone: &str, name: &str, change: InstChange, disk: Option<String>, ok: bool) { 61 if let Some(d) = disk.and_then(|d| self.disks.get_mut(&(zone.to_string(), d))) { 62 d.busy = None; 63 } 64 let key = (zone.to_string(), name.to_string()); 65 let wants_ip = matches!(&change, InstChange::AddAccess(a) if a.nat_ip.is_none()) && self.instances.get(&key).is_some_and(|i| i.status == "RUNNING"); 66 let ip = if ok && wants_ip { Some(self.next_nat()) } else { None }; 67 let Some(i) = self.instances.get_mut(&key) else { return }; 68 i.busy = None; 69 if !ok { 70 return; 71 } 72 match change { 73 InstChange::Attach(a) => { 74 let disk = a.disk.clone(); 75 i.attached.push(a); 76 if let Some(d) = self.disks.get_mut(&(zone.to_string(), disk)) { 77 d.users.push(name.to_string()); 78 } 79 } 80 InstChange::Detach(device) => { 81 if let Some(pos) = i.attached.iter().position(|a| a.device == device) { 82 let gone = i.attached.remove(pos); 83 if let Some(d) = self.disks.get_mut(&(zone.to_string(), gone.disk)) { 84 d.users.retain(|u| u != name); 85 } 86 } 87 } 88 InstChange::AutoDelete { device, auto } => { 89 if device == BOOT_DEVICE { 90 i.boot_auto_delete = auto; 91 } else if let Some(a) = i.attached.iter_mut().find(|a| a.device == device) { 92 a.auto_delete = auto; 93 } 94 } 95 InstChange::AddAccess(mut a) => { 96 a.nat_ip = a.nat_ip.or(ip); 97 i.access.push(a); 98 } 99 InstChange::DeleteAccess(n) => i.access.retain(|a| a.name != n), 100 InstChange::Scheduling(patch) => { 101 if let (Some(s), Some(p)) = (i.scheduling.as_object_mut(), patch.as_object()) { 102 s.extend(p.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone()))); 103 } 104 } 105 InstChange::ServiceAccounts(v) => i.service_accounts = v, 106 InstChange::DeletionProtection(b) => i.deletion_protection = b, 107 } 108 }
The instance that runs a disk read-write, if any: its boot disk, or one attached that way.
The disk named by an AttachedDisk, checked to be attachable as mode (to instance, which has the disks in plus).
116 fn attachable(&self, zone: &str, source: &str, mode: &str, instance: &str, plus: &[Attached]) -> Result<String, Response> { 117 let name = last_segment(source); 118 if source.contains("/zones/") && !source.contains(&format!("/zones/{zone}/")) { 119 return Err(errors::invalid("resource.source", source, "The disk must be in the instance's zone.")); 120 } 121 let disk = self.free_disk(zone, name)?; 122 let in_use = |who: &str| errors::response(400, "resourceInUseByAnotherResource", None, &format!("The disk resource '{}' is already being used by '{}'", self.disk_url(zone, name), self.instance_url(zone, who))); 123 if plus.iter().any(|a| a.disk == name) { 124 return Err(in_use(instance)); 125 } 126 match mode { 127 "READ_WRITE" => disk.users.first().map_or(Ok(()), |u| Err(in_use(u)))?, 128 _ => self.read_write_user(zone, name).map_or(Ok(()), |u| Err(in_use(&u)))?, 129 } 130 Ok(name.to_string()) 131 }
The other disks of an instances.insert, and whether the boot disk goes with the instance.
A disk besides the boot disk must already exist (source); one made with it is not modelled.
142 pub(crate) fn extra_disks(&self, zone: &str, instance: &str, body: &Value) -> Result<(bool, Vec<Attached>), Response> { 143 let boot_auto_delete = body["disks"][0]["autoDelete"] == true; 144 let mut out: Vec<Attached> = Vec::new(); 145 for (n, d) in body["disks"].as_array().into_iter().flatten().enumerate().skip(1) { 146 let Some(source) = d["source"].as_str() else { return Err(not_modelled("a disk made by instances.insert besides the boot disk: make it with disks.insert and name it as `source`")) }; 147 let mode = Self::mode_of(d)?; 148 let disk = self.attachable(zone, source, &mode, instance, &out)?; 149 let device = d["deviceName"].as_str().map_or_else(|| format!("persistent-disk-{n}"), str::to_string); 150 if device == BOOT_DEVICE || out.iter().any(|a| a.device == device) { 151 return Err(errors::invalid("resource.disks.deviceName", &device, "The device name is already used.")); 152 } 153 out.push(Attached { disk, device, mode, auto_delete: d["autoDelete"] == true }); 154 } 155 Ok((boot_auto_delete, out)) 156 }
instances.attachDisk.
159 pub(crate) fn attach_disk(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 160 let Ok(body) = req.json_value() else { return errors::bad_json() }; 161 let attached = match self.free_instance(zone, name) { 162 Ok(i) => i.attached.clone(), 163 Err(r) => return r, 164 }; 165 let Some(source) = body["source"].as_str() else { return errors::invalid("resource.source", "", "An existing disk is required: it is not possible to create and attach a disk at the same time.") }; 166 if body["boot"] == true { 167 return not_modelled("attaching a boot disk"); 168 } 169 if body["type"].as_str().is_some_and(|t| t != "PERSISTENT") { 170 return not_modelled("an attached disk that is not PERSISTENT"); 171 } 172 if attached.len() + 1 >= MAX_DISKS { 173 return errors::invalid("resource.disks", &(attached.len() + 1).to_string(), &format!("At most {MAX_DISKS} disks can be attached.")); 174 } 175 let mode = match Self::mode_of(&body) { 176 Ok(m) => m, 177 Err(r) => return r, 178 }; 179 let disk = match self.attachable(zone, source, &mode, name, &attached) { 180 Ok(d) => d, 181 Err(r) => return r, 182 }; 183 let device = body["deviceName"].as_str().map_or_else(|| format!("persistent-disk-{}", attached.len() + 1), str::to_string); 184 if device == BOOT_DEVICE || attached.iter().any(|a| a.device == device) { 185 return errors::invalid("resource.deviceName", &device, "The device name is already used."); 186 } 187 let a = Attached { disk: disk.clone(), device, mode, auto_delete: body["autoDelete"] == true }; 188 self.instance_op(zone, name, "attachDisk", InstChange::Attach(a), Some(disk)) 189 }
instances.detachDisk: by device name; the boot disk is not detached.
192 pub(crate) fn detach_disk(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 193 let attached = match self.free_instance(zone, name) { 194 Ok(i) => i.attached.clone(), 195 Err(r) => return r, 196 }; 197 let device = req.query_one("deviceName").unwrap_or("").to_string(); 198 if device == BOOT_DEVICE { 199 return errors::invalid("deviceName", &device, "The boot disk cannot be detached."); 200 } 201 let Some(a) = attached.iter().find(|a| a.device == device) else { return errors::invalid("deviceName", &device, "No disk with that device name is attached to the instance.") }; 202 let disk = a.disk.clone(); 203 self.instance_op(zone, name, "detachDisk", InstChange::Detach(device), Some(disk)) 204 }
instances.setDiskAutoDelete.
207 pub(crate) fn set_disk_auto_delete(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 208 let attached = match self.free_instance(zone, name) { 209 Ok(i) => i.attached.clone(), 210 Err(r) => return r, 211 }; 212 let device = req.query_one("deviceName").unwrap_or("").to_string(); 213 if device != BOOT_DEVICE && !attached.iter().any(|a| a.device == device) { 214 return errors::invalid("deviceName", &device, "No disk with that device name is attached to the instance."); 215 } 216 let auto = match req.query_one("autoDelete") { 217 Some("true") => true, 218 Some("false") => false, 219 other => return errors::invalid("autoDelete", other.unwrap_or(""), "Must be true or false."), 220 }; 221 self.instance_op(zone, name, "setDiskAutoDelete", InstChange::AutoDelete { device, auto }, None) 222 }
instances.addAccessConfig: a second ONE_TO_ONE_NAT with another name.
232 pub(crate) fn add_access_config(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 233 let Ok(body) = req.json_value() else { return errors::bad_json() }; 234 let existing: Vec<String> = match self.free_instance(zone, name) { 235 Ok(i) => i.access.iter().map(|a| a.name.clone()).collect(), 236 Err(r) => return r, 237 }; 238 if let Err(r) = Self::nic_zero(req) { 239 return r; 240 } 241 let access = Access::from_body(&body); 242 if body["type"].as_str().is_some_and(|t| t != "ONE_TO_ONE_NAT") { 243 return not_modelled("an access config of a type other than ONE_TO_ONE_NAT"); 244 } 245 if existing.contains(&access.name) { 246 return errors::invalid("accessConfig.name", &access.name, "An access config of that name is already on the network interface."); 247 } 248 self.instance_op(zone, name, "addAccessConfig", InstChange::AddAccess(access), None) 249 }
instances.deleteAccessConfig.
252 pub(crate) fn delete_access_config(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 253 let existing: Vec<String> = match self.free_instance(zone, name) { 254 Ok(i) => i.access.iter().map(|a| a.name.clone()).collect(), 255 Err(r) => return r, 256 }; 257 if let Err(r) = Self::nic_zero(req) { 258 return r; 259 } 260 let which = req.query_one("accessConfig").unwrap_or("").to_string(); 261 if !existing.contains(&which) { 262 return errors::invalid("accessConfig", &which, "The network interface has no access config of that name."); 263 } 264 self.instance_op(zone, name, "deleteAccessConfig", InstChange::DeleteAccess(which), None) 265 }
The instance, which must be TERMINATED for the change the document restricts so.
instances.setScheduling: only a TERMINATED instance.
274 pub(crate) fn set_scheduling(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 275 let Ok(body) = req.json_value() else { return errors::bad_json() }; 276 if let Err(r) = self.stopped_instance(zone, name) { 277 return r; 278 } 279 if let Some(m) = body["onHostMaintenance"].as_str().filter(|m| !matches!(*m, "MIGRATE" | "TERMINATE")) { 280 return errors::invalid("onHostMaintenance", m, "Must be MIGRATE or TERMINATE."); 281 } 282 self.instance_op(zone, name, "setScheduling", InstChange::Scheduling(body), None) 283 }
instances.setServiceAccount: only a TERMINATED instance. No email removes the service account.
286 pub(crate) fn set_service_account(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 287 let Ok(body) = req.json_value() else { return errors::bad_json() }; 288 if let Err(r) = self.stopped_instance(zone, name) { 289 return r; 290 } 291 let value = match body["email"].as_str().filter(|e| !e.is_empty()) { 292 Some(email) => json!([{ "email": email, "scopes": body["scopes"].clone() }]), 293 None => Value::Null, 294 }; 295 self.instance_op(zone, name, "setServiceAccount", InstChange::ServiceAccounts(value), None) 296 }
instances.setDeletionProtection: on unless the query says false.
299 pub(crate) fn set_deletion_protection(&mut self, req: &Req<'_>, zone: &str, name: &str) -> Response { 300 if let Err(r) = self.free_instance(zone, name) { 301 return r; 302 } 303 let on = match req.query_one("deletionProtection") { 304 None | Some("true") => true, 305 Some("false") => false, 306 Some(other) => return errors::invalid("deletionProtection", other, "Must be true or false."), 307 }; 308 self.instance_op(zone, name, "setDeletionProtection", InstChange::DeletionProtection(on), None) 309 } 310}