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
33 #include <arpa/inet.h>
34 #include <sys/sysmacros.h>
36 #include <sys/mount.h>
37 #include <sys/syscall.h>
38 #include <sys/types.h>
43 #include "lxcoverlay.h"
50 #include "confile_legacy.h"
55 #include "lxccontainer.h"
58 #include "namespace.h"
68 # include <sys/mkdev.h>
74 #include <../include/ifaddrs.h>
78 #include <../include/lxcmntent.h>
83 #define MAX_BUFFER 4096
85 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
87 /* Define faccessat() if missing from the C library */
88 #ifndef HAVE_FACCESSAT
89 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
92 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
100 lxc_log_define(lxc_container
, lxc
);
102 static bool do_lxcapi_destroy(struct lxc_container
*c
);
103 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
104 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
105 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
106 static bool container_destroy(struct lxc_container
*c
);
107 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
108 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
109 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
111 static bool config_file_exists(const char *lxcpath
, const char *cname
)
113 /* $lxcpath + '/' + $cname + '/config' + \0 */
114 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
115 char *fname
= alloca(len
);
117 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
118 if (ret
< 0 || ret
>= len
)
121 return file_exists(fname
);
125 * A few functions to help detect when a container creation failed.
126 * If a container creation was killed partway through, then trying
127 * to actually start that container could harm the host. We detect
128 * this by creating a 'partial' file under the container directory,
129 * and keeping an advisory lock. When container creation completes,
130 * we remove that file. When we load or try to start a container, if
131 * we find that file, without a flock, we remove the container.
133 static int ongoing_create(struct lxc_container
*c
)
135 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
136 char *path
= alloca(len
);
140 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
141 if (ret
< 0 || ret
>= len
) {
142 ERROR("Error writing partial pathname");
146 if (!file_exists(path
))
148 fd
= open(path
, O_RDWR
);
150 // give benefit of the doubt
151 SYSERROR("Error opening partial file");
155 lk
.l_whence
= SEEK_SET
;
159 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
160 // create is still ongoing
164 // create completed but partial is still there.
169 static int create_partial(struct lxc_container
*c
)
171 // $lxcpath + '/' + $name + '/partial' + \0
172 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
173 char *path
= alloca(len
);
177 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
178 if (ret
< 0 || ret
>= len
) {
179 ERROR("Error writing partial pathname");
182 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
183 SYSERROR("Error creating partial file");
187 lk
.l_whence
= SEEK_SET
;
190 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
191 SYSERROR("Error locking partial file %s", path
);
199 static void remove_partial(struct lxc_container
*c
, int fd
)
201 // $lxcpath + '/' + $name + '/partial' + \0
202 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
203 char *path
= alloca(len
);
207 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
208 if (ret
< 0 || ret
>= len
) {
209 ERROR("Error writing partial pathname");
212 if (unlink(path
) < 0)
213 SYSERROR("Error unlink partial file %s", path
);
217 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
218 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
219 * container configuration file.
220 * The container_disk_lock also takes the container_mem_lock.
221 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
222 * NOTHING mutexes two independent programs with their own struct
223 * lxc_container for the same c->name, between API calls. For instance,
224 * c->config_read(); c->start(); Between those calls, data on disk
225 * could change (which shouldn't bother the caller unless for instance
226 * the rootfs get moved). c->config_read(); update; c->config_write();
227 * Two such updaters could race. The callers should therefore check their
228 * results. Trying to prevent that would necessarily expose us to deadlocks
229 * due to hung callers. So I prefer to keep the locks only within our own
230 * functions, not across functions.
232 * If you're going to clone while holding a lxccontainer, increment
233 * c->numthreads (under privlock) before forking. When deleting,
234 * decrement numthreads under privlock, then if it hits 0 you can delete.
235 * Do not ever use a lxccontainer whose numthreads you did not bump.
238 static void lxc_container_free(struct lxc_container
*c
)
244 c
->configfile
= NULL
;
245 free(c
->error_string
);
246 c
->error_string
= NULL
;
248 lxc_putlock(c
->slock
);
252 lxc_putlock(c
->privlock
);
258 lxc_conf_free(c
->lxc_conf
);
261 free(c
->config_path
);
262 c
->config_path
= NULL
;
268 * Consider the following case:
269 freer | racing get()er
270 ==================================================================
271 lxc_container_put() | lxc_container_get()
272 \ lxclock(c->privlock) | c->numthreads < 1? (no)
273 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
275 \ lxc_container_free() | \ lxclock() returns
276 | \ c->numthreads < 1 -> return 0
278 \ \ sem_destroy(privlock) |
280 * When the get()er checks numthreads the first time, one of the following
282 * 1. freer has set numthreads = 0. get() returns 0
283 * 2. freer is between lxclock and setting numthreads to 0. get()er will
284 * sem_wait on privlock, get lxclock after freer() drops it, then see
285 * numthreads is 0 and exit without touching lxclock again..
286 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
287 * will see --numthreads = 1 and not call lxc_container_free().
290 int lxc_container_get(struct lxc_container
*c
)
295 // if someone else has already started freeing the container, don't
296 // try to take the lock, which may be invalid
297 if (c
->numthreads
< 1)
300 if (container_mem_lock(c
))
302 if (c
->numthreads
< 1) {
303 // bail without trying to unlock, bc the privlock is now probably
308 container_mem_unlock(c
);
312 int lxc_container_put(struct lxc_container
*c
)
316 if (container_mem_lock(c
))
318 if (--c
->numthreads
< 1) {
319 container_mem_unlock(c
);
320 lxc_container_free(c
);
323 container_mem_unlock(c
);
327 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
336 if (container_mem_lock(c
))
340 statret
= stat(c
->configfile
, &statbuf
);
346 container_mem_unlock(c
);
350 #define WRAP_API(rettype, fnname) \
351 static rettype fnname(struct lxc_container *c) \
354 bool reset_config = false; \
356 if (!current_config && c && c->lxc_conf) { \
357 current_config = c->lxc_conf; \
358 reset_config = true; \
361 ret = do_##fnname(c); \
363 current_config = NULL; \
368 #define WRAP_API_1(rettype, fnname, t1) \
369 static rettype fnname(struct lxc_container *c, t1 a1) \
372 bool reset_config = false; \
374 if (!current_config && c && c->lxc_conf) { \
375 current_config = c->lxc_conf; \
376 reset_config = true; \
379 ret = do_##fnname(c, a1); \
381 current_config = NULL; \
386 #define WRAP_API_2(rettype, fnname, t1, t2) \
387 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
390 bool reset_config = false; \
392 if (!current_config && c && c->lxc_conf) { \
393 current_config = c->lxc_conf; \
394 reset_config = true; \
397 ret = do_##fnname(c, a1, a2); \
399 current_config = NULL; \
404 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
405 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
408 bool reset_config = false; \
410 if (!current_config && c && c->lxc_conf) { \
411 current_config = c->lxc_conf; \
412 reset_config = true; \
415 ret = do_##fnname(c, a1, a2, a3); \
417 current_config = NULL; \
422 WRAP_API(bool, lxcapi_is_defined
)
424 static const char *do_lxcapi_state(struct lxc_container
*c
)
430 s
= lxc_getstate(c
->name
, c
->config_path
);
431 return lxc_state2str(s
);
434 WRAP_API(const char *, lxcapi_state
)
436 static bool is_stopped(struct lxc_container
*c
)
439 s
= lxc_getstate(c
->name
, c
->config_path
);
440 return (s
== STOPPED
);
443 static bool do_lxcapi_is_running(struct lxc_container
*c
)
449 s
= do_lxcapi_state(c
);
450 if (!s
|| strcmp(s
, "STOPPED") == 0)
455 WRAP_API(bool, lxcapi_is_running
)
457 static bool do_lxcapi_freeze(struct lxc_container
*c
)
463 ret
= lxc_freeze(c
->name
, c
->config_path
);
469 WRAP_API(bool, lxcapi_freeze
)
471 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
477 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
483 WRAP_API(bool, lxcapi_unfreeze
)
485 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
491 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
495 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
497 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
498 int stdoutfd
, int stderrfd
, int escape
)
505 current_config
= c
->lxc_conf
;
506 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
507 current_config
= NULL
;
511 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
516 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
519 WRAP_API(pid_t
, lxcapi_init_pid
)
521 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
524 c
->lxc_conf
= lxc_conf_init();
527 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
532 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
534 bool ret
= false, need_disklock
= false;
540 fname
= c
->configfile
;
546 * If we're reading something other than the container's config,
547 * we only need to lock the in-memory container. If loading the
548 * container's config file, take the disk lock.
550 if (strcmp(fname
, c
->configfile
) == 0)
551 need_disklock
= true;
554 lret
= container_disk_lock(c
);
556 lret
= container_mem_lock(c
);
560 ret
= load_config_locked(c
, fname
);
563 container_disk_unlock(c
);
565 container_mem_unlock(c
);
569 WRAP_API_1(bool, lxcapi_load_config
, const char *)
571 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
573 if (!c
|| !c
->lxc_conf
)
575 if (container_mem_lock(c
)) {
576 ERROR("Error getting mem lock");
579 c
->daemonize
= state
;
580 container_mem_unlock(c
);
584 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
586 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
588 if (!c
|| !c
->lxc_conf
)
590 if (container_mem_lock(c
)) {
591 ERROR("Error getting mem lock");
594 c
->lxc_conf
->close_all_fds
= state
;
595 container_mem_unlock(c
);
599 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
601 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
608 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
612 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
614 static bool do_wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
616 /* we'll probably want to make this timeout configurable? */
617 int timeout
= 5, ret
, status
;
620 * our child is going to fork again, then exit. reap the
623 ret
= waitpid(pid
, &status
, 0);
624 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
625 DEBUG("failed waiting for first dual-fork child");
626 return do_lxcapi_wait(c
, "RUNNING", timeout
);
629 WRAP_API_1(bool, wait_on_daemonized_start
, int)
631 static bool am_single_threaded(void)
633 struct dirent
*direntp
;
637 dir
= opendir("/proc/self/task");
639 INFO("failed to open /proc/self/task");
643 while ((direntp
= readdir(dir
))) {
647 if (!strcmp(direntp
->d_name
, "."))
650 if (!strcmp(direntp
->d_name
, ".."))
659 static void push_arg(char ***argp
, char *arg
, int *nargs
)
668 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
676 static char **split_init_cmd(const char *incmd
)
680 char *copy
, *p
, *saveptr
= NULL
;
686 len
= strlen(incmd
) + 1;
688 strncpy(copy
, incmd
, len
);
692 argv
= malloc(sizeof(char *));
695 for (p
= strtok_r(copy
, " ", &saveptr
); p
!= NULL
;
696 p
= strtok_r(NULL
, " ", &saveptr
))
697 push_arg(&argv
, p
, &nargs
);
706 static void free_init_cmd(char **argv
)
717 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
720 struct lxc_handler
*handler
;
721 struct lxc_conf
*conf
;
722 bool daemonize
= false;
724 char *default_args
[] = {
728 char **init_cmd
= NULL
;
730 /* container exists */
734 /* If anything fails before we set error_num, we want an error in there */
737 /* container has not been setup */
741 ret
= ongoing_create(c
);
743 ERROR("Error checking for incomplete creation");
745 } else if (ret
== 1) {
746 ERROR("Error: creation of %s is ongoing", c
->name
);
748 } else if (ret
== 2) {
749 ERROR("Error: %s creation was not completed", c
->name
);
750 do_lxcapi_destroy(c
);
754 /* is this app meant to be run through lxcinit, as in lxc-execute? */
755 if (useinit
&& !argv
)
758 if (container_mem_lock(c
))
761 daemonize
= c
->daemonize
;
763 /* initialize handler */
764 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
);
765 container_mem_unlock(c
);
770 TRACE("calling \"lxc_execute\"");
771 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
774 return ret
== 0 ? true : false;
777 /* if no argv was passed in, use lxc.init_cmd if provided in
780 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
782 /* ... and otherwise use default_args */
787 * say, I'm not sure - what locks do we want here? Any?
788 * Is liblxc's locking enough here to protect the on disk
789 * container? We don't want to exclude things like lxc_info
790 * while container is running...
798 free_init_cmd(init_cmd
);
799 lxc_free_handler(handler
);
804 /* Set to NULL because we don't want father unlink
805 * the PID file, child will do the free and unlink.
808 close(handler
->conf
->maincmd_fd
);
809 return wait_on_daemonized_start(c
, pid
);
812 /* We don't really care if this doesn't print all the
813 * characters; all that it means is that the proctitle will be
814 * ugly. Similarly, we also don't care if setproctitle()
816 snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
817 INFO("Attempting to set proc title to %s", title
);
820 /* second fork to be reparented by init */
823 SYSERROR("Error doing dual-fork");
828 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
830 SYSERROR("Error chdir()ing to /.");
833 lxc_check_inherited(conf
, true, handler
->conf
->maincmd_fd
);
834 if (null_stdfds() < 0) {
835 ERROR("failed to close fds");
840 if (!am_single_threaded()) {
841 ERROR("Cannot start non-daemonized container when threaded");
842 lxc_free_handler(handler
);
847 /* We need to write PID file after daemonize, so we always
848 * write the right PID.
851 pid_fp
= fopen(c
->pidfile
, "w");
852 if (pid_fp
== NULL
) {
853 SYSERROR("Failed to create pidfile '%s' for '%s'",
854 c
->pidfile
, c
->name
);
855 free_init_cmd(init_cmd
);
856 lxc_free_handler(handler
);
862 if (fprintf(pid_fp
, "%d\n", getpid()) < 0) {
863 SYSERROR("Failed to write '%s'", c
->pidfile
);
866 free_init_cmd(init_cmd
);
867 lxc_free_handler(handler
);
879 /* Unshare the mount namespace if requested */
880 if (conf
->monitor_unshare
) {
881 if (unshare(CLONE_NEWNS
)) {
882 SYSERROR("failed to unshare mount namespace");
883 free_init_cmd(init_cmd
);
884 lxc_free_handler(handler
);
887 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
888 SYSERROR("Failed to make / rslave at startup");
889 free_init_cmd(init_cmd
);
890 lxc_free_handler(handler
);
896 if (conf
->reboot
== 2) {
897 /* initialize handler */
898 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
);
903 if (lxc_check_inherited(conf
, daemonize
, handler
->conf
->maincmd_fd
)) {
904 ERROR("Inherited fds found");
905 lxc_free_handler(handler
);
910 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
, daemonize
);
913 if (conf
->reboot
== 1) {
914 INFO("container requested reboot");
925 free_init_cmd(init_cmd
);
928 exit(ret
== 0 ? true : false);
929 return (ret
== 0 ? true : false);
932 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
935 current_config
= c
? c
->lxc_conf
: NULL
;
936 ret
= do_lxcapi_start(c
, useinit
, argv
);
937 current_config
= NULL
;
942 * note there MUST be an ending NULL
944 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
947 char **inargs
= NULL
;
950 /* container exists */
954 current_config
= c
->lxc_conf
;
956 va_start(ap
, useinit
);
957 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
961 ERROR("Memory allocation error.");
965 /* pass NULL if no arguments were supplied */
966 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
971 for (arg
= inargs
; *arg
; arg
++)
976 current_config
= NULL
;
980 static bool do_lxcapi_stop(struct lxc_container
*c
)
987 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
992 WRAP_API(bool, lxcapi_stop
)
994 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
996 int ret
= -1, lasterr
;
997 char *p
= alloca(strlen(path
)+1);
998 mode_t mask
= umask(0002);
999 ret
= mkdir(path
, 0770);
1004 if (errno
== EEXIST
)
1007 SYSERROR("failed to create container path %s", path
);
1012 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
1013 ERROR("Failed to chown container dir");
1020 * create the standard expected container dir
1022 static bool create_container_dir(struct lxc_container
*c
)
1027 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1031 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1032 if (ret
< 0 || ret
>= len
) {
1036 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1042 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
1043 * it returns a mounted bdev on success, NULL on error.
1045 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
1046 struct bdev_specs
*specs
)
1053 /* rootfs.path or lxcpath/lxcname/rootfs */
1054 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
1055 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1056 len
= strlen(rpath
) + 1;
1058 ret
= snprintf(dest
, len
, "%s", rpath
);
1060 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1061 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1063 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1065 if (ret
< 0 || ret
>= len
)
1068 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
1070 ERROR("Failed to create backing store type %s", type
);
1074 do_lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
1075 do_lxcapi_set_config_item(c
, "lxc.rootfs.backend", bdev
->type
);
1077 /* if we are not root, chown the rootfs dir to root in the
1080 if (geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1081 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
1082 ERROR("Error chowning %s to container root", bdev
->dest
);
1083 suggest_default_idmap();
1092 static char *lxcbasename(char *path
)
1094 char *p
= path
+ strlen(path
) - 1;
1095 while (*p
!= '/' && p
> path
)
1100 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool need_null_stdfds
,
1110 SYSERROR("failed to fork task for container creation template");
1114 if (pid
== 0) { // child
1115 char *patharg
, *namearg
, *rootfsarg
;
1116 struct bdev
*bdev
= NULL
;
1118 int ret
, len
, nargs
= 0;
1120 struct lxc_conf
*conf
= c
->lxc_conf
;
1122 if (need_null_stdfds
&& null_stdfds() < 0) {
1126 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1128 ERROR("Error opening rootfs");
1132 if (geteuid() == 0) {
1133 if (unshare(CLONE_NEWNS
) < 0) {
1134 ERROR("error unsharing mounts");
1137 if (detect_shared_rootfs()) {
1138 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
1139 SYSERROR("Failed to make / rslave to run template");
1140 ERROR("Continuing...");
1144 if (strcmp(bdev
->type
, "dir") && strcmp(bdev
->type
, "btrfs")) {
1145 if (geteuid() != 0) {
1146 ERROR("non-root users can only create btrfs and directory-backed containers");
1149 if (bdev
->ops
->mount(bdev
) < 0) {
1150 ERROR("Error mounting rootfs");
1153 } else { // TODO come up with a better way here!
1155 bdev
->dest
= strdup(bdev
->src
);
1159 * create our new array, pre-pend the template name and
1163 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
1164 nargs
+= 4; // template, path, rootfs and name args
1166 newargv
= malloc(nargs
* sizeof(*newargv
));
1169 newargv
[0] = lxcbasename(tpath
);
1171 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1172 patharg
= malloc(len
);
1175 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1176 if (ret
< 0 || ret
>= len
)
1178 newargv
[1] = patharg
;
1179 len
= strlen("--name=") + strlen(c
->name
) + 1;
1180 namearg
= malloc(len
);
1183 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1184 if (ret
< 0 || ret
>= len
)
1186 newargv
[2] = namearg
;
1188 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1189 rootfsarg
= malloc(len
);
1192 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1193 if (ret
< 0 || ret
>= len
)
1195 newargv
[3] = rootfsarg
;
1197 /* add passed-in args */
1199 for (i
= 4; i
< nargs
; i
++)
1200 newargv
[i
] = argv
[i
-4];
1202 /* add trailing NULL */
1204 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1207 newargv
[nargs
- 1] = NULL
;
1210 * If we're running the template in a mapped userns, then
1211 * we prepend the template command with:
1212 * lxc-usernsexec <-m map1> ... <-m mapn> --
1213 * and we append "--mapped-uid x", where x is the mapped uid
1216 if (!lxc_list_empty(&conf
->id_map
)) {
1220 char **n2
= malloc(n2args
* sizeof(*n2
));
1221 struct lxc_list
*it
;
1225 SYSERROR("out of memory");
1229 tpath
= "lxc-usernsexec";
1230 n2
[0] = "lxc-usernsexec";
1231 lxc_list_for_each(it
, &conf
->id_map
) {
1234 n2
= realloc(n2
, n2args
* sizeof(char *));
1237 n2
[n2args
-2] = "-m";
1238 n2
[n2args
-1] = malloc(200);
1241 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
1242 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1243 map
->nsid
, map
->hostid
, map
->range
);
1244 if (ret
< 0 || ret
>= 200)
1247 int hostid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1248 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
1249 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1252 if (hostid_mapped
< 0) {
1253 hostid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1254 n2
[n2args
++] = "-m";
1255 if (hostid_mapped
< 0) {
1256 ERROR("Could not find free uid to map");
1259 n2
[n2args
++] = malloc(200);
1260 if (!n2
[n2args
-1]) {
1261 SYSERROR("out of memory");
1264 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1265 hostid_mapped
, geteuid());
1266 if (ret
< 0 || ret
>= 200) {
1267 ERROR("string too long");
1271 int hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1272 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1273 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1276 if (hostgid_mapped
< 0) {
1277 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1278 n2
[n2args
++] = "-m";
1279 if (hostgid_mapped
< 0) {
1280 ERROR("Could not find free uid to map");
1283 n2
[n2args
++] = malloc(200);
1284 if (!n2
[n2args
-1]) {
1285 SYSERROR("out of memory");
1288 ret
= snprintf(n2
[n2args
-1], 200, "g:%d:%d:1",
1289 hostgid_mapped
, getegid());
1290 if (ret
< 0 || ret
>= 200) {
1291 ERROR("string too long");
1295 n2
[n2args
++] = "--";
1296 for (i
= 0; i
< nargs
; i
++)
1297 n2
[i
+ n2args
] = newargv
[i
];
1299 // Finally add "--mapped-uid $uid" to tell template what to chown
1302 n2
= realloc(n2
, n2args
* sizeof(char *));
1304 SYSERROR("out of memory");
1307 // note n2[n2args-1] is NULL
1308 n2
[n2args
-5] = "--mapped-uid";
1309 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1310 n2
[n2args
-4] = txtuid
;
1311 n2
[n2args
-3] = "--mapped-gid";
1312 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1313 n2
[n2args
-2] = txtgid
;
1314 n2
[n2args
-1] = NULL
;
1319 execvp(tpath
, newargv
);
1320 SYSERROR("failed to execute template %s", tpath
);
1324 if (wait_for_pid(pid
) != 0) {
1325 ERROR("container creation template for %s failed", c
->name
);
1332 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1340 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1344 f
= fopen(path
, "r");
1348 if (fseek(f
, 0, SEEK_END
) < 0)
1350 if ((flen
= ftell(f
)) < 0)
1352 if (fseek(f
, 0, SEEK_SET
) < 0)
1354 if ((contents
= malloc(flen
+ 1)) == NULL
)
1356 if (fread(contents
, 1, flen
, f
) != flen
)
1357 goto out_free_contents
;
1359 contents
[flen
] = '\0';
1363 goto out_free_contents
;
1366 tpath
= get_template_path(t
);
1368 ERROR("bad template: %s", t
);
1369 goto out_free_contents
;
1372 ret
= sha1sum_file(tpath
, md_value
);
1374 ERROR("Error getting sha1sum of %s", tpath
);
1376 goto out_free_contents
;
1381 f
= fopen(path
, "w");
1383 SYSERROR("reopening config for writing");
1387 fprintf(f
, "# Template used to create this container: %s\n", t
);
1389 fprintf(f
, "# Parameters passed to the template:");
1391 fprintf(f
, " %s", *argv
);
1397 fprintf(f
, "# Template script checksum (SHA-1): ");
1398 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1399 fprintf(f
, "%02x", md_value
[i
]);
1402 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1403 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1404 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1405 fprintf(f
, "# (Be aware this has security implications)\n\n");
1406 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1407 SYSERROR("Writing original contents");
1423 SYSERROR("Error prepending header");
1429 static void lxcapi_clear_config(struct lxc_container
*c
)
1433 lxc_conf_free(c
->lxc_conf
);
1439 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1443 * create a container with the given parameters.
1444 * @c: container to be created. It has the lxcpath, name, and a starting
1445 * configuration already set
1446 * @t: the template to execute to instantiate the root filesystem and
1447 * adjust the configuration.
1448 * @bdevtype: backing store type to use. If NULL, dir will be used.
1449 * @specs: additional parameters for the backing store, i.e. LVM vg to
1452 * @argv: the arguments to pass to the template, terminated by NULL. If no
1453 * arguments, you can just pass NULL.
1455 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1456 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1468 tpath
= get_template_path(t
);
1470 ERROR("bad template: %s", t
);
1476 * If a template is passed in, and the rootfs already is defined in
1477 * the container config and exists, then * caller is trying to create
1478 * an existing container. Return an error, but do NOT delete the
1481 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1482 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1483 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1488 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1489 ERROR("Error loading default configuration file %s", lxc_global_config_value("lxc.default_config"));
1494 if (!create_container_dir(c
))
1498 * if both template and rootfs.path are set, template is setup as rootfs.path.
1499 * container is already created if we have a config and rootfs.path is accessible
1501 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1502 /* no template passed in and rootfs does not exist */
1503 if (!c
->save_config(c
, NULL
)) {
1504 ERROR("failed to save starting configuration for %s\n", c
->name
);
1510 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1511 /* rootfs passed into configuration, but does not exist: error */
1513 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1514 /* Rootfs already existed, user just wanted to save the
1515 * loaded configuration */
1516 if (!c
->save_config(c
, NULL
))
1517 ERROR("failed to save starting configuration for %s\n", c
->name
);
1522 /* Mark that this container is being created */
1523 if ((partial_fd
= create_partial(c
)) < 0)
1526 /* no need to get disk lock bc we have the partial locked */
1529 * Create the backing store
1530 * Note we can't do this in the same task as we use to execute the
1531 * template because of the way zfs works.
1532 * After you 'zfs create', zfs mounts the fs only in the initial
1537 SYSERROR("failed to fork task for container creation template");
1541 if (pid
== 0) { // child
1542 struct bdev
*bdev
= NULL
;
1544 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1545 ERROR("Error creating backing store type %s for %s",
1546 bdevtype
? bdevtype
: "(none)", c
->name
);
1550 /* save config file again to store the new rootfs location */
1551 if (!do_lxcapi_save_config(c
, NULL
)) {
1552 ERROR("failed to save starting configuration for %s", c
->name
);
1553 // parent task won't see bdev in config so we delete it
1554 bdev
->ops
->umount(bdev
);
1555 bdev
->ops
->destroy(bdev
);
1560 if (wait_for_pid(pid
) != 0)
1563 /* reload config to get the rootfs */
1564 lxc_conf_free(c
->lxc_conf
);
1566 if (!load_config_locked(c
, c
->configfile
))
1569 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1572 // now clear out the lxc_conf we have, reload from the created
1574 do_lxcapi_clear_config(c
);
1577 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1578 ERROR("Error prepending header to configuration file");
1582 ret
= load_config_locked(c
, c
->configfile
);
1585 if (partial_fd
>= 0)
1586 remove_partial(c
, partial_fd
);
1589 container_destroy(c
);
1595 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1596 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1600 current_config
= c
? c
->lxc_conf
: NULL
;
1601 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1602 current_config
= NULL
;
1606 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1609 int rebootsignal
= SIGINT
;
1613 if (!do_lxcapi_is_running(c
))
1615 pid
= do_lxcapi_init_pid(c
);
1618 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1619 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1620 if (kill(pid
, rebootsignal
) < 0) {
1621 WARN("Could not send signal %d to pid %d.", rebootsignal
, pid
);
1628 WRAP_API(bool, lxcapi_reboot
)
1630 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1634 int haltsignal
= SIGPWR
;
1639 if (!do_lxcapi_is_running(c
))
1641 pid
= do_lxcapi_init_pid(c
);
1645 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
1646 if (task_blocking_signal(pid
, (SIGRTMIN
+ 3)))
1647 haltsignal
= (SIGRTMIN
+ 3);
1649 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1650 haltsignal
= c
->lxc_conf
->haltsignal
;
1652 INFO("Using signal number '%d' as halt signal.", haltsignal
);
1654 if (kill(pid
, haltsignal
) < 0)
1655 WARN("Could not send signal %d to pid %d.", haltsignal
, pid
);
1657 retv
= do_lxcapi_wait(c
, "STOPPED", timeout
);
1661 WRAP_API_1(bool, lxcapi_shutdown
, int)
1663 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1664 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1673 current_config
= c
->lxc_conf
;
1676 * since we're going to wait for create to finish, I don't think we
1677 * need to get a copy of the arguments.
1679 va_start(ap
, flags
);
1680 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1683 ERROR("Memory allocation error.");
1687 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
1691 current_config
= NULL
;
1695 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
1697 if (strcmp(key
, "lxc.cgroup") == 0)
1698 clear_unexp_config_line(conf
, key
, true);
1699 else if (strcmp(key
, "lxc.network") == 0)
1700 clear_unexp_config_line(conf
, key
, true);
1701 else if (strcmp(key
, "lxc.net") == 0)
1702 clear_unexp_config_line(conf
, key
, true);
1703 else if (strcmp(key
, "lxc.hook") == 0)
1704 clear_unexp_config_line(conf
, key
, true);
1706 clear_unexp_config_line(conf
, key
, false);
1707 if (!do_append_unexp_config_line(conf
, key
, ""))
1708 WARN("Error clearing configuration for %s", key
);
1711 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
1715 struct lxc_config_t
*config
;
1717 if (!c
|| !c
->lxc_conf
)
1720 if (container_mem_lock(c
))
1723 config
= lxc_getconfig(key
);
1724 /* Verify that the config key exists and that it has a callback
1727 if (config
&& config
->clr
)
1728 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
1730 do_clear_unexp_config_line(c
->lxc_conf
, key
);
1732 container_mem_unlock(c
);
1736 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
1738 static inline bool enter_net_ns(struct lxc_container
*c
)
1740 pid_t pid
= do_lxcapi_init_pid(c
);
1742 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
1743 if (!switch_to_ns(pid
, "user"))
1746 return switch_to_ns(pid
, "net");
1749 // used by qsort and bsearch functions for comparing names
1750 static inline int string_cmp(char **first
, char **second
)
1752 return strcmp(*first
, *second
);
1755 // used by qsort and bsearch functions for comparing container names
1756 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1758 return strcmp((*first
)->name
, (*second
)->name
);
1761 static bool add_to_array(char ***names
, char *cname
, int pos
)
1763 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1765 ERROR("Out of memory");
1770 newnames
[pos
] = strdup(cname
);
1774 // sort the arrray as we will use binary search on it
1775 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1780 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1782 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1784 ERROR("Out of memory");
1791 // sort the arrray as we will use binary search on it
1793 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1798 static char** get_from_array(char ***names
, char *cname
, int size
)
1800 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1804 static bool array_contains(char ***names
, char *cname
, int size
) {
1805 if(get_from_array(names
, cname
, size
) != NULL
)
1810 static bool remove_from_array(char ***names
, char *cname
, int size
)
1812 char **result
= get_from_array(names
, cname
, size
);
1813 if (result
!= NULL
) {
1820 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
1823 int i
, count
= 0, pipefd
[2];
1824 char **interfaces
= NULL
;
1825 char interface
[IFNAMSIZ
];
1827 if(pipe(pipefd
) < 0) {
1828 SYSERROR("pipe failed");
1834 SYSERROR("failed to fork task to get interfaces information");
1840 if (pid
== 0) { // child
1841 int ret
= 1, nbytes
;
1842 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1844 /* close the read-end of the pipe */
1847 if (!enter_net_ns(c
)) {
1848 SYSERROR("failed to enter namespace");
1852 /* Grab the list of interfaces */
1853 if (getifaddrs(&interfaceArray
)) {
1854 SYSERROR("failed to get interfaces list");
1858 /* Iterate through the interfaces */
1859 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1860 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1862 ERROR("write failed");
1871 freeifaddrs(interfaceArray
);
1873 /* close the write-end of the pipe, thus sending EOF to the reader */
1878 /* close the write-end of the pipe */
1881 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1882 if (array_contains(&interfaces
, interface
, count
))
1885 if(!add_to_array(&interfaces
, interface
, count
))
1886 ERROR("PARENT: add_to_array failed");
1890 if (wait_for_pid(pid
) != 0) {
1891 for(i
=0;i
<count
;i
++)
1892 free(interfaces
[i
]);
1897 /* close the read-end of the pipe */
1900 /* Append NULL to the array */
1902 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1907 WRAP_API(char **, lxcapi_get_interfaces
)
1909 static char** do_lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1912 int i
, count
= 0, pipefd
[2];
1913 char **addresses
= NULL
;
1914 char address
[INET6_ADDRSTRLEN
];
1916 if(pipe(pipefd
) < 0) {
1917 SYSERROR("pipe failed");
1923 SYSERROR("failed to fork task to get container ips");
1929 if (pid
== 0) { // child
1930 int ret
= 1, nbytes
;
1931 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1932 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1933 void *tempAddrPtr
= NULL
;
1934 char *address
= NULL
;
1936 /* close the read-end of the pipe */
1939 if (!enter_net_ns(c
)) {
1940 SYSERROR("failed to enter namespace");
1944 /* Grab the list of interfaces */
1945 if (getifaddrs(&interfaceArray
)) {
1946 SYSERROR("failed to get interfaces list");
1950 /* Iterate through the interfaces */
1951 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1952 if (tempIfAddr
->ifa_addr
== NULL
)
1955 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1956 if (family
&& strcmp(family
, "inet"))
1958 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1961 if (family
&& strcmp(family
, "inet6"))
1964 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1967 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1970 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1972 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1975 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1977 addressOutputBuffer
,
1978 sizeof(addressOutputBuffer
));
1982 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1984 ERROR("write failed");
1993 freeifaddrs(interfaceArray
);
1995 /* close the write-end of the pipe, thus sending EOF to the reader */
2000 /* close the write-end of the pipe */
2003 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2004 if(!add_to_array(&addresses
, address
, count
))
2005 ERROR("PARENT: add_to_array failed");
2009 if (wait_for_pid(pid
) != 0) {
2010 for(i
=0;i
<count
;i
++)
2016 /* close the read-end of the pipe */
2019 /* Append NULL to the array */
2021 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2026 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2028 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2031 struct lxc_config_t
*config
;
2033 if (!c
|| !c
->lxc_conf
)
2036 if (container_mem_lock(c
))
2039 config
= lxc_getconfig(key
);
2040 /* Verify that the config key exists and that it has a callback
2043 if (config
&& config
->get
)
2044 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2046 container_mem_unlock(c
);
2050 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2052 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2056 if (!c
|| !c
->lxc_conf
)
2058 if (container_mem_lock(c
))
2060 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2061 container_mem_unlock(c
);
2065 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2067 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2070 return lxc_listconfigs(retv
, inlen
);
2072 * Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2073 * This is an intelligent result to show which keys are valid given
2074 * the type of nic it is
2076 if (!c
|| !c
->lxc_conf
)
2078 if (container_mem_lock(c
))
2081 if (strncmp(key
, "lxc.net.", 8) == 0)
2082 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
2083 else if (strncmp(key
, "lxc.network.", 12) == 0)
2084 ret
= lxc_list_nicconfigs_legacy(c
->lxc_conf
, key
, retv
, inlen
);
2085 container_mem_unlock(c
);
2089 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2091 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2094 bool ret
= false, need_disklock
= false;
2098 alt_file
= c
->configfile
;
2100 return false; // should we write to stdout if no file is specified?
2102 // If we haven't yet loaded a config, load the stock config
2104 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2105 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
2110 if (!create_container_dir(c
))
2114 * If we're writing to the container's config file, take the
2115 * disk lock. Otherwise just take the memlock to protect the
2116 * struct lxc_container while we're traversing it.
2118 if (strcmp(c
->configfile
, alt_file
) == 0)
2119 need_disklock
= true;
2122 lret
= container_disk_lock(c
);
2124 lret
= container_mem_lock(c
);
2129 fout
= fopen(alt_file
, "w");
2132 write_config(fout
, c
->lxc_conf
);
2138 container_disk_unlock(c
);
2140 container_mem_unlock(c
);
2144 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2147 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2153 char path
[MAXPATHLEN
];
2154 char newpath
[MAXPATHLEN
];
2155 int fd
, ret
, n
= 0, v
= 0;
2157 size_t len
= 0, bytes
= 0;
2159 if (container_disk_lock(c0
))
2162 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2163 if (ret
< 0 || ret
> MAXPATHLEN
)
2165 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2166 if (ret
< 0 || ret
> MAXPATHLEN
)
2169 /* If we find an lxc-snapshot file using the old format only listing the
2170 * number of snapshots we will keep using it. */
2171 f1
= fopen(path
, "r");
2173 n
= fscanf(f1
, "%d", &v
);
2175 if (n
== 1 && v
== 0) {
2182 f1
= fopen(path
, "w");
2185 if (fprintf(f1
, "%d\n", v
) < 0) {
2186 ERROR("Error writing new snapshots value");
2192 SYSERROR("Error writing to or closing snapshots file");
2196 /* Here we know that we have or can use an lxc-snapshot file
2197 * using the new format. */
2199 f1
= fopen(path
, "a");
2203 if (fprintf(f1
, "%s", newpath
) < 0) {
2204 ERROR("Error writing new snapshots entry");
2207 SYSERROR("Error writing to or closing snapshots file");
2213 SYSERROR("Error writing to or closing snapshots file");
2217 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2220 if (fstat(fd
, &fbuf
) < 0) {
2225 if (fbuf
.st_size
!= 0) {
2227 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2228 if (buf
== MAP_FAILED
) {
2229 SYSERROR("Failed to create mapping %s", path
);
2234 len
= strlen(newpath
);
2235 while ((del
= strstr((char *)buf
, newpath
))) {
2236 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2240 lxc_strmunmap(buf
, fbuf
.st_size
);
2241 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2242 SYSERROR("Failed to truncate file %s", path
);
2250 /* If the lxc-snapshot file is empty, remove it. */
2251 if (stat(path
, &fbuf
) < 0)
2253 if (!fbuf
.st_size
) {
2261 container_disk_unlock(c0
);
2265 static void strip_newline(char *p
)
2267 size_t len
= strlen(p
);
2270 if (p
[len
-1] == '\n')
2274 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2276 struct lxc_container
*p
;
2277 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2278 size_t pathlen
= 0, namelen
= 0;
2282 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2283 c
->config_path
, c
->name
);
2284 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2285 ERROR("Path name too long");
2288 f
= fopen(path
, "r");
2291 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2292 if (getline(&lxcname
, &namelen
, f
) == -1) {
2293 ERROR("badly formatted file %s", path
);
2296 strip_newline(lxcpath
);
2297 strip_newline(lxcname
);
2298 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2299 ERROR("Unable to find dependent container %s:%s",
2303 if (!mod_rdep(p
, c
, inc
))
2304 ERROR("Failed to update snapshots file for %s:%s",
2306 lxc_container_put(p
);
2314 static bool has_fs_snapshots(struct lxc_container
*c
)
2317 char path
[MAXPATHLEN
];
2322 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2324 if (ret
< 0 || ret
> MAXPATHLEN
)
2326 /* If the file doesn't exist there are no snapshots. */
2327 if (stat(path
, &fbuf
) < 0)
2331 f
= fopen(path
, "r");
2334 ret
= fscanf(f
, "%d", &v
);
2336 // TODO: Figure out what to do with the return value of fscanf.
2338 INFO("Container uses new lxc-snapshots format %s", path
);
2346 static bool has_snapshots(struct lxc_container
*c
)
2348 char path
[MAXPATHLEN
];
2349 struct dirent
*direntp
;
2353 if (!get_snappath_dir(c
, path
))
2355 dir
= opendir(path
);
2358 while ((direntp
= readdir(dir
))) {
2362 if (!strcmp(direntp
->d_name
, "."))
2365 if (!strcmp(direntp
->d_name
, ".."))
2374 static bool do_destroy_container(struct lxc_conf
*conf
) {
2376 if (userns_exec_1(conf
, bdev_destroy_wrapper
, conf
,
2377 "bdev_destroy_wrapper") < 0)
2381 return bdev_destroy(conf
);
2384 static int lxc_rmdir_onedev_wrapper(void *data
)
2386 char *arg
= (char *) data
;
2387 return lxc_rmdir_onedev(arg
, "snaps");
2390 static bool container_destroy(struct lxc_container
*c
)
2394 struct lxc_conf
*conf
;
2396 if (!c
|| !do_lxcapi_is_defined(c
))
2400 if (container_disk_lock(c
))
2403 if (!is_stopped(c
)) {
2404 // we should queue some sort of error - in c->error_string?
2405 ERROR("container %s is not stopped", c
->name
);
2409 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2410 /* Start of environment variable setup for hooks */
2411 if (c
->name
&& setenv("LXC_NAME", c
->name
, 1)) {
2412 SYSERROR("failed to set environment variable for container name");
2414 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2415 SYSERROR("failed to set environment variable for config path");
2417 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
2418 SYSERROR("failed to set environment variable for rootfs mount");
2420 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2421 SYSERROR("failed to set environment variable for rootfs mount");
2423 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1)) {
2424 SYSERROR("failed to set environment variable for console path");
2426 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1)) {
2427 SYSERROR("failed to set environment variable for console log");
2429 /* End of environment variable setup for hooks */
2431 if (run_lxc_hooks(c
->name
, "destroy", conf
, c
->get_config_path(c
), NULL
)) {
2432 ERROR("Error executing clone hook for %s", c
->name
);
2437 if (current_config
&& conf
== current_config
) {
2438 current_config
= NULL
;
2439 if (conf
->logfd
!= -1) {
2445 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2446 if (!do_destroy_container(conf
)) {
2447 ERROR("Error destroying rootfs for %s", c
->name
);
2450 INFO("Destroyed rootfs for %s", c
->name
);
2453 mod_all_rdeps(c
, false);
2455 const char *p1
= do_lxcapi_get_config_path(c
);
2456 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
2457 sprintf(path
, "%s/%s", p1
, c
->name
);
2459 ret
= userns_exec_1(conf
, lxc_rmdir_onedev_wrapper
, path
,
2460 "lxc_rmdir_onedev_wrapper");
2462 ret
= lxc_rmdir_onedev(path
, "snaps");
2464 ERROR("Error destroying container directory for %s", c
->name
);
2467 INFO("Destroyed directory for %s", c
->name
);
2472 container_disk_unlock(c
);
2476 static bool do_lxcapi_destroy(struct lxc_container
*c
)
2478 if (!c
|| !lxcapi_is_defined(c
))
2480 if (has_snapshots(c
)) {
2481 ERROR("Container %s has snapshots; not removing", c
->name
);
2485 if (has_fs_snapshots(c
)) {
2486 ERROR("container %s has snapshots on its rootfs", c
->name
);
2490 return container_destroy(c
);
2493 WRAP_API(bool, lxcapi_destroy
)
2495 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2497 if (!c
|| !lxcapi_is_defined(c
))
2499 if (!lxcapi_snapshot_destroy_all(c
)) {
2500 ERROR("Error deleting all snapshots");
2503 return lxcapi_destroy(c
);
2506 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
2508 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
2510 struct lxc_config_t
*config
;
2513 c
->lxc_conf
= lxc_conf_init();
2516 config
= lxc_getconfig(key
);
2519 if (config
->set(key
, v
, c
->lxc_conf
, NULL
) != 0)
2521 return do_append_unexp_config_line(c
->lxc_conf
, key
, v
);
2524 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2531 if (container_mem_lock(c
))
2534 b
= set_config_item_locked(c
, key
, v
);
2536 container_mem_unlock(c
);
2540 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
2542 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2544 if (!c
|| !c
->configfile
)
2546 return strdup(c
->configfile
);
2549 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2551 if (!c
|| !c
->config_path
)
2553 return (const char *)(c
->config_path
);
2558 * Just recalculate the c->configfile based on the
2559 * c->config_path, which must be set.
2560 * The lxc_container must be locked or not yet public.
2562 static bool set_config_filename(struct lxc_container
*c
)
2567 if (!c
->config_path
)
2570 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2571 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2572 newpath
= malloc(len
);
2576 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2577 if (ret
< 0 || ret
>= len
) {
2578 fprintf(stderr
, "Error printing out config file name\n");
2583 free(c
->configfile
);
2584 c
->configfile
= newpath
;
2589 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2593 char *oldpath
= NULL
;
2598 if (container_mem_lock(c
))
2603 ERROR("Out of memory setting new lxc path");
2609 oldpath
= c
->config_path
;
2612 /* Since we've changed the config path, we have to change the
2613 * config file name too */
2614 if (!set_config_filename(c
)) {
2615 ERROR("Out of memory setting new config filename");
2617 free(c
->config_path
);
2618 c
->config_path
= oldpath
;
2623 container_mem_unlock(c
);
2627 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
2629 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2639 if (container_disk_lock(c
))
2642 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2644 container_disk_unlock(c
);
2648 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
2650 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2660 if (container_disk_lock(c
))
2663 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2665 container_disk_unlock(c
);
2669 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
2671 const char *lxc_get_global_config_item(const char *key
)
2673 return lxc_global_config_value(key
);
2676 const char *lxc_get_version(void)
2681 static int copy_file(const char *old
, const char *new)
2688 if (file_exists(new)) {
2689 ERROR("copy destination %s exists", new);
2692 ret
= stat(old
, &sbuf
);
2694 INFO("Error stat'ing %s", old
);
2698 in
= open(old
, O_RDONLY
);
2700 SYSERROR("Error opening original file %s", old
);
2703 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2705 SYSERROR("Error opening new file %s", new);
2711 len
= read(in
, buf
, 8096);
2713 SYSERROR("Error reading old file %s", old
);
2718 ret
= write(out
, buf
, len
);
2719 if (ret
< len
) { // should we retry?
2720 SYSERROR("Error: write to new file %s was interrupted", new);
2727 // we set mode, but not owner/group
2728 ret
= chmod(new, sbuf
.st_mode
);
2730 SYSERROR("Error setting mode on %s", new);
2742 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2745 struct lxc_list
*it
;
2748 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2749 cpath
= alloca(len
);
2750 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2751 if (ret
< 0 || ret
>= len
)
2754 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2755 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2756 char *hookname
= it
->elem
;
2757 char *fname
= strrchr(hookname
, '/');
2758 char tmppath
[MAXPATHLEN
];
2759 if (!fname
) // relative path - we don't support, but maybe we should
2761 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2762 // this hook is public - ignore
2765 // copy the script, and change the entry in confile
2766 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2767 c
->config_path
, c
->name
, fname
+1);
2768 if (ret
< 0 || ret
>= MAXPATHLEN
)
2770 ret
= copy_file(it
->elem
, tmppath
);
2774 it
->elem
= strdup(tmppath
);
2776 ERROR("out of memory copying hook path");
2782 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
2783 c
->config_path
, oldc
->name
, c
->name
)) {
2784 ERROR("Error saving new hooks in clone");
2787 do_lxcapi_save_config(c
, NULL
);
2792 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2794 char newpath
[MAXPATHLEN
];
2795 char *oldpath
= oldc
->lxc_conf
->fstab
;
2801 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount", false);
2803 char *p
= strrchr(oldpath
, '/');
2806 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2807 c
->config_path
, c
->name
, p
);
2808 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2809 ERROR("error printing new path for %s", oldpath
);
2812 if (file_exists(newpath
)) {
2813 ERROR("error: fstab file %s exists", newpath
);
2817 if (copy_file(oldpath
, newpath
) < 0) {
2818 ERROR("error: copying %s to %s", oldpath
, newpath
);
2821 free(c
->lxc_conf
->fstab
);
2822 c
->lxc_conf
->fstab
= strdup(newpath
);
2823 if (!c
->lxc_conf
->fstab
) {
2824 ERROR("error: allocating pathname");
2827 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount", newpath
)) {
2828 ERROR("error saving new lxctab");
2835 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2837 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2840 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2842 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2843 WARN("Error copying reverse dependencies");
2846 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2848 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2849 WARN("Error copying reverse dependencies");
2852 if (copy_file(path0
, path1
) < 0) {
2853 INFO("Error copying reverse dependencies");
2858 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2861 char path
[MAXPATHLEN
];
2865 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2867 if (ret
< 0 || ret
>= MAXPATHLEN
)
2869 f
= fopen(path
, "a");
2873 // if anything goes wrong, just return an error
2874 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2882 * If the fs natively supports snapshot clones with no penalty,
2883 * then default to those even if not requested.
2884 * Currently we only do this for btrfs.
2886 bool should_default_to_snapshot(struct lxc_container
*c0
,
2887 struct lxc_container
*c1
)
2889 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
2890 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
2891 char *p0
= alloca(l0
+ 1);
2892 char *p1
= alloca(l1
+ 1);
2893 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
2895 snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
2896 snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
2898 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
2901 if (is_btrfs_subvol(rootfs
) <= 0)
2904 return btrfs_same_fs(p0
, p1
) == 0;
2907 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2908 const char *newtype
, int flags
, const char *bdevdata
,
2914 if (should_default_to_snapshot(c0
, c
))
2915 flags
|= LXC_CLONE_SNAPSHOT
;
2917 bdev
= bdev_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
, bdevdata
,
2918 newsize
, &need_rdep
);
2920 ERROR("Error copying storage.");
2924 /* Set new rootfs. */
2925 free(c
->lxc_conf
->rootfs
.path
);
2926 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2928 /* Set new bdev type. */
2929 free(c
->lxc_conf
->rootfs
.bdev_type
);
2930 c
->lxc_conf
->rootfs
.bdev_type
= strdup(bdev
->type
);
2933 if (!c
->lxc_conf
->rootfs
.path
) {
2934 ERROR("Out of memory while setting storage path.");
2937 if (!c
->lxc_conf
->rootfs
.bdev_type
) {
2938 ERROR("Out of memory while setting rootfs backend.");
2942 /* Append a new lxc.rootfs entry to the unexpanded config. */
2943 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
2944 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs",
2945 c
->lxc_conf
->rootfs
.path
)) {
2946 ERROR("Error saving new rootfs to cloned config.");
2950 /* Append a new lxc.rootfs.backend entry to the unexpanded config. */
2951 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.backend", false);
2952 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.backend",
2953 c
->lxc_conf
->rootfs
.bdev_type
)) {
2954 ERROR("Error saving new rootfs backend to cloned config.");
2958 if (flags
& LXC_CLONE_SNAPSHOT
)
2959 copy_rdepends(c
, c0
);
2961 if (!add_rdepends(c
, c0
))
2962 WARN("Error adding reverse dependency from %s to %s",
2966 mod_all_rdeps(c
, true);
2971 struct clone_update_data
{
2972 struct lxc_container
*c0
;
2973 struct lxc_container
*c1
;
2978 static int clone_update_rootfs(struct clone_update_data
*data
)
2980 struct lxc_container
*c0
= data
->c0
;
2981 struct lxc_container
*c
= data
->c1
;
2982 int flags
= data
->flags
;
2983 char **hookargs
= data
->hookargs
;
2985 char path
[MAXPATHLEN
];
2988 struct lxc_conf
*conf
= c
->lxc_conf
;
2990 /* update hostname in rootfs */
2991 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2993 if (setgid(0) < 0) {
2994 ERROR("Failed to setgid to 0");
2997 if (setuid(0) < 0) {
2998 ERROR("Failed to setuid to 0");
3001 if (setgroups(0, NULL
) < 0)
3002 WARN("Failed to clear groups");
3004 if (unshare(CLONE_NEWNS
) < 0)
3006 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3009 if (strcmp(bdev
->type
, "dir") != 0) {
3010 if (unshare(CLONE_NEWNS
) < 0) {
3011 ERROR("error unsharing mounts");
3015 if (detect_shared_rootfs()) {
3016 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3017 SYSERROR("Failed to make / rslave");
3018 ERROR("Continuing...");
3021 if (bdev
->ops
->mount(bdev
) < 0) {
3025 } else { // TODO come up with a better way
3027 bdev
->dest
= strdup(bdev
->src
);
3030 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3031 /* Start of environment variable setup for hooks */
3032 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1)) {
3033 SYSERROR("failed to set environment variable for source container name");
3035 if (c
->name
&& setenv("LXC_NAME", c
->name
, 1)) {
3036 SYSERROR("failed to set environment variable for container name");
3038 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
3039 SYSERROR("failed to set environment variable for config path");
3041 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
3042 SYSERROR("failed to set environment variable for rootfs mount");
3044 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
3045 SYSERROR("failed to set environment variable for rootfs mount");
3048 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
3049 ERROR("Error executing clone hook for %s", c
->name
);
3055 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3056 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3059 if (ret
< 0 || ret
>= MAXPATHLEN
)
3061 if (!file_exists(path
))
3063 if (!(fout
= fopen(path
, "w"))) {
3064 SYSERROR("unable to open %s: ignoring", path
);
3067 if (fprintf(fout
, "%s", c
->name
) < 0) {
3071 if (fclose(fout
) < 0)
3080 static int clone_update_rootfs_wrapper(void *data
)
3082 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3083 return clone_update_rootfs(arg
);
3087 * We want to support:
3088 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3089 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3091 -s [ implies overlayfs]
3095 only rootfs gets converted (copied/snapshotted) on clone.
3098 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3100 char *p
= strrchr(path
, '/');
3106 ret
= do_create_container_dir(path
, conf
);
3111 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3112 const char *lxcpath
, int flags
,
3113 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3116 struct lxc_container
*c2
= NULL
;
3117 char newpath
[MAXPATHLEN
];
3118 int ret
, storage_copied
= 0;
3119 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3120 struct clone_update_data data
;
3121 size_t saved_unexp_len
;
3125 if (!c
|| !do_lxcapi_is_defined(c
))
3128 if (container_mem_lock(c
))
3131 if (!is_stopped(c
)) {
3132 ERROR("error: Original container (%s) is running", c
->name
);
3136 // Make sure the container doesn't yet exist.
3140 lxcpath
= do_lxcapi_get_config_path(c
);
3141 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3142 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3143 SYSERROR("clone: failed making config pathname");
3146 if (file_exists(newpath
)) {
3147 ERROR("error: clone: %s exists", newpath
);
3151 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3152 if (ret
< 0 && errno
!= EEXIST
) {
3153 ERROR("Error creating container dir for %s", newpath
);
3157 // copy the configuration, tweak it as needed,
3158 if (c
->lxc_conf
->rootfs
.path
) {
3159 origroot
= c
->lxc_conf
->rootfs
.path
;
3160 c
->lxc_conf
->rootfs
.path
= NULL
;
3162 fout
= fopen(newpath
, "w");
3164 SYSERROR("open %s", newpath
);
3168 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3169 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3170 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3171 if (!c
->lxc_conf
->unexpanded_config
) {
3172 ERROR("Out of memory");
3176 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs", false);
3177 write_config(fout
, c
->lxc_conf
);
3179 c
->lxc_conf
->rootfs
.path
= origroot
;
3180 free(c
->lxc_conf
->unexpanded_config
);
3181 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3182 saved_unexp_conf
= NULL
;
3183 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3185 sprintf(newpath
, "%s/%s/rootfs", lxcpath
, newname
);
3186 if (mkdir(newpath
, 0755) < 0) {
3187 SYSERROR("error creating %s", newpath
);
3192 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3193 ERROR("Error chowning %s to container root", newpath
);
3198 c2
= lxc_container_new(newname
, lxcpath
);
3200 ERROR("clone: failed to create new container (%s %s)", newname
,
3205 // copy/snapshot rootfs's
3206 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3212 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3213 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3215 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
3216 ERROR("Error setting new hostname");
3222 ret
= copyhooks(c
, c2
);
3224 ERROR("error copying hooks");
3228 if (copy_fstab(c
, c2
) < 0) {
3229 ERROR("error copying fstab");
3234 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3235 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3236 ERROR("Error updating mac addresses");
3241 // update absolute paths for overlay mount directories
3242 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3245 // We've now successfully created c2's storage, so clear it out if we
3249 if (!c2
->save_config(c2
, NULL
))
3252 if ((pid
= fork()) < 0) {
3257 ret
= wait_for_pid(pid
);
3260 container_mem_unlock(c
);
3266 data
.hookargs
= hookargs
;
3268 ret
= userns_exec_1(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3269 &data
, "clone_update_rootfs_wrapper");
3271 ret
= clone_update_rootfs(&data
);
3275 container_mem_unlock(c
);
3279 container_mem_unlock(c
);
3281 if (!storage_copied
)
3282 c2
->lxc_conf
->rootfs
.path
= NULL
;
3284 lxc_container_put(c2
);
3290 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3291 const char *lxcpath
, int flags
,
3292 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3295 struct lxc_container
* ret
;
3296 current_config
= c
? c
->lxc_conf
: NULL
;
3297 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3298 current_config
= NULL
;
3302 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3305 struct lxc_container
*newc
;
3307 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3310 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3311 ERROR("Renaming a container with snapshots is not supported");
3314 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3316 ERROR("Failed to find original backing store type");
3320 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3323 lxc_container_put(newc
);
3327 if (newc
&& lxcapi_is_defined(newc
))
3328 lxc_container_put(newc
);
3330 if (!container_destroy(c
)) {
3331 ERROR("Could not destroy existing container %s", c
->name
);
3337 WRAP_API_1(bool, lxcapi_rename
, const char *)
3339 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
)
3346 current_config
= c
->lxc_conf
;
3348 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
3349 current_config
= NULL
;
3353 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3355 lxc_attach_command_t command
;
3362 command
.program
= (char*)program
;
3363 command
.argv
= (char**)argv
;
3364 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
3369 return lxc_wait_for_pid_status(pid
);
3372 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3375 current_config
= c
? c
->lxc_conf
: NULL
;
3376 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
3377 current_config
= NULL
;
3381 static int get_next_index(const char *lxcpath
, char *cname
)
3387 fname
= alloca(strlen(lxcpath
) + 20);
3389 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
3390 ret
= stat(fname
, &sb
);
3397 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
3401 * If the old style snapshot path exists, use it
3402 * /var/lib/lxc -> /var/lib/lxcsnaps
3404 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
3405 if (ret
< 0 || ret
>= MAXPATHLEN
)
3407 if (dir_exists(snappath
)) {
3408 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3409 if (ret
< 0 || ret
>= MAXPATHLEN
)
3415 * Use the new style path
3416 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3418 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
3419 if (ret
< 0 || ret
>= MAXPATHLEN
)
3424 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
3427 struct lxc_container
*c2
;
3428 char snappath
[MAXPATHLEN
], newname
[20];
3430 if (!c
|| !lxcapi_is_defined(c
))
3433 if (!bdev_can_backup(c
->lxc_conf
)) {
3434 ERROR("%s's backing store cannot be backed up.", c
->name
);
3435 ERROR("Your container must use another backing store type.");
3439 if (!get_snappath_dir(c
, snappath
))
3442 i
= get_next_index(snappath
, c
->name
);
3444 if (mkdir_p(snappath
, 0755) < 0) {
3445 ERROR("Failed to create snapshot directory %s", snappath
);
3449 ret
= snprintf(newname
, 20, "snap%d", i
);
3450 if (ret
< 0 || ret
>= 20)
3454 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3455 * created in the original container
3457 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
3458 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
3459 if (bdev_is_dir(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
)) {
3460 ERROR("Snapshot of directory-backed container requested.");
3461 ERROR("Making a copy-clone. If you do want snapshots, then");
3462 ERROR("please create an aufs or overlayfs clone first, snapshot that");
3463 ERROR("and keep the original container pristine.");
3464 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3466 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
3468 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
3472 lxc_container_put(c2
);
3474 // Now write down the creation time
3481 tm_info
= localtime(&timer
);
3483 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
3485 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
3486 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
3487 f
= fopen(dfnam
, "w");
3489 ERROR("Failed to open %s", dfnam
);
3492 if (fprintf(f
, "%s", buffer
) < 0) {
3493 SYSERROR("Writing timestamp");
3499 SYSERROR("Writing timestamp");
3504 // $p / $name / comment \0
3505 int len
= strlen(snappath
) + strlen(newname
) + 10;
3506 char *path
= alloca(len
);
3507 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3508 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3514 WRAP_API_1(int, lxcapi_snapshot
, const char *)
3516 static void lxcsnap_free(struct lxc_snapshot
*s
)
3519 free(s
->comment_pathname
);
3524 static char *get_snapcomment_path(char* snappath
, char *name
)
3526 // $snappath/$name/comment
3527 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3528 char *s
= malloc(len
);
3531 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3532 if (ret
< 0 || ret
>= len
) {
3540 static char *get_timestamp(char* snappath
, char *name
)
3542 char path
[MAXPATHLEN
], *s
= NULL
;
3546 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3547 if (ret
< 0 || ret
>= MAXPATHLEN
)
3549 fin
= fopen(path
, "r");
3552 (void) fseek(fin
, 0, SEEK_END
);
3554 (void) fseek(fin
, 0, SEEK_SET
);
3559 if (fread(s
, 1, len
, fin
) != len
) {
3560 SYSERROR("reading timestamp");
3570 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3572 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3574 struct dirent
*direntp
;
3575 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3578 if (!c
|| !lxcapi_is_defined(c
))
3581 if (!get_snappath_dir(c
, snappath
)) {
3582 ERROR("path name too long");
3585 dir
= opendir(snappath
);
3587 INFO("failed to open %s - assuming no snapshots", snappath
);
3591 while ((direntp
= readdir(dir
))) {
3595 if (!strcmp(direntp
->d_name
, "."))
3598 if (!strcmp(direntp
->d_name
, ".."))
3601 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
3602 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3603 ERROR("pathname too long");
3606 if (!file_exists(path2
))
3608 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
3610 SYSERROR("Out of memory");
3614 snaps
[count
].free
= lxcsnap_free
;
3615 snaps
[count
].name
= strdup(direntp
->d_name
);
3616 if (!snaps
[count
].name
)
3618 snaps
[count
].lxcpath
= strdup(snappath
);
3619 if (!snaps
[count
].lxcpath
) {
3620 free(snaps
[count
].name
);
3623 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
3624 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
3629 WARN("failed to close directory");
3637 for (i
=0; i
<count
; i
++)
3638 lxcsnap_free(&snaps
[i
]);
3642 WARN("failed to close directory");
3646 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
3648 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
3650 char clonelxcpath
[MAXPATHLEN
];
3652 struct lxc_container
*snap
, *rest
;
3656 if (!c
|| !c
->name
|| !c
->config_path
)
3659 if (has_fs_snapshots(c
)) {
3660 ERROR("container rootfs has dependent snapshots");
3664 bdev
= bdev_init(c
->lxc_conf
, c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
3666 ERROR("Failed to find original backing store type");
3673 if (!get_snappath_dir(c
, clonelxcpath
)) {
3677 // how should we lock this?
3679 snap
= lxc_container_new(snapname
, clonelxcpath
);
3680 if (!snap
|| !lxcapi_is_defined(snap
)) {
3681 ERROR("Could not open snapshot %s", snapname
);
3682 if (snap
) lxc_container_put(snap
);
3687 if (strcmp(c
->name
, newname
) == 0) {
3688 if (!container_destroy(c
)) {
3689 ERROR("Could not destroy existing container %s", newname
);
3690 lxc_container_put(snap
);
3696 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
3697 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3698 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
,
3699 bdev
->type
, NULL
, 0, NULL
);
3701 if (rest
&& lxcapi_is_defined(rest
))
3704 lxc_container_put(rest
);
3705 lxc_container_put(snap
);
3709 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
3711 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
3713 struct lxc_container
*snap
= NULL
;
3716 snap
= lxc_container_new(snapname
, clonelxcpath
);
3718 ERROR("Could not find snapshot %s", snapname
);
3722 if (!do_lxcapi_destroy(snap
)) {
3723 ERROR("Could not destroy snapshot %s", snapname
);
3730 lxc_container_put(snap
);
3734 static bool remove_all_snapshots(const char *path
)
3737 struct dirent
*direntp
;
3740 dir
= opendir(path
);
3742 SYSERROR("opendir on snapshot path %s", path
);
3745 while ((direntp
= readdir(dir
))) {
3748 if (!strcmp(direntp
->d_name
, "."))
3750 if (!strcmp(direntp
->d_name
, ".."))
3752 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
3761 SYSERROR("Error removing directory %s", path
);
3766 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
3768 char clonelxcpath
[MAXPATHLEN
];
3770 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
3773 if (!get_snappath_dir(c
, clonelxcpath
))
3776 return do_snapshot_destroy(snapname
, clonelxcpath
);
3779 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
3781 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
3783 char clonelxcpath
[MAXPATHLEN
];
3785 if (!c
|| !c
->name
|| !c
->config_path
)
3788 if (!get_snappath_dir(c
, clonelxcpath
))
3791 return remove_all_snapshots(clonelxcpath
);
3794 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
3796 static bool do_lxcapi_may_control(struct lxc_container
*c
)
3798 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3801 WRAP_API(bool, lxcapi_may_control
)
3803 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
3806 char chrootpath
[MAXPATHLEN
];
3807 char *directory_path
= NULL
;
3811 if ((pid
= fork()) < 0) {
3812 SYSERROR("failed to fork a child helper");
3816 if (wait_for_pid(pid
) != 0) {
3817 ERROR("Failed to create note in guest");
3823 /* prepare the path */
3824 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
3825 if (ret
< 0 || ret
>= MAXPATHLEN
)
3828 if (chroot(chrootpath
) < 0)
3832 /* remove path if it exists */
3833 if(faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0) {
3834 if (unlink(path
) < 0) {
3835 ERROR("unlink failed");
3842 /* create any missing directories */
3843 directory_path
= dirname(strdup(path
));
3844 if (mkdir_p(directory_path
, 0755) < 0 && errno
!= EEXIST
) {
3845 ERROR("failed to create directory");
3849 /* create the device node */
3850 if (mknod(path
, st
->st_mode
, st
->st_rdev
) < 0) {
3851 ERROR("mknod failed");
3858 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3862 char value
[MAX_BUFFER
];
3865 /* make sure container is running */
3866 if (!do_lxcapi_is_running(c
)) {
3867 ERROR("container is not running");
3871 /* use src_path if dest_path is NULL otherwise use dest_path */
3872 p
= dest_path
? dest_path
: src_path
;
3874 /* make sure we can access p */
3875 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3878 /* continue if path is character device or block device */
3879 if (S_ISCHR(st
.st_mode
))
3880 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3881 else if (S_ISBLK(st
.st_mode
))
3882 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3886 /* check snprintf return code */
3887 if (ret
< 0 || ret
>= MAX_BUFFER
)
3890 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
3893 /* add or remove device to/from cgroup access list */
3895 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
3896 ERROR("set_cgroup_item failed while adding the device node");
3900 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
3901 ERROR("set_cgroup_item failed while removing the device node");
3909 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3912 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3915 return add_remove_device_node(c
, src_path
, dest_path
, true);
3918 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
3920 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3923 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3926 return add_remove_device_node(c
, src_path
, dest_path
, false);
3929 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
3931 static bool do_lxcapi_attach_interface(struct lxc_container
*c
, const char *ifname
,
3932 const char *dst_ifname
)
3936 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3941 ERROR("No source interface name given");
3945 ret
= lxc_netdev_isup(ifname
);
3948 /* netdev of ifname is up. */
3949 ret
= lxc_netdev_down(ifname
);
3954 ret
= lxc_netdev_move_by_name(ifname
, do_lxcapi_init_pid(c
), dst_ifname
);
3964 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
3966 static bool do_lxcapi_detach_interface(struct lxc_container
*c
, const char *ifname
,
3967 const char *dst_ifname
)
3969 pid_t pid
, pid_outside
;
3972 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3977 ERROR("No source interface name given");
3981 pid_outside
= getpid();
3984 ERROR("failed to fork task to get interfaces information");
3988 if (pid
== 0) { // child
3990 if (!enter_net_ns(c
)) {
3991 ERROR("failed to enter namespace");
3995 ret
= lxc_netdev_isup(ifname
);
3999 /* netdev of ifname is up. */
4001 ret
= lxc_netdev_down(ifname
);
4006 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4008 /* -EINVAL means there is no netdev named as ifanme. */
4009 if (ret
== -EINVAL
) {
4010 ERROR("No network device named as %s.", ifname
);
4015 if (wait_for_pid(pid
) != 0)
4021 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4023 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4024 struct migrate_opts
*opts
, unsigned int size
)
4027 struct migrate_opts
*valid_opts
= opts
;
4029 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4030 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4031 * to do anything special.
4033 if (size
> sizeof(*opts
)) {
4034 unsigned char *addr
;
4037 addr
= (void *)opts
+ sizeof(*opts
);
4038 end
= (void *)opts
+ size
;
4039 for (; addr
< end
; addr
++) {
4046 /* If the caller has a smaller struct, let's zero out the end for them
4047 * so we don't accidentally use bits of it that they didn't know about
4050 if (size
< sizeof(*opts
)) {
4051 valid_opts
= malloc(sizeof(*opts
));
4055 memset(valid_opts
, 0, sizeof(*opts
));
4056 memcpy(valid_opts
, opts
, size
);
4060 case MIGRATE_PRE_DUMP
:
4061 if (!do_lxcapi_is_running(c
)) {
4062 ERROR("container is not running");
4065 ret
= !__criu_pre_dump(c
, valid_opts
);
4068 if (!do_lxcapi_is_running(c
)) {
4069 ERROR("container is not running");
4072 ret
= !__criu_dump(c
, valid_opts
);
4074 case MIGRATE_RESTORE
:
4075 if (do_lxcapi_is_running(c
)) {
4076 ERROR("container is already running");
4079 ret
= !__criu_restore(c
, valid_opts
);
4082 ERROR("invalid migrate command %u", cmd
);
4086 if (size
< sizeof(*opts
))
4092 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4094 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4096 struct migrate_opts opts
;
4098 memset(&opts
, 0, sizeof(opts
));
4100 opts
.directory
= directory
;
4102 opts
.verbose
= verbose
;
4104 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4107 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4109 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4111 struct migrate_opts opts
;
4113 memset(&opts
, 0, sizeof(opts
));
4115 opts
.directory
= directory
;
4116 opts
.verbose
= verbose
;
4118 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4121 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4123 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4132 current_config
= c
->lxc_conf
;
4135 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4139 ERROR("Memory allocation error.");
4145 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4148 current_config
= NULL
;
4152 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4154 struct lxc_container
*c
;
4159 c
= malloc(sizeof(*c
));
4161 fprintf(stderr
, "failed to malloc lxc_container\n");
4164 memset(c
, 0, sizeof(*c
));
4167 c
->config_path
= strdup(configpath
);
4169 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4171 if (!c
->config_path
) {
4172 fprintf(stderr
, "Out of memory\n");
4176 remove_trailing_slashes(c
->config_path
);
4177 c
->name
= malloc(strlen(name
)+1);
4179 fprintf(stderr
, "Error allocating lxc_container name\n");
4182 strcpy(c
->name
, name
);
4185 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
4186 fprintf(stderr
, "failed to create lock\n");
4190 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
4191 fprintf(stderr
, "failed to alloc privlock\n");
4195 if (!set_config_filename(c
)) {
4196 fprintf(stderr
, "Error allocating config file pathname\n");
4200 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
))
4203 if (ongoing_create(c
) == 2) {
4204 ERROR("Error: %s creation was not completed", c
->name
);
4205 container_destroy(c
);
4206 lxcapi_clear_config(c
);
4208 c
->daemonize
= true;
4211 // assign the member functions
4212 c
->is_defined
= lxcapi_is_defined
;
4213 c
->state
= lxcapi_state
;
4214 c
->is_running
= lxcapi_is_running
;
4215 c
->freeze
= lxcapi_freeze
;
4216 c
->unfreeze
= lxcapi_unfreeze
;
4217 c
->console
= lxcapi_console
;
4218 c
->console_getfd
= lxcapi_console_getfd
;
4219 c
->init_pid
= lxcapi_init_pid
;
4220 c
->load_config
= lxcapi_load_config
;
4221 c
->want_daemonize
= lxcapi_want_daemonize
;
4222 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4223 c
->start
= lxcapi_start
;
4224 c
->startl
= lxcapi_startl
;
4225 c
->stop
= lxcapi_stop
;
4226 c
->config_file_name
= lxcapi_config_file_name
;
4227 c
->wait
= lxcapi_wait
;
4228 c
->set_config_item
= lxcapi_set_config_item
;
4229 c
->destroy
= lxcapi_destroy
;
4230 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4231 c
->rename
= lxcapi_rename
;
4232 c
->save_config
= lxcapi_save_config
;
4233 c
->get_keys
= lxcapi_get_keys
;
4234 c
->create
= lxcapi_create
;
4235 c
->createl
= lxcapi_createl
;
4236 c
->shutdown
= lxcapi_shutdown
;
4237 c
->reboot
= lxcapi_reboot
;
4238 c
->clear_config
= lxcapi_clear_config
;
4239 c
->clear_config_item
= lxcapi_clear_config_item
;
4240 c
->get_config_item
= lxcapi_get_config_item
;
4241 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4242 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4243 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4244 c
->get_config_path
= lxcapi_get_config_path
;
4245 c
->set_config_path
= lxcapi_set_config_path
;
4246 c
->clone
= lxcapi_clone
;
4247 c
->get_interfaces
= lxcapi_get_interfaces
;
4248 c
->get_ips
= lxcapi_get_ips
;
4249 c
->attach
= lxcapi_attach
;
4250 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4251 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4252 c
->snapshot
= lxcapi_snapshot
;
4253 c
->snapshot_list
= lxcapi_snapshot_list
;
4254 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4255 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4256 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4257 c
->may_control
= lxcapi_may_control
;
4258 c
->add_device_node
= lxcapi_add_device_node
;
4259 c
->remove_device_node
= lxcapi_remove_device_node
;
4260 c
->attach_interface
= lxcapi_attach_interface
;
4261 c
->detach_interface
= lxcapi_detach_interface
;
4262 c
->checkpoint
= lxcapi_checkpoint
;
4263 c
->restore
= lxcapi_restore
;
4264 c
->migrate
= lxcapi_migrate
;
4269 lxc_container_free(c
);
4273 int lxc_get_wait_states(const char **states
)
4278 for (i
=0; i
<MAX_STATE
; i
++)
4279 states
[i
] = lxc_state2str(i
);
4284 * These next two could probably be done smarter with reusing a common function
4285 * with different iterators and tests...
4287 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4290 int i
, cfound
= 0, nfound
= 0;
4291 struct dirent
*direntp
;
4292 struct lxc_container
*c
;
4295 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4297 dir
= opendir(lxcpath
);
4299 SYSERROR("opendir on lxcpath");
4308 while ((direntp
= readdir(dir
))) {
4312 // Ignore '.', '..' and any hidden directory
4313 if (!strncmp(direntp
->d_name
, ".", 1))
4316 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4320 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4330 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4332 INFO("Container %s:%s has a config but could not be loaded",
4333 lxcpath
, direntp
->d_name
);
4335 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4339 if (!do_lxcapi_is_defined(c
)) {
4340 INFO("Container %s:%s has a config but is not defined",
4341 lxcpath
, direntp
->d_name
);
4343 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4345 lxc_container_put(c
);
4349 if (!add_to_clist(cret
, c
, nfound
, true)) {
4350 lxc_container_put(c
);
4360 if (names
&& *names
) {
4361 for (i
=0; i
<cfound
; i
++)
4365 if (cret
&& *cret
) {
4366 for (i
=0; i
<nfound
; i
++)
4367 lxc_container_put((*cret
)[i
]);
4374 int list_active_containers(const char *lxcpath
, char ***nret
,
4375 struct lxc_container
***cret
)
4377 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4380 char **ct_name
= NULL
;
4382 struct lxc_container
*c
= NULL
;
4386 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4387 lxcpath_len
= strlen(lxcpath
);
4394 FILE *f
= fopen("/proc/net/unix", "r");
4398 while (getline(&line
, &len
, f
) != -1) {
4400 char *p
= strrchr(line
, ' '), *p2
;
4409 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4411 } else if (strncmp(p
, "lxc/", 4) == 0) {
4421 // Now p is the start of lxc_name
4422 p2
= strchr(p
, '/');
4423 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4428 char *recvpath
= lxc_cmd_get_lxcpath(p
);
4431 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0)
4433 p
= lxc_cmd_get_name(p
);
4436 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4439 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4440 goto free_cret_list
;
4447 c
= lxc_container_new(p
, lxcpath
);
4449 INFO("Container %s:%s is running but could not be loaded",
4451 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4456 * If this is an anonymous container, then is_defined *can*
4457 * return false. So we don't do that check. Count on the
4458 * fact that the command socket exists.
4461 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
4462 lxc_container_put(c
);
4463 goto free_cret_list
;
4468 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
4470 lxc_container_put(c
);
4471 goto free_cret_list
;
4482 if (cret
&& *cret
) {
4483 for (i
= 0; i
< cret_cnt
; i
++)
4484 lxc_container_put((*cret
)[i
]);
4490 for (i
= 0; i
< ct_name_cnt
; i
++)
4502 int list_all_containers(const char *lxcpath
, char ***nret
,
4503 struct lxc_container
***cret
)
4505 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
4508 struct lxc_container
**ct_list
= NULL
;
4510 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
4514 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
4515 if (active_cnt
< 0) {
4520 for (i
= 0; i
< active_cnt
; i
++) {
4521 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
4522 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
4524 goto free_active_name
;
4528 free(active_name
[i
]);
4529 active_name
[i
] = NULL
;
4535 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
4536 struct lxc_container
*c
;
4538 c
= lxc_container_new(ct_name
[i
], lxcpath
);
4540 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
4541 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
4545 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
4546 lxc_container_put(c
);
4565 for (i
= 0; i
< ct_list_cnt
; i
++) {
4566 lxc_container_put(ct_list
[i
]);
4571 for (i
= 0; i
< active_cnt
; i
++) {
4572 free(active_name
[i
]);
4577 for (i
= 0; i
< ct_cnt
; i
++) {
4584 bool lxc_config_item_is_supported(const char *key
)
4586 return !!lxc_getconfig(key
);