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>
42 #include <lxc/network.h>
57 #include "namespace.h"
65 #include <../include/ifaddrs.h>
68 #define MAX_BUFFER 4096
70 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
72 /* Define faccessat() if missing from the C library */
73 #ifndef HAVE_FACCESSAT
74 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
77 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
86 lxc_log_define(lxc_container
, lxc
);
88 static bool config_file_exists(const char *lxcpath
, const char *cname
)
90 /* $lxcpath + '/' + $cname + '/config' + \0 */
91 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
92 char *fname
= alloca(len
);
94 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
95 if (ret
< 0 || ret
>= len
)
98 return file_exists(fname
);
102 * A few functions to help detect when a container creation failed.
103 * If a container creation was killed partway through, then trying
104 * to actually start that container could harm the host. We detect
105 * this by creating a 'partial' file under the container directory,
106 * and keeping an advisory lock. When container creation completes,
107 * we remove that file. When we load or try to start a container, if
108 * we find that file, without a flock, we remove the container.
110 static int ongoing_create(struct lxc_container
*c
)
112 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
113 char *path
= alloca(len
);
117 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
118 if (ret
< 0 || ret
>= len
) {
119 ERROR("Error writing partial pathname");
123 if (!file_exists(path
))
125 fd
= open(path
, O_RDWR
);
127 // give benefit of the doubt
128 SYSERROR("Error opening partial file");
132 lk
.l_whence
= SEEK_SET
;
136 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
137 // create is still ongoing
141 // create completed but partial is still there.
146 static int create_partial(struct lxc_container
*c
)
148 // $lxcpath + '/' + $name + '/partial' + \0
149 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
150 char *path
= alloca(len
);
154 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
155 if (ret
< 0 || ret
>= len
) {
156 ERROR("Error writing partial pathname");
159 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
160 SYSERROR("Erorr creating partial file");
164 lk
.l_whence
= SEEK_SET
;
167 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
168 SYSERROR("Error locking partial file %s", path
);
176 static void remove_partial(struct lxc_container
*c
, int fd
)
178 // $lxcpath + '/' + $name + '/partial' + \0
179 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
180 char *path
= alloca(len
);
184 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
185 if (ret
< 0 || ret
>= len
) {
186 ERROR("Error writing partial pathname");
189 if (unlink(path
) < 0)
190 SYSERROR("Error unlink partial file %s", path
);
194 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
195 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
196 * container configuration file.
197 * The container_disk_lock also takes the container_mem_lock.
198 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
199 * NOTHING mutexes two independent programs with their own struct
200 * lxc_container for the same c->name, between API calls. For instance,
201 * c->config_read(); c->start(); Between those calls, data on disk
202 * could change (which shouldn't bother the caller unless for instance
203 * the rootfs get moved). c->config_read(); update; c->config_write();
204 * Two such updaters could race. The callers should therefore check their
205 * results. Trying to prevent that would necessarily expose us to deadlocks
206 * due to hung callers. So I prefer to keep the locks only within our own
207 * functions, not across functions.
209 * If you're going to clone while holding a lxccontainer, increment
210 * c->numthreads (under privlock) before forking. When deleting,
211 * decrement numthreads under privlock, then if it hits 0 you can delete.
212 * Do not ever use a lxccontainer whose numthreads you did not bump.
215 static void lxc_container_free(struct lxc_container
*c
)
222 c
->configfile
= NULL
;
224 if (c
->error_string
) {
225 free(c
->error_string
);
226 c
->error_string
= NULL
;
229 lxc_putlock(c
->slock
);
233 lxc_putlock(c
->privlock
);
241 lxc_conf_free(c
->lxc_conf
);
244 if (c
->config_path
) {
245 free(c
->config_path
);
246 c
->config_path
= NULL
;
253 * Consider the following case:
254 freer | racing get()er
255 ==================================================================
256 lxc_container_put() | lxc_container_get()
257 \ lxclock(c->privlock) | c->numthreads < 1? (no)
258 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
260 \ lxc_container_free() | \ lxclock() returns
261 | \ c->numthreads < 1 -> return 0
263 \ \ sem_destroy(privlock) |
265 * When the get()er checks numthreads the first time, one of the following
267 * 1. freer has set numthreads = 0. get() returns 0
268 * 2. freer is between lxclock and setting numthreads to 0. get()er will
269 * sem_wait on privlock, get lxclock after freer() drops it, then see
270 * numthreads is 0 and exit without touching lxclock again..
271 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
272 * will see --numthreads = 1 and not call lxc_container_free().
275 int lxc_container_get(struct lxc_container
*c
)
280 // if someone else has already started freeing the container, don't
281 // try to take the lock, which may be invalid
282 if (c
->numthreads
< 1)
285 if (container_mem_lock(c
))
287 if (c
->numthreads
< 1) {
288 // bail without trying to unlock, bc the privlock is now probably
293 container_mem_unlock(c
);
297 int lxc_container_put(struct lxc_container
*c
)
301 if (container_mem_lock(c
))
303 if (--c
->numthreads
< 1) {
304 container_mem_unlock(c
);
305 lxc_container_free(c
);
308 container_mem_unlock(c
);
312 static bool lxcapi_is_defined(struct lxc_container
*c
)
321 if (container_mem_lock(c
))
325 statret
= stat(c
->configfile
, &statbuf
);
331 container_mem_unlock(c
);
335 static const char *lxcapi_state(struct lxc_container
*c
)
341 s
= lxc_getstate(c
->name
, c
->config_path
);
342 return lxc_state2str(s
);
345 static bool is_stopped(struct lxc_container
*c
)
348 s
= lxc_getstate(c
->name
, c
->config_path
);
349 return (s
== STOPPED
);
352 static bool lxcapi_is_running(struct lxc_container
*c
)
359 if (!s
|| strcmp(s
, "STOPPED") == 0)
364 static bool lxcapi_freeze(struct lxc_container
*c
)
370 ret
= lxc_freeze(c
->name
, c
->config_path
);
376 static bool lxcapi_unfreeze(struct lxc_container
*c
)
382 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
388 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
394 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
398 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
399 int stdoutfd
, int stderrfd
, int escape
)
401 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
404 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
409 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
412 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
415 c
->lxc_conf
= lxc_conf_init();
418 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
423 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
425 bool ret
= false, need_disklock
= false;
431 fname
= c
->configfile
;
437 * If we're reading something other than the container's config,
438 * we only need to lock the in-memory container. If loading the
439 * container's config file, take the disk lock.
441 if (strcmp(fname
, c
->configfile
) == 0)
442 need_disklock
= true;
445 lret
= container_disk_lock(c
);
447 lret
= container_mem_lock(c
);
451 ret
= load_config_locked(c
, fname
);
454 container_disk_unlock(c
);
456 container_mem_unlock(c
);
460 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
462 if (!c
|| !c
->lxc_conf
)
464 if (container_mem_lock(c
)) {
465 ERROR("Error getting mem lock");
468 c
->daemonize
= state
;
469 /* daemonize implies close_all_fds so set it */
471 c
->lxc_conf
->close_all_fds
= 1;
472 container_mem_unlock(c
);
476 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
478 if (!c
|| !c
->lxc_conf
)
480 if (container_mem_lock(c
)) {
481 ERROR("Error getting mem lock");
484 c
->lxc_conf
->close_all_fds
= state
;
485 container_mem_unlock(c
);
489 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
496 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
501 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
503 /* we'll probably want to make this timeout configurable? */
504 int timeout
= 5, ret
, status
;
507 * our child is going to fork again, then exit. reap the
510 ret
= waitpid(pid
, &status
, 0);
511 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
512 DEBUG("failed waiting for first dual-fork child");
513 return lxcapi_wait(c
, "RUNNING", timeout
);
516 static bool am_single_threaded(void)
518 struct dirent dirent
, *direntp
;
522 dir
= opendir("/proc/self/task");
524 INFO("failed to open /proc/self/task");
528 while (!readdir_r(dir
, &dirent
, &direntp
)) {
532 if (!strcmp(direntp
->d_name
, "."))
535 if (!strcmp(direntp
->d_name
, ".."))
545 * I can't decide if it'd be more convenient for callers if we accept '...',
546 * or a null-terminated array (i.e. execl vs execv)
548 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
551 struct lxc_conf
*conf
;
552 bool daemonize
= false;
554 char *default_args
[] = {
559 /* container exists */
562 /* container has been setup */
566 if ((ret
= ongoing_create(c
)) < 0) {
567 ERROR("Error checking for incomplete creation");
571 ERROR("Error: %s creation was not completed", c
->name
);
574 } else if (ret
== 1) {
575 ERROR("Error: creation of %s is ongoing", c
->name
);
579 /* is this app meant to be run through lxcinit, as in lxc-execute? */
580 if (useinit
&& !argv
)
583 if (container_mem_lock(c
))
586 daemonize
= c
->daemonize
;
587 container_mem_unlock(c
);
590 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
591 return ret
== 0 ? true : false;
598 * say, I'm not sure - what locks do we want here? Any?
599 * Is liblxc's locking enough here to protect the on disk
600 * container? We don't want to exclude things like lxc_info
601 * while container is running...
604 lxc_monitord_spawn(c
->config_path
);
611 /* Set to NULL because we don't want father unlink
612 * the PID file, child will do the free and unlink.
615 return wait_on_daemonized_start(c
, pid
);
618 /* second fork to be reparented by init */
621 SYSERROR("Error doing dual-fork");
626 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
628 SYSERROR("Error chdir()ing to /.");
631 lxc_check_inherited(conf
, -1);
635 open("/dev/zero", O_RDONLY
);
636 open("/dev/null", O_RDWR
);
637 open("/dev/null", O_RDWR
);
640 if (!am_single_threaded()) {
641 ERROR("Cannot start non-daemonized container when threaded");
646 /* We need to write PID file after daeminize, so we always
647 * write the right PID.
650 pid_fp
= fopen(c
->pidfile
, "w");
651 if (pid_fp
== NULL
) {
652 SYSERROR("Failed to create pidfile '%s' for '%s'",
653 c
->pidfile
, c
->name
);
657 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
658 SYSERROR("Failed to write '%s'", c
->pidfile
);
670 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
674 INFO("container requested reboot");
686 exit (ret
== 0 ? true : false);
688 return (ret
== 0 ? true : false);
692 * note there MUST be an ending NULL
694 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
697 char **inargs
= NULL
;
700 /* container exists */
704 va_start(ap
, useinit
);
705 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
709 ERROR("Memory allocation error.");
713 /* pass NULL if no arguments were supplied */
714 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
719 for (arg
= inargs
; *arg
; arg
++)
727 static bool lxcapi_stop(struct lxc_container
*c
)
734 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
739 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
741 int ret
= -1, lasterr
;
742 char *p
= alloca(strlen(path
)+1);
743 mode_t mask
= umask(0002);
744 ret
= mkdir(path
, 0770);
752 SYSERROR("failed to create container path %s", path
);
757 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
758 ERROR("Failed to chown container dir");
765 * create the standard expected container dir
767 static bool create_container_dir(struct lxc_container
*c
)
772 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
776 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
777 if (ret
< 0 || ret
>= len
) {
781 ret
= do_create_container_dir(s
, c
->lxc_conf
);
786 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
787 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
790 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
791 * it returns a mounted bdev on success, NULL on error.
793 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
794 struct bdev_specs
*specs
)
801 /* rootfs.path or lxcpath/lxcname/rootfs */
802 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
803 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
804 len
= strlen(rpath
) + 1;
806 ret
= snprintf(dest
, len
, "%s", rpath
);
808 const char *lxcpath
= lxcapi_get_config_path(c
);
809 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
811 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
813 if (ret
< 0 || ret
>= len
)
816 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
818 ERROR("Failed to create backing store type %s", type
);
822 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
824 /* if we are not root, chown the rootfs dir to root in the
827 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
828 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
829 ERROR("Error chowning %s to container root", bdev
->dest
);
830 suggest_default_idmap();
840 * Given the '-t' template option to lxc-create, figure out what to
841 * do. If the template is a full executable path, use that. If it
842 * is something like 'sshd', then return $templatepath/lxc-sshd.
843 * On success return the template, on error return NULL.
845 static char *get_template_path(const char *t
)
850 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
855 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
859 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
860 if (ret
< 0 || ret
>= len
) {
864 if (access(tpath
, X_OK
) < 0) {
865 SYSERROR("bad template: %s", t
);
873 static char *lxcbasename(char *path
)
875 char *p
= path
+ strlen(path
) - 1;
876 while (*p
!= '/' && p
> path
)
881 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
891 SYSERROR("failed to fork task for container creation template");
895 if (pid
== 0) { // child
896 char *patharg
, *namearg
, *rootfsarg
, *src
;
897 struct bdev
*bdev
= NULL
;
899 int ret
, len
, nargs
= 0;
901 struct lxc_conf
*conf
= c
->lxc_conf
;
907 open("/dev/zero", O_RDONLY
);
908 open("/dev/null", O_RDWR
);
909 open("/dev/null", O_RDWR
);
912 src
= c
->lxc_conf
->rootfs
.path
;
914 * for an overlay create, what the user wants is the template to fill
915 * in what will become the readonly lower layer. So don't mount for
918 if (strncmp(src
, "overlayfs:", 10) == 0)
919 src
= overlay_getlower(src
+10);
920 if (strncmp(src
, "aufs:", 5) == 0)
921 src
= overlay_getlower(src
+5);
923 bdev
= bdev_init(c
->lxc_conf
, src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
925 ERROR("Error opening rootfs");
929 if (geteuid() == 0) {
930 if (unshare(CLONE_NEWNS
) < 0) {
931 ERROR("error unsharing mounts");
934 if (detect_shared_rootfs()) {
935 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
936 SYSERROR("Failed to make / rslave to run template");
937 ERROR("Continuing...");
941 if (strcmp(bdev
->type
, "dir") && strcmp(bdev
->type
, "btrfs")) {
942 if (geteuid() != 0) {
943 ERROR("non-root users can only create btrfs and directory-backed containers");
946 if (bdev
->ops
->mount(bdev
) < 0) {
947 ERROR("Error mounting rootfs");
950 } else { // TODO come up with a better way here!
953 bdev
->dest
= strdup(bdev
->src
);
957 * create our new array, pre-pend the template name and
961 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
962 nargs
+= 4; // template, path, rootfs and name args
964 newargv
= malloc(nargs
* sizeof(*newargv
));
967 newargv
[0] = lxcbasename(tpath
);
969 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
970 patharg
= malloc(len
);
973 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
974 if (ret
< 0 || ret
>= len
)
976 newargv
[1] = patharg
;
977 len
= strlen("--name=") + strlen(c
->name
) + 1;
978 namearg
= malloc(len
);
981 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
982 if (ret
< 0 || ret
>= len
)
984 newargv
[2] = namearg
;
986 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
987 rootfsarg
= malloc(len
);
990 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
991 if (ret
< 0 || ret
>= len
)
993 newargv
[3] = rootfsarg
;
995 /* add passed-in args */
997 for (i
= 4; i
< nargs
; i
++)
998 newargv
[i
] = argv
[i
-4];
1000 /* add trailing NULL */
1002 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1005 newargv
[nargs
- 1] = NULL
;
1008 * If we're running the template in a mapped userns, then
1009 * we prepend the template command with:
1010 * lxc-usernsexec <-m map1> ... <-m mapn> --
1011 * and we append "--mapped-uid x", where x is the mapped uid
1014 if (!lxc_list_empty(&conf
->id_map
)) {
1018 char **n2
= malloc(n2args
* sizeof(*n2
));
1019 struct lxc_list
*it
;
1023 SYSERROR("out of memory");
1027 tpath
= "lxc-usernsexec";
1028 n2
[0] = "lxc-usernsexec";
1029 lxc_list_for_each(it
, &conf
->id_map
) {
1032 n2
= realloc(n2
, n2args
* sizeof(char *));
1035 n2
[n2args
-2] = "-m";
1036 n2
[n2args
-1] = malloc(200);
1039 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1040 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1041 map
->nsid
, map
->hostid
, map
->range
);
1042 if (ret
< 0 || ret
>= 200)
1045 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1046 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1047 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1050 if (hostid_mapped
< 0) {
1051 hostid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_UID
);
1052 n2
[n2args
++] = "-m";
1053 if (hostid_mapped
< 0) {
1054 ERROR("Could not find free uid to map");
1057 n2
[n2args
++] = malloc(200);
1058 if (!n2
[n2args
-1]) {
1059 SYSERROR("out of memory");
1062 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1063 hostid_mapped
, geteuid());
1064 if (ret
< 0 || ret
>= 200) {
1065 ERROR("string too long");
1069 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1070 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1071 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1074 if (hostgid_mapped
< 0) {
1075 hostgid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_GID
);
1076 n2
[n2args
++] = "-m";
1077 if (hostgid_mapped
< 0) {
1078 ERROR("Could not find free uid to map");
1081 n2
[n2args
++] = malloc(200);
1082 if (!n2
[n2args
-1]) {
1083 SYSERROR("out of memory");
1086 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1087 hostgid_mapped
, getegid());
1088 if (ret
< 0 || ret
>= 200) {
1089 ERROR("string too long");
1093 n2
[n2args
++] = "--";
1094 for (i
= 0; i
< nargs
; i
++)
1095 n2
[i
+ n2args
] = newargv
[i
];
1097 // Finally add "--mapped-uid $uid" to tell template what to chown
1100 n2
= realloc(n2
, n2args
* sizeof(char *));
1102 SYSERROR("out of memory");
1105 // note n2[n2args-1] is NULL
1106 n2
[n2args
-5] = "--mapped-uid";
1107 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1108 n2
[n2args
-4] = txtuid
;
1109 n2
[n2args
-3] = "--mapped-gid";
1110 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1111 n2
[n2args
-2] = txtgid
;
1112 n2
[n2args
-1] = NULL
;
1117 execvp(tpath
, newargv
);
1118 SYSERROR("failed to execute template %s", tpath
);
1122 if (wait_for_pid(pid
) != 0) {
1123 ERROR("container creation template for %s failed", c
->name
);
1130 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1138 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1142 f
= fopen(path
, "r");
1146 if (fseek(f
, 0, SEEK_END
) < 0)
1148 if ((flen
= ftell(f
)) < 0)
1150 if (fseek(f
, 0, SEEK_SET
) < 0)
1152 if ((contents
= malloc(flen
+ 1)) == NULL
)
1154 if (fread(contents
, 1, flen
, f
) != flen
)
1155 goto out_free_contents
;
1157 contents
[flen
] = '\0';
1161 goto out_free_contents
;
1164 tpath
= get_template_path(t
);
1166 ERROR("bad template: %s", t
);
1167 goto out_free_contents
;
1170 ret
= sha1sum_file(tpath
, md_value
);
1172 ERROR("Error getting sha1sum of %s", tpath
);
1174 goto out_free_contents
;
1179 f
= fopen(path
, "w");
1181 SYSERROR("reopening config for writing");
1185 fprintf(f
, "# Template used to create this container: %s\n", t
);
1187 fprintf(f
, "# Parameters passed to the template:");
1189 fprintf(f
, " %s", *argv
);
1195 fprintf(f
, "# Template script checksum (SHA-1): ");
1196 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1197 fprintf(f
, "%02x", md_value
[i
]);
1200 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1201 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1202 SYSERROR("Writing original contents");
1218 SYSERROR("Error prepending header");
1224 static void lxcapi_clear_config(struct lxc_container
*c
)
1228 lxc_conf_free(c
->lxc_conf
);
1234 static bool lxcapi_destroy(struct lxc_container
*c
);
1235 static bool container_destroy(struct lxc_container
*c
);
1236 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
1239 * create a container with the given parameters.
1240 * @c: container to be created. It has the lxcpath, name, and a starting
1241 * configuration already set
1242 * @t: the template to execute to instantiate the root filesystem and
1243 * adjust the configuration.
1244 * @bdevtype: backing store type to use. If NULL, dir will be used.
1245 * @specs: additional parameters for the backing store, i.e. LVM vg to
1248 * @argv: the arguments to pass to the template, terminated by NULL. If no
1249 * arguments, you can just pass NULL.
1251 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1252 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1264 tpath
= get_template_path(t
);
1266 ERROR("bad template: %s", t
);
1272 * If a template is passed in, and the rootfs already is defined in
1273 * the container config and exists, then * caller is trying to create
1274 * an existing container. Return an error, but do NOT delete the
1277 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1278 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1279 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1284 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1285 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1290 if (!create_container_dir(c
))
1294 * either template or rootfs.path should be set.
1295 * if both template and rootfs.path are set, template is setup as rootfs.path.
1296 * container is already created if we have a config and rootfs.path is accessible
1298 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1299 /* no template passed in and rootfs does not exist: error */
1301 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1302 /* rootfs passed into configuration, but does not exist: error */
1304 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1305 /* Rootfs already existed, user just wanted to save the
1306 * loaded configuration */
1311 /* Mark that this container is being created */
1312 if ((partial_fd
= create_partial(c
)) < 0)
1315 /* no need to get disk lock bc we have the partial locked */
1318 * Create the backing store
1319 * Note we can't do this in the same task as we use to execute the
1320 * template because of the way zfs works.
1321 * After you 'zfs create', zfs mounts the fs only in the initial
1326 SYSERROR("failed to fork task for container creation template");
1330 if (pid
== 0) { // child
1331 struct bdev
*bdev
= NULL
;
1333 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1334 ERROR("Error creating backing store type %s for %s",
1335 bdevtype
? bdevtype
: "(none)", c
->name
);
1339 /* save config file again to store the new rootfs location */
1340 if (!c
->save_config(c
, NULL
)) {
1341 ERROR("failed to save starting configuration for %s", c
->name
);
1342 // parent task won't see bdev in config so we delete it
1343 bdev
->ops
->umount(bdev
);
1344 bdev
->ops
->destroy(bdev
);
1349 if (wait_for_pid(pid
) != 0)
1352 /* reload config to get the rootfs */
1353 lxc_conf_free(c
->lxc_conf
);
1355 if (!load_config_locked(c
, c
->configfile
))
1358 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1361 // now clear out the lxc_conf we have, reload from the created
1363 lxcapi_clear_config(c
);
1366 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1367 ERROR("Error prepending header to configuration file");
1371 ret
= load_config_locked(c
, c
->configfile
);
1374 if (partial_fd
>= 0)
1375 remove_partial(c
, partial_fd
);
1378 container_destroy(c
);
1385 static bool lxcapi_reboot(struct lxc_container
*c
)
1391 if (!c
->is_running(c
))
1393 pid
= c
->init_pid(c
);
1396 if (kill(pid
, SIGINT
) < 0)
1402 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1406 int haltsignal
= SIGPWR
;
1411 if (!c
->is_running(c
))
1413 pid
= c
->init_pid(c
);
1416 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1417 haltsignal
= c
->lxc_conf
->haltsignal
;
1418 kill(pid
, haltsignal
);
1419 retv
= c
->wait(c
, "STOPPED", timeout
);
1423 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1424 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1434 * since we're going to wait for create to finish, I don't think we
1435 * need to get a copy of the arguments.
1437 va_start(ap
, flags
);
1438 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1441 ERROR("Memory allocation error.");
1445 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1452 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
1454 if (strcmp(key
, "lxc.cgroup") == 0)
1455 clear_unexp_config_line(conf
, key
, true);
1456 else if (strcmp(key
, "lxc.network") == 0)
1457 clear_unexp_config_line(conf
, key
, true);
1458 else if (strcmp(key
, "lxc.hook") == 0)
1459 clear_unexp_config_line(conf
, key
, true);
1461 clear_unexp_config_line(conf
, key
, false);
1462 if (!do_append_unexp_config_line(conf
, key
, ""))
1463 WARN("Error clearing configuration for %s", key
);
1466 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1470 if (!c
|| !c
->lxc_conf
)
1472 if (container_mem_lock(c
))
1474 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1476 do_clear_unexp_config_line(c
->lxc_conf
, key
);
1477 container_mem_unlock(c
);
1481 static inline bool enter_net_ns(struct lxc_container
*c
)
1483 pid_t pid
= c
->init_pid(c
);
1485 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1486 if (!switch_to_ns(pid
, "user"))
1489 return switch_to_ns(pid
, "net");
1492 // used by qsort and bsearch functions for comparing names
1493 static inline int string_cmp(char **first
, char **second
)
1495 return strcmp(*first
, *second
);
1498 // used by qsort and bsearch functions for comparing container names
1499 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1501 return strcmp((*first
)->name
, (*second
)->name
);
1504 static bool add_to_array(char ***names
, char *cname
, int pos
)
1506 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1508 ERROR("Out of memory");
1513 newnames
[pos
] = strdup(cname
);
1517 // sort the arrray as we will use binary search on it
1518 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1523 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1525 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1527 ERROR("Out of memory");
1534 // sort the arrray as we will use binary search on it
1536 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1541 static char** get_from_array(char ***names
, char *cname
, int size
)
1543 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1547 static bool array_contains(char ***names
, char *cname
, int size
) {
1548 if(get_from_array(names
, cname
, size
) != NULL
)
1553 static bool remove_from_array(char ***names
, char *cname
, int size
)
1555 char **result
= get_from_array(names
, cname
, size
);
1556 if (result
!= NULL
) {
1563 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1566 int i
, count
= 0, pipefd
[2];
1567 char **interfaces
= NULL
;
1568 char interface
[IFNAMSIZ
];
1570 if(pipe(pipefd
) < 0) {
1571 SYSERROR("pipe failed");
1577 SYSERROR("failed to fork task to get interfaces information");
1583 if (pid
== 0) { // child
1584 int ret
= 1, nbytes
;
1585 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1587 /* close the read-end of the pipe */
1590 if (!enter_net_ns(c
)) {
1591 SYSERROR("failed to enter namespace");
1595 /* Grab the list of interfaces */
1596 if (getifaddrs(&interfaceArray
)) {
1597 SYSERROR("failed to get interfaces list");
1601 /* Iterate through the interfaces */
1602 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1603 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1605 ERROR("write failed");
1614 freeifaddrs(interfaceArray
);
1616 /* close the write-end of the pipe, thus sending EOF to the reader */
1621 /* close the write-end of the pipe */
1624 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1625 if (array_contains(&interfaces
, interface
, count
))
1628 if(!add_to_array(&interfaces
, interface
, count
))
1629 ERROR("PARENT: add_to_array failed");
1633 if (wait_for_pid(pid
) != 0) {
1634 for(i
=0;i
<count
;i
++)
1635 free(interfaces
[i
]);
1640 /* close the read-end of the pipe */
1643 /* Append NULL to the array */
1645 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1650 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1653 int i
, count
= 0, pipefd
[2];
1654 char **addresses
= NULL
;
1655 char address
[INET6_ADDRSTRLEN
];
1657 if(pipe(pipefd
) < 0) {
1658 SYSERROR("pipe failed");
1664 SYSERROR("failed to fork task to get container ips");
1670 if (pid
== 0) { // child
1671 int ret
= 1, nbytes
;
1672 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1673 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1674 void *tempAddrPtr
= NULL
;
1675 char *address
= NULL
;
1677 /* close the read-end of the pipe */
1680 if (!enter_net_ns(c
)) {
1681 SYSERROR("failed to enter namespace");
1685 /* Grab the list of interfaces */
1686 if (getifaddrs(&interfaceArray
)) {
1687 SYSERROR("failed to get interfaces list");
1691 /* Iterate through the interfaces */
1692 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1693 if (tempIfAddr
->ifa_addr
== NULL
)
1696 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1697 if (family
&& strcmp(family
, "inet"))
1699 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1702 if (family
&& strcmp(family
, "inet6"))
1705 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1708 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1711 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1713 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1716 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1718 addressOutputBuffer
,
1719 sizeof(addressOutputBuffer
));
1723 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1725 ERROR("write failed");
1734 freeifaddrs(interfaceArray
);
1736 /* close the write-end of the pipe, thus sending EOF to the reader */
1741 /* close the write-end of the pipe */
1744 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1745 if(!add_to_array(&addresses
, address
, count
))
1746 ERROR("PARENT: add_to_array failed");
1750 if (wait_for_pid(pid
) != 0) {
1751 for(i
=0;i
<count
;i
++)
1757 /* close the read-end of the pipe */
1760 /* Append NULL to the array */
1762 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1767 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1771 if (!c
|| !c
->lxc_conf
)
1773 if (container_mem_lock(c
))
1775 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1776 container_mem_unlock(c
);
1780 static char* lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
1784 if (!c
|| !c
->lxc_conf
)
1786 if (container_mem_lock(c
))
1788 ret
= lxc_cmd_get_config_item(c
->name
, key
, c
->get_config_path(c
));
1789 container_mem_unlock(c
);
1793 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1796 return lxc_listconfigs(retv
, inlen
);
1798 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1799 * This is an intelligent result to show which keys are valid given
1800 * the type of nic it is
1802 if (!c
|| !c
->lxc_conf
)
1804 if (container_mem_lock(c
))
1807 if (strncmp(key
, "lxc.network.", 12) == 0)
1808 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1809 container_mem_unlock(c
);
1813 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1816 bool ret
= false, need_disklock
= false;
1820 alt_file
= c
->configfile
;
1822 return false; // should we write to stdout if no file is specified?
1824 // If we haven't yet loaded a config, load the stock config
1826 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1827 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
1832 if (!create_container_dir(c
))
1836 * If we're writing to the container's config file, take the
1837 * disk lock. Otherwise just take the memlock to protect the
1838 * struct lxc_container while we're traversing it.
1840 if (strcmp(c
->configfile
, alt_file
) == 0)
1841 need_disklock
= true;
1844 lret
= container_disk_lock(c
);
1846 lret
= container_mem_lock(c
);
1851 fout
= fopen(alt_file
, "w");
1854 write_config(fout
, c
->lxc_conf
);
1860 container_disk_unlock(c
);
1862 container_mem_unlock(c
);
1866 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1868 char path
[MAXPATHLEN
];
1873 if (container_disk_lock(c
))
1875 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1877 if (ret
< 0 || ret
> MAXPATHLEN
)
1879 f
= fopen(path
, "r");
1881 ret
= fscanf(f
, "%d", &v
);
1884 ERROR("Corrupted file %s", path
);
1889 f
= fopen(path
, "w");
1892 if (fprintf(f
, "%d\n", v
) < 0) {
1893 ERROR("Error writing new snapshots value");
1899 SYSERROR("Error writing to or closing snapshots file");
1906 container_disk_unlock(c
);
1910 static void strip_newline(char *p
)
1912 size_t len
= strlen(p
);
1915 if (p
[len
-1] == '\n')
1919 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1921 struct lxc_container
*p
;
1922 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1923 size_t pathlen
= 0, namelen
= 0;
1927 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1928 c
->config_path
, c
->name
);
1929 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1930 ERROR("Path name too long");
1933 f
= fopen(path
, "r");
1936 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1937 if (getline(&lxcname
, &namelen
, f
) == -1) {
1938 ERROR("badly formatted file %s", path
);
1941 strip_newline(lxcpath
);
1942 strip_newline(lxcname
);
1943 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1944 ERROR("Unable to find dependent container %s:%s",
1948 if (!mod_rdep(p
, inc
))
1949 ERROR("Failed to increase numsnapshots for %s:%s",
1951 lxc_container_put(p
);
1954 if (lxcpath
) free(lxcpath
);
1955 if (lxcname
) free(lxcname
);
1959 static bool has_fs_snapshots(struct lxc_container
*c
)
1961 char path
[MAXPATHLEN
];
1966 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1968 if (ret
< 0 || ret
> MAXPATHLEN
)
1970 f
= fopen(path
, "r");
1973 ret
= fscanf(f
, "%d", &v
);
1983 static bool has_snapshots(struct lxc_container
*c
)
1985 char path
[MAXPATHLEN
];
1986 struct dirent dirent
, *direntp
;
1990 if (!get_snappath_dir(c
, path
))
1992 dir
= opendir(path
);
1995 while (!readdir_r(dir
, &dirent
, &direntp
)) {
1999 if (!strcmp(direntp
->d_name
, "."))
2002 if (!strcmp(direntp
->d_name
, ".."))
2011 static int lxc_rmdir_onedev_wrapper(void *data
)
2013 char *arg
= (char *) data
;
2014 return lxc_rmdir_onedev(arg
, "snaps");
2017 static int do_bdev_destroy(struct lxc_conf
*conf
)
2022 r
= bdev_init(conf
, conf
->rootfs
.path
, conf
->rootfs
.mount
, NULL
);
2026 if (r
->ops
->destroy(r
) < 0)
2032 static int bdev_destroy_wrapper(void *data
)
2034 struct lxc_conf
*conf
= data
;
2036 if (setgid(0) < 0) {
2037 ERROR("Failed to setgid to 0");
2040 if (setgroups(0, NULL
) < 0)
2041 WARN("Failed to clear groups");
2042 if (setuid(0) < 0) {
2043 ERROR("Failed to setuid to 0");
2046 return do_bdev_destroy(conf
);
2049 static bool container_destroy(struct lxc_container
*c
)
2054 if (!c
|| !lxcapi_is_defined(c
))
2057 if (container_disk_lock(c
))
2060 if (!is_stopped(c
)) {
2061 // we should queue some sort of error - in c->error_string?
2062 ERROR("container %s is not stopped", c
->name
);
2066 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
2068 ret
= userns_exec_1(c
->lxc_conf
, bdev_destroy_wrapper
, c
->lxc_conf
);
2070 ret
= do_bdev_destroy(c
->lxc_conf
);
2072 ERROR("Error destroying rootfs for %s", c
->name
);
2077 mod_all_rdeps(c
, false);
2079 const char *p1
= lxcapi_get_config_path(c
);
2080 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2081 sprintf(path
, "%s/%s", p1
, c
->name
);
2083 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
2085 ret
= lxc_rmdir_onedev(path
, "snaps");
2087 ERROR("Error destroying container directory for %s", c
->name
);
2093 container_disk_unlock(c
);
2097 static bool lxcapi_destroy(struct lxc_container
*c
)
2099 if (!c
|| !lxcapi_is_defined(c
))
2101 if (has_snapshots(c
)) {
2102 ERROR("Container %s has snapshots; not removing", c
->name
);
2106 if (has_fs_snapshots(c
)) {
2107 ERROR("container %s has snapshots on its rootfs", c
->name
);
2111 return container_destroy(c
);
2114 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
2116 static bool lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2118 if (!c
|| !lxcapi_is_defined(c
))
2120 if (!lxcapi_snapshot_destroy_all(c
)) {
2121 ERROR("Error deleting all snapshots");
2124 return lxcapi_destroy(c
);
2127 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2129 struct lxc_config_t
*config
;
2132 c
->lxc_conf
= lxc_conf_init();
2135 config
= lxc_getconfig(key
);
2138 if (config
->cb(key
, v
, c
->lxc_conf
) != 0)
2140 return do_append_unexp_config_line(c
->lxc_conf
, key
, v
);
2143 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2150 if (container_mem_lock(c
))
2153 b
= set_config_item_locked(c
, key
, v
);
2155 container_mem_unlock(c
);
2159 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2161 if (!c
|| !c
->configfile
)
2163 return strdup(c
->configfile
);
2166 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2168 if (!c
|| !c
->config_path
)
2170 return (const char *)(c
->config_path
);
2175 * Just recalculate the c->configfile based on the
2176 * c->config_path, which must be set.
2177 * The lxc_container must be locked or not yet public.
2179 static bool set_config_filename(struct lxc_container
*c
)
2184 if (!c
->config_path
)
2187 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2188 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2189 newpath
= malloc(len
);
2193 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2194 if (ret
< 0 || ret
>= len
) {
2195 fprintf(stderr
, "Error printing out config file name\n");
2201 free(c
->configfile
);
2202 c
->configfile
= newpath
;
2207 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2211 char *oldpath
= NULL
;
2216 if (container_mem_lock(c
))
2221 ERROR("Out of memory setting new lxc path");
2227 oldpath
= c
->config_path
;
2230 /* Since we've changed the config path, we have to change the
2231 * config file name too */
2232 if (!set_config_filename(c
)) {
2233 ERROR("Out of memory setting new config filename");
2235 free(c
->config_path
);
2236 c
->config_path
= oldpath
;
2242 container_mem_unlock(c
);
2247 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2257 if (container_disk_lock(c
))
2260 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2262 container_disk_unlock(c
);
2266 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2276 if (container_disk_lock(c
))
2279 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2281 container_disk_unlock(c
);
2285 const char *lxc_get_global_config_item(const char *key
)
2287 return lxc_global_config_value(key
);
2290 const char *lxc_get_version(void)
2295 static int copy_file(const char *old
, const char *new)
2302 if (file_exists(new)) {
2303 ERROR("copy destination %s exists", new);
2306 ret
= stat(old
, &sbuf
);
2308 INFO("Error stat'ing %s", old
);
2312 in
= open(old
, O_RDONLY
);
2314 SYSERROR("Error opening original file %s", old
);
2317 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2319 SYSERROR("Error opening new file %s", new);
2325 len
= read(in
, buf
, 8096);
2327 SYSERROR("Error reading old file %s", old
);
2332 ret
= write(out
, buf
, len
);
2333 if (ret
< len
) { // should we retry?
2334 SYSERROR("Error: write to new file %s was interrupted", new);
2341 // we set mode, but not owner/group
2342 ret
= chmod(new, sbuf
.st_mode
);
2344 SYSERROR("Error setting mode on %s", new);
2356 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2359 struct lxc_list
*it
;
2362 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2363 cpath
= alloca(len
);
2364 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2365 if (ret
< 0 || ret
>= len
)
2368 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2369 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2370 char *hookname
= it
->elem
;
2371 char *fname
= strrchr(hookname
, '/');
2372 char tmppath
[MAXPATHLEN
];
2373 if (!fname
) // relative path - we don't support, but maybe we should
2375 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2376 // this hook is public - ignore
2379 // copy the script, and change the entry in confile
2380 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2381 c
->config_path
, c
->name
, fname
+1);
2382 if (ret
< 0 || ret
>= MAXPATHLEN
)
2384 ret
= copy_file(it
->elem
, tmppath
);
2388 it
->elem
= strdup(tmppath
);
2390 ERROR("out of memory copying hook path");
2396 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
2397 c
->config_path
, oldc
->name
, c
->name
)) {
2398 ERROR("Error saving new hooks in clone");
2401 c
->save_config(c
, NULL
);
2406 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2408 char newpath
[MAXPATHLEN
];
2409 char *oldpath
= oldc
->lxc_conf
->fstab
;
2415 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount", false);
2417 char *p
= strrchr(oldpath
, '/');
2420 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2421 c
->config_path
, c
->name
, p
);
2422 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2423 ERROR("error printing new path for %s", oldpath
);
2426 if (file_exists(newpath
)) {
2427 ERROR("error: fstab file %s exists", newpath
);
2431 if (copy_file(oldpath
, newpath
) < 0) {
2432 ERROR("error: copying %s to %s", oldpath
, newpath
);
2435 free(c
->lxc_conf
->fstab
);
2436 c
->lxc_conf
->fstab
= strdup(newpath
);
2437 if (!c
->lxc_conf
->fstab
) {
2438 ERROR("error: allocating pathname");
2441 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount", newpath
)) {
2442 ERROR("error saving new lxctab");
2449 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2451 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2454 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2456 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2457 WARN("Error copying reverse dependencies");
2460 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2462 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2463 WARN("Error copying reverse dependencies");
2466 if (copy_file(path0
, path1
) < 0) {
2467 INFO("Error copying reverse dependencies");
2472 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2475 char path
[MAXPATHLEN
];
2479 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2481 if (ret
< 0 || ret
>= MAXPATHLEN
)
2483 f
= fopen(path
, "a");
2487 // if anything goes wrong, just return an error
2488 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2495 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2496 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2501 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
2502 bdevdata
, newsize
, &need_rdep
);
2504 ERROR("Error copying storage");
2507 free(c
->lxc_conf
->rootfs
.path
);
2508 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2510 if (!c
->lxc_conf
->rootfs
.path
) {
2511 ERROR("Out of memory while setting storage path");
2514 // We will simply append a new lxc.rootfs entry to the unexpanded config
2515 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
2516 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", c
->lxc_conf
->rootfs
.path
)) {
2517 ERROR("Error saving new rootfs to cloend config");
2520 if (flags
& LXC_CLONE_SNAPSHOT
)
2521 copy_rdepends(c
, c0
);
2523 if (!add_rdepends(c
, c0
))
2524 WARN("Error adding reverse dependency from %s to %s",
2528 mod_all_rdeps(c
, true);
2533 struct clone_update_data
{
2534 struct lxc_container
*c0
;
2535 struct lxc_container
*c1
;
2540 static int clone_update_rootfs(struct clone_update_data
*data
)
2542 struct lxc_container
*c0
= data
->c0
;
2543 struct lxc_container
*c
= data
->c1
;
2544 int flags
= data
->flags
;
2545 char **hookargs
= data
->hookargs
;
2547 char path
[MAXPATHLEN
];
2550 struct lxc_conf
*conf
= c
->lxc_conf
;
2552 /* update hostname in rootfs */
2553 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2555 if (setgid(0) < 0) {
2556 ERROR("Failed to setgid to 0");
2559 if (setuid(0) < 0) {
2560 ERROR("Failed to setuid to 0");
2563 if (setgroups(0, NULL
) < 0)
2564 WARN("Failed to clear groups");
2566 if (unshare(CLONE_NEWNS
) < 0)
2568 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2571 if (strcmp(bdev
->type
, "dir") != 0) {
2572 if (unshare(CLONE_NEWNS
) < 0) {
2573 ERROR("error unsharing mounts");
2577 if (detect_shared_rootfs()) {
2578 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2579 SYSERROR("Failed to make / rslave");
2580 ERROR("Continuing...");
2583 if (bdev
->ops
->mount(bdev
) < 0) {
2587 } else { // TODO come up with a better way
2590 bdev
->dest
= strdup(bdev
->src
);
2593 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2594 /* Start of environment variable setup for hooks */
2595 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2596 SYSERROR("failed to set environment variable for source container name");
2598 if (setenv("LXC_NAME", c
->name
, 1)) {
2599 SYSERROR("failed to set environment variable for container name");
2601 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2602 SYSERROR("failed to set environment variable for config path");
2604 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2605 SYSERROR("failed to set environment variable for rootfs mount");
2607 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2608 SYSERROR("failed to set environment variable for rootfs mount");
2611 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2612 ERROR("Error executing clone hook for %s", c
->name
);
2618 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2619 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2622 if (ret
< 0 || ret
>= MAXPATHLEN
)
2624 if (!file_exists(path
))
2626 if (!(fout
= fopen(path
, "w"))) {
2627 SYSERROR("unable to open %s: ignoring", path
);
2630 if (fprintf(fout
, "%s", c
->name
) < 0) {
2634 if (fclose(fout
) < 0)
2643 static int clone_update_rootfs_wrapper(void *data
)
2645 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
2646 return clone_update_rootfs(arg
);
2650 * We want to support:
2651 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2652 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2654 -s [ implies overlayfs]
2658 only rootfs gets converted (copied/snapshotted) on clone.
2661 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
2663 char *p
= strrchr(path
, '/');
2669 ret
= do_create_container_dir(path
, conf
);
2674 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2675 const char *lxcpath
, int flags
,
2676 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2679 struct lxc_container
*c2
= NULL
;
2680 char newpath
[MAXPATHLEN
];
2681 int ret
, storage_copied
= 0;
2682 char *origroot
= NULL
;
2683 struct clone_update_data data
;
2687 if (!c
|| !c
->is_defined(c
))
2690 if (container_mem_lock(c
))
2693 if (!is_stopped(c
)) {
2694 ERROR("error: Original container (%s) is running", c
->name
);
2698 // Make sure the container doesn't yet exist.
2702 lxcpath
= c
->get_config_path(c
);
2703 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
2704 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2705 SYSERROR("clone: failed making config pathname");
2708 if (file_exists(newpath
)) {
2709 ERROR("error: clone: %s exists", newpath
);
2713 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
2714 if (ret
< 0 && errno
!= EEXIST
) {
2715 ERROR("Error creating container dir for %s", newpath
);
2719 // copy the configuration, tweak it as needed,
2720 if (c
->lxc_conf
->rootfs
.path
) {
2721 origroot
= c
->lxc_conf
->rootfs
.path
;
2722 c
->lxc_conf
->rootfs
.path
= NULL
;
2724 fout
= fopen(newpath
, "w");
2726 SYSERROR("open %s", newpath
);
2729 write_config(fout
, c
->lxc_conf
);
2731 c
->lxc_conf
->rootfs
.path
= origroot
;
2733 sprintf(newpath
, "%s/%s/rootfs", lxcpath
, newname
);
2734 if (mkdir(newpath
, 0755) < 0) {
2735 SYSERROR("error creating %s", newpath
);
2740 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
2741 ERROR("Error chowning %s to container root", newpath
);
2746 c2
= lxc_container_new(newname
, lxcpath
);
2748 ERROR("clone: failed to create new container (%s %s)", newname
,
2753 // copy/snapshot rootfs's
2754 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2758 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
2761 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2762 ERROR("Error setting new hostname");
2767 ret
= copyhooks(c
, c2
);
2769 ERROR("error copying hooks");
2773 if (copy_fstab(c
, c2
) < 0) {
2774 ERROR("error copying fstab");
2779 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
2780 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
2781 ERROR("Error updating mac addresses");
2786 // We've now successfully created c2's storage, so clear it out if we
2790 if (!c2
->save_config(c2
, NULL
))
2793 if ((pid
= fork()) < 0) {
2798 ret
= wait_for_pid(pid
);
2801 container_mem_unlock(c
);
2807 data
.hookargs
= hookargs
;
2809 ret
= userns_exec_1(c
->lxc_conf
, clone_update_rootfs_wrapper
,
2812 ret
= clone_update_rootfs(&data
);
2816 container_mem_unlock(c
);
2820 container_mem_unlock(c
);
2822 if (!storage_copied
)
2823 c2
->lxc_conf
->rootfs
.path
= NULL
;
2825 lxc_container_put(c2
);
2831 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2834 struct lxc_container
*newc
;
2836 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
2839 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
2840 ERROR("Renaming a container with snapshots is not supported");
2843 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2845 ERROR("Failed to find original backing store type");
2849 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2852 lxc_container_put(newc
);
2856 if (newc
&& lxcapi_is_defined(newc
))
2857 lxc_container_put(newc
);
2859 if (!container_destroy(c
)) {
2860 ERROR("Could not destroy existing container %s", c
->name
);
2866 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
)
2871 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2874 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2876 lxc_attach_command_t command
;
2883 command
.program
= (char*)program
;
2884 command
.argv
= (char**)argv
;
2885 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2890 return lxc_wait_for_pid_status(pid
);
2893 static int get_next_index(const char *lxcpath
, char *cname
)
2899 fname
= alloca(strlen(lxcpath
) + 20);
2901 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2902 ret
= stat(fname
, &sb
);
2909 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
2913 * If the old style snapshot path exists, use it
2914 * /var/lib/lxc -> /var/lib/lxcsnaps
2916 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
2917 if (ret
< 0 || ret
>= MAXPATHLEN
)
2919 if (dir_exists(snappath
)) {
2920 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2921 if (ret
< 0 || ret
>= MAXPATHLEN
)
2927 * Use the new style path
2928 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
2930 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
2931 if (ret
< 0 || ret
>= MAXPATHLEN
)
2936 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2939 struct lxc_container
*c2
;
2940 char snappath
[MAXPATHLEN
], newname
[20];
2942 if (!c
|| !lxcapi_is_defined(c
))
2945 if (!bdev_can_backup(c
->lxc_conf
)) {
2946 ERROR("%s's backing store cannot be backed up.", c
->name
);
2947 ERROR("Your container must use another backing store type.");
2951 if (!get_snappath_dir(c
, snappath
))
2954 i
= get_next_index(snappath
, c
->name
);
2956 if (mkdir_p(snappath
, 0755) < 0) {
2957 ERROR("Failed to create snapshot directory %s", snappath
);
2961 ret
= snprintf(newname
, 20, "snap%d", i
);
2962 if (ret
< 0 || ret
>= 20)
2966 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2967 * created in the original container
2969 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2970 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2971 if (bdev_is_dir(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
)) {
2972 ERROR("Snapshot of directory-backed container requested.");
2973 ERROR("Making a copy-clone. If you do want snapshots, then");
2974 ERROR("please create an aufs or overlayfs clone first, snapshot that");
2975 ERROR("and keep the original container pristine.");
2976 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
2978 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2980 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
2984 lxc_container_put(c2
);
2986 // Now write down the creation time
2993 tm_info
= localtime(&timer
);
2995 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2997 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2998 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2999 f
= fopen(dfnam
, "w");
3001 ERROR("Failed to open %s", dfnam
);
3004 if (fprintf(f
, "%s", buffer
) < 0) {
3005 SYSERROR("Writing timestamp");
3011 SYSERROR("Writing timestamp");
3016 // $p / $name / comment \0
3017 int len
= strlen(snappath
) + strlen(newname
) + 10;
3018 char *path
= alloca(len
);
3019 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3020 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3026 static void lxcsnap_free(struct lxc_snapshot
*s
)
3030 if (s
->comment_pathname
)
3031 free(s
->comment_pathname
);
3038 static char *get_snapcomment_path(char* snappath
, char *name
)
3040 // $snappath/$name/comment
3041 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3042 char *s
= malloc(len
);
3045 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3046 if (ret
< 0 || ret
>= len
) {
3054 static char *get_timestamp(char* snappath
, char *name
)
3056 char path
[MAXPATHLEN
], *s
= NULL
;
3060 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3061 if (ret
< 0 || ret
>= MAXPATHLEN
)
3063 fin
= fopen(path
, "r");
3066 (void) fseek(fin
, 0, SEEK_END
);
3068 (void) fseek(fin
, 0, SEEK_SET
);
3073 if (fread(s
, 1, len
, fin
) != len
) {
3074 SYSERROR("reading timestamp");
3084 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3086 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3088 struct dirent dirent
, *direntp
;
3089 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3092 if (!c
|| !lxcapi_is_defined(c
))
3095 if (!get_snappath_dir(c
, snappath
)) {
3096 ERROR("path name too long");
3099 dir
= opendir(snappath
);
3101 INFO("failed to open %s - assuming no snapshots", snappath
);
3105 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3109 if (!strcmp(direntp
->d_name
, "."))
3112 if (!strcmp(direntp
->d_name
, ".."))
3115 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3116 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3117 ERROR("pathname too long");
3120 if (!file_exists(path2
))
3122 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3124 SYSERROR("Out of memory");
3128 snaps
[count
].free
= lxcsnap_free
;
3129 snaps
[count
].name
= strdup(direntp
->d_name
);
3130 if (!snaps
[count
].name
)
3132 snaps
[count
].lxcpath
= strdup(snappath
);
3133 if (!snaps
[count
].lxcpath
) {
3134 free(snaps
[count
].name
);
3137 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3138 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3143 WARN("failed to close directory");
3151 for (i
=0; i
<count
; i
++)
3152 lxcsnap_free(&snaps
[i
]);
3156 WARN("failed to close directory");
3160 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3162 char clonelxcpath
[MAXPATHLEN
];
3164 struct lxc_container
*snap
, *rest
;
3168 if (!c
|| !c
->name
|| !c
->config_path
)
3171 if (has_fs_snapshots(c
)) {
3172 ERROR("container rootfs has dependent snapshots");
3176 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3178 ERROR("Failed to find original backing store type");
3185 if (!get_snappath_dir(c
, clonelxcpath
)) {
3189 // how should we lock this?
3191 snap
= lxc_container_new(snapname
, clonelxcpath
);
3192 if (!snap
|| !lxcapi_is_defined(snap
)) {
3193 ERROR("Could not open snapshot %s", snapname
);
3194 if (snap
) lxc_container_put(snap
);
3199 if (strcmp(c
->name
, newname
) == 0) {
3200 if (!container_destroy(c
)) {
3201 ERROR("Could not destroy existing container %s", newname
);
3202 lxc_container_put(snap
);
3208 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
3209 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3210 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
,
3211 bdev
->type
, NULL
, 0, NULL
);
3213 if (rest
&& lxcapi_is_defined(rest
))
3216 lxc_container_put(rest
);
3217 lxc_container_put(snap
);
3221 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
3223 struct lxc_container
*snap
= NULL
;
3226 snap
= lxc_container_new(snapname
, clonelxcpath
);
3228 ERROR("Could not find snapshot %s", snapname
);
3232 if (!lxcapi_destroy(snap
)) {
3233 ERROR("Could not destroy snapshot %s", snapname
);
3240 lxc_container_put(snap
);
3244 static bool remove_all_snapshots(const char *path
)
3247 struct dirent dirent
, *direntp
;
3250 dir
= opendir(path
);
3252 SYSERROR("opendir on snapshot path %s", path
);
3255 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3258 if (!strcmp(direntp
->d_name
, "."))
3260 if (!strcmp(direntp
->d_name
, ".."))
3262 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
3271 SYSERROR("Error removing directory %s", path
);
3276 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3278 char clonelxcpath
[MAXPATHLEN
];
3280 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
3283 if (!get_snappath_dir(c
, clonelxcpath
))
3286 return do_snapshot_destroy(snapname
, clonelxcpath
);
3289 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
3291 char clonelxcpath
[MAXPATHLEN
];
3293 if (!c
|| !c
->name
|| !c
->config_path
)
3296 if (!get_snappath_dir(c
, clonelxcpath
))
3299 return remove_all_snapshots(clonelxcpath
);
3302 static bool lxcapi_may_control(struct lxc_container
*c
)
3304 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3307 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3310 char chrootpath
[MAXPATHLEN
];
3311 char *directory_path
= NULL
;
3315 if ((pid
= fork()) < 0) {
3316 SYSERROR("failed to fork a child helper");
3320 if (wait_for_pid(pid
) != 0) {
3321 ERROR("Failed to create note in guest");
3327 /* prepare the path */
3328 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3329 if (ret
< 0 || ret
>= MAXPATHLEN
)
3332 if (chroot(chrootpath
) < 0)
3336 /* remove path if it exists */
3337 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3338 if (unlink(path
) < 0) {
3339 ERROR("unlink failed");
3346 /* create any missing directories */
3347 directory_path
= dirname(strdup(path
));
3348 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3349 ERROR("failed to create directory");
3353 /* create the device node */
3354 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3355 ERROR("mknod failed");
3362 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3366 char value
[MAX_BUFFER
];
3369 /* make sure container is running */
3370 if (!c
->is_running(c
)) {
3371 ERROR("container is not running");
3375 /* use src_path if dest_path is NULL otherwise use dest_path */
3376 p
= dest_path
? dest_path
: src_path
;
3378 /* make sure we can access p */
3379 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3382 /* continue if path is character device or block device */
3383 if (S_ISCHR(st
.st_mode
))
3384 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3385 else if (S_ISBLK(st
.st_mode
))
3386 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3390 /* check snprintf return code */
3391 if (ret
< 0 || ret
>= MAX_BUFFER
)
3394 if (!do_add_remove_node(c
->init_pid(c
), p
, add
, &st
))
3397 /* add or remove device to/from cgroup access list */
3399 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3400 ERROR("set_cgroup_item failed while adding the device node");
3404 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3405 ERROR("set_cgroup_item failed while removing the device node");
3413 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3416 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3419 return add_remove_device_node(c
, src_path
, dest_path
, true);
3422 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3425 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3428 return add_remove_device_node(c
, src_path
, dest_path
, false);
3431 static bool lxcapi_attach_interface(struct lxc_container
*c
, const char *ifname
,
3432 const char *dst_ifname
)
3436 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3441 ERROR("No source interface name given");
3445 ret
= lxc_netdev_isup(ifname
);
3448 /* netdev of ifname is up. */
3449 ret
= lxc_netdev_down(ifname
);
3454 ret
= lxc_netdev_move_by_name(ifname
, c
->init_pid(c
), dst_ifname
);
3464 static bool lxcapi_detach_interface(struct lxc_container
*c
, const char *ifname
,
3465 const char *dst_ifname
)
3467 pid_t pid
, pid_outside
;
3470 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3475 ERROR("No source interface name given");
3479 pid_outside
= getpid();
3482 ERROR("failed to fork task to get interfaces information");
3486 if (pid
== 0) { // child
3488 if (!enter_net_ns(c
)) {
3489 ERROR("failed to enter namespace");
3493 ret
= lxc_netdev_isup(ifname
);
3497 /* netdev of ifname is up. */
3499 ret
= lxc_netdev_down(ifname
);
3504 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
3506 /* -EINVAL means there is no netdev named as ifanme. */
3507 if (ret
== -EINVAL
) {
3508 ERROR("No network device named as %s.", ifname
);
3513 if (wait_for_pid(pid
) != 0)
3520 /* The type of criu invocation, one of "dump" or "restore" */
3523 /* The directory to pass to criu */
3526 /* The container to dump */
3527 struct lxc_container
*c
;
3529 /* Enable criu verbose mode? */
3532 /* dump: stop the container or not after dumping? */
3535 /* restore: the file to write the init process' pid into */
3537 const char *cgroup_path
;
3540 static void exec_criu(struct criu_opts
*opts
)
3542 char **argv
, log
[PATH_MAX
], buf
[257];
3543 int static_args
= 14, argc
= 0, i
, ret
;
3545 struct lxc_list
*it
;
3547 /* The command line always looks like:
3548 * criu $(action) --tcp-established --file-locks --link-remap --force-irmap \
3549 * --manage-cgroups action-script foo.sh -D $(directory) \
3550 * -o $(directory)/$(action).log
3551 * +1 for final NULL */
3553 if (strcmp(opts
->action
, "dump") == 0) {
3557 /* --leave-running */
3560 } else if (strcmp(opts
->action
, "restore") == 0) {
3561 /* --root $(lxc_mount_point) --restore-detached
3562 * --restore-sibling --pidfile $foo --cgroup-root $foo */
3571 ret
= snprintf(log
, PATH_MAX
, "%s/%s.log", opts
->directory
, opts
->action
);
3572 if (ret
< 0 || ret
>= PATH_MAX
) {
3573 ERROR("logfile name too long\n");
3577 argv
= malloc(static_args
* sizeof(*argv
));
3581 memset(argv
, 0, static_args
* sizeof(*argv
));
3583 #define DECLARE_ARG(arg) \
3585 if (arg == NULL) { \
3586 ERROR("Got NULL argument for criu"); \
3589 argv[argc++] = strdup(arg); \
3590 if (!argv[argc-1]) \
3594 argv
[argc
++] = on_path("criu", NULL
);
3595 if (!argv
[argc
-1]) {
3596 ERROR("Couldn't find criu binary\n");
3600 DECLARE_ARG(opts
->action
);
3601 DECLARE_ARG("--tcp-established");
3602 DECLARE_ARG("--file-locks");
3603 DECLARE_ARG("--link-remap");
3604 DECLARE_ARG("--force-irmap");
3605 DECLARE_ARG("--manage-cgroups");
3606 DECLARE_ARG("--action-script");
3607 DECLARE_ARG(LIBEXECDIR
"/lxc/lxc-restore-net");
3609 DECLARE_ARG(opts
->directory
);
3614 DECLARE_ARG("-vvvvvv");
3616 if (strcmp(opts
->action
, "dump") == 0) {
3619 if (sprintf(pid
, "%d", lxcapi_init_pid(opts
->c
)) < 0)
3625 DECLARE_ARG("--leave-running");
3626 } else if (strcmp(opts
->action
, "restore") == 0) {
3627 DECLARE_ARG("--root");
3628 DECLARE_ARG(opts
->c
->lxc_conf
->rootfs
.mount
);
3629 DECLARE_ARG("--restore-detached");
3630 DECLARE_ARG("--restore-sibling");
3631 DECLARE_ARG("--pidfile");
3632 DECLARE_ARG(opts
->pidfile
);
3633 DECLARE_ARG("--cgroup-root");
3634 DECLARE_ARG(opts
->cgroup_path
);
3636 lxc_list_for_each(it
, &opts
->c
->lxc_conf
->network
) {
3637 char eth
[128], *veth
;
3639 struct lxc_netdev
*n
= it
->elem
;
3642 if (strlen(n
->name
) >= 128)
3644 strncpy(eth
, n
->name
, 128);
3646 sprintf(eth
, "eth%d", netnr
);
3648 veth
= n
->priv
.veth_attr
.pair
;
3650 ret
= snprintf(buf
, 257, "%s=%s", eth
, veth
);
3651 if (ret
< 0 || ret
>= 257)
3654 /* final NULL and --veth-pair eth0=vethASDF */
3655 m
= realloc(argv
, (argc
+ 1 + 2) * sizeof(*argv
));
3660 DECLARE_ARG("--veth-pair");
3668 lxc_list_for_each(it
, &opts
->c
->lxc_conf
->network
) {
3669 struct lxc_netdev
*n
= it
->elem
;
3673 * Here, we set some parameters that lxc-restore-net
3674 * will examine to figure out the right network to
3677 snprintf(buf
, sizeof(buf
), "LXC_CRIU_BRIDGE%d", netnr
);
3678 if (setenv(buf
, n
->link
, 1))
3681 if (strcmp("restore", opts
->action
) == 0)
3682 strncpy(veth
, n
->priv
.veth_attr
.pair
, sizeof(veth
));
3685 ret
= snprintf(buf
, sizeof(buf
), "lxc.network.%d.veth.pair", netnr
);
3686 if (ret
< 0 || ret
>= sizeof(buf
))
3688 tmp
= lxcapi_get_running_config_item(opts
->c
, buf
);
3689 strncpy(veth
, tmp
, sizeof(veth
));
3693 snprintf(buf
, sizeof(buf
), "LXC_CRIU_VETH%d", netnr
);
3694 if (setenv(buf
, veth
, 1))
3701 execv(argv
[0], argv
);
3703 for (i
= 0; argv
[i
]; i
++)
3708 /* Check and make sure the container has a configuration that we know CRIU can
3710 static bool criu_ok(struct lxc_container
*c
)
3712 struct lxc_list
*it
;
3713 bool found_deny_rule
= false;
3716 ERROR("Must be root to checkpoint\n");
3720 /* We only know how to restore containers with veth networks. */
3721 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3722 struct lxc_netdev
*n
= it
->elem
;
3723 if (n
->type
!= LXC_NET_VETH
&& n
->type
!= LXC_NET_NONE
) {
3724 ERROR("Found network that is not VETH or NONE\n");
3729 // These requirements come from http://criu.org/LXC
3730 if (c
->lxc_conf
->console
.path
&&
3731 strcmp(c
->lxc_conf
->console
.path
, "none") != 0) {
3732 ERROR("lxc.console must be none\n");
3736 if (c
->lxc_conf
->tty
!= 0) {
3737 ERROR("lxc.tty must be 0\n");
3741 lxc_list_for_each(it
, &c
->lxc_conf
->cgroup
) {
3742 struct lxc_cgroup
*cg
= it
->elem
;
3743 if (strcmp(cg
->subsystem
, "devices.deny") == 0 &&
3744 strcmp(cg
->value
, "c 5:1 rwm") == 0) {
3746 found_deny_rule
= true;
3751 if (!found_deny_rule
) {
3752 ERROR("couldn't find devices.deny = c 5:1 rwm");
3759 static bool dump_net_info(struct lxc_container
*c
, char *directory
)
3762 struct lxc_list
*it
;
3765 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3766 char *veth
= NULL
, *bridge
= NULL
, veth_path
[PATH_MAX
], eth
[128];
3767 struct lxc_netdev
*n
= it
->elem
;
3768 bool has_error
= true;
3771 pret
= snprintf(veth_path
, PATH_MAX
, "lxc.network.%d.veth.pair", netnr
);
3772 if (pret
< 0 || pret
>= PATH_MAX
)
3775 veth
= lxcapi_get_running_config_item(c
, veth_path
);
3777 /* criu_ok() checks that all interfaces are
3778 * LXC_NET{VETH,NONE}, and VETHs should have this
3780 assert(n
->type
== LXC_NET_NONE
);
3784 bridge
= lxcapi_get_running_config_item(c
, veth_path
);
3788 pret
= snprintf(veth_path
, PATH_MAX
, "%s/veth%d", directory
, netnr
);
3789 if (pret
< 0 || pret
>= PATH_MAX
|| print_to_file(veth_path
, veth
) < 0)
3793 if (strlen(n
->name
) >= 128)
3795 strncpy(eth
, n
->name
, 128);
3797 sprintf(eth
, "eth%d", netnr
);
3812 static bool lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
3820 if (mkdir(directory
, 0700) < 0 && errno
!= EEXIST
)
3823 if (!dump_net_info(c
, directory
))
3831 struct criu_opts os
;
3834 os
.directory
= directory
;
3837 os
.verbose
= verbose
;
3839 /* exec_criu() returning is an error */
3843 pid_t w
= waitpid(pid
, &status
, 0);
3849 if (WIFEXITED(status
)) {
3850 return !WEXITSTATUS(status
);
3857 static bool restore_net_info(struct lxc_container
*c
)
3859 struct lxc_list
*it
;
3860 bool has_error
= true;
3862 if (container_mem_lock(c
))
3865 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3866 struct lxc_netdev
*netdev
= it
->elem
;
3867 char template[IFNAMSIZ
];
3868 snprintf(template, sizeof(template), "vethXXXXXX");
3870 if (!netdev
->priv
.veth_attr
.pair
)
3871 netdev
->priv
.veth_attr
.pair
= lxc_mkifname(template);
3873 if (!netdev
->priv
.veth_attr
.pair
)
3880 container_mem_unlock(c
);
3884 static bool lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
3887 struct lxc_rootfs
*rootfs
;
3888 char pidfile
[L_tmpnam
];
3889 struct lxc_handler
*handler
;
3890 bool has_error
= true;
3896 ERROR("Must be root to restore\n");
3900 if (!tmpnam(pidfile
))
3903 handler
= lxc_init(c
->name
, c
->lxc_conf
, c
->config_path
);
3907 if (!cgroup_init(handler
)) {
3908 ERROR("failed initing cgroups");
3909 goto out_fini_handler
;
3912 if (!cgroup_create(handler
)) {
3913 ERROR("failed creating groups");
3914 goto out_fini_handler
;
3917 if (!restore_net_info(c
)) {
3918 ERROR("failed restoring network info");
3919 goto out_fini_handler
;
3924 goto out_fini_handler
;
3927 struct criu_opts os
;
3929 if (unshare(CLONE_NEWNS
))
3932 /* CRIU needs the lxc root bind mounted so that it is the root of some
3934 rootfs
= &c
->lxc_conf
->rootfs
;
3936 if (rootfs_is_blockdev(c
->lxc_conf
)) {
3937 if (do_rootfs_setup(c
->lxc_conf
, c
->name
, c
->config_path
) < 0)
3941 if (mkdir(rootfs
->mount
, 0755) < 0 && errno
!= EEXIST
)
3944 if (mount(rootfs
->path
, rootfs
->mount
, NULL
, MS_BIND
, NULL
) < 0) {
3945 rmdir(rootfs
->mount
);
3950 os
.action
= "restore";
3951 os
.directory
= directory
;
3953 os
.pidfile
= pidfile
;
3954 os
.verbose
= verbose
;
3955 os
.cgroup_path
= cgroup_canonical_path(handler
);
3957 /* exec_criu() returning is an error */
3959 umount(rootfs
->mount
);
3960 rmdir(rootfs
->mount
);
3965 pid_t w
= waitpid(pid
, &status
, 0);
3969 goto out_fini_handler
;
3972 if (WIFEXITED(status
)) {
3973 if (WEXITSTATUS(status
)) {
3974 goto out_fini_handler
;
3978 FILE *f
= fopen(pidfile
, "r");
3980 perror("reading pidfile");
3981 ERROR("couldn't read restore's init pidfile %s\n", pidfile
);
3982 goto out_fini_handler
;
3985 ret
= fscanf(f
, "%d", (int*) &handler
->pid
);
3988 ERROR("reading restore pid failed");
3989 goto out_fini_handler
;
3992 if (lxc_set_state(c
->name
, handler
, RUNNING
))
3993 goto out_fini_handler
;
3996 ERROR("CRIU was killed with signal %d\n", WTERMSIG(status
));
3997 goto out_fini_handler
;
4000 if (lxc_poll(c
->name
, handler
)) {
4001 lxc_abort(c
->name
, handler
);
4002 goto out_fini_handler
;
4009 lxc_fini(c
->name
, handler
);
4013 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4023 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4027 ERROR("Memory allocation error.");
4032 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4037 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4039 struct lxc_container
*c
;
4044 c
= malloc(sizeof(*c
));
4046 fprintf(stderr
, "failed to malloc lxc_container\n");
4049 memset(c
, 0, sizeof(*c
));
4052 c
->config_path
= strdup(configpath
);
4054 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4056 if (!c
->config_path
) {
4057 fprintf(stderr
, "Out of memory\n");
4061 remove_trailing_slashes(c
->config_path
);
4062 c
->name
= malloc(strlen(name
)+1);
4064 fprintf(stderr
, "Error allocating lxc_container name\n");
4067 strcpy(c
->name
, name
);
4070 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
4071 fprintf(stderr
, "failed to create lock\n");
4075 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
4076 fprintf(stderr
, "failed to alloc privlock\n");
4080 if (!set_config_filename(c
)) {
4081 fprintf(stderr
, "Error allocating config file pathname\n");
4085 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
4088 if (ongoing_create(c
) == 2) {
4089 ERROR("Error: %s creation was not completed", c
->name
);
4090 container_destroy(c
);
4091 lxcapi_clear_config(c
);
4093 c
->daemonize
= true;
4096 // assign the member functions
4097 c
->is_defined
= lxcapi_is_defined
;
4098 c
->state
= lxcapi_state
;
4099 c
->is_running
= lxcapi_is_running
;
4100 c
->freeze
= lxcapi_freeze
;
4101 c
->unfreeze
= lxcapi_unfreeze
;
4102 c
->console
= lxcapi_console
;
4103 c
->console_getfd
= lxcapi_console_getfd
;
4104 c
->init_pid
= lxcapi_init_pid
;
4105 c
->load_config
= lxcapi_load_config
;
4106 c
->want_daemonize
= lxcapi_want_daemonize
;
4107 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4108 c
->start
= lxcapi_start
;
4109 c
->startl
= lxcapi_startl
;
4110 c
->stop
= lxcapi_stop
;
4111 c
->config_file_name
= lxcapi_config_file_name
;
4112 c
->wait
= lxcapi_wait
;
4113 c
->set_config_item
= lxcapi_set_config_item
;
4114 c
->destroy
= lxcapi_destroy
;
4115 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4116 c
->rename
= lxcapi_rename
;
4117 c
->save_config
= lxcapi_save_config
;
4118 c
->get_keys
= lxcapi_get_keys
;
4119 c
->create
= lxcapi_create
;
4120 c
->createl
= lxcapi_createl
;
4121 c
->shutdown
= lxcapi_shutdown
;
4122 c
->reboot
= lxcapi_reboot
;
4123 c
->clear_config
= lxcapi_clear_config
;
4124 c
->clear_config_item
= lxcapi_clear_config_item
;
4125 c
->get_config_item
= lxcapi_get_config_item
;
4126 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4127 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4128 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4129 c
->get_config_path
= lxcapi_get_config_path
;
4130 c
->set_config_path
= lxcapi_set_config_path
;
4131 c
->clone
= lxcapi_clone
;
4132 c
->get_interfaces
= lxcapi_get_interfaces
;
4133 c
->get_ips
= lxcapi_get_ips
;
4134 c
->attach
= lxcapi_attach
;
4135 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4136 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4137 c
->snapshot
= lxcapi_snapshot
;
4138 c
->snapshot_list
= lxcapi_snapshot_list
;
4139 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4140 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4141 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4142 c
->may_control
= lxcapi_may_control
;
4143 c
->add_device_node
= lxcapi_add_device_node
;
4144 c
->remove_device_node
= lxcapi_remove_device_node
;
4145 c
->attach_interface
= lxcapi_attach_interface
;
4146 c
->detach_interface
= lxcapi_detach_interface
;
4147 c
->checkpoint
= lxcapi_checkpoint
;
4148 c
->restore
= lxcapi_restore
;
4150 /* we'll allow the caller to update these later */
4151 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
4152 fprintf(stderr
, "failed to open log\n");
4159 lxc_container_free(c
);
4163 int lxc_get_wait_states(const char **states
)
4168 for (i
=0; i
<MAX_STATE
; i
++)
4169 states
[i
] = lxc_state2str(i
);
4174 * These next two could probably be done smarter with reusing a common function
4175 * with different iterators and tests...
4177 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4180 int i
, cfound
= 0, nfound
= 0;
4181 struct dirent dirent
, *direntp
;
4182 struct lxc_container
*c
;
4185 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4187 dir
= opendir(lxcpath
);
4189 SYSERROR("opendir on lxcpath");
4198 while (!readdir_r(dir
, &dirent
, &direntp
)) {
4201 if (!strcmp(direntp
->d_name
, "."))
4203 if (!strcmp(direntp
->d_name
, ".."))
4206 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4210 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4220 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4222 INFO("Container %s:%s has a config but could not be loaded",
4223 lxcpath
, direntp
->d_name
);
4225 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4229 if (!lxcapi_is_defined(c
)) {
4230 INFO("Container %s:%s has a config but is not defined",
4231 lxcpath
, direntp
->d_name
);
4233 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4235 lxc_container_put(c
);
4239 if (!add_to_clist(cret
, c
, nfound
, true)) {
4240 lxc_container_put(c
);
4250 if (names
&& *names
) {
4251 for (i
=0; i
<cfound
; i
++)
4255 if (cret
&& *cret
) {
4256 for (i
=0; i
<nfound
; i
++)
4257 lxc_container_put((*cret
)[i
]);
4264 int list_active_containers(const char *lxcpath
, char ***nret
,
4265 struct lxc_container
***cret
)
4267 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4270 char **ct_name
= NULL
;
4272 struct lxc_container
*c
;
4276 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4277 lxcpath_len
= strlen(lxcpath
);
4284 FILE *f
= fopen("/proc/net/unix", "r");
4288 while (getline(&line
, &len
, f
) != -1) {
4290 char *p
= strrchr(line
, ' '), *p2
;
4299 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4301 } else if (strncmp(p
, "lxc/", 4) == 0) {
4311 // Now p is the start of lxc_name
4313 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4318 if (strncmp(lxcpath
, lxc_cmd_get_lxcpath(p
), lxcpath_len
) != 0)
4320 p
= lxc_cmd_get_name(p
);
4323 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4326 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4327 goto free_cret_list
;
4334 c
= lxc_container_new(p
, lxcpath
);
4336 INFO("Container %s:%s is running but could not be loaded",
4338 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4343 * If this is an anonymous container, then is_defined *can*
4344 * return false. So we don't do that check. Count on the
4345 * fact that the command socket exists.
4348 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
4349 lxc_container_put(c
);
4350 goto free_cret_list
;
4355 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
4364 if (cret
&& *cret
) {
4365 for (i
= 0; i
< cret_cnt
; i
++)
4366 lxc_container_put((*cret
)[i
]);
4372 for (i
= 0; i
< ct_name_cnt
; i
++)
4385 int list_all_containers(const char *lxcpath
, char ***nret
,
4386 struct lxc_container
***cret
)
4388 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
4391 struct lxc_container
**ct_list
= NULL
;
4393 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
4397 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
4398 if (active_cnt
< 0) {
4403 for (i
= 0; i
< active_cnt
; i
++) {
4404 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
4405 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
4407 goto free_active_name
;
4411 free(active_name
[i
]);
4412 active_name
[i
] = NULL
;
4418 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
4419 struct lxc_container
*c
;
4421 c
= lxc_container_new(ct_name
[i
], lxcpath
);
4423 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
4424 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
4428 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
4429 lxc_container_put(c
);
4448 for (i
= 0; i
< ct_list_cnt
; i
++) {
4449 lxc_container_put(ct_list
[i
]);
4455 for (i
= 0; i
< active_cnt
; i
++) {
4457 free(active_name
[i
]);
4463 for (i
= 0; i
< ct_cnt
; i
++) {