-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathzone_bundle.rs
2332 lines (2161 loc) · 83.7 KB
/
zone_bundle.rs
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright 2023 Oxide Computer Company
//! Tools for collecting and inspecting service bundles for zones.
use anyhow::Context;
use anyhow::anyhow;
use camino::FromPathBufError;
use camino::Utf8Path;
use camino::Utf8PathBuf;
use flate2::bufread::GzDecoder;
use illumos_utils::running_zone::RunningZone;
use illumos_utils::running_zone::ServiceProcess;
use illumos_utils::running_zone::is_oxide_smf_log_file;
use illumos_utils::zfs::CreateSnapshotError;
use illumos_utils::zfs::DestroyDatasetError;
use illumos_utils::zfs::DestroySnapshotError;
use illumos_utils::zfs::EnsureDatasetError;
use illumos_utils::zfs::GetValueError;
use illumos_utils::zfs::ListDatasetsError;
use illumos_utils::zfs::ListSnapshotsError;
use illumos_utils::zfs::SetValueError;
use illumos_utils::zfs::Snapshot;
use illumos_utils::zfs::ZFS;
use illumos_utils::zfs::Zfs;
use illumos_utils::zone::AdmError;
use sled_agent_types::zone_bundle::*;
use sled_storage::dataset::U2_DEBUG_DATASET;
use sled_storage::manager::StorageHandle;
use slog::Logger;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::io::Cursor;
use std::sync::Arc;
use std::time::Duration;
use std::time::SystemTime;
use tar::Archive;
use tar::Builder;
use tar::Header;
use tokio::process::Command;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::time::Instant;
use tokio::time::sleep;
use uuid::Uuid;
// The name of the snapshot created from the zone root filesystem.
const ZONE_ROOT_SNAPSHOT_NAME: &'static str = "zone-root";
// The prefix for all the snapshots for each filesystem containing archived
// logs. Each debug data, such as `oxp_<UUID>/crypt/debug`, generates a snapshot
// named `zone-archives-<UUID>`.
const ARCHIVE_SNAPSHOT_PREFIX: &'static str = "zone-archives-";
// An extra ZFS user property attached to all zone bundle snapshots.
//
// This is used to ensure that we are not accidentally deleting ZFS objects that
// a user has created, but which happen to be named the same thing.
const ZONE_BUNDLE_ZFS_PROPERTY_NAME: &'static str = "oxide:for-zone-bundle";
const ZONE_BUNDLE_ZFS_PROPERTY_VALUE: &'static str = "true";
// Initialize the ZFS resources we need for zone bundling.
//
// This deletes any snapshots matching the names we expect to create ourselves
// during bundling.
#[cfg(not(test))]
fn initialize_zfs_resources(log: &Logger) -> Result<(), BundleError> {
let zb_snapshots =
Zfs::list_snapshots().unwrap().into_iter().filter(|snap| {
// Check for snapshots named how we expect to create them.
if snap.snap_name != ZONE_ROOT_SNAPSHOT_NAME
|| !snap.snap_name.starts_with(ARCHIVE_SNAPSHOT_PREFIX)
{
return false;
}
// Additionally check for the zone-bundle-specific property.
//
// If we find a dataset that matches our names, but which _does not_
// have such a property, we'll panic rather than possibly deleting
// user data.
let name = snap.to_string();
let value =
Zfs::get_oxide_value(&name, ZONE_BUNDLE_ZFS_PROPERTY_NAME)
.unwrap_or_else(|_| {
panic!(
"Found a ZFS snapshot with a name reserved for \
zone bundling, but which does not have the \
zone-bundle-specific property. Bailing out, \
rather than risking deletion of user data. \
snap_name = {}, property = {}",
&name, ZONE_BUNDLE_ZFS_PROPERTY_NAME
)
});
assert_eq!(value, ZONE_BUNDLE_ZFS_PROPERTY_VALUE);
true
});
for snapshot in zb_snapshots {
Zfs::destroy_snapshot(&snapshot.filesystem, &snapshot.snap_name)?;
debug!(
log,
"destroyed pre-existing zone bundle snapshot";
"snapshot" => %snapshot,
);
}
Ok(())
}
/// A type managing zone bundle creation and automatic cleanup.
#[derive(Clone)]
pub struct ZoneBundler {
log: Logger,
inner: Arc<Mutex<Inner>>,
// Channel for notifying the cleanup task that it should reevaluate.
notify_cleanup: Arc<Notify>,
}
// State shared between tasks, e.g., used when creating a bundle in different
// tasks or between a creation and cleanup.
struct Inner {
storage_handle: StorageHandle,
cleanup_context: CleanupContext,
last_cleanup_at: Instant,
}
impl Inner {
// Return the time at which the next cleanup should occur, and the duration
// until that time.
//
// The instant may be in the past, in which case duration would be 0.
fn next_cleanup(&self) -> (Instant, Duration) {
let next =
self.last_cleanup_at + self.cleanup_context.period.as_duration();
let delta = next.saturating_duration_since(Instant::now());
(next, delta)
}
// Ensure that the zone bundle directories that _can_ exist in fact do.
//
// The zone bundles are stored in a ZFS dataset on each M.2. These datasets
// are created by the storage manager upon request. Until those parent
// datasets exist, the bundle directories themselves cannot be accessed
// either.
//
// This method takes the _expected_ zone bundle directories; creates any
// that can exist but do not, i.e., those whose parent datasets already
// exist; and returns those.
async fn bundle_directories(&self) -> Vec<Utf8PathBuf> {
let resources = self.storage_handle.get_latest_disks().await;
// NOTE: These bundle directories are always stored on M.2s, so we don't
// need to worry about synchronizing with U.2 disk expungement at the
// callsite.
let expected = resources.all_zone_bundle_directories();
let mut out = Vec::with_capacity(expected.len());
for each in expected.into_iter() {
if tokio::fs::create_dir_all(&each).await.is_ok() {
out.push(each);
}
}
out.sort();
out
}
}
impl ZoneBundler {
// A task run in the background that periodically cleans up bundles.
//
// This waits for:
//
// - A timeout at the current cleanup period
// - A notification that the cleanup context has changed.
//
// When needed, it actually runs the period cleanup itself, using the
// current context.
async fn periodic_cleanup(
log: Logger,
inner: Arc<Mutex<Inner>>,
notify_cleanup: Arc<Notify>,
) {
let (mut next_cleanup, mut time_to_next_cleanup) =
inner.lock().await.next_cleanup();
loop {
info!(
log,
"top of bundle cleanup loop";
"next_cleanup" => ?&next_cleanup,
"time_to_next_cleanup" => ?time_to_next_cleanup,
);
// Wait for the cleanup period to expire, or a notification that the
// context has been changed.
tokio::select! {
_ = sleep(time_to_next_cleanup) => {
info!(log, "running automatic periodic zone bundle cleanup");
let mut inner_ = inner.lock().await;
let dirs = inner_.bundle_directories().await;
let res = run_cleanup(&log, &dirs, &inner_.cleanup_context).await;
inner_.last_cleanup_at = Instant::now();
(next_cleanup, time_to_next_cleanup) = inner_.next_cleanup();
debug!(log, "cleanup completed"; "result" => ?res);
}
_ = notify_cleanup.notified() => {
debug!(log, "notified about cleanup context change");
let inner_ = inner.lock().await;
(next_cleanup, time_to_next_cleanup) = inner_.next_cleanup();
}
}
}
}
/// Create a new zone bundler.
///
/// This creates an object that manages zone bundles on the system. It can
/// be used to create bundles from running zones, and runs a periodic task
/// to clean them up to free up space.
pub fn new(
log: Logger,
storage_handle: StorageHandle,
cleanup_context: CleanupContext,
) -> Self {
// This is compiled out in tests because there's no way to set our
// expectations on the mockall object it uses internally. Not great.
#[cfg(not(test))]
initialize_zfs_resources(&log)
.expect("Failed to initialize existing ZFS resources");
let notify_cleanup = Arc::new(Notify::new());
let inner = Arc::new(Mutex::new(Inner {
storage_handle,
cleanup_context,
last_cleanup_at: Instant::now(),
}));
let cleanup_log = log.new(slog::o!("component" => "auto-cleanup-task"));
let notify_clone = notify_cleanup.clone();
let inner_clone = inner.clone();
tokio::task::spawn(Self::periodic_cleanup(
cleanup_log,
inner_clone,
notify_clone,
));
Self { log, inner, notify_cleanup }
}
/// Trigger an immediate cleanup of low-priority zone bundles.
pub async fn cleanup(
&self,
) -> Result<BTreeMap<Utf8PathBuf, CleanupCount>, BundleError> {
let mut inner = self.inner.lock().await;
let dirs = inner.bundle_directories().await;
let res = run_cleanup(&self.log, &dirs, &inner.cleanup_context).await;
inner.last_cleanup_at = Instant::now();
self.notify_cleanup.notify_one();
res
}
/// Return the utilization of the system for zone bundles.
pub async fn utilization(
&self,
) -> Result<BTreeMap<Utf8PathBuf, BundleUtilization>, BundleError> {
let inner = self.inner.lock().await;
let dirs = inner.bundle_directories().await;
compute_bundle_utilization(&self.log, &dirs, &inner.cleanup_context)
.await
}
/// Return the context used to periodically clean up zone bundles.
pub async fn cleanup_context(&self) -> CleanupContext {
self.inner.lock().await.cleanup_context
}
/// Update the context used to periodically clean up zone bundles.
pub async fn update_cleanup_context(
&self,
new_period: Option<CleanupPeriod>,
new_storage_limit: Option<StorageLimit>,
new_priority: Option<PriorityOrder>,
) -> Result<(), BundleError> {
let mut inner = self.inner.lock().await;
info!(
self.log,
"received request to update cleanup context";
"period" => ?new_period,
"priority" => ?new_priority,
"storage_limit" => ?new_storage_limit,
);
let mut notify_cleanup_task = false;
if let Some(new_period) = new_period {
if new_period < inner.cleanup_context.period {
warn!(
self.log,
"auto cleanup period has been reduced, \
the cleanup task will be notified"
);
notify_cleanup_task = true;
}
inner.cleanup_context.period = new_period;
}
if let Some(new_priority) = new_priority {
inner.cleanup_context.priority = new_priority;
}
if let Some(new_storage_limit) = new_storage_limit {
if new_storage_limit < inner.cleanup_context.storage_limit {
notify_cleanup_task = true;
warn!(
self.log,
"storage limit has been lowered, a \
cleanup will be run immediately"
);
}
inner.cleanup_context.storage_limit = new_storage_limit;
}
if notify_cleanup_task {
self.notify_cleanup.notify_one();
}
Ok(())
}
/// Create a bundle from the provided zone.
pub async fn create(
&self,
zone: &RunningZone,
cause: ZoneBundleCause,
) -> Result<ZoneBundleMetadata, BundleError> {
// NOTE: [Self::await_completion_of_prior_bundles] relies on this lock
// being held across this whole function. If we want more concurrency,
// we'll need to add a barrier-like mechanism to let callers know when
// prior bundles have completed.
let inner = self.inner.lock().await;
let storage_dirs = inner.bundle_directories().await;
let resources = inner.storage_handle.get_latest_disks().await;
let extra_log_dirs = resources
.all_u2_mountpoints(U2_DEBUG_DATASET)
.into_iter()
.map(|pool_path| pool_path.path)
.collect();
let context = ZoneBundleContext { cause, storage_dirs, extra_log_dirs };
info!(
self.log,
"creating zone bundle";
"zone_name" => zone.name(),
"context" => ?context,
);
create(&self.log, zone, &context).await
}
/// Awaits the completion of all prior calls to [ZoneBundler::create].
///
/// This is critical for disk expungement, which wants to ensure that the
/// Sled Agent is no longer using devices after they have been expunged.
pub async fn await_completion_of_prior_bundles(&self) {
let _ = self.inner.lock().await;
}
/// Return the paths for all bundles of the provided zone and ID.
pub async fn bundle_paths(
&self,
name: &str,
id: &Uuid,
) -> Result<Vec<Utf8PathBuf>, BundleError> {
let inner = self.inner.lock().await;
let dirs = inner.bundle_directories().await;
get_zone_bundle_paths(&self.log, &dirs, name, id).await
}
/// List bundles for a zone with the provided name.
pub async fn list_for_zone(
&self,
name: &str,
) -> Result<Vec<ZoneBundleMetadata>, BundleError> {
// The zone bundles are replicated in several places, so we'll use a set
// to collect them all, to avoid duplicating.
let mut bundles = BTreeSet::new();
let inner = self.inner.lock().await;
let dirs = inner.bundle_directories().await;
for dir in dirs.iter() {
bundles.extend(
list_bundles_for_zone(&self.log, &dir, name)
.await?
.into_iter()
.map(|(_path, bdl)| bdl),
);
}
Ok(bundles.into_iter().collect())
}
/// List all zone bundles that match the provided filter, if any.
///
/// The filter is a simple substring match -- any zone bundle with a zone
/// name that contains the filter anywhere will match. If no filter is
/// provided, all extant bundles will be listed.
pub async fn list(
&self,
filter: Option<&str>,
) -> Result<Vec<ZoneBundleMetadata>, BundleError> {
// The zone bundles are replicated in several places, so we'll use a set
// to collect them all, to avoid duplicating.
let mut bundles = BTreeSet::new();
let inner = self.inner.lock().await;
let dirs = inner.bundle_directories().await;
for dir in dirs.iter() {
let mut rd = tokio::fs::read_dir(dir).await.map_err(|err| {
BundleError::ReadDirectory { directory: dir.to_owned(), err }
})?;
while let Some(entry) = rd.next_entry().await.map_err(|err| {
BundleError::ReadDirectory { directory: dir.to_owned(), err }
})? {
let search_dir = Utf8PathBuf::try_from(entry.path())?;
bundles.extend(
filter_zone_bundles(&self.log, &search_dir, |md| {
filter
.map(|filt| md.id.zone_name.contains(filt))
.unwrap_or(true)
})
.await?
.into_values(),
);
}
}
Ok(bundles.into_iter().collect())
}
}
// Context for creating a bundle of a specified zone.
#[derive(Debug, Default)]
struct ZoneBundleContext {
// The directories into which the zone bundles are written.
storage_dirs: Vec<Utf8PathBuf>,
// The reason or cause for creating a zone bundle.
cause: ZoneBundleCause,
// Extra directories searched for logfiles for the named zone.
//
// Logs are periodically archived out of their original location, and onto
// one or more U.2 drives. This field is used to specify that archive
// location, so that rotated logs for the zone's services may be found.
extra_log_dirs: Vec<Utf8PathBuf>,
}
// The set of zone-wide commands, which don't require any details about the
// processes we've launched in the zone.
const ZONE_WIDE_COMMANDS: [&[&str]; 6] = [
&["ptree"],
&["uptime"],
&["last"],
&["who"],
&["svcs", "-p"],
&["netstat", "-an"],
];
// The name for zone bundle metadata files.
const ZONE_BUNDLE_METADATA_FILENAME: &str = "metadata.toml";
/// Errors related to managing service zone bundles.
#[derive(Debug, thiserror::Error)]
pub enum BundleError {
#[error("I/O error running command '{cmd}'")]
Command {
cmd: String,
#[source]
err: std::io::Error,
},
#[error("I/O error creating directory '{directory}'")]
CreateDirectory {
directory: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("I/O error opening bundle tarball '{path}'")]
OpenBundleFile {
path: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("I/O error adding bundle tarball data to '{tarball_path}'")]
AddBundleData {
tarball_path: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("I/O error reading bundle tarball data from '{path}'")]
ReadBundleData {
path: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("I/O error copying bundle tarball from '{from}' to '{to}'")]
CopyArchive {
from: Utf8PathBuf,
to: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("I/O error reading directory '{directory}'")]
ReadDirectory {
directory: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("I/O error fetching metadata for '{path}'")]
Metadata {
path: Utf8PathBuf,
#[source]
err: std::io::Error,
},
#[error("TOML serialization failure")]
Serialization(#[from] toml::ser::Error),
#[error("TOML deserialization failure")]
Deserialization(#[from] toml::de::Error),
#[error("No zone named '{name}' is available for bundling")]
NoSuchZone { name: String },
#[error("No storage available for bundles")]
NoStorage,
#[error("Failed to join zone bundling task")]
Task(#[from] tokio::task::JoinError),
#[error("Failed to send request to instance/instance manager")]
FailedSend(anyhow::Error),
#[error("Instance/Instance Manager dropped our request")]
DroppedRequest(anyhow::Error),
#[error("Failed to create bundle: {0}")]
BundleFailed(#[from] anyhow::Error),
#[error("Zone error")]
Zone(#[from] AdmError),
#[error(transparent)]
PathBuf(#[from] FromPathBufError),
#[error("Zone '{name}' cannot currently be bundled")]
Unavailable { name: String },
#[error(transparent)]
StorageLimitCreate(#[from] StorageLimitCreateError),
#[error(transparent)]
CleanupPeriodCreate(#[from] CleanupPeriodCreateError),
#[error(transparent)]
PriorityOrderCreate(#[from] PriorityOrderCreateError),
#[error("Cleanup failed")]
Cleanup(#[source] anyhow::Error),
#[error("Failed to create ZFS snapshot")]
CreateSnapshot(#[from] CreateSnapshotError),
#[error("Failed to destroy ZFS snapshot")]
DestroySnapshot(#[from] DestroySnapshotError),
#[error("Failed to list ZFS snapshots")]
ListSnapshot(#[from] ListSnapshotsError),
#[error("Failed to ensure ZFS dataset")]
EnsureDataset(#[from] EnsureDatasetError),
#[error("Failed to destroy ZFS dataset")]
DestroyDataset(#[from] DestroyDatasetError),
#[error("Failed to list ZFS datasets")]
ListDatasets(#[from] ListDatasetsError),
#[error("Failed to set Oxide-specific ZFS property")]
SetProperty(#[from] SetValueError),
#[error("Failed to get ZFS property value")]
GetProperty(#[from] GetValueError),
#[error("Instance is terminating")]
InstanceTerminating,
/// The `walkdir` crate's errors already include the path which could not be
/// read (if one exists), so we can just wrap them directly.
#[error(transparent)]
WalkDir(#[from] walkdir::Error),
}
// Helper function to write an array of bytes into the tar archive, with
// the provided name.
fn insert_data<W: std::io::Write>(
builder: &mut Builder<W>,
name: &str,
contents: &[u8],
) -> Result<(), BundleError> {
let mtime = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.context("failed to compute mtime")?
.as_secs();
let mut hdr = Header::new_ustar();
hdr.set_size(contents.len().try_into().unwrap());
hdr.set_mode(0o444);
hdr.set_mtime(mtime);
hdr.set_entry_type(tar::EntryType::Regular);
// NOTE: This internally sets the path and checksum.
builder.append_data(&mut hdr, name, Cursor::new(contents)).map_err(|err| {
BundleError::AddBundleData { tarball_path: name.into(), err }
})
}
// Create a read-only snapshot from an existing filesystem.
fn create_snapshot(
log: &Logger,
filesystem: &str,
snap_name: &str,
) -> Result<Snapshot, BundleError> {
Zfs::create_snapshot(
filesystem,
snap_name,
&[(ZONE_BUNDLE_ZFS_PROPERTY_NAME, ZONE_BUNDLE_ZFS_PROPERTY_VALUE)],
)?;
debug!(
log,
"created snapshot";
"filesystem" => filesystem,
"snap_name" => snap_name,
);
Ok(Snapshot {
filesystem: filesystem.to_string(),
snap_name: snap_name.to_string(),
})
}
// Create snapshots for the filesystems we need to copy out all log files.
//
// A key feature of the zone-bundle process is that we pull all the log files
// for a zone. This is tricky. The logs are both being written to by the
// programs we're interested in, and also potentially being rotated by `logadm`,
// and / or archived out to the U.2s through the code in `crate::dump_setup`.
//
// We need to capture all these logs, while avoiding inconsistent state (e.g., a
// missing log message that existed when the bundle was created) and also
// interrupting the rotation and archival processes. We do this by taking ZFS
// snapshots of the relevant datasets when we want to create the bundle.
//
// When we receive a bundling request, we take a snapshot of a few datasets:
//
// - The zone filesystem itself, `oxz_<UUID>/crypt/zone/<ZONE_NAME>`.
//
// - All of the U.2 debug datasets, like `oxp_<UUID>/crypt/debug`, which we know
// contain logs for the given zone. This is done by looking at all the service
// processes in the zone, and mapping the locations of archived logs, such as
// `/pool/ext/<UUID>/crypt/debug/<ZONE_NAME>` to the zpool name.
//
// This provides us with a consistent view of the log files at the time the
// bundle was requested. Note that this ordering, taking the root FS snapshot
// first followed by the archive datasets, ensures that we don't _miss_ log
// messages that existed when the bundle was requested. It's possible that we
// double-count them however: the archiver could run concurrently, and result in
// a log file existing on the root snapshot when we create it, and also on the
// achive snapshot by the time we get around to creating that.
//
// At this point, we operate entirely on those snapshots. We search for
// "current" log files in the root snapshot, and archived log files in the
// archive snapshots.
fn create_zfs_snapshots(
log: &Logger,
zone: &RunningZone,
extra_log_dirs: &[Utf8PathBuf],
) -> Result<Vec<Snapshot>, BundleError> {
// Snapshot the root filesystem.
let dataset = Zfs::get_dataset_name(zone.root().as_str())?;
let root_snapshot =
create_snapshot(log, &dataset, ZONE_ROOT_SNAPSHOT_NAME)?;
let mut snapshots = vec![root_snapshot];
// Look at all the provided extra log directories, and take a snapshot for
// any that have a directory with the zone name. These may not have any log
// file in them yet, but we'll snapshot now and then filter more judiciously
// when we actually find the files we want to bundle.
let mut maybe_err = None;
for dir in extra_log_dirs.iter() {
let zone_dir = dir.join(zone.name());
match std::fs::metadata(&zone_dir) {
Ok(d) => {
if d.is_dir() {
let dataset = match Zfs::get_dataset_name(zone_dir.as_str())
{
Ok(ds) => Utf8PathBuf::from(ds),
Err(e) => {
error!(
log,
"failed to list datasets, will \
unwind any previously created snapshots";
"error" => ?e,
);
assert!(
maybe_err
.replace(BundleError::from(e))
.is_none()
);
break;
}
};
// These datasets are named like `<pool_name>/...`. Since
// we're snapshotting zero or more of them, we disambiguate
// with the pool name.
let pool_name = dataset
.components()
.next()
.expect("Zone archive datasets must be non-empty");
let snap_name =
format!("{}{}", ARCHIVE_SNAPSHOT_PREFIX, pool_name);
match create_snapshot(log, dataset.as_str(), &snap_name) {
Ok(snapshot) => snapshots.push(snapshot),
Err(e) => {
error!(
log,
"failed to create snapshot, will \
unwind any previously created";
"error" => ?e,
);
assert!(maybe_err.replace(e).is_none());
break;
}
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
trace!(
log,
"skipping non-existent zone-bundle directory";
"dir" => %zone_dir,
);
}
Err(e) => {
error!(
log,
"failed to get metadata for potential zone directory";
"zone_dir" => %zone_dir,
"error" => ?e,
);
}
}
}
if let Some(err) = maybe_err {
cleanup_zfs_snapshots(log, &snapshots);
return Err(err);
};
Ok(snapshots)
}
// Destroy any created ZFS snapshots.
fn cleanup_zfs_snapshots(log: &Logger, snapshots: &[Snapshot]) {
for snapshot in snapshots.iter() {
match Zfs::destroy_snapshot(&snapshot.filesystem, &snapshot.snap_name) {
Ok(_) => debug!(
log,
"destroyed zone bundle ZFS snapshot";
"snapshot" => %snapshot,
),
Err(e) => error!(
log,
"failed to destroy zone bundle ZFS snapshot";
"snapshot" => %snapshot,
"error" => ?e,
),
}
}
}
// List all log files (current, rotated, and archived) that should be part of
// the zone bundle for a single service.
async fn find_service_log_files(
log: &Logger,
zone_name: &str,
svc: &ServiceProcess,
extra_log_dirs: &[Utf8PathBuf],
snapshots: &[Snapshot],
) -> Result<Vec<Utf8PathBuf>, BundleError> {
// The current and any rotated, but not archived, log files live in the zone
// root filesystem. Extract any which match.
//
// There are a few path tricks to keep in mind here. We've created a
// snapshot from the zone's filesystem, which is usually something like
// `<pool_name>/crypt/zone/<zone_name>`. That snapshot is placed in a hidden
// directory within the base dataset, something like
// `oxp_<pool_id>/crypt/zone/.zfs/snapshot/<snap_name>`.
//
// The log files themselves are things like `/var/svc/log/...`, but in the
// actual ZFS dataset comprising the root FS for the zone, there are
// additional directories, most notably `<zonepath>/root`. So the _cloned_
// log file will live at
// `/<pool_name>/crypt/zone/.zfs/snapshot/<snap_name>/root/var/svc/log/...`.
let mut current_log_file = snapshots[0].full_path()?;
current_log_file.push(RunningZone::ROOT_FS_PATH);
current_log_file.push(svc.log_file.as_str().trim_start_matches('/'));
let log_dir =
current_log_file.parent().expect("Current log file must have a parent");
let mut log_files = vec![current_log_file.clone()];
for entry in log_dir.read_dir_utf8().map_err(|err| {
BundleError::ReadDirectory { directory: log_dir.into(), err }
})? {
let entry = entry.map_err(|err| BundleError::ReadDirectory {
directory: log_dir.into(),
err,
})?;
let path = entry.path();
// Camino's Utf8Path only considers whole path components to match,
// so convert both paths into a &str and use that object's
// starts_with. See the `camino_starts_with_behaviour` test.
let path_ref: &str = path.as_ref();
let current_log_file_ref: &str = current_log_file.as_ref();
if path != current_log_file
&& path_ref.starts_with(current_log_file_ref)
{
log_files.push(path.into());
}
}
// The _archived_ log files are slightly trickier. They can technically live
// in many different datasets, because the archive process may need to start
// archiving to one location, but move to another if a quota is hit. We'll
// iterate over all the extra log directories and try to find any log files
// in those filesystem snapshots.
let snapped_extra_log_dirs = snapshots
.iter()
.skip(1)
.flat_map(|snapshot| {
extra_log_dirs.iter().map(|d| {
// Join the snapshot path with both the log directory and the
// zone name, to arrive at something like:
// /path/to/dataset/.zfs/snapshot/<snap_name>/path/to/extra/<zone_name>
snapshot.full_path().map(|p| p.join(d).join(zone_name))
})
})
.collect::<Result<BTreeSet<_>, _>>()?;
debug!(
log,
"looking for extra log files in filesystem snapshots";
"extra_dirs" => ?&snapped_extra_log_dirs,
);
log_files.extend(
find_archived_log_files(
log,
zone_name,
&svc.service_name,
svc.log_file.file_name().unwrap(),
snapped_extra_log_dirs.iter(),
)
.await,
);
debug!(
log,
"found log files";
"log_files" => ?&log_files,
);
Ok(log_files)
}
// Create a service bundle for the provided zone.
//
// This runs a series of debugging commands in the zone, to collect data about
// the state of the zone and any Oxide service processes running inside. The
// data is packaged into a tarball, and placed in the provided output
// directories.
async fn create(
log: &Logger,
zone: &RunningZone,
context: &ZoneBundleContext,
) -> Result<ZoneBundleMetadata, BundleError> {
// Fetch the directory into which we'll store data, and ensure it exists.
if context.storage_dirs.is_empty() {
warn!(log, "no directories available for zone bundles");
return Err(BundleError::NoStorage);
}
let mut zone_bundle_dirs = Vec::with_capacity(context.storage_dirs.len());
for dir in context.storage_dirs.iter() {
let bundle_dir = dir.join(zone.name());
debug!(log, "creating bundle directory"; "dir" => %bundle_dir);
tokio::fs::create_dir_all(&bundle_dir).await.map_err(|err| {
BundleError::CreateDirectory {
directory: bundle_dir.to_owned(),
err,
}
})?;
zone_bundle_dirs.push(bundle_dir);
}
// Create metadata and the tarball writer.
//
// We'll write the contents of the bundle into a gzipped tar archive,
// including metadata and a file for the output of each command we run in
// the zone.
let zone_metadata = ZoneBundleMetadata::new(zone.name(), context.cause);
let filename = format!("{}.tar.gz", zone_metadata.id.bundle_id);
let full_path = zone_bundle_dirs[0].join(&filename);
let file = match tokio::fs::File::create(&full_path).await {
Ok(f) => f.into_std().await,
Err(e) => {
error!(
log,
"failed to create bundle file";
"zone" => zone.name(),
"file" => %full_path,
"error" => ?e,
);
return Err(BundleError::OpenBundleFile {
path: full_path.to_owned(),
err: e,
});
}
};
debug!(
log,
"created bundle tarball file";
"zone" => zone.name(),
"path" => %full_path
);
let gz = flate2::GzBuilder::new()
.filename(filename.as_str())
.write(file, flate2::Compression::best());
let mut builder = Builder::new(gz);
// Write the metadata file itself, in TOML format.
let contents = toml::to_string(&zone_metadata)?;
insert_data(
&mut builder,
ZONE_BUNDLE_METADATA_FILENAME,
contents.as_bytes(),
)?;
debug!(
log,
"wrote zone bundle metadata";
"zone" => zone.name(),
);
for cmd in ZONE_WIDE_COMMANDS {
debug!(
log,
"running zone bundle command";
"zone" => zone.name(),
"command" => ?cmd,
);
let output = match zone.run_cmd(cmd) {
Ok(s) => s,
Err(e) => format!("{}", e),
};
let contents = format!("Command: {:?}\n{}", cmd, output).into_bytes();
if let Err(e) = insert_data(&mut builder, cmd[0], &contents) {
error!(
log,
"failed to save zone bundle command output";
"zone" => zone.name(),
"command" => ?cmd,
"error" => ?e,
);
}
}
// Enumerate the list of Oxide-specific services inside the zone that we
// want to include in the bundling process.
let procs = match zone
.service_processes()
.context("failed to enumerate zone service processes")
{
Ok(p) => {
debug!(
log,
"enumerated service processes";
"zone" => zone.name(),
"procs" => ?p,
);
p
}
Err(e) => {
error!(
log,
"failed to enumerate zone service processes";
"zone" => zone.name(),
"error" => ?e,
);
return Err(BundleError::from(e));
}
};
// Create ZFS snapshots of filesystems containing log files.
//
// We need to capture log files from two kinds of locations:
//
// - The zone root filesystem, where the current and rotated (but not
// archived) log files live.
// - Zero or more filesystems on the U.2s used for archiving older log
// files.
//