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>
38 #include <sys/syscall.h>
40 #include <lxc/lxccontainer.h>
41 #include <lxc/version.h>
56 #include "namespace.h"
63 #include <../include/ifaddrs.h>
66 #define MAX_BUFFER 4096
68 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
70 /* Define faccessat() if missing from the C library */
71 #ifndef HAVE_FACCESSAT
72 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
75 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
84 lxc_log_define(lxc_container
, lxc
);
86 static bool config_file_exists(const char *lxcpath
, const char *cname
)
88 /* $lxcpath + '/' + $cname + '/config' + \0 */
89 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
90 char *fname
= alloca(len
);
92 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
93 if (ret
< 0 || ret
>= len
)
96 return file_exists(fname
);
100 * A few functions to help detect when a container creation failed.
101 * If a container creation was killed partway through, then trying
102 * to actually start that container could harm the host. We detect
103 * this by creating a 'partial' file under the container directory,
104 * and keeping an advisory lock. When container creation completes,
105 * we remove that file. When we load or try to start a container, if
106 * we find that file, without a flock, we remove the container.
108 static int ongoing_create(struct lxc_container
*c
)
110 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
111 char *path
= alloca(len
);
115 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
116 if (ret
< 0 || ret
>= len
) {
117 ERROR("Error writing partial pathname");
121 if (!file_exists(path
))
123 fd
= open(path
, O_RDWR
);
125 // give benefit of the doubt
126 SYSERROR("Error opening partial file");
130 lk
.l_whence
= SEEK_SET
;
134 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
135 // create is still ongoing
139 // create completed but partial is still there.
144 static int create_partial(struct lxc_container
*c
)
146 // $lxcpath + '/' + $name + '/partial' + \0
147 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
148 char *path
= alloca(len
);
152 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
153 if (ret
< 0 || ret
>= len
) {
154 ERROR("Error writing partial pathname");
157 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
158 SYSERROR("Erorr creating partial file");
162 lk
.l_whence
= SEEK_SET
;
165 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
166 SYSERROR("Error locking partial file %s", path
);
174 static void remove_partial(struct lxc_container
*c
, int fd
)
176 // $lxcpath + '/' + $name + '/partial' + \0
177 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
178 char *path
= alloca(len
);
182 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
183 if (ret
< 0 || ret
>= len
) {
184 ERROR("Error writing partial pathname");
187 if (unlink(path
) < 0)
188 SYSERROR("Error unlink partial file %s", path
);
192 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
193 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
194 * container configuration file.
195 * The container_disk_lock also takes the container_mem_lock.
196 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
197 * NOTHING mutexes two independent programs with their own struct
198 * lxc_container for the same c->name, between API calls. For instance,
199 * c->config_read(); c->start(); Between those calls, data on disk
200 * could change (which shouldn't bother the caller unless for instance
201 * the rootfs get moved). c->config_read(); update; c->config_write();
202 * Two such updaters could race. The callers should therefore check their
203 * results. Trying to prevent that would necessarily expose us to deadlocks
204 * due to hung callers. So I prefer to keep the locks only within our own
205 * functions, not across functions.
207 * If you're going to clone while holding a lxccontainer, increment
208 * c->numthreads (under privlock) before forking. When deleting,
209 * decrement numthreads under privlock, then if it hits 0 you can delete.
210 * Do not ever use a lxccontainer whose numthreads you did not bump.
213 static void lxc_container_free(struct lxc_container
*c
)
220 c
->configfile
= NULL
;
222 if (c
->error_string
) {
223 free(c
->error_string
);
224 c
->error_string
= NULL
;
227 lxc_putlock(c
->slock
);
231 lxc_putlock(c
->privlock
);
239 lxc_conf_free(c
->lxc_conf
);
242 if (c
->config_path
) {
243 free(c
->config_path
);
244 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 /* daemonize implies close_all_fds so set it */
469 c
->lxc_conf
->close_all_fds
= 1;
470 container_mem_unlock(c
);
474 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
476 if (!c
|| !c
->lxc_conf
)
478 if (container_mem_lock(c
)) {
479 ERROR("Error getting mem lock");
482 c
->lxc_conf
->close_all_fds
= state
;
483 container_mem_unlock(c
);
487 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
494 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
499 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
501 /* we'll probably want to make this timeout configurable? */
502 int timeout
= 5, ret
, status
;
505 * our child is going to fork again, then exit. reap the
508 ret
= waitpid(pid
, &status
, 0);
509 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
510 DEBUG("failed waiting for first dual-fork child");
511 return lxcapi_wait(c
, "RUNNING", timeout
);
514 static bool am_single_threaded(void)
516 struct dirent dirent
, *direntp
;
520 dir
= opendir("/proc/self/task");
522 INFO("failed to open /proc/self/task");
526 while (!readdir_r(dir
, &dirent
, &direntp
)) {
530 if (!strcmp(direntp
->d_name
, "."))
533 if (!strcmp(direntp
->d_name
, ".."))
543 * I can't decide if it'd be more convenient for callers if we accept '...',
544 * or a null-terminated array (i.e. execl vs execv)
546 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
549 struct lxc_conf
*conf
;
550 bool daemonize
= false;
552 char *default_args
[] = {
557 /* container exists */
560 /* container has been setup */
564 if ((ret
= ongoing_create(c
)) < 0) {
565 ERROR("Error checking for incomplete creation");
569 ERROR("Error: %s creation was not completed", c
->name
);
572 } else if (ret
== 1) {
573 ERROR("Error: creation of %s is ongoing", c
->name
);
577 /* is this app meant to be run through lxcinit, as in lxc-execute? */
578 if (useinit
&& !argv
)
581 if (container_mem_lock(c
))
584 daemonize
= c
->daemonize
;
585 container_mem_unlock(c
);
588 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
589 return ret
== 0 ? true : false;
596 * say, I'm not sure - what locks do we want here? Any?
597 * Is liblxc's locking enough here to protect the on disk
598 * container? We don't want to exclude things like lxc_info
599 * while container is running...
602 lxc_monitord_spawn(c
->config_path
);
609 /* Set to NULL because we don't want father unlink
610 * the PID file, child will do the free and unlink.
613 return wait_on_daemonized_start(c
, pid
);
616 /* second fork to be reparented by init */
619 SYSERROR("Error doing dual-fork");
624 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
626 SYSERROR("Error chdir()ing to /.");
629 lxc_check_inherited(conf
, -1);
633 open("/dev/zero", O_RDONLY
);
634 open("/dev/null", O_RDWR
);
635 open("/dev/null", O_RDWR
);
638 if (!am_single_threaded()) {
639 ERROR("Cannot start non-daemonized container when threaded");
644 /* We need to write PID file after daeminize, so we always
645 * write the right PID.
648 pid_fp
= fopen(c
->pidfile
, "w");
649 if (pid_fp
== NULL
) {
650 SYSERROR("Failed to create pidfile '%s' for '%s'",
651 c
->pidfile
, c
->name
);
655 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
656 SYSERROR("Failed to write '%s'", c
->pidfile
);
668 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
672 INFO("container requested reboot");
684 exit (ret
== 0 ? true : false);
686 return (ret
== 0 ? true : false);
690 * note there MUST be an ending NULL
692 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
695 char **inargs
= NULL
;
698 /* container exists */
702 va_start(ap
, useinit
);
703 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
707 ERROR("Memory allocation error.");
711 /* pass NULL if no arguments were supplied */
712 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
717 for (arg
= inargs
; *arg
; arg
++)
725 static bool lxcapi_stop(struct lxc_container
*c
)
732 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
737 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
739 int ret
= -1, lasterr
;
740 char *p
= alloca(strlen(path
)+1);
741 mode_t mask
= umask(0002);
742 ret
= mkdir(path
, 0770);
750 SYSERROR("failed to create container path %s", path
);
755 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
756 ERROR("Failed to chown container dir");
763 * create the standard expected container dir
765 static bool create_container_dir(struct lxc_container
*c
)
770 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
774 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
775 if (ret
< 0 || ret
>= len
) {
779 ret
= do_create_container_dir(s
, c
->lxc_conf
);
784 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
785 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
788 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
789 * it returns a mounted bdev on success, NULL on error.
791 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
792 struct bdev_specs
*specs
)
799 /* rootfs.path or lxcpath/lxcname/rootfs */
800 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
801 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
802 len
= strlen(rpath
) + 1;
804 ret
= snprintf(dest
, len
, "%s", rpath
);
806 const char *lxcpath
= lxcapi_get_config_path(c
);
807 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
809 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
811 if (ret
< 0 || ret
>= len
)
814 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
816 ERROR("Failed to create backing store type %s", type
);
820 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
822 /* if we are not root, chown the rootfs dir to root in the
825 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
826 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
827 ERROR("Error chowning %s to container root", bdev
->dest
);
828 suggest_default_idmap();
838 * Given the '-t' template option to lxc-create, figure out what to
839 * do. If the template is a full executable path, use that. If it
840 * is something like 'sshd', then return $templatepath/lxc-sshd.
841 * On success return the template, on error return NULL.
843 static char *get_template_path(const char *t
)
848 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
853 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
857 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
858 if (ret
< 0 || ret
>= len
) {
862 if (access(tpath
, X_OK
) < 0) {
863 SYSERROR("bad template: %s", t
);
871 static char *lxcbasename(char *path
)
873 char *p
= path
+ strlen(path
) - 1;
874 while (*p
!= '/' && p
> path
)
879 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
889 SYSERROR("failed to fork task for container creation template");
893 if (pid
== 0) { // child
894 char *patharg
, *namearg
, *rootfsarg
, *src
;
895 struct bdev
*bdev
= NULL
;
897 int ret
, len
, nargs
= 0;
899 struct lxc_conf
*conf
= c
->lxc_conf
;
905 open("/dev/zero", O_RDONLY
);
906 open("/dev/null", O_RDWR
);
907 open("/dev/null", O_RDWR
);
910 src
= c
->lxc_conf
->rootfs
.path
;
912 * for an overlay create, what the user wants is the template to fill
913 * in what will become the readonly lower layer. So don't mount for
916 if (strncmp(src
, "overlayfs:", 10) == 0)
917 src
= overlay_getlower(src
+10);
918 if (strncmp(src
, "aufs:", 5) == 0)
919 src
= overlay_getlower(src
+5);
921 bdev
= bdev_init(c
->lxc_conf
, src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
923 ERROR("Error opening rootfs");
927 if (geteuid() == 0) {
928 if (unshare(CLONE_NEWNS
) < 0) {
929 ERROR("error unsharing mounts");
932 if (detect_shared_rootfs()) {
933 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
934 SYSERROR("Failed to make / rslave to run template");
935 ERROR("Continuing...");
939 if (strcmp(bdev
->type
, "dir") && strcmp(bdev
->type
, "btrfs")) {
940 if (geteuid() != 0) {
941 ERROR("non-root users can only create btrfs and directory-backed containers");
944 if (bdev
->ops
->mount(bdev
) < 0) {
945 ERROR("Error mounting rootfs");
948 } else { // TODO come up with a better way here!
951 bdev
->dest
= strdup(bdev
->src
);
955 * create our new array, pre-pend the template name and
959 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
960 nargs
+= 4; // template, path, rootfs and name args
962 newargv
= malloc(nargs
* sizeof(*newargv
));
965 newargv
[0] = lxcbasename(tpath
);
967 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
968 patharg
= malloc(len
);
971 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
972 if (ret
< 0 || ret
>= len
)
974 newargv
[1] = patharg
;
975 len
= strlen("--name=") + strlen(c
->name
) + 1;
976 namearg
= malloc(len
);
979 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
980 if (ret
< 0 || ret
>= len
)
982 newargv
[2] = namearg
;
984 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
985 rootfsarg
= malloc(len
);
988 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
989 if (ret
< 0 || ret
>= len
)
991 newargv
[3] = rootfsarg
;
993 /* add passed-in args */
995 for (i
= 4; i
< nargs
; i
++)
996 newargv
[i
] = argv
[i
-4];
998 /* add trailing NULL */
1000 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1003 newargv
[nargs
- 1] = NULL
;
1006 * If we're running the template in a mapped userns, then
1007 * we prepend the template command with:
1008 * lxc-usernsexec <-m map1> ... <-m mapn> --
1009 * and we append "--mapped-uid x", where x is the mapped uid
1012 if (!lxc_list_empty(&conf
->id_map
)) {
1016 char **n2
= malloc(n2args
* sizeof(*n2
));
1017 struct lxc_list
*it
;
1021 SYSERROR("out of memory");
1025 tpath
= "lxc-usernsexec";
1026 n2
[0] = "lxc-usernsexec";
1027 lxc_list_for_each(it
, &conf
->id_map
) {
1030 n2
= realloc(n2
, n2args
* sizeof(char *));
1033 n2
[n2args
-2] = "-m";
1034 n2
[n2args
-1] = malloc(200);
1037 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1038 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1039 map
->nsid
, map
->hostid
, map
->range
);
1040 if (ret
< 0 || ret
>= 200)
1043 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1044 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1045 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1048 if (hostid_mapped
< 0) {
1049 hostid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_UID
);
1050 n2
[n2args
++] = "-m";
1051 if (hostid_mapped
< 0) {
1052 ERROR("Could not find free uid to map");
1055 n2
[n2args
++] = malloc(200);
1056 if (!n2
[n2args
-1]) {
1057 SYSERROR("out of memory");
1060 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1061 hostid_mapped
, geteuid());
1062 if (ret
< 0 || ret
>= 200) {
1063 ERROR("string too long");
1067 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1068 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1069 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1072 if (hostgid_mapped
< 0) {
1073 hostgid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_GID
);
1074 n2
[n2args
++] = "-m";
1075 if (hostgid_mapped
< 0) {
1076 ERROR("Could not find free uid to map");
1079 n2
[n2args
++] = malloc(200);
1080 if (!n2
[n2args
-1]) {
1081 SYSERROR("out of memory");
1084 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1085 hostgid_mapped
, getegid());
1086 if (ret
< 0 || ret
>= 200) {
1087 ERROR("string too long");
1091 n2
[n2args
++] = "--";
1092 for (i
= 0; i
< nargs
; i
++)
1093 n2
[i
+ n2args
] = newargv
[i
];
1095 // Finally add "--mapped-uid $uid" to tell template what to chown
1098 n2
= realloc(n2
, n2args
* sizeof(char *));
1100 SYSERROR("out of memory");
1103 // note n2[n2args-1] is NULL
1104 n2
[n2args
-5] = "--mapped-uid";
1105 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1106 n2
[n2args
-4] = txtuid
;
1107 n2
[n2args
-3] = "--mapped-gid";
1108 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1109 n2
[n2args
-2] = txtgid
;
1110 n2
[n2args
-1] = NULL
;
1115 execvp(tpath
, newargv
);
1116 SYSERROR("failed to execute template %s", tpath
);
1120 if (wait_for_pid(pid
) != 0) {
1121 ERROR("container creation template for %s failed", c
->name
);
1128 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1136 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1140 f
= fopen(path
, "r");
1144 if (fseek(f
, 0, SEEK_END
) < 0)
1146 if ((flen
= ftell(f
)) < 0)
1148 if (fseek(f
, 0, SEEK_SET
) < 0)
1150 if ((contents
= malloc(flen
+ 1)) == NULL
)
1152 if (fread(contents
, 1, flen
, f
) != flen
)
1153 goto out_free_contents
;
1155 contents
[flen
] = '\0';
1159 goto out_free_contents
;
1162 tpath
= get_template_path(t
);
1164 ERROR("bad template: %s", t
);
1165 goto out_free_contents
;
1168 ret
= sha1sum_file(tpath
, md_value
);
1170 ERROR("Error getting sha1sum of %s", tpath
);
1172 goto out_free_contents
;
1177 f
= fopen(path
, "w");
1179 SYSERROR("reopening config for writing");
1183 fprintf(f
, "# Template used to create this container: %s\n", t
);
1185 fprintf(f
, "# Parameters passed to the template:");
1187 fprintf(f
, " %s", *argv
);
1193 fprintf(f
, "# Template script checksum (SHA-1): ");
1194 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1195 fprintf(f
, "%02x", md_value
[i
]);
1198 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1199 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1200 SYSERROR("Writing original contents");
1216 SYSERROR("Error prepending header");
1222 static void lxcapi_clear_config(struct lxc_container
*c
)
1226 lxc_conf_free(c
->lxc_conf
);
1232 static bool lxcapi_destroy(struct lxc_container
*c
);
1233 static bool container_destroy(struct lxc_container
*c
);
1234 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
1237 * create a container with the given parameters.
1238 * @c: container to be created. It has the lxcpath, name, and a starting
1239 * configuration already set
1240 * @t: the template to execute to instantiate the root filesystem and
1241 * adjust the configuration.
1242 * @bdevtype: backing store type to use. If NULL, dir will be used.
1243 * @specs: additional parameters for the backing store, i.e. LVM vg to
1246 * @argv: the arguments to pass to the template, terminated by NULL. If no
1247 * arguments, you can just pass NULL.
1249 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1250 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1262 tpath
= get_template_path(t
);
1264 ERROR("bad template: %s", t
);
1270 * If a template is passed in, and the rootfs already is defined in
1271 * the container config and exists, then * caller is trying to create
1272 * an existing container. Return an error, but do NOT delete the
1275 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1276 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1277 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1282 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1283 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1288 if (!create_container_dir(c
))
1292 * either template or rootfs.path should be set.
1293 * if both template and rootfs.path are set, template is setup as rootfs.path.
1294 * container is already created if we have a config and rootfs.path is accessible
1296 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1297 /* no template passed in and rootfs does not exist: error */
1299 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1300 /* rootfs passed into configuration, but does not exist: error */
1302 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1303 /* Rootfs already existed, user just wanted to save the
1304 * loaded configuration */
1309 /* Mark that this container is being created */
1310 if ((partial_fd
= create_partial(c
)) < 0)
1313 /* no need to get disk lock bc we have the partial locked */
1316 * Create the backing store
1317 * Note we can't do this in the same task as we use to execute the
1318 * template because of the way zfs works.
1319 * After you 'zfs create', zfs mounts the fs only in the initial
1324 SYSERROR("failed to fork task for container creation template");
1328 if (pid
== 0) { // child
1329 struct bdev
*bdev
= NULL
;
1331 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1332 ERROR("Error creating backing store type %s for %s",
1333 bdevtype
? bdevtype
: "(none)", c
->name
);
1337 /* save config file again to store the new rootfs location */
1338 if (!c
->save_config(c
, NULL
)) {
1339 ERROR("failed to save starting configuration for %s", c
->name
);
1340 // parent task won't see bdev in config so we delete it
1341 bdev
->ops
->umount(bdev
);
1342 bdev
->ops
->destroy(bdev
);
1347 if (wait_for_pid(pid
) != 0)
1350 /* reload config to get the rootfs */
1351 lxc_conf_free(c
->lxc_conf
);
1353 if (!load_config_locked(c
, c
->configfile
))
1356 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1359 // now clear out the lxc_conf we have, reload from the created
1361 lxcapi_clear_config(c
);
1364 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1365 ERROR("Error prepending header to configuration file");
1369 ret
= load_config_locked(c
, c
->configfile
);
1372 if (partial_fd
>= 0)
1373 remove_partial(c
, partial_fd
);
1376 container_destroy(c
);
1383 static bool lxcapi_reboot(struct lxc_container
*c
)
1389 if (!c
->is_running(c
))
1391 pid
= c
->init_pid(c
);
1394 if (kill(pid
, SIGINT
) < 0)
1400 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1404 int haltsignal
= SIGPWR
;
1409 if (!c
->is_running(c
))
1411 pid
= c
->init_pid(c
);
1414 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1415 haltsignal
= c
->lxc_conf
->haltsignal
;
1416 kill(pid
, haltsignal
);
1417 retv
= c
->wait(c
, "STOPPED", timeout
);
1421 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1422 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1432 * since we're going to wait for create to finish, I don't think we
1433 * need to get a copy of the arguments.
1435 va_start(ap
, flags
);
1436 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1439 ERROR("Memory allocation error.");
1443 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1450 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
1452 if (strcmp(key
, "lxc.cgroup") == 0)
1453 clear_unexp_config_line(conf
, key
, true);
1454 else if (strcmp(key
, "lxc.network") == 0)
1455 clear_unexp_config_line(conf
, key
, true);
1456 else if (strcmp(key
, "lxc.hook") == 0)
1457 clear_unexp_config_line(conf
, key
, true);
1459 clear_unexp_config_line(conf
, key
, false);
1460 if (!do_append_unexp_config_line(conf
, key
, ""))
1461 WARN("Error clearing configuration for %s", key
);
1464 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1468 if (!c
|| !c
->lxc_conf
)
1470 if (container_mem_lock(c
))
1472 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1474 do_clear_unexp_config_line(c
->lxc_conf
, key
);
1475 container_mem_unlock(c
);
1479 static inline bool enter_to_ns(struct lxc_container
*c
)
1481 pid_t pid
= c
->init_pid(c
);
1483 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1484 if (!switch_to_ns(pid
, "user"))
1487 return switch_to_ns(pid
, "net");
1490 // used by qsort and bsearch functions for comparing names
1491 static inline int string_cmp(char **first
, char **second
)
1493 return strcmp(*first
, *second
);
1496 // used by qsort and bsearch functions for comparing container names
1497 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1499 return strcmp((*first
)->name
, (*second
)->name
);
1502 static bool add_to_array(char ***names
, char *cname
, int pos
)
1504 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1506 ERROR("Out of memory");
1511 newnames
[pos
] = strdup(cname
);
1515 // sort the arrray as we will use binary search on it
1516 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1521 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1523 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1525 ERROR("Out of memory");
1532 // sort the arrray as we will use binary search on it
1534 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1539 static char** get_from_array(char ***names
, char *cname
, int size
)
1541 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1545 static bool array_contains(char ***names
, char *cname
, int size
) {
1546 if(get_from_array(names
, cname
, size
) != NULL
)
1551 static bool remove_from_array(char ***names
, char *cname
, int size
)
1553 char **result
= get_from_array(names
, cname
, size
);
1554 if (result
!= NULL
) {
1561 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1564 int i
, count
= 0, pipefd
[2];
1565 char **interfaces
= NULL
;
1566 char interface
[IFNAMSIZ
];
1568 if(pipe(pipefd
) < 0) {
1569 SYSERROR("pipe failed");
1575 SYSERROR("failed to fork task to get interfaces information");
1581 if (pid
== 0) { // child
1582 int ret
= 1, nbytes
;
1583 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1585 /* close the read-end of the pipe */
1588 if (!enter_to_ns(c
)) {
1589 SYSERROR("failed to enter namespace");
1593 /* Grab the list of interfaces */
1594 if (getifaddrs(&interfaceArray
)) {
1595 SYSERROR("failed to get interfaces list");
1599 /* Iterate through the interfaces */
1600 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1601 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1603 ERROR("write failed");
1612 freeifaddrs(interfaceArray
);
1614 /* close the write-end of the pipe, thus sending EOF to the reader */
1619 /* close the write-end of the pipe */
1622 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1623 if (array_contains(&interfaces
, interface
, count
))
1626 if(!add_to_array(&interfaces
, interface
, count
))
1627 ERROR("PARENT: add_to_array failed");
1631 if (wait_for_pid(pid
) != 0) {
1632 for(i
=0;i
<count
;i
++)
1633 free(interfaces
[i
]);
1638 /* close the read-end of the pipe */
1641 /* Append NULL to the array */
1643 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1648 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1651 int i
, count
= 0, pipefd
[2];
1652 char **addresses
= NULL
;
1653 char address
[INET6_ADDRSTRLEN
];
1655 if(pipe(pipefd
) < 0) {
1656 SYSERROR("pipe failed");
1662 SYSERROR("failed to fork task to get container ips");
1668 if (pid
== 0) { // child
1669 int ret
= 1, nbytes
;
1670 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1671 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1672 void *tempAddrPtr
= NULL
;
1673 char *address
= NULL
;
1675 /* close the read-end of the pipe */
1678 if (!enter_to_ns(c
)) {
1679 SYSERROR("failed to enter namespace");
1683 /* Grab the list of interfaces */
1684 if (getifaddrs(&interfaceArray
)) {
1685 SYSERROR("failed to get interfaces list");
1689 /* Iterate through the interfaces */
1690 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1691 if (tempIfAddr
->ifa_addr
== NULL
)
1694 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1695 if (family
&& strcmp(family
, "inet"))
1697 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1700 if (family
&& strcmp(family
, "inet6"))
1703 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1706 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1709 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1711 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1714 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1716 addressOutputBuffer
,
1717 sizeof(addressOutputBuffer
));
1721 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1723 ERROR("write failed");
1732 freeifaddrs(interfaceArray
);
1734 /* close the write-end of the pipe, thus sending EOF to the reader */
1739 /* close the write-end of the pipe */
1742 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1743 if(!add_to_array(&addresses
, address
, count
))
1744 ERROR("PARENT: add_to_array failed");
1748 if (wait_for_pid(pid
) != 0) {
1749 for(i
=0;i
<count
;i
++)
1755 /* close the read-end of the pipe */
1758 /* Append NULL to the array */
1760 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1765 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1769 if (!c
|| !c
->lxc_conf
)
1771 if (container_mem_lock(c
))
1773 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1774 container_mem_unlock(c
);
1778 static char* lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
1782 if (!c
|| !c
->lxc_conf
)
1784 if (container_mem_lock(c
))
1786 ret
= lxc_cmd_get_config_item(c
->name
, key
, c
->get_config_path(c
));
1787 container_mem_unlock(c
);
1791 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1794 return lxc_listconfigs(retv
, inlen
);
1796 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1797 * This is an intelligent result to show which keys are valid given
1798 * the type of nic it is
1800 if (!c
|| !c
->lxc_conf
)
1802 if (container_mem_lock(c
))
1805 if (strncmp(key
, "lxc.network.", 12) == 0)
1806 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1807 container_mem_unlock(c
);
1811 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1814 bool ret
= false, need_disklock
= false;
1818 alt_file
= c
->configfile
;
1820 return false; // should we write to stdout if no file is specified?
1822 // If we haven't yet loaded a config, load the stock config
1824 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1825 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
1830 if (!create_container_dir(c
))
1834 * If we're writing to the container's config file, take the
1835 * disk lock. Otherwise just take the memlock to protect the
1836 * struct lxc_container while we're traversing it.
1838 if (strcmp(c
->configfile
, alt_file
) == 0)
1839 need_disklock
= true;
1842 lret
= container_disk_lock(c
);
1844 lret
= container_mem_lock(c
);
1849 fout
= fopen(alt_file
, "w");
1852 write_config(fout
, c
->lxc_conf
);
1858 container_disk_unlock(c
);
1860 container_mem_unlock(c
);
1864 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1866 char path
[MAXPATHLEN
];
1871 if (container_disk_lock(c
))
1873 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1875 if (ret
< 0 || ret
> MAXPATHLEN
)
1877 f
= fopen(path
, "r");
1879 ret
= fscanf(f
, "%d", &v
);
1882 ERROR("Corrupted file %s", path
);
1887 f
= fopen(path
, "w");
1890 if (fprintf(f
, "%d\n", v
) < 0) {
1891 ERROR("Error writing new snapshots value");
1897 SYSERROR("Error writing to or closing snapshots file");
1904 container_disk_unlock(c
);
1908 static void strip_newline(char *p
)
1910 size_t len
= strlen(p
);
1913 if (p
[len
-1] == '\n')
1917 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1919 struct lxc_container
*p
;
1920 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1921 size_t pathlen
= 0, namelen
= 0;
1925 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1926 c
->config_path
, c
->name
);
1927 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1928 ERROR("Path name too long");
1931 f
= fopen(path
, "r");
1934 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1935 if (getline(&lxcname
, &namelen
, f
) == -1) {
1936 ERROR("badly formatted file %s", path
);
1939 strip_newline(lxcpath
);
1940 strip_newline(lxcname
);
1941 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1942 ERROR("Unable to find dependent container %s:%s",
1946 if (!mod_rdep(p
, inc
))
1947 ERROR("Failed to increase numsnapshots for %s:%s",
1949 lxc_container_put(p
);
1952 if (lxcpath
) free(lxcpath
);
1953 if (lxcname
) free(lxcname
);
1957 static bool has_fs_snapshots(struct lxc_container
*c
)
1959 char path
[MAXPATHLEN
];
1964 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1966 if (ret
< 0 || ret
> MAXPATHLEN
)
1968 f
= fopen(path
, "r");
1971 ret
= fscanf(f
, "%d", &v
);
1981 static bool has_snapshots(struct lxc_container
*c
)
1983 char path
[MAXPATHLEN
];
1984 struct dirent dirent
, *direntp
;
1988 if (!get_snappath_dir(c
, path
))
1990 dir
= opendir(path
);
1993 while (!readdir_r(dir
, &dirent
, &direntp
)) {
1997 if (!strcmp(direntp
->d_name
, "."))
2000 if (!strcmp(direntp
->d_name
, ".."))
2009 static int lxc_rmdir_onedev_wrapper(void *data
)
2011 char *arg
= (char *) data
;
2012 return lxc_rmdir_onedev(arg
, "snaps");
2015 static int do_bdev_destroy(struct lxc_conf
*conf
)
2020 r
= bdev_init(conf
, conf
->rootfs
.path
, conf
->rootfs
.mount
, NULL
);
2024 if (r
->ops
->destroy(r
) < 0)
2030 static int bdev_destroy_wrapper(void *data
)
2032 struct lxc_conf
*conf
= data
;
2034 if (setgid(0) < 0) {
2035 ERROR("Failed to setgid to 0");
2038 if (setgroups(0, NULL
) < 0)
2039 WARN("Failed to clear groups");
2040 if (setuid(0) < 0) {
2041 ERROR("Failed to setuid to 0");
2044 return do_bdev_destroy(conf
);
2047 static bool container_destroy(struct lxc_container
*c
)
2052 if (!c
|| !lxcapi_is_defined(c
))
2055 if (container_disk_lock(c
))
2058 if (!is_stopped(c
)) {
2059 // we should queue some sort of error - in c->error_string?
2060 ERROR("container %s is not stopped", c
->name
);
2064 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
2066 ret
= userns_exec_1(c
->lxc_conf
, bdev_destroy_wrapper
, c
->lxc_conf
);
2068 ret
= do_bdev_destroy(c
->lxc_conf
);
2070 ERROR("Error destroying rootfs for %s", c
->name
);
2075 mod_all_rdeps(c
, false);
2077 const char *p1
= lxcapi_get_config_path(c
);
2078 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2079 sprintf(path
, "%s/%s", p1
, c
->name
);
2081 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
2083 ret
= lxc_rmdir_onedev(path
, "snaps");
2085 ERROR("Error destroying container directory for %s", c
->name
);
2091 container_disk_unlock(c
);
2095 static bool lxcapi_destroy(struct lxc_container
*c
)
2097 if (!c
|| !lxcapi_is_defined(c
))
2099 if (has_snapshots(c
)) {
2100 ERROR("Container %s has snapshots; not removing", c
->name
);
2104 if (has_fs_snapshots(c
)) {
2105 ERROR("container %s has snapshots on its rootfs", c
->name
);
2109 return container_destroy(c
);
2112 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
2114 static bool lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2116 if (!c
|| !lxcapi_is_defined(c
))
2118 if (!lxcapi_snapshot_destroy_all(c
)) {
2119 ERROR("Error deleting all snapshots");
2122 return lxcapi_destroy(c
);
2125 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2127 struct lxc_config_t
*config
;
2130 c
->lxc_conf
= lxc_conf_init();
2133 config
= lxc_getconfig(key
);
2136 if (config
->cb(key
, v
, c
->lxc_conf
) != 0)
2138 return do_append_unexp_config_line(c
->lxc_conf
, key
, v
);
2141 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2148 if (container_mem_lock(c
))
2151 b
= set_config_item_locked(c
, key
, v
);
2153 container_mem_unlock(c
);
2157 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2159 if (!c
|| !c
->configfile
)
2161 return strdup(c
->configfile
);
2164 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2166 if (!c
|| !c
->config_path
)
2168 return (const char *)(c
->config_path
);
2173 * Just recalculate the c->configfile based on the
2174 * c->config_path, which must be set.
2175 * The lxc_container must be locked or not yet public.
2177 static bool set_config_filename(struct lxc_container
*c
)
2182 if (!c
->config_path
)
2185 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2186 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2187 newpath
= malloc(len
);
2191 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2192 if (ret
< 0 || ret
>= len
) {
2193 fprintf(stderr
, "Error printing out config file name\n");
2199 free(c
->configfile
);
2200 c
->configfile
= newpath
;
2205 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2209 char *oldpath
= NULL
;
2214 if (container_mem_lock(c
))
2219 ERROR("Out of memory setting new lxc path");
2225 oldpath
= c
->config_path
;
2228 /* Since we've changed the config path, we have to change the
2229 * config file name too */
2230 if (!set_config_filename(c
)) {
2231 ERROR("Out of memory setting new config filename");
2233 free(c
->config_path
);
2234 c
->config_path
= oldpath
;
2240 container_mem_unlock(c
);
2245 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2255 if (container_disk_lock(c
))
2258 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2260 container_disk_unlock(c
);
2264 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2274 if (container_disk_lock(c
))
2277 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2279 container_disk_unlock(c
);
2283 const char *lxc_get_global_config_item(const char *key
)
2285 return lxc_global_config_value(key
);
2288 const char *lxc_get_version(void)
2293 static int copy_file(const char *old
, const char *new)
2300 if (file_exists(new)) {
2301 ERROR("copy destination %s exists", new);
2304 ret
= stat(old
, &sbuf
);
2306 INFO("Error stat'ing %s", old
);
2310 in
= open(old
, O_RDONLY
);
2312 SYSERROR("Error opening original file %s", old
);
2315 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2317 SYSERROR("Error opening new file %s", new);
2323 len
= read(in
, buf
, 8096);
2325 SYSERROR("Error reading old file %s", old
);
2330 ret
= write(out
, buf
, len
);
2331 if (ret
< len
) { // should we retry?
2332 SYSERROR("Error: write to new file %s was interrupted", new);
2339 // we set mode, but not owner/group
2340 ret
= chmod(new, sbuf
.st_mode
);
2342 SYSERROR("Error setting mode on %s", new);
2354 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2357 struct lxc_list
*it
;
2360 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2361 cpath
= alloca(len
);
2362 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2363 if (ret
< 0 || ret
>= len
)
2366 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2367 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2368 char *hookname
= it
->elem
;
2369 char *fname
= strrchr(hookname
, '/');
2370 char tmppath
[MAXPATHLEN
];
2371 if (!fname
) // relative path - we don't support, but maybe we should
2373 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2374 // this hook is public - ignore
2377 // copy the script, and change the entry in confile
2378 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2379 c
->config_path
, c
->name
, fname
+1);
2380 if (ret
< 0 || ret
>= MAXPATHLEN
)
2382 ret
= copy_file(it
->elem
, tmppath
);
2386 it
->elem
= strdup(tmppath
);
2388 ERROR("out of memory copying hook path");
2394 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
2395 c
->config_path
, oldc
->name
, c
->name
)) {
2396 ERROR("Error saving new hooks in clone");
2399 c
->save_config(c
, NULL
);
2404 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2406 char newpath
[MAXPATHLEN
];
2407 char *oldpath
= oldc
->lxc_conf
->fstab
;
2413 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount", false);
2415 char *p
= strrchr(oldpath
, '/');
2418 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2419 c
->config_path
, c
->name
, p
);
2420 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2421 ERROR("error printing new path for %s", oldpath
);
2424 if (file_exists(newpath
)) {
2425 ERROR("error: fstab file %s exists", newpath
);
2429 if (copy_file(oldpath
, newpath
) < 0) {
2430 ERROR("error: copying %s to %s", oldpath
, newpath
);
2433 free(c
->lxc_conf
->fstab
);
2434 c
->lxc_conf
->fstab
= strdup(newpath
);
2435 if (!c
->lxc_conf
->fstab
) {
2436 ERROR("error: allocating pathname");
2439 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount", newpath
)) {
2440 ERROR("error saving new lxctab");
2447 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2449 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2452 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2454 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2455 WARN("Error copying reverse dependencies");
2458 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2460 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2461 WARN("Error copying reverse dependencies");
2464 if (copy_file(path0
, path1
) < 0) {
2465 INFO("Error copying reverse dependencies");
2470 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2473 char path
[MAXPATHLEN
];
2477 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2479 if (ret
< 0 || ret
>= MAXPATHLEN
)
2481 f
= fopen(path
, "a");
2485 // if anything goes wrong, just return an error
2486 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2493 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2494 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2499 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
2500 bdevdata
, newsize
, &need_rdep
);
2502 ERROR("Error copying storage");
2505 free(c
->lxc_conf
->rootfs
.path
);
2506 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2508 if (!c
->lxc_conf
->rootfs
.path
) {
2509 ERROR("Out of memory while setting storage path");
2512 // We will simply append a new lxc.rootfs entry to the unexpanded config
2513 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
2514 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", c
->lxc_conf
->rootfs
.path
)) {
2515 ERROR("Error saving new rootfs to cloend config");
2518 if (flags
& LXC_CLONE_SNAPSHOT
)
2519 copy_rdepends(c
, c0
);
2521 if (!add_rdepends(c
, c0
))
2522 WARN("Error adding reverse dependency from %s to %s",
2526 mod_all_rdeps(c
, true);
2531 struct clone_update_data
{
2532 struct lxc_container
*c0
;
2533 struct lxc_container
*c1
;
2538 static int clone_update_rootfs(struct clone_update_data
*data
)
2540 struct lxc_container
*c0
= data
->c0
;
2541 struct lxc_container
*c
= data
->c1
;
2542 int flags
= data
->flags
;
2543 char **hookargs
= data
->hookargs
;
2545 char path
[MAXPATHLEN
];
2548 struct lxc_conf
*conf
= c
->lxc_conf
;
2550 /* update hostname in rootfs */
2551 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2553 if (setgid(0) < 0) {
2554 ERROR("Failed to setgid to 0");
2557 if (setuid(0) < 0) {
2558 ERROR("Failed to setuid to 0");
2561 if (setgroups(0, NULL
) < 0)
2562 WARN("Failed to clear groups");
2564 if (unshare(CLONE_NEWNS
) < 0)
2566 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2569 if (strcmp(bdev
->type
, "dir") != 0) {
2570 if (unshare(CLONE_NEWNS
) < 0) {
2571 ERROR("error unsharing mounts");
2575 if (detect_shared_rootfs()) {
2576 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2577 SYSERROR("Failed to make / rslave");
2578 ERROR("Continuing...");
2581 if (bdev
->ops
->mount(bdev
) < 0) {
2585 } else { // TODO come up with a better way
2588 bdev
->dest
= strdup(bdev
->src
);
2591 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2592 /* Start of environment variable setup for hooks */
2593 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2594 SYSERROR("failed to set environment variable for source container name");
2596 if (setenv("LXC_NAME", c
->name
, 1)) {
2597 SYSERROR("failed to set environment variable for container name");
2599 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2600 SYSERROR("failed to set environment variable for config path");
2602 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2603 SYSERROR("failed to set environment variable for rootfs mount");
2605 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2606 SYSERROR("failed to set environment variable for rootfs mount");
2609 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2610 ERROR("Error executing clone hook for %s", c
->name
);
2616 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2617 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2620 if (ret
< 0 || ret
>= MAXPATHLEN
)
2622 if (!file_exists(path
))
2624 if (!(fout
= fopen(path
, "w"))) {
2625 SYSERROR("unable to open %s: ignoring", path
);
2628 if (fprintf(fout
, "%s", c
->name
) < 0) {
2632 if (fclose(fout
) < 0)
2641 static int clone_update_rootfs_wrapper(void *data
)
2643 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
2644 return clone_update_rootfs(arg
);
2648 * We want to support:
2649 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2650 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2652 -s [ implies overlayfs]
2656 only rootfs gets converted (copied/snapshotted) on clone.
2659 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
2661 char *p
= strrchr(path
, '/');
2667 ret
= do_create_container_dir(path
, conf
);
2672 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2673 const char *lxcpath
, int flags
,
2674 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2677 struct lxc_container
*c2
= NULL
;
2678 char newpath
[MAXPATHLEN
];
2679 int ret
, storage_copied
= 0;
2680 char *origroot
= NULL
;
2681 struct clone_update_data data
;
2685 if (!c
|| !c
->is_defined(c
))
2688 if (container_mem_lock(c
))
2691 if (!is_stopped(c
)) {
2692 ERROR("error: Original container (%s) is running", c
->name
);
2696 // Make sure the container doesn't yet exist.
2700 lxcpath
= c
->get_config_path(c
);
2701 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
2702 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2703 SYSERROR("clone: failed making config pathname");
2706 if (file_exists(newpath
)) {
2707 ERROR("error: clone: %s exists", newpath
);
2711 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
2712 if (ret
< 0 && errno
!= EEXIST
) {
2713 ERROR("Error creating container dir for %s", newpath
);
2717 // copy the configuration, tweak it as needed,
2718 if (c
->lxc_conf
->rootfs
.path
) {
2719 origroot
= c
->lxc_conf
->rootfs
.path
;
2720 c
->lxc_conf
->rootfs
.path
= NULL
;
2722 fout
= fopen(newpath
, "w");
2724 SYSERROR("open %s", newpath
);
2727 write_config(fout
, c
->lxc_conf
);
2729 c
->lxc_conf
->rootfs
.path
= origroot
;
2731 sprintf(newpath
, "%s/%s/rootfs", lxcpath
, newname
);
2732 if (mkdir(newpath
, 0755) < 0) {
2733 SYSERROR("error creating %s", newpath
);
2738 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
2739 ERROR("Error chowning %s to container root", newpath
);
2744 c2
= lxc_container_new(newname
, lxcpath
);
2746 ERROR("clone: failed to create new container (%s %s)", newname
,
2751 // copy/snapshot rootfs's
2752 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2756 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
2759 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2760 ERROR("Error setting new hostname");
2765 ret
= copyhooks(c
, c2
);
2767 ERROR("error copying hooks");
2771 if (copy_fstab(c
, c2
) < 0) {
2772 ERROR("error copying fstab");
2777 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
2778 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
2779 ERROR("Error updating mac addresses");
2784 // We've now successfully created c2's storage, so clear it out if we
2788 if (!c2
->save_config(c2
, NULL
))
2791 if ((pid
= fork()) < 0) {
2796 ret
= wait_for_pid(pid
);
2799 container_mem_unlock(c
);
2805 data
.hookargs
= hookargs
;
2807 ret
= userns_exec_1(c
->lxc_conf
, clone_update_rootfs_wrapper
,
2810 ret
= clone_update_rootfs(&data
);
2814 container_mem_unlock(c
);
2818 container_mem_unlock(c
);
2820 if (!storage_copied
)
2821 c2
->lxc_conf
->rootfs
.path
= NULL
;
2823 lxc_container_put(c2
);
2829 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2832 struct lxc_container
*newc
;
2834 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
2837 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
2838 ERROR("Renaming a container with snapshots is not supported");
2841 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2843 ERROR("Failed to find original backing store type");
2847 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2850 lxc_container_put(newc
);
2854 if (newc
&& lxcapi_is_defined(newc
))
2855 lxc_container_put(newc
);
2857 if (!container_destroy(c
)) {
2858 ERROR("Could not destroy existing container %s", c
->name
);
2864 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
)
2869 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2872 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2874 lxc_attach_command_t command
;
2881 command
.program
= (char*)program
;
2882 command
.argv
= (char**)argv
;
2883 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2888 return lxc_wait_for_pid_status(pid
);
2891 static int get_next_index(const char *lxcpath
, char *cname
)
2897 fname
= alloca(strlen(lxcpath
) + 20);
2899 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2900 ret
= stat(fname
, &sb
);
2907 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
2911 * If the old style snapshot path exists, use it
2912 * /var/lib/lxc -> /var/lib/lxcsnaps
2914 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
2915 if (ret
< 0 || ret
>= MAXPATHLEN
)
2917 if (dir_exists(snappath
)) {
2918 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2919 if (ret
< 0 || ret
>= MAXPATHLEN
)
2925 * Use the new style path
2926 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
2928 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
2929 if (ret
< 0 || ret
>= MAXPATHLEN
)
2934 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2937 struct lxc_container
*c2
;
2938 char snappath
[MAXPATHLEN
], newname
[20];
2940 if (!c
|| !lxcapi_is_defined(c
))
2943 if (!bdev_can_backup(c
->lxc_conf
)) {
2944 ERROR("%s's backing store cannot be backed up.", c
->name
);
2945 ERROR("Your container must use another backing store type.");
2949 if (!get_snappath_dir(c
, snappath
))
2952 i
= get_next_index(snappath
, c
->name
);
2954 if (mkdir_p(snappath
, 0755) < 0) {
2955 ERROR("Failed to create snapshot directory %s", snappath
);
2959 ret
= snprintf(newname
, 20, "snap%d", i
);
2960 if (ret
< 0 || ret
>= 20)
2964 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2965 * created in the original container
2967 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2968 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2969 if (bdev_is_dir(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
)) {
2970 ERROR("Snapshot of directory-backed container requested.");
2971 ERROR("Making a copy-clone. If you do want snapshots, then");
2972 ERROR("please create an aufs or overlayfs clone first, snapshot that");
2973 ERROR("and keep the original container pristine.");
2974 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
2976 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2978 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
2982 lxc_container_put(c2
);
2984 // Now write down the creation time
2991 tm_info
= localtime(&timer
);
2993 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2995 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2996 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2997 f
= fopen(dfnam
, "w");
2999 ERROR("Failed to open %s", dfnam
);
3002 if (fprintf(f
, "%s", buffer
) < 0) {
3003 SYSERROR("Writing timestamp");
3009 SYSERROR("Writing timestamp");
3014 // $p / $name / comment \0
3015 int len
= strlen(snappath
) + strlen(newname
) + 10;
3016 char *path
= alloca(len
);
3017 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3018 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3024 static void lxcsnap_free(struct lxc_snapshot
*s
)
3028 if (s
->comment_pathname
)
3029 free(s
->comment_pathname
);
3036 static char *get_snapcomment_path(char* snappath
, char *name
)
3038 // $snappath/$name/comment
3039 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3040 char *s
= malloc(len
);
3043 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3044 if (ret
< 0 || ret
>= len
) {
3052 static char *get_timestamp(char* snappath
, char *name
)
3054 char path
[MAXPATHLEN
], *s
= NULL
;
3058 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3059 if (ret
< 0 || ret
>= MAXPATHLEN
)
3061 fin
= fopen(path
, "r");
3064 (void) fseek(fin
, 0, SEEK_END
);
3066 (void) fseek(fin
, 0, SEEK_SET
);
3071 if (fread(s
, 1, len
, fin
) != len
) {
3072 SYSERROR("reading timestamp");
3082 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3084 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3086 struct dirent dirent
, *direntp
;
3087 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3090 if (!c
|| !lxcapi_is_defined(c
))
3093 if (!get_snappath_dir(c
, snappath
)) {
3094 ERROR("path name too long");
3097 dir
= opendir(snappath
);
3099 INFO("failed to open %s - assuming no snapshots", snappath
);
3103 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3107 if (!strcmp(direntp
->d_name
, "."))
3110 if (!strcmp(direntp
->d_name
, ".."))
3113 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3114 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3115 ERROR("pathname too long");
3118 if (!file_exists(path2
))
3120 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3122 SYSERROR("Out of memory");
3126 snaps
[count
].free
= lxcsnap_free
;
3127 snaps
[count
].name
= strdup(direntp
->d_name
);
3128 if (!snaps
[count
].name
)
3130 snaps
[count
].lxcpath
= strdup(snappath
);
3131 if (!snaps
[count
].lxcpath
) {
3132 free(snaps
[count
].name
);
3135 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3136 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3141 WARN("failed to close directory");
3149 for (i
=0; i
<count
; i
++)
3150 lxcsnap_free(&snaps
[i
]);
3154 WARN("failed to close directory");
3158 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3160 char clonelxcpath
[MAXPATHLEN
];
3162 struct lxc_container
*snap
, *rest
;
3166 if (!c
|| !c
->name
|| !c
->config_path
)
3169 if (has_fs_snapshots(c
)) {
3170 ERROR("container rootfs has dependent snapshots");
3174 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3176 ERROR("Failed to find original backing store type");
3183 if (!get_snappath_dir(c
, clonelxcpath
)) {
3187 // how should we lock this?
3189 snap
= lxc_container_new(snapname
, clonelxcpath
);
3190 if (!snap
|| !lxcapi_is_defined(snap
)) {
3191 ERROR("Could not open snapshot %s", snapname
);
3192 if (snap
) lxc_container_put(snap
);
3197 if (strcmp(c
->name
, newname
) == 0) {
3198 if (!container_destroy(c
)) {
3199 ERROR("Could not destroy existing container %s", newname
);
3200 lxc_container_put(snap
);
3206 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
3207 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3208 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
,
3209 bdev
->type
, NULL
, 0, NULL
);
3211 if (rest
&& lxcapi_is_defined(rest
))
3214 lxc_container_put(rest
);
3215 lxc_container_put(snap
);
3219 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
3221 struct lxc_container
*snap
= NULL
;
3224 snap
= lxc_container_new(snapname
, clonelxcpath
);
3226 ERROR("Could not find snapshot %s", snapname
);
3230 if (!lxcapi_destroy(snap
)) {
3231 ERROR("Could not destroy snapshot %s", snapname
);
3238 lxc_container_put(snap
);
3242 static bool remove_all_snapshots(const char *path
)
3245 struct dirent dirent
, *direntp
;
3248 dir
= opendir(path
);
3250 SYSERROR("opendir on snapshot path %s", path
);
3253 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3256 if (!strcmp(direntp
->d_name
, "."))
3258 if (!strcmp(direntp
->d_name
, ".."))
3260 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
3269 SYSERROR("Error removing directory %s", path
);
3274 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3276 char clonelxcpath
[MAXPATHLEN
];
3278 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
3281 if (!get_snappath_dir(c
, clonelxcpath
))
3284 return do_snapshot_destroy(snapname
, clonelxcpath
);
3287 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
3289 char clonelxcpath
[MAXPATHLEN
];
3291 if (!c
|| !c
->name
|| !c
->config_path
)
3294 if (!get_snappath_dir(c
, clonelxcpath
))
3297 return remove_all_snapshots(clonelxcpath
);
3300 static bool lxcapi_may_control(struct lxc_container
*c
)
3302 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3305 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3308 char chrootpath
[MAXPATHLEN
];
3309 char *directory_path
= NULL
;
3313 if ((pid
= fork()) < 0) {
3314 SYSERROR("failed to fork a child helper");
3318 if (wait_for_pid(pid
) != 0) {
3319 ERROR("Failed to create note in guest");
3325 /* prepare the path */
3326 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3327 if (ret
< 0 || ret
>= MAXPATHLEN
)
3330 if (chroot(chrootpath
) < 0)
3334 /* remove path if it exists */
3335 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3336 if (unlink(path
) < 0) {
3337 ERROR("unlink failed");
3344 /* create any missing directories */
3345 directory_path
= dirname(strdup(path
));
3346 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3347 ERROR("failed to create directory");
3351 /* create the device node */
3352 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3353 ERROR("mknod failed");
3360 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3364 char value
[MAX_BUFFER
];
3367 /* make sure container is running */
3368 if (!c
->is_running(c
)) {
3369 ERROR("container is not running");
3373 /* use src_path if dest_path is NULL otherwise use dest_path */
3374 p
= dest_path
? dest_path
: src_path
;
3376 /* make sure we can access p */
3377 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3380 /* continue if path is character device or block device */
3381 if (S_ISCHR(st
.st_mode
))
3382 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3383 else if (S_ISBLK(st
.st_mode
))
3384 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3388 /* check snprintf return code */
3389 if (ret
< 0 || ret
>= MAX_BUFFER
)
3392 if (!do_add_remove_node(c
->init_pid(c
), p
, add
, &st
))
3395 /* add or remove device to/from cgroup access list */
3397 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3398 ERROR("set_cgroup_item failed while adding the device node");
3402 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3403 ERROR("set_cgroup_item failed while removing the device node");
3411 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3414 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3417 return add_remove_device_node(c
, src_path
, dest_path
, true);
3420 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3423 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3426 return add_remove_device_node(c
, src_path
, dest_path
, false);
3430 /* The type of criu invocation, one of "dump" or "restore" */
3433 /* The directory to pass to criu */
3436 /* The container to dump */
3437 struct lxc_container
*c
;
3439 /* Enable criu verbose mode? */
3442 /* dump: stop the container or not after dumping? */
3445 /* restore: the file to write the init process' pid into */
3447 const char *cgroup_path
;
3451 * @out must be 128 bytes long
3453 static int read_criu_file(const char *directory
, const char *file
, int netnr
, char *out
)
3455 char path
[PATH_MAX
];
3459 ret
= snprintf(path
, PATH_MAX
, "%s/%s%d", directory
, file
, netnr
);
3460 if (ret
< 0 || ret
>= PATH_MAX
) {
3461 ERROR("%s: path too long", __func__
);
3465 f
= fopen(path
, "r");
3469 ret
= fscanf(f
, "%127s", out
);
3477 static void exec_criu(struct criu_opts
*opts
)
3479 char **argv
, log
[PATH_MAX
];
3480 int static_args
= 14, argc
= 0, i
, ret
;
3482 /* The command line always looks like:
3483 * criu $(action) --tcp-established --file-locks --link-remap --force-irmap \
3484 * --manage-cgroups action-script foo.sh -D $(directory) \
3485 * -o $(directory)/$(action).log
3486 * +1 for final NULL */
3488 if (strcmp(opts
->action
, "dump") == 0) {
3492 /* --leave-running */
3495 } else if (strcmp(opts
->action
, "restore") == 0) {
3496 /* --root $(lxc_mount_point) --restore-detached
3497 * --restore-sibling --pidfile $foo --cgroup-root $foo */
3506 ret
= snprintf(log
, PATH_MAX
, "%s/%s.log", opts
->directory
, opts
->action
);
3507 if (ret
< 0 || ret
>= PATH_MAX
) {
3508 ERROR("logfile name too long\n");
3512 argv
= malloc(static_args
* sizeof(*argv
));
3516 memset(argv
, 0, static_args
* sizeof(*argv
));
3518 #define DECLARE_ARG(arg) \
3520 if (arg == NULL) { \
3521 ERROR("Got NULL argument for criu"); \
3524 argv[argc++] = strdup(arg); \
3525 if (!argv[argc-1]) \
3529 argv
[argc
++] = on_path("criu", NULL
);
3530 if (!argv
[argc
-1]) {
3531 ERROR("Couldn't find criu binary\n");
3535 DECLARE_ARG(opts
->action
);
3536 DECLARE_ARG("--tcp-established");
3537 DECLARE_ARG("--file-locks");
3538 DECLARE_ARG("--link-remap");
3539 DECLARE_ARG("--force-irmap");
3540 DECLARE_ARG("--manage-cgroups");
3541 DECLARE_ARG("--action-script");
3542 DECLARE_ARG(LIBEXECDIR
"/lxc/lxc-restore-net");
3544 DECLARE_ARG(opts
->directory
);
3549 DECLARE_ARG("-vvvvvv");
3551 if (strcmp(opts
->action
, "dump") == 0) {
3554 if (sprintf(pid
, "%d", lxcapi_init_pid(opts
->c
)) < 0)
3560 DECLARE_ARG("--leave-running");
3561 } else if (strcmp(opts
->action
, "restore") == 0) {
3563 struct lxc_list
*it
;
3565 DECLARE_ARG("--root");
3566 DECLARE_ARG(opts
->c
->lxc_conf
->rootfs
.mount
);
3567 DECLARE_ARG("--restore-detached");
3568 DECLARE_ARG("--restore-sibling");
3569 DECLARE_ARG("--pidfile");
3570 DECLARE_ARG(opts
->pidfile
);
3571 DECLARE_ARG("--cgroup-root");
3572 DECLARE_ARG(opts
->cgroup_path
);
3574 lxc_list_for_each(it
, &opts
->c
->lxc_conf
->network
) {
3575 char eth
[128], veth
[128], buf
[257];
3578 if (read_criu_file(opts
->directory
, "veth", netnr
, veth
))
3580 if (read_criu_file(opts
->directory
, "eth", netnr
, eth
))
3582 ret
= snprintf(buf
, 257, "%s=%s", eth
, veth
);
3583 if (ret
< 0 || ret
>= 257)
3586 /* final NULL and --veth-pair eth0:vethASDF */
3587 m
= realloc(argv
, (argc
+ 1 + 2) * sizeof(*argv
));
3592 DECLARE_ARG("--veth-pair");
3602 execv(argv
[0], argv
);
3604 for (i
= 0; argv
[i
]; i
++)
3609 /* Check and make sure the container has a configuration that we know CRIU can
3611 static bool criu_ok(struct lxc_container
*c
)
3613 struct lxc_list
*it
;
3614 bool found_deny_rule
= false;
3617 ERROR("Must be root to checkpoint\n");
3621 /* We only know how to restore containers with veth networks. */
3622 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3623 struct lxc_netdev
*n
= it
->elem
;
3624 if (n
->type
!= LXC_NET_VETH
&& n
->type
!= LXC_NET_NONE
) {
3625 ERROR("Found network that is not VETH or NONE\n");
3630 // These requirements come from http://criu.org/LXC
3631 if (c
->lxc_conf
->console
.path
&&
3632 strcmp(c
->lxc_conf
->console
.path
, "none") != 0) {
3633 ERROR("lxc.console must be none\n");
3637 if (c
->lxc_conf
->tty
!= 0) {
3638 ERROR("lxc.tty must be 0\n");
3642 lxc_list_for_each(it
, &c
->lxc_conf
->cgroup
) {
3643 struct lxc_cgroup
*cg
= it
->elem
;
3644 if (strcmp(cg
->subsystem
, "devices.deny") == 0 &&
3645 strcmp(cg
->value
, "c 5:1 rwm") == 0) {
3647 found_deny_rule
= true;
3652 if (!found_deny_rule
) {
3653 ERROR("couldn't find devices.deny = c 5:1 rwm");
3660 static bool lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
3663 struct lxc_list
*it
;
3670 if (mkdir(directory
, 0700) < 0 && errno
!= EEXIST
)
3674 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3675 char *veth
= NULL
, *bridge
= NULL
, veth_path
[PATH_MAX
], eth
[128];
3676 struct lxc_netdev
*n
= it
->elem
;
3679 pret
= snprintf(veth_path
, PATH_MAX
, "lxc.network.%d.veth.pair", netnr
);
3680 if (pret
< 0 || pret
>= PATH_MAX
) {
3685 veth
= lxcapi_get_running_config_item(c
, veth_path
);
3687 /* criu_ok() checks that all interfaces are
3688 * LXC_NET{VETH,NONE}, and VETHs should have this
3690 assert(n
->type
== LXC_NET_NONE
);
3694 pret
= snprintf(veth_path
, PATH_MAX
, "lxc.network.%d.link", netnr
);
3695 if (pret
< 0 || pret
>= PATH_MAX
) {
3700 bridge
= lxcapi_get_running_config_item(c
, veth_path
);
3706 pret
= snprintf(veth_path
, PATH_MAX
, "%s/veth%d", directory
, netnr
);
3707 if (pret
< 0 || pret
>= PATH_MAX
|| print_to_file(veth_path
, veth
) < 0) {
3712 pret
= snprintf(veth_path
, PATH_MAX
, "%s/bridge%d", directory
, netnr
);
3713 if (pret
< 0 || pret
>= PATH_MAX
|| print_to_file(veth_path
, bridge
) < 0) {
3719 if (strlen(n
->name
) >= 128) {
3723 strncpy(eth
, n
->name
, 128);
3725 sprintf(eth
, "eth%d", netnr
);
3727 pret
= snprintf(veth_path
, PATH_MAX
, "%s/eth%d", directory
, netnr
);
3728 if (pret
< 0 || pret
>= PATH_MAX
|| print_to_file(veth_path
, eth
) < 0)
3743 struct criu_opts os
;
3746 os
.directory
= directory
;
3749 os
.verbose
= verbose
;
3751 /* exec_criu() returning is an error */
3755 pid_t w
= waitpid(pid
, &status
, 0);
3761 if (WIFEXITED(status
)) {
3762 return !WEXITSTATUS(status
);
3769 static bool lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
3772 struct lxc_list
*it
;
3773 struct lxc_rootfs
*rootfs
;
3774 char pidfile
[L_tmpnam
];
3775 struct lxc_handler
*handler
;
3776 bool has_error
= true;
3782 ERROR("Must be root to restore\n");
3786 if (!tmpnam(pidfile
))
3789 handler
= lxc_init(c
->name
, c
->lxc_conf
, c
->config_path
);
3793 if (!cgroup_init(handler
)) {
3794 ERROR("failed initing cgroups");
3795 goto out_fini_handler
;
3798 if (!cgroup_create(handler
)) {
3799 ERROR("failed creating groups");
3800 goto out_fini_handler
;
3805 goto out_fini_handler
;
3808 struct criu_opts os
;
3810 if (unshare(CLONE_NEWNS
))
3813 /* CRIU needs the lxc root bind mounted so that it is the root of some
3815 rootfs
= &c
->lxc_conf
->rootfs
;
3817 if (rootfs_is_blockdev(c
->lxc_conf
)) {
3818 if (do_rootfs_setup(c
->lxc_conf
, c
->name
, c
->config_path
) < 0)
3822 if (mkdir(rootfs
->mount
, 0755) < 0 && errno
!= EEXIST
)
3825 if (mount(rootfs
->path
, rootfs
->mount
, NULL
, MS_BIND
, NULL
) < 0) {
3826 rmdir(rootfs
->mount
);
3831 os
.action
= "restore";
3832 os
.directory
= directory
;
3834 os
.pidfile
= pidfile
;
3835 os
.verbose
= verbose
;
3836 os
.cgroup_path
= cgroup_canonical_path(handler
);
3838 /* exec_criu() returning is an error */
3840 umount(rootfs
->mount
);
3841 rmdir(rootfs
->mount
);
3846 pid_t w
= waitpid(pid
, &status
, 0);
3850 goto out_fini_handler
;
3853 if (WIFEXITED(status
)) {
3854 if (WEXITSTATUS(status
)) {
3855 goto out_fini_handler
;
3859 FILE *f
= fopen(pidfile
, "r");
3861 perror("reading pidfile");
3862 ERROR("couldn't read restore's init pidfile %s\n", pidfile
);
3863 goto out_fini_handler
;
3866 ret
= fscanf(f
, "%d", (int*) &handler
->pid
);
3869 ERROR("reading restore pid failed");
3870 goto out_fini_handler
;
3873 if (container_mem_lock(c
))
3874 goto out_fini_handler
;
3876 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3877 char eth
[128], veth
[128];
3878 struct lxc_netdev
*netdev
= it
->elem
;
3880 if (read_criu_file(directory
, "veth", netnr
, veth
)) {
3881 container_mem_unlock(c
);
3882 goto out_fini_handler
;
3885 if (read_criu_file(directory
, "eth", netnr
, eth
)) {
3886 container_mem_unlock(c
);
3887 goto out_fini_handler
;
3890 netdev
->priv
.veth_attr
.pair
= strdup(veth
);
3891 if (!netdev
->priv
.veth_attr
.pair
) {
3892 container_mem_unlock(c
);
3893 goto out_fini_handler
;
3899 container_mem_unlock(c
);
3901 if (lxc_set_state(c
->name
, handler
, RUNNING
))
3902 goto out_fini_handler
;
3905 ERROR("CRIU was killed with signal %d\n", WTERMSIG(status
));
3906 goto out_fini_handler
;
3909 if (lxc_poll(c
->name
, handler
)) {
3910 lxc_abort(c
->name
, handler
);
3911 goto out_fini_handler
;
3918 lxc_fini(c
->name
, handler
);
3922 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
3932 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
3936 ERROR("Memory allocation error.");
3941 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3946 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3948 struct lxc_container
*c
;
3953 c
= malloc(sizeof(*c
));
3955 fprintf(stderr
, "failed to malloc lxc_container\n");
3958 memset(c
, 0, sizeof(*c
));
3961 c
->config_path
= strdup(configpath
);
3963 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
3965 if (!c
->config_path
) {
3966 fprintf(stderr
, "Out of memory\n");
3970 remove_trailing_slashes(c
->config_path
);
3971 c
->name
= malloc(strlen(name
)+1);
3973 fprintf(stderr
, "Error allocating lxc_container name\n");
3976 strcpy(c
->name
, name
);
3979 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3980 fprintf(stderr
, "failed to create lock\n");
3984 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3985 fprintf(stderr
, "failed to alloc privlock\n");
3989 if (!set_config_filename(c
)) {
3990 fprintf(stderr
, "Error allocating config file pathname\n");
3994 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
3997 if (ongoing_create(c
) == 2) {
3998 ERROR("Error: %s creation was not completed", c
->name
);
3999 container_destroy(c
);
4000 lxcapi_clear_config(c
);
4002 c
->daemonize
= true;
4005 // assign the member functions
4006 c
->is_defined
= lxcapi_is_defined
;
4007 c
->state
= lxcapi_state
;
4008 c
->is_running
= lxcapi_is_running
;
4009 c
->freeze
= lxcapi_freeze
;
4010 c
->unfreeze
= lxcapi_unfreeze
;
4011 c
->console
= lxcapi_console
;
4012 c
->console_getfd
= lxcapi_console_getfd
;
4013 c
->init_pid
= lxcapi_init_pid
;
4014 c
->load_config
= lxcapi_load_config
;
4015 c
->want_daemonize
= lxcapi_want_daemonize
;
4016 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4017 c
->start
= lxcapi_start
;
4018 c
->startl
= lxcapi_startl
;
4019 c
->stop
= lxcapi_stop
;
4020 c
->config_file_name
= lxcapi_config_file_name
;
4021 c
->wait
= lxcapi_wait
;
4022 c
->set_config_item
= lxcapi_set_config_item
;
4023 c
->destroy
= lxcapi_destroy
;
4024 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4025 c
->rename
= lxcapi_rename
;
4026 c
->save_config
= lxcapi_save_config
;
4027 c
->get_keys
= lxcapi_get_keys
;
4028 c
->create
= lxcapi_create
;
4029 c
->createl
= lxcapi_createl
;
4030 c
->shutdown
= lxcapi_shutdown
;
4031 c
->reboot
= lxcapi_reboot
;
4032 c
->clear_config
= lxcapi_clear_config
;
4033 c
->clear_config_item
= lxcapi_clear_config_item
;
4034 c
->get_config_item
= lxcapi_get_config_item
;
4035 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4036 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4037 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4038 c
->get_config_path
= lxcapi_get_config_path
;
4039 c
->set_config_path
= lxcapi_set_config_path
;
4040 c
->clone
= lxcapi_clone
;
4041 c
->get_interfaces
= lxcapi_get_interfaces
;
4042 c
->get_ips
= lxcapi_get_ips
;
4043 c
->attach
= lxcapi_attach
;
4044 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4045 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4046 c
->snapshot
= lxcapi_snapshot
;
4047 c
->snapshot_list
= lxcapi_snapshot_list
;
4048 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4049 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4050 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4051 c
->may_control
= lxcapi_may_control
;
4052 c
->add_device_node
= lxcapi_add_device_node
;
4053 c
->remove_device_node
= lxcapi_remove_device_node
;
4054 c
->checkpoint
= lxcapi_checkpoint
;
4055 c
->restore
= lxcapi_restore
;
4057 /* we'll allow the caller to update these later */
4058 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
4059 fprintf(stderr
, "failed to open log\n");
4066 lxc_container_free(c
);
4070 int lxc_get_wait_states(const char **states
)
4075 for (i
=0; i
<MAX_STATE
; i
++)
4076 states
[i
] = lxc_state2str(i
);
4081 * These next two could probably be done smarter with reusing a common function
4082 * with different iterators and tests...
4084 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4087 int i
, cfound
= 0, nfound
= 0;
4088 struct dirent dirent
, *direntp
;
4089 struct lxc_container
*c
;
4092 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4094 dir
= opendir(lxcpath
);
4096 SYSERROR("opendir on lxcpath");
4105 while (!readdir_r(dir
, &dirent
, &direntp
)) {
4108 if (!strcmp(direntp
->d_name
, "."))
4110 if (!strcmp(direntp
->d_name
, ".."))
4113 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4117 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4127 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4129 INFO("Container %s:%s has a config but could not be loaded",
4130 lxcpath
, direntp
->d_name
);
4132 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4136 if (!lxcapi_is_defined(c
)) {
4137 INFO("Container %s:%s has a config but is not defined",
4138 lxcpath
, direntp
->d_name
);
4140 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4142 lxc_container_put(c
);
4146 if (!add_to_clist(cret
, c
, nfound
, true)) {
4147 lxc_container_put(c
);
4157 if (names
&& *names
) {
4158 for (i
=0; i
<cfound
; i
++)
4162 if (cret
&& *cret
) {
4163 for (i
=0; i
<nfound
; i
++)
4164 lxc_container_put((*cret
)[i
]);
4171 int list_active_containers(const char *lxcpath
, char ***nret
,
4172 struct lxc_container
***cret
)
4174 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4177 char **ct_name
= NULL
;
4179 struct lxc_container
*c
;
4183 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4184 lxcpath_len
= strlen(lxcpath
);
4191 FILE *f
= fopen("/proc/net/unix", "r");
4195 while (getline(&line
, &len
, f
) != -1) {
4197 char *p
= strrchr(line
, ' '), *p2
;
4206 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4208 } else if (strncmp(p
, "lxc/", 4) == 0) {
4218 // Now p is the start of lxc_name
4220 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4225 if (strncmp(lxcpath
, lxc_cmd_get_lxcpath(p
), lxcpath_len
) != 0)
4227 p
= lxc_cmd_get_name(p
);
4230 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4233 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4234 goto free_cret_list
;
4241 c
= lxc_container_new(p
, lxcpath
);
4243 INFO("Container %s:%s is running but could not be loaded",
4245 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4250 * If this is an anonymous container, then is_defined *can*
4251 * return false. So we don't do that check. Count on the
4252 * fact that the command socket exists.
4255 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
4256 lxc_container_put(c
);
4257 goto free_cret_list
;
4262 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
4271 if (cret
&& *cret
) {
4272 for (i
= 0; i
< cret_cnt
; i
++)
4273 lxc_container_put((*cret
)[i
]);
4279 for (i
= 0; i
< ct_name_cnt
; i
++)
4292 int list_all_containers(const char *lxcpath
, char ***nret
,
4293 struct lxc_container
***cret
)
4295 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
4298 struct lxc_container
**ct_list
= NULL
;
4300 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
4304 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
4305 if (active_cnt
< 0) {
4310 for (i
= 0; i
< active_cnt
; i
++) {
4311 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
4312 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
4314 goto free_active_name
;
4318 free(active_name
[i
]);
4319 active_name
[i
] = NULL
;
4325 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
4326 struct lxc_container
*c
;
4328 c
= lxc_container_new(ct_name
[i
], lxcpath
);
4330 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
4331 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
4335 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
4336 lxc_container_put(c
);
4355 for (i
= 0; i
< ct_list_cnt
; i
++) {
4356 lxc_container_put(ct_list
[i
]);
4362 for (i
= 0; i
< active_cnt
; i
++) {
4364 free(active_name
[i
]);
4370 for (i
= 0; i
< ct_cnt
; i
++) {