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