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
)
221 c
->configfile
= NULL
;
222 free(c
->error_string
);
223 c
->error_string
= NULL
;
225 lxc_putlock(c
->slock
);
229 lxc_putlock(c
->privlock
);
235 lxc_conf_free(c
->lxc_conf
);
238 free(c
->config_path
);
239 c
->config_path
= NULL
;
245 * Consider the following case:
246 freer | racing get()er
247 ==================================================================
248 lxc_container_put() | lxc_container_get()
249 \ lxclock(c->privlock) | c->numthreads < 1? (no)
250 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
252 \ lxc_container_free() | \ lxclock() returns
253 | \ c->numthreads < 1 -> return 0
255 \ \ sem_destroy(privlock) |
257 * When the get()er checks numthreads the first time, one of the following
259 * 1. freer has set numthreads = 0. get() returns 0
260 * 2. freer is between lxclock and setting numthreads to 0. get()er will
261 * sem_wait on privlock, get lxclock after freer() drops it, then see
262 * numthreads is 0 and exit without touching lxclock again..
263 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
264 * will see --numthreads = 1 and not call lxc_container_free().
267 int lxc_container_get(struct lxc_container
*c
)
272 // if someone else has already started freeing the container, don't
273 // try to take the lock, which may be invalid
274 if (c
->numthreads
< 1)
277 if (container_mem_lock(c
))
279 if (c
->numthreads
< 1) {
280 // bail without trying to unlock, bc the privlock is now probably
285 container_mem_unlock(c
);
289 int lxc_container_put(struct lxc_container
*c
)
293 if (container_mem_lock(c
))
295 if (--c
->numthreads
< 1) {
296 container_mem_unlock(c
);
297 lxc_container_free(c
);
300 container_mem_unlock(c
);
304 static bool lxcapi_is_defined(struct lxc_container
*c
)
313 if (container_mem_lock(c
))
317 statret
= stat(c
->configfile
, &statbuf
);
323 container_mem_unlock(c
);
327 static const char *lxcapi_state(struct lxc_container
*c
)
333 s
= lxc_getstate(c
->name
, c
->config_path
);
334 return lxc_state2str(s
);
337 static bool is_stopped(struct lxc_container
*c
)
340 s
= lxc_getstate(c
->name
, c
->config_path
);
341 return (s
== STOPPED
);
344 static bool lxcapi_is_running(struct lxc_container
*c
)
351 if (!s
|| strcmp(s
, "STOPPED") == 0)
356 static bool lxcapi_freeze(struct lxc_container
*c
)
362 ret
= lxc_freeze(c
->name
, c
->config_path
);
368 static bool lxcapi_unfreeze(struct lxc_container
*c
)
374 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
380 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
386 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
390 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
391 int stdoutfd
, int stderrfd
, int escape
)
393 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
396 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
401 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
404 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
407 c
->lxc_conf
= lxc_conf_init();
410 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
415 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
417 bool ret
= false, need_disklock
= false;
423 fname
= c
->configfile
;
429 * If we're reading something other than the container's config,
430 * we only need to lock the in-memory container. If loading the
431 * container's config file, take the disk lock.
433 if (strcmp(fname
, c
->configfile
) == 0)
434 need_disklock
= true;
437 lret
= container_disk_lock(c
);
439 lret
= container_mem_lock(c
);
443 ret
= load_config_locked(c
, fname
);
446 container_disk_unlock(c
);
448 container_mem_unlock(c
);
452 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
454 if (!c
|| !c
->lxc_conf
)
456 if (container_mem_lock(c
)) {
457 ERROR("Error getting mem lock");
460 c
->daemonize
= state
;
461 container_mem_unlock(c
);
465 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
467 if (!c
|| !c
->lxc_conf
)
469 if (container_mem_lock(c
)) {
470 ERROR("Error getting mem lock");
473 c
->lxc_conf
->close_all_fds
= state
;
474 container_mem_unlock(c
);
478 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
485 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
490 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
492 /* we'll probably want to make this timeout configurable? */
493 int timeout
= 5, ret
, status
;
496 * our child is going to fork again, then exit. reap the
499 ret
= waitpid(pid
, &status
, 0);
500 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
501 DEBUG("failed waiting for first dual-fork child");
502 return lxcapi_wait(c
, "RUNNING", timeout
);
505 static bool am_single_threaded(void)
507 struct dirent dirent
, *direntp
;
511 dir
= opendir("/proc/self/task");
513 INFO("failed to open /proc/self/task");
517 while (!readdir_r(dir
, &dirent
, &direntp
)) {
521 if (!strcmp(direntp
->d_name
, "."))
524 if (!strcmp(direntp
->d_name
, ".."))
534 * I can't decide if it'd be more convenient for callers if we accept '...',
535 * or a null-terminated array (i.e. execl vs execv)
537 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
540 struct lxc_conf
*conf
;
541 bool daemonize
= false;
543 char *default_args
[] = {
549 /* container exists */
552 /* container has been setup */
556 if ((ret
= ongoing_create(c
)) < 0) {
557 ERROR("Error checking for incomplete creation");
561 ERROR("Error: %s creation was not completed", c
->name
);
564 } else if (ret
== 1) {
565 ERROR("Error: creation of %s is ongoing", c
->name
);
569 /* is this app meant to be run through lxcinit, as in lxc-execute? */
570 if (useinit
&& !argv
)
573 if (container_mem_lock(c
))
576 daemonize
= c
->daemonize
;
577 container_mem_unlock(c
);
580 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
581 return ret
== 0 ? true : false;
585 if (conf
->init_cmd
) {
586 init_cmd
[0] = conf
->init_cmd
;
595 * say, I'm not sure - what locks do we want here? Any?
596 * Is liblxc's locking enough here to protect the on disk
597 * container? We don't want to exclude things like lxc_info
598 * while container is running...
601 lxc_monitord_spawn(c
->config_path
);
608 /* Set to NULL because we don't want father unlink
609 * the PID file, child will do the free and unlink.
612 return wait_on_daemonized_start(c
, pid
);
615 /* second fork to be reparented by init */
618 SYSERROR("Error doing dual-fork");
623 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
625 SYSERROR("Error chdir()ing to /.");
628 lxc_check_inherited(conf
, true, -1);
632 open("/dev/zero", O_RDONLY
);
633 open("/dev/null", O_RDWR
);
634 open("/dev/null", O_RDWR
);
637 if (!am_single_threaded()) {
638 ERROR("Cannot start non-daemonized container when threaded");
643 /* We need to write PID file after daeminize, so we always
644 * write the right PID.
647 pid_fp
= fopen(c
->pidfile
, "w");
648 if (pid_fp
== NULL
) {
649 SYSERROR("Failed to create pidfile '%s' for '%s'",
650 c
->pidfile
, c
->name
);
654 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
655 SYSERROR("Failed to write '%s'", c
->pidfile
);
668 if (lxc_check_inherited(conf
, daemonize
, -1)) {
669 ERROR("Inherited fds found");
674 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
678 INFO("container requested reboot");
691 exit (ret
== 0 ? true : false);
693 return (ret
== 0 ? true : false);
697 * note there MUST be an ending NULL
699 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
702 char **inargs
= NULL
;
705 /* container exists */
709 va_start(ap
, useinit
);
710 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
714 ERROR("Memory allocation error.");
718 /* pass NULL if no arguments were supplied */
719 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
724 for (arg
= inargs
; *arg
; arg
++)
732 static bool lxcapi_stop(struct lxc_container
*c
)
739 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
744 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
746 int ret
= -1, lasterr
;
747 char *p
= alloca(strlen(path
)+1);
748 mode_t mask
= umask(0002);
749 ret
= mkdir(path
, 0770);
757 SYSERROR("failed to create container path %s", path
);
762 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
763 ERROR("Failed to chown container dir");
770 * create the standard expected container dir
772 static bool create_container_dir(struct lxc_container
*c
)
777 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
781 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
782 if (ret
< 0 || ret
>= len
) {
786 ret
= do_create_container_dir(s
, c
->lxc_conf
);
791 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
792 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
795 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
796 * it returns a mounted bdev on success, NULL on error.
798 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
799 struct bdev_specs
*specs
)
806 /* rootfs.path or lxcpath/lxcname/rootfs */
807 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
808 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
809 len
= strlen(rpath
) + 1;
811 ret
= snprintf(dest
, len
, "%s", rpath
);
813 const char *lxcpath
= lxcapi_get_config_path(c
);
814 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
816 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
818 if (ret
< 0 || ret
>= len
)
821 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
823 ERROR("Failed to create backing store type %s", type
);
827 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
829 /* if we are not root, chown the rootfs dir to root in the
832 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
833 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
834 ERROR("Error chowning %s to container root", bdev
->dest
);
835 suggest_default_idmap();
845 * Given the '-t' template option to lxc-create, figure out what to
846 * do. If the template is a full executable path, use that. If it
847 * is something like 'sshd', then return $templatepath/lxc-sshd.
848 * On success return the template, on error return NULL.
850 static char *get_template_path(const char *t
)
855 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
860 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
864 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
865 if (ret
< 0 || ret
>= len
) {
869 if (access(tpath
, X_OK
) < 0) {
870 SYSERROR("bad template: %s", t
);
878 static char *lxcbasename(char *path
)
880 char *p
= path
+ strlen(path
) - 1;
881 while (*p
!= '/' && p
> path
)
886 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
896 SYSERROR("failed to fork task for container creation template");
900 if (pid
== 0) { // child
901 char *patharg
, *namearg
, *rootfsarg
, *src
;
902 struct bdev
*bdev
= NULL
;
904 int ret
, len
, nargs
= 0;
906 struct lxc_conf
*conf
= c
->lxc_conf
;
912 open("/dev/zero", O_RDONLY
);
913 open("/dev/null", O_RDWR
);
914 open("/dev/null", O_RDWR
);
917 src
= c
->lxc_conf
->rootfs
.path
;
919 * for an overlay create, what the user wants is the template to fill
920 * in what will become the readonly lower layer. So don't mount for
923 if (strncmp(src
, "overlayfs:", 10) == 0)
924 src
= overlay_getlower(src
+10);
925 if (strncmp(src
, "aufs:", 5) == 0)
926 src
= overlay_getlower(src
+5);
928 bdev
= bdev_init(c
->lxc_conf
, src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
930 ERROR("Error opening rootfs");
934 if (geteuid() == 0) {
935 if (unshare(CLONE_NEWNS
) < 0) {
936 ERROR("error unsharing mounts");
939 if (detect_shared_rootfs()) {
940 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
941 SYSERROR("Failed to make / rslave to run template");
942 ERROR("Continuing...");
946 if (strcmp(bdev
->type
, "dir") && strcmp(bdev
->type
, "btrfs")) {
947 if (geteuid() != 0) {
948 ERROR("non-root users can only create btrfs and directory-backed containers");
951 if (bdev
->ops
->mount(bdev
) < 0) {
952 ERROR("Error mounting rootfs");
955 } else { // TODO come up with a better way here!
957 bdev
->dest
= strdup(bdev
->src
);
961 * create our new array, pre-pend the template name and
965 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
966 nargs
+= 4; // template, path, rootfs and name args
968 newargv
= malloc(nargs
* sizeof(*newargv
));
971 newargv
[0] = lxcbasename(tpath
);
973 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
974 patharg
= malloc(len
);
977 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
978 if (ret
< 0 || ret
>= len
)
980 newargv
[1] = patharg
;
981 len
= strlen("--name=") + strlen(c
->name
) + 1;
982 namearg
= malloc(len
);
985 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
986 if (ret
< 0 || ret
>= len
)
988 newargv
[2] = namearg
;
990 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
991 rootfsarg
= malloc(len
);
994 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
995 if (ret
< 0 || ret
>= len
)
997 newargv
[3] = rootfsarg
;
999 /* add passed-in args */
1001 for (i
= 4; i
< nargs
; i
++)
1002 newargv
[i
] = argv
[i
-4];
1004 /* add trailing NULL */
1006 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1009 newargv
[nargs
- 1] = NULL
;
1012 * If we're running the template in a mapped userns, then
1013 * we prepend the template command with:
1014 * lxc-usernsexec <-m map1> ... <-m mapn> --
1015 * and we append "--mapped-uid x", where x is the mapped uid
1018 if (!lxc_list_empty(&conf
->id_map
)) {
1022 char **n2
= malloc(n2args
* sizeof(*n2
));
1023 struct lxc_list
*it
;
1027 SYSERROR("out of memory");
1031 tpath
= "lxc-usernsexec";
1032 n2
[0] = "lxc-usernsexec";
1033 lxc_list_for_each(it
, &conf
->id_map
) {
1036 n2
= realloc(n2
, n2args
* sizeof(char *));
1039 n2
[n2args
-2] = "-m";
1040 n2
[n2args
-1] = malloc(200);
1043 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1044 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1045 map
->nsid
, map
->hostid
, map
->range
);
1046 if (ret
< 0 || ret
>= 200)
1049 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1050 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1051 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1054 if (hostid_mapped
< 0) {
1055 hostid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_UID
);
1056 n2
[n2args
++] = "-m";
1057 if (hostid_mapped
< 0) {
1058 ERROR("Could not find free uid to map");
1061 n2
[n2args
++] = malloc(200);
1062 if (!n2
[n2args
-1]) {
1063 SYSERROR("out of memory");
1066 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1067 hostid_mapped
, geteuid());
1068 if (ret
< 0 || ret
>= 200) {
1069 ERROR("string too long");
1073 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1074 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1075 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1078 if (hostgid_mapped
< 0) {
1079 hostgid_mapped
= find_unmapped_nsuid(conf
, ID_TYPE_GID
);
1080 n2
[n2args
++] = "-m";
1081 if (hostgid_mapped
< 0) {
1082 ERROR("Could not find free uid to map");
1085 n2
[n2args
++] = malloc(200);
1086 if (!n2
[n2args
-1]) {
1087 SYSERROR("out of memory");
1090 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1091 hostgid_mapped
, getegid());
1092 if (ret
< 0 || ret
>= 200) {
1093 ERROR("string too long");
1097 n2
[n2args
++] = "--";
1098 for (i
= 0; i
< nargs
; i
++)
1099 n2
[i
+ n2args
] = newargv
[i
];
1101 // Finally add "--mapped-uid $uid" to tell template what to chown
1104 n2
= realloc(n2
, n2args
* sizeof(char *));
1106 SYSERROR("out of memory");
1109 // note n2[n2args-1] is NULL
1110 n2
[n2args
-5] = "--mapped-uid";
1111 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1112 n2
[n2args
-4] = txtuid
;
1113 n2
[n2args
-3] = "--mapped-gid";
1114 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1115 n2
[n2args
-2] = txtgid
;
1116 n2
[n2args
-1] = NULL
;
1121 execvp(tpath
, newargv
);
1122 SYSERROR("failed to execute template %s", tpath
);
1126 if (wait_for_pid(pid
) != 0) {
1127 ERROR("container creation template for %s failed", c
->name
);
1134 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1142 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1146 f
= fopen(path
, "r");
1150 if (fseek(f
, 0, SEEK_END
) < 0)
1152 if ((flen
= ftell(f
)) < 0)
1154 if (fseek(f
, 0, SEEK_SET
) < 0)
1156 if ((contents
= malloc(flen
+ 1)) == NULL
)
1158 if (fread(contents
, 1, flen
, f
) != flen
)
1159 goto out_free_contents
;
1161 contents
[flen
] = '\0';
1165 goto out_free_contents
;
1168 tpath
= get_template_path(t
);
1170 ERROR("bad template: %s", t
);
1171 goto out_free_contents
;
1174 ret
= sha1sum_file(tpath
, md_value
);
1176 ERROR("Error getting sha1sum of %s", tpath
);
1178 goto out_free_contents
;
1183 f
= fopen(path
, "w");
1185 SYSERROR("reopening config for writing");
1189 fprintf(f
, "# Template used to create this container: %s\n", t
);
1191 fprintf(f
, "# Parameters passed to the template:");
1193 fprintf(f
, " %s", *argv
);
1199 fprintf(f
, "# Template script checksum (SHA-1): ");
1200 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1201 fprintf(f
, "%02x", md_value
[i
]);
1204 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1205 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1206 SYSERROR("Writing original contents");
1222 SYSERROR("Error prepending header");
1228 static void lxcapi_clear_config(struct lxc_container
*c
)
1232 lxc_conf_free(c
->lxc_conf
);
1238 static bool lxcapi_destroy(struct lxc_container
*c
);
1239 static bool container_destroy(struct lxc_container
*c
);
1240 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
1243 * create a container with the given parameters.
1244 * @c: container to be created. It has the lxcpath, name, and a starting
1245 * configuration already set
1246 * @t: the template to execute to instantiate the root filesystem and
1247 * adjust the configuration.
1248 * @bdevtype: backing store type to use. If NULL, dir will be used.
1249 * @specs: additional parameters for the backing store, i.e. LVM vg to
1252 * @argv: the arguments to pass to the template, terminated by NULL. If no
1253 * arguments, you can just pass NULL.
1255 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1256 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1268 tpath
= get_template_path(t
);
1270 ERROR("bad template: %s", t
);
1276 * If a template is passed in, and the rootfs already is defined in
1277 * the container config and exists, then * caller is trying to create
1278 * an existing container. Return an error, but do NOT delete the
1281 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1282 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1283 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1288 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1289 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1294 if (!create_container_dir(c
))
1298 * either template or rootfs.path should be set.
1299 * if both template and rootfs.path are set, template is setup as rootfs.path.
1300 * container is already created if we have a config and rootfs.path is accessible
1302 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1303 /* no template passed in and rootfs does not exist: error */
1305 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1306 /* rootfs passed into configuration, but does not exist: error */
1308 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1309 /* Rootfs already existed, user just wanted to save the
1310 * loaded configuration */
1315 /* Mark that this container is being created */
1316 if ((partial_fd
= create_partial(c
)) < 0)
1319 /* no need to get disk lock bc we have the partial locked */
1322 * Create the backing store
1323 * Note we can't do this in the same task as we use to execute the
1324 * template because of the way zfs works.
1325 * After you 'zfs create', zfs mounts the fs only in the initial
1330 SYSERROR("failed to fork task for container creation template");
1334 if (pid
== 0) { // child
1335 struct bdev
*bdev
= NULL
;
1337 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1338 ERROR("Error creating backing store type %s for %s",
1339 bdevtype
? bdevtype
: "(none)", c
->name
);
1343 /* save config file again to store the new rootfs location */
1344 if (!c
->save_config(c
, NULL
)) {
1345 ERROR("failed to save starting configuration for %s", c
->name
);
1346 // parent task won't see bdev in config so we delete it
1347 bdev
->ops
->umount(bdev
);
1348 bdev
->ops
->destroy(bdev
);
1353 if (wait_for_pid(pid
) != 0)
1356 /* reload config to get the rootfs */
1357 lxc_conf_free(c
->lxc_conf
);
1359 if (!load_config_locked(c
, c
->configfile
))
1362 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1365 // now clear out the lxc_conf we have, reload from the created
1367 lxcapi_clear_config(c
);
1370 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1371 ERROR("Error prepending header to configuration file");
1375 ret
= load_config_locked(c
, c
->configfile
);
1378 if (partial_fd
>= 0)
1379 remove_partial(c
, partial_fd
);
1382 container_destroy(c
);
1388 static bool lxcapi_reboot(struct lxc_container
*c
)
1394 if (!c
->is_running(c
))
1396 pid
= c
->init_pid(c
);
1399 if (kill(pid
, SIGINT
) < 0)
1405 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1409 int haltsignal
= SIGPWR
;
1414 if (!c
->is_running(c
))
1416 pid
= c
->init_pid(c
);
1419 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1420 haltsignal
= c
->lxc_conf
->haltsignal
;
1421 kill(pid
, haltsignal
);
1422 retv
= c
->wait(c
, "STOPPED", timeout
);
1426 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1427 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1437 * since we're going to wait for create to finish, I don't think we
1438 * need to get a copy of the arguments.
1440 va_start(ap
, flags
);
1441 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1444 ERROR("Memory allocation error.");
1448 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1455 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
1457 if (strcmp(key
, "lxc.cgroup") == 0)
1458 clear_unexp_config_line(conf
, key
, true);
1459 else if (strcmp(key
, "lxc.network") == 0)
1460 clear_unexp_config_line(conf
, key
, true);
1461 else if (strcmp(key
, "lxc.hook") == 0)
1462 clear_unexp_config_line(conf
, key
, true);
1464 clear_unexp_config_line(conf
, key
, false);
1465 if (!do_append_unexp_config_line(conf
, key
, ""))
1466 WARN("Error clearing configuration for %s", key
);
1469 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1473 if (!c
|| !c
->lxc_conf
)
1475 if (container_mem_lock(c
))
1477 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1479 do_clear_unexp_config_line(c
->lxc_conf
, key
);
1480 container_mem_unlock(c
);
1484 static inline bool enter_net_ns(struct lxc_container
*c
)
1486 pid_t pid
= c
->init_pid(c
);
1488 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1489 if (!switch_to_ns(pid
, "user"))
1492 return switch_to_ns(pid
, "net");
1495 // used by qsort and bsearch functions for comparing names
1496 static inline int string_cmp(char **first
, char **second
)
1498 return strcmp(*first
, *second
);
1501 // used by qsort and bsearch functions for comparing container names
1502 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1504 return strcmp((*first
)->name
, (*second
)->name
);
1507 static bool add_to_array(char ***names
, char *cname
, int pos
)
1509 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1511 ERROR("Out of memory");
1516 newnames
[pos
] = strdup(cname
);
1520 // sort the arrray as we will use binary search on it
1521 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1526 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1528 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1530 ERROR("Out of memory");
1537 // sort the arrray as we will use binary search on it
1539 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1544 static char** get_from_array(char ***names
, char *cname
, int size
)
1546 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1550 static bool array_contains(char ***names
, char *cname
, int size
) {
1551 if(get_from_array(names
, cname
, size
) != NULL
)
1556 static bool remove_from_array(char ***names
, char *cname
, int size
)
1558 char **result
= get_from_array(names
, cname
, size
);
1559 if (result
!= NULL
) {
1566 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1569 int i
, count
= 0, pipefd
[2];
1570 char **interfaces
= NULL
;
1571 char interface
[IFNAMSIZ
];
1573 if(pipe(pipefd
) < 0) {
1574 SYSERROR("pipe failed");
1580 SYSERROR("failed to fork task to get interfaces information");
1586 if (pid
== 0) { // child
1587 int ret
= 1, nbytes
;
1588 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1590 /* close the read-end of the pipe */
1593 if (!enter_net_ns(c
)) {
1594 SYSERROR("failed to enter namespace");
1598 /* Grab the list of interfaces */
1599 if (getifaddrs(&interfaceArray
)) {
1600 SYSERROR("failed to get interfaces list");
1604 /* Iterate through the interfaces */
1605 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1606 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1608 ERROR("write failed");
1617 freeifaddrs(interfaceArray
);
1619 /* close the write-end of the pipe, thus sending EOF to the reader */
1624 /* close the write-end of the pipe */
1627 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1628 if (array_contains(&interfaces
, interface
, count
))
1631 if(!add_to_array(&interfaces
, interface
, count
))
1632 ERROR("PARENT: add_to_array failed");
1636 if (wait_for_pid(pid
) != 0) {
1637 for(i
=0;i
<count
;i
++)
1638 free(interfaces
[i
]);
1643 /* close the read-end of the pipe */
1646 /* Append NULL to the array */
1648 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1653 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1656 int i
, count
= 0, pipefd
[2];
1657 char **addresses
= NULL
;
1658 char address
[INET6_ADDRSTRLEN
];
1660 if(pipe(pipefd
) < 0) {
1661 SYSERROR("pipe failed");
1667 SYSERROR("failed to fork task to get container ips");
1673 if (pid
== 0) { // child
1674 int ret
= 1, nbytes
;
1675 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1676 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1677 void *tempAddrPtr
= NULL
;
1678 char *address
= NULL
;
1680 /* close the read-end of the pipe */
1683 if (!enter_net_ns(c
)) {
1684 SYSERROR("failed to enter namespace");
1688 /* Grab the list of interfaces */
1689 if (getifaddrs(&interfaceArray
)) {
1690 SYSERROR("failed to get interfaces list");
1694 /* Iterate through the interfaces */
1695 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1696 if (tempIfAddr
->ifa_addr
== NULL
)
1699 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1700 if (family
&& strcmp(family
, "inet"))
1702 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1705 if (family
&& strcmp(family
, "inet6"))
1708 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1711 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1714 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1716 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1719 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1721 addressOutputBuffer
,
1722 sizeof(addressOutputBuffer
));
1726 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1728 ERROR("write failed");
1737 freeifaddrs(interfaceArray
);
1739 /* close the write-end of the pipe, thus sending EOF to the reader */
1744 /* close the write-end of the pipe */
1747 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1748 if(!add_to_array(&addresses
, address
, count
))
1749 ERROR("PARENT: add_to_array failed");
1753 if (wait_for_pid(pid
) != 0) {
1754 for(i
=0;i
<count
;i
++)
1760 /* close the read-end of the pipe */
1763 /* Append NULL to the array */
1765 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1770 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1774 if (!c
|| !c
->lxc_conf
)
1776 if (container_mem_lock(c
))
1778 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1779 container_mem_unlock(c
);
1783 static char* lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
1787 if (!c
|| !c
->lxc_conf
)
1789 if (container_mem_lock(c
))
1791 ret
= lxc_cmd_get_config_item(c
->name
, key
, c
->get_config_path(c
));
1792 container_mem_unlock(c
);
1796 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1799 return lxc_listconfigs(retv
, inlen
);
1801 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1802 * This is an intelligent result to show which keys are valid given
1803 * the type of nic it is
1805 if (!c
|| !c
->lxc_conf
)
1807 if (container_mem_lock(c
))
1810 if (strncmp(key
, "lxc.network.", 12) == 0)
1811 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1812 container_mem_unlock(c
);
1816 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1819 bool ret
= false, need_disklock
= false;
1823 alt_file
= c
->configfile
;
1825 return false; // should we write to stdout if no file is specified?
1827 // If we haven't yet loaded a config, load the stock config
1829 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1830 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
1835 if (!create_container_dir(c
))
1839 * If we're writing to the container's config file, take the
1840 * disk lock. Otherwise just take the memlock to protect the
1841 * struct lxc_container while we're traversing it.
1843 if (strcmp(c
->configfile
, alt_file
) == 0)
1844 need_disklock
= true;
1847 lret
= container_disk_lock(c
);
1849 lret
= container_mem_lock(c
);
1854 fout
= fopen(alt_file
, "w");
1857 write_config(fout
, c
->lxc_conf
);
1863 container_disk_unlock(c
);
1865 container_mem_unlock(c
);
1869 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1871 char path
[MAXPATHLEN
];
1876 if (container_disk_lock(c
))
1878 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1880 if (ret
< 0 || ret
> MAXPATHLEN
)
1882 f
= fopen(path
, "r");
1884 ret
= fscanf(f
, "%d", &v
);
1887 ERROR("Corrupted file %s", path
);
1892 f
= fopen(path
, "w");
1895 if (fprintf(f
, "%d\n", v
) < 0) {
1896 ERROR("Error writing new snapshots value");
1902 SYSERROR("Error writing to or closing snapshots file");
1909 container_disk_unlock(c
);
1913 static void strip_newline(char *p
)
1915 size_t len
= strlen(p
);
1918 if (p
[len
-1] == '\n')
1922 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1924 struct lxc_container
*p
;
1925 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1926 size_t pathlen
= 0, namelen
= 0;
1930 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1931 c
->config_path
, c
->name
);
1932 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1933 ERROR("Path name too long");
1936 f
= fopen(path
, "r");
1939 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1940 if (getline(&lxcname
, &namelen
, f
) == -1) {
1941 ERROR("badly formatted file %s", path
);
1944 strip_newline(lxcpath
);
1945 strip_newline(lxcname
);
1946 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1947 ERROR("Unable to find dependent container %s:%s",
1951 if (!mod_rdep(p
, inc
))
1952 ERROR("Failed to increase numsnapshots for %s:%s",
1954 lxc_container_put(p
);
1962 static bool has_fs_snapshots(struct lxc_container
*c
)
1964 char path
[MAXPATHLEN
];
1969 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1971 if (ret
< 0 || ret
> MAXPATHLEN
)
1973 f
= fopen(path
, "r");
1976 ret
= fscanf(f
, "%d", &v
);
1986 static bool has_snapshots(struct lxc_container
*c
)
1988 char path
[MAXPATHLEN
];
1989 struct dirent dirent
, *direntp
;
1993 if (!get_snappath_dir(c
, path
))
1995 dir
= opendir(path
);
1998 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2002 if (!strcmp(direntp
->d_name
, "."))
2005 if (!strcmp(direntp
->d_name
, ".."))
2014 static int lxc_rmdir_onedev_wrapper(void *data
)
2016 char *arg
= (char *) data
;
2017 return lxc_rmdir_onedev(arg
, "snaps");
2020 static int do_bdev_destroy(struct lxc_conf
*conf
)
2025 r
= bdev_init(conf
, conf
->rootfs
.path
, conf
->rootfs
.mount
, NULL
);
2029 if (r
->ops
->destroy(r
) < 0)
2035 static int bdev_destroy_wrapper(void *data
)
2037 struct lxc_conf
*conf
= data
;
2039 if (setgid(0) < 0) {
2040 ERROR("Failed to setgid to 0");
2043 if (setgroups(0, NULL
) < 0)
2044 WARN("Failed to clear groups");
2045 if (setuid(0) < 0) {
2046 ERROR("Failed to setuid to 0");
2049 return do_bdev_destroy(conf
);
2052 static bool container_destroy(struct lxc_container
*c
)
2057 if (!c
|| !lxcapi_is_defined(c
))
2060 if (container_disk_lock(c
))
2063 if (!is_stopped(c
)) {
2064 // we should queue some sort of error - in c->error_string?
2065 ERROR("container %s is not stopped", c
->name
);
2069 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
2071 ret
= userns_exec_1(c
->lxc_conf
, bdev_destroy_wrapper
, c
->lxc_conf
);
2073 ret
= do_bdev_destroy(c
->lxc_conf
);
2075 ERROR("Error destroying rootfs for %s", c
->name
);
2080 mod_all_rdeps(c
, false);
2082 const char *p1
= lxcapi_get_config_path(c
);
2083 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2084 sprintf(path
, "%s/%s", p1
, c
->name
);
2086 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
2088 ret
= lxc_rmdir_onedev(path
, "snaps");
2090 ERROR("Error destroying container directory for %s", c
->name
);
2096 container_disk_unlock(c
);
2100 static bool lxcapi_destroy(struct lxc_container
*c
)
2102 if (!c
|| !lxcapi_is_defined(c
))
2104 if (has_snapshots(c
)) {
2105 ERROR("Container %s has snapshots; not removing", c
->name
);
2109 if (has_fs_snapshots(c
)) {
2110 ERROR("container %s has snapshots on its rootfs", c
->name
);
2114 return container_destroy(c
);
2117 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
2119 static bool lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2121 if (!c
|| !lxcapi_is_defined(c
))
2123 if (!lxcapi_snapshot_destroy_all(c
)) {
2124 ERROR("Error deleting all snapshots");
2127 return lxcapi_destroy(c
);
2130 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2132 struct lxc_config_t
*config
;
2135 c
->lxc_conf
= lxc_conf_init();
2138 config
= lxc_getconfig(key
);
2141 if (config
->cb(key
, v
, c
->lxc_conf
) != 0)
2143 return do_append_unexp_config_line(c
->lxc_conf
, key
, v
);
2146 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2153 if (container_mem_lock(c
))
2156 b
= set_config_item_locked(c
, key
, v
);
2158 container_mem_unlock(c
);
2162 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2164 if (!c
|| !c
->configfile
)
2166 return strdup(c
->configfile
);
2169 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2171 if (!c
|| !c
->config_path
)
2173 return (const char *)(c
->config_path
);
2178 * Just recalculate the c->configfile based on the
2179 * c->config_path, which must be set.
2180 * The lxc_container must be locked or not yet public.
2182 static bool set_config_filename(struct lxc_container
*c
)
2187 if (!c
->config_path
)
2190 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2191 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2192 newpath
= malloc(len
);
2196 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2197 if (ret
< 0 || ret
>= len
) {
2198 fprintf(stderr
, "Error printing out config file name\n");
2203 free(c
->configfile
);
2204 c
->configfile
= newpath
;
2209 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2213 char *oldpath
= NULL
;
2218 if (container_mem_lock(c
))
2223 ERROR("Out of memory setting new lxc path");
2229 oldpath
= c
->config_path
;
2232 /* Since we've changed the config path, we have to change the
2233 * config file name too */
2234 if (!set_config_filename(c
)) {
2235 ERROR("Out of memory setting new config filename");
2237 free(c
->config_path
);
2238 c
->config_path
= oldpath
;
2243 container_mem_unlock(c
);
2248 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2258 if (container_disk_lock(c
))
2261 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2263 container_disk_unlock(c
);
2267 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2277 if (container_disk_lock(c
))
2280 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2282 container_disk_unlock(c
);
2286 const char *lxc_get_global_config_item(const char *key
)
2288 return lxc_global_config_value(key
);
2291 const char *lxc_get_version(void)
2296 static int copy_file(const char *old
, const char *new)
2303 if (file_exists(new)) {
2304 ERROR("copy destination %s exists", new);
2307 ret
= stat(old
, &sbuf
);
2309 INFO("Error stat'ing %s", old
);
2313 in
= open(old
, O_RDONLY
);
2315 SYSERROR("Error opening original file %s", old
);
2318 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2320 SYSERROR("Error opening new file %s", new);
2326 len
= read(in
, buf
, 8096);
2328 SYSERROR("Error reading old file %s", old
);
2333 ret
= write(out
, buf
, len
);
2334 if (ret
< len
) { // should we retry?
2335 SYSERROR("Error: write to new file %s was interrupted", new);
2342 // we set mode, but not owner/group
2343 ret
= chmod(new, sbuf
.st_mode
);
2345 SYSERROR("Error setting mode on %s", new);
2357 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2360 struct lxc_list
*it
;
2363 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2364 cpath
= alloca(len
);
2365 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2366 if (ret
< 0 || ret
>= len
)
2369 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2370 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2371 char *hookname
= it
->elem
;
2372 char *fname
= strrchr(hookname
, '/');
2373 char tmppath
[MAXPATHLEN
];
2374 if (!fname
) // relative path - we don't support, but maybe we should
2376 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2377 // this hook is public - ignore
2380 // copy the script, and change the entry in confile
2381 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2382 c
->config_path
, c
->name
, fname
+1);
2383 if (ret
< 0 || ret
>= MAXPATHLEN
)
2385 ret
= copy_file(it
->elem
, tmppath
);
2389 it
->elem
= strdup(tmppath
);
2391 ERROR("out of memory copying hook path");
2397 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
2398 c
->config_path
, oldc
->name
, c
->name
)) {
2399 ERROR("Error saving new hooks in clone");
2402 c
->save_config(c
, NULL
);
2407 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2409 char newpath
[MAXPATHLEN
];
2410 char *oldpath
= oldc
->lxc_conf
->fstab
;
2416 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount", false);
2418 char *p
= strrchr(oldpath
, '/');
2421 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2422 c
->config_path
, c
->name
, p
);
2423 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2424 ERROR("error printing new path for %s", oldpath
);
2427 if (file_exists(newpath
)) {
2428 ERROR("error: fstab file %s exists", newpath
);
2432 if (copy_file(oldpath
, newpath
) < 0) {
2433 ERROR("error: copying %s to %s", oldpath
, newpath
);
2436 free(c
->lxc_conf
->fstab
);
2437 c
->lxc_conf
->fstab
= strdup(newpath
);
2438 if (!c
->lxc_conf
->fstab
) {
2439 ERROR("error: allocating pathname");
2442 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount", newpath
)) {
2443 ERROR("error saving new lxctab");
2450 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2452 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2455 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2457 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2458 WARN("Error copying reverse dependencies");
2461 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2463 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2464 WARN("Error copying reverse dependencies");
2467 if (copy_file(path0
, path1
) < 0) {
2468 INFO("Error copying reverse dependencies");
2473 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2476 char path
[MAXPATHLEN
];
2480 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2482 if (ret
< 0 || ret
>= MAXPATHLEN
)
2484 f
= fopen(path
, "a");
2488 // if anything goes wrong, just return an error
2489 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2496 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2497 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2502 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
2503 bdevdata
, newsize
, &need_rdep
);
2505 ERROR("Error copying storage");
2508 free(c
->lxc_conf
->rootfs
.path
);
2509 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2511 if (!c
->lxc_conf
->rootfs
.path
) {
2512 ERROR("Out of memory while setting storage path");
2515 // We will simply append a new lxc.rootfs entry to the unexpanded config
2516 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
2517 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", c
->lxc_conf
->rootfs
.path
)) {
2518 ERROR("Error saving new rootfs to cloend config");
2521 if (flags
& LXC_CLONE_SNAPSHOT
)
2522 copy_rdepends(c
, c0
);
2524 if (!add_rdepends(c
, c0
))
2525 WARN("Error adding reverse dependency from %s to %s",
2529 mod_all_rdeps(c
, true);
2534 struct clone_update_data
{
2535 struct lxc_container
*c0
;
2536 struct lxc_container
*c1
;
2541 static int clone_update_rootfs(struct clone_update_data
*data
)
2543 struct lxc_container
*c0
= data
->c0
;
2544 struct lxc_container
*c
= data
->c1
;
2545 int flags
= data
->flags
;
2546 char **hookargs
= data
->hookargs
;
2548 char path
[MAXPATHLEN
];
2551 struct lxc_conf
*conf
= c
->lxc_conf
;
2553 /* update hostname in rootfs */
2554 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2556 if (setgid(0) < 0) {
2557 ERROR("Failed to setgid to 0");
2560 if (setuid(0) < 0) {
2561 ERROR("Failed to setuid to 0");
2564 if (setgroups(0, NULL
) < 0)
2565 WARN("Failed to clear groups");
2567 if (unshare(CLONE_NEWNS
) < 0)
2569 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2572 if (strcmp(bdev
->type
, "dir") != 0) {
2573 if (unshare(CLONE_NEWNS
) < 0) {
2574 ERROR("error unsharing mounts");
2578 if (detect_shared_rootfs()) {
2579 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
2580 SYSERROR("Failed to make / rslave");
2581 ERROR("Continuing...");
2584 if (bdev
->ops
->mount(bdev
) < 0) {
2588 } 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
)
3029 free(s
->comment_pathname
);
3034 static char *get_snapcomment_path(char* snappath
, char *name
)
3036 // $snappath/$name/comment
3037 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3038 char *s
= malloc(len
);
3041 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3042 if (ret
< 0 || ret
>= len
) {
3050 static char *get_timestamp(char* snappath
, char *name
)
3052 char path
[MAXPATHLEN
], *s
= NULL
;
3056 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3057 if (ret
< 0 || ret
>= MAXPATHLEN
)
3059 fin
= fopen(path
, "r");
3062 (void) fseek(fin
, 0, SEEK_END
);
3064 (void) fseek(fin
, 0, SEEK_SET
);
3069 if (fread(s
, 1, len
, fin
) != len
) {
3070 SYSERROR("reading timestamp");
3080 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3082 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3084 struct dirent dirent
, *direntp
;
3085 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3088 if (!c
|| !lxcapi_is_defined(c
))
3091 if (!get_snappath_dir(c
, snappath
)) {
3092 ERROR("path name too long");
3095 dir
= opendir(snappath
);
3097 INFO("failed to open %s - assuming no snapshots", snappath
);
3101 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3105 if (!strcmp(direntp
->d_name
, "."))
3108 if (!strcmp(direntp
->d_name
, ".."))
3111 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3112 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3113 ERROR("pathname too long");
3116 if (!file_exists(path2
))
3118 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3120 SYSERROR("Out of memory");
3124 snaps
[count
].free
= lxcsnap_free
;
3125 snaps
[count
].name
= strdup(direntp
->d_name
);
3126 if (!snaps
[count
].name
)
3128 snaps
[count
].lxcpath
= strdup(snappath
);
3129 if (!snaps
[count
].lxcpath
) {
3130 free(snaps
[count
].name
);
3133 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3134 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3139 WARN("failed to close directory");
3147 for (i
=0; i
<count
; i
++)
3148 lxcsnap_free(&snaps
[i
]);
3152 WARN("failed to close directory");
3156 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3158 char clonelxcpath
[MAXPATHLEN
];
3160 struct lxc_container
*snap
, *rest
;
3164 if (!c
|| !c
->name
|| !c
->config_path
)
3167 if (has_fs_snapshots(c
)) {
3168 ERROR("container rootfs has dependent snapshots");
3172 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3174 ERROR("Failed to find original backing store type");
3181 if (!get_snappath_dir(c
, clonelxcpath
)) {
3185 // how should we lock this?
3187 snap
= lxc_container_new(snapname
, clonelxcpath
);
3188 if (!snap
|| !lxcapi_is_defined(snap
)) {
3189 ERROR("Could not open snapshot %s", snapname
);
3190 if (snap
) lxc_container_put(snap
);
3195 if (strcmp(c
->name
, newname
) == 0) {
3196 if (!container_destroy(c
)) {
3197 ERROR("Could not destroy existing container %s", newname
);
3198 lxc_container_put(snap
);
3204 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
3205 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3206 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
,
3207 bdev
->type
, NULL
, 0, NULL
);
3209 if (rest
&& lxcapi_is_defined(rest
))
3212 lxc_container_put(rest
);
3213 lxc_container_put(snap
);
3217 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
3219 struct lxc_container
*snap
= NULL
;
3222 snap
= lxc_container_new(snapname
, clonelxcpath
);
3224 ERROR("Could not find snapshot %s", snapname
);
3228 if (!lxcapi_destroy(snap
)) {
3229 ERROR("Could not destroy snapshot %s", snapname
);
3236 lxc_container_put(snap
);
3240 static bool remove_all_snapshots(const char *path
)
3243 struct dirent dirent
, *direntp
;
3246 dir
= opendir(path
);
3248 SYSERROR("opendir on snapshot path %s", path
);
3251 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3254 if (!strcmp(direntp
->d_name
, "."))
3256 if (!strcmp(direntp
->d_name
, ".."))
3258 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
3267 SYSERROR("Error removing directory %s", path
);
3272 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3274 char clonelxcpath
[MAXPATHLEN
];
3276 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
3279 if (!get_snappath_dir(c
, clonelxcpath
))
3282 return do_snapshot_destroy(snapname
, clonelxcpath
);
3285 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
3287 char clonelxcpath
[MAXPATHLEN
];
3289 if (!c
|| !c
->name
|| !c
->config_path
)
3292 if (!get_snappath_dir(c
, clonelxcpath
))
3295 return remove_all_snapshots(clonelxcpath
);
3298 static bool lxcapi_may_control(struct lxc_container
*c
)
3300 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3303 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3306 char chrootpath
[MAXPATHLEN
];
3307 char *directory_path
= NULL
;
3311 if ((pid
= fork()) < 0) {
3312 SYSERROR("failed to fork a child helper");
3316 if (wait_for_pid(pid
) != 0) {
3317 ERROR("Failed to create note in guest");
3323 /* prepare the path */
3324 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3325 if (ret
< 0 || ret
>= MAXPATHLEN
)
3328 if (chroot(chrootpath
) < 0)
3332 /* remove path if it exists */
3333 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3334 if (unlink(path
) < 0) {
3335 ERROR("unlink failed");
3342 /* create any missing directories */
3343 directory_path
= dirname(strdup(path
));
3344 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3345 ERROR("failed to create directory");
3349 /* create the device node */
3350 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3351 ERROR("mknod failed");
3358 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3362 char value
[MAX_BUFFER
];
3365 /* make sure container is running */
3366 if (!c
->is_running(c
)) {
3367 ERROR("container is not running");
3371 /* use src_path if dest_path is NULL otherwise use dest_path */
3372 p
= dest_path
? dest_path
: src_path
;
3374 /* make sure we can access p */
3375 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3378 /* continue if path is character device or block device */
3379 if (S_ISCHR(st
.st_mode
))
3380 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3381 else if (S_ISBLK(st
.st_mode
))
3382 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3386 /* check snprintf return code */
3387 if (ret
< 0 || ret
>= MAX_BUFFER
)
3390 if (!do_add_remove_node(c
->init_pid(c
), p
, add
, &st
))
3393 /* add or remove device to/from cgroup access list */
3395 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3396 ERROR("set_cgroup_item failed while adding the device node");
3400 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3401 ERROR("set_cgroup_item failed while removing the device node");
3409 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3412 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3415 return add_remove_device_node(c
, src_path
, dest_path
, true);
3418 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3421 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3424 return add_remove_device_node(c
, src_path
, dest_path
, false);
3427 static bool lxcapi_attach_interface(struct lxc_container
*c
, const char *ifname
,
3428 const char *dst_ifname
)
3432 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3437 ERROR("No source interface name given");
3441 ret
= lxc_netdev_isup(ifname
);
3444 /* netdev of ifname is up. */
3445 ret
= lxc_netdev_down(ifname
);
3450 ret
= lxc_netdev_move_by_name(ifname
, c
->init_pid(c
), dst_ifname
);
3460 static bool lxcapi_detach_interface(struct lxc_container
*c
, const char *ifname
,
3461 const char *dst_ifname
)
3463 pid_t pid
, pid_outside
;
3466 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3471 ERROR("No source interface name given");
3475 pid_outside
= getpid();
3478 ERROR("failed to fork task to get interfaces information");
3482 if (pid
== 0) { // child
3484 if (!enter_net_ns(c
)) {
3485 ERROR("failed to enter namespace");
3489 ret
= lxc_netdev_isup(ifname
);
3493 /* netdev of ifname is up. */
3495 ret
= lxc_netdev_down(ifname
);
3500 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
3502 /* -EINVAL means there is no netdev named as ifanme. */
3503 if (ret
== -EINVAL
) {
3504 ERROR("No network device named as %s.", ifname
);
3509 if (wait_for_pid(pid
) != 0)
3516 /* The type of criu invocation, one of "dump" or "restore" */
3519 /* The directory to pass to criu */
3522 /* The container to dump */
3523 struct lxc_container
*c
;
3525 /* Enable criu verbose mode? */
3528 /* dump: stop the container or not after dumping? */
3531 /* restore: the file to write the init process' pid into */
3533 const char *cgroup_path
;
3536 static void exec_criu(struct criu_opts
*opts
)
3538 char **argv
, log
[PATH_MAX
], buf
[257];
3539 int static_args
= 14, argc
= 0, i
, ret
;
3541 struct lxc_list
*it
;
3543 /* The command line always looks like:
3544 * criu $(action) --tcp-established --file-locks --link-remap --force-irmap \
3545 * --manage-cgroups action-script foo.sh -D $(directory) \
3546 * -o $(directory)/$(action).log
3547 * +1 for final NULL */
3549 if (strcmp(opts
->action
, "dump") == 0) {
3553 /* --leave-running */
3556 } else if (strcmp(opts
->action
, "restore") == 0) {
3557 /* --root $(lxc_mount_point) --restore-detached
3558 * --restore-sibling --pidfile $foo --cgroup-root $foo */
3567 ret
= snprintf(log
, PATH_MAX
, "%s/%s.log", opts
->directory
, opts
->action
);
3568 if (ret
< 0 || ret
>= PATH_MAX
) {
3569 ERROR("logfile name too long\n");
3573 argv
= malloc(static_args
* sizeof(*argv
));
3577 memset(argv
, 0, static_args
* sizeof(*argv
));
3579 #define DECLARE_ARG(arg) \
3581 if (arg == NULL) { \
3582 ERROR("Got NULL argument for criu"); \
3585 argv[argc++] = strdup(arg); \
3586 if (!argv[argc-1]) \
3590 argv
[argc
++] = on_path("criu", NULL
);
3591 if (!argv
[argc
-1]) {
3592 ERROR("Couldn't find criu binary\n");
3596 DECLARE_ARG(opts
->action
);
3597 DECLARE_ARG("--tcp-established");
3598 DECLARE_ARG("--file-locks");
3599 DECLARE_ARG("--link-remap");
3600 DECLARE_ARG("--force-irmap");
3601 DECLARE_ARG("--manage-cgroups");
3602 DECLARE_ARG("--action-script");
3603 DECLARE_ARG(DATADIR
"/lxc/lxc-restore-net");
3605 DECLARE_ARG(opts
->directory
);
3610 DECLARE_ARG("-vvvvvv");
3612 if (strcmp(opts
->action
, "dump") == 0) {
3615 if (sprintf(pid
, "%d", lxcapi_init_pid(opts
->c
)) < 0)
3621 DECLARE_ARG("--leave-running");
3622 } else if (strcmp(opts
->action
, "restore") == 0) {
3623 DECLARE_ARG("--root");
3624 DECLARE_ARG(opts
->c
->lxc_conf
->rootfs
.mount
);
3625 DECLARE_ARG("--restore-detached");
3626 DECLARE_ARG("--restore-sibling");
3627 DECLARE_ARG("--pidfile");
3628 DECLARE_ARG(opts
->pidfile
);
3629 DECLARE_ARG("--cgroup-root");
3630 DECLARE_ARG(opts
->cgroup_path
);
3632 lxc_list_for_each(it
, &opts
->c
->lxc_conf
->network
) {
3633 char eth
[128], *veth
;
3635 struct lxc_netdev
*n
= it
->elem
;
3638 if (strlen(n
->name
) >= sizeof(eth
))
3640 strncpy(eth
, n
->name
, sizeof(eth
));
3642 sprintf(eth
, "eth%d", netnr
);
3644 veth
= n
->priv
.veth_attr
.pair
;
3646 ret
= snprintf(buf
, sizeof(buf
), "%s=%s", eth
, veth
);
3647 if (ret
< 0 || ret
>= sizeof(buf
))
3650 /* final NULL and --veth-pair eth0=vethASDF */
3651 m
= realloc(argv
, (argc
+ 1 + 2) * sizeof(*argv
));
3656 DECLARE_ARG("--veth-pair");
3664 lxc_list_for_each(it
, &opts
->c
->lxc_conf
->network
) {
3665 struct lxc_netdev
*n
= it
->elem
;
3669 * Here, we set some parameters that lxc-restore-net
3670 * will examine to figure out the right network to
3673 snprintf(buf
, sizeof(buf
), "LXC_CRIU_BRIDGE%d", netnr
);
3674 if (setenv(buf
, n
->link
, 1))
3677 if (strcmp("restore", opts
->action
) == 0)
3678 strncpy(veth
, n
->priv
.veth_attr
.pair
, sizeof(veth
));
3681 ret
= snprintf(buf
, sizeof(buf
), "lxc.network.%d.veth.pair", netnr
);
3682 if (ret
< 0 || ret
>= sizeof(buf
))
3684 tmp
= lxcapi_get_running_config_item(opts
->c
, buf
);
3685 strncpy(veth
, tmp
, sizeof(veth
));
3689 snprintf(buf
, sizeof(buf
), "LXC_CRIU_VETH%d", netnr
);
3690 if (setenv(buf
, veth
, 1))
3697 execv(argv
[0], argv
);
3699 for (i
= 0; argv
[i
]; i
++)
3704 /* Check and make sure the container has a configuration that we know CRIU can
3706 static bool criu_ok(struct lxc_container
*c
)
3708 struct lxc_list
*it
;
3709 bool found_deny_rule
= false;
3712 ERROR("Must be root to checkpoint\n");
3716 /* We only know how to restore containers with veth networks. */
3717 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3718 struct lxc_netdev
*n
= it
->elem
;
3719 if (n
->type
!= LXC_NET_VETH
&& n
->type
!= LXC_NET_NONE
) {
3720 ERROR("Found network that is not VETH or NONE\n");
3725 // These requirements come from http://criu.org/LXC
3726 if (c
->lxc_conf
->console
.path
&&
3727 strcmp(c
->lxc_conf
->console
.path
, "none") != 0) {
3728 ERROR("lxc.console must be none\n");
3732 if (c
->lxc_conf
->tty
!= 0) {
3733 ERROR("lxc.tty must be 0\n");
3737 lxc_list_for_each(it
, &c
->lxc_conf
->cgroup
) {
3738 struct lxc_cgroup
*cg
= it
->elem
;
3739 if (strcmp(cg
->subsystem
, "devices.deny") == 0 &&
3740 strcmp(cg
->value
, "c 5:1 rwm") == 0) {
3742 found_deny_rule
= true;
3747 if (!found_deny_rule
) {
3748 ERROR("couldn't find devices.deny = c 5:1 rwm");
3755 static bool dump_net_info(struct lxc_container
*c
, char *directory
)
3758 struct lxc_list
*it
;
3761 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3762 char *veth
= NULL
, *bridge
= NULL
, veth_path
[PATH_MAX
], eth
[128];
3763 struct lxc_netdev
*n
= it
->elem
;
3764 bool has_error
= true;
3767 pret
= snprintf(veth_path
, PATH_MAX
, "lxc.network.%d.veth.pair", netnr
);
3768 if (pret
< 0 || pret
>= PATH_MAX
)
3771 veth
= lxcapi_get_running_config_item(c
, veth_path
);
3773 /* criu_ok() checks that all interfaces are
3774 * LXC_NET{VETH,NONE}, and VETHs should have this
3776 assert(n
->type
== LXC_NET_NONE
);
3780 bridge
= lxcapi_get_running_config_item(c
, veth_path
);
3784 pret
= snprintf(veth_path
, PATH_MAX
, "%s/veth%d", directory
, netnr
);
3785 if (pret
< 0 || pret
>= PATH_MAX
|| print_to_file(veth_path
, veth
) < 0)
3789 if (strlen(n
->name
) >= 128)
3791 strncpy(eth
, n
->name
, 128);
3793 sprintf(eth
, "eth%d", netnr
);
3806 static bool lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
3814 if (mkdir(directory
, 0700) < 0 && errno
!= EEXIST
)
3817 if (!dump_net_info(c
, directory
))
3825 struct criu_opts os
;
3828 os
.directory
= directory
;
3831 os
.verbose
= verbose
;
3833 /* exec_criu() returning is an error */
3837 pid_t w
= waitpid(pid
, &status
, 0);
3843 if (WIFEXITED(status
)) {
3844 return !WEXITSTATUS(status
);
3851 static bool restore_net_info(struct lxc_container
*c
)
3853 struct lxc_list
*it
;
3854 bool has_error
= true;
3856 if (container_mem_lock(c
))
3859 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
3860 struct lxc_netdev
*netdev
= it
->elem
;
3861 char template[IFNAMSIZ
];
3862 snprintf(template, sizeof(template), "vethXXXXXX");
3864 if (!netdev
->priv
.veth_attr
.pair
)
3865 netdev
->priv
.veth_attr
.pair
= lxc_mkifname(template);
3867 if (!netdev
->priv
.veth_attr
.pair
)
3874 container_mem_unlock(c
);
3878 static bool lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
3881 struct lxc_rootfs
*rootfs
;
3882 char pidfile
[L_tmpnam
];
3883 struct lxc_handler
*handler
;
3884 bool has_error
= true;
3890 ERROR("Must be root to restore\n");
3894 if (!tmpnam(pidfile
))
3897 handler
= lxc_init(c
->name
, c
->lxc_conf
, c
->config_path
);
3901 if (!cgroup_init(handler
)) {
3902 ERROR("failed initing cgroups");
3903 goto out_fini_handler
;
3906 if (!cgroup_create(handler
)) {
3907 ERROR("failed creating groups");
3908 goto out_fini_handler
;
3911 if (!restore_net_info(c
)) {
3912 ERROR("failed restoring network info");
3913 goto out_fini_handler
;
3918 goto out_fini_handler
;
3921 struct criu_opts os
;
3923 if (unshare(CLONE_NEWNS
))
3926 /* CRIU needs the lxc root bind mounted so that it is the root of some
3928 rootfs
= &c
->lxc_conf
->rootfs
;
3930 if (rootfs_is_blockdev(c
->lxc_conf
)) {
3931 if (do_rootfs_setup(c
->lxc_conf
, c
->name
, c
->config_path
) < 0)
3935 if (mkdir(rootfs
->mount
, 0755) < 0 && errno
!= EEXIST
)
3938 if (mount(rootfs
->path
, rootfs
->mount
, NULL
, MS_BIND
, NULL
) < 0) {
3939 rmdir(rootfs
->mount
);
3944 os
.action
= "restore";
3945 os
.directory
= directory
;
3947 os
.pidfile
= pidfile
;
3948 os
.verbose
= verbose
;
3949 os
.cgroup_path
= cgroup_canonical_path(handler
);
3951 /* exec_criu() returning is an error */
3953 umount(rootfs
->mount
);
3954 rmdir(rootfs
->mount
);
3959 pid_t w
= waitpid(pid
, &status
, 0);
3963 goto out_fini_handler
;
3966 if (WIFEXITED(status
)) {
3967 if (WEXITSTATUS(status
)) {
3968 goto out_fini_handler
;
3972 FILE *f
= fopen(pidfile
, "r");
3974 perror("reading pidfile");
3975 ERROR("couldn't read restore's init pidfile %s\n", pidfile
);
3976 goto out_fini_handler
;
3979 ret
= fscanf(f
, "%d", (int*) &handler
->pid
);
3982 ERROR("reading restore pid failed");
3983 goto out_fini_handler
;
3986 if (lxc_set_state(c
->name
, handler
, RUNNING
))
3987 goto out_fini_handler
;
3990 ERROR("CRIU was killed with signal %d\n", WTERMSIG(status
));
3991 goto out_fini_handler
;
3994 if (lxc_poll(c
->name
, handler
)) {
3995 lxc_abort(c
->name
, handler
);
3996 goto out_fini_handler
;
4003 lxc_fini(c
->name
, handler
);
4007 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4017 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4021 ERROR("Memory allocation error.");
4026 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4031 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4033 struct lxc_container
*c
;
4038 c
= malloc(sizeof(*c
));
4040 fprintf(stderr
, "failed to malloc lxc_container\n");
4043 memset(c
, 0, sizeof(*c
));
4046 c
->config_path
= strdup(configpath
);
4048 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4050 if (!c
->config_path
) {
4051 fprintf(stderr
, "Out of memory\n");
4055 remove_trailing_slashes(c
->config_path
);
4056 c
->name
= malloc(strlen(name
)+1);
4058 fprintf(stderr
, "Error allocating lxc_container name\n");
4061 strcpy(c
->name
, name
);
4064 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
4065 fprintf(stderr
, "failed to create lock\n");
4069 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
4070 fprintf(stderr
, "failed to alloc privlock\n");
4074 if (!set_config_filename(c
)) {
4075 fprintf(stderr
, "Error allocating config file pathname\n");
4079 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
4082 if (ongoing_create(c
) == 2) {
4083 ERROR("Error: %s creation was not completed", c
->name
);
4084 container_destroy(c
);
4085 lxcapi_clear_config(c
);
4087 c
->daemonize
= true;
4090 // assign the member functions
4091 c
->is_defined
= lxcapi_is_defined
;
4092 c
->state
= lxcapi_state
;
4093 c
->is_running
= lxcapi_is_running
;
4094 c
->freeze
= lxcapi_freeze
;
4095 c
->unfreeze
= lxcapi_unfreeze
;
4096 c
->console
= lxcapi_console
;
4097 c
->console_getfd
= lxcapi_console_getfd
;
4098 c
->init_pid
= lxcapi_init_pid
;
4099 c
->load_config
= lxcapi_load_config
;
4100 c
->want_daemonize
= lxcapi_want_daemonize
;
4101 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4102 c
->start
= lxcapi_start
;
4103 c
->startl
= lxcapi_startl
;
4104 c
->stop
= lxcapi_stop
;
4105 c
->config_file_name
= lxcapi_config_file_name
;
4106 c
->wait
= lxcapi_wait
;
4107 c
->set_config_item
= lxcapi_set_config_item
;
4108 c
->destroy
= lxcapi_destroy
;
4109 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4110 c
->rename
= lxcapi_rename
;
4111 c
->save_config
= lxcapi_save_config
;
4112 c
->get_keys
= lxcapi_get_keys
;
4113 c
->create
= lxcapi_create
;
4114 c
->createl
= lxcapi_createl
;
4115 c
->shutdown
= lxcapi_shutdown
;
4116 c
->reboot
= lxcapi_reboot
;
4117 c
->clear_config
= lxcapi_clear_config
;
4118 c
->clear_config_item
= lxcapi_clear_config_item
;
4119 c
->get_config_item
= lxcapi_get_config_item
;
4120 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4121 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4122 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4123 c
->get_config_path
= lxcapi_get_config_path
;
4124 c
->set_config_path
= lxcapi_set_config_path
;
4125 c
->clone
= lxcapi_clone
;
4126 c
->get_interfaces
= lxcapi_get_interfaces
;
4127 c
->get_ips
= lxcapi_get_ips
;
4128 c
->attach
= lxcapi_attach
;
4129 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4130 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4131 c
->snapshot
= lxcapi_snapshot
;
4132 c
->snapshot_list
= lxcapi_snapshot_list
;
4133 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4134 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4135 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4136 c
->may_control
= lxcapi_may_control
;
4137 c
->add_device_node
= lxcapi_add_device_node
;
4138 c
->remove_device_node
= lxcapi_remove_device_node
;
4139 c
->attach_interface
= lxcapi_attach_interface
;
4140 c
->detach_interface
= lxcapi_detach_interface
;
4141 c
->checkpoint
= lxcapi_checkpoint
;
4142 c
->restore
= lxcapi_restore
;
4144 /* we'll allow the caller to update these later */
4145 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
4146 fprintf(stderr
, "failed to open log\n");
4153 lxc_container_free(c
);
4157 int lxc_get_wait_states(const char **states
)
4162 for (i
=0; i
<MAX_STATE
; i
++)
4163 states
[i
] = lxc_state2str(i
);
4168 * These next two could probably be done smarter with reusing a common function
4169 * with different iterators and tests...
4171 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4174 int i
, cfound
= 0, nfound
= 0;
4175 struct dirent dirent
, *direntp
;
4176 struct lxc_container
*c
;
4179 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4181 dir
= opendir(lxcpath
);
4183 SYSERROR("opendir on lxcpath");
4192 while (!readdir_r(dir
, &dirent
, &direntp
)) {
4195 if (!strcmp(direntp
->d_name
, "."))
4197 if (!strcmp(direntp
->d_name
, ".."))
4200 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4204 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4214 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4216 INFO("Container %s:%s has a config but could not be loaded",
4217 lxcpath
, direntp
->d_name
);
4219 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4223 if (!lxcapi_is_defined(c
)) {
4224 INFO("Container %s:%s has a config but is not defined",
4225 lxcpath
, direntp
->d_name
);
4227 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4229 lxc_container_put(c
);
4233 if (!add_to_clist(cret
, c
, nfound
, true)) {
4234 lxc_container_put(c
);
4244 if (names
&& *names
) {
4245 for (i
=0; i
<cfound
; i
++)
4249 if (cret
&& *cret
) {
4250 for (i
=0; i
<nfound
; i
++)
4251 lxc_container_put((*cret
)[i
]);
4258 int list_active_containers(const char *lxcpath
, char ***nret
,
4259 struct lxc_container
***cret
)
4261 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4264 char **ct_name
= NULL
;
4266 struct lxc_container
*c
;
4270 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4271 lxcpath_len
= strlen(lxcpath
);
4278 FILE *f
= fopen("/proc/net/unix", "r");
4282 while (getline(&line
, &len
, f
) != -1) {
4284 char *p
= strrchr(line
, ' '), *p2
;
4293 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4295 } else if (strncmp(p
, "lxc/", 4) == 0) {
4305 // Now p is the start of lxc_name
4307 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4312 if (strncmp(lxcpath
, lxc_cmd_get_lxcpath(p
), lxcpath_len
) != 0)
4314 p
= lxc_cmd_get_name(p
);
4317 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4320 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4321 goto free_cret_list
;
4328 c
= lxc_container_new(p
, lxcpath
);
4330 INFO("Container %s:%s is running but could not be loaded",
4332 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4337 * If this is an anonymous container, then is_defined *can*
4338 * return false. So we don't do that check. Count on the
4339 * fact that the command socket exists.
4342 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
4343 lxc_container_put(c
);
4344 goto free_cret_list
;
4349 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
4358 if (cret
&& *cret
) {
4359 for (i
= 0; i
< cret_cnt
; i
++)
4360 lxc_container_put((*cret
)[i
]);
4366 for (i
= 0; i
< ct_name_cnt
; i
++)
4378 int list_all_containers(const char *lxcpath
, char ***nret
,
4379 struct lxc_container
***cret
)
4381 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
4384 struct lxc_container
**ct_list
= NULL
;
4386 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
4390 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
4391 if (active_cnt
< 0) {
4396 for (i
= 0; i
< active_cnt
; i
++) {
4397 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
4398 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
4400 goto free_active_name
;
4404 free(active_name
[i
]);
4405 active_name
[i
] = NULL
;
4411 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
4412 struct lxc_container
*c
;
4414 c
= lxc_container_new(ct_name
[i
], lxcpath
);
4416 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
4417 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
4421 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
4422 lxc_container_put(c
);
4441 for (i
= 0; i
< ct_list_cnt
; i
++) {
4442 lxc_container_put(ct_list
[i
]);
4447 for (i
= 0; i
< active_cnt
; i
++) {
4448 free(active_name
[i
]);
4453 for (i
= 0; i
< ct_cnt
; i
++) {