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
22 #include <arpa/inet.h>
36 #include <sys/mount.h>
38 #include <sys/syscall.h>
39 #include <sys/sysmacros.h>
40 #include <sys/types.h>
48 #include "commands_utils.h"
52 #include "confile_utils.h"
55 #include "initutils.h"
58 #include "lxccontainer.h"
61 #include "namespace.h"
67 #include "storage/btrfs.h"
68 #include "storage/overlay.h"
69 #include "storage_utils.h"
77 #include <sys/mkdev.h>
83 #include <../include/ifaddrs.h>
87 #include <../include/lxcmntent.h>
93 #include "include/strlcpy.h"
96 /* Define faccessat() if missing from the C library */
97 #ifndef HAVE_FACCESSAT
98 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
100 #ifdef __NR_faccessat
101 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
109 lxc_log_define(lxccontainer
, lxc
);
111 static bool do_lxcapi_destroy(struct lxc_container
*c
);
112 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
113 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
114 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
115 static bool container_destroy(struct lxc_container
*c
,
116 struct lxc_storage
*storage
);
117 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
118 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
119 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
121 static bool config_file_exists(const char *lxcpath
, const char *cname
)
127 /* $lxcpath + '/' + $cname + '/config' + \0 */
128 len
= strlen(lxcpath
) + strlen(cname
) + 9;
130 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
131 if (ret
< 0 || (size_t)ret
>= len
)
134 return file_exists(fname
);
137 /* A few functions to help detect when a container creation failed. If a
138 * container creation was killed partway through, then trying to actually start
139 * that container could harm the host. We detect this by creating a 'partial'
140 * file under the container directory, and keeping an advisory lock. When
141 * container creation completes, we remove that file. When we load or try to
142 * start a container, if we find that file, without a flock, we remove the
145 static int ongoing_create(struct lxc_container
*c
)
150 struct flock lk
= {0};
152 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
154 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
155 if (ret
< 0 || (size_t)ret
>= len
)
158 if (!file_exists(path
))
161 fd
= open(path
, O_RDWR
);
166 lk
.l_whence
= SEEK_SET
;
169 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
170 if (ret
< 0 && errno
== EINVAL
)
171 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
175 if (ret
== 0 && lk
.l_pid
!= -1)
176 /* create is still ongoing */
179 /* Create completed but partial is still there. */
183 static int create_partial(struct lxc_container
*c
)
188 struct flock lk
= {0};
190 /* $lxcpath + '/' + $name + '/partial' + \0 */
191 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
193 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
194 if (ret
< 0 || (size_t)ret
>= len
)
197 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
202 lk
.l_whence
= SEEK_SET
;
204 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
206 if (errno
== EINVAL
) {
207 ret
= flock(fd
, LOCK_EX
);
212 SYSERROR("Failed to lock partial file %s", path
);
220 static void remove_partial(struct lxc_container
*c
, int fd
)
228 /* $lxcpath + '/' + $name + '/partial' + \0 */
229 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
231 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
232 if (ret
< 0 || (size_t)ret
>= len
)
237 SYSERROR("Failed to remove partial file %s", path
);
241 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
242 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
243 * container configuration file.
244 * The container_disk_lock also takes the container_mem_lock.
245 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
246 * NOTHING mutexes two independent programs with their own struct
247 * lxc_container for the same c->name, between API calls. For instance,
248 * c->config_read(); c->start(); Between those calls, data on disk
249 * could change (which shouldn't bother the caller unless for instance
250 * the rootfs get moved). c->config_read(); update; c->config_write();
251 * Two such updaters could race. The callers should therefore check their
252 * results. Trying to prevent that would necessarily expose us to deadlocks
253 * due to hung callers. So I prefer to keep the locks only within our own
254 * functions, not across functions.
256 * If you're going to clone while holding a lxccontainer, increment
257 * c->numthreads (under privlock) before forking. When deleting,
258 * decrement numthreads under privlock, then if it hits 0 you can delete.
259 * Do not ever use a lxccontainer whose numthreads you did not bump.
261 static void lxc_container_free(struct lxc_container
*c
)
267 c
->configfile
= NULL
;
269 free(c
->error_string
);
270 c
->error_string
= NULL
;
273 lxc_putlock(c
->slock
);
278 lxc_putlock(c
->privlock
);
286 lxc_conf_free(c
->lxc_conf
);
290 free(c
->config_path
);
291 c
->config_path
= NULL
;
296 /* Consider the following case:
298 * |====================================================================|
299 * | freer | racing get()er |
300 * |====================================================================|
301 * | lxc_container_put() | lxc_container_get() |
302 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
303 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
304 * | \ lxcunlock() | \ |
305 * | \ lxc_container_free() | \ lxclock() returns |
306 * | | \ c->numthreads < 1 -> return 0 |
307 * | \ \ (free stuff) | |
308 * | \ \ sem_destroy(privlock) | |
309 * |_______________________________|____________________________________|
311 * When the get()er checks numthreads the first time, one of the following
313 * 1. freer has set numthreads = 0. get() returns 0
314 * 2. freer is between lxclock and setting numthreads to 0. get()er will
315 * sem_wait on privlock, get lxclock after freer() drops it, then see
316 * numthreads is 0 and exit without touching lxclock again..
317 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
318 * will see --numthreads = 1 and not call lxc_container_free().
321 int lxc_container_get(struct lxc_container
*c
)
326 /* If someone else has already started freeing the container, don't try
327 * to take the lock, which may be invalid.
329 if (c
->numthreads
< 1)
332 if (container_mem_lock(c
))
335 /* Bail without trying to unlock, bc the privlock is now probably in
338 if (c
->numthreads
< 1)
342 container_mem_unlock(c
);
347 int lxc_container_put(struct lxc_container
*c
)
352 if (container_mem_lock(c
))
357 if (c
->numthreads
< 1) {
358 container_mem_unlock(c
);
359 lxc_container_free(c
);
363 container_mem_unlock(c
);
367 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
376 if (container_mem_lock(c
))
382 statret
= stat(c
->configfile
, &statbuf
);
389 container_mem_unlock(c
);
393 static int ensure_dir(const char *dest
) {
397 if (stat(dest
, &sb
) == 0) {
398 if ((sb
.st_mode
& S_IFMT
) == S_IFDIR
)
402 SYSERROR("Failed to remove old \"%s\"", dest
);
407 ret
= mkdir(dest
, 0755);
409 SYSERROR("Failed to mkdir \"%s\"", dest
);
416 static int ensure_file(const char *dest
) {
420 if (stat(dest
, &sb
) == 0) {
421 if ((sb
.st_mode
& S_IFMT
) != S_IFDIR
)
425 SYSERROR("Failed to remove old \"%s\"", dest
);
430 fd
= creat(dest
, 0755);
432 SYSERROR("Failed to mkdir \"%s\"", dest
);
440 /* @st_mode is the st_mode field of the stat(source) return struct */
441 static int create_mount_target(mode_t st_mode
, const char *dest
) {
442 char *dirdup
, *destdirname
;
445 dirdup
= strdup(dest
);
447 SYSERROR("Failed to duplicate target name");
451 destdirname
= dirname(dirdup
);
453 ret
= mkdir_p(destdirname
, 0755);
455 SYSERROR("failed to create path: %s", destdirname
);
461 switch (st_mode
& S_IFMT
) {
471 #define WRAP_API(rettype, fnname) \
472 static rettype fnname(struct lxc_container *c) \
475 bool reset_config = false; \
477 if (!current_config && c && c->lxc_conf) { \
478 current_config = c->lxc_conf; \
479 reset_config = true; \
482 ret = do_##fnname(c); \
484 current_config = NULL; \
489 #define WRAP_API_1(rettype, fnname, t1) \
490 static rettype fnname(struct lxc_container *c, t1 a1) \
493 bool reset_config = false; \
495 if (!current_config && c && c->lxc_conf) { \
496 current_config = c->lxc_conf; \
497 reset_config = true; \
500 ret = do_##fnname(c, a1); \
502 current_config = NULL; \
507 #define WRAP_API_2(rettype, fnname, t1, t2) \
508 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
511 bool reset_config = false; \
513 if (!current_config && c && c->lxc_conf) { \
514 current_config = c->lxc_conf; \
515 reset_config = true; \
518 ret = do_##fnname(c, a1, a2); \
520 current_config = NULL; \
525 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
526 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
529 bool reset_config = false; \
531 if (!current_config && c && c->lxc_conf) { \
532 current_config = c->lxc_conf; \
533 reset_config = true; \
536 ret = do_##fnname(c, a1, a2, a3); \
538 current_config = NULL; \
543 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
544 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
545 t4 a4, t5 a5, t6 a6) \
548 bool reset_config = false; \
550 if (!current_config && c && c->lxc_conf) { \
551 current_config = c->lxc_conf; \
552 reset_config = true; \
555 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
557 current_config = NULL; \
562 WRAP_API(bool, lxcapi_is_defined
)
564 static const char *do_lxcapi_state(struct lxc_container
*c
)
571 s
= lxc_getstate(c
->name
, c
->config_path
);
572 return lxc_state2str(s
);
575 WRAP_API(const char *, lxcapi_state
)
577 static bool is_stopped(struct lxc_container
*c
)
581 s
= lxc_getstate(c
->name
, c
->config_path
);
582 return (s
== STOPPED
);
585 static bool do_lxcapi_is_running(struct lxc_container
*c
)
590 return !is_stopped(c
);
593 WRAP_API(bool, lxcapi_is_running
)
595 static bool do_lxcapi_freeze(struct lxc_container
*c
)
602 ret
= lxc_freeze(c
->name
, c
->config_path
);
609 WRAP_API(bool, lxcapi_freeze
)
611 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
618 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
625 WRAP_API(bool, lxcapi_unfreeze
)
627 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
632 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
635 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
637 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
638 int stdoutfd
, int stderrfd
, int escape
)
645 current_config
= c
->lxc_conf
;
646 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
647 current_config
= NULL
;
652 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
656 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
659 NOTICE("The console log is empty");
660 else if (ret
== -EFAULT
)
661 NOTICE("The container does not keep a console log");
662 else if (ret
== -ENOENT
)
663 NOTICE("The container does not keep a console log file");
664 else if (ret
== -EIO
)
665 NOTICE("Failed to write console log to log file");
667 ERROR("Failed to retrieve console log");
673 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
675 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
680 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
683 WRAP_API(pid_t
, lxcapi_init_pid
)
685 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
688 c
->lxc_conf
= lxc_conf_init();
693 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
696 c
->lxc_conf
->name
= c
->name
;
700 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
704 bool need_disklock
= false, ret
= false;
709 fname
= c
->configfile
;
717 /* If we're reading something other than the container's config, we only
718 * need to lock the in-memory container. If loading the container's
719 * config file, take the disk lock.
721 if (strcmp(fname
, c
->configfile
) == 0)
722 need_disklock
= true;
725 lret
= container_disk_lock(c
);
727 lret
= container_mem_lock(c
);
731 ret
= load_config_locked(c
, fname
);
734 container_disk_unlock(c
);
736 container_mem_unlock(c
);
741 WRAP_API_1(bool, lxcapi_load_config
, const char *)
743 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
745 if (!c
|| !c
->lxc_conf
)
748 if (container_mem_lock(c
))
751 c
->daemonize
= state
;
753 container_mem_unlock(c
);
758 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
760 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
762 if (!c
|| !c
->lxc_conf
)
765 if (container_mem_lock(c
))
768 c
->lxc_conf
->close_all_fds
= state
;
770 container_mem_unlock(c
);
775 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
777 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
785 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
789 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
791 static bool am_single_threaded(void)
794 struct dirent
*direntp
;
797 dir
= opendir("/proc/self/task");
801 while ((direntp
= readdir(dir
))) {
802 if (strcmp(direntp
->d_name
, ".") == 0)
805 if (strcmp(direntp
->d_name
, "..") == 0)
817 static void push_arg(char ***argp
, char *arg
, int *nargs
)
822 copy
= must_copy_string(arg
);
825 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
834 static char **split_init_cmd(const char *incmd
)
840 char *saveptr
= NULL
;
845 len
= strlen(incmd
) + 1;
847 retlen
= strlcpy(copy
, incmd
, len
);
852 argv
= malloc(sizeof(char *));
856 for (; (p
= strtok_r(copy
, " ", &saveptr
)); copy
= NULL
)
857 push_arg(&argv
, p
, &nargs
);
867 static void free_init_cmd(char **argv
)
880 static int lxc_rcv_status(int state_socket
)
886 /* Receive container state. */
887 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
892 TRACE("Caught EINTR; retrying");
899 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
903 /* Close write end of the socket pair. */
904 close(handler
->state_socket_pair
[1]);
905 handler
->state_socket_pair
[1] = -1;
907 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
909 /* Close read end of the socket pair. */
910 close(handler
->state_socket_pair
[0]);
911 handler
->state_socket_pair
[0] = -1;
913 /* The first child is going to fork() again and then exits. So we reap
914 * the first child here.
916 ret
= wait_for_pid(pid
);
918 DEBUG("Failed waiting on first child %d", pid
);
920 DEBUG("First child %d exited", pid
);
923 SYSERROR("Failed to receive the container state");
927 /* If we receive anything else then running we know that the container
930 if (state
!= RUNNING
) {
931 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
932 lxc_state2str(state
));
936 TRACE("Container is in \"RUNNING\" state");
940 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
943 struct lxc_handler
*handler
;
944 struct lxc_conf
*conf
;
945 char *default_args
[] = {
949 char **init_cmd
= NULL
;
950 int keepfds
[3] = {-1, -1, -1};
952 /* container does exist */
956 /* If anything fails before we set error_num, we want an error in there.
960 /* Container has not been setup. */
964 ret
= ongoing_create(c
);
966 ERROR("Failed checking for incomplete container creation");
968 } else if (ret
== 1) {
969 ERROR("Ongoing container creation detected");
971 } else if (ret
== 2) {
972 ERROR("Failed to create container");
973 do_lxcapi_destroy(c
);
977 if (container_mem_lock(c
))
982 /* initialize handler */
983 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
985 container_mem_unlock(c
);
990 if (useinit
&& conf
->execute_cmd
)
991 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
993 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
996 /* ... otherwise use default_args. */
999 ERROR("No valid init detected");
1000 lxc_free_handler(handler
);
1003 argv
= default_args
;
1006 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
1007 * here to protect the on disk container? We don't want to exclude
1008 * things like lxc_info while the container is running.
1017 free_init_cmd(init_cmd
);
1018 lxc_free_handler(handler
);
1024 /* Set to NULL because we don't want father unlink
1025 * the PID file, child will do the free and unlink.
1029 /* Wait for container to tell us whether it started
1032 started
= wait_on_daemonized_start(handler
, pid
);
1034 free_init_cmd(init_cmd
);
1035 lxc_free_handler(handler
);
1041 /* We don't really care if this doesn't print all the
1042 * characters. All that it means is that the proctitle will be
1043 * ugly. Similarly, we also don't care if setproctitle() fails.
1045 (void)snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
1046 INFO("Attempting to set proc title to %s", title
);
1047 (void)setproctitle(title
);
1049 /* We fork() a second time to be reparented to init. Like
1050 * POSIX's daemon() function we change to "/" and redirect
1051 * std{in,out,err} to /dev/null.
1055 SYSERROR("Failed to fork first child process");
1056 _exit(EXIT_FAILURE
);
1061 free_init_cmd(init_cmd
);
1062 lxc_free_handler(handler
);
1063 _exit(EXIT_SUCCESS
);
1068 /* change to / directory */
1071 SYSERROR("Failed to change to \"/\" directory");
1072 _exit(EXIT_FAILURE
);
1075 keepfds
[0] = handler
->conf
->maincmd_fd
;
1076 keepfds
[1] = handler
->state_socket_pair
[0];
1077 keepfds
[2] = handler
->state_socket_pair
[1];
1078 ret
= lxc_check_inherited(conf
, true, keepfds
,
1079 sizeof(keepfds
) / sizeof(keepfds
[0]));
1081 _exit(EXIT_FAILURE
);
1083 /* redirect std{in,out,err} to /dev/null */
1084 ret
= null_stdfds();
1086 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1087 _exit(EXIT_FAILURE
);
1090 /* become session leader */
1093 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1095 if (!am_single_threaded()) {
1096 ERROR("Cannot start non-daemonized container when threaded");
1097 free_init_cmd(init_cmd
);
1098 lxc_free_handler(handler
);
1103 /* We need to write PID file after daemonize, so we always
1104 * write the right PID.
1108 char pidstr
[LXC_NUMSTRLEN64
];
1110 w
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", (int)lxc_raw_getpid());
1111 if (w
< 0 || (size_t)w
>= LXC_NUMSTRLEN64
) {
1112 free_init_cmd(init_cmd
);
1113 lxc_free_handler(handler
);
1115 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1118 _exit(EXIT_FAILURE
);
1123 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1125 free_init_cmd(init_cmd
);
1126 lxc_free_handler(handler
);
1128 SYSERROR("Failed to write '%s'", c
->pidfile
);
1131 _exit(EXIT_FAILURE
);
1137 conf
->reboot
= REBOOT_NONE
;
1139 /* Unshare the mount namespace if requested */
1140 if (conf
->monitor_unshare
) {
1141 ret
= unshare(CLONE_NEWNS
);
1143 SYSERROR("failed to unshare mount namespace");
1144 lxc_free_handler(handler
);
1149 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1151 SYSERROR("Failed to make / rslave at startup");
1152 lxc_free_handler(handler
);
1159 if (conf
->reboot
== REBOOT_INIT
) {
1160 /* initialize handler */
1161 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1168 keepfds
[0] = handler
->conf
->maincmd_fd
;
1169 keepfds
[1] = handler
->state_socket_pair
[0];
1170 keepfds
[2] = handler
->state_socket_pair
[1];
1171 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1172 sizeof(keepfds
) / sizeof(keepfds
[0]));
1174 lxc_free_handler(handler
);
1180 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1181 c
->daemonize
, &c
->error_num
);
1183 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1184 c
->daemonize
, &c
->error_num
);
1186 if (conf
->reboot
== REBOOT_REQ
) {
1187 INFO("Container requested reboot");
1188 conf
->reboot
= REBOOT_INIT
;
1198 free_init_cmd(init_cmd
);
1200 if (c
->daemonize
&& ret
!= 0)
1201 _exit(EXIT_FAILURE
);
1202 else if (c
->daemonize
)
1203 _exit(EXIT_SUCCESS
);
1211 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1216 current_config
= c
? c
->lxc_conf
: NULL
;
1217 ret
= do_lxcapi_start(c
, useinit
, argv
);
1218 current_config
= NULL
;
1223 /* Note, there MUST be an ending NULL. */
1224 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1227 char **inargs
= NULL
;
1230 /* container exists */
1234 current_config
= c
->lxc_conf
;
1236 va_start(ap
, useinit
);
1237 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1242 /* pass NULL if no arguments were supplied */
1243 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1249 for (arg
= inargs
; *arg
; arg
++)
1254 current_config
= NULL
;
1259 static bool do_lxcapi_stop(struct lxc_container
*c
)
1266 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1271 WRAP_API(bool, lxcapi_stop
)
1273 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1280 mode_t mask
= umask(0002);
1281 ret
= mkdir(path
, 0770);
1286 if (errno
!= EEXIST
)
1293 p
= alloca(len
+ 1);
1294 (void)strlcpy(p
, path
, len
+ 1);
1296 if (!lxc_list_empty(&conf
->id_map
)) {
1297 ret
= chown_mapped_root(p
, conf
);
1305 /* Create the standard expected container dir. */
1306 static bool create_container_dir(struct lxc_container
*c
)
1312 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1317 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1318 if (ret
< 0 || (size_t)ret
>= len
) {
1323 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1329 /* do_storage_create: thin wrapper around storage_create(). Like
1330 * storage_create(), it returns a mounted bdev on success, NULL on error.
1332 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1334 struct bdev_specs
*specs
)
1339 struct lxc_storage
*bdev
;
1341 /* rootfs.path or lxcpath/lxcname/rootfs */
1342 if (c
->lxc_conf
->rootfs
.path
&&
1343 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1344 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1345 len
= strlen(rpath
) + 1;
1347 ret
= snprintf(dest
, len
, "%s", rpath
);
1349 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1350 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1352 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1354 if (ret
< 0 || (size_t)ret
>= len
)
1357 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1359 ERROR("Failed to create \"%s\" storage", type
);
1363 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1364 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1368 /* If we are not root, chown the rootfs dir to root in the target user
1372 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1373 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1375 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1376 suggest_default_idmap();
1385 static char *lxcbasename(char *path
)
1389 p
= path
+ strlen(path
) - 1;
1390 while (*p
!= '/' && p
> path
)
1396 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1397 bool need_null_stdfds
, char *const argv
[])
1407 SYSERROR("Failed to fork task for container creation template");
1411 if (pid
== 0) { /* child */
1413 char *namearg
, *patharg
, *rootfsarg
;
1416 struct lxc_storage
*bdev
= NULL
;
1417 struct lxc_conf
*conf
= c
->lxc_conf
;
1420 if (need_null_stdfds
) {
1421 ret
= null_stdfds();
1423 _exit(EXIT_FAILURE
);
1426 bdev
= storage_init(c
->lxc_conf
);
1428 ERROR("Failed to initialize storage");
1429 _exit(EXIT_FAILURE
);
1434 ret
= unshare(CLONE_NEWNS
);
1436 ERROR("Failed to unshare CLONE_NEWNS");
1437 _exit(EXIT_FAILURE
);
1440 ret
= detect_shared_rootfs();
1442 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1444 SYSERROR("Failed to make \"/\" rslave");
1445 ERROR("Continuing...");
1450 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1452 ERROR("Unprivileged users can only create "
1453 "btrfs and directory-backed containers");
1454 _exit(EXIT_FAILURE
);
1457 if (strcmp(bdev
->type
, "overlay") == 0 ||
1458 strcmp(bdev
->type
, "overlayfs") == 0) {
1459 /* If we create an overlay container we need to
1460 * rsync the contents into
1461 * <container-path>/<container-name>/rootfs.
1462 * However, the overlay mount function will
1464 * <container-path>/<container-name>/delta0
1466 * <container-path>/<container-name>/rootfs
1467 * which means we would rsync the rootfs into
1468 * the delta directory. That doesn't make sense
1469 * since the delta directory only exists to
1470 * record the differences to
1471 * <container-path>/<container-name>/rootfs. So
1472 * let's simply bind-mount here and then rsync
1474 * <container-path>/<container-name>/rootfs.
1478 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1480 ERROR("Failed to get rootfs");
1481 _exit(EXIT_FAILURE
);
1484 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1486 ERROR("Failed to mount rootfs");
1487 _exit(EXIT_FAILURE
);
1490 ret
= bdev
->ops
->mount(bdev
);
1492 ERROR("Failed to mount rootfs");
1493 _exit(EXIT_FAILURE
);
1496 } else { /* TODO come up with a better way here! */
1499 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1500 bdev
->dest
= strdup(src
);
1503 /* Create our new array, pre-pend the template name and base
1507 for (nargs
= 0; argv
[nargs
]; nargs
++)
1510 /* template, path, rootfs and name args */
1513 newargv
= malloc(nargs
* sizeof(*newargv
));
1515 _exit(EXIT_FAILURE
);
1516 newargv
[0] = lxcbasename(tpath
);
1519 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1520 patharg
= malloc(len
);
1522 _exit(EXIT_FAILURE
);
1524 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1525 if (ret
< 0 || ret
>= len
)
1526 _exit(EXIT_FAILURE
);
1527 newargv
[1] = patharg
;
1530 len
= strlen("--name=") + strlen(c
->name
) + 1;
1531 namearg
= malloc(len
);
1533 _exit(EXIT_FAILURE
);
1535 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1536 if (ret
< 0 || ret
>= len
)
1537 _exit(EXIT_FAILURE
);
1538 newargv
[2] = namearg
;
1541 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1542 rootfsarg
= malloc(len
);
1544 _exit(EXIT_FAILURE
);
1546 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1547 if (ret
< 0 || ret
>= len
)
1548 _exit(EXIT_FAILURE
);
1549 newargv
[3] = rootfsarg
;
1551 /* add passed-in args */
1553 for (i
= 4; i
< nargs
; i
++)
1554 newargv
[i
] = argv
[i
- 4];
1556 /* add trailing NULL */
1558 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1560 _exit(EXIT_FAILURE
);
1561 newargv
[nargs
- 1] = NULL
;
1563 /* If we're running the template in a mapped userns, then we
1564 * prepend the template command with: lxc-usernsexec <-m map1>
1565 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1566 * the mapped uid for our geteuid()
1568 if (!lxc_list_empty(&conf
->id_map
)) {
1569 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1571 char txtuid
[20], txtgid
[20];
1572 struct lxc_list
*it
;
1576 n2
= malloc(n2args
* sizeof(*n2
));
1578 _exit(EXIT_FAILURE
);
1581 tpath
= "lxc-usernsexec";
1582 n2
[0] = "lxc-usernsexec";
1584 lxc_list_for_each(it
, &conf
->id_map
) {
1587 n2
= realloc(n2
, n2args
* sizeof(char *));
1589 _exit(EXIT_FAILURE
);
1591 n2
[n2args
- 2] = "-m";
1592 n2
[n2args
- 1] = malloc(200);
1593 if (!n2
[n2args
- 1])
1594 _exit(EXIT_FAILURE
);
1596 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1597 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1598 map
->nsid
, map
->hostid
, map
->range
);
1599 if (ret
< 0 || ret
>= 200)
1600 _exit(EXIT_FAILURE
);
1603 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1604 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1606 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1608 _exit(EXIT_FAILURE
);
1610 if (hostuid_mapped
< 0) {
1611 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1612 n2
[n2args
++] = "-m";
1613 if (hostuid_mapped
< 0) {
1614 ERROR("Failed to find free uid to map");
1615 _exit(EXIT_FAILURE
);
1618 n2
[n2args
++] = malloc(200);
1619 if (!n2
[n2args
- 1]) {
1620 SYSERROR("out of memory");
1621 _exit(EXIT_FAILURE
);
1624 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1625 hostuid_mapped
, geteuid());
1626 if (ret
< 0 || ret
>= 200)
1627 _exit(EXIT_FAILURE
);
1630 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1631 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1633 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1635 _exit(EXIT_FAILURE
);
1637 if (hostgid_mapped
< 0) {
1638 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1639 n2
[n2args
++] = "-m";
1640 if (hostgid_mapped
< 0) {
1641 ERROR("Failed to find free gid to map");
1642 _exit(EXIT_FAILURE
);
1645 n2
[n2args
++] = malloc(200);
1646 if (!n2
[n2args
- 1]) {
1647 SYSERROR("out of memory");
1648 _exit(EXIT_FAILURE
);
1651 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1652 hostgid_mapped
, getegid());
1653 if (ret
< 0 || ret
>= 200)
1654 _exit(EXIT_FAILURE
);
1657 n2
[n2args
++] = "--";
1659 for (i
= 0; i
< nargs
; i
++)
1660 n2
[i
+ n2args
] = newargv
[i
];
1663 /* Finally add "--mapped-uid $uid" to tell template what
1664 * to chown cached images to.
1667 n2
= realloc(n2
, n2args
* sizeof(char *));
1669 _exit(EXIT_FAILURE
);
1671 /* note n2[n2args-1] is NULL */
1672 n2
[n2args
- 5] = "--mapped-uid";
1674 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1675 if (ret
< 0 || ret
>= 20) {
1678 _exit(EXIT_FAILURE
);
1681 n2
[n2args
- 4] = txtuid
;
1682 n2
[n2args
- 3] = "--mapped-gid";
1684 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1685 if (ret
< 0 || ret
>= 20) {
1688 _exit(EXIT_FAILURE
);
1691 n2
[n2args
- 2] = txtgid
;
1692 n2
[n2args
- 1] = NULL
;
1697 execvp(tpath
, newargv
);
1698 SYSERROR("Failed to execute template %s", tpath
);
1699 _exit(EXIT_FAILURE
);
1702 ret
= wait_for_pid(pid
);
1704 ERROR("Failed to create container from template");
1711 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1720 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1724 f
= fopen(path
, "r");
1728 ret
= fseek(f
, 0, SEEK_END
);
1737 ret
= fseek(f
, 0, SEEK_SET
);
1741 ret
= fseek(f
, 0, SEEK_SET
);
1746 contents
= malloc(flen
+ 1);
1750 len
= fread(contents
, 1, flen
, f
);
1752 goto out_free_contents
;
1754 contents
[flen
] = '\0';
1759 goto out_free_contents
;
1762 tpath
= get_template_path(t
);
1764 ERROR("Invalid template \"%s\" specified", t
);
1765 goto out_free_contents
;
1768 ret
= sha1sum_file(tpath
, md_value
);
1770 ERROR("Failed to get sha1sum of %s", tpath
);
1772 goto out_free_contents
;
1777 f
= fopen(path
, "w");
1779 SYSERROR("Reopening config for writing");
1784 fprintf(f
, "# Template used to create this container: %s\n", t
);
1786 fprintf(f
, "# Parameters passed to the template:");
1788 fprintf(f
, " %s", *argv
);
1795 fprintf(f
, "# Template script checksum (SHA-1): ");
1796 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1797 fprintf(f
, "%02x", md_value
[i
]);
1800 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1801 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1802 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1803 fprintf(f
, "# (Be aware this has security implications)\n\n");
1804 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1805 SYSERROR("Writing original contents");
1825 SYSERROR("Error prepending header");
1832 static void lxcapi_clear_config(struct lxc_container
*c
)
1834 if (!c
|| !c
->lxc_conf
)
1837 lxc_conf_free(c
->lxc_conf
);
1841 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1845 * create a container with the given parameters.
1846 * @c: container to be created. It has the lxcpath, name, and a starting
1847 * configuration already set
1848 * @t: the template to execute to instantiate the root filesystem and
1849 * adjust the configuration.
1850 * @bdevtype: backing store type to use. If NULL, dir will be used.
1851 * @specs: additional parameters for the backing store, i.e. LVM vg to
1854 * @argv: the arguments to pass to the template, terminated by NULL. If no
1855 * arguments, you can just pass NULL.
1857 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1858 const char *bdevtype
, struct bdev_specs
*specs
,
1859 int flags
, char *const argv
[])
1871 tpath
= get_template_path(t
);
1873 ERROR("Unknown template \"%s\"", t
);
1878 /* If a template is passed in, and the rootfs already is defined in the
1879 * container config and exists, then the caller is trying to create an
1880 * existing container. Return an error, but do NOT delete the container.
1882 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1883 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1884 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1890 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1891 ERROR("Error loading default configuration file %s",
1892 lxc_global_config_value("lxc.default_config"));
1897 if (!create_container_dir(c
))
1900 /* If both template and rootfs.path are set, template is setup as
1901 * rootfs.path. The container is already created if we have a config and
1902 * rootfs.path is accessible
1904 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1905 /* No template passed in and rootfs does not exist. */
1906 if (!c
->save_config(c
, NULL
)) {
1907 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1914 /* Rootfs passed into configuration, but does not exist. */
1915 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1918 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1919 /* Rootfs already existed, user just wanted to save the loaded
1922 if (!c
->save_config(c
, NULL
))
1923 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1929 /* Mark that this container is being created */
1930 partial_fd
= create_partial(c
);
1934 /* No need to get disk lock bc we have the partial lock. */
1938 /* Create the storage.
1939 * Note we can't do this in the same task as we use to execute the
1940 * template because of the way zfs works.
1941 * After you 'zfs create', zfs mounts the fs only in the initial
1946 SYSERROR("Failed to fork task for container creation template");
1950 if (pid
== 0) { /* child */
1951 struct lxc_storage
*bdev
= NULL
;
1953 bdev
= do_storage_create(c
, bdevtype
, specs
);
1955 ERROR("Failed to create %s storage for %s",
1956 bdevtype
? bdevtype
: "(none)", c
->name
);
1957 _exit(EXIT_FAILURE
);
1960 /* Save config file again to store the new rootfs location. */
1961 if (!do_lxcapi_save_config(c
, NULL
)) {
1962 ERROR("Failed to save initial config for %s", c
->name
);
1963 /* Parent task won't see the storage driver in the
1964 * config so we delete it.
1966 bdev
->ops
->umount(bdev
);
1967 bdev
->ops
->destroy(bdev
);
1968 _exit(EXIT_FAILURE
);
1971 _exit(EXIT_SUCCESS
);
1974 if (wait_for_pid(pid
) != 0)
1977 /* Reload config to get the rootfs. */
1978 lxc_conf_free(c
->lxc_conf
);
1981 if (!load_config_locked(c
, c
->configfile
))
1984 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1987 /* Now clear out the lxc_conf we have, reload from the created
1990 do_lxcapi_clear_config(c
);
1993 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1994 ERROR("Failed to prepend header to config file");
1999 ret
= load_config_locked(c
, c
->configfile
);
2003 if (partial_fd
>= 0)
2004 remove_partial(c
, partial_fd
);
2008 container_destroy(c
, NULL
);
2015 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
2016 const char *bdevtype
, struct bdev_specs
*specs
,
2017 int flags
, char *const argv
[])
2021 current_config
= c
? c
->lxc_conf
: NULL
;
2023 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
2024 current_config
= NULL
;
2028 static bool do_lxcapi_reboot(struct lxc_container
*c
)
2032 int rebootsignal
= SIGINT
;
2037 if (!do_lxcapi_is_running(c
))
2040 pid
= do_lxcapi_init_pid(c
);
2044 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2045 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2047 ret
= kill(pid
, rebootsignal
);
2049 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2056 WRAP_API(bool, lxcapi_reboot
)
2058 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
2062 int rebootsignal
= SIGINT
, state_client_fd
= -1;
2063 lxc_state_t states
[MAX_STATE
] = {0};
2068 if (!do_lxcapi_is_running(c
))
2071 pid
= do_lxcapi_init_pid(c
);
2075 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2076 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2078 /* Add a new state client before sending the shutdown signal so that we
2079 * don't miss a state.
2082 states
[RUNNING
] = 2;
2083 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2088 if (state_client_fd
< 0)
2094 if (ret
< MAX_STATE
)
2098 /* Send reboot signal to container. */
2099 killret
= kill(pid
, rebootsignal
);
2101 if (state_client_fd
>= 0)
2102 close(state_client_fd
);
2104 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2107 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2112 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2113 close(state_client_fd
);
2117 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2124 WRAP_API_1(bool, lxcapi_reboot2
, int)
2126 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2130 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2131 lxc_state_t states
[MAX_STATE
] = {0};
2136 if (!do_lxcapi_is_running(c
))
2139 pid
= do_lxcapi_init_pid(c
);
2143 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2144 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2145 haltsignal
= c
->lxc_conf
->haltsignal
;
2146 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2147 haltsignal
= (SIGRTMIN
+ 3);
2149 /* Add a new state client before sending the shutdown signal so that we
2150 * don't miss a state.
2153 states
[STOPPED
] = 1;
2154 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2159 if (state_client_fd
< 0)
2165 if (ret
< MAX_STATE
)
2169 /* Send shutdown signal to container. */
2170 killret
= kill(pid
, haltsignal
);
2172 if (state_client_fd
>= 0)
2173 close(state_client_fd
);
2175 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2178 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2183 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2184 close(state_client_fd
);
2188 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2195 WRAP_API_1(bool, lxcapi_shutdown
, int)
2197 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2198 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2207 current_config
= c
->lxc_conf
;
2210 * since we're going to wait for create to finish, I don't think we
2211 * need to get a copy of the arguments.
2213 va_start(ap
, flags
);
2214 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2217 ERROR("Failed to allocate memory");
2221 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2225 current_config
= NULL
;
2229 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2231 if (!strcmp(key
, "lxc.cgroup"))
2232 return clear_unexp_config_line(conf
, key
, true);
2234 if (!strcmp(key
, "lxc.network"))
2235 return clear_unexp_config_line(conf
, key
, true);
2237 if (!strcmp(key
, "lxc.net"))
2238 return clear_unexp_config_line(conf
, key
, true);
2240 /* Clear a network with a specific index. */
2241 if (!strncmp(key
, "lxc.net.", 8)) {
2246 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2248 return clear_unexp_config_line(conf
, key
, true);
2251 if (!strcmp(key
, "lxc.hook"))
2252 return clear_unexp_config_line(conf
, key
, true);
2254 return clear_unexp_config_line(conf
, key
, false);
2257 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2261 struct lxc_config_t
*config
;
2263 if (!c
|| !c
->lxc_conf
)
2266 if (container_mem_lock(c
))
2269 config
= lxc_get_config(key
);
2270 /* Verify that the config key exists and that it has a callback
2273 if (config
&& config
->clr
)
2274 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2277 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2279 container_mem_unlock(c
);
2283 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2285 static inline bool enter_net_ns(struct lxc_container
*c
)
2287 pid_t pid
= do_lxcapi_init_pid(c
);
2289 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2290 (access("/proc/self/ns/user", F_OK
) == 0))
2291 if (!switch_to_ns(pid
, "user"))
2294 return switch_to_ns(pid
, "net");
2297 /* Used by qsort and bsearch functions for comparing names. */
2298 static inline int string_cmp(char **first
, char **second
)
2300 return strcmp(*first
, *second
);
2303 /* Used by qsort and bsearch functions for comparing container names. */
2304 static inline int container_cmp(struct lxc_container
**first
,
2305 struct lxc_container
**second
)
2307 return strcmp((*first
)->name
, (*second
)->name
);
2310 static bool add_to_array(char ***names
, char *cname
, int pos
)
2312 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2314 ERROR("Out of memory");
2319 newnames
[pos
] = strdup(cname
);
2323 /* Sort the arrray as we will use binary search on it. */
2324 qsort(newnames
, pos
+ 1, sizeof(char *),
2325 (int (*)(const void *, const void *))string_cmp
);
2330 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2333 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2335 ERROR("Out of memory");
2342 /* Sort the arrray as we will use binary search on it. */
2344 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2345 (int (*)(const void *, const void *))container_cmp
);
2350 static char** get_from_array(char ***names
, char *cname
, int size
)
2352 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2355 static bool array_contains(char ***names
, char *cname
, int size
)
2357 if(get_from_array(names
, cname
, size
) != NULL
)
2363 static bool remove_from_array(char ***names
, char *cname
, int size
)
2365 char **result
= get_from_array(names
, cname
, size
);
2366 if (result
!= NULL
) {
2374 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2377 int i
, count
= 0, pipefd
[2];
2378 char **interfaces
= NULL
;
2379 char interface
[IFNAMSIZ
];
2381 if(pipe(pipefd
) < 0) {
2382 SYSERROR("pipe failed");
2388 SYSERROR("failed to fork task to get interfaces information");
2394 if (pid
== 0) { /* child */
2395 int ret
= 1, nbytes
;
2396 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2398 /* close the read-end of the pipe */
2401 if (!enter_net_ns(c
)) {
2402 SYSERROR("failed to enter namespace");
2406 /* Grab the list of interfaces */
2407 if (getifaddrs(&interfaceArray
)) {
2408 SYSERROR("failed to get interfaces list");
2412 /* Iterate through the interfaces */
2413 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2414 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2416 ERROR("write failed");
2426 freeifaddrs(interfaceArray
);
2428 /* close the write-end of the pipe, thus sending EOF to the reader */
2433 /* close the write-end of the pipe */
2436 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2437 interface
[IFNAMSIZ
- 1] = '\0';
2439 if (array_contains(&interfaces
, interface
, count
))
2442 if(!add_to_array(&interfaces
, interface
, count
))
2443 ERROR("Failed to add \"%s\" to array", interface
);
2448 if (wait_for_pid(pid
) != 0) {
2449 for(i
=0;i
<count
;i
++)
2450 free(interfaces
[i
]);
2456 /* close the read-end of the pipe */
2459 /* Append NULL to the array */
2461 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2466 WRAP_API(char **, lxcapi_get_interfaces
)
2468 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2469 const char *family
, int scope
)
2474 char address
[INET6_ADDRSTRLEN
];
2476 char **addresses
= NULL
;
2480 SYSERROR("Failed to create pipe");
2486 SYSERROR("Failed to create new process");
2494 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2496 char *address
= NULL
;
2497 void *tempAddrPtr
= NULL
;
2498 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2500 /* close the read-end of the pipe */
2503 if (!enter_net_ns(c
)) {
2504 SYSERROR("Failed to attach to network namespace");
2508 /* Grab the list of interfaces */
2509 if (getifaddrs(&interfaceArray
)) {
2510 SYSERROR("Failed to get interfaces list");
2514 /* Iterate through the interfaces */
2515 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2516 tempIfAddr
= tempIfAddr
->ifa_next
) {
2517 if (tempIfAddr
->ifa_addr
== NULL
)
2520 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2521 if (family
&& strcmp(family
, "inet"))
2524 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2526 if (family
&& strcmp(family
, "inet6"))
2529 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2532 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2535 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2537 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2540 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2541 tempAddrPtr
, addressOutputBuffer
,
2542 sizeof(addressOutputBuffer
));
2546 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2547 if (nbytes
!= INET6_ADDRSTRLEN
) {
2548 SYSERROR("Failed to send ipv6 address \"%s\"",
2560 freeifaddrs(interfaceArray
);
2562 /* close the write-end of the pipe, thus sending EOF to the reader */
2567 /* close the write-end of the pipe */
2570 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2571 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2573 if (!add_to_array(&addresses
, address
, count
))
2574 ERROR("PARENT: add_to_array failed");
2579 if (wait_for_pid(pid
) != 0) {
2580 for (i
= 0; i
< count
; i
++)
2587 /* close the read-end of the pipe */
2590 /* Append NULL to the array */
2592 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2597 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2599 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2602 struct lxc_config_t
*config
;
2604 if (!c
|| !c
->lxc_conf
)
2607 if (container_mem_lock(c
))
2610 config
= lxc_get_config(key
);
2611 /* Verify that the config key exists and that it has a callback
2614 if (config
&& config
->get
)
2615 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2617 container_mem_unlock(c
);
2621 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2623 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2627 if (!c
|| !c
->lxc_conf
)
2630 if (container_mem_lock(c
))
2633 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2634 container_mem_unlock(c
);
2638 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2640 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2644 /* List all config items. */
2646 return lxc_list_config_items(retv
, inlen
);
2648 if (!c
|| !c
->lxc_conf
)
2651 if (container_mem_lock(c
))
2654 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2655 * This is an intelligent result to show which keys are valid given the
2656 * type of nic it is.
2658 if (strncmp(key
, "lxc.net.", 8) == 0)
2659 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2661 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2663 container_mem_unlock(c
);
2667 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2669 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2672 bool ret
= false, need_disklock
= false;
2675 alt_file
= c
->configfile
;
2680 /* If we haven't yet loaded a config, load the stock config. */
2682 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2683 ERROR("Error loading default configuration file %s "
2685 lxc_global_config_value("lxc.default_config"),
2691 if (!create_container_dir(c
))
2694 /* If we're writing to the container's config file, take the disk lock.
2695 * Otherwise just take the memlock to protect the struct lxc_container
2696 * while we're traversing it.
2698 if (strcmp(c
->configfile
, alt_file
) == 0)
2699 need_disklock
= true;
2702 lret
= container_disk_lock(c
);
2704 lret
= container_mem_lock(c
);
2708 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2709 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2713 lret
= write_config(fd
, c
->lxc_conf
);
2722 container_disk_unlock(c
);
2724 container_mem_unlock(c
);
2729 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2732 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2738 char path
[MAXPATHLEN
];
2739 char newpath
[MAXPATHLEN
];
2740 int fd
, ret
, n
= 0, v
= 0;
2742 size_t len
= 0, bytes
= 0;
2744 if (container_disk_lock(c0
))
2747 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2748 if (ret
< 0 || ret
> MAXPATHLEN
)
2751 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2752 if (ret
< 0 || ret
> MAXPATHLEN
)
2755 /* If we find an lxc-snapshot file using the old format only listing the
2756 * number of snapshots we will keep using it. */
2757 f1
= fopen(path
, "r");
2759 n
= fscanf(f1
, "%d", &v
);
2761 if (n
== 1 && v
== 0) {
2764 SYSERROR("Failed to remove \"%s\"", path
);
2772 f1
= fopen(path
, "w");
2776 if (fprintf(f1
, "%d\n", v
) < 0) {
2777 ERROR("Error writing new snapshots value");
2784 SYSERROR("Error writing to or closing snapshots file");
2788 /* Here we know that we have or can use an lxc-snapshot file
2789 * using the new format. */
2791 f1
= fopen(path
, "a");
2795 if (fprintf(f1
, "%s", newpath
) < 0) {
2796 ERROR("Error writing new snapshots entry");
2799 SYSERROR("Error writing to or closing snapshots file");
2805 SYSERROR("Error writing to or closing snapshots file");
2809 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2812 if (fstat(fd
, &fbuf
) < 0) {
2817 if (fbuf
.st_size
!= 0) {
2818 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2819 if (buf
== MAP_FAILED
) {
2820 SYSERROR("Failed to create mapping %s", path
);
2825 len
= strlen(newpath
);
2826 while ((del
= strstr((char *)buf
, newpath
))) {
2827 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2831 lxc_strmunmap(buf
, fbuf
.st_size
);
2832 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2833 SYSERROR("Failed to truncate file %s", path
);
2842 /* If the lxc-snapshot file is empty, remove it. */
2843 if (stat(path
, &fbuf
) < 0)
2846 if (!fbuf
.st_size
) {
2849 SYSERROR("Failed to remove \"%s\"", path
);
2856 container_disk_unlock(c0
);
2860 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2862 struct lxc_container
*p
;
2863 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2864 size_t pathlen
= 0, namelen
= 0;
2868 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2869 c
->config_path
, c
->name
);
2870 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2871 ERROR("Path name too long");
2875 f
= fopen(path
, "r");
2879 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2880 if (getline(&lxcname
, &namelen
, f
) == -1) {
2881 ERROR("badly formatted file %s", path
);
2885 remove_trailing_newlines(lxcpath
);
2886 remove_trailing_newlines(lxcname
);
2888 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2889 ERROR("Unable to find dependent container %s:%s",
2894 if (!mod_rdep(p
, c
, inc
))
2895 ERROR("Failed to update snapshots file for %s:%s",
2898 lxc_container_put(p
);
2907 static bool has_fs_snapshots(struct lxc_container
*c
)
2910 char path
[MAXPATHLEN
];
2915 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2917 if (ret
< 0 || ret
> MAXPATHLEN
)
2920 /* If the file doesn't exist there are no snapshots. */
2921 if (stat(path
, &fbuf
) < 0)
2926 f
= fopen(path
, "r");
2930 ret
= fscanf(f
, "%d", &v
);
2932 /* TODO: Figure out what to do with the return value of fscanf. */
2934 INFO("Container uses new lxc-snapshots format %s", path
);
2943 static bool has_snapshots(struct lxc_container
*c
)
2945 char path
[MAXPATHLEN
];
2946 struct dirent
*direntp
;
2950 if (!get_snappath_dir(c
, path
))
2953 dir
= opendir(path
);
2957 while ((direntp
= readdir(dir
))) {
2958 if (!strcmp(direntp
->d_name
, "."))
2961 if (!strcmp(direntp
->d_name
, ".."))
2971 static bool do_destroy_container(struct lxc_conf
*conf
) {
2974 if (am_guest_unpriv()) {
2975 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2976 "storage_destroy_wrapper");
2983 return storage_destroy(conf
);
2986 static int lxc_rmdir_onedev_wrapper(void *data
)
2988 char *arg
= (char *) data
;
2989 return lxc_rmdir_onedev(arg
, "snaps");
2992 static int lxc_unlink_exec_wrapper(void *data
)
2998 static bool container_destroy(struct lxc_container
*c
,
2999 struct lxc_storage
*storage
)
3003 struct lxc_conf
*conf
;
3008 if (!c
|| !do_lxcapi_is_defined(c
))
3012 if (container_disk_lock(c
))
3015 if (!is_stopped(c
)) {
3016 /* We should queue some sort of error - in c->error_string? */
3017 ERROR("container %s is not stopped", c
->name
);
3021 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
3022 /* Start of environment variable setup for hooks */
3023 if (setenv("LXC_NAME", c
->name
, 1))
3024 SYSERROR("Failed to set environment variable for container name");
3026 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3027 SYSERROR("Failed to set environment variable for config path");
3029 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
3030 SYSERROR("Failed to set environment variable for rootfs mount");
3032 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3033 SYSERROR("Failed to set environment variable for rootfs mount");
3035 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
3036 SYSERROR("Failed to set environment variable for console path");
3038 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
3039 SYSERROR("Failed to set environment variable for console log");
3040 /* End of environment variable setup for hooks */
3042 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
3043 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
3048 if (current_config
&& conf
== current_config
) {
3049 current_config
= NULL
;
3051 if (conf
->logfd
!= -1) {
3057 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
3058 if (!do_destroy_container(conf
)) {
3059 ERROR("Error destroying rootfs for %s", c
->name
);
3062 INFO("Destroyed rootfs for %s", c
->name
);
3065 mod_all_rdeps(c
, false);
3067 p1
= do_lxcapi_get_config_path(c
);
3076 * strlen("config") = 6
3080 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3083 ERROR("Failed to allocate memory");
3087 /* For an overlay container the rootfs is considered immutable and
3088 * cannot be removed when restoring from a snapshot.
3090 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3091 !strcmp(storage
->type
, "overlayfs")) &&
3092 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3093 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3094 if (ret
< 0 || (size_t)ret
>= len
)
3097 if (am_guest_unpriv())
3098 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3099 "lxc_unlink_exec_wrapper");
3103 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3107 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3113 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3114 if (ret
< 0 || (size_t)ret
>= len
)
3117 if (am_guest_unpriv())
3118 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3119 "lxc_rmdir_onedev_wrapper");
3121 ret
= lxc_rmdir_onedev(path
, "snaps");
3123 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3127 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3135 container_disk_unlock(c
);
3139 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3141 if (!c
|| !lxcapi_is_defined(c
))
3144 if (has_snapshots(c
)) {
3145 ERROR("Container %s has snapshots; not removing", c
->name
);
3149 if (has_fs_snapshots(c
)) {
3150 ERROR("container %s has snapshots on its rootfs", c
->name
);
3154 return container_destroy(c
, NULL
);
3157 WRAP_API(bool, lxcapi_destroy
)
3159 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3161 if (!c
|| !lxcapi_is_defined(c
))
3164 if (!lxcapi_snapshot_destroy_all(c
)) {
3165 ERROR("Error deleting all snapshots");
3169 return lxcapi_destroy(c
);
3172 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3174 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3178 struct lxc_config_t
*config
;
3181 config
= lxc_get_config(key
);
3185 ret
= config
->set(key
, v
, conf
, NULL
);
3189 if (lxc_config_value_empty(v
))
3190 do_clear_unexp_config_line(conf
, key
);
3192 bret
= do_append_unexp_config_line(conf
, key
, v
);
3199 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3205 c
->lxc_conf
= lxc_conf_init();
3210 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3217 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3224 if (container_mem_lock(c
))
3227 b
= do_set_config_item_locked(c
, key
, v
);
3229 container_mem_unlock(c
);
3233 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3235 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3237 if (!c
|| !c
->configfile
)
3240 return strdup(c
->configfile
);
3243 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3245 if (!c
|| !c
->config_path
)
3248 return (const char *)(c
->config_path
);
3253 * Just recalculate the c->configfile based on the
3254 * c->config_path, which must be set.
3255 * The lxc_container must be locked or not yet public.
3257 static bool set_config_filename(struct lxc_container
*c
)
3262 if (!c
->config_path
)
3265 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3266 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3267 newpath
= malloc(len
);
3271 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3272 if (ret
< 0 || ret
>= len
) {
3273 fprintf(stderr
, "Error printing out config file name\n");
3278 free(c
->configfile
);
3279 c
->configfile
= newpath
;
3284 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3288 char *oldpath
= NULL
;
3293 if (container_mem_lock(c
))
3298 ERROR("Out of memory setting new lxc path");
3304 oldpath
= c
->config_path
;
3307 /* Since we've changed the config path, we have to change the
3308 * config file name too */
3309 if (!set_config_filename(c
)) {
3310 ERROR("Out of memory setting new config filename");
3312 free(c
->config_path
);
3313 c
->config_path
= oldpath
;
3319 container_mem_unlock(c
);
3323 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3325 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3328 struct cgroup_ops
*cgroup_ops
;
3336 cgroup_ops
= cgroup_init(NULL
);
3340 if (container_disk_lock(c
))
3343 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3345 container_disk_unlock(c
);
3347 cgroup_exit(cgroup_ops
);
3352 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3354 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3357 struct cgroup_ops
*cgroup_ops
;
3365 cgroup_ops
= cgroup_init(NULL
);
3369 if (container_disk_lock(c
))
3372 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3375 container_disk_unlock(c
);
3377 cgroup_exit(cgroup_ops
);
3382 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3384 const char *lxc_get_global_config_item(const char *key
)
3386 return lxc_global_config_value(key
);
3389 const char *lxc_get_version(void)
3394 static int copy_file(const char *old
, const char *new)
3401 if (file_exists(new)) {
3402 ERROR("copy destination %s exists", new);
3406 ret
= stat(old
, &sbuf
);
3408 INFO("Error stat'ing %s", old
);
3412 in
= open(old
, O_RDONLY
);
3414 SYSERROR("Error opening original file %s", old
);
3418 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3420 SYSERROR("Error opening new file %s", new);
3426 len
= read(in
, buf
, 8096);
3428 SYSERROR("Error reading old file %s", old
);
3435 ret
= write(out
, buf
, len
);
3436 if (ret
< len
) { /* should we retry? */
3437 SYSERROR("Error: write to new file %s was interrupted", new);
3445 /* We set mode, but not owner/group. */
3446 ret
= chmod(new, sbuf
.st_mode
);
3448 SYSERROR("Error setting mode on %s", new);
3460 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3463 struct lxc_list
*it
;
3466 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3467 cpath
= alloca(len
);
3468 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3469 if (ret
< 0 || ret
>= len
)
3472 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3473 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3474 char *hookname
= it
->elem
;
3475 char *fname
= strrchr(hookname
, '/');
3476 char tmppath
[MAXPATHLEN
];
3477 if (!fname
) /* relative path - we don't support, but maybe we should */
3480 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3481 /* this hook is public - ignore */
3485 /* copy the script, and change the entry in confile */
3486 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3487 c
->config_path
, c
->name
, fname
+1);
3488 if (ret
< 0 || ret
>= MAXPATHLEN
)
3491 ret
= copy_file(it
->elem
, tmppath
);
3497 it
->elem
= strdup(tmppath
);
3499 ERROR("out of memory copying hook path");
3505 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3506 c
->config_path
, oldc
->name
, c
->name
)) {
3507 ERROR("Error saving new hooks in clone");
3511 do_lxcapi_save_config(c
, NULL
);
3516 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3518 char newpath
[MAXPATHLEN
];
3519 char *oldpath
= oldc
->lxc_conf
->fstab
;
3525 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3527 char *p
= strrchr(oldpath
, '/');
3531 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3532 c
->config_path
, c
->name
, p
);
3533 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3534 ERROR("error printing new path for %s", oldpath
);
3538 if (file_exists(newpath
)) {
3539 ERROR("error: fstab file %s exists", newpath
);
3543 if (copy_file(oldpath
, newpath
) < 0) {
3544 ERROR("error: copying %s to %s", oldpath
, newpath
);
3548 free(c
->lxc_conf
->fstab
);
3550 c
->lxc_conf
->fstab
= strdup(newpath
);
3551 if (!c
->lxc_conf
->fstab
) {
3552 ERROR("error: allocating pathname");
3556 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3557 ERROR("error saving new lxctab");
3564 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3566 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3569 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3571 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3572 WARN("Error copying reverse dependencies");
3576 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3578 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3579 WARN("Error copying reverse dependencies");
3583 if (copy_file(path0
, path1
) < 0) {
3584 INFO("Error copying reverse dependencies");
3589 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3592 char path
[MAXPATHLEN
];
3596 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3598 if (ret
< 0 || ret
>= MAXPATHLEN
)
3601 f
= fopen(path
, "a");
3607 /* If anything goes wrong, just return an error. */
3608 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3618 * If the fs natively supports snapshot clones with no penalty,
3619 * then default to those even if not requested.
3620 * Currently we only do this for btrfs.
3622 bool should_default_to_snapshot(struct lxc_container
*c0
,
3623 struct lxc_container
*c1
)
3626 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3627 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3628 char *p0
= alloca(l0
+ 1);
3629 char *p1
= alloca(l1
+ 1);
3630 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3632 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3633 if (ret
< 0 || ret
>= l0
)
3636 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3637 if (ret
< 0 || ret
>= l1
)
3640 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3643 if (is_btrfs_subvol(rootfs
) <= 0)
3646 return btrfs_same_fs(p0
, p1
) == 0;
3649 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3650 const char *newtype
, int flags
, const char *bdevdata
,
3653 struct lxc_storage
*bdev
;
3656 if (should_default_to_snapshot(c0
, c
))
3657 flags
|= LXC_CLONE_SNAPSHOT
;
3659 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3660 bdevdata
, newsize
, &need_rdep
);
3662 ERROR("Error copying storage.");
3666 /* Set new rootfs. */
3667 free(c
->lxc_conf
->rootfs
.path
);
3668 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3671 if (!c
->lxc_conf
->rootfs
.path
) {
3672 ERROR("Out of memory while setting storage path.");
3676 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3677 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3678 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3679 c
->lxc_conf
->rootfs
.path
)) {
3680 ERROR("Error saving new rootfs to cloned config.");
3684 if (flags
& LXC_CLONE_SNAPSHOT
)
3685 copy_rdepends(c
, c0
);
3688 if (!add_rdepends(c
, c0
))
3689 WARN("Error adding reverse dependency from %s to %s",
3693 mod_all_rdeps(c
, true);
3698 struct clone_update_data
{
3699 struct lxc_container
*c0
;
3700 struct lxc_container
*c1
;
3705 static int clone_update_rootfs(struct clone_update_data
*data
)
3707 struct lxc_container
*c0
= data
->c0
;
3708 struct lxc_container
*c
= data
->c1
;
3709 int flags
= data
->flags
;
3710 char **hookargs
= data
->hookargs
;
3712 char path
[MAXPATHLEN
];
3713 struct lxc_storage
*bdev
;
3715 struct lxc_conf
*conf
= c
->lxc_conf
;
3717 /* update hostname in rootfs */
3718 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3720 if (setgid(0) < 0) {
3721 ERROR("Failed to setgid to 0");
3725 if (setuid(0) < 0) {
3726 ERROR("Failed to setuid to 0");
3730 if (setgroups(0, NULL
) < 0)
3731 WARN("Failed to clear groups");
3733 if (unshare(CLONE_NEWNS
) < 0)
3736 bdev
= storage_init(c
->lxc_conf
);
3740 if (strcmp(bdev
->type
, "dir") != 0) {
3741 if (unshare(CLONE_NEWNS
) < 0) {
3742 ERROR("error unsharing mounts");
3747 if (detect_shared_rootfs()) {
3748 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3749 SYSERROR("Failed to make / rslave");
3750 ERROR("Continuing...");
3754 if (bdev
->ops
->mount(bdev
) < 0) {
3758 } else { /* TODO come up with a better way */
3760 bdev
->dest
= strdup(bdev
->src
);
3763 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3764 /* Start of environment variable setup for hooks */
3765 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3766 SYSERROR("failed to set environment variable for source container name");
3768 if (setenv("LXC_NAME", c
->name
, 1))
3769 SYSERROR("failed to set environment variable for container name");
3771 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3772 SYSERROR("failed to set environment variable for config path");
3774 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3775 SYSERROR("failed to set environment variable for rootfs mount");
3777 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3778 SYSERROR("failed to set environment variable for rootfs mount");
3780 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3781 ERROR("Error executing clone hook for %s", c
->name
);
3787 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3788 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3791 if (ret
< 0 || ret
>= MAXPATHLEN
)
3794 if (!file_exists(path
))
3797 if (!(fout
= fopen(path
, "w"))) {
3798 SYSERROR("unable to open %s: ignoring", path
);
3802 if (fprintf(fout
, "%s", c
->name
) < 0) {
3807 if (fclose(fout
) < 0)
3816 static int clone_update_rootfs_wrapper(void *data
)
3818 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3819 return clone_update_rootfs(arg
);
3823 * We want to support:
3824 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3825 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3827 -s [ implies overlay]
3830 only rootfs gets converted (copied/snapshotted) on clone.
3833 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3835 char *p
= strrchr(path
, '/');
3842 ret
= do_create_container_dir(path
, conf
);
3848 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3849 const char *lxcpath
, int flags
,
3850 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3853 char newpath
[MAXPATHLEN
];
3855 struct clone_update_data data
;
3856 size_t saved_unexp_len
;
3858 int storage_copied
= 0;
3859 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3860 struct lxc_container
*c2
= NULL
;
3862 if (!c
|| !do_lxcapi_is_defined(c
))
3865 if (container_mem_lock(c
))
3868 if (!is_stopped(c
)) {
3869 ERROR("error: Original container (%s) is running", c
->name
);
3873 /* Make sure the container doesn't yet exist. */
3878 lxcpath
= do_lxcapi_get_config_path(c
);
3880 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3881 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3882 SYSERROR("clone: failed making config pathname");
3886 if (file_exists(newpath
)) {
3887 ERROR("error: clone: %s exists", newpath
);
3891 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3892 if (ret
< 0 && errno
!= EEXIST
) {
3893 ERROR("Error creating container dir for %s", newpath
);
3897 /* Copy the configuration. Tweak it as needed. */
3898 if (c
->lxc_conf
->rootfs
.path
) {
3899 origroot
= c
->lxc_conf
->rootfs
.path
;
3900 c
->lxc_conf
->rootfs
.path
= NULL
;
3903 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3904 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3906 SYSERROR("Failed to open \"%s\"", newpath
);
3910 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3911 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3912 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3913 if (!c
->lxc_conf
->unexpanded_config
) {
3918 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3919 write_config(fd
, c
->lxc_conf
);
3922 c
->lxc_conf
->rootfs
.path
= origroot
;
3924 free(c
->lxc_conf
->unexpanded_config
);
3925 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3926 saved_unexp_conf
= NULL
;
3927 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3929 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3930 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3931 SYSERROR("clone: failed making rootfs pathname");
3935 ret
= mkdir(newpath
, 0755);
3937 /* For an overlay container the rootfs is considered immutable
3938 * and will not have been removed when restoring from a
3941 if (errno
!= ENOENT
&&
3942 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3943 SYSERROR("Failed to create directory \"%s\"", newpath
);
3948 if (am_guest_unpriv()) {
3949 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3950 ERROR("Error chowning %s to container root", newpath
);
3955 c2
= lxc_container_new(newname
, lxcpath
);
3957 ERROR("clone: failed to create new container (%s %s)", newname
,
3962 /* copy/snapshot rootfs's */
3963 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3967 /* update utsname */
3968 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3969 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3970 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3972 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3973 ERROR("Error setting new hostname");
3979 ret
= copyhooks(c
, c2
);
3981 ERROR("error copying hooks");
3985 if (copy_fstab(c
, c2
) < 0) {
3986 ERROR("error copying fstab");
3990 /* update macaddrs */
3991 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3992 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3993 ERROR("Error updating mac addresses");
3998 /* Update absolute paths for overlay mount directories. */
3999 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
4002 /* We've now successfully created c2's storage, so clear it out if we
4007 if (!c2
->save_config(c2
, NULL
))
4010 if ((pid
= fork()) < 0) {
4016 ret
= wait_for_pid(pid
);
4020 container_mem_unlock(c
);
4027 data
.hookargs
= hookargs
;
4029 if (am_guest_unpriv())
4030 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
4031 &data
, "clone_update_rootfs_wrapper");
4033 ret
= clone_update_rootfs(&data
);
4035 _exit(EXIT_FAILURE
);
4037 container_mem_unlock(c
);
4038 _exit(EXIT_SUCCESS
);
4041 container_mem_unlock(c
);
4043 if (!storage_copied
)
4044 c2
->lxc_conf
->rootfs
.path
= NULL
;
4047 lxc_container_put(c2
);
4053 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
4054 const char *lxcpath
, int flags
,
4055 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
4058 struct lxc_container
* ret
;
4060 current_config
= c
? c
->lxc_conf
: NULL
;
4061 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
4062 current_config
= NULL
;
4067 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4069 struct lxc_storage
*bdev
;
4070 struct lxc_container
*newc
;
4072 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4075 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4076 ERROR("Renaming a container with snapshots is not supported");
4080 bdev
= storage_init(c
->lxc_conf
);
4082 ERROR("Failed to find original backing store type");
4086 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4089 lxc_container_put(newc
);
4093 if (newc
&& lxcapi_is_defined(newc
))
4094 lxc_container_put(newc
);
4096 if (!container_destroy(c
, NULL
)) {
4097 ERROR("Could not destroy existing container %s", c
->name
);
4104 WRAP_API_1(bool, lxcapi_rename
, const char *)
4106 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
)
4113 current_config
= c
->lxc_conf
;
4115 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4116 current_config
= NULL
;
4120 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4122 lxc_attach_command_t command
;
4129 command
.program
= (char*)program
;
4130 command
.argv
= (char**)argv
;
4132 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4138 return lxc_wait_for_pid_status(pid
);
4141 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4145 current_config
= c
? c
->lxc_conf
: NULL
;
4146 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4147 current_config
= NULL
;
4152 static int get_next_index(const char *lxcpath
, char *cname
)
4158 fname
= alloca(strlen(lxcpath
) + 20);
4161 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4163 ret
= stat(fname
, &sb
);
4171 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4176 * If the old style snapshot path exists, use it
4177 * /var/lib/lxc -> /var/lib/lxcsnaps
4179 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
4180 if (ret
< 0 || ret
>= MAXPATHLEN
)
4183 if (dir_exists(snappath
)) {
4184 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
4185 if (ret
< 0 || ret
>= MAXPATHLEN
)
4192 * Use the new style path
4193 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4195 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
4196 if (ret
< 0 || ret
>= MAXPATHLEN
)
4202 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4205 struct lxc_container
*c2
;
4206 char snappath
[MAXPATHLEN
], newname
[20];
4208 if (!c
|| !lxcapi_is_defined(c
))
4211 if (!storage_can_backup(c
->lxc_conf
)) {
4212 ERROR("%s's backing store cannot be backed up.", c
->name
);
4213 ERROR("Your container must use another backing store type.");
4217 if (!get_snappath_dir(c
, snappath
))
4220 i
= get_next_index(snappath
, c
->name
);
4222 if (mkdir_p(snappath
, 0755) < 0) {
4223 ERROR("Failed to create snapshot directory %s", snappath
);
4227 ret
= snprintf(newname
, 20, "snap%d", i
);
4228 if (ret
< 0 || ret
>= 20)
4232 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4233 * created in the original container
4235 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4236 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4237 if (storage_is_dir(c
->lxc_conf
)) {
4238 ERROR("Snapshot of directory-backed container requested.");
4239 ERROR("Making a copy-clone. If you do want snapshots, then");
4240 ERROR("please create overlay clone first, snapshot that");
4241 ERROR("and keep the original container pristine.");
4242 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4245 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4247 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
4251 lxc_container_put(c2
);
4253 /* Now write down the creation time. */
4260 tm_info
= localtime(&timer
);
4262 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
4264 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4265 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4266 f
= fopen(dfnam
, "w");
4268 ERROR("Failed to open %s", dfnam
);
4272 if (fprintf(f
, "%s", buffer
) < 0) {
4273 SYSERROR("Writing timestamp");
4280 SYSERROR("Writing timestamp");
4285 /* $p / $name / comment \0 */
4286 int len
= strlen(snappath
) + strlen(newname
) + 10;
4287 char *path
= alloca(len
);
4289 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4290 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4296 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4298 static void lxcsnap_free(struct lxc_snapshot
*s
)
4301 free(s
->comment_pathname
);
4306 static char *get_snapcomment_path(char* snappath
, char *name
)
4308 /* $snappath/$name/comment */
4309 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4310 char *s
= malloc(len
);
4313 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4314 if (ret
< 0 || ret
>= len
) {
4323 static char *get_timestamp(char* snappath
, char *name
)
4325 char path
[MAXPATHLEN
], *s
= NULL
;
4329 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4330 if (ret
< 0 || ret
>= MAXPATHLEN
)
4333 fin
= fopen(path
, "r");
4337 (void) fseek(fin
, 0, SEEK_END
);
4339 (void) fseek(fin
, 0, SEEK_SET
);
4344 if (fread(s
, 1, len
, fin
) != len
) {
4345 SYSERROR("reading timestamp");
4356 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4358 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4360 struct dirent
*direntp
;
4361 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4364 if (!c
|| !lxcapi_is_defined(c
))
4367 if (!get_snappath_dir(c
, snappath
)) {
4368 ERROR("path name too long");
4372 dir
= opendir(snappath
);
4374 INFO("Failed to open %s - assuming no snapshots", snappath
);
4378 while ((direntp
= readdir(dir
))) {
4379 if (!strcmp(direntp
->d_name
, "."))
4382 if (!strcmp(direntp
->d_name
, ".."))
4385 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4386 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4387 ERROR("pathname too long");
4391 if (!file_exists(path2
))
4394 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4396 SYSERROR("Out of memory");
4401 snaps
[count
].free
= lxcsnap_free
;
4402 snaps
[count
].name
= strdup(direntp
->d_name
);
4403 if (!snaps
[count
].name
)
4406 snaps
[count
].lxcpath
= strdup(snappath
);
4407 if (!snaps
[count
].lxcpath
) {
4408 free(snaps
[count
].name
);
4412 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4413 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4418 WARN("Failed to close directory");
4427 for (i
=0; i
<count
; i
++)
4428 lxcsnap_free(&snaps
[i
]);
4434 WARN("Failed to close directory");
4439 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4441 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4443 char clonelxcpath
[MAXPATHLEN
];
4445 struct lxc_container
*snap
, *rest
;
4446 struct lxc_storage
*bdev
;
4449 if (!c
|| !c
->name
|| !c
->config_path
)
4452 if (has_fs_snapshots(c
)) {
4453 ERROR("container rootfs has dependent snapshots");
4457 bdev
= storage_init(c
->lxc_conf
);
4459 ERROR("Failed to find original backing store type");
4463 /* For an overlay container the rootfs is considered immutable
4464 * and cannot be removed when restoring from a snapshot. We pass this
4465 * internal flag along to communicate this to various parts of the
4468 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4469 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4474 if (!get_snappath_dir(c
, clonelxcpath
)) {
4478 /* how should we lock this? */
4480 snap
= lxc_container_new(snapname
, clonelxcpath
);
4481 if (!snap
|| !lxcapi_is_defined(snap
)) {
4482 ERROR("Could not open snapshot %s", snapname
);
4485 lxc_container_put(snap
);
4491 if (!strcmp(c
->name
, newname
)) {
4492 if (!container_destroy(c
, bdev
)) {
4493 ERROR("Could not destroy existing container %s", newname
);
4494 lxc_container_put(snap
);
4500 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4501 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4503 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4504 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4506 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4509 if (rest
&& lxcapi_is_defined(rest
))
4513 lxc_container_put(rest
);
4515 lxc_container_put(snap
);
4519 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4521 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4523 struct lxc_container
*snap
= NULL
;
4526 snap
= lxc_container_new(snapname
, clonelxcpath
);
4528 ERROR("Could not find snapshot %s", snapname
);
4532 if (!do_lxcapi_destroy(snap
)) {
4533 ERROR("Could not destroy snapshot %s", snapname
);
4541 lxc_container_put(snap
);
4546 static bool remove_all_snapshots(const char *path
)
4549 struct dirent
*direntp
;
4552 dir
= opendir(path
);
4554 SYSERROR("opendir on snapshot path %s", path
);
4558 while ((direntp
= readdir(dir
))) {
4559 if (!strcmp(direntp
->d_name
, "."))
4562 if (!strcmp(direntp
->d_name
, ".."))
4565 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4574 SYSERROR("Error removing directory %s", path
);
4579 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4581 char clonelxcpath
[MAXPATHLEN
];
4583 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4586 if (!get_snappath_dir(c
, clonelxcpath
))
4589 return do_snapshot_destroy(snapname
, clonelxcpath
);
4592 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4594 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4596 char clonelxcpath
[MAXPATHLEN
];
4598 if (!c
|| !c
->name
|| !c
->config_path
)
4601 if (!get_snappath_dir(c
, clonelxcpath
))
4604 return remove_all_snapshots(clonelxcpath
);
4607 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4609 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4611 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4614 WRAP_API(bool, lxcapi_may_control
)
4616 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4622 char chrootpath
[MAXPATHLEN
];
4623 char *directory_path
= NULL
;
4627 SYSERROR("Failed to fork()");
4632 ret
= wait_for_pid(pid
);
4634 ERROR("Failed to create device node");
4641 /* prepare the path */
4642 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4643 if (ret
< 0 || ret
>= MAXPATHLEN
)
4646 ret
= chroot(chrootpath
);
4648 _exit(EXIT_FAILURE
);
4652 _exit(EXIT_FAILURE
);
4654 /* remove path if it exists */
4655 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4659 SYSERROR("Failed to remove \"%s\"", path
);
4660 _exit(EXIT_FAILURE
);
4665 _exit(EXIT_SUCCESS
);
4667 /* create any missing directories */
4670 _exit(EXIT_FAILURE
);
4672 directory_path
= dirname(tmp
);
4673 ret
= mkdir_p(directory_path
, 0755);
4674 if (ret
< 0 && errno
!= EEXIST
) {
4675 SYSERROR("Failed to create path \"%s\"", directory_path
);
4677 _exit(EXIT_FAILURE
);
4680 /* create the device node */
4681 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4684 SYSERROR("Failed to create device node at \"%s\"", path
);
4685 _exit(EXIT_FAILURE
);
4688 _exit(EXIT_SUCCESS
);
4691 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4695 char value
[LXC_MAX_BUFFER
];
4698 /* make sure container is running */
4699 if (!do_lxcapi_is_running(c
)) {
4700 ERROR("container is not running");
4704 /* use src_path if dest_path is NULL otherwise use dest_path */
4705 p
= dest_path
? dest_path
: src_path
;
4707 /* make sure we can access p */
4708 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4711 /* continue if path is character device or block device */
4712 if (S_ISCHR(st
.st_mode
))
4713 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4714 else if (S_ISBLK(st
.st_mode
))
4715 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4719 /* check snprintf return code */
4720 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4723 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4726 /* add or remove device to/from cgroup access list */
4728 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4729 ERROR("set_cgroup_item failed while adding the device node");
4733 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4734 ERROR("set_cgroup_item failed while removing the device node");
4742 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4744 // cannot mknod if we're not privileged wrt init_user_ns
4745 if (am_host_unpriv()) {
4746 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4750 return add_remove_device_node(c
, src_path
, dest_path
, true);
4753 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4755 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4757 if (am_guest_unpriv()) {
4758 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4762 return add_remove_device_node(c
, src_path
, dest_path
, false);
4765 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4767 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4769 const char *dst_ifname
)
4774 if (am_guest_unpriv()) {
4775 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4780 ERROR("No source interface name given");
4784 ret
= lxc_netdev_isup(ifname
);
4786 /* netdev of ifname is up. */
4787 ret
= lxc_netdev_down(ifname
);
4792 init_pid
= do_lxcapi_init_pid(c
);
4793 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4797 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4804 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4806 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4808 const char *dst_ifname
)
4811 pid_t pid
, pid_outside
;
4814 * TODO - if this is a physical device, then we need am_host_unpriv.
4815 * But for other types guest privilege suffices.
4817 if (am_guest_unpriv()) {
4818 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4823 ERROR("No source interface name given");
4827 pid_outside
= lxc_raw_getpid();
4830 ERROR("Failed to fork");
4834 if (pid
== 0) { /* child */
4837 init_pid
= do_lxcapi_init_pid(c
);
4838 if (!switch_to_ns(init_pid
, "net")) {
4839 ERROR("Failed to enter network namespace");
4840 _exit(EXIT_FAILURE
);
4843 ret
= lxc_netdev_isup(ifname
);
4845 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4846 _exit(EXIT_FAILURE
);
4849 /* netdev of ifname is up. */
4851 ret
= lxc_netdev_down(ifname
);
4853 ERROR("Failed to set network device \"%s\" down", ifname
);
4854 _exit(EXIT_FAILURE
);
4858 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4859 /* -EINVAL means there is no netdev named as ifname. */
4862 ERROR("Network device \"%s\" not found", ifname
);
4864 ERROR("Failed to remove network device \"%s\"", ifname
);
4866 _exit(EXIT_FAILURE
);
4869 _exit(EXIT_SUCCESS
);
4872 ret
= wait_for_pid(pid
);
4876 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4880 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4882 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4883 struct migrate_opts
*opts
, unsigned int size
)
4886 struct migrate_opts
*valid_opts
= opts
;
4887 uint64_t features_to_check
= 0;
4889 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4890 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4891 * to do anything special.
4893 if (size
> sizeof(*opts
)) {
4894 unsigned char *addr
;
4897 addr
= (void *)opts
+ sizeof(*opts
);
4898 end
= (void *)opts
+ size
;
4900 for (; addr
< end
; addr
++)
4905 /* If the caller has a smaller struct, let's zero out the end for them
4906 * so we don't accidentally use bits of it that they didn't know about
4909 if (size
< sizeof(*opts
)) {
4910 valid_opts
= malloc(sizeof(*opts
));
4914 memset(valid_opts
, 0, sizeof(*opts
));
4915 memcpy(valid_opts
, opts
, size
);
4919 case MIGRATE_PRE_DUMP
:
4920 if (!do_lxcapi_is_running(c
)) {
4921 ERROR("container is not running");
4925 ret
= !__criu_pre_dump(c
, valid_opts
);
4928 if (!do_lxcapi_is_running(c
)) {
4929 ERROR("container is not running");
4933 ret
= !__criu_dump(c
, valid_opts
);
4935 case MIGRATE_RESTORE
:
4936 if (do_lxcapi_is_running(c
)) {
4937 ERROR("container is already running");
4941 ret
= !__criu_restore(c
, valid_opts
);
4943 case MIGRATE_FEATURE_CHECK
:
4944 features_to_check
= valid_opts
->features_to_check
;
4945 ret
= !__criu_check_feature(&features_to_check
);
4947 /* Something went wrong. Let's let the caller
4948 * know which feature checks failed. */
4949 valid_opts
->features_to_check
= features_to_check
;
4953 ERROR("invalid migrate command %u", cmd
);
4958 if (size
< sizeof(*opts
))
4964 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4966 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4968 struct migrate_opts opts
;
4970 memset(&opts
, 0, sizeof(opts
));
4972 opts
.directory
= directory
;
4974 opts
.verbose
= verbose
;
4976 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4979 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4981 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4983 struct migrate_opts opts
;
4985 memset(&opts
, 0, sizeof(opts
));
4987 opts
.directory
= directory
;
4988 opts
.verbose
= verbose
;
4990 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4993 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4995 static int do_lxcapi_mount(struct lxc_container
*c
,
4996 const char *source
, const char *target
,
4997 const char *filesystemtype
, unsigned long mountflags
,
4998 const void *data
, struct lxc_mount
*mnt
) {
5000 char template[MAXPATHLEN
], path
[MAXPATHLEN
];
5001 pid_t pid
, init_pid
;
5004 int ret
= -1, fd
= -EBADF
;
5006 if (!c
|| !c
->lxc_conf
) {
5007 ERROR("Container or configuration is NULL");
5011 if (!c
->lxc_conf
->lxc_shmount
.path_host
) {
5012 ERROR("Host path to shared mountpoint must be specified in the config\n");
5015 len
= strlen(c
->lxc_conf
->lxc_shmount
.path_host
) + sizeof("/.lxcmount_XXXXXX") - 1;
5017 ret
= snprintf(template, len
+ 1, "%s/.lxcmount_XXXXXX", c
->lxc_conf
->lxc_shmount
.path_host
);
5018 if (ret
< 0 || (size_t)ret
>= len
+ 1) {
5019 SYSERROR("Error writing shmounts tempdir name");
5023 /* Create a temporary file / dir under the shared mountpoint */
5024 if (!source
|| strcmp(source
, "") == 0) {
5025 /* If source is not specified, maybe we want to mount a filesystem? */
5026 sb
.st_mode
= S_IFDIR
;
5028 ret
= stat(source
, &sb
);
5030 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5035 if ((sb
.st_mode
& S_IFMT
) == S_IFDIR
) {
5036 sret
= mkdtemp(template);
5038 SYSERROR("Could not create shmounts temporary dir");
5041 ret
= chmod(template, 0);
5043 SYSERROR("Could not chmod shmounts temporary dir \"%s\"", template);
5047 fd
= lxc_make_tmpfile(template, false);
5049 SYSERROR("Could not create shmounts temporary file");
5052 ret
= fchmod(fd
, 0);
5054 SYSERROR("Could not chmod shmounts temporary file");
5062 SYSERROR("Could not fork");
5068 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5070 SYSERROR("Failed to mount onto \"%s\"", template);
5071 _exit(EXIT_FAILURE
);
5074 init_pid
= do_lxcapi_init_pid(c
);
5076 ERROR("Failed to obtain container's init pid");
5077 _exit(EXIT_FAILURE
);
5080 /* Enter the container namespaces */
5081 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5082 if (!switch_to_ns(init_pid
, "user")){
5083 ERROR("Failed to enter user namespace");
5084 _exit(EXIT_FAILURE
);
5087 if (!switch_to_ns(init_pid
, "mnt")) {
5088 ERROR("Failed to enter mount namespace");
5089 _exit(EXIT_FAILURE
);
5092 ret
= create_mount_target(sb
.st_mode
, target
);
5094 _exit(EXIT_FAILURE
);
5096 suff
= strrchr(template, '/');
5098 _exit(EXIT_FAILURE
);
5100 len
= strlen(c
->lxc_conf
->lxc_shmount
.path_cont
) + sizeof("/.lxcmount_XXXXXX") - 1;
5101 ret
= snprintf(path
, len
+ 1, "%s%s", c
->lxc_conf
->lxc_shmount
.path_cont
, suff
);
5102 if (ret
< 0 || (size_t)ret
>= len
+ 1) {
5103 SYSERROR("Error writing container mountpoint name");
5104 _exit(EXIT_FAILURE
);
5107 ret
= mount(path
, target
, NULL
, MS_REC
| MS_MOVE
, NULL
);
5109 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5110 _exit(EXIT_FAILURE
);
5113 _exit(EXIT_SUCCESS
);
5116 ret
= wait_for_pid(pid
);
5118 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5124 (void)umount2(template, MNT_DETACH
);
5125 (void)unlink(template);
5133 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5134 unsigned long, const void *, struct lxc_mount
*)
5136 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5137 unsigned long mountflags
, struct lxc_mount
*mnt
)
5139 pid_t pid
, init_pid
;
5142 if (!c
|| !c
->lxc_conf
) {
5143 ERROR("Container or configuration is NULL");
5150 SYSERROR("Could not fork");
5155 init_pid
= do_lxcapi_init_pid(c
);
5157 ERROR("Failed to obtain container's init pid");
5158 _exit(EXIT_FAILURE
);
5161 /* Enter the container namespaces */
5162 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5163 if (!switch_to_ns(init_pid
, "user")) {
5164 ERROR("Failed to enter user namespace");
5165 _exit(EXIT_FAILURE
);
5169 if (!switch_to_ns(init_pid
, "mnt")) {
5170 ERROR("Failed to enter mount namespace");
5171 _exit(EXIT_FAILURE
);
5174 /* Do the unmount */
5175 ret
= umount2(target
, mountflags
);
5177 SYSERROR("Failed to umount \"%s\"", target
);
5178 _exit(EXIT_FAILURE
);
5181 _exit(EXIT_SUCCESS
);
5184 ret
= wait_for_pid(pid
);
5186 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5193 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5195 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5204 current_config
= c
->lxc_conf
;
5207 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5211 ERROR("Memory allocation error.");
5217 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5221 current_config
= NULL
;
5225 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5227 struct lxc_container
*c
;
5233 c
= malloc(sizeof(*c
));
5235 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5238 memset(c
, 0, sizeof(*c
));
5241 c
->config_path
= strdup(configpath
);
5243 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5244 if (!c
->config_path
) {
5245 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5249 remove_trailing_slashes(c
->config_path
);
5252 c
->name
= malloc(len
+ 1);
5254 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5257 (void)strlcpy(c
->name
, name
, len
+ 1);
5260 c
->slock
= lxc_newlock(c
->config_path
, name
);
5262 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5266 c
->privlock
= lxc_newlock(NULL
, NULL
);
5268 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5272 if (!set_config_filename(c
)) {
5273 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5277 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5278 fprintf(stderr
, "Failed to load config for %s\n", name
);
5282 if (ongoing_create(c
) == 2) {
5283 ERROR("Failed to complete container creation for %s", c
->name
);
5284 container_destroy(c
, NULL
);
5285 lxcapi_clear_config(c
);
5288 c
->daemonize
= true;
5291 /* Assign the member functions. */
5292 c
->is_defined
= lxcapi_is_defined
;
5293 c
->state
= lxcapi_state
;
5294 c
->is_running
= lxcapi_is_running
;
5295 c
->freeze
= lxcapi_freeze
;
5296 c
->unfreeze
= lxcapi_unfreeze
;
5297 c
->console
= lxcapi_console
;
5298 c
->console_getfd
= lxcapi_console_getfd
;
5299 c
->init_pid
= lxcapi_init_pid
;
5300 c
->load_config
= lxcapi_load_config
;
5301 c
->want_daemonize
= lxcapi_want_daemonize
;
5302 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5303 c
->start
= lxcapi_start
;
5304 c
->startl
= lxcapi_startl
;
5305 c
->stop
= lxcapi_stop
;
5306 c
->config_file_name
= lxcapi_config_file_name
;
5307 c
->wait
= lxcapi_wait
;
5308 c
->set_config_item
= lxcapi_set_config_item
;
5309 c
->destroy
= lxcapi_destroy
;
5310 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5311 c
->rename
= lxcapi_rename
;
5312 c
->save_config
= lxcapi_save_config
;
5313 c
->get_keys
= lxcapi_get_keys
;
5314 c
->create
= lxcapi_create
;
5315 c
->createl
= lxcapi_createl
;
5316 c
->shutdown
= lxcapi_shutdown
;
5317 c
->reboot
= lxcapi_reboot
;
5318 c
->reboot2
= lxcapi_reboot2
;
5319 c
->clear_config
= lxcapi_clear_config
;
5320 c
->clear_config_item
= lxcapi_clear_config_item
;
5321 c
->get_config_item
= lxcapi_get_config_item
;
5322 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5323 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5324 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5325 c
->get_config_path
= lxcapi_get_config_path
;
5326 c
->set_config_path
= lxcapi_set_config_path
;
5327 c
->clone
= lxcapi_clone
;
5328 c
->get_interfaces
= lxcapi_get_interfaces
;
5329 c
->get_ips
= lxcapi_get_ips
;
5330 c
->attach
= lxcapi_attach
;
5331 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5332 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5333 c
->snapshot
= lxcapi_snapshot
;
5334 c
->snapshot_list
= lxcapi_snapshot_list
;
5335 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5336 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5337 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5338 c
->may_control
= lxcapi_may_control
;
5339 c
->add_device_node
= lxcapi_add_device_node
;
5340 c
->remove_device_node
= lxcapi_remove_device_node
;
5341 c
->attach_interface
= lxcapi_attach_interface
;
5342 c
->detach_interface
= lxcapi_detach_interface
;
5343 c
->checkpoint
= lxcapi_checkpoint
;
5344 c
->restore
= lxcapi_restore
;
5345 c
->migrate
= lxcapi_migrate
;
5346 c
->console_log
= lxcapi_console_log
;
5347 c
->mount
= lxcapi_mount
;
5348 c
->umount
= lxcapi_umount
;
5353 lxc_container_free(c
);
5357 int lxc_get_wait_states(const char **states
)
5362 for (i
=0; i
<MAX_STATE
; i
++)
5363 states
[i
] = lxc_state2str(i
);
5369 * These next two could probably be done smarter with reusing a common function
5370 * with different iterators and tests...
5372 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5375 int i
, cfound
= 0, nfound
= 0;
5376 struct dirent
*direntp
;
5377 struct lxc_container
*c
;
5380 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5382 dir
= opendir(lxcpath
);
5384 SYSERROR("opendir on lxcpath");
5394 while ((direntp
= readdir(dir
))) {
5395 /* Ignore '.', '..' and any hidden directory. */
5396 if (!strncmp(direntp
->d_name
, ".", 1))
5399 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5403 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5413 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5415 INFO("Container %s:%s has a config but could not be loaded",
5416 lxcpath
, direntp
->d_name
);
5419 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5425 if (!do_lxcapi_is_defined(c
)) {
5426 INFO("Container %s:%s has a config but is not defined",
5427 lxcpath
, direntp
->d_name
);
5430 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5433 lxc_container_put(c
);
5437 if (!add_to_clist(cret
, c
, nfound
, true)) {
5438 lxc_container_put(c
);
5449 if (names
&& *names
) {
5450 for (i
=0; i
<cfound
; i
++)
5455 if (cret
&& *cret
) {
5456 for (i
=0; i
<nfound
; i
++)
5457 lxc_container_put((*cret
)[i
]);
5465 int list_active_containers(const char *lxcpath
, char ***nret
,
5466 struct lxc_container
***cret
)
5468 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5471 char **ct_name
= NULL
;
5473 struct lxc_container
*c
= NULL
;
5477 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5478 lxcpath_len
= strlen(lxcpath
);
5486 FILE *f
= fopen("/proc/net/unix", "r");
5490 while (getline(&line
, &len
, f
) != -1) {
5491 char *p
= strrchr(line
, ' '), *p2
;
5502 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5504 } else if (strncmp(p
, "lxc/", 4) == 0) {
5514 /* Now p is the start of lxc_name. */
5515 p2
= strchr(p
, '/');
5516 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5521 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5525 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5531 p
= lxc_cmd_get_name(p
);
5536 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5542 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5545 goto free_cret_list
;
5556 c
= lxc_container_new(p
, lxcpath
);
5558 INFO("Container %s:%s is running but could not be loaded",
5561 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5572 * If this is an anonymous container, then is_defined *can*
5573 * return false. So we don't do that check. Count on the
5574 * fact that the command socket exists.
5577 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5578 lxc_container_put(c
);
5579 goto free_cret_list
;
5585 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5587 lxc_container_put(c
);
5588 goto free_cret_list
;
5600 if (cret
&& *cret
) {
5601 for (i
= 0; i
< cret_cnt
; i
++)
5602 lxc_container_put((*cret
)[i
]);
5608 for (i
= 0; i
< ct_name_cnt
; i
++)
5619 int list_all_containers(const char *lxcpath
, char ***nret
,
5620 struct lxc_container
***cret
)
5622 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5625 struct lxc_container
**ct_list
= NULL
;
5627 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5631 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5632 if (active_cnt
< 0) {
5637 for (i
= 0; i
< active_cnt
; i
++) {
5638 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5639 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5641 goto free_active_name
;
5647 free(active_name
[i
]);
5648 active_name
[i
] = NULL
;
5655 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5656 struct lxc_container
*c
;
5658 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5660 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5661 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5665 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5666 lxc_container_put(c
);
5687 for (i
= 0; i
< ct_list_cnt
; i
++) {
5688 lxc_container_put(ct_list
[i
]);
5693 for (i
= 0; i
< active_cnt
; i
++) {
5694 free(active_name
[i
]);
5699 for (i
= 0; i
< ct_cnt
; i
++) {
5706 bool lxc_config_item_is_supported(const char *key
)
5708 return !!lxc_get_config(key
);