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