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