]> git.proxmox.com Git - proxmox-backup.git/blob - src/api2/types/mod.rs
save last verify result in snapshot manifest
[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, 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!() ,"):)?(", 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 REMOTE_ID_SCHEMA: Schema = StringSchema::new("Remote ID.")
306 .format(&PROXMOX_SAFE_ID_FORMAT)
307 .min_length(3)
308 .max_length(32)
309 .schema();
310
311 pub const JOB_ID_SCHEMA: Schema = StringSchema::new("Job ID.")
312 .format(&PROXMOX_SAFE_ID_FORMAT)
313 .min_length(3)
314 .max_length(32)
315 .schema();
316
317 pub const REMOVE_VANISHED_BACKUPS_SCHEMA: Schema = BooleanSchema::new(
318 "Delete vanished backups. This remove the local copy if the remote backup was deleted.")
319 .default(true)
320 .schema();
321
322 pub const SINGLE_LINE_COMMENT_SCHEMA: Schema = StringSchema::new("Comment (single line).")
323 .format(&SINGLE_LINE_COMMENT_FORMAT)
324 .schema();
325
326 pub const HOSTNAME_SCHEMA: Schema = StringSchema::new("Hostname (as defined in RFC1123).")
327 .format(&HOSTNAME_FORMAT)
328 .schema();
329
330 pub const DNS_NAME_OR_IP_SCHEMA: Schema = StringSchema::new("DNS name or IP address.")
331 .format(&DNS_NAME_OR_IP_FORMAT)
332 .schema();
333
334 pub const BLOCKDEVICE_NAME_SCHEMA: Schema = StringSchema::new("Block device name (/sys/block/<name>).")
335 .format(&BLOCKDEVICE_NAME_FORMAT)
336 .min_length(3)
337 .max_length(64)
338 .schema();
339
340 // Complex type definitions
341
342 #[api(
343 properties: {
344 "backup-type": {
345 schema: BACKUP_TYPE_SCHEMA,
346 },
347 "backup-id": {
348 schema: BACKUP_ID_SCHEMA,
349 },
350 "last-backup": {
351 schema: BACKUP_TIME_SCHEMA,
352 },
353 "backup-count": {
354 type: Integer,
355 },
356 files: {
357 items: {
358 schema: BACKUP_ARCHIVE_NAME_SCHEMA
359 },
360 },
361 owner: {
362 type: Userid,
363 optional: true,
364 },
365 },
366 )]
367 #[derive(Serialize, Deserialize)]
368 #[serde(rename_all="kebab-case")]
369 /// Basic information about a backup group.
370 pub struct GroupListItem {
371 pub backup_type: String, // enum
372 pub backup_id: String,
373 pub last_backup: i64,
374 /// Number of contained snapshots
375 pub backup_count: u64,
376 /// List of contained archive files.
377 pub files: Vec<String>,
378 /// The owner of group
379 #[serde(skip_serializing_if="Option::is_none")]
380 pub owner: Option<Userid>,
381 }
382
383 #[api(
384 properties: {
385 upid: {
386 schema: UPID_SCHEMA
387 },
388 state: {
389 type: String
390 },
391 },
392 )]
393 #[derive(Serialize, Deserialize)]
394 /// Task properties.
395 pub struct SnapshotVerifyState {
396 /// UPID of the verify task
397 pub upid: UPID,
398 /// State of the verification. "failed" or "ok"
399 pub state: String,
400 }
401
402 #[api(
403 properties: {
404 "backup-type": {
405 schema: BACKUP_TYPE_SCHEMA,
406 },
407 "backup-id": {
408 schema: BACKUP_ID_SCHEMA,
409 },
410 "backup-time": {
411 schema: BACKUP_TIME_SCHEMA,
412 },
413 comment: {
414 schema: SINGLE_LINE_COMMENT_SCHEMA,
415 optional: true,
416 },
417 verification: {
418 type: SnapshotVerifyState,
419 optional: true,
420 },
421 files: {
422 items: {
423 schema: BACKUP_ARCHIVE_NAME_SCHEMA
424 },
425 },
426 owner: {
427 type: Userid,
428 optional: true,
429 },
430 },
431 )]
432 #[derive(Serialize, Deserialize)]
433 #[serde(rename_all="kebab-case")]
434 /// Basic information about backup snapshot.
435 pub struct SnapshotListItem {
436 pub backup_type: String, // enum
437 pub backup_id: String,
438 pub backup_time: i64,
439 /// The first line from manifest "notes"
440 #[serde(skip_serializing_if="Option::is_none")]
441 pub comment: Option<String>,
442 /// The result of the last run verify task
443 #[serde(skip_serializing_if="Option::is_none")]
444 pub verification: Option<SnapshotVerifyState>,
445 /// List of contained archive files.
446 pub files: Vec<BackupContent>,
447 /// Overall snapshot size (sum of all archive sizes).
448 #[serde(skip_serializing_if="Option::is_none")]
449 pub size: Option<u64>,
450 /// The owner of the snapshots group
451 #[serde(skip_serializing_if="Option::is_none")]
452 pub owner: Option<Userid>,
453 }
454
455 #[api(
456 properties: {
457 "backup-type": {
458 schema: BACKUP_TYPE_SCHEMA,
459 },
460 "backup-id": {
461 schema: BACKUP_ID_SCHEMA,
462 },
463 "backup-time": {
464 schema: BACKUP_TIME_SCHEMA,
465 },
466 },
467 )]
468 #[derive(Serialize, Deserialize)]
469 #[serde(rename_all="kebab-case")]
470 /// Prune result.
471 pub struct PruneListItem {
472 pub backup_type: String, // enum
473 pub backup_id: String,
474 pub backup_time: i64,
475 /// Keep snapshot
476 pub keep: bool,
477 }
478
479 pub const PRUNE_SCHEMA_KEEP_DAILY: Schema = IntegerSchema::new(
480 "Number of daily backups to keep.")
481 .minimum(1)
482 .schema();
483
484 pub const PRUNE_SCHEMA_KEEP_HOURLY: Schema = IntegerSchema::new(
485 "Number of hourly backups to keep.")
486 .minimum(1)
487 .schema();
488
489 pub const PRUNE_SCHEMA_KEEP_LAST: Schema = IntegerSchema::new(
490 "Number of backups to keep.")
491 .minimum(1)
492 .schema();
493
494 pub const PRUNE_SCHEMA_KEEP_MONTHLY: Schema = IntegerSchema::new(
495 "Number of monthly backups to keep.")
496 .minimum(1)
497 .schema();
498
499 pub const PRUNE_SCHEMA_KEEP_WEEKLY: Schema = IntegerSchema::new(
500 "Number of weekly backups to keep.")
501 .minimum(1)
502 .schema();
503
504 pub const PRUNE_SCHEMA_KEEP_YEARLY: Schema = IntegerSchema::new(
505 "Number of yearly backups to keep.")
506 .minimum(1)
507 .schema();
508
509 #[api(
510 properties: {
511 "filename": {
512 schema: BACKUP_ARCHIVE_NAME_SCHEMA,
513 },
514 "crypt-mode": {
515 type: CryptMode,
516 optional: true,
517 },
518 },
519 )]
520 #[derive(Serialize, Deserialize)]
521 #[serde(rename_all="kebab-case")]
522 /// Basic information about archive files inside a backup snapshot.
523 pub struct BackupContent {
524 pub filename: String,
525 /// Info if file is encrypted, signed, or neither.
526 #[serde(skip_serializing_if="Option::is_none")]
527 pub crypt_mode: Option<CryptMode>,
528 /// Archive size (from backup manifest).
529 #[serde(skip_serializing_if="Option::is_none")]
530 pub size: Option<u64>,
531 }
532
533 #[api(
534 properties: {
535 "upid": {
536 optional: true,
537 schema: UPID_SCHEMA,
538 },
539 },
540 )]
541 #[derive(Clone, Serialize, Deserialize)]
542 #[serde(rename_all="kebab-case")]
543 /// Garbage collection status.
544 pub struct GarbageCollectionStatus {
545 pub upid: Option<String>,
546 /// Number of processed index files.
547 pub index_file_count: usize,
548 /// Sum of bytes referred by index files.
549 pub index_data_bytes: u64,
550 /// Bytes used on disk.
551 pub disk_bytes: u64,
552 /// Chunks used on disk.
553 pub disk_chunks: usize,
554 /// Sum of removed bytes.
555 pub removed_bytes: u64,
556 /// Number of removed chunks.
557 pub removed_chunks: usize,
558 /// Sum of pending bytes (pending removal - kept for safety).
559 pub pending_bytes: u64,
560 /// Number of pending chunks (pending removal - kept for safety).
561 pub pending_chunks: usize,
562 }
563
564 impl Default for GarbageCollectionStatus {
565 fn default() -> Self {
566 GarbageCollectionStatus {
567 upid: None,
568 index_file_count: 0,
569 index_data_bytes: 0,
570 disk_bytes: 0,
571 disk_chunks: 0,
572 removed_bytes: 0,
573 removed_chunks: 0,
574 pending_bytes: 0,
575 pending_chunks: 0,
576 }
577 }
578 }
579
580
581 #[api()]
582 #[derive(Serialize, Deserialize)]
583 /// Storage space usage information.
584 pub struct StorageStatus {
585 /// Total space (bytes).
586 pub total: u64,
587 /// Used space (bytes).
588 pub used: u64,
589 /// Available space (bytes).
590 pub avail: u64,
591 }
592
593 #[api(
594 properties: {
595 upid: { schema: UPID_SCHEMA },
596 user: { type: Userid },
597 },
598 )]
599 #[derive(Serialize, Deserialize)]
600 /// Task properties.
601 pub struct TaskListItem {
602 pub upid: String,
603 /// The node name where the task is running on.
604 pub node: String,
605 /// The Unix PID
606 pub pid: i64,
607 /// The task start time (Epoch)
608 pub pstart: u64,
609 /// The task start time (Epoch)
610 pub starttime: i64,
611 /// Worker type (arbitrary ASCII string)
612 pub worker_type: String,
613 /// Worker ID (arbitrary ASCII string)
614 pub worker_id: Option<String>,
615 /// The user who started the task
616 pub user: Userid,
617 /// The task end time (Epoch)
618 #[serde(skip_serializing_if="Option::is_none")]
619 pub endtime: Option<i64>,
620 /// Task end status
621 #[serde(skip_serializing_if="Option::is_none")]
622 pub status: Option<String>,
623 }
624
625 impl From<crate::server::TaskListInfo> for TaskListItem {
626 fn from(info: crate::server::TaskListInfo) -> Self {
627 let (endtime, status) = info
628 .state
629 .map_or_else(|| (None, None), |a| (Some(a.endtime()), Some(a.to_string())));
630
631 TaskListItem {
632 upid: info.upid_str,
633 node: "localhost".to_string(),
634 pid: info.upid.pid as i64,
635 pstart: info.upid.pstart,
636 starttime: info.upid.starttime,
637 worker_type: info.upid.worker_type,
638 worker_id: info.upid.worker_id,
639 user: info.upid.userid,
640 endtime,
641 status,
642 }
643 }
644 }
645
646 #[api()]
647 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
648 #[serde(rename_all = "lowercase")]
649 /// Node Power command type.
650 pub enum NodePowerCommand {
651 /// Restart the server
652 Reboot,
653 /// Shutdown the server
654 Shutdown,
655 }
656
657 #[api()]
658 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
659 #[serde(rename_all = "lowercase")]
660 /// Interface configuration method
661 pub enum NetworkConfigMethod {
662 /// Configuration is done manually using other tools
663 Manual,
664 /// Define interfaces with statically allocated addresses.
665 Static,
666 /// Obtain an address via DHCP
667 DHCP,
668 /// Define the loopback interface.
669 Loopback,
670 }
671
672 #[api()]
673 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
674 #[serde(rename_all = "kebab-case")]
675 #[allow(non_camel_case_types)]
676 #[repr(u8)]
677 /// Linux Bond Mode
678 pub enum LinuxBondMode {
679 /// Round-robin policy
680 balance_rr = 0,
681 /// Active-backup policy
682 active_backup = 1,
683 /// XOR policy
684 balance_xor = 2,
685 /// Broadcast policy
686 broadcast = 3,
687 /// IEEE 802.3ad Dynamic link aggregation
688 //#[serde(rename = "802.3ad")]
689 ieee802_3ad = 4,
690 /// Adaptive transmit load balancing
691 balance_tlb = 5,
692 /// Adaptive load balancing
693 balance_alb = 6,
694 }
695
696 #[api()]
697 #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
698 #[serde(rename_all = "lowercase")]
699 /// Network interface type
700 pub enum NetworkInterfaceType {
701 /// Loopback
702 Loopback,
703 /// Physical Ethernet device
704 Eth,
705 /// Linux Bridge
706 Bridge,
707 /// Linux Bond
708 Bond,
709 /// Linux VLAN (eth.10)
710 Vlan,
711 /// Interface Alias (eth:1)
712 Alias,
713 /// Unknown interface type
714 Unknown,
715 }
716
717 pub const NETWORK_INTERFACE_NAME_SCHEMA: Schema = StringSchema::new("Network interface name.")
718 .format(&NETWORK_INTERFACE_FORMAT)
719 .min_length(1)
720 .max_length(libc::IFNAMSIZ-1)
721 .schema();
722
723 pub const NETWORK_INTERFACE_ARRAY_SCHEMA: Schema = ArraySchema::new(
724 "Network interface list.", &NETWORK_INTERFACE_NAME_SCHEMA)
725 .schema();
726
727 pub const NETWORK_INTERFACE_LIST_SCHEMA: Schema = StringSchema::new(
728 "A list of network devices, comma separated.")
729 .format(&ApiStringFormat::PropertyString(&NETWORK_INTERFACE_ARRAY_SCHEMA))
730 .schema();
731
732 #[api(
733 properties: {
734 name: {
735 schema: NETWORK_INTERFACE_NAME_SCHEMA,
736 },
737 "type": {
738 type: NetworkInterfaceType,
739 },
740 method: {
741 type: NetworkConfigMethod,
742 optional: true,
743 },
744 method6: {
745 type: NetworkConfigMethod,
746 optional: true,
747 },
748 cidr: {
749 schema: CIDR_V4_SCHEMA,
750 optional: true,
751 },
752 cidr6: {
753 schema: CIDR_V6_SCHEMA,
754 optional: true,
755 },
756 gateway: {
757 schema: IP_V4_SCHEMA,
758 optional: true,
759 },
760 gateway6: {
761 schema: IP_V6_SCHEMA,
762 optional: true,
763 },
764 options: {
765 description: "Option list (inet)",
766 type: Array,
767 items: {
768 description: "Optional attribute line.",
769 type: String,
770 },
771 },
772 options6: {
773 description: "Option list (inet6)",
774 type: Array,
775 items: {
776 description: "Optional attribute line.",
777 type: String,
778 },
779 },
780 comments: {
781 description: "Comments (inet, may span multiple lines)",
782 type: String,
783 optional: true,
784 },
785 comments6: {
786 description: "Comments (inet6, may span multiple lines)",
787 type: String,
788 optional: true,
789 },
790 bridge_ports: {
791 schema: NETWORK_INTERFACE_ARRAY_SCHEMA,
792 optional: true,
793 },
794 slaves: {
795 schema: NETWORK_INTERFACE_ARRAY_SCHEMA,
796 optional: true,
797 },
798 bond_mode: {
799 type: LinuxBondMode,
800 optional: true,
801 }
802 }
803 )]
804 #[derive(Debug, Serialize, Deserialize)]
805 /// Network Interface configuration
806 pub struct Interface {
807 /// Autostart interface
808 #[serde(rename = "autostart")]
809 pub autostart: bool,
810 /// Interface is active (UP)
811 pub active: bool,
812 /// Interface name
813 pub name: String,
814 /// Interface type
815 #[serde(rename = "type")]
816 pub interface_type: NetworkInterfaceType,
817 #[serde(skip_serializing_if="Option::is_none")]
818 pub method: Option<NetworkConfigMethod>,
819 #[serde(skip_serializing_if="Option::is_none")]
820 pub method6: Option<NetworkConfigMethod>,
821 #[serde(skip_serializing_if="Option::is_none")]
822 /// IPv4 address with netmask
823 pub cidr: Option<String>,
824 #[serde(skip_serializing_if="Option::is_none")]
825 /// IPv4 gateway
826 pub gateway: Option<String>,
827 #[serde(skip_serializing_if="Option::is_none")]
828 /// IPv6 address with netmask
829 pub cidr6: Option<String>,
830 #[serde(skip_serializing_if="Option::is_none")]
831 /// IPv6 gateway
832 pub gateway6: Option<String>,
833
834 #[serde(skip_serializing_if="Vec::is_empty")]
835 pub options: Vec<String>,
836 #[serde(skip_serializing_if="Vec::is_empty")]
837 pub options6: Vec<String>,
838
839 #[serde(skip_serializing_if="Option::is_none")]
840 pub comments: Option<String>,
841 #[serde(skip_serializing_if="Option::is_none")]
842 pub comments6: Option<String>,
843
844 #[serde(skip_serializing_if="Option::is_none")]
845 /// Maximum Transmission Unit
846 pub mtu: Option<u64>,
847
848 #[serde(skip_serializing_if="Option::is_none")]
849 pub bridge_ports: Option<Vec<String>>,
850 /// Enable bridge vlan support.
851 #[serde(skip_serializing_if="Option::is_none")]
852 pub bridge_vlan_aware: Option<bool>,
853
854 #[serde(skip_serializing_if="Option::is_none")]
855 pub slaves: Option<Vec<String>>,
856 #[serde(skip_serializing_if="Option::is_none")]
857 pub bond_mode: Option<LinuxBondMode>,
858 }
859
860 // Regression tests
861
862 #[test]
863 fn test_cert_fingerprint_schema() -> Result<(), anyhow::Error> {
864
865 let schema = CERT_FINGERPRINT_SHA256_SCHEMA;
866
867 let invalid_fingerprints = [
868 "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",
869 "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",
870 "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",
871 "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",
872 "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",
873 "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",
874 ];
875
876 for fingerprint in invalid_fingerprints.iter() {
877 if let Ok(_) = parse_simple_value(fingerprint, &schema) {
878 bail!("test fingerprint '{}' failed - got Ok() while exception an error.", fingerprint);
879 }
880 }
881
882 let valid_fingerprints = [
883 "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",
884 "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",
885 ];
886
887 for fingerprint in valid_fingerprints.iter() {
888 let v = match parse_simple_value(fingerprint, &schema) {
889 Ok(v) => v,
890 Err(err) => {
891 bail!("unable to parse fingerprint '{}' - {}", fingerprint, err);
892 }
893 };
894
895 if v != serde_json::json!(fingerprint) {
896 bail!("unable to parse fingerprint '{}' - got wrong value {:?}", fingerprint, v);
897 }
898 }
899
900 Ok(())
901 }
902
903 #[test]
904 fn test_proxmox_user_id_schema() -> Result<(), anyhow::Error> {
905 let invalid_user_ids = [
906 "x", // too short
907 "xx", // too short
908 "xxx", // no realm
909 "xxx@", // no realm
910 "xx x@test", // contains space
911 "xx\nx@test", // contains control character
912 "x:xx@test", // contains collon
913 "xx/x@test", // contains slash
914 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@test", // too long
915 ];
916
917 for name in invalid_user_ids.iter() {
918 if let Ok(_) = parse_simple_value(name, &Userid::API_SCHEMA) {
919 bail!("test userid '{}' failed - got Ok() while exception an error.", name);
920 }
921 }
922
923 let valid_user_ids = [
924 "xxx@y",
925 "name@y",
926 "xxx@test-it.com",
927 "xxx@_T_E_S_T-it.com",
928 "x_x-x.x@test-it.com",
929 ];
930
931 for name in valid_user_ids.iter() {
932 let v = match parse_simple_value(name, &Userid::API_SCHEMA) {
933 Ok(v) => v,
934 Err(err) => {
935 bail!("unable to parse userid '{}' - {}", name, err);
936 }
937 };
938
939 if v != serde_json::json!(name) {
940 bail!("unable to parse userid '{}' - got wrong value {:?}", name, v);
941 }
942 }
943
944 Ok(())
945 }
946
947 #[api()]
948 #[derive(Copy, Clone, Serialize, Deserialize)]
949 #[serde(rename_all = "UPPERCASE")]
950 pub enum RRDMode {
951 /// Maximum
952 Max,
953 /// Average
954 Average,
955 }
956
957
958 #[api()]
959 #[repr(u64)]
960 #[derive(Copy, Clone, Serialize, Deserialize)]
961 #[serde(rename_all = "lowercase")]
962 pub enum RRDTimeFrameResolution {
963 /// 1 min => last 70 minutes
964 Hour = 60,
965 /// 30 min => last 35 hours
966 Day = 60*30,
967 /// 3 hours => about 8 days
968 Week = 60*180,
969 /// 12 hours => last 35 days
970 Month = 60*720,
971 /// 1 week => last 490 days
972 Year = 60*10080,
973 }
974
975 #[api()]
976 #[derive(Serialize, Deserialize)]
977 #[serde(rename_all = "PascalCase")]
978 /// Describes a package for which an update is available.
979 pub struct APTUpdateInfo {
980 /// Package name
981 pub package: String,
982 /// Package title
983 pub title: String,
984 /// Package architecture
985 pub arch: String,
986 /// Human readable package description
987 pub description: String,
988 /// New version to be updated to
989 pub version: String,
990 /// Old version currently installed
991 pub old_version: String,
992 /// Package origin
993 pub origin: String,
994 /// Package priority in human-readable form
995 pub priority: String,
996 /// Package section
997 pub section: String,
998 /// URL under which the package's changelog can be retrieved
999 pub change_log_url: String,
1000 }