]> git.proxmox.com Git - pve-container.git/blob - src/PVE/API2/LXC.pm
644cc2005a5c9fddbeecbfc933b8cf315cb6b12e
[pve-container.git] / src / PVE / API2 / LXC.pm
1 package PVE::API2::LXC;
2
3 use strict;
4 use warnings;
5
6 use PVE::SafeSyslog;
7 use PVE::Tools qw(extract_param run_command);
8 use PVE::Exception qw(raise raise_param_exc);
9 use PVE::INotify;
10 use PVE::Cluster qw(cfs_read_file);
11 use PVE::AccessControl;
12 use PVE::Storage;
13 use PVE::RESTHandler;
14 use PVE::RPCEnvironment;
15 use PVE::LXC;
16 use PVE::JSONSchema qw(get_standard_option);
17 use base qw(PVE::RESTHandler);
18
19 use Data::Dumper; # fixme: remove
20
21 my $get_container_storage = sub {
22 my ($stcfg, $vmid, $lxc_conf) = @_;
23
24 my $path = $lxc_conf->{'lxc.rootfs'};
25 my ($vtype, $volid) = PVE::Storage::path_to_volume_id($stcfg, $path);
26 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1) if $volid;
27 return wantarray ? ($sid, $volname, $path) : $sid;
28 };
29
30 my $check_ct_modify_config_perm = sub {
31 my ($rpcenv, $authuser, $vmid, $pool, $key_list) = @_;
32
33 return 1 if $authuser ne 'root@pam';
34
35 foreach my $opt (@$key_list) {
36
37 if ($opt eq 'cpus' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
38 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
39 } elsif ($opt eq 'disk') {
40 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
41 } elsif ($opt eq 'memory' || $opt eq 'swap') {
42 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
43 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
44 $opt eq 'searchdomain' || $opt eq 'hostname') {
45 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
46 } else {
47 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
48 }
49 }
50
51 return 1;
52 };
53
54
55 __PACKAGE__->register_method({
56 name => 'vmlist',
57 path => '',
58 method => 'GET',
59 description => "LXC container index (per node).",
60 permissions => {
61 description => "Only list CTs where you have VM.Audit permissons on /vms/<vmid>.",
62 user => 'all',
63 },
64 proxyto => 'node',
65 protected => 1, # /proc files are only readable by root
66 parameters => {
67 additionalProperties => 0,
68 properties => {
69 node => get_standard_option('pve-node'),
70 },
71 },
72 returns => {
73 type => 'array',
74 items => {
75 type => "object",
76 properties => {},
77 },
78 links => [ { rel => 'child', href => "{vmid}" } ],
79 },
80 code => sub {
81 my ($param) = @_;
82
83 my $rpcenv = PVE::RPCEnvironment::get();
84 my $authuser = $rpcenv->get_user();
85
86 my $vmstatus = PVE::LXC::vmstatus();
87
88 my $res = [];
89 foreach my $vmid (keys %$vmstatus) {
90 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Audit' ], 1);
91
92 my $data = $vmstatus->{$vmid};
93 $data->{vmid} = $vmid;
94 push @$res, $data;
95 }
96
97 return $res;
98
99 }});
100
101 __PACKAGE__->register_method({
102 name => 'create_vm',
103 path => '',
104 method => 'POST',
105 description => "Create or restore a container.",
106 permissions => {
107 user => 'all', # check inside
108 description => "You need 'VM.Allocate' permissions on /vms/{vmid} or on the VM pool /pool/{pool}. " .
109 "For restore, it is enough if the user has 'VM.Backup' permission and the VM already exists. " .
110 "You also need 'Datastore.AllocateSpace' permissions on the storage.",
111 },
112 protected => 1,
113 proxyto => 'node',
114 parameters => {
115 additionalProperties => 0,
116 properties => PVE::LXC::json_config_properties({
117 node => get_standard_option('pve-node'),
118 vmid => get_standard_option('pve-vmid'),
119 ostemplate => {
120 description => "The OS template or backup file.",
121 type => 'string',
122 maxLength => 255,
123 },
124 password => {
125 optional => 1,
126 type => 'string',
127 description => "Sets root password inside container.",
128 },
129 storage => get_standard_option('pve-storage-id', {
130 description => "Target storage.",
131 default => 'local',
132 optional => 1,
133 }),
134 force => {
135 optional => 1,
136 type => 'boolean',
137 description => "Allow to overwrite existing container.",
138 },
139 restore => {
140 optional => 1,
141 type => 'boolean',
142 description => "Mark this as restore task.",
143 },
144 pool => {
145 optional => 1,
146 type => 'string', format => 'pve-poolid',
147 description => "Add the VM to the specified pool.",
148 },
149 }),
150 },
151 returns => {
152 type => 'string',
153 },
154 code => sub {
155 my ($param) = @_;
156
157 my $rpcenv = PVE::RPCEnvironment::get();
158
159 my $authuser = $rpcenv->get_user();
160
161 my $node = extract_param($param, 'node');
162
163 my $vmid = extract_param($param, 'vmid');
164
165 my $basecfg_fn = PVE::LXC::config_file($vmid);
166
167 my $same_container_exists = -f $basecfg_fn;
168
169 my $restore = extract_param($param, 'restore');
170
171 my $force = extract_param($param, 'force');
172
173 if (!($same_container_exists && $restore && $force)) {
174 PVE::Cluster::check_vmid_unused($vmid);
175 }
176
177 my $password = extract_param($param, 'password');
178
179 my $storage = extract_param($param, 'storage') || 'local';
180
181 my $pool = extract_param($param, 'pool');
182
183 my $storage_cfg = cfs_read_file("storage.cfg");
184
185 my $scfg = PVE::Storage::storage_check_node($storage_cfg, $storage, $node);
186
187 raise_param_exc({ storage => "storage '$storage' does not support container root directories"})
188 if !$scfg->{content}->{rootdir};
189
190 my $private = PVE::Storage::get_private_dir($storage_cfg, $storage, $vmid);
191
192 if (defined($pool)) {
193 $rpcenv->check_pool_exist($pool);
194 $rpcenv->check_perm_modify($authuser, "/pool/$pool");
195 }
196
197 if ($rpcenv->check($authuser, "/vms/$vmid", ['VM.Allocate'], 1)) {
198 # OK
199 } elsif ($pool && $rpcenv->check($authuser, "/pool/$pool", ['VM.Allocate'], 1)) {
200 # OK
201 } elsif ($restore && $force && $same_container_exists &&
202 $rpcenv->check($authuser, "/vms/$vmid", ['VM.Backup'], 1)) {
203 # OK: user has VM.Backup permissions, and want to restore an existing VM
204 } else {
205 raise_perm_exc();
206 }
207
208 &$check_ct_modify_config_perm($rpcenv, $authuser, $vmid, $pool, [ keys %$param]);
209
210 PVE::Storage::activate_storage($storage_cfg, $storage);
211
212 my $ostemplate = extract_param($param, 'ostemplate');
213
214 my $archive;
215
216 if ($ostemplate eq '-') {
217 die "archive pipe not implemented\n"
218 # $archive = '-';
219 } else {
220 $rpcenv->check_volume_access($authuser, $storage_cfg, $vmid, $ostemplate);
221 $archive = PVE::Storage::abs_filesystem_path($storage_cfg, $ostemplate);
222 }
223
224 my $memory = $param->{memory} || 512;
225 my $hostname = $param->{hostname} || "T$vmid";
226 my $conf = {};
227
228 $conf->{'lxc.utsname'} = $param->{hostname} || "CT$vmid";
229 $conf->{'lxc.cgroup.memory.limit_in_bytes'} = "${memory}M";
230
231 my $code = sub {
232 my $temp_conf_fn = PVE::LXC::write_temp_config($vmid, $conf);
233
234 my $cmd = ['lxc-create', '-f', $temp_conf_fn, '-t', 'pve', '-n', $vmid,
235 '--', '--archive', $archive];
236
237 eval { PVE::Tools::run_command($cmd); };
238 my $err = $@;
239
240 unlink $temp_conf_fn;
241
242 die $err if $err;
243 };
244
245 my $realcmd = sub { PVE::LXC::lock_container($vmid, 1, $code); };
246
247 return $rpcenv->fork_worker($param->{restore} ? 'vzrestore' : 'vzcreate',
248 $vmid, $authuser, $realcmd);
249
250 }});
251
252 my $vm_config_perm_list = [
253 'VM.Config.Disk',
254 'VM.Config.CPU',
255 'VM.Config.Memory',
256 'VM.Config.Network',
257 'VM.Config.Options',
258 ];
259
260 __PACKAGE__->register_method({
261 name => 'update_vm',
262 path => '{vmid}/config',
263 method => 'PUT',
264 protected => 1,
265 proxyto => 'node',
266 description => "Set container options.",
267 permissions => {
268 check => ['perm', '/vms/{vmid}', $vm_config_perm_list, any => 1],
269 },
270 parameters => {
271 additionalProperties => 0,
272 properties => PVE::LXC::json_config_properties(
273 {
274 node => get_standard_option('pve-node'),
275 vmid => get_standard_option('pve-vmid'),
276 digest => {
277 type => 'string',
278 description => 'Prevent changes if current configuration file has different SHA1 digest. This can be used to prevent concurrent modifications.',
279 maxLength => 40,
280 optional => 1,
281 }
282 }),
283 },
284 returns => { type => 'null'},
285 code => sub {
286 my ($param) = @_;
287
288 my $rpcenv = PVE::RPCEnvironment::get();
289
290 my $authuser = $rpcenv->get_user();
291
292 my $node = extract_param($param, 'node');
293
294 my $vmid = extract_param($param, 'vmid');
295
296 my $digest = extract_param($param, 'digest');
297
298 die "no options specified\n" if !scalar(keys %$param);
299
300 &$check_ct_modify_config_perm($rpcenv, $authuser, $vmid, undef, [keys %$param]);
301
302 my $code = sub {
303
304 my $conf = PVE::LXC::load_config($vmid);
305
306 PVE::Tools::assert_if_modified($digest, $conf->{digest});
307
308 die "implement me"
309 };
310
311 PVE::LXC::lock_container($vmid, undef, $code);
312
313 return undef;
314 }});
315
316 __PACKAGE__->register_method ({
317 subclass => "PVE::API2::Firewall::CT",
318 path => '{vmid}/firewall',
319 });
320
321 __PACKAGE__->register_method({
322 name => 'vmdiridx',
323 path => '{vmid}',
324 method => 'GET',
325 proxyto => 'node',
326 description => "Directory index",
327 permissions => {
328 user => 'all',
329 },
330 parameters => {
331 additionalProperties => 0,
332 properties => {
333 node => get_standard_option('pve-node'),
334 vmid => get_standard_option('pve-vmid'),
335 },
336 },
337 returns => {
338 type => 'array',
339 items => {
340 type => "object",
341 properties => {
342 subdir => { type => 'string' },
343 },
344 },
345 links => [ { rel => 'child', href => "{subdir}" } ],
346 },
347 code => sub {
348 my ($param) = @_;
349
350 # test if VM exists
351 my $conf = PVE::OpenVZ::load_config($param->{vmid});
352
353 my $res = [
354 { subdir => 'config' },
355 # { subdir => 'status' },
356 # { subdir => 'vncproxy' },
357 # { subdir => 'spiceproxy' },
358 # { subdir => 'migrate' },
359 # { subdir => 'initlog' },
360 { subdir => 'rrd' },
361 { subdir => 'rrddata' },
362 { subdir => 'firewall' },
363 ];
364
365 return $res;
366 }});
367
368 __PACKAGE__->register_method({
369 name => 'rrd',
370 path => '{vmid}/rrd',
371 method => 'GET',
372 protected => 1, # fixme: can we avoid that?
373 permissions => {
374 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
375 },
376 description => "Read VM RRD statistics (returns PNG)",
377 parameters => {
378 additionalProperties => 0,
379 properties => {
380 node => get_standard_option('pve-node'),
381 vmid => get_standard_option('pve-vmid'),
382 timeframe => {
383 description => "Specify the time frame you are interested in.",
384 type => 'string',
385 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
386 },
387 ds => {
388 description => "The list of datasources you want to display.",
389 type => 'string', format => 'pve-configid-list',
390 },
391 cf => {
392 description => "The RRD consolidation function",
393 type => 'string',
394 enum => [ 'AVERAGE', 'MAX' ],
395 optional => 1,
396 },
397 },
398 },
399 returns => {
400 type => "object",
401 properties => {
402 filename => { type => 'string' },
403 },
404 },
405 code => sub {
406 my ($param) = @_;
407
408 return PVE::Cluster::create_rrd_graph(
409 "pve2-vm/$param->{vmid}", $param->{timeframe},
410 $param->{ds}, $param->{cf});
411
412 }});
413
414 __PACKAGE__->register_method({
415 name => 'rrddata',
416 path => '{vmid}/rrddata',
417 method => 'GET',
418 protected => 1, # fixme: can we avoid that?
419 permissions => {
420 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
421 },
422 description => "Read VM RRD statistics",
423 parameters => {
424 additionalProperties => 0,
425 properties => {
426 node => get_standard_option('pve-node'),
427 vmid => get_standard_option('pve-vmid'),
428 timeframe => {
429 description => "Specify the time frame you are interested in.",
430 type => 'string',
431 enum => [ 'hour', 'day', 'week', 'month', 'year' ],
432 },
433 cf => {
434 description => "The RRD consolidation function",
435 type => 'string',
436 enum => [ 'AVERAGE', 'MAX' ],
437 optional => 1,
438 },
439 },
440 },
441 returns => {
442 type => "array",
443 items => {
444 type => "object",
445 properties => {},
446 },
447 },
448 code => sub {
449 my ($param) = @_;
450
451 return PVE::Cluster::create_rrd_data(
452 "pve2-vm/$param->{vmid}", $param->{timeframe}, $param->{cf});
453 }});
454
455
456 __PACKAGE__->register_method({
457 name => 'vm_config',
458 path => '{vmid}/config',
459 method => 'GET',
460 proxyto => 'node',
461 description => "Get container configuration.",
462 permissions => {
463 check => ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
464 },
465 parameters => {
466 additionalProperties => 0,
467 properties => {
468 node => get_standard_option('pve-node'),
469 vmid => get_standard_option('pve-vmid'),
470 },
471 },
472 returns => {
473 type => "object",
474 properties => {
475 digest => {
476 type => 'string',
477 description => 'SHA1 digest of configuration file. This can be used to prevent concurrent modifications.',
478 }
479 },
480 },
481 code => sub {
482 my ($param) = @_;
483
484 my $lxc_conf = PVE::LXC::load_config($param->{vmid});
485
486 # NOTE: we only return selected/converted values
487
488 my $conf = { digest => $lxc_conf->{digest} };
489
490 my $stcfg = PVE::Cluster::cfs_read_file("storage.cfg");
491
492 my ($sid, undef, $path) = &$get_container_storage($stcfg, $param->{vmid}, $lxc_conf);
493 $conf->{storage} = $sid || $path;
494
495 my $properties = PVE::LXC::json_config_properties();
496
497 foreach my $k (keys %$properties) {
498
499 if ($k eq 'description') {
500 if (my $raw = $lxc_conf->{'pve.comment'}) {
501 $conf->{$k} = PVE::Tools::decode_text($raw);
502 }
503 } elsif ($k eq 'hostname') {
504 $conf->{$k} = $lxc_conf->{'lxc.utsname'} if $lxc_conf->{'lxc.utsname'};
505 } elsif ($k =~ m/^net\d$/) {
506 my $net = $lxc_conf->{$k};
507 next if !$net;
508 $conf->{$k} = PVE::LXC::print_netif($net);
509 }
510 }
511
512 return $conf;
513 }});
514
515 __PACKAGE__->register_method({
516 name => 'destroy_vm',
517 path => '{vmid}',
518 method => 'DELETE',
519 protected => 1,
520 proxyto => 'node',
521 description => "Destroy the container (also delete all uses files).",
522 permissions => {
523 check => [ 'perm', '/vms/{vmid}', ['VM.Allocate']],
524 },
525 parameters => {
526 additionalProperties => 0,
527 properties => {
528 node => get_standard_option('pve-node'),
529 vmid => get_standard_option('pve-vmid'),
530 },
531 },
532 returns => {
533 type => 'string',
534 },
535 code => sub {
536 my ($param) = @_;
537
538 my $rpcenv = PVE::RPCEnvironment::get();
539
540 my $authuser = $rpcenv->get_user();
541
542 my $vmid = $param->{vmid};
543
544 # test if container exists
545 my $conf = PVE::LXC::load_config($param->{vmid});
546
547 my $realcmd = sub {
548 my $cmd = ['lxc-destroy', '-n', $vmid ];
549
550 run_command($cmd);
551
552 PVE::AccessControl::remove_vm_from_pool($vmid);
553 };
554
555 return $rpcenv->fork_worker('vzdestroy', $vmid, $authuser, $realcmd);
556 }});
557
558 1;