3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include <sys/types.h>
28 #include <sys/mount.h>
34 #include <arpa/inet.h>
39 #include <sys/syscall.h>
41 #include <lxc/lxccontainer.h>
42 #include <lxc/version.h>
43 #include <lxc/network.h>
58 #include "namespace.h"
66 #include <../include/ifaddrs.h>
70 #include <../include/lxcmntent.h>
75 #define MAX_BUFFER 4096
77 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
79 /* Define faccessat() if missing from the C library */
80 #ifndef HAVE_FACCESSAT
81 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
84 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
92 lxc_log_define(lxc_container
, lxc
);
94 static bool config_file_exists(const char *lxcpath
, const char *cname
)
96 /* $lxcpath + '/' + $cname + '/config' + \0 */
97 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
98 char *fname
= alloca(len
);
100 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
101 if (ret
< 0 || ret
>= len
)
104 return file_exists(fname
);
108 * A few functions to help detect when a container creation failed.
109 * If a container creation was killed partway through, then trying
110 * to actually start that container could harm the host. We detect
111 * this by creating a 'partial' file under the container directory,
112 * and keeping an advisory lock. When container creation completes,
113 * we remove that file. When we load or try to start a container, if
114 * we find that file, without a flock, we remove the container.
116 static int ongoing_create(struct lxc_container
*c
)
118 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
119 char *path
= alloca(len
);
123 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
124 if (ret
< 0 || ret
>= len
) {
125 ERROR("Error writing partial pathname");
129 if (!file_exists(path
))
131 fd
= open(path
, O_RDWR
);
133 // give benefit of the doubt
134 SYSERROR("Error opening partial file");
138 lk
.l_whence
= SEEK_SET
;
142 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
143 // create is still ongoing
147 // create completed but partial is still there.
152 static int create_partial(struct lxc_container
*c
)
154 // $lxcpath + '/' + $name + '/partial' + \0
155 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
156 char *path
= alloca(len
);
160 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
161 if (ret
< 0 || ret
>= len
) {
162 ERROR("Error writing partial pathname");
165 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
166 SYSERROR("Erorr creating partial file");
170 lk
.l_whence
= SEEK_SET
;
173 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
174 SYSERROR("Error locking partial file %s", path
);
182 static void remove_partial(struct lxc_container
*c
, int fd
)
184 // $lxcpath + '/' + $name + '/partial' + \0
185 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
186 char *path
= alloca(len
);
190 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
191 if (ret
< 0 || ret
>= len
) {
192 ERROR("Error writing partial pathname");
195 if (unlink(path
) < 0)
196 SYSERROR("Error unlink partial file %s", path
);
200 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
201 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
202 * container configuration file.
203 * The container_disk_lock also takes the container_mem_lock.
204 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
205 * NOTHING mutexes two independent programs with their own struct
206 * lxc_container for the same c->name, between API calls. For instance,
207 * c->config_read(); c->start(); Between those calls, data on disk
208 * could change (which shouldn't bother the caller unless for instance
209 * the rootfs get moved). c->config_read(); update; c->config_write();
210 * Two such updaters could race. The callers should therefore check their
211 * results. Trying to prevent that would necessarily expose us to deadlocks
212 * due to hung callers. So I prefer to keep the locks only within our own
213 * functions, not across functions.
215 * If you're going to clone while holding a lxccontainer, increment
216 * c->numthreads (under privlock) before forking. When deleting,
217 * decrement numthreads under privlock, then if it hits 0 you can delete.
218 * Do not ever use a lxccontainer whose numthreads you did not bump.
221 static void lxc_container_free(struct lxc_container
*c
)
227 c
->configfile
= NULL
;
228 free(c
->error_string
);
229 c
->error_string
= NULL
;
231 lxc_putlock(c
->slock
);
235 lxc_putlock(c
->privlock
);
241 lxc_conf_free(c
->lxc_conf
);
244 free(c
->config_path
);
245 c
->config_path
= NULL
;
251 * Consider the following case:
252 freer | racing get()er
253 ==================================================================
254 lxc_container_put() | lxc_container_get()
255 \ lxclock(c->privlock) | c->numthreads < 1? (no)
256 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
258 \ lxc_container_free() | \ lxclock() returns
259 | \ c->numthreads < 1 -> return 0
261 \ \ sem_destroy(privlock) |
263 * When the get()er checks numthreads the first time, one of the following
265 * 1. freer has set numthreads = 0. get() returns 0
266 * 2. freer is between lxclock and setting numthreads to 0. get()er will
267 * sem_wait on privlock, get lxclock after freer() drops it, then see
268 * numthreads is 0 and exit without touching lxclock again..
269 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
270 * will see --numthreads = 1 and not call lxc_container_free().
273 int lxc_container_get(struct lxc_container
*c
)
278 // if someone else has already started freeing the container, don't
279 // try to take the lock, which may be invalid
280 if (c
->numthreads
< 1)
283 if (container_mem_lock(c
))
285 if (c
->numthreads
< 1) {
286 // bail without trying to unlock, bc the privlock is now probably
291 container_mem_unlock(c
);
295 int lxc_container_put(struct lxc_container
*c
)
299 if (container_mem_lock(c
))
301 if (--c
->numthreads
< 1) {
302 container_mem_unlock(c
);
303 lxc_container_free(c
);
306 container_mem_unlock(c
);
310 static bool lxcapi_is_defined(struct lxc_container
*c
)
319 if (container_mem_lock(c
))
323 statret
= stat(c
->configfile
, &statbuf
);
329 container_mem_unlock(c
);
333 static const char *lxcapi_state(struct lxc_container
*c
)
339 s
= lxc_getstate(c
->name
, c
->config_path
);
340 return lxc_state2str(s
);
343 static bool is_stopped(struct lxc_container
*c
)
346 s
= lxc_getstate(c
->name
, c
->config_path
);
347 return (s
== STOPPED
);
350 static bool lxcapi_is_running(struct lxc_container
*c
)
357 if (!s
|| strcmp(s
, "STOPPED") == 0)
362 static bool lxcapi_freeze(struct lxc_container
*c
)
368 ret
= lxc_freeze(c
->name
, c
->config_path
);
374 static bool lxcapi_unfreeze(struct lxc_container
*c
)
380 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
386 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
392 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
396 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
397 int stdoutfd
, int stderrfd
, int escape
)
399 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
402 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
407 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
410 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
413 c
->lxc_conf
= lxc_conf_init();
416 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
421 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
423 bool ret
= false, need_disklock
= false;
429 fname
= c
->configfile
;
435 * If we're reading something other than the container's config,
436 * we only need to lock the in-memory container. If loading the
437 * container's config file, take the disk lock.
439 if (strcmp(fname
, c
->configfile
) == 0)
440 need_disklock
= true;
443 lret
= container_disk_lock(c
);
445 lret
= container_mem_lock(c
);
449 ret
= load_config_locked(c
, fname
);
452 container_disk_unlock(c
);
454 container_mem_unlock(c
);
458 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
460 if (!c
|| !c
->lxc_conf
)
462 if (container_mem_lock(c
)) {
463 ERROR("Error getting mem lock");
466 c
->daemonize
= state
;
467 container_mem_unlock(c
);
471 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
473 if (!c
|| !c
->lxc_conf
)
475 if (container_mem_lock(c
)) {
476 ERROR("Error getting mem lock");
479 c
->lxc_conf
->close_all_fds
= state
;
480 container_mem_unlock(c
);
484 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
491 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
496 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
498 /* we'll probably want to make this timeout configurable? */
499 int timeout
= 5, ret
, status
;
502 * our child is going to fork again, then exit. reap the
505 ret
= waitpid(pid
, &status
, 0);
506 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
507 DEBUG("failed waiting for first dual-fork child");
508 return lxcapi_wait(c
, "RUNNING", timeout
);
511 static bool am_single_threaded(void)
513 struct dirent dirent
, *direntp
;
517 dir
= opendir("/proc/self/task");
519 INFO("failed to open /proc/self/task");
523 while (!readdir_r(dir
, &dirent
, &direntp
)) {
527 if (!strcmp(direntp
->d_name
, "."))
530 if (!strcmp(direntp
->d_name
, ".."))
540 * I can't decide if it'd be more convenient for callers if we accept '...',
541 * or a null-terminated array (i.e. execl vs execv)
543 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
546 struct lxc_conf
*conf
;
547 bool daemonize
= false;
549 char *default_args
[] = {
555 /* container exists */
558 /* container has been setup */
562 if ((ret
= ongoing_create(c
)) < 0) {
563 ERROR("Error checking for incomplete creation");
567 ERROR("Error: %s creation was not completed", c
->name
);
570 } else if (ret
== 1) {
571 ERROR("Error: creation of %s is ongoing", c
->name
);
575 /* is this app meant to be run through lxcinit, as in lxc-execute? */
576 if (useinit
&& !argv
)
579 if (container_mem_lock(c
))
582 daemonize
= c
->daemonize
;
583 container_mem_unlock(c
);
586 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
587 return ret
== 0 ? true : false;
591 if (conf
->init_cmd
) {
592 init_cmd
[0] = conf
->init_cmd
;
601 * say, I'm not sure - what locks do we want here? Any?
602 * Is liblxc's locking enough here to protect the on disk
603 * container? We don't want to exclude things like lxc_info
604 * while container is running...
608 lxc_monitord_spawn(c
->config_path
);
615 /* Set to NULL because we don't want father unlink
616 * the PID file, child will do the free and unlink.
619 return wait_on_daemonized_start(c
, pid
);
622 /* We don't really care if this doesn't print all the
623 * characters; all that it means is that the proctitle will be
624 * ugly. Similarly, we also don't care if setproctitle()
626 snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
627 INFO("Attempting to set proc title to %s", title
);
630 /* second fork to be reparented by init */
633 SYSERROR("Error doing dual-fork");
638 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
640 SYSERROR("Error chdir()ing to /.");
643 lxc_check_inherited(conf
, true, -1);
647 open("/dev/zero", O_RDONLY
);
648 open("/dev/null", O_RDWR
);
649 open("/dev/null", O_RDWR
);
652 if (!am_single_threaded()) {
653 ERROR("Cannot start non-daemonized container when threaded");
658 /* We need to write PID file after daeminize, so we always
659 * write the right PID.
662 pid_fp
= fopen(c
->pidfile
, "w");
663 if (pid_fp
== NULL
) {
664 SYSERROR("Failed to create pidfile '%s' for '%s'",
665 c
->pidfile
, c
->name
);
669 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
670 SYSERROR("Failed to write '%s'", c
->pidfile
);
683 if (lxc_check_inherited(conf
, daemonize
, -1)) {
684 ERROR("Inherited fds found");
689 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
693 INFO("container requested reboot");
706 exit (ret
== 0 ? true : false);
708 return (ret
== 0 ? true : false);
712 * note there MUST be an ending NULL
714 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
717 char **inargs
= NULL
;
720 /* container exists */
724 va_start(ap
, useinit
);
725 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
729 ERROR("Memory allocation error.");
733 /* pass NULL if no arguments were supplied */
734 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
739 for (arg
= inargs
; *arg
; arg
++)
747 static bool lxcapi_stop(struct lxc_container
*c
)
754 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
759 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
761 int ret
= -1, lasterr
;
762 char *p
= alloca(strlen(path
)+1);
763 mode_t mask
= umask(0002);
764 ret
= mkdir(path
, 0770);
772 SYSERROR("failed to create container path %s", path
);
777 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
778 ERROR("Failed to chown container dir");
785 * create the standard expected container dir
787 static bool create_container_dir(struct lxc_container
*c
)
792 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
796 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
797 if (ret
< 0 || ret
>= len
) {
801 ret
= do_create_container_dir(s
, c
->lxc_conf
);
806 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
807 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
810 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
811 * it returns a mounted bdev on success, NULL on error.
813 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
814 struct bdev_specs
*specs
)
821 /* rootfs.path or lxcpath/lxcname/rootfs */
822 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
823 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
824 len
= strlen(rpath
) + 1;
826 ret
= snprintf(dest
, len
, "%s", rpath
);
828 const char *lxcpath
= lxcapi_get_config_path(c
);
829 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
831 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
833 if (ret
< 0 || ret
>= len
)
836 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
838 ERROR("Failed to create backing store type %s", type
);
842 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
844 /* if we are not root, chown the rootfs dir to root in the
847 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
848 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
849 ERROR("Error chowning %s to container root", bdev
->dest
);
850 suggest_default_idmap();
859 static char *lxcbasename(char *path
)
861 char *p
= path
+ strlen(path
) - 1;
862 while (*p
!= '/' && p
> path
)
867 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
877 SYSERROR("failed to fork task for container creation template");
881 if (pid
== 0) { // child
882 char *patharg
, *namearg
, *rootfsarg
, *src
;
883 struct bdev
*bdev
= NULL
;
885 int ret
, len
, nargs
= 0;
887 struct lxc_conf
*conf
= c
->lxc_conf
;
893 open("/dev/zero", O_RDONLY
);
894 open("/dev/null", O_RDWR
);
895 open("/dev/null", O_RDWR
);
898 src
= c
->lxc_conf
->rootfs
.path
;
900 * for an overlay create, what the user wants is the template to fill
901 * in what will become the readonly lower layer. So don't mount for
904 if (strncmp(src
, "overlayfs:", 10) == 0)
905 src
= overlay_getlower(src
+10);
906 if (strncmp(src
, "aufs:", 5) == 0)
907 src
= overlay_getlower(src
+5);
909 bdev
= bdev_init(c
->lxc_conf
, src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
911 ERROR("Error opening rootfs");
915 if (geteuid() == 0) {
916 if (unshare(CLONE_NEWNS
) < 0) {
917 ERROR("error unsharing mounts");
920 if (detect_shared_rootfs()) {
921 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
922 SYSERROR("Failed to make / rslave to run template");
923 ERROR("Continuing...");
927 if (strcmp(bdev
->type
, "dir") && strcmp(bdev
->type
, "btrfs")) {
928 if (geteuid() != 0) {
929 ERROR("non-root users can only create btrfs and directory-backed containers");
932 if (bdev
->ops
->mount(bdev
) < 0) {
933 ERROR("Error mounting rootfs");
936 } else { // TODO come up with a better way here!
938 bdev
->dest
= strdup(bdev
->src
);
942 * create our new array, pre-pend the template name and
946 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
947 nargs
+= 4; // template, path, rootfs and name args
949 newargv
= malloc(nargs
* sizeof(*newargv
));
952 newargv
[0] = lxcbasename(tpath
);
954 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
955 patharg
= malloc(len
);
958 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
959 if (ret
< 0 || ret
>= len
)
961 newargv
[1] = patharg
;
962 len
= strlen("--name=") + strlen(c
->name
) + 1;
963 namearg
= malloc(len
);
966 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
967 if (ret
< 0 || ret
>= len
)
969 newargv
[2] = namearg
;
971 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
972 rootfsarg
= malloc(len
);
975 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
976 if (ret
< 0 || ret
>= len
)
978 newargv
[3] = rootfsarg
;
980 /* add passed-in args */
982 for (i
= 4; i
< nargs
; i
++)
983 newargv
[i
] = argv
[i
-4];
985 /* add trailing NULL */
987 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
990 newargv
[nargs
- 1] = NULL
;
993 * If we're running the template in a mapped userns, then
994 * we prepend the template command with:
995 * lxc-usernsexec <-m map1> ... <-m mapn> --
996 * and we append "--mapped-uid x", where x is the mapped uid
999 if (!lxc_list_empty(&conf
->id_map
)) {
1003 char **n2
= malloc(n2args
* sizeof(*n2
));
1004 struct lxc_list
*it
;
1008 SYSERROR("out of memory");
1012 tpath
= "lxc-usernsexec";
1013 n2
[0] = "lxc-usernsexec";
1014 lxc_list_for_each(it
, &conf
->id_map
) {
1017 n2
= realloc(n2
, n2args
* sizeof(char *));
1020 n2
[n2args
-2] = "-m";
1021 n2
[n2args
-1] = malloc(200);
1024 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1025 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1026 map
->nsid
, map
->hostid
, map
->range
);
1027 if (ret
< 0 || ret
>= 200)
1030 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1031 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1032 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1035 if (hostid_mapped
< 0) {
1036 hostid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_UID
);
1037 n2
[n2args
++] = "-m";
1038 if (hostid_mapped
< 0) {
1039 ERROR("Could not find free uid to map");
1042 n2
[n2args
++] = malloc(200);
1043 if (!n2
[n2args
-1]) {
1044 SYSERROR("out of memory");
1047 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1048 hostid_mapped
, geteuid());
1049 if (ret
< 0 || ret
>= 200) {
1050 ERROR("string too long");
1054 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1055 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1056 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1059 if (hostgid_mapped
< 0) {
1060 hostgid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_GID
);
1061 n2
[n2args
++] = "-m";
1062 if (hostgid_mapped
< 0) {
1063 ERROR("Could not find free uid to map");
1066 n2
[n2args
++] = malloc(200);
1067 if (!n2
[n2args
-1]) {
1068 SYSERROR("out of memory");
1071 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1072 hostgid_mapped
, getegid());
1073 if (ret
< 0 || ret
>= 200) {
1074 ERROR("string too long");
1078 n2
[n2args
++] = "--";
1079 for (i
= 0; i
< nargs
; i
++)
1080 n2
[i
+ n2args
] = newargv
[i
];
1082 // Finally add "--mapped-uid $uid" to tell template what to chown
1085 n2
= realloc(n2
, n2args
* sizeof(char *));
1087 SYSERROR("out of memory");
1090 // note n2[n2args-1] is NULL
1091 n2
[n2args
-5] = "--mapped-uid";
1092 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1093 n2
[n2args
-4] = txtuid
;
1094 n2
[n2args
-3] = "--mapped-gid";
1095 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1096 n2
[n2args
-2] = txtgid
;
1097 n2
[n2args
-1] = NULL
;
1102 execvp(tpath
, newargv
);
1103 SYSERROR("failed to execute template %s", tpath
);
1107 if (wait_for_pid(pid
) != 0) {
1108 ERROR("container creation template for %s failed", c
->name
);
1115 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1123 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1127 f
= fopen(path
, "r");
1131 if (fseek(f
, 0, SEEK_END
) < 0)
1133 if ((flen
= ftell(f
)) < 0)
1135 if (fseek(f
, 0, SEEK_SET
) < 0)
1137 if ((contents
= malloc(flen
+ 1)) == NULL
)
1139 if (fread(contents
, 1, flen
, f
) != flen
)
1140 goto out_free_contents
;
1142 contents
[flen
] = '\0';
1146 goto out_free_contents
;
1149 tpath
= get_template_path(t
);
1151 ERROR("bad template: %s", t
);
1152 goto out_free_contents
;
1155 ret
= sha1sum_file(tpath
, md_value
);
1157 ERROR("Error getting sha1sum of %s", tpath
);
1159 goto out_free_contents
;
1164 f
= fopen(path
, "w");
1166 SYSERROR("reopening config for writing");
1170 fprintf(f
, "# Template used to create this container: %s\n", t
);
1172 fprintf(f
, "# Parameters passed to the template:");
1174 fprintf(f
, " %s", *argv
);
1180 fprintf(f
, "# Template script checksum (SHA-1): ");
1181 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1182 fprintf(f
, "%02x", md_value
[i
]);
1185 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1186 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1187 SYSERROR("Writing original contents");
1203 SYSERROR("Error prepending header");
1209 static void lxcapi_clear_config(struct lxc_container
*c
)
1213 lxc_conf_free(c
->lxc_conf
);
1219 static bool lxcapi_destroy(struct lxc_container
*c
);
1220 static bool container_destroy(struct lxc_container
*c
);
1221 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
1224 * create a container with the given parameters.
1225 * @c: container to be created. It has the lxcpath, name, and a starting
1226 * configuration already set
1227 * @t: the template to execute to instantiate the root filesystem and
1228 * adjust the configuration.
1229 * @bdevtype: backing store type to use. If NULL, dir will be used.
1230 * @specs: additional parameters for the backing store, i.e. LVM vg to
1233 * @argv: the arguments to pass to the template, terminated by NULL. If no
1234 * arguments, you can just pass NULL.
1236 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1237 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1249 tpath
= get_template_path(t
);
1251 ERROR("bad template: %s", t
);
1257 * If a template is passed in, and the rootfs already is defined in
1258 * the container config and exists, then * caller is trying to create
1259 * an existing container. Return an error, but do NOT delete the
1262 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1263 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1264 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1269 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1270 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1275 if (!create_container_dir(c
))
1279 * either template or rootfs.path should be set.
1280 * if both template and rootfs.path are set, template is setup as rootfs.path.
1281 * container is already created if we have a config and rootfs.path is accessible
1283 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1284 /* no template passed in and rootfs does not exist: error */
1286 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1287 /* rootfs passed into configuration, but does not exist: error */
1289 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1290 /* Rootfs already existed, user just wanted to save the
1291 * loaded configuration */
1296 /* Mark that this container is being created */
1297 if ((partial_fd
= create_partial(c
)) < 0)
1300 /* no need to get disk lock bc we have the partial locked */
1303 * Create the backing store
1304 * Note we can't do this in the same task as we use to execute the
1305 * template because of the way zfs works.
1306 * After you 'zfs create', zfs mounts the fs only in the initial
1311 SYSERROR("failed to fork task for container creation template");
1315 if (pid
== 0) { // child
1316 struct bdev
*bdev
= NULL
;
1318 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1319 ERROR("Error creating backing store type %s for %s",
1320 bdevtype
? bdevtype
: "(none)", c
->name
);
1324 /* save config file again to store the new rootfs location */
1325 if (!c
->save_config(c
, NULL
)) {
1326 ERROR("failed to save starting configuration for %s", c
->name
);
1327 // parent task won't see bdev in config so we delete it
1328 bdev
->ops
->umount(bdev
);
1329 bdev
->ops
->destroy(bdev
);
1334 if (wait_for_pid(pid
) != 0)
1337 /* reload config to get the rootfs */
1338 lxc_conf_free(c
->lxc_conf
);
1340 if (!load_config_locked(c
, c
->configfile
))
1343 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1346 // now clear out the lxc_conf we have, reload from the created
1348 lxcapi_clear_config(c
);
1351 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1352 ERROR("Error prepending header to configuration file");
1356 ret
= load_config_locked(c
, c
->configfile
);
1359 if (partial_fd
>= 0)
1360 remove_partial(c
, partial_fd
);
1363 container_destroy(c
);
1369 static bool lxcapi_reboot(struct lxc_container
*c
)
1372 int rebootsignal
= SIGINT
;
1376 if (!c
->is_running(c
))
1378 pid
= c
->init_pid(c
);
1381 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1382 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1383 if (kill(pid
, rebootsignal
) < 0)
1389 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1393 int haltsignal
= SIGPWR
;
1398 if (!c
->is_running(c
))
1400 pid
= c
->init_pid(c
);
1403 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1404 haltsignal
= c
->lxc_conf
->haltsignal
;
1405 kill(pid
, haltsignal
);
1406 retv
= c
->wait(c
, "STOPPED", timeout
);
1410 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1411 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1421 * since we're going to wait for create to finish, I don't think we
1422 * need to get a copy of the arguments.
1424 va_start(ap
, flags
);
1425 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1428 ERROR("Memory allocation error.");
1432 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1439 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
1441 if (strcmp(key
, "lxc.cgroup") == 0)
1442 clear_unexp_config_line(conf
, key
, true);
1443 else if (strcmp(key
, "lxc.network") == 0)
1444 clear_unexp_config_line(conf
, key
, true);
1445 else if (strcmp(key
, "lxc.hook") == 0)
1446 clear_unexp_config_line(conf
, key
, true);
1448 clear_unexp_config_line(conf
, key
, false);
1449 if (!do_append_unexp_config_line(conf
, key
, ""))
1450 WARN("Error clearing configuration for %s", key
);
1453 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1457 if (!c
|| !c
->lxc_conf
)
1459 if (container_mem_lock(c
))
1461 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1463 do_clear_unexp_config_line(c
->lxc_conf
, key
);
1464 container_mem_unlock(c
);
1468 static inline bool enter_net_ns(struct lxc_container
*c
)
1470 pid_t pid
= c
->init_pid(c
);
1472 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1473 if (!switch_to_ns(pid
, "user"))
1476 return switch_to_ns(pid
, "net");
1479 // used by qsort and bsearch functions for comparing names
1480 static inline int string_cmp(char **first
, char **second
)
1482 return strcmp(*first
, *second
);
1485 // used by qsort and bsearch functions for comparing container names
1486 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1488 return strcmp((*first
)->name
, (*second
)->name
);
1491 static bool add_to_array(char ***names
, char *cname
, int pos
)
1493 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1495 ERROR("Out of memory");
1500 newnames
[pos
] = strdup(cname
);
1504 // sort the arrray as we will use binary search on it
1505 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1510 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1512 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1514 ERROR("Out of memory");
1521 // sort the arrray as we will use binary search on it
1523 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1528 static char** get_from_array(char ***names
, char *cname
, int size
)
1530 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1534 static bool array_contains(char ***names
, char *cname
, int size
) {
1535 if(get_from_array(names
, cname
, size
) != NULL
)
1540 static bool remove_from_array(char ***names
, char *cname
, int size
)
1542 char **result
= get_from_array(names
, cname
, size
);
1543 if (result
!= NULL
) {
1550 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1553 int i
, count
= 0, pipefd
[2];
1554 char **interfaces
= NULL
;
1555 char interface
[IFNAMSIZ
];
1557 if(pipe(pipefd
) < 0) {
1558 SYSERROR("pipe failed");
1564 SYSERROR("failed to fork task to get interfaces information");
1570 if (pid
== 0) { // child
1571 int ret
= 1, nbytes
;
1572 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1574 /* close the read-end of the pipe */
1577 if (!enter_net_ns(c
)) {
1578 SYSERROR("failed to enter namespace");
1582 /* Grab the list of interfaces */
1583 if (getifaddrs(&interfaceArray
)) {
1584 SYSERROR("failed to get interfaces list");
1588 /* Iterate through the interfaces */
1589 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1590 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1592 ERROR("write failed");
1601 freeifaddrs(interfaceArray
);
1603 /* close the write-end of the pipe, thus sending EOF to the reader */
1608 /* close the write-end of the pipe */
1611 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1612 if (array_contains(&interfaces
, interface
, count
))
1615 if(!add_to_array(&interfaces
, interface
, count
))
1616 ERROR("PARENT: add_to_array failed");
1620 if (wait_for_pid(pid
) != 0) {
1621 for(i
=0;i
<count
;i
++)
1622 free(interfaces
[i
]);
1627 /* close the read-end of the pipe */
1630 /* Append NULL to the array */
1632 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1637 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1640 int i
, count
= 0, pipefd
[2];
1641 char **addresses
= NULL
;
1642 char address
[INET6_ADDRSTRLEN
];
1644 if(pipe(pipefd
) < 0) {
1645 SYSERROR("pipe failed");
1651 SYSERROR("failed to fork task to get container ips");
1657 if (pid
== 0) { // child
1658 int ret
= 1, nbytes
;
1659 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1660 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1661 void *tempAddrPtr
= NULL
;
1662 char *address
= NULL
;
1664 /* close the read-end of the pipe */
1667 if (!enter_net_ns(c
)) {
1668 SYSERROR("failed to enter namespace");
1672 /* Grab the list of interfaces */
1673 if (getifaddrs(&interfaceArray
)) {
1674 SYSERROR("failed to get interfaces list");
1678 /* Iterate through the interfaces */
1679 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1680 if (tempIfAddr
->ifa_addr
== NULL
)
1683 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1684 if (family
&& strcmp(family
, "inet"))
1686 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1689 if (family
&& strcmp(family
, "inet6"))
1692 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1695 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1698 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1700 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1703 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1705 addressOutputBuffer
,
1706 sizeof(addressOutputBuffer
));
1710 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1712 ERROR("write failed");
1721 freeifaddrs(interfaceArray
);
1723 /* close the write-end of the pipe, thus sending EOF to the reader */
1728 /* close the write-end of the pipe */
1731 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1732 if(!add_to_array(&addresses
, address
, count
))
1733 ERROR("PARENT: add_to_array failed");
1737 if (wait_for_pid(pid
) != 0) {
1738 for(i
=0;i
<count
;i
++)
1744 /* close the read-end of the pipe */
1747 /* Append NULL to the array */
1749 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1754 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1758 if (!c
|| !c
->lxc_conf
)
1760 if (container_mem_lock(c
))
1762 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1763 container_mem_unlock(c
);
1767 static char* lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
1771 if (!c
|| !c
->lxc_conf
)
1773 if (container_mem_lock(c
))
1775 ret
= lxc_cmd_get_config_item(c
->name
, key
, c
->get_config_path(c
));
1776 container_mem_unlock(c
);
1780 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1783 return lxc_listconfigs(retv
, inlen
);
1785 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1786 * This is an intelligent result to show which keys are valid given
1787 * the type of nic it is
1789 if (!c
|| !c
->lxc_conf
)
1791 if (container_mem_lock(c
))
1794 if (strncmp(key
, "lxc.network.", 12) == 0)
1795 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1796 container_mem_unlock(c
);
1800 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1803 bool ret
= false, need_disklock
= false;
1807 alt_file
= c
->configfile
;
1809 return false; // should we write to stdout if no file is specified?
1811 // If we haven't yet loaded a config, load the stock config
1813 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1814 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
1819 if (!create_container_dir(c
))
1823 * If we're writing to the container's config file, take the
1824 * disk lock. Otherwise just take the memlock to protect the
1825 * struct lxc_container while we're traversing it.
1827 if (strcmp(c
->configfile
, alt_file
) == 0)
1828 need_disklock
= true;
1831 lret
= container_disk_lock(c
);
1833 lret
= container_mem_lock(c
);
1838 fout
= fopen(alt_file
, "w");
1841 write_config(fout
, c
->lxc_conf
);
1847 container_disk_unlock(c
);
1849 container_mem_unlock(c
);
1853 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1855 char path
[MAXPATHLEN
];
1860 if (container_disk_lock(c
))
1862 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1864 if (ret
< 0 || ret
> MAXPATHLEN
)
1866 f
= fopen(path
, "r");
1868 ret
= fscanf(f
, "%d", &v
);
1871 ERROR("Corrupted file %s", path
);
1876 f
= fopen(path
, "w");
1879 if (fprintf(f
, "%d\n", v
) < 0) {
1880 ERROR("Error writing new snapshots value");
1886 SYSERROR("Error writing to or closing snapshots file");
1893 container_disk_unlock(c
);
1897 static void strip_newline(char *p
)
1899 size_t len
= strlen(p
);
1902 if (p
[len
-1] == '\n')
1906 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1908 struct lxc_container
*p
;
1909 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1910 size_t pathlen
= 0, namelen
= 0;
1914 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1915 c
->config_path
, c
->name
);
1916 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1917 ERROR("Path name too long");
1920 f
= fopen(path
, "r");
1923 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1924 if (getline(&lxcname
, &namelen
, f
) == -1) {
1925 ERROR("badly formatted file %s", path
);
1928 strip_newline(lxcpath
);
1929 strip_newline(lxcname
);
1930 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1931 ERROR("Unable to find dependent container %s:%s",
1935 if (!mod_rdep(p
, inc
))
1936 ERROR("Failed to increase numsnapshots for %s:%s",
1938 lxc_container_put(p
);
1946 static bool has_fs_snapshots(struct lxc_container
*c
)
1948 char path
[MAXPATHLEN
];
1953 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1955 if (ret
< 0 || ret
> MAXPATHLEN
)
1957 f
= fopen(path
, "r");
1960 ret
= fscanf(f
, "%d", &v
);
1970 static bool has_snapshots(struct lxc_container
*c
)
1972 char path
[MAXPATHLEN
];
1973 struct dirent dirent
, *direntp
;
1977 if (!get_snappath_dir(c
, path
))
1979 dir
= opendir(path
);
1982 while (!readdir_r(dir
, &dirent
, &direntp
)) {
1986 if (!strcmp(direntp
->d_name
, "."))
1989 if (!strcmp(direntp
->d_name
, ".."))
1998 static int lxc_rmdir_onedev_wrapper(void *data
)
2000 char *arg
= (char *) data
;
2001 return lxc_rmdir_onedev(arg
, "snaps");
2004 static int do_bdev_destroy(struct lxc_conf
*conf
)
2009 r
= bdev_init(conf
, conf
->rootfs
.path
, conf
->rootfs
.mount
, NULL
);
2013 if (r
->ops
->destroy(r
) < 0)
2019 static int bdev_destroy_wrapper(void *data
)
2021 struct lxc_conf
*conf
= data
;
2023 if (setgid(0) < 0) {
2024 ERROR("Failed to setgid to 0");
2027 if (setgroups(0, NULL
) < 0)
2028 WARN("Failed to clear groups");
2029 if (setuid(0) < 0) {
2030 ERROR("Failed to setuid to 0");
2033 return do_bdev_destroy(conf
);
2036 static bool container_destroy(struct lxc_container
*c
)
2041 if (!c
|| !lxcapi_is_defined(c
))
2044 if (container_disk_lock(c
))
2047 if (!is_stopped(c
)) {
2048 // we should queue some sort of error - in c->error_string?
2049 ERROR("container %s is not stopped", c
->name
);
2053 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
2055 ret
= userns_exec_1(c
->lxc_conf
, bdev_destroy_wrapper
, c
->lxc_conf
);
2057 ret
= do_bdev_destroy(c
->lxc_conf
);
2059 ERROR("Error destroying rootfs for %s", c
->name
);
2064 mod_all_rdeps(c
, false);
2066 const char *p1
= lxcapi_get_config_path(c
);
2067 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2068 sprintf(path
, "%s/%s", p1
, c
->name
);
2070 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
2072 ret
= lxc_rmdir_onedev(path
, "snaps");
2074 ERROR("Error destroying container directory for %s", c
->name
);
2080 container_disk_unlock(c
);
2084 static bool lxcapi_destroy(struct lxc_container
*c
)
2086 if (!c
|| !lxcapi_is_defined(c
))
2088 if (has_snapshots(c
)) {
2089 ERROR("Container %s has snapshots; not removing", c
->name
);
2093 if (has_fs_snapshots(c
)) {
2094 ERROR("container %s has snapshots on its rootfs", c
->name
);
2098 return container_destroy(c
);
2101 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
2103 static bool lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2105 if (!c
|| !lxcapi_is_defined(c
))
2107 if (!lxcapi_snapshot_destroy_all(c
)) {
2108 ERROR("Error deleting all snapshots");
2111 return lxcapi_destroy(c
);
2114 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2116 struct lxc_config_t
*config
;
2119 c
->lxc_conf
= lxc_conf_init();
2122 config
= lxc_getconfig(key
);
2125 if (config
->cb(key
, v
, c
->lxc_conf
) != 0)
2127 return do_append_unexp_config_line(c
->lxc_conf
, key
, v
);
2130 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2137 if (container_mem_lock(c
))
2140 b
= set_config_item_locked(c
, key
, v
);
2142 container_mem_unlock(c
);
2146 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2148 if (!c
|| !c
->configfile
)
2150 return strdup(c
->configfile
);
2153 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2155 if (!c
|| !c
->config_path
)
2157 return (const char *)(c
->config_path
);
2162 * Just recalculate the c->configfile based on the
2163 * c->config_path, which must be set.
2164 * The lxc_container must be locked or not yet public.
2166 static bool set_config_filename(struct lxc_container
*c
)
2171 if (!c
->config_path
)
2174 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2175 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2176 newpath
= malloc(len
);
2180 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2181 if (ret
< 0 || ret
>= len
) {
2182 fprintf(stderr
, "Error printing out config file name\n");
2187 free(c
->configfile
);
2188 c
->configfile
= newpath
;
2193 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2197 char *oldpath
= NULL
;
2202 if (container_mem_lock(c
))
2207 ERROR("Out of memory setting new lxc path");
2213 oldpath
= c
->config_path
;
2216 /* Since we've changed the config path, we have to change the
2217 * config file name too */
2218 if (!set_config_filename(c
)) {
2219 ERROR("Out of memory setting new config filename");
2221 free(c
->config_path
);
2222 c
->config_path
= oldpath
;
2227 container_mem_unlock(c
);
2232 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2242 if (container_disk_lock(c
))
2245 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2247 container_disk_unlock(c
);
2251 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2261 if (container_disk_lock(c
))
2264 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2266 container_disk_unlock(c
);
2270 const char *lxc_get_global_config_item(const char *key
)
2272 return lxc_global_config_value(key
);
2275 const char *lxc_get_version(void)
2280 static int copy_file(const char *old
, const char *new)
2287 if (file_exists(new)) {
2288 ERROR("copy destination %s exists", new);
2291 ret
= stat(old
, &sbuf
);
2293 INFO("Error stat'ing %s", old
);
2297 in
= open(old
, O_RDONLY
);
2299 SYSERROR("Error opening original file %s", old
);
2302 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2304 SYSERROR("Error opening new file %s", new);
2310 len
= read(in
, buf
, 8096);
2312 SYSERROR("Error reading old file %s", old
);
2317 ret
= write(out
, buf
, len
);
2318 if (ret
< len
) { // should we retry?
2319 SYSERROR("Error: write to new file %s was interrupted", new);
2326 // we set mode, but not owner/group
2327 ret
= chmod(new, sbuf
.st_mode
);
2329 SYSERROR("Error setting mode on %s", new);
2341 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2344 struct lxc_list
*it
;
2347 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2348 cpath
= alloca(len
);
2349 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2350 if (ret
< 0 || ret
>= len
)
2353 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2354 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2355 char *hookname
= it
->elem
;
2356 char *fname
= strrchr(hookname
, '/');
2357 char tmppath
[MAXPATHLEN
];
2358 if (!fname
) // relative path - we don't support, but maybe we should
2360 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2361 // this hook is public - ignore
2364 // copy the script, and change the entry in confile
2365 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2366 c
->config_path
, c
->name
, fname
+1);
2367 if (ret
< 0 || ret
>= MAXPATHLEN
)
2369 ret
= copy_file(it
->elem
, tmppath
);
2373 it
->elem
= strdup(tmppath
);
2375 ERROR("out of memory copying hook path");
2381 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
2382 c
->config_path
, oldc
->name
, c
->name
)) {
2383 ERROR("Error saving new hooks in clone");
2386 c
->save_config(c
, NULL
);
2391 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2393 char newpath
[MAXPATHLEN
];
2394 char *oldpath
= oldc
->lxc_conf
->fstab
;
2400 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount", false);
2402 char *p
= strrchr(oldpath
, '/');
2405 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2406 c
->config_path
, c
->name
, p
);
2407 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2408 ERROR("error printing new path for %s", oldpath
);
2411 if (file_exists(newpath
)) {
2412 ERROR("error: fstab file %s exists", newpath
);
2416 if (copy_file(oldpath
, newpath
) < 0) {
2417 ERROR("error: copying %s to %s", oldpath
, newpath
);
2420 free(c
->lxc_conf
->fstab
);
2421 c
->lxc_conf
->fstab
= strdup(newpath
);
2422 if (!c
->lxc_conf
->fstab
) {
2423 ERROR("error: allocating pathname");
2426 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount", newpath
)) {
2427 ERROR("error saving new lxctab");
2434 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2436 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2439 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2441 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2442 WARN("Error copying reverse dependencies");
2445 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2447 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2448 WARN("Error copying reverse dependencies");
2451 if (copy_file(path0
, path1
) < 0) {
2452 INFO("Error copying reverse dependencies");
2457 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2460 char path
[MAXPATHLEN
];
2464 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2466 if (ret
< 0 || ret
>= MAXPATHLEN
)
2468 f
= fopen(path
, "a");
2472 // if anything goes wrong, just return an error
2473 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2480 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2481 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2486 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
2487 bdevdata
, newsize
, &need_rdep
);
2489 ERROR("Error copying storage");
2492 free(c
->lxc_conf
->rootfs
.path
);
2493 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2495 if (!c
->lxc_conf
->rootfs
.path
) {
2496 ERROR("Out of memory while setting storage path");
2499 // We will simply append a new lxc.rootfs entry to the unexpanded config
2500 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
2501 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", c
->lxc_conf
->rootfs
.path
)) {
2502 ERROR("Error saving new rootfs to cloend config");
2505 if (flags
& LXC_CLONE_SNAPSHOT
)
2506 copy_rdepends(c
, c0
);
2508 if (!add_rdepends(c
, c0
))
2509 WARN("Error adding reverse dependency from %s to %s",
2513 mod_all_rdeps(c
, true);
2518 struct clone_update_data
{
2519 struct lxc_container
*c0
;
2520 struct lxc_container
*c1
;
2525 static int clone_update_rootfs(struct clone_update_data
*data
)
2527 struct lxc_container
*c0
= data
->c0
;
2528 struct lxc_container
*c
= data
->c1
;
2529 int flags
= data
->flags
;
2530 char **hookargs
= data
->hookargs
;
2532 char path
[MAXPATHLEN
];
2535 struct lxc_conf
*conf
= c
->lxc_conf
;
2537 /* update hostname in rootfs */
2538 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2540 if (setgid(0) < 0) {
2541 ERROR("Failed to setgid to 0");
2544 if (setuid(0) < 0) {
2545 ERROR("Failed to setuid to 0");
2548 if (setgroups(0, NULL
) < 0)
2549 WARN("Failed to clear groups");
2551 if (unshare(CLONE_NEWNS
) < 0)
2553 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2556 if (strcmp(bdev
->type
, "dir") != 0) {
2557 if (unshare(CLONE_NEWNS
) < 0) {
2558 ERROR("error unsharing mounts");
2562 if (detect_shared_rootfs()) {
2563 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2564 SYSERROR("Failed to make / rslave");
2565 ERROR("Continuing...");
2568 if (bdev
->ops
->mount(bdev
) < 0) {
2572 } else { // TODO come up with a better way
2574 bdev
->dest
= strdup(bdev
->src
);
2577 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2578 /* Start of environment variable setup for hooks */
2579 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2580 SYSERROR("failed to set environment variable for source container name");
2582 if (setenv("LXC_NAME", c
->name
, 1)) {
2583 SYSERROR("failed to set environment variable for container name");
2585 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2586 SYSERROR("failed to set environment variable for config path");
2588 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2589 SYSERROR("failed to set environment variable for rootfs mount");
2591 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2592 SYSERROR("failed to set environment variable for rootfs mount");
2595 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2596 ERROR("Error executing clone hook for %s", c
->name
);
2602 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2603 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2606 if (ret
< 0 || ret
>= MAXPATHLEN
)
2608 if (!file_exists(path
))
2610 if (!(fout
= fopen(path
, "w"))) {
2611 SYSERROR("unable to open %s: ignoring", path
);
2614 if (fprintf(fout
, "%s", c
->name
) < 0) {
2618 if (fclose(fout
) < 0)
2627 static int clone_update_rootfs_wrapper(void *data
)
2629 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
2630 return clone_update_rootfs(arg
);
2634 * We want to support:
2635 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2636 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2638 -s [ implies overlayfs]
2642 only rootfs gets converted (copied/snapshotted) on clone.
2645 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
2647 char *p
= strrchr(path
, '/');
2653 ret
= do_create_container_dir(path
, conf
);
2658 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2659 const char *lxcpath
, int flags
,
2660 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2663 struct lxc_container
*c2
= NULL
;
2664 char newpath
[MAXPATHLEN
];
2665 int ret
, storage_copied
= 0;
2666 char *origroot
= NULL
;
2667 struct clone_update_data data
;
2671 if (!c
|| !c
->is_defined(c
))
2674 if (container_mem_lock(c
))
2677 if (!is_stopped(c
)) {
2678 ERROR("error: Original container (%s) is running", c
->name
);
2682 // Make sure the container doesn't yet exist.
2686 lxcpath
= c
->get_config_path(c
);
2687 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
2688 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2689 SYSERROR("clone: failed making config pathname");
2692 if (file_exists(newpath
)) {
2693 ERROR("error: clone: %s exists", newpath
);
2697 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
2698 if (ret
< 0 && errno
!= EEXIST
) {
2699 ERROR("Error creating container dir for %s", newpath
);
2703 // copy the configuration, tweak it as needed,
2704 if (c
->lxc_conf
->rootfs
.path
) {
2705 origroot
= c
->lxc_conf
->rootfs
.path
;
2706 c
->lxc_conf
->rootfs
.path
= NULL
;
2708 fout
= fopen(newpath
, "w");
2710 SYSERROR("open %s", newpath
);
2713 write_config(fout
, c
->lxc_conf
);
2715 c
->lxc_conf
->rootfs
.path
= origroot
;
2717 sprintf(newpath
, "%s/%s/rootfs", lxcpath
, newname
);
2718 if (mkdir(newpath
, 0755) < 0) {
2719 SYSERROR("error creating %s", newpath
);
2724 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
2725 ERROR("Error chowning %s to container root", newpath
);
2730 c2
= lxc_container_new(newname
, lxcpath
);
2732 ERROR("clone: failed to create new container (%s %s)", newname
,
2737 // copy/snapshot rootfs's
2738 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2742 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
2745 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2746 ERROR("Error setting new hostname");
2751 ret
= copyhooks(c
, c2
);
2753 ERROR("error copying hooks");
2757 if (copy_fstab(c
, c2
) < 0) {
2758 ERROR("error copying fstab");
2763 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
2764 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
2765 ERROR("Error updating mac addresses");
2770 // We've now successfully created c2's storage, so clear it out if we
2774 if (!c2
->save_config(c2
, NULL
))
2777 if ((pid
= fork()) < 0) {
2782 ret
= wait_for_pid(pid
);
2785 container_mem_unlock(c
);
2791 data
.hookargs
= hookargs
;
2793 ret
= userns_exec_1(c
->lxc_conf
, clone_update_rootfs_wrapper
,
2796 ret
= clone_update_rootfs(&data
);
2800 container_mem_unlock(c
);
2804 container_mem_unlock(c
);
2806 if (!storage_copied
)
2807 c2
->lxc_conf
->rootfs
.path
= NULL
;
2809 lxc_container_put(c2
);
2815 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2818 struct lxc_container
*newc
;
2820 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
2823 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
2824 ERROR("Renaming a container with snapshots is not supported");
2827 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2829 ERROR("Failed to find original backing store type");
2833 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2836 lxc_container_put(newc
);
2840 if (newc
&& lxcapi_is_defined(newc
))
2841 lxc_container_put(newc
);
2843 if (!container_destroy(c
)) {
2844 ERROR("Could not destroy existing container %s", c
->name
);
2850 static int lxcapi_attach(struct lxc_container
*c
, lxc_attach_exec_t exec_function
, void *exec_payload
, lxc_attach_options_t
*options
, pid_t
*attached_process
)
2855 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2858 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2860 lxc_attach_command_t command
;
2867 command
.program
= (char*)program
;
2868 command
.argv
= (char**)argv
;
2869 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2874 return lxc_wait_for_pid_status(pid
);
2877 static int get_next_index(const char *lxcpath
, char *cname
)
2883 fname
= alloca(strlen(lxcpath
) + 20);
2885 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2886 ret
= stat(fname
, &sb
);
2893 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
2897 * If the old style snapshot path exists, use it
2898 * /var/lib/lxc -> /var/lib/lxcsnaps
2900 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
2901 if (ret
< 0 || ret
>= MAXPATHLEN
)
2903 if (dir_exists(snappath
)) {
2904 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2905 if (ret
< 0 || ret
>= MAXPATHLEN
)
2911 * Use the new style path
2912 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
2914 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
2915 if (ret
< 0 || ret
>= MAXPATHLEN
)
2920 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2923 struct lxc_container
*c2
;
2924 char snappath
[MAXPATHLEN
], newname
[20];
2926 if (!c
|| !lxcapi_is_defined(c
))
2929 if (!bdev_can_backup(c
->lxc_conf
)) {
2930 ERROR("%s's backing store cannot be backed up.", c
->name
);
2931 ERROR("Your container must use another backing store type.");
2935 if (!get_snappath_dir(c
, snappath
))
2938 i
= get_next_index(snappath
, c
->name
);
2940 if (mkdir_p(snappath
, 0755) < 0) {
2941 ERROR("Failed to create snapshot directory %s", snappath
);
2945 ret
= snprintf(newname
, 20, "snap%d", i
);
2946 if (ret
< 0 || ret
>= 20)
2950 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2951 * created in the original container
2953 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2954 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2955 if (bdev_is_dir(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
)) {
2956 ERROR("Snapshot of directory-backed container requested.");
2957 ERROR("Making a copy-clone. If you do want snapshots, then");
2958 ERROR("please create an aufs or overlayfs clone first, snapshot that");
2959 ERROR("and keep the original container pristine.");
2960 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
2962 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2964 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
2968 lxc_container_put(c2
);
2970 // Now write down the creation time
2977 tm_info
= localtime(&timer
);
2979 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2981 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2982 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2983 f
= fopen(dfnam
, "w");
2985 ERROR("Failed to open %s", dfnam
);
2988 if (fprintf(f
, "%s", buffer
) < 0) {
2989 SYSERROR("Writing timestamp");
2995 SYSERROR("Writing timestamp");
3000 // $p / $name / comment \0
3001 int len
= strlen(snappath
) + strlen(newname
) + 10;
3002 char *path
= alloca(len
);
3003 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3004 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3010 static void lxcsnap_free(struct lxc_snapshot
*s
)
3013 free(s
->comment_pathname
);
3018 static char *get_snapcomment_path(char* snappath
, char *name
)
3020 // $snappath/$name/comment
3021 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3022 char *s
= malloc(len
);
3025 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3026 if (ret
< 0 || ret
>= len
) {
3034 static char *get_timestamp(char* snappath
, char *name
)
3036 char path
[MAXPATHLEN
], *s
= NULL
;
3040 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3041 if (ret
< 0 || ret
>= MAXPATHLEN
)
3043 fin
= fopen(path
, "r");
3046 (void) fseek(fin
, 0, SEEK_END
);
3048 (void) fseek(fin
, 0, SEEK_SET
);
3053 if (fread(s
, 1, len
, fin
) != len
) {
3054 SYSERROR("reading timestamp");
3064 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3066 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3068 struct dirent dirent
, *direntp
;
3069 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3072 if (!c
|| !lxcapi_is_defined(c
))
3075 if (!get_snappath_dir(c
, snappath
)) {
3076 ERROR("path name too long");
3079 dir
= opendir(snappath
);
3081 INFO("failed to open %s - assuming no snapshots", snappath
);
3085 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3089 if (!strcmp(direntp
->d_name
, "."))
3092 if (!strcmp(direntp
->d_name
, ".."))
3095 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3096 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3097 ERROR("pathname too long");
3100 if (!file_exists(path2
))
3102 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3104 SYSERROR("Out of memory");
3108 snaps
[count
].free
= lxcsnap_free
;
3109 snaps
[count
].name
= strdup(direntp
->d_name
);
3110 if (!snaps
[count
].name
)
3112 snaps
[count
].lxcpath
= strdup(snappath
);
3113 if (!snaps
[count
].lxcpath
) {
3114 free(snaps
[count
].name
);
3117 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3118 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3123 WARN("failed to close directory");
3131 for (i
=0; i
<count
; i
++)
3132 lxcsnap_free(&snaps
[i
]);
3136 WARN("failed to close directory");
3140 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3142 char clonelxcpath
[MAXPATHLEN
];
3144 struct lxc_container
*snap
, *rest
;
3148 if (!c
|| !c
->name
|| !c
->config_path
)
3151 if (has_fs_snapshots(c
)) {
3152 ERROR("container rootfs has dependent snapshots");
3156 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3158 ERROR("Failed to find original backing store type");
3165 if (!get_snappath_dir(c
, clonelxcpath
)) {
3169 // how should we lock this?
3171 snap
= lxc_container_new(snapname
, clonelxcpath
);
3172 if (!snap
|| !lxcapi_is_defined(snap
)) {
3173 ERROR("Could not open snapshot %s", snapname
);
3174 if (snap
) lxc_container_put(snap
);
3179 if (strcmp(c
->name
, newname
) == 0) {
3180 if (!container_destroy(c
)) {
3181 ERROR("Could not destroy existing container %s", newname
);
3182 lxc_container_put(snap
);
3188 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
3189 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3190 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
,
3191 bdev
->type
, NULL
, 0, NULL
);
3193 if (rest
&& lxcapi_is_defined(rest
))
3196 lxc_container_put(rest
);
3197 lxc_container_put(snap
);
3201 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
3203 struct lxc_container
*snap
= NULL
;
3206 snap
= lxc_container_new(snapname
, clonelxcpath
);
3208 ERROR("Could not find snapshot %s", snapname
);
3212 if (!lxcapi_destroy(snap
)) {
3213 ERROR("Could not destroy snapshot %s", snapname
);
3220 lxc_container_put(snap
);
3224 static bool remove_all_snapshots(const char *path
)
3227 struct dirent dirent
, *direntp
;
3230 dir
= opendir(path
);
3232 SYSERROR("opendir on snapshot path %s", path
);
3235 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3238 if (!strcmp(direntp
->d_name
, "."))
3240 if (!strcmp(direntp
->d_name
, ".."))
3242 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
3251 SYSERROR("Error removing directory %s", path
);
3256 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3258 char clonelxcpath
[MAXPATHLEN
];
3260 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
3263 if (!get_snappath_dir(c
, clonelxcpath
))
3266 return do_snapshot_destroy(snapname
, clonelxcpath
);
3269 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
3271 char clonelxcpath
[MAXPATHLEN
];
3273 if (!c
|| !c
->name
|| !c
->config_path
)
3276 if (!get_snappath_dir(c
, clonelxcpath
))
3279 return remove_all_snapshots(clonelxcpath
);
3282 static bool lxcapi_may_control(struct lxc_container
*c
)
3284 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3287 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3290 char chrootpath
[MAXPATHLEN
];
3291 char *directory_path
= NULL
;
3295 if ((pid
= fork()) < 0) {
3296 SYSERROR("failed to fork a child helper");
3300 if (wait_for_pid(pid
) != 0) {
3301 ERROR("Failed to create note in guest");
3307 /* prepare the path */
3308 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3309 if (ret
< 0 || ret
>= MAXPATHLEN
)
3312 if (chroot(chrootpath
) < 0)
3316 /* remove path if it exists */
3317 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3318 if (unlink(path
) < 0) {
3319 ERROR("unlink failed");
3326 /* create any missing directories */
3327 directory_path
= dirname(strdup(path
));
3328 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3329 ERROR("failed to create directory");
3333 /* create the device node */
3334 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3335 ERROR("mknod failed");
3342 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3346 char value
[MAX_BUFFER
];
3349 /* make sure container is running */
3350 if (!c
->is_running(c
)) {
3351 ERROR("container is not running");
3355 /* use src_path if dest_path is NULL otherwise use dest_path */
3356 p
= dest_path
? dest_path
: src_path
;
3358 /* make sure we can access p */
3359 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3362 /* continue if path is character device or block device */
3363 if (S_ISCHR(st
.st_mode
))
3364 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3365 else if (S_ISBLK(st
.st_mode
))
3366 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3370 /* check snprintf return code */
3371 if (ret
< 0 || ret
>= MAX_BUFFER
)
3374 if (!do_add_remove_node(c
->init_pid(c
), p
, add
, &st
))
3377 /* add or remove device to/from cgroup access list */
3379 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3380 ERROR("set_cgroup_item failed while adding the device node");
3384 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3385 ERROR("set_cgroup_item failed while removing the device node");
3393 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3396 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3399 return add_remove_device_node(c
, src_path
, dest_path
, true);
3402 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3405 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3408 return add_remove_device_node(c
, src_path
, dest_path
, false);
3411 static bool lxcapi_attach_interface(struct lxc_container
*c
, const char *ifname
,
3412 const char *dst_ifname
)
3416 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3421 ERROR("No source interface name given");
3425 ret
= lxc_netdev_isup(ifname
);
3428 /* netdev of ifname is up. */
3429 ret
= lxc_netdev_down(ifname
);
3434 ret
= lxc_netdev_move_by_name(ifname
, c
->init_pid(c
), dst_ifname
);
3444 static bool lxcapi_detach_interface(struct lxc_container
*c
, const char *ifname
,
3445 const char *dst_ifname
)
3447 pid_t pid
, pid_outside
;
3450 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3455 ERROR("No source interface name given");
3459 pid_outside
= getpid();
3462 ERROR("failed to fork task to get interfaces information");
3466 if (pid
== 0) { // child
3468 if (!enter_net_ns(c
)) {
3469 ERROR("failed to enter namespace");
3473 ret
= lxc_netdev_isup(ifname
);
3477 /* netdev of ifname is up. */
3479 ret
= lxc_netdev_down(ifname
);
3484 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
3486 /* -EINVAL means there is no netdev named as ifanme. */
3487 if (ret
== -EINVAL
) {
3488 ERROR("No network device named as %s.", ifname
);
3493 if (wait_for_pid(pid
) != 0)
3500 /* The type of criu invocation, one of "dump" or "restore" */
3503 /* The directory to pass to criu */
3506 /* The container to dump */
3507 struct lxc_container
*c
;
3509 /* Enable criu verbose mode? */
3512 /* dump: stop the container or not after dumping? */
3515 /* restore: the file to write the init process' pid into */
3517 const char *cgroup_path
;
3520 static void exec_criu(struct criu_opts
*opts
)
3522 char **argv
, log
[PATH_MAX
];
3523 int static_args
= 18, argc
= 0, i
, ret
;
3525 struct lxc_list
*it
;
3530 /* The command line always looks like:
3531 * criu $(action) --tcp-established --file-locks --link-remap --force-irmap \
3532 * --manage-cgroups action-script foo.sh -D $(directory) \
3533 * -o $(directory)/$(action).log --ext-mount-map auto
3534 * --enable-external-sharing --enable-external-masters
3535 * +1 for final NULL */
3537 if (strcmp(opts
->action
, "dump") == 0) {
3541 /* --leave-running */
3544 } else if (strcmp(opts
->action
, "restore") == 0) {
3545 /* --root $(lxc_mount_point) --restore-detached
3546 * --restore-sibling --pidfile $foo --cgroup-root $foo */
3555 ret
= snprintf(log
, PATH_MAX
, "%s/%s.log", opts
->directory
, opts
->action
);
3556 if (ret
< 0 || ret
>= PATH_MAX
) {
3557 ERROR("logfile name too long\n");
3561 argv
= malloc(static_args
* sizeof(*argv
));
3565 memset(argv
, 0, static_args
* sizeof(*argv
));
3567 #define DECLARE_ARG(arg) \
3569 if (arg == NULL) { \
3570 ERROR("Got NULL argument for criu"); \
3573 argv[argc++] = strdup(arg); \
3574 if (!argv[argc-1]) \
3578 argv
[argc
++] = on_path("criu", NULL
);
3579 if (!argv
[argc
-1]) {
3580 ERROR("Couldn't find criu binary\n");
3584 DECLARE_ARG(opts
->action
);
3585 DECLARE_ARG("--tcp-established");
3586 DECLARE_ARG("--file-locks");
3587 DECLARE_ARG("--link-remap");
3588 DECLARE_ARG("--force-irmap");
3589 DECLARE_ARG("--manage-cgroups");
3590 DECLARE_ARG("--ext-mount-map");
3591 DECLARE_ARG("auto");
3592 DECLARE_ARG("--enable-external-sharing");
3593 DECLARE_ARG("--enable-external-masters");
3595 DECLARE_ARG(opts
->directory
);
3600 DECLARE_ARG("-vvvvvv");
3602 if (strcmp(opts
->action
, "dump") == 0) {
3605 if (sprintf(pid
, "%d", lxcapi_init_pid(opts
->c
)) < 0)
3611 DECLARE_ARG("--leave-running");
3612 } else if (strcmp(opts
->action
, "restore") == 0) {
3616 DECLARE_ARG("--root");
3617 DECLARE_ARG(opts
->c
->lxc_conf
->rootfs
.mount
);
3618 DECLARE_ARG("--restore-detached");
3619 DECLARE_ARG("--restore-sibling");
3620 DECLARE_ARG("--pidfile");
3621 DECLARE_ARG(opts
->pidfile
);
3622 DECLARE_ARG("--cgroup-root");
3623 DECLARE_ARG(opts
->cgroup_path
);
3625 additional
= lxc_list_len(&opts
->c
->lxc_conf
->network
) * 2;
3627 m
= realloc(argv
, (argc
+ additional
+ 1) * sizeof(*argv
)); \
3632 lxc_list_for_each(it
, &opts
->c
->lxc_conf
->network
) {
3633 char eth
[128], *veth
;
3634 struct lxc_netdev
*n
= it
->elem
;
3637 if (strlen(n
->name
) >= sizeof(eth
))
3639 strncpy(eth
, n
->name
, sizeof(eth
));
3641 sprintf(eth
, "eth%d", netnr
);
3643 veth
= n
->priv
.veth_attr
.pair
;
3645 ret
= snprintf(buf
, sizeof(buf
), "%s=%s@%s", eth
, veth
, n
->link
);
3646 if (ret
< 0 || ret
>= sizeof(buf
))
3649 DECLARE_ARG("--veth-pair");
3658 execv(argv
[0], argv
);
3662 for (i
= 0; argv
[i
]; i
++)
3667 /* Check and make sure the container has a configuration that we know CRIU can
3669 static bool criu_ok(struct lxc_container
*c
)
3671 struct lxc_list
*it
;
3672 bool found_deny_rule
= false;
3675 ERROR("Must be root to checkpoint\n");
3679 /* We only know how to restore containers with veth networks. */
3680 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3681 struct lxc_netdev
*n
= it
->elem
;
3682 if (n
->type
!= LXC_NET_VETH
&& n
->type
!= LXC_NET_NONE
) {
3683 ERROR("Found network that is not VETH or NONE\n");
3688 // These requirements come from http://criu.org/LXC
3689 if (c
->lxc_conf
->console
.path
&&
3690 strcmp(c
->lxc_conf
->console
.path
, "none") != 0) {
3691 ERROR("lxc.console must be none\n");
3695 if (c
->lxc_conf
->tty
!= 0) {
3696 ERROR("lxc.tty must be 0\n");
3700 lxc_list_for_each(it
, &c
->lxc_conf
->cgroup
) {
3701 struct lxc_cgroup
*cg
= it
->elem
;
3702 if (strcmp(cg
->subsystem
, "devices.deny") == 0 &&
3703 strcmp(cg
->value
, "c 5:1 rwm") == 0) {
3705 found_deny_rule
= true;
3710 if (!found_deny_rule
) {
3711 ERROR("couldn't find devices.deny = c 5:1 rwm");
3718 static bool dump_net_info(struct lxc_container
*c
, char *directory
)
3721 struct lxc_list
*it
;
3724 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3725 char *veth
= NULL
, *bridge
= NULL
, veth_path
[PATH_MAX
], eth
[128];
3726 struct lxc_netdev
*n
= it
->elem
;
3727 bool has_error
= true;
3730 pret
= snprintf(veth_path
, PATH_MAX
, "lxc.network.%d.veth.pair", netnr
);
3731 if (pret
< 0 || pret
>= PATH_MAX
)
3734 veth
= lxcapi_get_running_config_item(c
, veth_path
);
3736 /* criu_ok() checks that all interfaces are
3737 * LXC_NET{VETH,NONE}, and VETHs should have this
3739 assert(n
->type
== LXC_NET_NONE
);
3743 bridge
= lxcapi_get_running_config_item(c
, veth_path
);
3747 pret
= snprintf(veth_path
, PATH_MAX
, "%s/veth%d", directory
, netnr
);
3748 if (pret
< 0 || pret
>= PATH_MAX
|| print_to_file(veth_path
, veth
) < 0)
3752 if (strlen(n
->name
) >= 128)
3754 strncpy(eth
, n
->name
, 128);
3756 sprintf(eth
, "eth%d", netnr
);
3769 static bool lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
3777 if (mkdir(directory
, 0700) < 0 && errno
!= EEXIST
)
3780 if (!dump_net_info(c
, directory
))
3788 struct criu_opts os
;
3791 os
.directory
= directory
;
3794 os
.verbose
= verbose
;
3796 /* exec_criu() returning is an error */
3800 pid_t w
= waitpid(pid
, &status
, 0);
3802 SYSERROR("waitpid");
3806 if (WIFEXITED(status
)) {
3807 return !WEXITSTATUS(status
);
3814 static bool restore_net_info(struct lxc_container
*c
)
3816 struct lxc_list
*it
;
3817 bool has_error
= true;
3819 if (container_mem_lock(c
))
3822 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3823 struct lxc_netdev
*netdev
= it
->elem
;
3824 char template[IFNAMSIZ
];
3825 snprintf(template, sizeof(template), "vethXXXXXX");
3827 if (!netdev
->priv
.veth_attr
.pair
)
3828 netdev
->priv
.veth_attr
.pair
= lxc_mkifname(template);
3830 if (!netdev
->priv
.veth_attr
.pair
)
3837 container_mem_unlock(c
);
3841 // do_restore never returns, the calling process is used as the
3842 // monitor process. do_restore calls exit() if it fails.
3843 static void do_restore(struct lxc_container
*c
, int pipe
, char *directory
, bool verbose
)
3846 char pidfile
[L_tmpnam
];
3847 struct lxc_handler
*handler
;
3850 if (!tmpnam(pidfile
))
3853 handler
= lxc_init(c
->name
, c
->lxc_conf
, c
->config_path
);
3857 if (!cgroup_init(handler
)) {
3858 ERROR("failed initing cgroups");
3859 goto out_fini_handler
;
3862 if (!cgroup_create(handler
)) {
3863 ERROR("failed creating groups");
3864 goto out_fini_handler
;
3867 if (!restore_net_info(c
)) {
3868 ERROR("failed restoring network info");
3869 goto out_fini_handler
;
3872 resolve_clone_flags(handler
);
3876 goto out_fini_handler
;
3879 struct criu_opts os
;
3880 struct lxc_rootfs
*rootfs
;
3885 if (unshare(CLONE_NEWNS
))
3886 goto out_fini_handler
;
3888 /* CRIU needs the lxc root bind mounted so that it is the root of some
3890 rootfs
= &c
->lxc_conf
->rootfs
;
3892 if (rootfs_is_blockdev(c
->lxc_conf
)) {
3893 if (do_rootfs_setup(c
->lxc_conf
, c
->name
, c
->config_path
) < 0)
3894 goto out_fini_handler
;
3896 if (mkdir(rootfs
->mount
, 0755) < 0 && errno
!= EEXIST
)
3897 goto out_fini_handler
;
3899 if (mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
) < 0) {
3900 SYSERROR("remount / to private failed");
3901 goto out_fini_handler
;
3904 if (mount(rootfs
->path
, rootfs
->mount
, NULL
, MS_BIND
, NULL
) < 0) {
3905 rmdir(rootfs
->mount
);
3906 goto out_fini_handler
;
3910 os
.action
= "restore";
3911 os
.directory
= directory
;
3913 os
.pidfile
= pidfile
;
3914 os
.verbose
= verbose
;
3915 os
.cgroup_path
= cgroup_canonical_path(handler
);
3917 /* exec_criu() returning is an error */
3919 umount(rootfs
->mount
);
3920 rmdir(rootfs
->mount
);
3921 goto out_fini_handler
;
3926 pid_t w
= waitpid(pid
, &status
, 0);
3928 SYSERROR("waitpid");
3929 goto out_fini_handler
;
3932 ret
= write(pipe
, &status
, sizeof(status
));
3936 if (sizeof(status
) != ret
) {
3937 SYSERROR("failed to write all of status");
3938 goto out_fini_handler
;
3941 if (WIFEXITED(status
)) {
3942 if (WEXITSTATUS(status
)) {
3943 goto out_fini_handler
;
3946 FILE *f
= fopen(pidfile
, "r");
3948 SYSERROR("couldn't read restore's init pidfile %s\n", pidfile
);
3949 goto out_fini_handler
;
3952 ret
= fscanf(f
, "%d", (int*) &handler
->pid
);
3955 ERROR("reading restore pid failed");
3956 goto out_fini_handler
;
3959 if (lxc_set_state(c
->name
, handler
, RUNNING
))
3960 goto out_fini_handler
;
3963 ERROR("CRIU was killed with signal %d\n", WTERMSIG(status
));
3964 goto out_fini_handler
;
3968 * See comment in lxcapi_start; we don't care if these
3969 * fail because it's just a beauty thing. We just
3970 * assign the return here to silence potential.
3972 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
3973 ret
= setproctitle(title
);
3975 ret
= lxc_poll(c
->name
, handler
);
3977 lxc_abort(c
->name
, handler
);
3978 lxc_fini(c
->name
, handler
);
3983 lxc_fini(c
->name
, handler
);
3988 if (write(pipe
, &status
, sizeof(status
)) != sizeof(status
)) {
3989 SYSERROR("writing status failed");
3997 static bool lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4007 ERROR("Must be root to restore\n");
4012 ERROR("failed to create pipe");
4025 // this never returns
4026 do_restore(c
, pipefd
[1], directory
, verbose
);
4031 nread
= read(pipefd
[0], &status
, sizeof(status
));
4033 if (sizeof(status
) != nread
) {
4034 ERROR("reading status from pipe failed");
4038 // If the criu process was killed or exited nonzero, wait() for the
4039 // handler, since the restore process died. Otherwise, we don't need to
4040 // wait, since the child becomes the monitor process.
4041 if (!WIFEXITED(status
) || WEXITSTATUS(status
))
4046 if (wait_for_pid(pid
))
4047 ERROR("restore process died");
4051 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4061 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4065 ERROR("Memory allocation error.");
4070 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4075 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4077 struct lxc_container
*c
;
4082 c
= malloc(sizeof(*c
));
4084 fprintf(stderr
, "failed to malloc lxc_container\n");
4087 memset(c
, 0, sizeof(*c
));
4090 c
->config_path
= strdup(configpath
);
4092 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4094 if (!c
->config_path
) {
4095 fprintf(stderr
, "Out of memory\n");
4099 remove_trailing_slashes(c
->config_path
);
4100 c
->name
= malloc(strlen(name
)+1);
4102 fprintf(stderr
, "Error allocating lxc_container name\n");
4105 strcpy(c
->name
, name
);
4108 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
4109 fprintf(stderr
, "failed to create lock\n");
4113 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
4114 fprintf(stderr
, "failed to alloc privlock\n");
4118 if (!set_config_filename(c
)) {
4119 fprintf(stderr
, "Error allocating config file pathname\n");
4123 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
4126 if (ongoing_create(c
) == 2) {
4127 ERROR("Error: %s creation was not completed", c
->name
);
4128 container_destroy(c
);
4129 lxcapi_clear_config(c
);
4131 c
->daemonize
= true;
4134 // assign the member functions
4135 c
->is_defined
= lxcapi_is_defined
;
4136 c
->state
= lxcapi_state
;
4137 c
->is_running
= lxcapi_is_running
;
4138 c
->freeze
= lxcapi_freeze
;
4139 c
->unfreeze
= lxcapi_unfreeze
;
4140 c
->console
= lxcapi_console
;
4141 c
->console_getfd
= lxcapi_console_getfd
;
4142 c
->init_pid
= lxcapi_init_pid
;
4143 c
->load_config
= lxcapi_load_config
;
4144 c
->want_daemonize
= lxcapi_want_daemonize
;
4145 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4146 c
->start
= lxcapi_start
;
4147 c
->startl
= lxcapi_startl
;
4148 c
->stop
= lxcapi_stop
;
4149 c
->config_file_name
= lxcapi_config_file_name
;
4150 c
->wait
= lxcapi_wait
;
4151 c
->set_config_item
= lxcapi_set_config_item
;
4152 c
->destroy
= lxcapi_destroy
;
4153 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4154 c
->rename
= lxcapi_rename
;
4155 c
->save_config
= lxcapi_save_config
;
4156 c
->get_keys
= lxcapi_get_keys
;
4157 c
->create
= lxcapi_create
;
4158 c
->createl
= lxcapi_createl
;
4159 c
->shutdown
= lxcapi_shutdown
;
4160 c
->reboot
= lxcapi_reboot
;
4161 c
->clear_config
= lxcapi_clear_config
;
4162 c
->clear_config_item
= lxcapi_clear_config_item
;
4163 c
->get_config_item
= lxcapi_get_config_item
;
4164 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4165 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4166 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4167 c
->get_config_path
= lxcapi_get_config_path
;
4168 c
->set_config_path
= lxcapi_set_config_path
;
4169 c
->clone
= lxcapi_clone
;
4170 c
->get_interfaces
= lxcapi_get_interfaces
;
4171 c
->get_ips
= lxcapi_get_ips
;
4172 c
->attach
= lxcapi_attach
;
4173 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4174 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4175 c
->snapshot
= lxcapi_snapshot
;
4176 c
->snapshot_list
= lxcapi_snapshot_list
;
4177 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4178 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4179 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4180 c
->may_control
= lxcapi_may_control
;
4181 c
->add_device_node
= lxcapi_add_device_node
;
4182 c
->remove_device_node
= lxcapi_remove_device_node
;
4183 c
->attach_interface
= lxcapi_attach_interface
;
4184 c
->detach_interface
= lxcapi_detach_interface
;
4185 c
->checkpoint
= lxcapi_checkpoint
;
4186 c
->restore
= lxcapi_restore
;
4188 /* we'll allow the caller to update these later */
4189 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
4190 fprintf(stderr
, "failed to open log\n");
4197 lxc_container_free(c
);
4201 int lxc_get_wait_states(const char **states
)
4206 for (i
=0; i
<MAX_STATE
; i
++)
4207 states
[i
] = lxc_state2str(i
);
4212 * These next two could probably be done smarter with reusing a common function
4213 * with different iterators and tests...
4215 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4218 int i
, cfound
= 0, nfound
= 0;
4219 struct dirent dirent
, *direntp
;
4220 struct lxc_container
*c
;
4223 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4225 dir
= opendir(lxcpath
);
4227 SYSERROR("opendir on lxcpath");
4236 while (!readdir_r(dir
, &dirent
, &direntp
)) {
4239 if (!strcmp(direntp
->d_name
, "."))
4241 if (!strcmp(direntp
->d_name
, ".."))
4244 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4248 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4258 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4260 INFO("Container %s:%s has a config but could not be loaded",
4261 lxcpath
, direntp
->d_name
);
4263 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4267 if (!lxcapi_is_defined(c
)) {
4268 INFO("Container %s:%s has a config but is not defined",
4269 lxcpath
, direntp
->d_name
);
4271 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4273 lxc_container_put(c
);
4277 if (!add_to_clist(cret
, c
, nfound
, true)) {
4278 lxc_container_put(c
);
4288 if (names
&& *names
) {
4289 for (i
=0; i
<cfound
; i
++)
4293 if (cret
&& *cret
) {
4294 for (i
=0; i
<nfound
; i
++)
4295 lxc_container_put((*cret
)[i
]);
4302 int list_active_containers(const char *lxcpath
, char ***nret
,
4303 struct lxc_container
***cret
)
4305 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4308 char **ct_name
= NULL
;
4310 struct lxc_container
*c
;
4314 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4315 lxcpath_len
= strlen(lxcpath
);
4322 FILE *f
= fopen("/proc/net/unix", "r");
4326 while (getline(&line
, &len
, f
) != -1) {
4328 char *p
= strrchr(line
, ' '), *p2
;
4337 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4339 } else if (strncmp(p
, "lxc/", 4) == 0) {
4349 // Now p is the start of lxc_name
4350 p2
= strchr(p
, '/');
4351 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4356 if (strncmp(lxcpath
, lxc_cmd_get_lxcpath(p
), lxcpath_len
) != 0)
4358 p
= lxc_cmd_get_name(p
);
4361 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4364 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4365 goto free_cret_list
;
4372 c
= lxc_container_new(p
, lxcpath
);
4374 INFO("Container %s:%s is running but could not be loaded",
4376 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4381 * If this is an anonymous container, then is_defined *can*
4382 * return false. So we don't do that check. Count on the
4383 * fact that the command socket exists.
4386 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
4387 lxc_container_put(c
);
4388 goto free_cret_list
;
4393 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
4402 if (cret
&& *cret
) {
4403 for (i
= 0; i
< cret_cnt
; i
++)
4404 lxc_container_put((*cret
)[i
]);
4410 for (i
= 0; i
< ct_name_cnt
; i
++)
4422 int list_all_containers(const char *lxcpath
, char ***nret
,
4423 struct lxc_container
***cret
)
4425 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
4428 struct lxc_container
**ct_list
= NULL
;
4430 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
4434 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
4435 if (active_cnt
< 0) {
4440 for (i
= 0; i
< active_cnt
; i
++) {
4441 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
4442 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
4444 goto free_active_name
;
4448 free(active_name
[i
]);
4449 active_name
[i
] = NULL
;
4455 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
4456 struct lxc_container
*c
;
4458 c
= lxc_container_new(ct_name
[i
], lxcpath
);
4460 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
4461 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
4465 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
4466 lxc_container_put(c
);
4485 for (i
= 0; i
< ct_list_cnt
; i
++) {
4486 lxc_container_put(ct_list
[i
]);
4491 for (i
= 0; i
< active_cnt
; i
++) {
4492 free(active_name
[i
]);
4497 for (i
= 0; i
< ct_cnt
; i
++) {