]> git.proxmox.com Git - proxmox-backup.git/blob - src/api2/types/mod.rs
127c7210384d2f7f193de47dc6b48d4b15a39a19
[proxmox-backup.git] / src / api2 / types / mod.rs
1 use anyhow::bail;
2 use serde::{Deserialize, Serialize};
3
4 use proxmox::api::{api, schema::*};
5 use proxmox::const_regex;
6 use proxmox::{IPRE, IPRE_BRACKET, IPV4RE, IPV6RE, IPV4OCTET, IPV6H16, IPV6LS32};
7
8 use crate::backup::CryptMode;
9 use crate::server::UPID;
10
11 #[macro_use]
12 mod macros;
13
14 #[macro_use]
15 mod userid;
16 pub use userid::{Realm, RealmRef};
17 pub use userid::{Tokenname, TokennameRef};
18 pub use userid::{Username, UsernameRef};
19 pub use userid::Userid;
20 pub use userid::Authid;
21 pub use userid::{PROXMOX_TOKEN_ID_SCHEMA, PROXMOX_TOKEN_NAME_SCHEMA, PROXMOX_GROUP_ID_SCHEMA};
22
23 // File names: may not contain slashes, may not start with "."
24 pub const FILENAME_FORMAT: ApiStringFormat = ApiStringFormat::VerifyFn(|name| {
25 if name.starts_with('.') {
26 bail!("file names may not start with '.'");
27 }
28 if name.contains('/') {
29 bail!("file names may not contain slashes");
30 }
31 Ok(())
32 });
33
34 macro_rules! DNS_LABEL { () => (r"(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?)") }
35 macro_rules! DNS_NAME { () => (concat!(r"(?:(?:", DNS_LABEL!() , r"\.)*", DNS_LABEL!(), ")")) }
36
37 macro_rules! CIDR_V4_REGEX_STR { () => (concat!(r"(?:", IPV4RE!(), r"/\d{1,2})$")) }
38 macro_rules! CIDR_V6_REGEX_STR { () => (concat!(r"(?:", IPV6RE!(), r"/\d{1,3})$")) }
39
40 const_regex!{
41 pub IP_V4_REGEX = concat!(r"^", IPV4RE!(), r"$");
42 pub IP_V6_REGEX = concat!(r"^", IPV6RE!(), r"$");
43 pub IP_REGEX = concat!(r"^", IPRE!(), r"$");
44 pub CIDR_V4_REGEX = concat!(r"^", CIDR_V4_REGEX_STR!(), r"$");
45 pub CIDR_V6_REGEX = concat!(r"^", CIDR_V6_REGEX_STR!(), r"$");
46 pub CIDR_REGEX = concat!(r"^(?:", CIDR_V4_REGEX_STR!(), "|", CIDR_V6_REGEX_STR!(), r")$");
47
48 pub SHA256_HEX_REGEX = r"^[a-f0-9]{64}$"; // fixme: define in common_regex ?
49 pub SYSTEMD_DATETIME_REGEX = r"^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$"; // fixme: define in common_regex ?
50
51 pub PASSWORD_REGEX = r"^[[:^cntrl:]]*$"; // everything but control characters
52
53 /// Regex for safe identifiers.
54 ///
55 /// This
56 /// [article](https://dwheeler.com/essays/fixing-unix-linux-filenames.html)
57 /// contains further information why it is reasonable to restict
58 /// names this way. This is not only useful for filenames, but for
59 /// any identifier command line tools work with.
60 pub PROXMOX_SAFE_ID_REGEX = concat!(r"^", PROXMOX_SAFE_ID_REGEX_STR!(), r"$");
61
62 pub SINGLE_LINE_COMMENT_REGEX = r"^[[:^cntrl:]]*$";
63
64 pub HOSTNAME_REGEX = r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?)$";
65
66 pub DNS_NAME_REGEX = concat!(r"^", DNS_NAME!(), r"$");
67
68 pub DNS_NAME_OR_IP_REGEX = concat!(r"^(?:", DNS_NAME!(), "|", IPRE!(), r")$");
69
70 pub BACKUP_REPO_URL_REGEX = concat!(r"^^(?:(?:(", USER_ID_REGEX_STR!(), "|", APITOKEN_ID_REGEX_STR!(), ")@)?(", DNS_NAME!(), "|", IPRE_BRACKET!() ,"):)?(?:([0-9]{1,5}):)?(", PROXMOX_SAFE_ID_REGEX_STR!(), r")$");
71
72 pub CERT_FINGERPRINT_SHA256_REGEX = r"^(?:[0-9a-fA-F][0-9a-fA-F])(?::[0-9a-fA-F][0-9a-fA-F]){31}$";
73
74 pub ACL_PATH_REGEX = concat!(r"^(?:/|", r"(?:/", PROXMOX_SAFE_ID_REGEX_STR!(), ")+", r")$");
75
76 pub SUBSCRIPTION_KEY_REGEX = concat!(r"^pbs(?:[cbsp])-[0-9a-f]{10}$");
77
78 pub BLOCKDEVICE_NAME_REGEX = r"^(:?(:?h|s|x?v)d[a-z]+)|(:?nvme\d+n\d+)$";
79
80 pub ZPOOL_NAME_REGEX = r"^[a-zA-Z][a-z0-9A-Z\-_.:]+$";
81 }
82
83 pub const SYSTEMD_DATETIME_FORMAT: ApiStringFormat =
84 ApiStringFormat::Pattern(&SYSTEMD_DATETIME_REGEX);
85
86 pub const IP_V4_FORMAT: ApiStringFormat =
87 ApiStringFormat::Pattern(&IP_V4_REGEX);
88
89 pub const IP_V6_FORMAT: ApiStringFormat =
90 ApiStringFormat::Pattern(&IP_V6_REGEX);
91
92 pub const IP_FORMAT: ApiStringFormat =
93 ApiStringFormat::Pattern(&IP_REGEX);
94
95 pub const PVE_CONFIG_DIGEST_FORMAT: ApiStringFormat =
96 ApiStringFormat::Pattern(&SHA256_HEX_REGEX);
97
98 pub const CERT_FINGERPRINT_SHA256_FORMAT: ApiStringFormat =
99 ApiStringFormat::Pattern(&CERT_FINGERPRINT_SHA256_REGEX);
100
101 pub const PROXMOX_SAFE_ID_FORMAT: ApiStringFormat =
102 ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
103
104 pub const SINGLE_LINE_COMMENT_FORMAT: ApiStringFormat =
105 ApiStringFormat::Pattern(&SINGLE_LINE_COMMENT_REGEX);
106
107 pub const HOSTNAME_FORMAT: ApiStringFormat =
108 ApiStringFormat::Pattern(&HOSTNAME_REGEX);
109
110 pub const DNS_NAME_FORMAT: ApiStringFormat =
111 ApiStringFormat::Pattern(&DNS_NAME_REGEX);
112
113 pub const DNS_NAME_OR_IP_FORMAT: ApiStringFormat =
114 ApiStringFormat::Pattern(&DNS_NAME_OR_IP_REGEX);
115
116 pub const PASSWORD_FORMAT: ApiStringFormat =
117 ApiStringFormat::Pattern(&PASSWORD_REGEX);
118
119 pub const ACL_PATH_FORMAT: ApiStringFormat =
120 ApiStringFormat::Pattern(&ACL_PATH_REGEX);
121
122 pub const NETWORK_INTERFACE_FORMAT: ApiStringFormat =
123 ApiStringFormat::Pattern(&PROXMOX_SAFE_ID_REGEX);
124
125 pub const CIDR_V4_FORMAT: ApiStringFormat =
126 ApiStringFormat::Pattern(&CIDR_V4_REGEX);
127
128 pub const CIDR_V6_FORMAT: ApiStringFormat =
129 ApiStringFormat::Pattern(&CIDR_V6_REGEX);
130
131 pub const CIDR_FORMAT: ApiStringFormat =
132 ApiStringFormat::Pattern(&CIDR_REGEX);
133
134 pub const SUBSCRIPTION_KEY_FORMAT: ApiStringFormat =
135 ApiStringFormat::Pattern(&SUBSCRIPTION_KEY_REGEX);
136
137 pub const BLOCKDEVICE_NAME_FORMAT: ApiStringFormat =
138 ApiStringFormat::Pattern(&BLOCKDEVICE_NAME_REGEX);
139
140 pub const PASSWORD_SCHEMA: Schema = StringSchema::new("Password.")
141 .format(&PASSWORD_FORMAT)
142 .min_length(1)
143 .max_length(1024)
144 .schema();
145
146 pub const PBS_PASSWORD_SCHEMA: Schema = StringSchema::new("User Password.")
147 .format(&PASSWORD_FORMAT)
148 .min_length(5)
149 .max_length(64)
150 .schema();
151
152 pub const CERT_FINGERPRINT_SHA256_SCHEMA: Schema = StringSchema::new(
153 "X509 certificate fingerprint (sha256)."
154 )
155 .format(&CERT_FINGERPRINT_SHA256_FORMAT)
156 .schema();
157
158 pub const PROXMOX_CONFIG_DIGEST_SCHEMA: Schema = StringSchema::new(r#"\
159 Prevent changes if current configuration file has different SHA256 digest.
160 This can be used to prevent concurrent modifications.
161 "#
162 )
163 .format(&PVE_CONFIG_DIGEST_FORMAT)
164 .schema();
165
166
167 pub const CHUNK_DIGEST_FORMAT: ApiStringFormat =
168 ApiStringFormat::Pattern(&SHA256_HEX_REGEX);
169
170 pub const CHUNK_DIGEST_SCHEMA: Schema = StringSchema::new("Chunk digest (SHA256).")
171 .format(&CHUNK_DIGEST_FORMAT)
172 .schema();
173
174 pub const NODE_SCHEMA: Schema = StringSchema::new("Node name (or 'localhost')")
175 .format(&ApiStringFormat::VerifyFn(|node| {
176 if node == "localhost" || node == proxmox::tools::nodename() {
177 Ok(())
178 } else {
179 bail!("no such node '{}'", node);
180 }
181 }))
182 .schema();
183
184 pub const SEARCH_DOMAIN_SCHEMA: Schema =
185 StringSchema::new("Search domain for host-name lookup.").schema();
186
187 pub const FIRST_DNS_SERVER_SCHEMA: Schema =
188 StringSchema::new("First name server IP address.")
189 .format(&IP_FORMAT)
190 .schema();
191
192 pub const SECOND_DNS_SERVER_SCHEMA: Schema =
193 StringSchema::new("Second name server IP address.")
194 .format(&IP_FORMAT)
195 .schema();
196
197 pub const THIRD_DNS_SERVER_SCHEMA: Schema =
198 StringSchema::new("Third name server IP address.")
199 .format(&IP_FORMAT)
200 .schema();
201
202 pub const IP_V4_SCHEMA: Schema =
203 StringSchema::new("IPv4 address.")
204 .format(&IP_V4_FORMAT)
205 .max_length(15)
206 .schema();
207
208 pub const IP_V6_SCHEMA: Schema =
209 StringSchema::new("IPv6 address.")
210 .format(&IP_V6_FORMAT)
211 .max_length(39)
212 .schema();
213
214 pub const IP_SCHEMA: Schema =
215 StringSchema::new("IP (IPv4 or IPv6) address.")
216 .format(&IP_FORMAT)
217 .max_length(39)
218 .schema();
219
220 pub const CIDR_V4_SCHEMA: Schema =
221 StringSchema::new("IPv4 address with netmask (CIDR notation).")
222 .format(&CIDR_V4_FORMAT)
223 .max_length(18)
224 .schema();
225
226 pub const CIDR_V6_SCHEMA: Schema =
227 StringSchema::new("IPv6 address with netmask (CIDR notation).")
228 .format(&CIDR_V6_FORMAT)
229 .max_length(43)
230 .schema();
231
232 pub const CIDR_SCHEMA: Schema =
233 StringSchema::new("IP address (IPv4 or IPv6) with netmask (CIDR notation).")
234 .format(&CIDR_FORMAT)
235 .max_length(43)
236 .schema();
237
238 pub const TIME_ZONE_SCHEMA: Schema = StringSchema::new(
239 "Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.")
240 .format(&SINGLE_LINE_COMMENT_FORMAT)
241 .min_length(2)
242 .max_length(64)
243 .schema();
244
245 pub const ACL_PATH_SCHEMA: Schema = StringSchema::new(
246 "Access control path.")
247 .format(&ACL_PATH_FORMAT)
248 .min_length(1)
249 .max_length(128)
250 .schema();
251
252 pub const ACL_PROPAGATE_SCHEMA: Schema = BooleanSchema::new(
253 "Allow to propagate (inherit) permissions.")
254 .default(true)
255 .schema();
256
257 pub const ACL_UGID_TYPE_SCHEMA: Schema = StringSchema::new(
258 "Type of 'ugid' property.")
259 .format(&ApiStringFormat::Enum(&[
260 EnumEntry::new("user", "User"),
261 EnumEntry::new("group", "Group")]))
262 .schema();
263
264 pub const BACKUP_ARCHIVE_NAME_SCHEMA: Schema =
265 StringSchema::new("Backup archive name.")
266 .format(&PROXMOX_SAFE_ID_FORMAT)
267 .schema();
268
269 pub const BACKUP_TYPE_SCHEMA: Schema =
270 StringSchema::new("Backup type.")
271 .format(&ApiStringFormat::Enum(&[
272 EnumEntry::new("vm", "Virtual Machine Backup"),
273 EnumEntry::new("ct", "Container Backup"),
274 EnumEntry::new("host", "Host Backup")]))
275 .schema();
276
277 pub const BACKUP_ID_SCHEMA: Schema =
278 StringSchema::new("Backup ID.")
279 .format(&PROXMOX_SAFE_ID_FORMAT)
280 .schema();
281
282 pub const BACKUP_TIME_SCHEMA: Schema =
283 IntegerSchema::new("Backup time (Unix epoch.)")
284 .minimum(1_547_797_308)
285 .schema();
286
287 pub const UPID_SCHEMA: Schema = StringSchema::new("Unique Process/Task ID.")
288 .max_length(256)
289 .schema();
290
291 pub const DATASTORE_SCHEMA: Schema = StringSchema::new("Datastore name.")
292 .format(&PROXMOX_SAFE_ID_FORMAT)
293 .min_length(3)
294 .max_length(32)
295 .schema();
296
297 pub const SYNC_SCHEDULE_SCHEMA: Schema = StringSchema::new(
298 "Run sync job at specified schedule.")
299 .format(&ApiStringFormat::VerifyFn(crate::tools::systemd::time::verify_calendar_event))
300 .schema();
301
302 pub const GC_SCHEDULE_SCHEMA: Schema = StringSchema::new(
303 "Run garbage collection job at specified schedule.")
304 .format(&ApiStringFormat::VerifyFn(crate::tools::systemd::time::verify_calendar_event))
305 .schema();
306
307 pub const PRUNE_SCHEDULE_SCHEMA: Schema = StringSchema::new(
308 "Run prune job at specified schedule.")
309 .format(&ApiStringFormat::VerifyFn(crate::tools::systemd::time::verify_calendar_event))
310 .schema();
311
312 pub const VERIFICATION_SCHEDULE_SCHEMA: Schema = StringSchema::new(
313 "Run verify job at specified schedule.")
314 .format(&ApiStringFormat::VerifyFn(crate::tools::systemd::time::verify_calendar_event))
315 .schema();
316
317 pub const REMOTE_ID_SCHEMA: Schema = StringSchema::new("Remote ID.")
318 .format(&PROXMOX_SAFE_ID_FORMAT)
319 .min_length(3)
320 .max_length(32)
321 .schema();
322
323 pub const JOB_ID_SCHEMA: Schema = StringSchema::new("Job ID.")
324 .format(&PROXMOX_SAFE_ID_FORMAT)
325 .min_length(3)
326 .max_length(32)
327 .schema();
328
329 pub const REMOVE_VANISHED_BACKUPS_SCHEMA: Schema = BooleanSchema::new(
330 "Delete vanished backups. This remove the local copy if the remote backup was deleted.")
331 .default(true)
332 .schema();
333
334 pub const IGNORE_VERIFIED_BACKUPS_SCHEMA: Schema = BooleanSchema::new(
335 "Do not verify backups that are already verified if their verification is not outdated.")
336 .default(true)
337 .schema();
338
339 pub const VERIFICATION_OUTDATED_AFTER_SCHEMA: Schema = IntegerSchema::new(
340 "Days after that a verification becomes outdated")
341 .minimum(1)
342 .schema();
343
344 pub const SINGLE_LINE_COMMENT_SCHEMA: Schema = StringSchema::new("Comment (single line).")
345 .format(&SINGLE_LINE_COMMENT_FORMAT)
346 .schema();
347
348 pub const HOSTNAME_SCHEMA: Schema = StringSchema::new("Hostname (as defined in RFC1123).")
349 .format(&HOSTNAME_FORMAT)
350 .schema();
351
352 pub const DNS_NAME_OR_IP_SCHEMA: Schema = StringSchema::new("DNS name or IP address.")
353 .format(&DNS_NAME_OR_IP_FORMAT)
354 .schema();
355
356 pub const SUBSCRIPTION_KEY_SCHEMA: Schema = StringSchema::new("Proxmox Backup Server subscription key.")
357 .format(&SUBSCRIPTION_KEY_FORMAT)
358 .min_length(15)
359 .max_length(16)
360 .schema();
361
362 pub const BLOCKDEVICE_NAME_SCHEMA: Schema = StringSchema::new("Block device name (/sys/block/<name>).")
363 .format(&BLOCKDEVICE_NAME_FORMAT)
364 .min_length(3)
365 .max_length(64)
366 .schema();
367
368 // Complex type definitions
369
370 #[api(
371 properties: {
372 "backup-type": {
373 schema: BACKUP_TYPE_SCHEMA,
374 },
375 "backup-id": {
376 schema: BACKUP_ID_SCHEMA,
377 },
378 "last-backup": {
379 schema: BACKUP_TIME_SCHEMA,
380 },
381 "backup-count": {
382 type: Integer,
383 },
384 files: {
385 items: {
386 schema: BACKUP_ARCHIVE_NAME_SCHEMA
387 },
388 },
389 owner: {
390 type: Authid,
391 optional: true,
392 },
393 },
394 )]
395 #[derive(Serialize, Deserialize)]
396 #[serde(rename_all="kebab-case")]
397 /// Basic information about a backup group.
398 pub struct GroupListItem {
399 pub backup_type: String, // enum
400 pub backup_id: String,
401 pub last_backup: i64,
402 /// Number of contained snapshots
403 pub backup_count: u64,
404 /// List of contained archive files.
405 pub files: Vec<String>,
406 /// The owner of group
407 #[serde(skip_serializing_if="Option::is_none")]
408 pub owner: Option<Authid>,
409 }
410
411 #[api()]
412 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
413 #[serde(rename_all = "lowercase")]
414 /// Result of a verify operation.
415 pub enum VerifyState {
416 /// Verification was successful
417 Ok,
418 /// Verification reported one or more errors
419 Failed,
420 }
421
422 #[api(
423 properties: {
424 upid: {
425 schema: UPID_SCHEMA
426 },
427 state: {
428 type: VerifyState
429 },
430 },
431 )]
432 #[derive(Serialize, Deserialize)]
433 /// Task properties.
434 pub struct SnapshotVerifyState {
435 /// UPID of the verify task
436 pub upid: UPID,
437 /// State of the verification. Enum.
438 pub state: VerifyState,
439 }
440
441 #[api(
442 properties: {
443 "backup-type": {
444 schema: BACKUP_TYPE_SCHEMA,
445 },
446 "backup-id": {
447 schema: BACKUP_ID_SCHEMA,
448 },
449 "backup-time": {
450 schema: BACKUP_TIME_SCHEMA,
451 },
452 comment: {
453 schema: SINGLE_LINE_COMMENT_SCHEMA,
454 optional: true,
455 },
456 verification: {
457 type: SnapshotVerifyState,
458 optional: true,
459 },
460 files: {
461 items: {
462 schema: BACKUP_ARCHIVE_NAME_SCHEMA
463 },
464 },
465 owner: {
466 type: Authid,
467 optional: true,
468 },
469 },
470 )]
471 #[derive(Serialize, Deserialize)]
472 #[serde(rename_all="kebab-case")]
473 /// Basic information about backup snapshot.
474 pub struct SnapshotListItem {
475 pub backup_type: String, // enum
476 pub backup_id: String,
477 pub backup_time: i64,
478 /// The first line from manifest "notes"
479 #[serde(skip_serializing_if="Option::is_none")]
480 pub comment: Option<String>,
481 /// The result of the last run verify task
482 #[serde(skip_serializing_if="Option::is_none")]
483 pub verification: Option<SnapshotVerifyState>,
484 /// List of contained archive files.
485 pub files: Vec<BackupContent>,
486 /// Overall snapshot size (sum of all archive sizes).
487 #[serde(skip_serializing_if="Option::is_none")]
488 pub size: Option<u64>,
489 /// The owner of the snapshots group
490 #[serde(skip_serializing_if="Option::is_none")]
491 pub owner: Option<Authid>,
492 }
493
494 #[api(
495 properties: {
496 "backup-type": {
497 schema: BACKUP_TYPE_SCHEMA,
498 },
499 "backup-id": {
500 schema: BACKUP_ID_SCHEMA,
501 },
502 "backup-time": {
503 schema: BACKUP_TIME_SCHEMA,
504 },
505 },
506 )]
507 #[derive(Serialize, Deserialize)]
508 #[serde(rename_all="kebab-case")]
509 /// Prune result.
510 pub struct PruneListItem {
511 pub backup_type: String, // enum
512 pub backup_id: String,
513 pub backup_time: i64,
514 /// Keep snapshot
515 pub keep: bool,
516 }
517
518 pub const PRUNE_SCHEMA_KEEP_DAILY: Schema = IntegerSchema::new(
519 "Number of daily backups to keep.")
520 .minimum(1)
521 .schema();
522
523 pub const PRUNE_SCHEMA_KEEP_HOURLY: Schema = IntegerSchema::new(
524 "Number of hourly backups to keep.")
525 .minimum(1)
526 .schema();
527
528 pub const PRUNE_SCHEMA_KEEP_LAST: Schema = IntegerSchema::new(
529 "Number of backups to keep.")
530 .minimum(1)
531 .schema();
532
533 pub const PRUNE_SCHEMA_KEEP_MONTHLY: Schema = IntegerSchema::new(
534 "Number of monthly backups to keep.")
535 .minimum(1)
536 .schema();
537
538 pub const PRUNE_SCHEMA_KEEP_WEEKLY: Schema = IntegerSchema::new(
539 "Number of weekly backups to keep.")
540 .minimum(1)
541 .schema();
542
543 pub const PRUNE_SCHEMA_KEEP_YEARLY: Schema = IntegerSchema::new(
544 "Number of yearly backups to keep.")
545 .minimum(1)
546 .schema();
547
548 #[api(
549 properties: {
550 "filename": {
551 schema: BACKUP_ARCHIVE_NAME_SCHEMA,
552 },
553 "crypt-mode": {
554 type: CryptMode,
555 optional: true,
556 },
557 },
558 )]
559 #[derive(Serialize, Deserialize)]
560 #[serde(rename_all="kebab-case")]
561 /// Basic information about archive files inside a backup snapshot.
562 pub struct BackupContent {
563 pub filename: String,
564 /// Info if file is encrypted, signed, or neither.
565 #[serde(skip_serializing_if="Option::is_none")]
566 pub crypt_mode: Option<CryptMode>,
567 /// Archive size (from backup manifest).
568 #[serde(skip_serializing_if="Option::is_none")]
569 pub size: Option<u64>,
570 }
571
572 #[api(
573 properties: {
574 "upid": {
575 optional: true,
576 schema: UPID_SCHEMA,
577 },
578 },
579 )]
580 #[derive(Clone, Serialize, Deserialize)]
581 #[serde(rename_all="kebab-case")]
582 /// Garbage collection status.
583 pub struct GarbageCollectionStatus {
584 pub upid: Option<String>,
585 /// Number of processed index files.
586 pub index_file_count: usize,
587 /// Sum of bytes referred by index files.
588 pub index_data_bytes: u64,
589 /// Bytes used on disk.
590 pub disk_bytes: u64,
591 /// Chunks used on disk.
592 pub disk_chunks: usize,
593 /// Sum of removed bytes.
594 pub removed_bytes: u64,
595 /// Number of removed chunks.
596 pub removed_chunks: usize,
597 /// Sum of pending bytes (pending removal - kept for safety).
598 pub pending_bytes: u64,
599 /// Number of pending chunks (pending removal - kept for safety).
600 pub pending_chunks: usize,
601 /// Number of chunks marked as .bad by verify that have been removed by GC.
602 pub removed_bad: usize,
603 /// Number of chunks still marked as .bad after garbage collection.
604 pub still_bad: usize,
605 }
606
607 impl Default for GarbageCollectionStatus {
608 fn default() -> Self {
609 GarbageCollectionStatus {
610 upid: None,
611 index_file_count: 0,
612 index_data_bytes: 0,
613 disk_bytes: 0,
614 disk_chunks: 0,
615 removed_bytes: 0,
616 removed_chunks: 0,
617 pending_bytes: 0,
618 pending_chunks: 0,
619 removed_bad: 0,
620 still_bad: 0,
621 }
622 }
623 }
624
625
626 #[api()]
627 #[derive(Serialize, Deserialize)]
628 /// Storage space usage information.
629 pub struct StorageStatus {
630 /// Total space (bytes).
631 pub total: u64,
632 /// Used space (bytes).
633 pub used: u64,
634 /// Available space (bytes).
635 pub avail: u64,
636 }
637
638 #[api()]
639 #[derive(Serialize, Deserialize, Default)]
640 /// Backup Type group/snapshot counts.
641 pub struct TypeCounts {
642 /// The number of groups of the type.
643 pub groups: u64,
644 /// The number of snapshots of the type.
645 pub snapshots: u64,
646 }
647
648 #[api(
649 properties: {
650 ct: {
651 type: TypeCounts,
652 optional: true,
653 },
654 host: {
655 type: TypeCounts,
656 optional: true,
657 },
658 vm: {
659 type: TypeCounts,
660 optional: true,
661 },
662 other: {
663 type: TypeCounts,
664 optional: true,
665 },
666 },
667 )]
668 #[derive(Serialize, Deserialize)]
669 /// Counts of groups/snapshots per BackupType.
670 pub struct Counts {
671 /// The counts for CT backups
672 pub ct: Option<TypeCounts>,
673 /// The counts for Host backups
674 pub host: Option<TypeCounts>,
675 /// The counts for VM backups
676 pub vm: Option<TypeCounts>,
677 /// The counts for other backup types
678 pub other: Option<TypeCounts>,
679 }
680
681 #[api(
682 properties: {
683 "gc-status": { type: GarbageCollectionStatus, },
684 counts: { type: Counts, }
685 },
686 )]
687 #[derive(Serialize, Deserialize)]
688 #[serde(rename_all="kebab-case")]
689 /// Overall Datastore status and useful information.
690 pub struct DataStoreStatus {
691 /// Total space (bytes).
692 pub total: u64,
693 /// Used space (bytes).
694 pub used: u64,
695 /// Available space (bytes).
696 pub avail: u64,
697 /// Status of last GC
698 pub gc_status: GarbageCollectionStatus,
699 /// Group/Snapshot counts
700 pub counts: Counts,
701 }
702
703 #[api(
704 properties: {
705 upid: { schema: UPID_SCHEMA },
706 user: { type: Authid },
707 },
708 )]
709 #[derive(Serialize, Deserialize)]
710 /// Task properties.
711 pub struct TaskListItem {
712 pub upid: String,
713 /// The node name where the task is running on.
714 pub node: String,
715 /// The Unix PID
716 pub pid: i64,
717 /// The task start time (Epoch)
718 pub pstart: u64,
719 /// The task start time (Epoch)
720 pub starttime: i64,
721 /// Worker type (arbitrary ASCII string)
722 pub worker_type: String,
723 /// Worker ID (arbitrary ASCII string)
724 pub worker_id: Option<String>,
725 /// The authenticated entity who started the task
726 pub user: Authid,
727 /// The task end time (Epoch)
728 #[serde(skip_serializing_if="Option::is_none")]
729 pub endtime: Option<i64>,
730 /// Task end status
731 #[serde(skip_serializing_if="Option::is_none")]
732 pub status: Option<String>,
733 }
734
735 impl From<crate::server::TaskListInfo> for TaskListItem {
736 fn from(info: crate::server::TaskListInfo) -> Self {
737 let (endtime, status) = info
738 .state
739 .map_or_else(|| (None, None), |a| (Some(a.endtime()), Some(a.to_string())));
740
741 TaskListItem {
742 upid: info.upid_str,
743 node: "localhost".to_string(),
744 pid: info.upid.pid as i64,
745 pstart: info.upid.pstart,
746 starttime: info.upid.starttime,
747 worker_type: info.upid.worker_type,
748 worker_id: info.upid.worker_id,
749 user: info.upid.auth_id,
750 endtime,
751 status,
752 }
753 }
754 }
755
756 #[api()]
757 #[derive(Eq, PartialEq, Debug, Serialize, Deserialize)]
758 #[serde(rename_all = "lowercase")]
759 pub enum TaskStateType {
760 /// Ok
761 OK,
762 /// Warning
763 Warning,
764 /// Error
765 Error,
766 /// Unknown
767 Unknown,
768 }
769
770 #[api()]
771 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
772 #[serde(rename_all = "lowercase")]
773 /// Node Power command type.
774 pub enum NodePowerCommand {
775 /// Restart the server
776 Reboot,
777 /// Shutdown the server
778 Shutdown,
779 }
780
781 #[api()]
782 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
783 #[serde(rename_all = "lowercase")]
784 /// Interface configuration method
785 pub enum NetworkConfigMethod {
786 /// Configuration is done manually using other tools
787 Manual,
788 /// Define interfaces with statically allocated addresses.
789 Static,
790 /// Obtain an address via DHCP
791 DHCP,
792 /// Define the loopback interface.
793 Loopback,
794 }
795
796 #[api()]
797 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
798 #[serde(rename_all = "kebab-case")]
799 #[allow(non_camel_case_types)]
800 #[repr(u8)]
801 /// Linux Bond Mode
802 pub enum LinuxBondMode {
803 /// Round-robin policy
804 balance_rr = 0,
805 /// Active-backup policy
806 active_backup = 1,
807 /// XOR policy
808 balance_xor = 2,
809 /// Broadcast policy
810 broadcast = 3,
811 /// IEEE 802.3ad Dynamic link aggregation
812 #[serde(rename = "802.3ad")]
813 ieee802_3ad = 4,
814 /// Adaptive transmit load balancing
815 balance_tlb = 5,
816 /// Adaptive load balancing
817 balance_alb = 6,
818 }
819
820 #[api()]
821 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
822 #[serde(rename_all = "kebab-case")]
823 #[allow(non_camel_case_types)]
824 #[repr(u8)]
825 /// Bond Transmit Hash Policy for LACP (802.3ad)
826 pub enum BondXmitHashPolicy {
827 /// Layer 2
828 layer2 = 0,
829 /// Layer 2+3
830 #[serde(rename = "layer2+3")]
831 layer2_3 = 1,
832 /// Layer 3+4
833 #[serde(rename = "layer3+4")]
834 layer3_4 = 2,
835 }
836
837 #[api()]
838 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
839 #[serde(rename_all = "lowercase")]
840 /// Network interface type
841 pub enum NetworkInterfaceType {
842 /// Loopback
843 Loopback,
844 /// Physical Ethernet device
845 Eth,
846 /// Linux Bridge
847 Bridge,
848 /// Linux Bond
849 Bond,
850 /// Linux VLAN (eth.10)
851 Vlan,
852 /// Interface Alias (eth:1)
853 Alias,
854 /// Unknown interface type
855 Unknown,
856 }
857
858 pub const NETWORK_INTERFACE_NAME_SCHEMA: Schema = StringSchema::new("Network interface name.")
859 .format(&NETWORK_INTERFACE_FORMAT)
860 .min_length(1)
861 .max_length(libc::IFNAMSIZ-1)
862 .schema();
863
864 pub const NETWORK_INTERFACE_ARRAY_SCHEMA: Schema = ArraySchema::new(
865 "Network interface list.", &NETWORK_INTERFACE_NAME_SCHEMA)
866 .schema();
867
868 pub const NETWORK_INTERFACE_LIST_SCHEMA: Schema = StringSchema::new(
869 "A list of network devices, comma separated.")
870 .format(&ApiStringFormat::PropertyString(&NETWORK_INTERFACE_ARRAY_SCHEMA))
871 .schema();
872
873 #[api(
874 properties: {
875 name: {
876 schema: NETWORK_INTERFACE_NAME_SCHEMA,
877 },
878 "type": {
879 type: NetworkInterfaceType,
880 },
881 method: {
882 type: NetworkConfigMethod,
883 optional: true,
884 },
885 method6: {
886 type: NetworkConfigMethod,
887 optional: true,
888 },
889 cidr: {
890 schema: CIDR_V4_SCHEMA,
891 optional: true,
892 },
893 cidr6: {
894 schema: CIDR_V6_SCHEMA,
895 optional: true,
896 },
897 gateway: {
898 schema: IP_V4_SCHEMA,
899 optional: true,
900 },
901 gateway6: {
902 schema: IP_V6_SCHEMA,
903 optional: true,
904 },
905 options: {
906 description: "Option list (inet)",
907 type: Array,
908 items: {
909 description: "Optional attribute line.",
910 type: String,
911 },
912 },
913 options6: {
914 description: "Option list (inet6)",
915 type: Array,
916 items: {
917 description: "Optional attribute line.",
918 type: String,
919 },
920 },
921 comments: {
922 description: "Comments (inet, may span multiple lines)",
923 type: String,
924 optional: true,
925 },
926 comments6: {
927 description: "Comments (inet6, may span multiple lines)",
928 type: String,
929 optional: true,
930 },
931 bridge_ports: {
932 schema: NETWORK_INTERFACE_ARRAY_SCHEMA,
933 optional: true,
934 },
935 slaves: {
936 schema: NETWORK_INTERFACE_ARRAY_SCHEMA,
937 optional: true,
938 },
939 bond_mode: {
940 type: LinuxBondMode,
941 optional: true,
942 },
943 "bond-primary": {
944 schema: NETWORK_INTERFACE_NAME_SCHEMA,
945 optional: true,
946 },
947 bond_xmit_hash_policy: {
948 type: BondXmitHashPolicy,
949 optional: true,
950 },
951 }
952 )]
953 #[derive(Debug, Serialize, Deserialize)]
954 /// Network Interface configuration
955 pub struct Interface {
956 /// Autostart interface
957 #[serde(rename = "autostart")]
958 pub autostart: bool,
959 /// Interface is active (UP)
960 pub active: bool,
961 /// Interface name
962 pub name: String,
963 /// Interface type
964 #[serde(rename = "type")]
965 pub interface_type: NetworkInterfaceType,
966 #[serde(skip_serializing_if="Option::is_none")]
967 pub method: Option<NetworkConfigMethod>,
968 #[serde(skip_serializing_if="Option::is_none")]
969 pub method6: Option<NetworkConfigMethod>,
970 #[serde(skip_serializing_if="Option::is_none")]
971 /// IPv4 address with netmask
972 pub cidr: Option<String>,
973 #[serde(skip_serializing_if="Option::is_none")]
974 /// IPv4 gateway
975 pub gateway: Option<String>,
976 #[serde(skip_serializing_if="Option::is_none")]
977 /// IPv6 address with netmask
978 pub cidr6: Option<String>,
979 #[serde(skip_serializing_if="Option::is_none")]
980 /// IPv6 gateway
981 pub gateway6: Option<String>,
982
983 #[serde(skip_serializing_if="Vec::is_empty")]
984 pub options: Vec<String>,
985 #[serde(skip_serializing_if="Vec::is_empty")]
986 pub options6: Vec<String>,
987
988 #[serde(skip_serializing_if="Option::is_none")]
989 pub comments: Option<String>,
990 #[serde(skip_serializing_if="Option::is_none")]
991 pub comments6: Option<String>,
992
993 #[serde(skip_serializing_if="Option::is_none")]
994 /// Maximum Transmission Unit
995 pub mtu: Option<u64>,
996
997 #[serde(skip_serializing_if="Option::is_none")]
998 pub bridge_ports: Option<Vec<String>>,
999 /// Enable bridge vlan support.
1000 #[serde(skip_serializing_if="Option::is_none")]
1001 pub bridge_vlan_aware: Option<bool>,
1002
1003 #[serde(skip_serializing_if="Option::is_none")]
1004 pub slaves: Option<Vec<String>>,
1005 #[serde(skip_serializing_if="Option::is_none")]
1006 pub bond_mode: Option<LinuxBondMode>,
1007 #[serde(skip_serializing_if="Option::is_none")]
1008 #[serde(rename = "bond-primary")]
1009 pub bond_primary: Option<String>,
1010 pub bond_xmit_hash_policy: Option<BondXmitHashPolicy>,
1011 }
1012
1013 // Regression tests
1014
1015 #[test]
1016 fn test_cert_fingerprint_schema() -> Result<(), anyhow::Error> {
1017
1018 let schema = CERT_FINGERPRINT_SHA256_SCHEMA;
1019
1020 let invalid_fingerprints = [
1021 "86:88:7c:be:26:77:a5:62:67:d9:06:f5:e4::61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1022 "88:7C:BE:26:77:a5:62:67:D9:06:f5:e4:14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1023 "86:88:7c:be:26:77:a5:62:67:d9:06:f5:e4::14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8:ff",
1024 "XX:88:7c:be:26:77:a5:62:67:d9:06:f5:e4::14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1025 "86:88:Y4:be:26:77:a5:62:67:d9:06:f5:e4:14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1026 "86:88:0:be:26:77:a5:62:67:d9:06:f5:e4:14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1027 ];
1028
1029 for fingerprint in invalid_fingerprints.iter() {
1030 if let Ok(_) = parse_simple_value(fingerprint, &schema) {
1031 bail!("test fingerprint '{}' failed - got Ok() while exception an error.", fingerprint);
1032 }
1033 }
1034
1035 let valid_fingerprints = [
1036 "86:88:7c:be:26:77:a5:62:67:d9:06:f5:e4:14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1037 "86:88:7C:BE:26:77:a5:62:67:D9:06:f5:e4:14:61:3e:20:dc:cd:43:92:07:7f:fb:65:54:6c:ff:d2:96:36:f8",
1038 ];
1039
1040 for fingerprint in valid_fingerprints.iter() {
1041 let v = match parse_simple_value(fingerprint, &schema) {
1042 Ok(v) => v,
1043 Err(err) => {
1044 bail!("unable to parse fingerprint '{}' - {}", fingerprint, err);
1045 }
1046 };
1047
1048 if v != serde_json::json!(fingerprint) {
1049 bail!("unable to parse fingerprint '{}' - got wrong value {:?}", fingerprint, v);
1050 }
1051 }
1052
1053 Ok(())
1054 }
1055
1056 #[test]
1057 fn test_proxmox_user_id_schema() -> Result<(), anyhow::Error> {
1058 let invalid_user_ids = [
1059 "x", // too short
1060 "xx", // too short
1061 "xxx", // no realm
1062 "xxx@", // no realm
1063 "xx x@test", // contains space
1064 "xx\nx@test", // contains control character
1065 "x:xx@test", // contains collon
1066 "xx/x@test", // contains slash
1067 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@test", // too long
1068 ];
1069
1070 for name in invalid_user_ids.iter() {
1071 if let Ok(_) = parse_simple_value(name, &Userid::API_SCHEMA) {
1072 bail!("test userid '{}' failed - got Ok() while exception an error.", name);
1073 }
1074 }
1075
1076 let valid_user_ids = [
1077 "xxx@y",
1078 "name@y",
1079 "xxx@test-it.com",
1080 "xxx@_T_E_S_T-it.com",
1081 "x_x-x.x@test-it.com",
1082 ];
1083
1084 for name in valid_user_ids.iter() {
1085 let v = match parse_simple_value(name, &Userid::API_SCHEMA) {
1086 Ok(v) => v,
1087 Err(err) => {
1088 bail!("unable to parse userid '{}' - {}", name, err);
1089 }
1090 };
1091
1092 if v != serde_json::json!(name) {
1093 bail!("unable to parse userid '{}' - got wrong value {:?}", name, v);
1094 }
1095 }
1096
1097 Ok(())
1098 }
1099
1100 #[api()]
1101 #[derive(Copy, Clone, Serialize, Deserialize)]
1102 #[serde(rename_all = "UPPERCASE")]
1103 pub enum RRDMode {
1104 /// Maximum
1105 Max,
1106 /// Average
1107 Average,
1108 }
1109
1110
1111 #[api()]
1112 #[repr(u64)]
1113 #[derive(Copy, Clone, Serialize, Deserialize)]
1114 #[serde(rename_all = "lowercase")]
1115 pub enum RRDTimeFrameResolution {
1116 /// 1 min => last 70 minutes
1117 Hour = 60,
1118 /// 30 min => last 35 hours
1119 Day = 60*30,
1120 /// 3 hours => about 8 days
1121 Week = 60*180,
1122 /// 12 hours => last 35 days
1123 Month = 60*720,
1124 /// 1 week => last 490 days
1125 Year = 60*10080,
1126 }
1127
1128 #[api()]
1129 #[derive(Debug, Serialize, Deserialize)]
1130 #[serde(rename_all = "PascalCase")]
1131 /// Describes a package for which an update is available.
1132 pub struct APTUpdateInfo {
1133 /// Package name
1134 pub package: String,
1135 /// Package title
1136 pub title: String,
1137 /// Package architecture
1138 pub arch: String,
1139 /// Human readable package description
1140 pub description: String,
1141 /// New version to be updated to
1142 pub version: String,
1143 /// Old version currently installed
1144 pub old_version: String,
1145 /// Package origin
1146 pub origin: String,
1147 /// Package priority in human-readable form
1148 pub priority: String,
1149 /// Package section
1150 pub section: String,
1151 /// URL under which the package's changelog can be retrieved
1152 pub change_log_url: String,
1153 }