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