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