]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/lxccontainer.c
lxcapi: Add new get_ips() call
[mirror_lxc.git] / src / lxc / lxccontainer.c
CommitLineData
72d0e1cb
SG
1/* liblxcapi
2 *
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2, as
8 * published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
9be53773 20#define _GNU_SOURCE
71454076 21#include <pthread.h>
9be53773
SH
22#include <unistd.h>
23#include <sys/types.h>
24#include <sys/wait.h>
25#include <errno.h>
26#include <sched.h>
27#include "config.h"
72d0e1cb
SG
28#include "lxc.h"
29#include "state.h"
30#include "lxccontainer.h"
31#include "conf.h"
72d0e1cb
SG
32#include "confile.h"
33#include "cgroup.h"
34#include "commands.h"
b6b918a1 35#include "version.h"
72d0e1cb 36#include "log.h"
9be53773 37#include "bdev.h"
2a59a681 38#include <lxc/utils.h>
e51d4895 39#include <lxc/monitor.h>
9c83a661
SG
40#include <sched.h>
41#include <fcntl.h>
42#include <arpa/inet.h>
43#include <ifaddrs.h>
72d0e1cb 44
71454076
DE
45static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;
46
9be53773
SH
47/* Define unshare() if missing from the C library */
48/* this is also in attach.c and lxccontainer.c: commonize it in utils.c */
49#ifndef HAVE_UNSHARE
50static int unshare(int flags)
51{
52#ifdef __NR_unshare
53 return syscall(__NR_unshare, flags);
54#else
55 errno = ENOSYS;
56 return -1;
57#endif
58}
59#else
60int unshare(int);
61#endif
62
72d0e1cb
SG
63lxc_log_define(lxc_container, lxc);
64
65/* LOCKING
66 * c->privlock protects the struct lxc_container from multiple threads.
67 * c->slock protects the on-disk container data
71454076 68 * thread_mutex protects process data (ex: fd table) from multiple threads
72d0e1cb
SG
69 * NOTHING mutexes two independent programs with their own struct
70 * lxc_container for the same c->name, between API calls. For instance,
71 * c->config_read(); c->start(); Between those calls, data on disk
72 * could change (which shouldn't bother the caller unless for instance
73 * the rootfs get moved). c->config_read(); update; c->config_write();
74 * Two such updaters could race. The callers should therefore check their
75 * results. Trying to prevent that would necessarily expose us to deadlocks
76 * due to hung callers. So I prefer to keep the locks only within our own
77 * functions, not across functions.
78 *
79 * If you're going to fork while holding a lxccontainer, increment
80 * c->numthreads (under privlock) before forking. When deleting,
81 * decrement numthreads under privlock, then if it hits 0 you can delete.
82 * Do not ever use a lxccontainer whose numthreads you did not bump.
83 */
84
85static void lxc_container_free(struct lxc_container *c)
86{
87 if (!c)
88 return;
89
90 if (c->configfile) {
91 free(c->configfile);
92 c->configfile = NULL;
93 }
94 if (c->error_string) {
95 free(c->error_string);
96 c->error_string = NULL;
97 }
d95db067
DE
98 if (c->slock) {
99 sem_close(c->slock);
100 c->slock = NULL;
101 }
72d0e1cb 102 if (c->privlock) {
43d1aa34 103 sem_t *l = c->privlock;
72d0e1cb 104 c->privlock = NULL;
43d1aa34
SH
105 sem_destroy(l);
106 free(l);
72d0e1cb
SG
107 }
108 if (c->name) {
109 free(c->name);
110 c->name = NULL;
111 }
d95db067
DE
112 if (c->lxc_conf) {
113 lxc_conf_free(c->lxc_conf);
114 c->lxc_conf = NULL;
115 }
2a59a681
SH
116 if (c->config_path) {
117 free(c->config_path);
118 c->config_path = NULL;
119 }
72d0e1cb
SG
120 free(c);
121}
122
43d1aa34
SH
123/*
124 * Consider the following case:
125freer | racing get()er
126==================================================================
127lxc_container_put() | lxc_container_get()
128\ lxclock(c->privlock) | c->numthreads < 1? (no)
129\ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
130\ lxcunlock() | \
131\ lxc_container_free() | \ lxclock() returns
132 | \ c->numthreads < 1 -> return 0
133\ \ (free stuff) |
134\ \ sem_destroy(privlock) |
135
136 * When the get()er checks numthreads the first time, one of the following
137 * is true:
138 * 1. freer has set numthreads = 0. get() returns 0
139 * 2. freer is between lxclock and setting numthreads to 0. get()er will
140 * sem_wait on privlock, get lxclock after freer() drops it, then see
141 * numthreads is 0 and exit without touching lxclock again..
142 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
143 * will see --numthreads = 1 and not call lxc_container_free().
144*/
145
72d0e1cb
SG
146int lxc_container_get(struct lxc_container *c)
147{
148 if (!c)
149 return 0;
150
43d1aa34
SH
151 // if someone else has already started freeing the container, don't
152 // try to take the lock, which may be invalid
153 if (c->numthreads < 1)
154 return 0;
155
72d0e1cb
SG
156 if (lxclock(c->privlock, 0))
157 return 0;
158 if (c->numthreads < 1) {
159 // bail without trying to unlock, bc the privlock is now probably
160 // in freed memory
161 return 0;
162 }
163 c->numthreads++;
164 lxcunlock(c->privlock);
165 return 1;
166}
167
168int lxc_container_put(struct lxc_container *c)
169{
170 if (!c)
171 return -1;
172 if (lxclock(c->privlock, 0))
173 return -1;
174 if (--c->numthreads < 1) {
175 lxcunlock(c->privlock);
176 lxc_container_free(c);
177 return 1;
178 }
179 lxcunlock(c->privlock);
180 return 0;
181}
182
183static bool file_exists(char *f)
184{
185 struct stat statbuf;
186
187 return stat(f, &statbuf) == 0;
188}
189
190static bool lxcapi_is_defined(struct lxc_container *c)
191{
192 struct stat statbuf;
193 bool ret = false;
194 int statret;
195
196 if (!c)
197 return false;
198
199 if (lxclock(c->privlock, 0))
200 return false;
201 if (!c->configfile)
202 goto out;
203 statret = stat(c->configfile, &statbuf);
204 if (statret != 0)
205 goto out;
206 ret = true;
207
208out:
209 lxcunlock(c->privlock);
210 return ret;
211}
212
213static const char *lxcapi_state(struct lxc_container *c)
214{
215 const char *ret;
216 lxc_state_t s;
217
218 if (!c)
219 return NULL;
220 if (lxclock(c->slock, 0))
221 return NULL;
13f5be62 222 s = lxc_getstate(c->name, c->config_path);
72d0e1cb
SG
223 ret = lxc_state2str(s);
224 lxcunlock(c->slock);
225
226 return ret;
227}
228
794dd120
SH
229static bool is_stopped_nolock(struct lxc_container *c)
230{
231 lxc_state_t s;
13f5be62 232 s = lxc_getstate(c->name, c->config_path);
794dd120
SH
233 return (s == STOPPED);
234}
235
72d0e1cb
SG
236static bool lxcapi_is_running(struct lxc_container *c)
237{
238 const char *s;
239
240 if (!c)
241 return false;
242 s = lxcapi_state(c);
243 if (!s || strcmp(s, "STOPPED") == 0)
244 return false;
245 return true;
246}
247
248static bool lxcapi_freeze(struct lxc_container *c)
249{
250 int ret;
251 if (!c)
252 return false;
253
254 if (lxclock(c->slock, 0))
255 return false;
9123e471 256 ret = lxc_freeze(c->name, c->config_path);
72d0e1cb
SG
257 lxcunlock(c->slock);
258 if (ret)
259 return false;
260 return true;
261}
262
263static bool lxcapi_unfreeze(struct lxc_container *c)
264{
265 int ret;
266 if (!c)
267 return false;
268
269 if (lxclock(c->slock, 0))
270 return false;
9123e471 271 ret = lxc_unfreeze(c->name, c->config_path);
72d0e1cb
SG
272 lxcunlock(c->slock);
273 if (ret)
274 return false;
275 return true;
276}
277
278static pid_t lxcapi_init_pid(struct lxc_container *c)
279{
280 pid_t ret;
281 if (!c)
282 return -1;
283
284 if (lxclock(c->slock, 0))
285 return -1;
13f5be62 286 ret = get_init_pid(c->name, c->config_path);
72d0e1cb
SG
287 lxcunlock(c->slock);
288 return ret;
289}
290
12a50cc6 291static bool load_config_locked(struct lxc_container *c, const char *fname)
8eb5694b
SH
292{
293 if (!c->lxc_conf)
294 c->lxc_conf = lxc_conf_init();
295 if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
296 return true;
297 return false;
298}
299
12a50cc6 300static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
72d0e1cb
SG
301{
302 bool ret = false;
12a50cc6 303 const char *fname;
72d0e1cb
SG
304 if (!c)
305 return false;
306
307 fname = c->configfile;
308 if (alt_file)
309 fname = alt_file;
310 if (!fname)
311 return false;
312 if (lxclock(c->slock, 0))
313 return false;
8eb5694b 314 ret = load_config_locked(c, fname);
72d0e1cb
SG
315 lxcunlock(c->slock);
316 return ret;
317}
318
319static void lxcapi_want_daemonize(struct lxc_container *c)
320{
321 if (!c)
322 return;
323 c->daemonize = 1;
324}
325
12a50cc6 326static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
7a44c8b4
SG
327{
328 int ret;
329
330 if (!c)
331 return false;
332
67e571de 333 ret = lxc_wait(c->name, state, timeout, c->config_path);
7a44c8b4
SG
334 return ret == 0;
335}
336
337
338static bool wait_on_daemonized_start(struct lxc_container *c)
339{
340 /* we'll probably want to make this timeout configurable? */
697fa639 341 int timeout = 5, ret, status;
7a44c8b4 342
697fa639
SH
343 /*
344 * our child is going to fork again, then exit. reap the
345 * child
346 */
347 ret = wait(&status);
348 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
349 DEBUG("failed waiting for first dual-fork child");
7a44c8b4
SG
350 return lxcapi_wait(c, "RUNNING", timeout);
351}
352
72d0e1cb
SG
353/*
354 * I can't decide if it'd be more convenient for callers if we accept '...',
355 * or a null-terminated array (i.e. execl vs execv)
356 */
12a50cc6 357static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
72d0e1cb
SG
358{
359 int ret;
360 struct lxc_conf *conf;
361 int daemonize = 0;
362 char *default_args[] = {
363 "/sbin/init",
364 '\0',
365 };
366
367 /* container exists */
368 if (!c)
369 return false;
370 /* container has been setup */
371 if (!c->lxc_conf)
372 return false;
373
374 /* is this app meant to be run through lxcinit, as in lxc-execute? */
375 if (useinit && !argv)
376 return false;
377
378 if (lxclock(c->privlock, 0))
379 return false;
380 conf = c->lxc_conf;
381 daemonize = c->daemonize;
382 lxcunlock(c->privlock);
383
384 if (useinit) {
13f5be62 385 ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
72d0e1cb
SG
386 return ret == 0 ? true : false;
387 }
388
389 if (!argv)
390 argv = default_args;
391
392 /*
393 * say, I'm not sure - what locks do we want here? Any?
394 * Is liblxc's locking enough here to protect the on disk
395 * container? We don't want to exclude things like lxc_info
396 * while container is running...
397 */
398 if (daemonize) {
399 if (!lxc_container_get(c))
400 return false;
e51d4895 401 lxc_monitord_spawn(c->config_path);
71454076
DE
402
403 ret = pthread_mutex_lock(&thread_mutex);
404 if (ret != 0) {
405 ERROR("pthread_mutex_lock returned:%d %s", ret, strerror(ret));
406 return false;
407 }
72d0e1cb
SG
408 pid_t pid = fork();
409 if (pid < 0) {
410 lxc_container_put(c);
71454076 411 pthread_mutex_unlock(&thread_mutex);
72d0e1cb
SG
412 return false;
413 }
71454076
DE
414 if (pid != 0) {
415 ret = wait_on_daemonized_start(c);
416 pthread_mutex_unlock(&thread_mutex);
417 return ret;
418 }
419 pthread_mutex_unlock(&thread_mutex);
697fa639
SH
420 /* second fork to be reparented by init */
421 pid = fork();
422 if (pid < 0) {
423 SYSERROR("Error doing dual-fork");
424 return false;
425 }
426 if (pid != 0)
427 exit(0);
72d0e1cb 428 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
c278cef2
SH
429 if (chdir("/")) {
430 SYSERROR("Error chdir()ing to /.");
431 return false;
432 }
72d0e1cb
SG
433 close(0);
434 close(1);
435 close(2);
436 open("/dev/null", O_RDONLY);
437 open("/dev/null", O_RDWR);
438 open("/dev/null", O_RDWR);
439 setsid();
440 }
441
72d0e1cb
SG
442reboot:
443 conf->reboot = 0;
13f5be62 444 ret = lxc_start(c->name, argv, conf, c->config_path);
72d0e1cb
SG
445
446 if (conf->reboot) {
447 INFO("container requested reboot");
448 conf->reboot = 0;
72d0e1cb
SG
449 goto reboot;
450 }
451
452 if (daemonize) {
453 lxc_container_put(c);
454 exit (ret == 0 ? true : false);
455 } else {
456 return (ret == 0 ? true : false);
457 }
458}
459
460/*
461 * note there MUST be an ending NULL
462 */
463static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
464{
465 va_list ap;
466 char **inargs = NULL, **temp;
467 int n_inargs = 0;
468 bool bret = false;
469
470 /* container exists */
471 if (!c)
472 return false;
473
474 /* build array of arguments if any */
475 va_start(ap, useinit);
476 while (1) {
477 char *arg;
478 arg = va_arg(ap, char *);
479 if (!arg)
480 break;
481 n_inargs++;
482 temp = realloc(inargs, n_inargs * sizeof(*inargs));
586d4e9b
SH
483 if (!temp) {
484 va_end(ap);
72d0e1cb 485 goto out;
586d4e9b 486 }
72d0e1cb
SG
487 inargs = temp;
488 inargs[n_inargs - 1] = strdup(arg); // not sure if it's safe not to copy
489 }
490 va_end(ap);
491
492 /* add trailing NULL */
493 if (n_inargs) {
494 n_inargs++;
495 temp = realloc(inargs, n_inargs * sizeof(*inargs));
496 if (!temp)
497 goto out;
498 inargs = temp;
499 inargs[n_inargs - 1] = NULL;
500 }
501
502 bret = lxcapi_start(c, useinit, inargs);
503
504out:
505 if (inargs) {
506 int i;
507 for (i = 0; i < n_inargs; i++) {
508 if (inargs[i])
509 free(inargs[i]);
510 }
511 free(inargs);
512 }
513
514 return bret;
515}
516
517static bool lxcapi_stop(struct lxc_container *c)
518{
519 int ret;
520
521 if (!c)
522 return false;
523
13f5be62 524 ret = lxc_stop(c->name, c->config_path);
72d0e1cb
SG
525
526 return ret == 0;
72d0e1cb
SG
527}
528
529static bool valid_template(char *t)
530{
531 struct stat statbuf;
532 int statret;
533
534 statret = stat(t, &statbuf);
535 if (statret == 0)
536 return true;
537 return false;
538}
539
540/*
541 * create the standard expected container dir
542 */
543static bool create_container_dir(struct lxc_container *c)
544{
545 char *s;
546 int len, ret;
547
2a59a681 548 len = strlen(c->config_path) + strlen(c->name) + 2;
72d0e1cb
SG
549 s = malloc(len);
550 if (!s)
551 return false;
2a59a681 552 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
72d0e1cb
SG
553 if (ret < 0 || ret >= len) {
554 free(s);
555 return false;
556 }
557 ret = mkdir(s, 0755);
558 if (ret) {
559 if (errno == EEXIST)
560 ret = 0;
561 else
562 SYSERROR("failed to create container path for %s\n", c->name);
563 }
564 free(s);
565 return ret == 0;
566}
567
568/*
569 * backing stores not (yet) supported
570 * for ->create, argv contains the arguments to pass to the template,
571 * terminated by NULL. If no arguments, you can just pass NULL.
572 */
12a50cc6 573static bool lxcapi_create(struct lxc_container *c, char *t, char *const argv[])
72d0e1cb
SG
574{
575 bool bret = false;
576 pid_t pid;
9be53773
SH
577 char *tpath = NULL, **newargv;
578 int ret, len, nargs = 0;
72d0e1cb
SG
579
580 if (!c)
581 return false;
582
583 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
584 tpath = malloc(len);
585 if (!tpath)
586 return false;
587 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
588 if (ret < 0 || ret >= len)
589 goto out;
590 if (!valid_template(tpath)) {
591 ERROR("bad template: %s\n", t);
592 goto out;
593 }
594
72d0e1cb
SG
595 if (!c->save_config(c, NULL)) {
596 ERROR("failed to save starting configuration for %s\n", c->name);
597 goto out;
598 }
599
5a3d2e1e 600 /* container is already created if we have a config and rootfs.path is accessible */
e51d4895 601 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0)
a741a85d 602 goto out;
5a3d2e1e 603
72d0e1cb 604 /* we're going to fork. but since we'll wait for our child, we
9be53773 605 * don't need to lxc_container_get */
72d0e1cb
SG
606
607 if (lxclock(c->slock, 0)) {
608 ERROR("failed to grab global container lock for %s\n", c->name);
609 goto out;
610 }
611
612 pid = fork();
613 if (pid < 0) {
614 SYSERROR("failed to fork task for container creation template\n");
615 goto out_unlock;
616 }
617
618 if (pid == 0) { // child
619 char *patharg, *namearg;
620 int i;
621
622 close(0);
623 close(1);
624 close(2);
625 open("/dev/null", O_RDONLY);
626 open("/dev/null", O_RDWR);
627 open("/dev/null", O_RDWR);
628
629 /*
630 * create our new array, pre-pend the template name and
631 * base args
632 */
633 if (argv)
634 for (; argv[nargs]; nargs++) ;
635 nargs += 3; // template, path and name args
636 newargv = malloc(nargs * sizeof(*newargv));
637 if (!newargv)
638 exit(1);
639 newargv[0] = t;
640
2a59a681 641 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
72d0e1cb
SG
642 patharg = malloc(len);
643 if (!patharg)
644 exit(1);
2a59a681 645 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
72d0e1cb
SG
646 if (ret < 0 || ret >= len)
647 exit(1);
648 newargv[1] = patharg;
649 len = strlen("--name=") + strlen(c->name) + 1;
650 namearg = malloc(len);
651 if (!namearg)
652 exit(1);
653 ret = snprintf(namearg, len, "--name=%s", c->name);
654 if (ret < 0 || ret >= len)
655 exit(1);
656 newargv[2] = namearg;
657
658 /* add passed-in args */
659 if (argv)
660 for (i = 3; i < nargs; i++)
661 newargv[i] = argv[i-3];
662
663 /* add trailing NULL */
664 nargs++;
665 newargv = realloc(newargv, nargs * sizeof(*newargv));
666 if (!newargv)
667 exit(1);
668 newargv[nargs - 1] = NULL;
669
670 /* execute */
e6a19d26 671 execv(tpath, newargv);
72d0e1cb
SG
672 SYSERROR("failed to execute template %s", tpath);
673 exit(1);
674 }
675
9be53773
SH
676 if (wait_for_pid(pid) != 0) {
677 ERROR("container creation template for %s failed\n", c->name);
8eb5694b
SH
678 goto out_unlock;
679 }
680
681 // now clear out the lxc_conf we have, reload from the created
682 // container
683 if (c->lxc_conf)
684 lxc_conf_free(c->lxc_conf);
685 c->lxc_conf = NULL;
686 bret = load_config_locked(c, c->configfile);
72d0e1cb
SG
687
688out_unlock:
689 lxcunlock(c->slock);
690out:
691 if (tpath)
692 free(tpath);
693 return bret;
694}
695
696static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
697{
698 bool retv;
699 pid_t pid;
700
701 if (!c)
702 return false;
703
704 if (!timeout)
705 timeout = -1;
706 if (!c->is_running(c))
707 return true;
708 pid = c->init_pid(c);
709 if (pid <= 0)
710 return true;
711 kill(pid, SIGPWR);
712 retv = c->wait(c, "STOPPED", timeout);
f6144ed4 713 if (!retv && timeout > 0) {
72d0e1cb
SG
714 c->stop(c);
715 retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
716 }
717 return retv;
718}
719
720static bool lxcapi_createl(struct lxc_container *c, char *t, ...)
721{
722 bool bret = false;
723 char **args = NULL, **temp;
724 va_list ap;
725 int nargs = 0;
726
727 if (!c)
728 return false;
729
730 /*
731 * since we're going to wait for create to finish, I don't think we
732 * need to get a copy of the arguments.
733 */
734 va_start(ap, t);
735 while (1) {
736 char *arg;
737 arg = va_arg(ap, char *);
738 if (!arg)
739 break;
740 nargs++;
83cab6e0 741 temp = realloc(args, (nargs+1) * sizeof(*args));
41670788
SH
742 if (!temp) {
743 va_end(ap);
72d0e1cb 744 goto out;
41670788 745 }
72d0e1cb
SG
746 args = temp;
747 args[nargs - 1] = arg;
748 }
749 va_end(ap);
63e414f8
SH
750 if (args)
751 args[nargs] = NULL;
72d0e1cb
SG
752
753 bret = c->create(c, t, args);
754
755out:
756 if (args)
757 free(args);
758 return bret;
759}
760
12a50cc6 761static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
72d0e1cb
SG
762{
763 int ret;
764
765 if (!c || !c->lxc_conf)
766 return false;
767 if (lxclock(c->privlock, 0)) {
768 return false;
769 }
770 ret = lxc_clear_config_item(c->lxc_conf, key);
771 lxcunlock(c->privlock);
772 return ret == 0;
773}
774
9c83a661
SG
775char** lxcapi_get_ips(struct lxc_container *c, char* interface, char* family, int scope)
776{
777 int count = 0;
778 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
779 char addressOutputBuffer[INET6_ADDRSTRLEN];
780 void *tempAddrPtr = NULL;
781 char **addresses = NULL, **temp;
782 char *address = NULL;
783 char new_netns_path[MAXPATHLEN];
784 int old_netns = -1, new_netns = -1, ret = 0;
785
786 if (!c->is_running(c))
787 goto out;
788
789 /* Save reference to old netns */
790 old_netns = open("/proc/self/ns/net", O_RDONLY);
791 if (old_netns < 0) {
792 SYSERROR("failed to open /proc/self/ns/net");
793 goto out;
794 }
795
796 /* Switch to new netns */
797 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", c->init_pid(c));
798 if (ret < 0 || ret >= MAXPATHLEN)
799 goto out;
800
801 new_netns = open(new_netns_path, O_RDONLY);
802 if (new_netns < 0) {
803 SYSERROR("failed to open %s", new_netns_path);
804 goto out;
805 }
806
807 if (setns(new_netns, CLONE_NEWNET)) {
808 SYSERROR("failed to setns");
809 goto out;
810 }
811
812 /* Grab the list of interfaces */
813 if (getifaddrs(&interfaceArray)) {
814 SYSERROR("failed to get interfaces list");
815 goto out;
816 }
817
818 /* Iterate through the interfaces */
819 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
820 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
821 if (family && strcmp(family, "inet"))
822 continue;
823 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
824 }
825 else {
826 if (family && strcmp(family, "inet6"))
827 continue;
828
829 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
830 continue;
831
832 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
833 }
834
835 if (interface && strcmp(interface, tempIfAddr->ifa_name))
836 continue;
837 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
838 continue;
839
840 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
841 tempAddrPtr,
842 addressOutputBuffer,
843 sizeof(addressOutputBuffer));
844 if (!address)
845 continue;
846
847 count += 1;
848 temp = realloc(addresses, count * sizeof(*addresses));
849 if (!temp) {
850 count--;
851 goto out;
852 }
853 addresses = temp;
854 addresses[count - 1] = strdup(address);
855 }
856
857out:
858 if(interfaceArray)
859 freeifaddrs(interfaceArray);
860
861 /* Switch back to original netns */
862 if (old_netns >= 0 && setns(old_netns, CLONE_NEWNET))
863 SYSERROR("failed to setns");
864 if (new_netns >= 0)
865 close(new_netns);
866 if (old_netns >= 0)
867 close(old_netns);
868
869 /* Append NULL to the array */
870 if (count) {
871 count++;
872 temp = realloc(addresses, count * sizeof(*addresses));
873 if (!temp) {
874 for (int i = 0; i < count-1; i++)
875 free(addresses[i]);
876 free(addresses);
877 return NULL;
878 }
879 addresses = temp;
880 addresses[count - 1] = NULL;
881 }
882
883 return addresses;
884}
885
12a50cc6 886static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
887{
888 int ret;
889
890 if (!c || !c->lxc_conf)
891 return -1;
892 if (lxclock(c->privlock, 0)) {
893 return -1;
894 }
895 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
896 lxcunlock(c->privlock);
897 return ret;
898}
899
12a50cc6 900static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
72d0e1cb
SG
901{
902 if (!key)
903 return lxc_listconfigs(retv, inlen);
904 /*
905 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
906 * This is an intelligent result to show which keys are valid given
907 * the type of nic it is
908 */
909 if (!c || !c->lxc_conf)
910 return -1;
911 if (lxclock(c->privlock, 0))
912 return -1;
913 int ret = -1;
914 if (strncmp(key, "lxc.network.", 12) == 0)
915 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
916 lxcunlock(c->privlock);
917 return ret;
918}
919
920
921/* default config file - should probably come through autoconf */
bb9702b5 922#define LXC_DEFAULT_CONFIG "/etc/lxc/default.conf"
12a50cc6 923static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
72d0e1cb
SG
924{
925 if (!alt_file)
926 alt_file = c->configfile;
927 if (!alt_file)
928 return false; // should we write to stdout if no file is specified?
929 if (!c->lxc_conf)
930 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
931 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
932 return false;
933 }
934
5a3d2e1e
SG
935 if (!create_container_dir(c))
936 return false;
937
72d0e1cb
SG
938 FILE *fout = fopen(alt_file, "w");
939 if (!fout)
940 return false;
941 if (lxclock(c->privlock, 0)) {
942 fclose(fout);
943 return false;
944 }
945 write_config(fout, c->lxc_conf);
946 fclose(fout);
947 lxcunlock(c->privlock);
948 return true;
949}
950
951static bool lxcapi_destroy(struct lxc_container *c)
952{
953 pid_t pid;
72d0e1cb
SG
954
955 if (!c)
956 return false;
957
5a3d2e1e 958 /* container is already destroyed if we don't have a config and rootfs.path is not accessible */
e51d4895 959 if (!lxcapi_is_defined(c) && (!c->lxc_conf || !c->lxc_conf->rootfs.path || access(c->lxc_conf->rootfs.path, F_OK) != 0))
5a3d2e1e
SG
960 return false;
961
72d0e1cb
SG
962 pid = fork();
963 if (pid < 0)
964 return false;
965 if (pid == 0) { // child
e6a19d26 966 execlp("lxc-destroy", "lxc-destroy", "-n", c->name, "-P", c->config_path, NULL);
72d0e1cb
SG
967 perror("execl");
968 exit(1);
969 }
970
9be53773
SH
971 if (wait_for_pid(pid) < 0) {
972 ERROR("Error destroying container %s", c->name);
72d0e1cb
SG
973 return false;
974 }
975
9be53773 976 return true;
72d0e1cb
SG
977}
978
12a50cc6 979static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
72d0e1cb
SG
980{
981 int ret;
982 bool b = false;
983 struct lxc_config_t *config;
984
985 if (!c)
986 return false;
987
988 if (lxclock(c->privlock, 0))
989 return false;
990
991 if (!c->lxc_conf)
992 c->lxc_conf = lxc_conf_init();
993 if (!c->lxc_conf)
994 goto err;
995 config = lxc_getconfig(key);
996 if (!config)
997 goto err;
998 ret = config->cb(key, v, c->lxc_conf);
999 if (!ret)
1000 b = true;
1001
1002err:
1003 lxcunlock(c->privlock);
1004 return b;
1005}
1006
1007static char *lxcapi_config_file_name(struct lxc_container *c)
1008{
1009 if (!c || !c->configfile)
1010 return NULL;
1011 return strdup(c->configfile);
1012}
1013
2a59a681
SH
1014static const char *lxcapi_get_config_path(struct lxc_container *c)
1015{
1016 if (!c || !c->config_path)
1017 return NULL;
1018 return (const char *)(c->config_path);
1019}
1020
afeecbba
SH
1021/*
1022 * not for export
1023 * Just recalculate the c->configfile based on the
1024 * c->config_path, which must be set.
1025 * The lxc_container must be locked or not yet public.
1026 */
1027static bool set_config_filename(struct lxc_container *c)
1028{
1029 char *newpath;
1030 int len, ret;
1031
1032 if (!c->config_path)
1033 return false;
1034
1035 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1036 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
1037 newpath = malloc(len);
1038 if (!newpath)
1039 return false;
1040
1041 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
1042 if (ret < 0 || ret >= len) {
1043 fprintf(stderr, "Error printing out config file name\n");
1044 free(newpath);
1045 return false;
1046 }
1047
1048 if (c->configfile)
1049 free(c->configfile);
1050 c->configfile = newpath;
1051
1052 return true;
1053}
1054
2a59a681
SH
1055static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
1056{
1057 char *p;
1058 bool b = false;
afeecbba 1059 char *oldpath = NULL;
2a59a681
SH
1060
1061 if (!c)
1062 return b;
1063
1064 if (lxclock(c->privlock, 0))
1065 return b;
1066
1067 p = strdup(path);
afeecbba
SH
1068 if (!p) {
1069 ERROR("Out of memory setting new lxc path");
2a59a681 1070 goto err;
afeecbba
SH
1071 }
1072
2a59a681
SH
1073 b = true;
1074 if (c->config_path)
afeecbba 1075 oldpath = c->config_path;
2a59a681 1076 c->config_path = p;
afeecbba
SH
1077
1078 /* Since we've changed the config path, we have to change the
1079 * config file name too */
1080 if (!set_config_filename(c)) {
1081 ERROR("Out of memory setting new config filename");
1082 b = false;
1083 free(c->config_path);
1084 c->config_path = oldpath;
1085 oldpath = NULL;
1086 }
2a59a681 1087err:
afeecbba
SH
1088 if (oldpath)
1089 free(oldpath);
2a59a681
SH
1090 lxcunlock(c->privlock);
1091 return b;
1092}
1093
1094
794dd120
SH
1095static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
1096{
1097 int ret;
1098 bool b = false;
1099
1100 if (!c)
1101 return false;
1102
1103 if (lxclock(c->privlock, 0))
1104 return false;
1105
1106 if (is_stopped_nolock(c))
1107 goto err;
1108
ae5c8b8e 1109 ret = lxc_cgroup_set(c->name, subsys, value, c->config_path);
794dd120
SH
1110 if (!ret)
1111 b = true;
1112err:
1113 lxcunlock(c->privlock);
1114 return b;
1115}
1116
1117static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
1118{
1119 int ret = -1;
1120
1121 if (!c || !c->lxc_conf)
1122 return -1;
1123
1124 if (lxclock(c->privlock, 0))
1125 return -1;
1126
1127 if (is_stopped_nolock(c))
1128 goto out;
1129
ae5c8b8e 1130 ret = lxc_cgroup_get(c->name, subsys, retv, inlen, c->config_path);
794dd120
SH
1131
1132out:
1133 lxcunlock(c->privlock);
1134 return ret;
1135}
1136
67e571de 1137const char *lxc_get_default_config_path(void)
83c98d82
DE
1138{
1139 return default_lxc_path();
1140}
794dd120 1141
a8428dfa
SH
1142const char *lxc_get_default_lvm_vg(void)
1143{
1144 return default_lvm_vg();
1145}
1146
1147const char *lxc_get_default_zfs_root(void)
1148{
1149 return default_zfs_root();
1150}
1151
b6b918a1
SG
1152const char *lxc_get_version(void)
1153{
1154 return lxc_version();
1155}
1156
9be53773
SH
1157static int copy_file(char *old, char *new)
1158{
1159 int in, out;
1160 ssize_t len, ret;
1161 char buf[8096];
1162 struct stat sbuf;
1163
1164 if (file_exists(new)) {
1165 ERROR("copy destination %s exists", new);
1166 return -1;
1167 }
1168 ret = stat(old, &sbuf);
1169 if (ret < 0) {
1170 SYSERROR("stat'ing %s", old);
1171 return -1;
1172 }
1173
1174 in = open(old, O_RDONLY);
1175 if (in < 0) {
1176 SYSERROR("opening original file %s", old);
1177 return -1;
1178 }
1179 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
1180 if (out < 0) {
1181 SYSERROR("opening new file %s", new);
1182 close(in);
1183 return -1;
1184 }
1185
1186 while (1) {
1187 len = read(in, buf, 8096);
1188 if (len < 0) {
1189 SYSERROR("reading old file %s", old);
1190 goto err;
1191 }
1192 if (len == 0)
1193 break;
1194 ret = write(out, buf, len);
1195 if (ret < len) { // should we retry?
1196 SYSERROR("write to new file %s was interrupted", new);
1197 goto err;
1198 }
1199 }
1200 close(in);
1201 close(out);
1202
1203 // we set mode, but not owner/group
1204 ret = chmod(new, sbuf.st_mode);
1205 if (ret) {
1206 SYSERROR("setting mode on %s", new);
1207 return -1;
1208 }
1209
1210 return 0;
1211
1212err:
1213 close(in);
1214 close(out);
1215 return -1;
1216}
1217
1218/*
1219 * we're being passed result of two strstrs(x, y). We want to write
1220 * all data up to the first found string, or to end of the string if
1221 * neither string was found.
1222 * This function will return the earliest found string if any, or else
1223 * NULL
1224 */
1225static const char *lowest_nonnull(const char *p1, const char *p2)
1226{
1227 if (!p1)
1228 return p2;
1229 if (!p2)
1230 return p1;
1231 return p1 < p2 ? p1 : p2;
1232}
1233
1234static int is_word_sep(char c)
1235{
1236 switch(c) {
1237 case '\0':
1238 case '\n':
1239 case '\r':
1240 case '\t':
1241 case ' ':
1242 case '=':
1243 case '/':
1244 return 1;
1245 default: return 0;
1246 }
1247}
1248
1249static const char *find_first_wholeword(const char *p, const char *word)
1250{
1251 if (!p)
1252 return NULL;
1253
1254 while ((p = strstr(p, word)) != NULL) {
1255 if (is_word_sep(*(p-1)) && is_word_sep(p[strlen(word)]))
1256 return p;
1257 p++;
1258 }
1259 return NULL;
1260}
1261
1262static int update_name_and_paths(const char *path, struct lxc_container *oldc,
1263 const char *newname, const char *newpath)
1264{
1265 FILE *f;
a7478944 1266 long flen;
9be53773
SH
1267 char *contents;
1268 const char *p0, *p1, *p2, *end;
1269 const char *oldpath = oldc->get_config_path(oldc);
1270 const char *oldname = oldc->name;
1271
1272 f = fopen(path, "r");
1273 if (!f) {
1274 SYSERROR("opening old config");
1275 return -1;
1276 }
1277 if (fseek(f, 0, SEEK_END) < 0) {
1278 SYSERROR("seeking to end of old config");
1279 fclose(f);
1280 return -1;
1281 }
1282 flen = ftell(f);
1283 if (flen < 0) {
1284 fclose(f);
1285 SYSERROR("telling size of old config");
1286 return -1;
1287 }
1288 if (fseek(f, 0, SEEK_SET) < 0) {
1289 fclose(f);
1290 SYSERROR("rewinding old config");
1291 return -1;
1292 }
a2eea3c1 1293 contents = malloc(flen+1);
9be53773
SH
1294 if (!contents) {
1295 SYSERROR("out of memory");
1296 fclose(f);
a2eea3c1 1297 return -1;
9be53773
SH
1298 }
1299 if (fread(contents, 1, flen, f) != flen) {
1300 free(contents);
1301 fclose(f);
1302 SYSERROR("reading old config");
1303 return -1;
1304 }
a2eea3c1 1305 contents[flen] = '\0';
9be53773
SH
1306 if (fclose(f) < 0) {
1307 free(contents);
1308 SYSERROR("closing old config");
1309 return -1;
1310 }
1311
1312 f = fopen(path, "w");
1313 if (!f) {
1314 SYSERROR("reopening config");
1315 free(contents);
1316 return -1;
1317 }
1318
1319 p0 = contents;
1320 end = contents + flen;
1321 while (1) {
1322 p1 = find_first_wholeword(p0, oldpath);
1323 p2 = find_first_wholeword(p0, oldname);
1324 if (!p1 && !p2) {
1325 // write the rest and be done
1326 if (fwrite(p0, 1, (end-p0), f) != (end-p0)) {
1327 SYSERROR("writing new config");
1328 free(contents);
1329 fclose(f);
1330 return -1;
1331 }
1332 free(contents);
1333 fclose(f);
1334 // success
1335 return 0;
1336 } else {
1337 const char *p = lowest_nonnull(p1, p2);
1338 const char *new = (p == p2) ? newname : newpath;
1339 if (fwrite(p0, 1, (p-p0), f) != (p-p0)) {
1340 SYSERROR("writing new config");
1341 free(contents);
1342 fclose(f);
1343 return -1;
1344 }
1345 p0 = p;
1346 // now write the newpath or newname
1347 if (fwrite(new, 1, strlen(new), f) != strlen(new)) {
1348 SYSERROR("writing new name or path in new config");
1349 free(contents);
1350 fclose(f);
1351 return -1;
1352 }
1353 p0 += (p == p2) ? strlen(oldname) : strlen(oldpath);
1354 }
1355 }
1356}
1357
1358static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
1359{
1360 int i;
1361 int ret;
1362 struct lxc_list *it;
1363
1364 for (i=0; i<NUM_LXC_HOOKS; i++) {
1365 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
1366 char *hookname = it->elem;
1367 char *fname = rindex(hookname, '/');
1368 char tmppath[MAXPATHLEN];
1369 if (!fname) // relative path - we don't support, but maybe we should
1370 return 0;
1371 // copy the script, and change the entry in confile
1372 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
1373 c->config_path, c->name, fname+1);
1374 if (ret < 0 || ret >= MAXPATHLEN)
1375 return -1;
1376 ret = copy_file(it->elem, tmppath);
1377 if (ret < 0)
1378 return -1;
1379 free(it->elem);
1380 it->elem = strdup(tmppath);
1381 if (!it->elem) {
1382 ERROR("out of memory copying hook path");
1383 return -1;
1384 }
1385 update_name_and_paths(it->elem, oldc, c->name, c->get_config_path(c));
1386 }
1387 }
1388
1389 c->save_config(c, NULL);
1390 return 0;
1391}
1392
1393static void new_hwaddr(char *hwaddr)
1394{
1395 FILE *f = fopen("/dev/urandom", "r");
1396 if (f) {
1397 unsigned int seed;
1398 int ret = fread(&seed, sizeof(seed), 1, f);
1399 if (ret != 1)
1400 seed = time(NULL);
1401 fclose(f);
1402 srand(seed);
1403 } else
1404 srand(time(NULL));
1405 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
1406 rand() % 255, rand() % 255, rand() % 255);
1407}
1408
1409static void network_new_hwaddrs(struct lxc_container *c)
1410{
1411 struct lxc_list *it;
1412
1413 lxc_list_for_each(it, &c->lxc_conf->network) {
1414 struct lxc_netdev *n = it->elem;
1415 if (n->hwaddr)
1416 new_hwaddr(n->hwaddr);
1417 }
1418}
1419
1420static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
1421{
1422 char newpath[MAXPATHLEN];
1423 char *oldpath = oldc->lxc_conf->fstab;
1424 int ret;
1425
1426 if (!oldpath)
1427 return 0;
1428
1429 char *p = rindex(oldpath, '/');
1430 if (!p)
1431 return -1;
1432 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
1433 c->config_path, c->name, p);
1434 if (ret < 0 || ret >= MAXPATHLEN) {
1435 ERROR("error printing new path for %s", oldpath);
1436 return -1;
1437 }
1438 if (file_exists(newpath)) {
1439 ERROR("error: fstab file %s exists", newpath);
1440 return -1;
1441 }
1442
1443 if (copy_file(oldpath, newpath) < 0) {
1444 ERROR("error: copying %s to %s", oldpath, newpath);
1445 return -1;
1446 }
1447 free(c->lxc_conf->fstab);
1448 c->lxc_conf->fstab = strdup(newpath);
1449 if (!c->lxc_conf->fstab) {
1450 ERROR("error: allocating pathname");
1451 return -1;
1452 }
1453
1454 return 0;
1455}
1456
1457static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
1458 const char *newtype, int flags, const char *bdevdata, unsigned long newsize)
1459{
1460 struct bdev *bdev;
1461
1462 bdev = bdev_copy(c0->lxc_conf->rootfs.path, c0->name, c->name,
1463 c0->config_path, c->config_path, newtype, !!(flags & LXC_CLONE_SNAPSHOT),
1464 bdevdata, newsize);
1465 if (!bdev) {
1466 ERROR("error copying storage");
1467 return -1;
1468 }
1469 free(c->lxc_conf->rootfs.path);
1470 c->lxc_conf->rootfs.path = strdup(bdev->src);
1471 bdev_put(bdev);
1472 if (!c->lxc_conf->rootfs.path)
1473 return -1;
1474 // here we could also update all lxc.mount.entries or even
1475 // items in the lxc.mount fstab list. As discussed on m-l,
1476 // we could do either any source paths starting with the
1477 // lxcpath/oldname, or simply anythign which is not a virtual
1478 // fs or a bind mount.
1479 return 0;
1480}
1481
148e91f5 1482static int clone_update_rootfs(struct lxc_container *c, int flags, char **hookargs)
9be53773
SH
1483{
1484 int ret = -1;
1485 char path[MAXPATHLEN];
1486 struct bdev *bdev;
1487 FILE *fout;
1488 pid_t pid;
148e91f5 1489 struct lxc_conf *conf = c->lxc_conf;
9be53773
SH
1490
1491 /* update hostname in rootfs */
1492 /* we're going to mount, so run in a clean namespace to simplify cleanup */
1493
1494 pid = fork();
1495 if (pid < 0)
1496 return -1;
1497 if (pid > 0)
1498 return wait_for_pid(pid);
1499
1500 if (unshare(CLONE_NEWNS) < 0) {
1501 ERROR("error unsharing mounts");
1502 exit(1);
1503 }
1504 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
1505 if (!bdev)
1506 exit(1);
1507 if (bdev->ops->mount(bdev) < 0)
1508 exit(1);
148e91f5
SH
1509
1510 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
1511 /* Start of environment variable setup for hooks */
1512 if (setenv("LXC_NAME", c->name, 1)) {
1513 SYSERROR("failed to set environment variable for container name");
1514 }
1515 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
1516 SYSERROR("failed to set environment variable for config path");
1517 }
1518 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
1519 SYSERROR("failed to set environment variable for rootfs mount");
1520 }
1521 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
1522 SYSERROR("failed to set environment variable for rootfs mount");
1523 }
1524
1525 if (run_lxc_hooks(c->name, "clone", conf, hookargs)) {
1526 ERROR("Error executing clone hook for %s", c->name);
1527 exit(1);
1528 }
1529 }
1530
1531 if (!(flags & LXC_CLONE_KEEPNAME)) {
1532 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
1533 if (ret < 0 || ret >= MAXPATHLEN)
1534 exit(1);
1535 if (!(fout = fopen(path, "w"))) {
1536 SYSERROR("unable to open %s: ignoring\n", path);
1537 exit(0);
1538 }
1539 if (fprintf(fout, "%s", c->name) < 0)
1540 exit(1);
1541 if (fclose(fout) < 0)
1542 exit(1);
9be53773 1543 }
9be53773
SH
1544 exit(0);
1545}
1546
1547/*
1548 * We want to support:
1549sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
1550 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
1551
1552-s [ implies overlayfs]
1553-s -B overlayfs
1554-s -B aufs
1555
1556only rootfs gets converted (copied/snapshotted) on clone.
1557*/
1558
1559static int create_file_dirname(char *path)
1560{
1561 char *p = rindex(path, '/');
1562 int ret;
1563
1564 if (!p)
1565 return -1;
1566 *p = '\0';
1567 ret = mkdir(path, 0755);
1568 if (ret && errno != EEXIST)
1569 SYSERROR("creating container path %s\n", path);
1570 *p = '/';
1571 return ret;
1572}
1573
1574struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
1575 const char *lxcpath, int flags,
148e91f5
SH
1576 const char *bdevtype, const char *bdevdata, unsigned long newsize,
1577 char **hookargs)
9be53773
SH
1578{
1579 struct lxc_container *c2 = NULL;
1580 char newpath[MAXPATHLEN];
1581 int ret;
1582 const char *n, *l;
1583 FILE *fout;
1584
1585 if (!c || !c->is_defined(c))
1586 return NULL;
1587
1588 if (lxclock(c->privlock, 0))
1589 return NULL;
1590
1591 if (c->is_running(c)) {
1592 ERROR("error: Original container (%s) is running", c->name);
1593 goto out;
1594 }
1595
1596 // Make sure the container doesn't yet exist.
1597 n = newname ? newname : c->name;
1598 l = lxcpath ? lxcpath : c->get_config_path(c);
1599 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
1600 if (ret < 0 || ret >= MAXPATHLEN) {
1601 SYSERROR("clone: failed making config pathname");
1602 goto out;
1603 }
1604 if (file_exists(newpath)) {
1605 ERROR("error: clone: %s exists", newpath);
1606 goto out;
1607 }
1608
1609 if (create_file_dirname(newpath) < 0) {
1610 ERROR("Error creating container dir for %s", newpath);
1611 goto out;
1612 }
1613
1614 // copy the configuration, tweak it as needed,
1615 fout = fopen(newpath, "w");
1616 if (!fout) {
1617 SYSERROR("open %s", newpath);
1618 goto out;
1619 }
1620 write_config(fout, c->lxc_conf);
1621 fclose(fout);
1622
1623 if (update_name_and_paths(newpath, c, n, l) < 0) {
1624 ERROR("Error updating name in cloned config");
1625 goto out;
1626 }
1627
1628 sprintf(newpath, "%s/%s/rootfs", l, n);
1629 if (mkdir(newpath, 0755) < 0) {
1630 SYSERROR("error creating %s", newpath);
1631 goto out;
1632 }
1633
1634 c2 = lxc_container_new(n, l);
375c2258 1635 if (!c2) {
9be53773
SH
1636 ERROR("clone: failed to create new container (%s %s)", n, l);
1637 goto out;
1638 }
1639
1640 // copy hooks if requested
1641 if (flags & LXC_CLONE_COPYHOOKS) {
1642 ret = copyhooks(c, c2);
1643 if (ret < 0) {
1644 ERROR("error copying hooks");
9be53773
SH
1645 goto out;
1646 }
1647 }
1648
1649 if (copy_fstab(c, c2) < 0) {
1650 ERROR("error copying fstab");
9be53773
SH
1651 goto out;
1652 }
1653
1654 // update macaddrs
1655 if (!(flags & LXC_CLONE_KEEPMACADDR))
1656 network_new_hwaddrs(c2);
1657
1658 // copy/snapshot rootfs's
1659 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
375c2258 1660 if (ret < 0)
9be53773 1661 goto out;
9be53773 1662
375c2258 1663 if (!c2->save_config(c2, NULL))
9be53773 1664 goto out;
9be53773 1665
148e91f5 1666 if (clone_update_rootfs(c2, flags, hookargs) < 0)
9be53773 1667 goto out;
9be53773
SH
1668
1669 // TODO: update c's lxc.snapshot = count
1670 lxcunlock(c->privlock);
1671 return c2;
1672
1673out:
1674 lxcunlock(c->privlock);
375c2258
SH
1675 if (c2) {
1676 c2->destroy(c2);
9be53773 1677 lxc_container_put(c2);
375c2258 1678 }
9be53773
SH
1679
1680 return NULL;
1681}
1682
afeecbba 1683struct lxc_container *lxc_container_new(const char *name, const char *configpath)
72d0e1cb
SG
1684{
1685 struct lxc_container *c;
72d0e1cb
SG
1686
1687 c = malloc(sizeof(*c));
1688 if (!c) {
1689 fprintf(stderr, "failed to malloc lxc_container\n");
1690 return NULL;
1691 }
1692 memset(c, 0, sizeof(*c));
1693
afeecbba
SH
1694 if (configpath)
1695 c->config_path = strdup(configpath);
1696 else
67e571de 1697 c->config_path = strdup(default_lxc_path());
afeecbba 1698
2a59a681
SH
1699 if (!c->config_path) {
1700 fprintf(stderr, "Out of memory");
1701 goto err;
1702 }
1703
72d0e1cb
SG
1704 c->name = malloc(strlen(name)+1);
1705 if (!c->name) {
1706 fprintf(stderr, "Error allocating lxc_container name\n");
1707 goto err;
1708 }
1709 strcpy(c->name, name);
1710
1711 c->numthreads = 1;
1712 c->slock = lxc_newlock(name);
1713 if (!c->slock) {
1714 fprintf(stderr, "failed to create lock\n");
1715 goto err;
1716 }
1717
1718 c->privlock = lxc_newlock(NULL);
1719 if (!c->privlock) {
1720 fprintf(stderr, "failed to alloc privlock\n");
1721 goto err;
1722 }
1723
afeecbba 1724 if (!set_config_filename(c)) {
72d0e1cb
SG
1725 fprintf(stderr, "Error allocating config file pathname\n");
1726 goto err;
1727 }
72d0e1cb
SG
1728
1729 if (file_exists(c->configfile))
1730 lxcapi_load_config(c, NULL);
1731
1732 // assign the member functions
1733 c->is_defined = lxcapi_is_defined;
1734 c->state = lxcapi_state;
1735 c->is_running = lxcapi_is_running;
1736 c->freeze = lxcapi_freeze;
1737 c->unfreeze = lxcapi_unfreeze;
1738 c->init_pid = lxcapi_init_pid;
1739 c->load_config = lxcapi_load_config;
1740 c->want_daemonize = lxcapi_want_daemonize;
1741 c->start = lxcapi_start;
1742 c->startl = lxcapi_startl;
1743 c->stop = lxcapi_stop;
1744 c->config_file_name = lxcapi_config_file_name;
1745 c->wait = lxcapi_wait;
1746 c->set_config_item = lxcapi_set_config_item;
1747 c->destroy = lxcapi_destroy;
1748 c->save_config = lxcapi_save_config;
1749 c->get_keys = lxcapi_get_keys;
1750 c->create = lxcapi_create;
1751 c->createl = lxcapi_createl;
1752 c->shutdown = lxcapi_shutdown;
1753 c->clear_config_item = lxcapi_clear_config_item;
1754 c->get_config_item = lxcapi_get_config_item;
794dd120
SH
1755 c->get_cgroup_item = lxcapi_get_cgroup_item;
1756 c->set_cgroup_item = lxcapi_set_cgroup_item;
2a59a681
SH
1757 c->get_config_path = lxcapi_get_config_path;
1758 c->set_config_path = lxcapi_set_config_path;
9be53773 1759 c->clone = lxcapi_clone;
9c83a661 1760 c->get_ips = lxcapi_get_ips;
72d0e1cb
SG
1761
1762 /* we'll allow the caller to update these later */
ab1bf971 1763 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
72d0e1cb
SG
1764 fprintf(stderr, "failed to open log\n");
1765 goto err;
1766 }
1767
72d0e1cb
SG
1768 return c;
1769
1770err:
1771 lxc_container_free(c);
1772 return NULL;
1773}
1774
4a7c7daa 1775int lxc_get_wait_states(const char **states)
72d0e1cb
SG
1776{
1777 int i;
1778
1779 if (states)
1780 for (i=0; i<MAX_STATE; i++)
1781 states[i] = lxc_state2str(i);
1782 return MAX_STATE;
1783}