libcontainer 0.7.0

Library for container control
Documentation
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
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use nix::unistd::Pid;
use oci_spec::runtime::LinuxIntelRdt;
use pathrs::flags::OpenFlags;
use pathrs::procfs::{ProcfsBase, ProcfsHandle};
use procfs::process::MountInfo;
use regex::Regex;

#[derive(Debug, thiserror::Error)]
pub enum IntelRdtError {
    #[error(transparent)]
    ProcError(#[from] procfs::ProcError),
    #[error("failed to find resctrl mount point")]
    ResctrlMountPointNotFound,
    #[error("failed to find ID for resctrl")]
    ResctrlIdNotFound,
    #[error("existing schemata found but data did not match")]
    ExistingSchemataMismatch,
    #[error("failed to read existing schemata")]
    ReadSchemata(#[source] std::io::Error),
    #[error("failed to write schemata")]
    WriteSchemata(#[source] std::io::Error),
    #[error("failed to open schemata file")]
    OpenSchemata(#[source] std::io::Error),
    #[error(transparent)]
    ParseLine(#[from] ParseLineError),
    #[error("no resctrl subdirectory found for container id")]
    NoResctrlSubdirectory,
    #[error("failed to remove subdirectory")]
    RemoveSubdirectory(#[source] std::io::Error),
    #[error("no parent for resctrl subdirectory")]
    NoResctrlSubdirectoryParent,
    #[error("invalid resctrl directory")]
    InvalidResctrlDirectory,
    #[error("resctrl closID directory didn't exist")]
    NoClosIDDirectory,
    #[error("failed to write to resctrl closID directory")]
    WriteClosIDTasksFile(#[source] std::io::Error),
    #[error("failed to open resctrl closID directory")]
    OpenClosIDTasksFile(#[source] std::io::Error),
    #[error("failed to create resctrl closID directory")]
    CreateClosIDDirectory(#[source] std::io::Error),
    #[error("failed to write to resctrl monitoring tasks file")]
    WriteMonitoringTasksFile(#[source] std::io::Error),
    #[error("failed to open resctrl monitoring tasks file")]
    OpenMonitoringTasksFile(#[source] std::io::Error),
    #[error("failed to create resctrl monitoring directory")]
    CreateMonitoringDirectory(#[source] std::io::Error),
    #[error("failed to canonicalize path")]
    Canonicalize(#[source] std::io::Error),
    #[error(transparent)]
    Pathrs(#[from] pathrs::error::Error),
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[error("failed to cleanup intel rdt: {0}")]
    Cleanup(String),
}

#[derive(Debug, thiserror::Error)]
pub enum ParseLineError {
    #[error("MB line doesn't match validation")]
    MBLine,
    #[error("MB token has wrong number of fields")]
    MBToken,
    #[error("L3 line doesn't match validation")]
    L3Line,
    #[error("L3 token has wrong number of fields")]
    L3Token,
    #[error("Generic line doesn't match validation")]
    GenericLine,
    #[error("Generic token has wrong number of fields")]
    GenericToken,
}

type Result<T> = std::result::Result<T, IntelRdtError>;

/// Removes the main resource control group (CLOS) directory for the container using its ID.
/// Helper to delete a resctrl subdirectory based ONLY on the container ID.
///
/// DEPRECATED: This function is only kept for backwards compatibility with
/// legacy state files. It performs strict bounds checking to ensure it only
/// deletes directories directly under the resctrl mount point, preventing
/// accidental deletion of arbitrary paths or nested kernel files.
pub fn delete_resctrl_subdirectory_by_id(id: &str) -> Result<()> {
    let dir = find_resctrl_mount_point().map_err(|err| {
        tracing::error!("failed to find resctrl mount point: {err}");
        err
    })?;

    let path = dir.join(id);
    let container_resctrl_path = match path.canonicalize() {
        Ok(p) => p,
        Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()),
        Err(err) => {
            tracing::error!(?dir, ?path, "failed to canonicalize path: {err}");
            return Err(IntelRdtError::Canonicalize(err));
        }
    };

    match container_resctrl_path.parent() {
        // Make sure the container_id really exists and the directory
        // is inside the resctrl fs.
        Some(parent) => {
            if parent == dir && container_resctrl_path.exists() {
                if let Err(err) = fs::remove_dir(&container_resctrl_path) {
                    if err.kind() != ErrorKind::NotFound {
                        tracing::error!(path = ?container_resctrl_path, "failed to remove resctrl subdirectory: {err}");
                        return Err(IntelRdtError::RemoveSubdirectory(err));
                    }
                }
            } else {
                return Err(IntelRdtError::NoResctrlSubdirectory);
            }
        }
        None => return Err(IntelRdtError::NoResctrlSubdirectoryParent),
    }

    Ok(())
}

/// Cleans up the Intel RDT directories.
///
/// This function attempts to remove the monitoring directory and the main resource
/// control (CLOS) directory. If the explicit path is not available but the legacy
/// `clean_up_intel_rdt_subdirectory` flag is set, it will attempt to remove the
/// directory by container ID.
///
/// It aggregates all cleanup failures into a single `Cleanup` error.
pub fn cleanup_intel_rdt(
    intel_rdt_dir: Option<&Path>,
    intel_rdt_monitoring_dir: Option<&Path>,
    clean_up_intel_rdt_subdirectory: Option<bool>,
    id: &str,
) -> Result<()> {
    let mut errors = Vec::new();

    let delete_resctrl_subdirectory = |path: &Path| -> Result<()> {
        if let Err(err) = fs::remove_dir(path) {
            if err.kind() != ErrorKind::NotFound {
                return Err(IntelRdtError::RemoveSubdirectory(err));
            }
        }
        Ok(())
    };

    if let Some(path) = intel_rdt_monitoring_dir {
        if let Err(e) = delete_resctrl_subdirectory(path) {
            errors.push(format!("failed to delete monitoring directory: {e}"));
        }
    }

    if let Some(path) = intel_rdt_dir {
        if let Err(e) = delete_resctrl_subdirectory(path) {
            errors.push(format!("failed to delete directory: {e}"));
        }
    } else if let Some(true) = clean_up_intel_rdt_subdirectory {
        // Fallback for legacy state files
        if let Err(e) = delete_resctrl_subdirectory_by_id(id) {
            errors.push(format!("failed to delete directory by id: {}", e));
        }
    }

    if !errors.is_empty() {
        return Err(IntelRdtError::Cleanup(errors.join(";")));
    }

    Ok(())
}

/// Finds the resctrl mount path by looking at the process mountinfo data.
pub fn find_resctrl_mount_point() -> Result<PathBuf> {
    let reader = BufReader::new(ProcfsHandle::new()?.open(
        ProcfsBase::ProcSelf,
        "mountinfo",
        OpenFlags::O_RDONLY | OpenFlags::O_CLOEXEC,
    )?);

    for lr in reader.lines() {
        let s = lr.map_err(IntelRdtError::from)?;
        let mi = MountInfo::from_line(&s).map_err(IntelRdtError::from)?;

        if mi.fs_type == "resctrl" {
            let path = mi
                .mount_point
                .canonicalize()
                .map_err(IntelRdtError::Canonicalize)?;
            return Ok(path);
        }
    }

    Err(IntelRdtError::ResctrlMountPointNotFound)
}

/// Sets up the main resource control group (CLOS) for the container.
/// This involves creating the subdirectory within the resctrl filesystem if needed,
/// and adding the container's PID to the group's `tasks` file.
///
/// Returns `true` if the runtime created the directory, or `false` if it already existed.
fn setup_resctrl_group(
    resctrl_container_dir: &Path,
    init_pid: Pid,
    only_clos_id_set: bool,
) -> Result<bool> {
    let mut created_dir = false;

    if !resctrl_container_dir.exists() {
        if only_clos_id_set {
            return Err(IntelRdtError::NoClosIDDirectory);
        }
        fs::create_dir_all(resctrl_container_dir).map_err(|err| {
            tracing::error!("failed to create resctrl subdirectory: {err}");
            IntelRdtError::CreateClosIDDirectory(err)
        })?;
        created_dir = true;
    }

    write_pid_to_tasks(
        resctrl_container_dir,
        init_pid,
        IntelRdtError::OpenClosIDTasksFile,
        IntelRdtError::WriteClosIDTasksFile,
    )?;

    Ok(created_dir)
}

/// Creates a dedicated monitoring group (`mon_groups/<container_id>`) inside the container's
/// Intel RDT resource control directory and adds the container's PID to its `tasks` file.
///
/// Helper function to write the process ID to the tasks file
fn write_pid_to_tasks<F1, F2>(dir: &Path, pid: Pid, on_open_err: F1, on_write_err: F2) -> Result<()>
where
    F1: FnOnce(std::io::Error) -> IntelRdtError,
    F2: FnOnce(std::io::Error) -> IntelRdtError,
{
    let tasks = dir.join("tasks");
    let mut file = OpenOptions::new()
        .write(true)
        .open(tasks)
        .map_err(on_open_err)?;

    file.write_all(pid.to_string().as_bytes())
        .map_err(on_write_err)?;

    Ok(())
}

/// Merges the two schemas together, removing lines starting with "MB:" from
/// l3_cache_schema if mem_bw_schema is also specified.
fn combine_l3_cache_and_mem_bw_schemas(
    l3_cache_schema: &Option<String>,
    mem_bw_schema: &Option<String>,
) -> Option<String> {
    match (l3_cache_schema, mem_bw_schema) {
        (Some(real_l3_cache_schema), Some(real_mem_bw_schema)) => {
            // Combine the results. Filter out "MB:"-lines from l3_cache_schema
            let mut output: Vec<&str> = vec![];

            for line in real_l3_cache_schema.lines() {
                if line.starts_with("MB:") {
                    continue;
                }
                output.push(line);
            }
            output.push(real_mem_bw_schema);
            Some(output.join("\n"))
        }
        (Some(_), None) => {
            // Apparently the "MB:"-lines don't need to be removed in this case?
            l3_cache_schema.to_owned()
        }
        (None, Some(_)) => mem_bw_schema.to_owned(),
        (None, None) => None,
    }
}

#[derive(PartialEq)]
enum LineType {
    L3Line,
    L3DataLine,
    L3CodeLine,
    MbLine,
    Generic(String),
}

#[derive(PartialEq)]
struct ParsedLine {
    line_type: LineType,
    tokens: HashMap<String, String>,
}

/// Parse tokens ("1=7000") from a "MB:" line.
fn parse_mb_line(line: &str) -> std::result::Result<HashMap<String, String>, ParseLineError> {
    let mut token_map = HashMap::new();

    static MB_VALIDATE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^MB:(?:\s|;)*(?:\w+\s*=\s*\w+)?(?:(?:\s*;+\s*)+\w+\s*=\s*\w+)*(?:\s|;)*$")
            .unwrap()
    });
    static MB_CAPTURE_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(\w+)\s*=\s*(\w+)").unwrap());

    if !MB_VALIDATE_RE.is_match(line) {
        return Err(ParseLineError::MBLine);
    }

    for token in MB_CAPTURE_RE.captures_iter(line) {
        match (token.get(1), token.get(2)) {
            (Some(key), Some(value)) => {
                token_map.insert(key.as_str().to_string(), value.as_str().to_string());
            }
            _ => return Err(ParseLineError::MBToken),
        }
    }

    Ok(token_map)
}

/// Parse tokens ("0=ffff") from a L3{,CODE,DATA} line.
fn parse_l3_line(line: &str) -> std::result::Result<HashMap<String, String>, ParseLineError> {
    let mut token_map = HashMap::new();

    static L3_VALIDATE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^(?:L3|L3DATA|L3CODE):(?:\s|;)*(?:\w+\s*=\s*[[:xdigit:]]+)?(?:(?:\s*;+\s*)+\w+\s*=\s*[[:xdigit:]]+)*(?:\s|;)*$").unwrap()
    });
    static L3_CAPTURE_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(\w+)\s*=\s*0*([[:xdigit:]]+)").unwrap());
    //                                        ^
    //                          +-------------+
    //                          |
    // The capture regexp also removes leading zeros from mask values.

    if !L3_VALIDATE_RE.is_match(line) {
        return Err(ParseLineError::L3Line);
    }

    for token in L3_CAPTURE_RE.captures_iter(line) {
        match (token.get(1), token.get(2)) {
            (Some(key), Some(value)) => {
                token_map.insert(key.as_str().to_string(), value.as_str().to_string());
            }
            _ => return Err(ParseLineError::L3Token),
        }
    }

    Ok(token_map)
}

/// Parse tokens from generic resctrl lines.
/// OCI runtime-spec v1.3.0 introduced the `schemata` list, allowing users to
/// specify any hardware resource (e.g. `L2`, `SMBA`). To safely verify these
/// new resources during `is_same_schema`, we must parse them into token maps
/// so we can perform strict semantic equality checks rather than basic string matching.
///
/// Example:
/// A line like "L2:0=00ff;1=f0" is parsed into a token map:
/// {"0": "ff", "1": "f0"}
/// Leading zeros are automatically stripped from the values to ensure
/// "00ff" correctly matches "ff" during equality comparison.
fn parse_generic_line(line: &str) -> std::result::Result<HashMap<String, String>, ParseLineError> {
    let mut token_map = HashMap::new();

    static OTHER_VALIDATE_RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(r"^[A-Za-z0-9]+:(?:\s|;)*(?:\w+\s*=\s*[[:xdigit:]]+)?(?:(?:\s*;+\s*)+\w+\s*=\s*[[:xdigit:]]+)*(?:\s|;)*$").unwrap()
    });

    static OTHER_CAPTURE_RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"(\w+)\s*=\s*([[:xdigit:]]+)").unwrap());
    if !OTHER_VALIDATE_RE.is_match(line) {
        return Err(ParseLineError::GenericLine);
    }

    for token in OTHER_CAPTURE_RE.captures_iter(line) {
        match (token.get(1), token.get(2)) {
            (Some(key), Some(value)) => {
                let val_str = value.as_str().trim_start_matches('0');
                let final_val = if val_str.is_empty() { "0" } else { val_str };
                token_map.insert(key.as_str().to_string(), final_val.to_string());
            }
            _ => return Err(ParseLineError::GenericToken),
        }
    }

    Ok(token_map)
}

/// Get the resctrl line type.
/// Supports traditional L3{,CODE,DATA} and MB resources.
/// Also supports generic hardware resources (e.g., L2, SMBA) as introduced
/// in OCI runtime-spec v1.3.0 via the `schemata` list feature.
fn get_line_type(line: &str) -> LineType {
    if line.starts_with("L3:") {
        return LineType::L3Line;
    }
    if line.starts_with("L3CODE:") {
        return LineType::L3CodeLine;
    }
    if line.starts_with("L3DATA:") {
        return LineType::L3DataLine;
    }
    if line.starts_with("MB:") {
        return LineType::MbLine;
    }

    // OCI runtime-spec v1.3.0 generic schemata list support.
    // If it's not a legacy L3/MB line, we extract the prefix before the colon
    // (e.g. "L2" from "L2:0=ff") and store it as `LineType::Other(prefix)`.
    // This allows us to retain the prefix for strict schema verification later,
    // rather than blindly dropping unknown hardware resources.
    if let Some(pos) = line.find(':') {
        let prefix = &line[..pos];
        if prefix.chars().all(|c| c.is_alphanumeric() || c == '_') {
            return LineType::Generic(prefix.to_string());
        }
    }

    LineType::Generic(String::new())
}

/// Parse a resctrl line.
fn parse_line(line: &str) -> Option<std::result::Result<ParsedLine, ParseLineError>> {
    let line_type = get_line_type(line);

    let maybe_tokens = match &line_type {
        LineType::L3Line => parse_l3_line(line).map(Some),
        LineType::L3DataLine => parse_l3_line(line).map(Some),
        LineType::L3CodeLine => parse_l3_line(line).map(Some),
        LineType::MbLine => parse_mb_line(line).map(Some),
        LineType::Generic(prefix) => {
            if prefix.is_empty() {
                Ok(None)
            } else {
                parse_generic_line(line).map(Some)
            }
        }
    };

    match maybe_tokens {
        Err(err) => Some(Err(err)),
        Ok(None) => None,
        Ok(Some(tokens)) => Some(Ok(ParsedLine { line_type, tokens })),
    }
}

/// Compare two sets of parsed lines. Do this both ways because of possible
/// duplicate lines, meaning that the vector lengths may be different.
fn compare_lines(first_lines: &[ParsedLine], second_lines: &[ParsedLine]) -> bool {
    first_lines.iter().all(|line| second_lines.contains(line))
        && second_lines.iter().all(|line| first_lines.contains(line))
}

/// Compares that two strings have the same set of lines (even if the lines are
/// in different order).
fn is_same_schema(combined_schema: &str, existing_schema: &str) -> Result<bool> {
    // Parse the strings first to lines and then to structs. Also filter
    // out lines that are non-L3{DATA,CODE} and non-MB.
    let combined = combined_schema
        .lines()
        .filter_map(parse_line)
        .collect::<std::result::Result<Vec<ParsedLine>, _>>()?;
    let existing = existing_schema
        .lines()
        .filter_map(parse_line)
        .collect::<std::result::Result<Vec<ParsedLine>, _>>()?;

    // Compare the two sets of parsed lines.
    Ok(compare_lines(&combined, &existing))
}

/// Retrieves the schemata data to be written to the resctrl filesystem.
/// OCI runtime-spec v1.3.0 introduced the generic `schemata` list, which
/// supersedes `l3_cache_schema` and `mem_bw_schema`. If the list is provided,
/// we append it to the legacy fields (l3_cache_schema and mem_bw_schema) and
/// join the array elements with a newline `\n` to format them correctly
/// for the Linux kernel's `schemata` file requirements.
fn get_schemata_data(intel_rdt: &LinuxIntelRdt) -> Option<String> {
    let legacy_schemata =
        combine_l3_cache_and_mem_bw_schemas(intel_rdt.l3_cache_schema(), intel_rdt.mem_bw_schema());

    if let Some(schemata) = intel_rdt.schemata() {
        if !schemata.is_empty() {
            let modern_schemata = schemata.join("\n");

            // If there's legacy schemata, prepend it (L3 first, then MB, then generic list)
            if let Some(legacy) = legacy_schemata {
                return Some(format!("{}\n{}", legacy, modern_schemata));
            }

            return Some(modern_schemata);
        }
    }

    legacy_schemata
}

/// Combines the l3_cache_schema and mem_bw_schema values together with the
/// rules given in Linux OCI runtime config spec. If clos_id_was_set parameter
/// is true and the directory wasn't created, the rules say that the schemas
/// need to be compared with the existing value and an error must be generated
/// if they don't match.
fn write_resctrl_schemata(
    path: &Path,
    id: &str,
    intel_rdt: &LinuxIntelRdt,
    clos_id_was_set: bool,
    created_dir: bool,
) -> Result<()> {
    let schemata = path.to_owned().join(id).join("schemata");
    let maybe_combined_schema = get_schemata_data(intel_rdt);

    if let Some(combined_schema) = maybe_combined_schema {
        if clos_id_was_set && !created_dir {
            // Compare existing schema and error out if no match.
            let data = fs::read_to_string(&schemata).map_err(IntelRdtError::ReadSchemata)?;
            if !is_same_schema(&combined_schema, &data)? {
                Err(IntelRdtError::ExistingSchemataMismatch)?;
            }
        } else {
            let mut file = OpenOptions::new()
                .truncate(true)
                .write(true)
                .open(schemata)
                .map_err(IntelRdtError::OpenSchemata)?;
            // Prevent write!() from writing the newline with a separate call.
            let schema_with_newline = combined_schema + "\n";
            write!(file, "{schema_with_newline}").map_err(IntelRdtError::WriteSchemata)?;
        }
    }

    Ok(())
}

/// Sets up Intel RDT configuration for the container process based on the OCI config.
/// This handles setting up the main resource allocation group (CLOS), applying schemata,
/// and setting up the dedicated monitoring group if `enable_monitoring` is true.
///
/// Returns a tuple of two optional paths: `(intel_rdt_dir, intel_rdt_monitoring_dir)`.
/// These indicate whether the runtime created the main group directory and/or the
/// monitoring directory, respectively. The runtime MUST remove these created
/// directories when the container is deleted.
pub fn setup_intel_rdt(
    maybe_container_id: Option<&str>,
    init_pid: &Pid,
    intel_rdt: &LinuxIntelRdt,
) -> Result<(Option<PathBuf>, Option<PathBuf>)> {
    // Find mounted resctrl filesystem, error out if it can't be found.
    let mount_point = find_resctrl_mount_point().inspect_err(|_err| {
        tracing::error!("failed to find a mounted resctrl file system");
    })?;

    let container_id = maybe_container_id.ok_or(IntelRdtError::ResctrlIdNotFound)?;
    let clos_id_set = intel_rdt.clos_id().is_some();
    let id = intel_rdt.clos_id().as_deref().unwrap_or(container_id);
    let has_schemata = intel_rdt.l3_cache_schema().is_some()
        || intel_rdt.mem_bw_schema().is_some()
        || intel_rdt.schemata().as_ref().is_some_and(|s| !s.is_empty());

    let only_clos_id_set = clos_id_set && !has_schemata;
    let container_dir = mount_point.join(id);
    let created_dir = setup_resctrl_group(&container_dir, *init_pid, only_clos_id_set)?;

    write_resctrl_schemata(&mount_point, id, intel_rdt, clos_id_set, created_dir).inspect_err(
        |_err| {
            tracing::error!("failed to write schemata to resctrl schemata file");
        },
    )?;

    let mut created_monitoring_dir = None;
    if intel_rdt.enable_monitoring().unwrap_or(false) {
        let mon_dir = container_dir.join("mon_groups").join(container_id);

        if !mon_dir.exists() {
            fs::create_dir_all(&mon_dir).map_err(|err| {
                tracing::error!("failed to create resctrl monitoring subdirectory: {err}");
                IntelRdtError::CreateMonitoringDirectory(err)
            })?;
        }

        write_pid_to_tasks(
            &mon_dir,
            *init_pid,
            IntelRdtError::OpenMonitoringTasksFile,
            IntelRdtError::WriteMonitoringTasksFile,
        )?;

        created_monitoring_dir = Some(mon_dir);
    }

    // If closID is not set and the runtime has created the sub-directory,
    // the runtime MUST remove the sub-directory when the container is deleted.
    let need_to_delete_directory = (!clos_id_set && created_dir).then_some(container_dir);

    Ok((need_to_delete_directory, created_monitoring_dir))
}

#[cfg(test)]
mod test {
    use std::fs;

    use anyhow::Result;

    use super::*;

    #[test]
    fn test_combine_schemas() -> Result<()> {
        let res = combine_l3_cache_and_mem_bw_schemas(&None, &None);
        assert!(res.is_none());

        let l3_1 = "L3:0=f;1=f0";
        let bw_1 = "MB:0=70;1=20";

        let res = combine_l3_cache_and_mem_bw_schemas(&Some(l3_1.to_owned()), &None);
        assert!(res.is_some());
        assert!(res.unwrap() == "L3:0=f;1=f0");

        let res = combine_l3_cache_and_mem_bw_schemas(&None, &Some(bw_1.to_owned()));
        assert!(res.is_some());
        assert!(res.unwrap() == "MB:0=70;1=20");

        let res =
            combine_l3_cache_and_mem_bw_schemas(&Some(l3_1.to_owned()), &Some(bw_1.to_owned()));
        assert!(res.is_some());
        let val = res.unwrap();
        assert!(val.lines().any(|line| line == "MB:0=70;1=20"));
        assert!(val.lines().any(|line| line == "L3:0=f;1=f0"));

        let l3_2 = "L3:0=f;1=f0\nL3:2=f\n;MB:0=20;1=70";
        let res =
            combine_l3_cache_and_mem_bw_schemas(&Some(l3_2.to_owned()), &Some(bw_1.to_owned()));
        assert!(res.is_some());
        let val = res.unwrap();
        assert!(val.lines().any(|line| line == "MB:0=70;1=20"));
        assert!(val.lines().any(|line| line == "L3:0=f;1=f0"));
        assert!(val.lines().any(|line| line == "L3:2=f"));
        assert!(!val.lines().any(|line| line == "MB:0=20;1=70"));

        // Generic schemata in the legacy L3 field should be passed through
        let l3_generic = "L3:0=f;1=f0\nL2:0=f\nMB:0=20;1=70";
        let res = combine_l3_cache_and_mem_bw_schemas(
            &Some(l3_generic.to_owned()),
            &Some(bw_1.to_owned()),
        );
        assert!(res.is_some());
        let val = res.unwrap();
        assert!(val.lines().any(|line| line == "L2:0=f"));
        assert!(!val.lines().any(|line| line == "MB:0=20;1=70"));

        // Messy whitespace and semicolons around MB in L3 should still be stripped
        let l3_messy_mb = "L3:0=f\nMB:  0=10; 1=20 ;;";
        let res = combine_l3_cache_and_mem_bw_schemas(
            &Some(l3_messy_mb.to_owned()),
            &Some(bw_1.to_owned()),
        );
        assert!(res.is_some());
        let val = res.unwrap();
        assert!(val.lines().any(|line| line == "L3:0=f"));
        assert!(!val.lines().any(|line| line.starts_with("MB:  0=10")));
        assert!(val.lines().any(|line| line == bw_1));

        Ok(())
    }

    #[test]
    fn test_is_same_schema() -> Result<()> {
        // Exact same schemas.
        assert!(is_same_schema("L3:0=f;1=f0", "L3:0=f;1=f0")?);
        assert!(is_same_schema("L3DATA:0=f;1=f0", "L3DATA:0=f;1=f0")?);
        assert!(is_same_schema("L3CODE:0=f;1=f0", "L3CODE:0=f;1=f0")?);
        assert!(is_same_schema("MB:0=bar;1=f0", "MB:0=bar;1=f0")?);
        assert!(is_same_schema("L3:", "L3:")?);
        assert!(is_same_schema("MB:", "MB:")?);
        assert!(is_same_schema("L2:0=f;1=f0", "L2:0=f;1=f0")?);
        assert!(is_same_schema("SMBA:0=20", "SMBA:0=20")?);

        // Different schemas.
        assert!(!is_same_schema("L3:0=f;1=f0", "L3:2=f")?);
        assert!(!is_same_schema("MB:0=bar;1=f0", "MB:0=foo;1=f0")?);
        assert!(!is_same_schema("L3DATA:0=f;1=f0", "L3CODE:2=f")?);
        assert!(!is_same_schema("L3DATA:0=f;1=f0", "L3CODE:2=f")?);
        assert!(!is_same_schema("L3DATA:0=f", "L3CODE:0=f")?);
        assert!(!is_same_schema("L3:0=f", "L3DATA:0=f")?);
        assert!(!is_same_schema("L3CODE:0=f", "L3:0=f")?);
        assert!(!is_same_schema("MB:0=f", "L3:0=f")?);
        assert!(!is_same_schema("L2:0=f", "L3:0=f")?);
        assert!(!is_same_schema("L2:0=f;1=f0", "L2:0=ff;1=f0")?);
        assert!(!is_same_schema("SMBA:0=20", "SMBA:0=30")?);
        assert!(!is_same_schema("SMBA:0=20", "MBA:0=20")?);

        // Exact same multi-line schema.
        assert!(is_same_schema(
            "L3:0=f;1=f0\nL3:2=f",
            "L3:0=f;1=f0\nL3:2=f"
        )?);

        // Malformed generic line types now cause verification to fail
        assert!(is_same_schema("L3:0=f;1=f0\nL3:2=f\nBAR:foo", "L3:0=f;1=f0\nL3:2=f").is_err());

        // Different multi-line schema.
        assert!(!is_same_schema(
            "L3:0=f;1=f0\nL3:2=f\nL3:3=f",
            "L3:0=f;1=f0\nL3:2=f"
        )?);

        // Different lines (two ways).
        assert!(!is_same_schema(
            "L3:0=f;1=f0\nL3:2=f\nL3:3=f",
            "L3:0=f;1=f0\nL3:2=f"
        )?);
        assert!(!is_same_schema(
            "L3:0=f;1=f0\nL3:2=f",
            "L3:0=f;1=f0\nL3:2=f\nL3:3=f"
        )?);

        // Same schema, different token order.
        assert!(is_same_schema("L3:1=f0;0=0", "L3:0=0;1=f0")?);
        assert!(is_same_schema("L2:1=f0;0=f", "L2:0=f;1=f0")?);

        // Same schema, different whitespace and semicolons.
        assert!(is_same_schema("L3:;;  0 = f; ;  1=f0", "L3:0=f;1  = f0;;")?);
        assert!(is_same_schema("L2:;;  0 = f; ;  1=f0", "L2:0=f;1  = f0;;")?);
        assert!(is_same_schema("L2:0=f;1=f0;", "L2:0=f;1=f0")?);
        assert!(is_same_schema("L2:  0  =  ff  ", "L2:0=ff")?);

        // Same schema, different leading zeros in masks.
        assert!(is_same_schema("L3:0=000f", "L3:0=0f")?);
        assert!(is_same_schema("L3:0=000f", "L3:0=0f")?);
        assert!(is_same_schema("L3:0=f", "L3:0=0f")?);
        assert!(is_same_schema("L3:0=0", "L3:0=0000")?);
        assert!(is_same_schema("L2:0=00ff;1=000f0", "L2:0=ff;1=f0")?);

        // Invalid schemas.
        assert!(is_same_schema("L3:1=;0=f", "L3:1=;0=f").is_err());
        assert!(is_same_schema("L3:=0;0=f", "L3:=0;0=f").is_err());
        assert!(is_same_schema("L3:1=0=3;0=f", "L3:1=0=3;0=f").is_err());
        assert!(is_same_schema("L3:1=bar", "L3:1=bar").is_err());
        assert!(is_same_schema("MB:1=;0=f", "MB:1=;0=f").is_err());
        assert!(is_same_schema("MB:=0;0=f", "MB:=0;0=f").is_err());
        assert!(is_same_schema("MB:1=0=3;0=f", "MB:1=0=3;0=f").is_err());
        assert!(is_same_schema("L2:0=invalid_hex_string", "L2:0=invalid_hex_string").is_err());
        assert!(
            is_same_schema(
                "L2:0=0123456789abcdef0123456789abcdef0123456789abcdefzz",
                "L2:0=0123456789abcdef0123456789abcdef0123456789abcdefzz"
            )
            .is_err()
        );

        // Generic schema handling leading zeros correctly
        assert!(is_same_schema("L2:0=00ff;1=000f0", "L2:0=ff;1=f0")?);

        // Zero value edge cases for generic schemas
        assert!(is_same_schema("L2:0=0;1=00", "L2:0=0;1=0")?);

        // Empty lines are ignored
        assert!(is_same_schema(
            "L3:0=f;1=f0\n\nL2:0=f\n",
            "L3:0=f;1=f0\nL2:0=f"
        )?);

        Ok(())
    }

    #[test]
    fn test_get_line_type() {
        assert!(matches!(get_line_type("L3:0=f"), LineType::L3Line));
        assert!(matches!(get_line_type("L3DATA:0=f"), LineType::L3DataLine));
        assert!(matches!(get_line_type("L3CODE:0=f"), LineType::L3CodeLine));
        assert!(matches!(get_line_type("MB:0=70"), LineType::MbLine));

        let generic_l2 = get_line_type("L2:0=f");
        if let LineType::Generic(prefix) = generic_l2 {
            assert_eq!(prefix, "L2");
        } else {
            panic!("Expected LineType::Generic");
        }

        let generic_smba = get_line_type("SMBA:0=20");
        if let LineType::Generic(prefix) = generic_smba {
            assert_eq!(prefix, "SMBA");
        } else {
            panic!("Expected LineType::Generic");
        }
    }

    #[test]
    fn test_parse_generic_line() -> Result<()> {
        let parsed = parse_generic_line("L2:0=00ff;1=f0")?;
        assert_eq!(parsed.get("0").unwrap(), "ff");
        assert_eq!(parsed.get("1").unwrap(), "f0");

        let parsed_zero = parse_generic_line("L2:0=0000;1=00")?;
        assert_eq!(parsed_zero.get("0").unwrap(), "0");
        assert_eq!(parsed_zero.get("1").unwrap(), "0");

        assert!(parse_generic_line("L2:0=;1=f0").is_err());
        assert!(parse_generic_line("L2:0=invalid_hex").is_err());

        Ok(())
    }

    #[test]
    fn test_get_schemata_data() {
        use oci_spec::runtime::LinuxIntelRdtBuilder;
        let rdt_modern = LinuxIntelRdtBuilder::default()
            .l3_cache_schema("L3:0=f;1=f0".to_owned())
            .mem_bw_schema("MB:0=70;1=20".to_owned())
            .schemata(vec!["L2:0=f;1=f0".to_owned(), "SMBA:0=20".to_owned()])
            .build()
            .unwrap();
        let combined_modern = get_schemata_data(&rdt_modern).unwrap();
        assert_eq!(
            combined_modern,
            "L3:0=f;1=f0\nMB:0=70;1=20\nL2:0=f;1=f0\nSMBA:0=20",
        );
    }

    #[test]
    fn test_setup_resctrl_group() -> Result<()> {
        let tmp = tempfile::tempdir().unwrap();

        // Helper to mock the resctrl filesystem structure
        let create_mock_group = |path: &std::path::Path| {
            fs::create_dir_all(path).unwrap();
            fs::File::create(path.join("tasks")).unwrap();
            fs::File::create(path.join("schemata")).unwrap();
        };

        // Create the directory for id "foo".
        let container_dir = tmp.path().join("foo");
        create_mock_group(&container_dir);
        let res = setup_resctrl_group(&container_dir, Pid::from_raw(1000), false);
        assert!(!res.unwrap()); // no new directory created
        let res = fs::read_to_string(container_dir.join("tasks"));
        assert!(res.unwrap() == "1000");

        // Create the same directory the second time.
        let res = setup_resctrl_group(&container_dir, Pid::from_raw(1500), false);
        assert!(!res.unwrap()); // no new directory created

        // If just clos_id then throw an error if the directory doesn't exist.
        let foobar_dir = tmp.path().join("foobar");
        let res = setup_resctrl_group(&foobar_dir, Pid::from_raw(2000), true);
        assert!(res.is_err());

        // If the directory already exists then it's fine to have just clos_id.
        create_mock_group(&foobar_dir);
        let res = setup_resctrl_group(&foobar_dir, Pid::from_raw(2500), true);
        assert!(!res.unwrap()); // no new directory created

        Ok(())
    }

    #[test]
    fn test_write_resctrl_schemata() -> Result<()> {
        use oci_spec::runtime::LinuxIntelRdtBuilder;
        let tmp = tempfile::tempdir().unwrap();
        let foobar_dir = tmp.path().join("foobar");

        let create_mock_group = |path: &Path| {
            fs::create_dir_all(path).unwrap();
            fs::File::create(path.join("tasks")).unwrap();
            fs::File::create(path.join("schemata")).unwrap();
        };
        create_mock_group(&foobar_dir);

        let res = setup_resctrl_group(&foobar_dir, Pid::from_raw(1000), false);
        assert!(!res.unwrap());

        // No schemes, clos_id was not set, directory created (with container id).
        let empty_rdt = LinuxIntelRdtBuilder::default().build().unwrap();
        let res = write_resctrl_schemata(tmp.path(), "foobar", &empty_rdt, false, true);
        assert!(res.is_ok());
        // Since we mock the files, it actually exists now but we haven't written to it
        let res = fs::read_to_string(tmp.path().join("foobar").join("schemata"));
        assert!(res.unwrap().is_empty());

        let l3_1 = "L3:0=f;1=f0\nL3:2=f\nMB:0=20;1=70";
        let bw_1 = "MB:0=70;1=20";
        let rdt_combined = LinuxIntelRdtBuilder::default()
            .l3_cache_schema(l3_1.to_owned())
            .mem_bw_schema(bw_1.to_owned())
            .build()
            .unwrap();
        let res = write_resctrl_schemata(tmp.path(), "foobar", &rdt_combined, false, true);
        assert!(res.is_ok());

        let res = fs::read_to_string(tmp.path().join("foobar").join("schemata"));
        assert!(res.is_ok());
        assert!(is_same_schema(
            "L3:0=f;1=f0\nL3:2=f\nMB:0=70;1=20\n",
            &res.unwrap()
        )?);

        // Try the verification case. If the directory existed (was not created
        // by us) and the clos_id was set, it needs to contain the same data as
        // we are trying to set. This is the same data:
        let res = write_resctrl_schemata(tmp.path(), "foobar", &rdt_combined, true, false);
        assert!(res.is_ok());

        // And this different data:
        let l3_2 = "L3:0=f;1=f0\nMB:0=20;1=70";
        let bw_2 = "MB:0=70;1=20";
        let rdt_different = LinuxIntelRdtBuilder::default()
            .l3_cache_schema(l3_2.to_owned())
            .mem_bw_schema(bw_2.to_owned())
            .build()
            .unwrap();
        let res = write_resctrl_schemata(tmp.path(), "foobar", &rdt_different, true, false);
        assert!(res.is_err());

        // Test modern schemata field merging
        let rdt_schemata = LinuxIntelRdtBuilder::default()
            .l3_cache_schema(l3_1.to_owned())
            .mem_bw_schema(bw_1.to_owned())
            .schemata(vec!["L2:0=f;1=f0".to_owned()])
            .build()
            .unwrap();

        let foobar_modern_dir = tmp.path().join("foobar_modern");
        create_mock_group(&foobar_modern_dir);
        let _ = setup_resctrl_group(&foobar_modern_dir, Pid::from_raw(1001), false);
        let res = write_resctrl_schemata(tmp.path(), "foobar_modern", &rdt_schemata, false, true);

        assert!(res.is_ok());
        let written_data =
            fs::read_to_string(tmp.path().join("foobar_modern").join("schemata")).unwrap();
        assert_eq!(
            written_data,
            "L3:0=f;1=f0\nL3:2=f\nMB:0=70;1=20\nL2:0=f;1=f0\n"
        );

        Ok(())
    }

    #[test]
    fn test_cleanup_intel_rdt() -> Result<()> {
        let tmp = tempfile::tempdir().unwrap();
        let mon_dir = tmp.path().join("mon_groups").join("test_container");
        fs::create_dir_all(&mon_dir)?;

        let res = cleanup_intel_rdt(None, Some(&mon_dir), None, "test_container");
        assert!(res.is_ok());
        assert!(!mon_dir.exists());

        // Both paths are provided, and since they are absolute and explicit,
        // it shouldn't fail even in test because it just deletes them directly.
        let rdt_dir = tmp.path().join("test_container");
        fs::create_dir_all(&rdt_dir)?;
        let res = cleanup_intel_rdt(Some(&rdt_dir), None, None, "test_container");
        assert!(res.is_ok());
        assert!(!rdt_dir.exists());

        // Legacy flag is provided (`clean_up_intel_rdt_subdirectory=true`).
        // It will also fail trying to find the mount point, and should aggregate correctly.
        let res = cleanup_intel_rdt(None, None, Some(true), "test_container");
        assert!(res.is_err());
        let err_str = res.unwrap_err().to_string();
        assert!(err_str.contains("failed to find resctrl mount point"));

        Ok(())
    }
}