1 package PVE
::API2
::Storage
::Status
;
11 use PVE
::Exception
qw(raise_param_exc);
13 use PVE
::JSONSchema
qw(get_standard_option);
15 use PVE
::RPCEnvironment
;
17 use PVE
::Tools
qw(run_command);
19 use PVE
::API2
::Storage
::Content
;
20 use PVE
::API2
::Storage
::FileRestore
;
21 use PVE
::API2
::Storage
::PruneBackups
;
24 use base
qw(PVE::RESTHandler);
26 __PACKAGE__-
>register_method ({
27 subclass
=> "PVE::API2::Storage::PruneBackups",
28 path
=> '{storage}/prunebackups',
31 __PACKAGE__-
>register_method ({
32 subclass
=> "PVE::API2::Storage::Content",
33 # set fragment delimiter (no subdirs) - we need that, because volume
34 # IDs may contain a slash '/'
35 fragmentDelimiter
=> '',
36 path
=> '{storage}/content',
39 __PACKAGE__-
>register_method ({
40 subclass
=> "PVE::API2::Storage::FileRestore",
41 path
=> '{storage}/file-restore',
44 __PACKAGE__-
>register_method ({
48 description
=> "Get status for all datastores.",
50 description
=> "Only list entries where you have 'Datastore.Audit' or 'Datastore.AllocateSpace' permissions on '/storage/<storage>'",
56 additionalProperties
=> 0,
58 node
=> get_standard_option
('pve-node'),
59 storage
=> get_standard_option
('pve-storage-id', {
60 description
=> "Only list status for specified storage",
62 completion
=> \
&PVE
::Storage
::complete_storage_enabled
,
65 description
=> "Only list stores which support this content type.",
66 type
=> 'string', format
=> 'pve-storage-content-list',
68 completion
=> \
&PVE
::Storage
::complete_content_type
,
71 description
=> "Only list stores which are enabled (not disabled in config).",
76 target
=> get_standard_option
('pve-node', {
77 description
=> "If target is different to 'node', we only lists shared storages which " .
78 "content is accessible on this 'node' and the specified 'target' node.",
80 completion
=> \
&PVE
::Cluster
::get_nodelist
,
83 description
=> "Include information about formats",
95 storage
=> get_standard_option
('pve-storage-id'),
97 description
=> "Storage type.",
101 description
=> "Allowed storage content types.",
102 type
=> 'string', format
=> 'pve-storage-content-list',
105 description
=> "Set when storage is enabled (not disabled).",
110 description
=> "Set when storage is accessible.",
115 description
=> "Shared flag from storage configuration.",
120 description
=> "Total storage space in bytes.",
126 description
=> "Used storage space in bytes.",
132 description
=> "Available storage space in bytes.",
138 description
=> "Used fraction (used/total).",
140 renderer
=> 'fraction_as_percentage',
145 links
=> [ { rel
=> 'child', href
=> "{storage}" } ],
150 my $rpcenv = PVE
::RPCEnvironment
::get
();
151 my $authuser = $rpcenv->get_user();
153 my $localnode = PVE
::INotify
::nodename
();
155 my $target = $param->{target
};
157 undef $target if $target && ($target eq $localnode || $target eq 'localhost');
159 my $cfg = PVE
::Storage
::config
();
161 my $info = PVE
::Storage
::storage_info
($cfg, $param->{content
}, $param->{format
});
163 raise_param_exc
({ storage
=> "No such storage." })
164 if $param->{storage
} && !defined($info->{$param->{storage
}});
167 my @sids = PVE
::Storage
::storage_ids
($cfg);
168 foreach my $storeid (@sids) {
169 my $data = $info->{$storeid};
171 my $privs = [ 'Datastore.Audit', 'Datastore.AllocateSpace' ];
172 next if !$rpcenv->check_any($authuser, "/storage/$storeid", $privs, 1);
173 next if $param->{storage
} && $param->{storage
} ne $storeid;
175 my $scfg = PVE
::Storage
::storage_config
($cfg, $storeid);
177 next if $param->{enabled
} && $scfg->{disable
};
180 # check if storage content is accessible on local node and specified target node
181 # we use this on the Clone GUI
183 next if !$scfg->{shared
};
184 next if !PVE
::Storage
::storage_check_node
($cfg, $storeid, undef, 1);
185 next if !PVE
::Storage
::storage_check_node
($cfg, $storeid, $target, 1);
188 if ($data->{total
}) {
189 $data->{used_fraction
} = ($data->{used
} // 0) / $data->{total
};
192 $res->{$storeid} = $data;
195 return PVE
::RESTHandler
::hash_to_array
($res, 'storage');
198 __PACKAGE__-
>register_method ({
204 check
=> ['perm', '/storage/{storage}', ['Datastore.Audit', 'Datastore.AllocateSpace'], any
=> 1],
207 additionalProperties
=> 0,
209 node
=> get_standard_option
('pve-node'),
210 storage
=> get_standard_option
('pve-storage-id'),
218 subdir
=> { type
=> 'string' },
221 links
=> [ { rel
=> 'child', href
=> "{subdir}" } ],
227 { subdir
=> 'content' },
228 { subdir
=> 'download-url' },
229 { subdir
=> 'file-restore' },
230 { subdir
=> 'prunebackups' },
232 { subdir
=> 'rrddata' },
233 { subdir
=> 'status' },
234 { subdir
=> 'upload' },
240 __PACKAGE__-
>register_method ({
241 name
=> 'read_status',
242 path
=> '{storage}/status',
244 description
=> "Read storage status.",
246 check
=> ['perm', '/storage/{storage}', ['Datastore.Audit', 'Datastore.AllocateSpace'], any
=> 1],
251 additionalProperties
=> 0,
253 node
=> get_standard_option
('pve-node'),
254 storage
=> get_standard_option
('pve-storage-id'),
264 my $cfg = PVE
::Storage
::config
();
266 my $info = PVE
::Storage
::storage_info
($cfg, $param->{content
});
268 my $data = $info->{$param->{storage
}};
270 raise_param_exc
({ storage
=> "No such storage." })
276 __PACKAGE__-
>register_method ({
278 path
=> '{storage}/rrd',
280 description
=> "Read storage RRD statistics (returns PNG).",
282 check
=> ['perm', '/storage/{storage}', ['Datastore.Audit', 'Datastore.AllocateSpace'], any
=> 1],
287 additionalProperties
=> 0,
289 node
=> get_standard_option
('pve-node'),
290 storage
=> get_standard_option
('pve-storage-id'),
292 description
=> "Specify the time frame you are interested in.",
294 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
297 description
=> "The list of datasources you want to display.",
298 type
=> 'string', format
=> 'pve-configid-list',
301 description
=> "The RRD consolidation function",
303 enum
=> [ 'AVERAGE', 'MAX' ],
311 filename
=> { type
=> 'string' },
317 return PVE
::RRD
::create_rrd_graph
(
318 "pve2-storage/$param->{node}/$param->{storage}",
319 $param->{timeframe
}, $param->{ds
}, $param->{cf
});
322 __PACKAGE__-
>register_method ({
324 path
=> '{storage}/rrddata',
326 description
=> "Read storage RRD statistics.",
328 check
=> ['perm', '/storage/{storage}', ['Datastore.Audit', 'Datastore.AllocateSpace'], any
=> 1],
333 additionalProperties
=> 0,
335 node
=> get_standard_option
('pve-node'),
336 storage
=> get_standard_option
('pve-storage-id'),
338 description
=> "Specify the time frame you are interested in.",
340 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
343 description
=> "The RRD consolidation function",
345 enum
=> [ 'AVERAGE', 'MAX' ],
360 return PVE
::RRD
::create_rrd_data
(
361 "pve2-storage/$param->{node}/$param->{storage}",
362 $param->{timeframe
}, $param->{cf
});
365 # makes no sense for big images and backup files (because it
366 # create a copy of the file).
367 __PACKAGE__-
>register_method ({
369 path
=> '{storage}/upload',
371 description
=> "Upload templates and ISO images.",
373 check
=> ['perm', '/storage/{storage}', ['Datastore.AllocateTemplate']],
377 additionalProperties
=> 0,
379 node
=> get_standard_option
('pve-node'),
380 storage
=> get_standard_option
('pve-storage-id'),
382 description
=> "Content type.",
383 type
=> 'string', format
=> 'pve-storage-content',
384 enum
=> ['iso', 'vztmpl'],
387 description
=> "The name of the file to create. Caution: This will be normalized!",
392 description
=> "The expected checksum of the file.",
394 requires
=> 'checksum-algorithm',
397 'checksum-algorithm' => {
398 description
=> "The algorithm to calculate the checksum of the file.",
400 enum
=> ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
401 requires
=> 'checksum',
405 description
=> "The source file name. This parameter is usually set by the REST handler. You can only overwrite it when connecting to the trusted port on localhost.",
411 returns
=> { type
=> "string" },
415 my $rpcenv = PVE
::RPCEnvironment
::get
();
417 my $user = $rpcenv->get_user();
419 my $cfg = PVE
::Storage
::config
();
421 my $node = $param->{node
};
422 my $scfg = PVE
::Storage
::storage_check_enabled
($cfg, $param->{storage
}, $node);
424 die "can't upload to storage type '$scfg->{type}'\n"
425 if !defined($scfg->{path
});
427 my $content = $param->{content
};
429 my $tmpfilename = $param->{tmpfilename
};
430 die "missing temporary file name\n" if !$tmpfilename;
432 my $size = -s
$tmpfilename;
433 die "temporary file '$tmpfilename' does not exist\n" if !defined($size);
435 my $filename = PVE
::Storage
::normalize_content_filename
($param->{filename
});
439 if ($content eq 'iso') {
440 if ($filename !~ m![^/]+$PVE::Storage::iso_extension_re$!) {
441 raise_param_exc
({ filename
=> "wrong file extension" });
443 $path = PVE
::Storage
::get_iso_dir
($cfg, $param->{storage
});
444 } elsif ($content eq 'vztmpl') {
445 if ($filename !~ m![^/]+$PVE::Storage::vztmpl_extension_re$!) {
446 raise_param_exc
({ filename
=> "wrong file extension" });
448 $path = PVE
::Storage
::get_vztmpl_dir
($cfg, $param->{storage
});
450 raise_param_exc
({ content
=> "upload content type '$content' not allowed" });
453 die "storage '$param->{storage}' does not support '$content' content\n"
454 if !$scfg->{content
}->{$content};
456 my $dest = "$path/$filename";
457 my $dirname = dirname
($dest);
459 # best effort to match apl_download behaviour
460 chmod 0644, $tmpfilename;
462 my $err_cleanup = sub { unlink $dest, $tmpfilename; die "cleanup failed: $!" if $! && $! != ENOENT
};
465 if ($node ne 'localhost' && $node ne PVE
::INotify
::nodename
()) {
466 my $remip = PVE
::Cluster
::remote_node_ip
($node);
468 my @ssh_options = ('-o', 'BatchMode=yes');
470 my @remcmd = ('/usr/bin/ssh', @ssh_options, $remip, '--');
472 eval { # activate remote storage
473 run_command
([@remcmd, '/usr/sbin/pvesm', 'status', '--storage', $param->{storage
}]);
475 die "can't activate storage '$param->{storage}' on node '$node': $@\n" if $@;
478 [@remcmd, '/bin/mkdir', '-p', '--', PVE
::Tools
::shell_quote
($dirname)],
479 errmsg
=> "mkdir failed",
482 $cmd = ['/usr/bin/scp', @ssh_options, '-p', '--', $tmpfilename, "[$remip]:" . PVE
::Tools
::shell_quote
($dest)];
484 $err_cleanup = sub { run_command
([@remcmd, 'rm', '-f', '--', $dest, $tmpfilename]) };
486 PVE
::Storage
::activate_storage
($cfg, $param->{storage
});
487 File
::Path
::make_path
($dirname);
488 $cmd = ['cp', '--', $tmpfilename, $dest];
491 # NOTE: we simply overwrite the destination file if it already exists
495 print "starting file import from: $tmpfilename\n";
498 my ($checksum, $checksum_algorithm) = $param->@{'checksum', 'checksum-algorithm'};
499 if ($checksum_algorithm) {
500 print "calculating checksum...";
502 my $checksum_got = PVE
::Tools
::get_file_hash
($checksum_algorithm, $tmpfilename);
504 if (lc($checksum_got) eq lc($checksum)) {
505 print "OK, checksum verified\n";
507 print "\n"; # the front end expects the error to reside at the last line without any noise
508 die "checksum mismatch: got '$checksum_got' != expect '$checksum'\n";
513 # unlinks only the temporary file from the http server
515 warn "unable to clean up temporory file '$tmpfilename' - $!\n"
516 if $! && $! != ENOENT
;
520 print "target node: $node\n";
521 print "target file: $dest\n";
522 print "file size is: $size\n";
523 print "command: " . join(' ', @$cmd) . "\n";
525 eval { run_command
($cmd, errmsg
=> 'import failed'); };
527 unlink $tmpfilename; # the temporary file got only uploaded locally, no need to rm remote
528 warn "unable to clean up temporary file '$tmpfilename' - $!\n" if $! && $! != ENOENT
;
531 eval { $err_cleanup->() };
535 print "finished file import successfully\n";
538 return $rpcenv->fork_worker('imgcopy', undef, $user, $worker);
541 __PACKAGE__-
>register_method({
542 name
=> 'download_url',
543 path
=> '{storage}/download-url',
545 description
=> "Download templates and ISO images by using an URL.",
549 ['perm', '/storage/{storage}', [ 'Datastore.AllocateTemplate' ]],
550 ['perm', '/', [ 'Sys.Audit', 'Sys.Modify' ]],
555 additionalProperties
=> 0,
557 node
=> get_standard_option
('pve-node'),
558 storage
=> get_standard_option
('pve-storage-id'),
560 description
=> "The URL to download the file from.",
562 pattern
=> 'https?://.*',
565 description
=> "Content type.", # TODO: could be optional & detected in most cases
566 type
=> 'string', format
=> 'pve-storage-content',
567 enum
=> ['iso', 'vztmpl'],
570 description
=> "The name of the file to create. Caution: This will be normalized!",
575 description
=> "The expected checksum of the file.",
577 requires
=> 'checksum-algorithm',
580 'checksum-algorithm' => {
581 description
=> "The algorithm to calculate the checksum of the file.",
583 enum
=> ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'],
584 requires
=> 'checksum',
587 'verify-certificates' => {
588 description
=> "If false, no SSL/TLS certificates will be verified.",
601 my $rpcenv = PVE
::RPCEnvironment
::get
();
602 my $user = $rpcenv->get_user();
604 my $cfg = PVE
::Storage
::config
();
606 my ($node, $storage) = $param->@{'node', 'storage'};
607 my $scfg = PVE
::Storage
::storage_check_enabled
($cfg, $storage, $node);
609 die "can't upload to storage type '$scfg->{type}', not a file based storage!\n"
610 if !defined($scfg->{path
});
612 my ($content, $url) = $param->@{'content', 'url'};
614 die "storage '$storage' is not configured for content-type '$content'\n"
615 if !$scfg->{content
}->{$content};
617 my $filename = PVE
::Storage
::normalize_content_filename
($param->{filename
});
620 if ($content eq 'iso') {
621 if ($filename !~ m![^/]+$PVE::Storage::iso_extension_re$!) {
622 raise_param_exc
({ filename
=> "wrong file extension" });
624 $path = PVE
::Storage
::get_iso_dir
($cfg, $storage);
625 } elsif ($content eq 'vztmpl') {
626 if ($filename !~ m![^/]+$PVE::Storage::vztmpl_extension_re$!) {
627 raise_param_exc
({ filename
=> "wrong file extension" });
629 $path = PVE
::Storage
::get_vztmpl_dir
($cfg, $storage);
631 raise_param_exc
({ content
=> "upload content-type '$content' is not allowed" });
634 PVE
::Storage
::activate_storage
($cfg, $storage);
635 File
::Path
::make_path
($path);
637 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
640 verify_certificates
=> $param->{'verify-certificates'} // 1,
641 http_proxy
=> $dccfg->{http_proxy
},
644 my ($checksum, $checksum_algorithm) = $param->@{'checksum', 'checksum-algorithm'};
646 $opts->{"${checksum_algorithm}sum"} = $checksum;
647 $opts->{hash_required
} = 1;
651 PVE
::Tools
::download_file_from_url
("$path/$filename", $url, $opts);
654 my $worker_id = PVE
::Tools
::encode_text
($filename); # must not pass : or the like as w-ID
656 return $rpcenv->fork_worker('download', $worker_id, $user, $worker);