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
24 #include <arpa/inet.h>
38 #include <sys/mount.h>
40 #include <sys/syscall.h>
41 #include <sys/sysmacros.h>
42 #include <sys/types.h>
46 #include "../include/netns_ifaddrs.h"
48 #include "api_extensions.h"
52 #include "commands_utils.h"
56 #include "confile_utils.h"
59 #include "initutils.h"
62 #include "lxccontainer.h"
65 #include "namespace.h"
68 #include "raw_syscalls.h"
72 #include "storage/btrfs.h"
73 #include "storage/overlay.h"
74 #include "storage_utils.h"
76 #include "syscall_wrappers.h"
83 #include <sys/mkdev.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 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
167 lk
.l_whence
= SEEK_SET
;
168 /* F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
173 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
174 if (ret
< 0 && errno
== EINVAL
) {
175 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
176 if (ret
< 0 && errno
== EWOULDBLOCK
)
182 /* F_OFD_GETLK will not send us back a pid so don't check it. */
184 /* Create is still ongoing. */
187 /* Create completed but partial is still there. */
191 static int create_partial(struct lxc_container
*c
)
196 struct flock lk
= {0};
198 /* $lxcpath + '/' + $name + '/partial' + \0 */
199 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
201 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
202 if (ret
< 0 || (size_t)ret
>= len
)
205 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
210 lk
.l_whence
= SEEK_SET
;
212 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
214 if (errno
== EINVAL
) {
215 ret
= flock(fd
, LOCK_EX
);
220 SYSERROR("Failed to lock partial file %s", path
);
228 static void remove_partial(struct lxc_container
*c
, int fd
)
236 /* $lxcpath + '/' + $name + '/partial' + \0 */
237 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
239 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
240 if (ret
< 0 || (size_t)ret
>= len
)
245 SYSERROR("Failed to remove partial file %s", path
);
249 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
250 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
251 * container configuration file.
252 * The container_disk_lock also takes the container_mem_lock.
253 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
254 * NOTHING mutexes two independent programs with their own struct
255 * lxc_container for the same c->name, between API calls. For instance,
256 * c->config_read(); c->start(); Between those calls, data on disk
257 * could change (which shouldn't bother the caller unless for instance
258 * the rootfs get moved). c->config_read(); update; c->config_write();
259 * Two such updaters could race. The callers should therefore check their
260 * results. Trying to prevent that would necessarily expose us to deadlocks
261 * due to hung callers. So I prefer to keep the locks only within our own
262 * functions, not across functions.
264 * If you're going to clone while holding a lxccontainer, increment
265 * c->numthreads (under privlock) before forking. When deleting,
266 * decrement numthreads under privlock, then if it hits 0 you can delete.
267 * Do not ever use a lxccontainer whose numthreads you did not bump.
269 static void lxc_container_free(struct lxc_container
*c
)
275 c
->configfile
= NULL
;
277 free(c
->error_string
);
278 c
->error_string
= NULL
;
281 lxc_putlock(c
->slock
);
286 lxc_putlock(c
->privlock
);
294 lxc_conf_free(c
->lxc_conf
);
298 free(c
->config_path
);
299 c
->config_path
= NULL
;
304 /* Consider the following case:
306 * |====================================================================|
307 * | freer | racing get()er |
308 * |====================================================================|
309 * | lxc_container_put() | lxc_container_get() |
310 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
311 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
312 * | \ lxcunlock() | \ |
313 * | \ lxc_container_free() | \ lxclock() returns |
314 * | | \ c->numthreads < 1 -> return 0 |
315 * | \ \ (free stuff) | |
316 * | \ \ sem_destroy(privlock) | |
317 * |_______________________________|____________________________________|
319 * When the get()er checks numthreads the first time, one of the following
321 * 1. freer has set numthreads = 0. get() returns 0
322 * 2. freer is between lxclock and setting numthreads to 0. get()er will
323 * sem_wait on privlock, get lxclock after freer() drops it, then see
324 * numthreads is 0 and exit without touching lxclock again..
325 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
326 * will see --numthreads = 1 and not call lxc_container_free().
329 int lxc_container_get(struct lxc_container
*c
)
334 /* If someone else has already started freeing the container, don't try
335 * to take the lock, which may be invalid.
337 if (c
->numthreads
< 1)
340 if (container_mem_lock(c
))
343 /* Bail without trying to unlock, bc the privlock is now probably in
346 if (c
->numthreads
< 1)
350 container_mem_unlock(c
);
355 int lxc_container_put(struct lxc_container
*c
)
360 if (container_mem_lock(c
))
365 if (c
->numthreads
< 1) {
366 container_mem_unlock(c
);
367 lxc_container_free(c
);
371 container_mem_unlock(c
);
375 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
384 if (container_mem_lock(c
))
390 statret
= stat(c
->configfile
, &statbuf
);
397 container_mem_unlock(c
);
401 #define WRAP_API(rettype, fnname) \
402 static rettype fnname(struct lxc_container *c) \
405 bool reset_config = false; \
407 if (!current_config && c && c->lxc_conf) { \
408 current_config = c->lxc_conf; \
409 reset_config = true; \
412 ret = do_##fnname(c); \
414 current_config = NULL; \
419 #define WRAP_API_1(rettype, fnname, t1) \
420 static rettype fnname(struct lxc_container *c, t1 a1) \
423 bool reset_config = false; \
425 if (!current_config && c && c->lxc_conf) { \
426 current_config = c->lxc_conf; \
427 reset_config = true; \
430 ret = do_##fnname(c, a1); \
432 current_config = NULL; \
437 #define WRAP_API_2(rettype, fnname, t1, t2) \
438 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
441 bool reset_config = false; \
443 if (!current_config && c && c->lxc_conf) { \
444 current_config = c->lxc_conf; \
445 reset_config = true; \
448 ret = do_##fnname(c, a1, a2); \
450 current_config = NULL; \
455 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
456 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
459 bool reset_config = false; \
461 if (!current_config && c && c->lxc_conf) { \
462 current_config = c->lxc_conf; \
463 reset_config = true; \
466 ret = do_##fnname(c, a1, a2, a3); \
468 current_config = NULL; \
473 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
474 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
475 t4 a4, t5 a5, t6 a6) \
478 bool reset_config = false; \
480 if (!current_config && c && c->lxc_conf) { \
481 current_config = c->lxc_conf; \
482 reset_config = true; \
485 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
487 current_config = NULL; \
492 WRAP_API(bool, lxcapi_is_defined
)
494 static const char *do_lxcapi_state(struct lxc_container
*c
)
501 s
= lxc_getstate(c
->name
, c
->config_path
);
502 return lxc_state2str(s
);
505 WRAP_API(const char *, lxcapi_state
)
507 static bool is_stopped(struct lxc_container
*c
)
511 s
= lxc_getstate(c
->name
, c
->config_path
);
512 return (s
== STOPPED
);
515 static bool do_lxcapi_is_running(struct lxc_container
*c
)
520 return !is_stopped(c
);
523 WRAP_API(bool, lxcapi_is_running
)
525 static bool do_lxcapi_freeze(struct lxc_container
*c
)
532 ret
= lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
);
539 WRAP_API(bool, lxcapi_freeze
)
541 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
548 ret
= lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
);
555 WRAP_API(bool, lxcapi_unfreeze
)
557 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
562 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
565 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
567 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
568 int stdoutfd
, int stderrfd
, int escape
)
575 current_config
= c
->lxc_conf
;
576 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
577 current_config
= NULL
;
582 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
589 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
592 NOTICE("The console log is empty");
593 else if (ret
== -EFAULT
)
594 NOTICE("The container does not keep a console log");
595 else if (ret
== -ENOENT
)
596 NOTICE("The container does not keep a console log file");
597 else if (ret
== -EIO
)
598 NOTICE("Failed to write console log to log file");
600 ERROR("Failed to retrieve console log");
606 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
608 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
613 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
616 WRAP_API(pid_t
, lxcapi_init_pid
)
618 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
621 c
->lxc_conf
= lxc_conf_init();
626 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
629 c
->lxc_conf
->name
= c
->name
;
633 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
637 bool need_disklock
= false, ret
= false;
642 fname
= c
->configfile
;
650 /* If we're reading something other than the container's config, we only
651 * need to lock the in-memory container. If loading the container's
652 * config file, take the disk lock.
654 if (strcmp(fname
, c
->configfile
) == 0)
655 need_disklock
= true;
658 lret
= container_disk_lock(c
);
660 lret
= container_mem_lock(c
);
664 ret
= load_config_locked(c
, fname
);
667 container_disk_unlock(c
);
669 container_mem_unlock(c
);
674 WRAP_API_1(bool, lxcapi_load_config
, const char *)
676 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
678 if (!c
|| !c
->lxc_conf
)
681 if (container_mem_lock(c
))
684 c
->daemonize
= state
;
686 container_mem_unlock(c
);
691 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
693 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
695 if (!c
|| !c
->lxc_conf
)
698 if (container_mem_lock(c
))
701 c
->lxc_conf
->close_all_fds
= state
;
703 container_mem_unlock(c
);
708 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
710 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
718 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
722 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
724 static bool am_single_threaded(void)
727 struct dirent
*direntp
;
730 dir
= opendir("/proc/self/task");
734 while ((direntp
= readdir(dir
))) {
735 if (strcmp(direntp
->d_name
, ".") == 0)
738 if (strcmp(direntp
->d_name
, "..") == 0)
750 static void push_arg(char ***argp
, char *arg
, int *nargs
)
755 copy
= must_copy_string(arg
);
758 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
767 static char **split_init_cmd(const char *incmd
)
777 len
= strlen(incmd
) + 1;
779 retlen
= strlcpy(copy
, incmd
, len
);
784 argv
= malloc(sizeof(char *));
788 lxc_iterate_parts(p
, copy
, " ")
789 push_arg(&argv
, p
, &nargs
);
799 static void free_init_cmd(char **argv
)
812 static int lxc_rcv_status(int state_socket
)
818 /* Receive container state. */
819 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
824 TRACE("Caught EINTR; retrying");
831 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
835 /* Close write end of the socket pair. */
836 close(handler
->state_socket_pair
[1]);
837 handler
->state_socket_pair
[1] = -1;
839 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
841 /* Close read end of the socket pair. */
842 close(handler
->state_socket_pair
[0]);
843 handler
->state_socket_pair
[0] = -1;
845 /* The first child is going to fork() again and then exits. So we reap
846 * the first child here.
848 ret
= wait_for_pid(pid
);
850 DEBUG("Failed waiting on first child %d", pid
);
852 DEBUG("First child %d exited", pid
);
855 SYSERROR("Failed to receive the container state");
859 /* If we receive anything else then running we know that the container
862 if (state
!= RUNNING
) {
863 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
864 lxc_state2str(state
));
868 TRACE("Container is in \"RUNNING\" state");
872 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
875 struct lxc_handler
*handler
;
876 struct lxc_conf
*conf
;
877 char *default_args
[] = {
881 char **init_cmd
= NULL
;
882 int keepfds
[3] = {-1, -1, -1};
884 /* container does exist */
888 /* If anything fails before we set error_num, we want an error in there.
892 /* Container has not been setup. */
896 ret
= ongoing_create(c
);
898 ERROR("Failed checking for incomplete container creation");
900 } else if (ret
== 1) {
901 ERROR("Ongoing container creation detected");
903 } else if (ret
== 2) {
904 ERROR("Failed to create container");
905 do_lxcapi_destroy(c
);
909 if (container_mem_lock(c
))
914 /* initialize handler */
915 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
917 container_mem_unlock(c
);
922 if (useinit
&& conf
->execute_cmd
)
923 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
925 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
928 /* ... otherwise use default_args. */
931 ERROR("No valid init detected");
932 lxc_free_handler(handler
);
938 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
939 * here to protect the on disk container? We don't want to exclude
940 * things like lxc_info while the container is running.
949 free_init_cmd(init_cmd
);
950 lxc_free_handler(handler
);
956 /* Set to NULL because we don't want father unlink
957 * the PID file, child will do the free and unlink.
961 /* Wait for container to tell us whether it started
964 started
= wait_on_daemonized_start(handler
, pid
);
966 free_init_cmd(init_cmd
);
967 lxc_free_handler(handler
);
973 /* We don't really care if this doesn't print all the
974 * characters. All that it means is that the proctitle will be
975 * ugly. Similarly, we also don't care if setproctitle() fails.
977 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
979 ret
= setproctitle(title
);
981 INFO("Failed to set process title to %s", title
);
983 INFO("Set process title to %s", title
);
986 /* We fork() a second time to be reparented to init. Like
987 * POSIX's daemon() function we change to "/" and redirect
988 * std{in,out,err} to /dev/null.
992 SYSERROR("Failed to fork first child process");
998 free_init_cmd(init_cmd
);
999 lxc_free_handler(handler
);
1000 _exit(EXIT_SUCCESS
);
1005 /* change to / directory */
1008 SYSERROR("Failed to change to \"/\" directory");
1009 _exit(EXIT_FAILURE
);
1012 keepfds
[0] = handler
->conf
->maincmd_fd
;
1013 keepfds
[1] = handler
->state_socket_pair
[0];
1014 keepfds
[2] = handler
->state_socket_pair
[1];
1015 ret
= lxc_check_inherited(conf
, true, keepfds
,
1016 sizeof(keepfds
) / sizeof(keepfds
[0]));
1018 _exit(EXIT_FAILURE
);
1020 /* redirect std{in,out,err} to /dev/null */
1021 ret
= null_stdfds();
1023 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1024 _exit(EXIT_FAILURE
);
1027 /* become session leader */
1030 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1031 } else if (!am_single_threaded()) {
1032 ERROR("Cannot start non-daemonized container when threaded");
1033 free_init_cmd(init_cmd
);
1034 lxc_free_handler(handler
);
1038 /* We need to write PID file after daemonize, so we always write the
1043 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1045 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1046 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1047 free_init_cmd(init_cmd
);
1048 lxc_free_handler(handler
);
1050 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1053 _exit(EXIT_FAILURE
);
1058 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1060 free_init_cmd(init_cmd
);
1061 lxc_free_handler(handler
);
1063 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1066 _exit(EXIT_FAILURE
);
1072 conf
->reboot
= REBOOT_NONE
;
1074 /* Unshare the mount namespace if requested */
1075 if (conf
->monitor_unshare
) {
1076 ret
= unshare(CLONE_NEWNS
);
1078 SYSERROR("Failed to unshare mount namespace");
1079 lxc_free_handler(handler
);
1084 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1086 SYSERROR("Failed to make / rslave at startup");
1087 lxc_free_handler(handler
);
1094 if (conf
->reboot
== REBOOT_INIT
) {
1095 /* initialize handler */
1096 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1103 keepfds
[0] = handler
->conf
->maincmd_fd
;
1104 keepfds
[1] = handler
->state_socket_pair
[0];
1105 keepfds
[2] = handler
->state_socket_pair
[1];
1106 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1107 sizeof(keepfds
) / sizeof(keepfds
[0]));
1109 lxc_free_handler(handler
);
1115 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1116 c
->daemonize
, &c
->error_num
);
1118 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1119 c
->daemonize
, &c
->error_num
);
1121 if (conf
->reboot
== REBOOT_REQ
) {
1122 INFO("Container requested reboot");
1123 conf
->reboot
= REBOOT_INIT
;
1133 free_init_cmd(init_cmd
);
1135 if (c
->daemonize
&& ret
!= 0)
1136 _exit(EXIT_FAILURE
);
1137 else if (c
->daemonize
)
1138 _exit(EXIT_SUCCESS
);
1146 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1151 current_config
= c
? c
->lxc_conf
: NULL
;
1152 ret
= do_lxcapi_start(c
, useinit
, argv
);
1153 current_config
= NULL
;
1158 /* Note, there MUST be an ending NULL. */
1159 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1162 char **inargs
= NULL
;
1165 /* container exists */
1169 current_config
= c
->lxc_conf
;
1171 va_start(ap
, useinit
);
1172 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1177 /* pass NULL if no arguments were supplied */
1178 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1184 for (arg
= inargs
; *arg
; arg
++)
1189 current_config
= NULL
;
1194 static bool do_lxcapi_stop(struct lxc_container
*c
)
1201 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1206 WRAP_API(bool, lxcapi_stop
)
1208 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1215 mode_t mask
= umask(0002);
1216 ret
= mkdir(path
, 0770);
1221 if (errno
!= EEXIST
)
1228 p
= alloca(len
+ 1);
1229 (void)strlcpy(p
, path
, len
+ 1);
1231 if (!lxc_list_empty(&conf
->id_map
)) {
1232 ret
= chown_mapped_root(p
, conf
);
1240 /* Create the standard expected container dir. */
1241 static bool create_container_dir(struct lxc_container
*c
)
1247 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1252 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1253 if (ret
< 0 || (size_t)ret
>= len
) {
1258 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1264 /* do_storage_create: thin wrapper around storage_create(). Like
1265 * storage_create(), it returns a mounted bdev on success, NULL on error.
1267 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1269 struct bdev_specs
*specs
)
1274 struct lxc_storage
*bdev
;
1276 /* rootfs.path or lxcpath/lxcname/rootfs */
1277 if (c
->lxc_conf
->rootfs
.path
&&
1278 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1279 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1280 len
= strlen(rpath
) + 1;
1282 ret
= snprintf(dest
, len
, "%s", rpath
);
1284 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1285 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1287 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1289 if (ret
< 0 || (size_t)ret
>= len
)
1292 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1294 ERROR("Failed to create \"%s\" storage", type
);
1298 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1299 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1303 /* If we are not root, chown the rootfs dir to root in the target user
1307 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1308 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1310 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1311 suggest_default_idmap();
1320 static char *lxcbasename(char *path
)
1324 p
= path
+ strlen(path
) - 1;
1325 while (*p
!= '/' && p
> path
)
1331 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1332 bool need_null_stdfds
, char *const argv
[])
1342 SYSERROR("Failed to fork task for container creation template");
1346 if (pid
== 0) { /* child */
1348 char *namearg
, *patharg
, *rootfsarg
;
1351 struct lxc_storage
*bdev
= NULL
;
1352 struct lxc_conf
*conf
= c
->lxc_conf
;
1355 if (need_null_stdfds
) {
1356 ret
= null_stdfds();
1358 _exit(EXIT_FAILURE
);
1361 bdev
= storage_init(c
->lxc_conf
);
1363 ERROR("Failed to initialize storage");
1364 _exit(EXIT_FAILURE
);
1369 ret
= unshare(CLONE_NEWNS
);
1371 ERROR("Failed to unshare CLONE_NEWNS");
1372 _exit(EXIT_FAILURE
);
1375 ret
= detect_shared_rootfs();
1377 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1379 SYSERROR("Failed to make \"/\" rslave");
1380 ERROR("Continuing...");
1385 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1387 ERROR("Unprivileged users can only create "
1388 "btrfs and directory-backed containers");
1389 _exit(EXIT_FAILURE
);
1392 if (strcmp(bdev
->type
, "overlay") == 0 ||
1393 strcmp(bdev
->type
, "overlayfs") == 0) {
1394 /* If we create an overlay container we need to
1395 * rsync the contents into
1396 * <container-path>/<container-name>/rootfs.
1397 * However, the overlay mount function will
1399 * <container-path>/<container-name>/delta0
1401 * <container-path>/<container-name>/rootfs
1402 * which means we would rsync the rootfs into
1403 * the delta directory. That doesn't make sense
1404 * since the delta directory only exists to
1405 * record the differences to
1406 * <container-path>/<container-name>/rootfs. So
1407 * let's simply bind-mount here and then rsync
1409 * <container-path>/<container-name>/rootfs.
1413 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1415 ERROR("Failed to get rootfs");
1416 _exit(EXIT_FAILURE
);
1419 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1421 ERROR("Failed to mount rootfs");
1422 _exit(EXIT_FAILURE
);
1425 ret
= bdev
->ops
->mount(bdev
);
1427 ERROR("Failed to mount rootfs");
1428 _exit(EXIT_FAILURE
);
1431 } else { /* TODO come up with a better way here! */
1434 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1435 bdev
->dest
= strdup(src
);
1438 /* Create our new array, pre-pend the template name and base
1442 for (nargs
= 0; argv
[nargs
]; nargs
++)
1445 /* template, path, rootfs and name args */
1448 newargv
= malloc(nargs
* sizeof(*newargv
));
1450 _exit(EXIT_FAILURE
);
1451 newargv
[0] = lxcbasename(tpath
);
1454 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1455 patharg
= malloc(len
);
1457 _exit(EXIT_FAILURE
);
1459 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1460 if (ret
< 0 || ret
>= len
)
1461 _exit(EXIT_FAILURE
);
1462 newargv
[1] = patharg
;
1465 len
= strlen("--name=") + strlen(c
->name
) + 1;
1466 namearg
= malloc(len
);
1468 _exit(EXIT_FAILURE
);
1470 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1471 if (ret
< 0 || ret
>= len
)
1472 _exit(EXIT_FAILURE
);
1473 newargv
[2] = namearg
;
1476 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1477 rootfsarg
= malloc(len
);
1479 _exit(EXIT_FAILURE
);
1481 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1482 if (ret
< 0 || ret
>= len
)
1483 _exit(EXIT_FAILURE
);
1484 newargv
[3] = rootfsarg
;
1486 /* add passed-in args */
1488 for (i
= 4; i
< nargs
; i
++)
1489 newargv
[i
] = argv
[i
- 4];
1491 /* add trailing NULL */
1493 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1495 _exit(EXIT_FAILURE
);
1496 newargv
[nargs
- 1] = NULL
;
1498 /* If we're running the template in a mapped userns, then we
1499 * prepend the template command with: lxc-usernsexec <-m map1>
1500 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1501 * the mapped uid for our geteuid()
1503 if (!lxc_list_empty(&conf
->id_map
)) {
1504 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1506 char txtuid
[20], txtgid
[20];
1507 struct lxc_list
*it
;
1511 n2
= malloc(n2args
* sizeof(*n2
));
1513 _exit(EXIT_FAILURE
);
1516 tpath
= "lxc-usernsexec";
1517 n2
[0] = "lxc-usernsexec";
1519 lxc_list_for_each(it
, &conf
->id_map
) {
1522 n2
= realloc(n2
, n2args
* sizeof(char *));
1524 _exit(EXIT_FAILURE
);
1526 n2
[n2args
- 2] = "-m";
1527 n2
[n2args
- 1] = malloc(200);
1528 if (!n2
[n2args
- 1])
1529 _exit(EXIT_FAILURE
);
1531 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1532 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1533 map
->nsid
, map
->hostid
, map
->range
);
1534 if (ret
< 0 || ret
>= 200)
1535 _exit(EXIT_FAILURE
);
1538 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1539 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1541 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1543 _exit(EXIT_FAILURE
);
1545 if (hostuid_mapped
< 0) {
1546 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1547 n2
[n2args
++] = "-m";
1548 if (hostuid_mapped
< 0) {
1549 ERROR("Failed to find free uid to map");
1550 _exit(EXIT_FAILURE
);
1553 n2
[n2args
++] = malloc(200);
1554 if (!n2
[n2args
- 1]) {
1555 SYSERROR("out of memory");
1556 _exit(EXIT_FAILURE
);
1559 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1560 hostuid_mapped
, geteuid());
1561 if (ret
< 0 || ret
>= 200)
1562 _exit(EXIT_FAILURE
);
1565 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1566 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1568 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1570 _exit(EXIT_FAILURE
);
1572 if (hostgid_mapped
< 0) {
1573 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1574 n2
[n2args
++] = "-m";
1575 if (hostgid_mapped
< 0) {
1576 ERROR("Failed to find free gid to map");
1577 _exit(EXIT_FAILURE
);
1580 n2
[n2args
++] = malloc(200);
1581 if (!n2
[n2args
- 1]) {
1582 SYSERROR("out of memory");
1583 _exit(EXIT_FAILURE
);
1586 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1587 hostgid_mapped
, getegid());
1588 if (ret
< 0 || ret
>= 200)
1589 _exit(EXIT_FAILURE
);
1592 n2
[n2args
++] = "--";
1594 for (i
= 0; i
< nargs
; i
++)
1595 n2
[i
+ n2args
] = newargv
[i
];
1598 /* Finally add "--mapped-uid $uid" to tell template what
1599 * to chown cached images to.
1602 n2
= realloc(n2
, n2args
* sizeof(char *));
1604 _exit(EXIT_FAILURE
);
1606 /* note n2[n2args-1] is NULL */
1607 n2
[n2args
- 5] = "--mapped-uid";
1609 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1610 if (ret
< 0 || ret
>= 20) {
1613 _exit(EXIT_FAILURE
);
1616 n2
[n2args
- 4] = txtuid
;
1617 n2
[n2args
- 3] = "--mapped-gid";
1619 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1620 if (ret
< 0 || ret
>= 20) {
1623 _exit(EXIT_FAILURE
);
1626 n2
[n2args
- 2] = txtgid
;
1627 n2
[n2args
- 1] = NULL
;
1632 execvp(tpath
, newargv
);
1633 SYSERROR("Failed to execute template %s", tpath
);
1634 _exit(EXIT_FAILURE
);
1637 ret
= wait_for_pid(pid
);
1639 ERROR("Failed to create container from template");
1646 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1655 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1659 f
= fopen(path
, "r");
1663 ret
= fseek(f
, 0, SEEK_END
);
1672 ret
= fseek(f
, 0, SEEK_SET
);
1676 ret
= fseek(f
, 0, SEEK_SET
);
1681 contents
= malloc(flen
+ 1);
1685 len
= fread(contents
, 1, flen
, f
);
1687 goto out_free_contents
;
1689 contents
[flen
] = '\0';
1694 goto out_free_contents
;
1697 tpath
= get_template_path(t
);
1699 ERROR("Invalid template \"%s\" specified", t
);
1700 goto out_free_contents
;
1703 ret
= sha1sum_file(tpath
, md_value
);
1705 ERROR("Failed to get sha1sum of %s", tpath
);
1707 goto out_free_contents
;
1712 f
= fopen(path
, "w");
1714 SYSERROR("Reopening config for writing");
1719 fprintf(f
, "# Template used to create this container: %s\n", t
);
1721 fprintf(f
, "# Parameters passed to the template:");
1723 fprintf(f
, " %s", *argv
);
1730 fprintf(f
, "# Template script checksum (SHA-1): ");
1731 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1732 fprintf(f
, "%02x", md_value
[i
]);
1735 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1736 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1737 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1738 fprintf(f
, "# (Be aware this has security implications)\n\n");
1739 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1740 SYSERROR("Writing original contents");
1760 SYSERROR("Error prepending header");
1767 static void lxcapi_clear_config(struct lxc_container
*c
)
1769 if (!c
|| !c
->lxc_conf
)
1772 lxc_conf_free(c
->lxc_conf
);
1776 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1780 * create a container with the given parameters.
1781 * @c: container to be created. It has the lxcpath, name, and a starting
1782 * configuration already set
1783 * @t: the template to execute to instantiate the root filesystem and
1784 * adjust the configuration.
1785 * @bdevtype: backing store type to use. If NULL, dir will be used.
1786 * @specs: additional parameters for the backing store, i.e. LVM vg to
1789 * @argv: the arguments to pass to the template, terminated by NULL. If no
1790 * arguments, you can just pass NULL.
1792 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1793 const char *bdevtype
, struct bdev_specs
*specs
,
1794 int flags
, char *const argv
[])
1806 tpath
= get_template_path(t
);
1808 ERROR("Unknown template \"%s\"", t
);
1813 /* If a template is passed in, and the rootfs already is defined in the
1814 * container config and exists, then the caller is trying to create an
1815 * existing container. Return an error, but do NOT delete the container.
1817 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1818 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1819 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1825 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1826 ERROR("Error loading default configuration file %s",
1827 lxc_global_config_value("lxc.default_config"));
1832 if (!create_container_dir(c
))
1835 /* If both template and rootfs.path are set, template is setup as
1836 * rootfs.path. The container is already created if we have a config and
1837 * rootfs.path is accessible
1839 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1840 /* No template passed in and rootfs does not exist. */
1841 if (!c
->save_config(c
, NULL
)) {
1842 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1849 /* Rootfs passed into configuration, but does not exist. */
1850 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1853 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1854 /* Rootfs already existed, user just wanted to save the loaded
1857 if (!c
->save_config(c
, NULL
))
1858 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1864 /* Mark that this container is being created */
1865 partial_fd
= create_partial(c
);
1869 /* No need to get disk lock bc we have the partial lock. */
1873 /* Create the storage.
1874 * Note we can't do this in the same task as we use to execute the
1875 * template because of the way zfs works.
1876 * After you 'zfs create', zfs mounts the fs only in the initial
1881 SYSERROR("Failed to fork task for container creation template");
1885 if (pid
== 0) { /* child */
1886 struct lxc_storage
*bdev
= NULL
;
1888 bdev
= do_storage_create(c
, bdevtype
, specs
);
1890 ERROR("Failed to create %s storage for %s",
1891 bdevtype
? bdevtype
: "(none)", c
->name
);
1892 _exit(EXIT_FAILURE
);
1895 /* Save config file again to store the new rootfs location. */
1896 if (!do_lxcapi_save_config(c
, NULL
)) {
1897 ERROR("Failed to save initial config for %s", c
->name
);
1898 /* Parent task won't see the storage driver in the
1899 * config so we delete it.
1901 bdev
->ops
->umount(bdev
);
1902 bdev
->ops
->destroy(bdev
);
1903 _exit(EXIT_FAILURE
);
1906 _exit(EXIT_SUCCESS
);
1909 if (wait_for_pid(pid
) != 0)
1912 /* Reload config to get the rootfs. */
1913 lxc_conf_free(c
->lxc_conf
);
1916 if (!load_config_locked(c
, c
->configfile
))
1919 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1922 /* Now clear out the lxc_conf we have, reload from the created
1925 do_lxcapi_clear_config(c
);
1928 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1929 ERROR("Failed to prepend header to config file");
1934 ret
= load_config_locked(c
, c
->configfile
);
1938 remove_partial(c
, partial_fd
);
1942 container_destroy(c
, NULL
);
1949 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1950 const char *bdevtype
, struct bdev_specs
*specs
,
1951 int flags
, char *const argv
[])
1955 current_config
= c
? c
->lxc_conf
: NULL
;
1957 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1958 current_config
= NULL
;
1962 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1966 int rebootsignal
= SIGINT
;
1971 if (!do_lxcapi_is_running(c
))
1974 pid
= do_lxcapi_init_pid(c
);
1978 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1979 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1981 ret
= kill(pid
, rebootsignal
);
1983 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
1990 WRAP_API(bool, lxcapi_reboot
)
1992 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1996 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1997 lxc_state_t states
[MAX_STATE
] = {0};
2002 if (!do_lxcapi_is_running(c
))
2005 pid
= do_lxcapi_init_pid(c
);
2009 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2010 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2012 /* Add a new state client before sending the shutdown signal so that we
2013 * don't miss a state.
2016 states
[RUNNING
] = 2;
2017 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2022 if (state_client_fd
< 0)
2028 if (ret
< MAX_STATE
)
2032 /* Send reboot signal to container. */
2033 killret
= kill(pid
, rebootsignal
);
2035 if (state_client_fd
>= 0)
2036 close(state_client_fd
);
2038 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2041 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2046 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2047 close(state_client_fd
);
2051 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2058 WRAP_API_1(bool, lxcapi_reboot2
, int)
2060 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2064 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2065 lxc_state_t states
[MAX_STATE
] = {0};
2070 if (!do_lxcapi_is_running(c
))
2073 pid
= do_lxcapi_init_pid(c
);
2077 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2078 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2079 haltsignal
= c
->lxc_conf
->haltsignal
;
2080 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2081 haltsignal
= (SIGRTMIN
+ 3);
2083 /* Add a new state client before sending the shutdown signal so that we
2084 * don't miss a state.
2087 states
[STOPPED
] = 1;
2088 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2093 if (state_client_fd
< 0)
2099 if (ret
< MAX_STATE
)
2103 /* Send shutdown signal to container. */
2104 killret
= kill(pid
, haltsignal
);
2106 if (state_client_fd
>= 0)
2107 close(state_client_fd
);
2109 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2112 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2117 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2118 close(state_client_fd
);
2122 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2129 WRAP_API_1(bool, lxcapi_shutdown
, int)
2131 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2132 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2141 current_config
= c
->lxc_conf
;
2144 * since we're going to wait for create to finish, I don't think we
2145 * need to get a copy of the arguments.
2147 va_start(ap
, flags
);
2148 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2151 ERROR("Failed to allocate memory");
2155 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2159 current_config
= NULL
;
2163 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2165 if (!strcmp(key
, "lxc.cgroup"))
2166 return clear_unexp_config_line(conf
, key
, true);
2168 if (!strcmp(key
, "lxc.network"))
2169 return clear_unexp_config_line(conf
, key
, true);
2171 if (!strcmp(key
, "lxc.net"))
2172 return clear_unexp_config_line(conf
, key
, true);
2174 /* Clear a network with a specific index. */
2175 if (!strncmp(key
, "lxc.net.", 8)) {
2180 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2182 return clear_unexp_config_line(conf
, key
, true);
2185 if (!strcmp(key
, "lxc.hook"))
2186 return clear_unexp_config_line(conf
, key
, true);
2188 return clear_unexp_config_line(conf
, key
, false);
2191 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2195 struct lxc_config_t
*config
;
2197 if (!c
|| !c
->lxc_conf
)
2200 if (container_mem_lock(c
))
2203 config
= lxc_get_config(key
);
2204 /* Verify that the config key exists and that it has a callback
2207 if (config
&& config
->clr
)
2208 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2211 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2213 container_mem_unlock(c
);
2217 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2219 static inline bool enter_net_ns(struct lxc_container
*c
)
2221 pid_t pid
= do_lxcapi_init_pid(c
);
2223 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2224 (access("/proc/self/ns/user", F_OK
) == 0))
2225 if (!switch_to_ns(pid
, "user"))
2228 return switch_to_ns(pid
, "net");
2231 /* Used by qsort and bsearch functions for comparing names. */
2232 static inline int string_cmp(char **first
, char **second
)
2234 return strcmp(*first
, *second
);
2237 /* Used by qsort and bsearch functions for comparing container names. */
2238 static inline int container_cmp(struct lxc_container
**first
,
2239 struct lxc_container
**second
)
2241 return strcmp((*first
)->name
, (*second
)->name
);
2244 static bool add_to_array(char ***names
, char *cname
, int pos
)
2246 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2248 ERROR("Out of memory");
2253 newnames
[pos
] = strdup(cname
);
2257 /* Sort the array as we will use binary search on it. */
2258 qsort(newnames
, pos
+ 1, sizeof(char *),
2259 (int (*)(const void *, const void *))string_cmp
);
2264 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2267 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2269 ERROR("Out of memory");
2276 /* Sort the array as we will use binary search on it. */
2278 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2279 (int (*)(const void *, const void *))container_cmp
);
2284 static char** get_from_array(char ***names
, char *cname
, int size
)
2286 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2289 static bool array_contains(char ***names
, char *cname
, int size
)
2291 if(get_from_array(names
, cname
, size
) != NULL
)
2297 static bool remove_from_array(char ***names
, char *cname
, int size
)
2299 char **result
= get_from_array(names
, cname
, size
);
2300 if (result
!= NULL
) {
2308 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2311 int i
, count
= 0, pipefd
[2];
2312 char **interfaces
= NULL
;
2313 char interface
[IFNAMSIZ
];
2315 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2320 SYSERROR("Failed to fork task to get interfaces information");
2326 if (pid
== 0) { /* child */
2327 int ret
= 1, nbytes
;
2328 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2330 /* close the read-end of the pipe */
2333 if (!enter_net_ns(c
)) {
2334 SYSERROR("Failed to enter network namespace");
2338 /* Grab the list of interfaces */
2339 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2340 SYSERROR("Failed to get interfaces list");
2344 /* Iterate through the interfaces */
2345 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2346 tempIfAddr
= tempIfAddr
->ifa_next
) {
2347 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2358 netns_freeifaddrs(interfaceArray
);
2360 /* close the write-end of the pipe, thus sending EOF to the reader */
2365 /* close the write-end of the pipe */
2368 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2369 interface
[IFNAMSIZ
- 1] = '\0';
2371 if (array_contains(&interfaces
, interface
, count
))
2374 if (!add_to_array(&interfaces
, interface
, count
))
2375 ERROR("Failed to add \"%s\" to array", interface
);
2380 if (wait_for_pid(pid
) != 0) {
2381 for (i
= 0; i
< count
; i
++)
2382 free(interfaces
[i
]);
2388 /* close the read-end of the pipe */
2391 /* Append NULL to the array */
2393 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2398 WRAP_API(char **, lxcapi_get_interfaces
)
2400 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2401 const char *family
, int scope
)
2406 char address
[INET6_ADDRSTRLEN
];
2408 char **addresses
= NULL
;
2410 ret
= pipe2(pipefd
, O_CLOEXEC
);
2412 SYSERROR("Failed to create pipe");
2418 SYSERROR("Failed to create new process");
2426 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2428 char *address
= NULL
;
2429 void *tempAddrPtr
= NULL
;
2430 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2432 /* close the read-end of the pipe */
2435 if (!enter_net_ns(c
)) {
2436 SYSERROR("Failed to attach to network namespace");
2440 /* Grab the list of interfaces */
2441 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2442 SYSERROR("Failed to get interfaces list");
2446 /* Iterate through the interfaces */
2447 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2448 tempIfAddr
= tempIfAddr
->ifa_next
) {
2449 if (tempIfAddr
->ifa_addr
== NULL
)
2452 #pragma GCC diagnostic push
2453 #pragma GCC diagnostic ignored "-Wcast-align"
2455 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2456 if (family
&& strcmp(family
, "inet"))
2459 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2461 if (family
&& strcmp(family
, "inet6"))
2464 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2467 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2470 #pragma GCC diagnostic pop
2472 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2474 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2477 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2478 tempAddrPtr
, addressOutputBuffer
,
2479 sizeof(addressOutputBuffer
));
2483 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2484 if (nbytes
!= INET6_ADDRSTRLEN
) {
2485 SYSERROR("Failed to send ipv6 address \"%s\"",
2497 netns_freeifaddrs(interfaceArray
);
2499 /* close the write-end of the pipe, thus sending EOF to the reader */
2504 /* close the write-end of the pipe */
2507 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2508 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2510 if (!add_to_array(&addresses
, address
, count
))
2511 ERROR("PARENT: add_to_array failed");
2516 if (wait_for_pid(pid
) != 0) {
2517 for (i
= 0; i
< count
; i
++)
2524 /* close the read-end of the pipe */
2527 /* Append NULL to the array */
2529 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2534 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2536 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2539 struct lxc_config_t
*config
;
2541 if (!c
|| !c
->lxc_conf
)
2544 if (container_mem_lock(c
))
2547 config
= lxc_get_config(key
);
2548 /* Verify that the config key exists and that it has a callback
2551 if (config
&& config
->get
)
2552 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2554 container_mem_unlock(c
);
2558 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2560 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2564 if (!c
|| !c
->lxc_conf
)
2567 if (container_mem_lock(c
))
2570 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2571 container_mem_unlock(c
);
2575 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2577 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2581 /* List all config items. */
2583 return lxc_list_config_items(retv
, inlen
);
2585 if (!c
|| !c
->lxc_conf
)
2588 if (container_mem_lock(c
))
2591 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2592 * This is an intelligent result to show which keys are valid given the
2593 * type of nic it is.
2595 if (strncmp(key
, "lxc.net.", 8) == 0)
2596 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2598 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2600 container_mem_unlock(c
);
2604 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2606 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2609 bool ret
= false, need_disklock
= false;
2612 alt_file
= c
->configfile
;
2617 /* If we haven't yet loaded a config, load the stock config. */
2619 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2620 ERROR("Error loading default configuration file %s "
2622 lxc_global_config_value("lxc.default_config"),
2628 if (!create_container_dir(c
))
2631 /* If we're writing to the container's config file, take the disk lock.
2632 * Otherwise just take the memlock to protect the struct lxc_container
2633 * while we're traversing it.
2635 if (strcmp(c
->configfile
, alt_file
) == 0)
2636 need_disklock
= true;
2639 lret
= container_disk_lock(c
);
2641 lret
= container_mem_lock(c
);
2645 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2646 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2650 lret
= write_config(fd
, c
->lxc_conf
);
2659 container_disk_unlock(c
);
2661 container_mem_unlock(c
);
2666 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2669 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2675 char path
[PATH_MAX
];
2676 char newpath
[PATH_MAX
];
2677 int fd
, ret
, n
= 0, v
= 0;
2679 size_t len
= 0, bytes
= 0;
2681 if (container_disk_lock(c0
))
2684 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2685 if (ret
< 0 || ret
> PATH_MAX
)
2688 ret
= snprintf(newpath
, PATH_MAX
, "%s\n%s\n", c
->config_path
, c
->name
);
2689 if (ret
< 0 || ret
> PATH_MAX
)
2692 /* If we find an lxc-snapshot file using the old format only listing the
2693 * number of snapshots we will keep using it. */
2694 f1
= fopen(path
, "r");
2696 n
= fscanf(f1
, "%d", &v
);
2698 if (n
== 1 && v
== 0) {
2701 SYSERROR("Failed to remove \"%s\"", path
);
2709 f1
= fopen(path
, "w");
2713 if (fprintf(f1
, "%d\n", v
) < 0) {
2714 ERROR("Error writing new snapshots value");
2721 SYSERROR("Error writing to or closing snapshots file");
2725 /* Here we know that we have or can use an lxc-snapshot file
2726 * using the new format. */
2728 f1
= fopen(path
, "a");
2732 if (fprintf(f1
, "%s", newpath
) < 0) {
2733 ERROR("Error writing new snapshots entry");
2736 SYSERROR("Error writing to or closing snapshots file");
2742 SYSERROR("Error writing to or closing snapshots file");
2746 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2749 if (fstat(fd
, &fbuf
) < 0) {
2754 if (fbuf
.st_size
!= 0) {
2755 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2756 if (buf
== MAP_FAILED
) {
2757 SYSERROR("Failed to create mapping %s", path
);
2762 len
= strlen(newpath
);
2763 while ((del
= strstr((char *)buf
, newpath
))) {
2764 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2768 lxc_strmunmap(buf
, fbuf
.st_size
);
2769 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2770 SYSERROR("Failed to truncate file %s", path
);
2779 /* If the lxc-snapshot file is empty, remove it. */
2780 if (stat(path
, &fbuf
) < 0)
2783 if (!fbuf
.st_size
) {
2786 SYSERROR("Failed to remove \"%s\"", path
);
2793 container_disk_unlock(c0
);
2797 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2799 struct lxc_container
*p
;
2800 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[PATH_MAX
];
2801 size_t pathlen
= 0, namelen
= 0;
2805 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends",
2806 c
->config_path
, c
->name
);
2807 if (ret
< 0 || ret
>= PATH_MAX
) {
2808 ERROR("Path name too long");
2812 f
= fopen(path
, "r");
2816 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2817 if (getline(&lxcname
, &namelen
, f
) == -1) {
2818 ERROR("badly formatted file %s", path
);
2822 remove_trailing_newlines(lxcpath
);
2823 remove_trailing_newlines(lxcname
);
2825 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2826 ERROR("Unable to find dependent container %s:%s",
2831 if (!mod_rdep(p
, c
, inc
))
2832 ERROR("Failed to update snapshots file for %s:%s",
2835 lxc_container_put(p
);
2844 static bool has_fs_snapshots(struct lxc_container
*c
)
2847 char path
[PATH_MAX
];
2852 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c
->config_path
,
2854 if (ret
< 0 || ret
> PATH_MAX
)
2857 /* If the file doesn't exist there are no snapshots. */
2858 if (stat(path
, &fbuf
) < 0)
2863 f
= fopen(path
, "r");
2867 ret
= fscanf(f
, "%d", &v
);
2869 /* TODO: Figure out what to do with the return value of fscanf. */
2871 INFO("Container uses new lxc-snapshots format %s", path
);
2880 static bool has_snapshots(struct lxc_container
*c
)
2882 char path
[PATH_MAX
];
2883 struct dirent
*direntp
;
2887 if (!get_snappath_dir(c
, path
))
2890 dir
= opendir(path
);
2894 while ((direntp
= readdir(dir
))) {
2895 if (!strcmp(direntp
->d_name
, "."))
2898 if (!strcmp(direntp
->d_name
, ".."))
2908 static bool do_destroy_container(struct lxc_conf
*conf
) {
2911 if (am_guest_unpriv()) {
2912 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2913 "storage_destroy_wrapper");
2920 return storage_destroy(conf
);
2923 static int lxc_rmdir_onedev_wrapper(void *data
)
2925 char *arg
= (char *) data
;
2926 return lxc_rmdir_onedev(arg
, "snaps");
2929 static int lxc_unlink_exec_wrapper(void *data
)
2935 static bool container_destroy(struct lxc_container
*c
,
2936 struct lxc_storage
*storage
)
2940 struct lxc_conf
*conf
;
2945 if (!c
|| !do_lxcapi_is_defined(c
))
2949 if (container_disk_lock(c
))
2952 if (!is_stopped(c
)) {
2953 /* We should queue some sort of error - in c->error_string? */
2954 ERROR("container %s is not stopped", c
->name
);
2958 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2959 /* Start of environment variable setup for hooks */
2960 if (setenv("LXC_NAME", c
->name
, 1))
2961 SYSERROR("Failed to set environment variable for container name");
2963 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2964 SYSERROR("Failed to set environment variable for config path");
2966 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2967 SYSERROR("Failed to set environment variable for rootfs mount");
2969 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2970 SYSERROR("Failed to set environment variable for rootfs mount");
2972 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2973 SYSERROR("Failed to set environment variable for console path");
2975 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2976 SYSERROR("Failed to set environment variable for console log");
2977 /* End of environment variable setup for hooks */
2979 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2980 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2985 if (current_config
&& conf
== current_config
) {
2986 current_config
= NULL
;
2988 if (conf
->logfd
!= -1) {
2994 /* LXC is not managing the storage of the container. */
2995 if (conf
&& !conf
->rootfs
.managed
)
2998 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2999 if (!do_destroy_container(conf
)) {
3000 ERROR("Error destroying rootfs for %s", c
->name
);
3003 INFO("Destroyed rootfs for %s", c
->name
);
3006 mod_all_rdeps(c
, false);
3008 p1
= do_lxcapi_get_config_path(c
);
3017 * strlen("config") = 6
3021 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3024 ERROR("Failed to allocate memory");
3028 /* For an overlay container the rootfs is considered immutable and
3029 * cannot be removed when restoring from a snapshot.
3031 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3032 !strcmp(storage
->type
, "overlayfs")) &&
3033 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3034 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3035 if (ret
< 0 || (size_t)ret
>= len
)
3038 if (am_guest_unpriv())
3039 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3040 "lxc_unlink_exec_wrapper");
3044 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3048 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3054 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3055 if (ret
< 0 || (size_t)ret
>= len
)
3058 if (am_guest_unpriv())
3059 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3060 "lxc_rmdir_onedev_wrapper");
3062 ret
= lxc_rmdir_onedev(path
, "snaps");
3064 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3068 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3077 container_disk_unlock(c
);
3081 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3083 if (!c
|| !lxcapi_is_defined(c
))
3086 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3087 if (has_snapshots(c
)) {
3088 ERROR("Container %s has snapshots; not removing", c
->name
);
3092 if (has_fs_snapshots(c
)) {
3093 ERROR("container %s has snapshots on its rootfs", c
->name
);
3098 return container_destroy(c
, NULL
);
3101 WRAP_API(bool, lxcapi_destroy
)
3103 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3105 if (!c
|| !lxcapi_is_defined(c
))
3108 if (!lxcapi_snapshot_destroy_all(c
)) {
3109 ERROR("Error deleting all snapshots");
3113 return lxcapi_destroy(c
);
3116 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3118 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3122 struct lxc_config_t
*config
;
3125 config
= lxc_get_config(key
);
3129 ret
= config
->set(key
, v
, conf
, NULL
);
3133 if (lxc_config_value_empty(v
))
3134 do_clear_unexp_config_line(conf
, key
);
3136 bret
= do_append_unexp_config_line(conf
, key
, v
);
3143 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3149 c
->lxc_conf
= lxc_conf_init();
3154 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3161 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3168 if (container_mem_lock(c
))
3171 b
= do_set_config_item_locked(c
, key
, v
);
3173 container_mem_unlock(c
);
3177 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3179 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3181 if (!c
|| !c
->configfile
)
3184 return strdup(c
->configfile
);
3187 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3189 if (!c
|| !c
->config_path
)
3192 return (const char *)(c
->config_path
);
3197 * Just recalculate the c->configfile based on the
3198 * c->config_path, which must be set.
3199 * The lxc_container must be locked or not yet public.
3201 static bool set_config_filename(struct lxc_container
*c
)
3206 if (!c
->config_path
)
3209 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3210 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3211 newpath
= malloc(len
);
3215 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3216 if (ret
< 0 || ret
>= len
) {
3217 fprintf(stderr
, "Error printing out config file name\n");
3222 free(c
->configfile
);
3223 c
->configfile
= newpath
;
3228 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3232 char *oldpath
= NULL
;
3237 if (container_mem_lock(c
))
3242 ERROR("Out of memory setting new lxc path");
3248 oldpath
= c
->config_path
;
3251 /* Since we've changed the config path, we have to change the
3252 * config file name too */
3253 if (!set_config_filename(c
)) {
3254 ERROR("Out of memory setting new config filename");
3256 free(c
->config_path
);
3257 c
->config_path
= oldpath
;
3263 container_mem_unlock(c
);
3267 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3269 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3272 struct cgroup_ops
*cgroup_ops
;
3280 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3284 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3286 cgroup_exit(cgroup_ops
);
3291 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3293 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3296 struct cgroup_ops
*cgroup_ops
;
3304 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3308 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3311 cgroup_exit(cgroup_ops
);
3316 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3318 const char *lxc_get_global_config_item(const char *key
)
3320 return lxc_global_config_value(key
);
3323 const char *lxc_get_version(void)
3328 static int copy_file(const char *old
, const char *new)
3335 if (file_exists(new)) {
3336 ERROR("copy destination %s exists", new);
3340 ret
= stat(old
, &sbuf
);
3342 INFO("Error stat'ing %s", old
);
3346 in
= open(old
, O_RDONLY
);
3348 SYSERROR("Error opening original file %s", old
);
3352 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3354 SYSERROR("Error opening new file %s", new);
3360 len
= lxc_read_nointr(in
, buf
, 8096);
3362 SYSERROR("Error reading old file %s", old
);
3369 ret
= lxc_write_nointr(out
, buf
, len
);
3370 if (ret
< len
) { /* should we retry? */
3371 SYSERROR("Error: write to new file %s was interrupted", new);
3379 /* We set mode, but not owner/group. */
3380 ret
= chmod(new, sbuf
.st_mode
);
3382 SYSERROR("Error setting mode on %s", new);
3394 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3397 struct lxc_list
*it
;
3400 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3401 cpath
= alloca(len
);
3402 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3403 if (ret
< 0 || ret
>= len
)
3406 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3407 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3408 char *hookname
= it
->elem
;
3409 char *fname
= strrchr(hookname
, '/');
3410 char tmppath
[PATH_MAX
];
3411 if (!fname
) /* relative path - we don't support, but maybe we should */
3414 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3415 /* this hook is public - ignore */
3419 /* copy the script, and change the entry in confile */
3420 ret
= snprintf(tmppath
, PATH_MAX
, "%s/%s/%s",
3421 c
->config_path
, c
->name
, fname
+1);
3422 if (ret
< 0 || ret
>= PATH_MAX
)
3425 ret
= copy_file(it
->elem
, tmppath
);
3431 it
->elem
= strdup(tmppath
);
3433 ERROR("out of memory copying hook path");
3439 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3440 c
->config_path
, oldc
->name
, c
->name
)) {
3441 ERROR("Error saving new hooks in clone");
3445 do_lxcapi_save_config(c
, NULL
);
3450 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3452 char newpath
[PATH_MAX
];
3453 char *oldpath
= oldc
->lxc_conf
->fstab
;
3459 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3461 char *p
= strrchr(oldpath
, '/');
3465 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s%s",
3466 c
->config_path
, c
->name
, p
);
3467 if (ret
< 0 || ret
>= PATH_MAX
) {
3468 ERROR("error printing new path for %s", oldpath
);
3472 if (file_exists(newpath
)) {
3473 ERROR("error: fstab file %s exists", newpath
);
3477 if (copy_file(oldpath
, newpath
) < 0) {
3478 ERROR("error: copying %s to %s", oldpath
, newpath
);
3482 free(c
->lxc_conf
->fstab
);
3484 c
->lxc_conf
->fstab
= strdup(newpath
);
3485 if (!c
->lxc_conf
->fstab
) {
3486 ERROR("error: allocating pathname");
3490 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3491 ERROR("error saving new lxctab");
3498 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3500 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3503 ret
= snprintf(path0
, PATH_MAX
, "%s/%s/lxc_rdepends", c0
->config_path
,
3505 if (ret
< 0 || ret
>= PATH_MAX
) {
3506 WARN("Error copying reverse dependencies");
3510 ret
= snprintf(path1
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3512 if (ret
< 0 || ret
>= PATH_MAX
) {
3513 WARN("Error copying reverse dependencies");
3517 if (copy_file(path0
, path1
) < 0) {
3518 INFO("Error copying reverse dependencies");
3523 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3526 char path
[PATH_MAX
];
3530 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3532 if (ret
< 0 || ret
>= PATH_MAX
)
3535 f
= fopen(path
, "a");
3541 /* If anything goes wrong, just return an error. */
3542 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3552 * If the fs natively supports snapshot clones with no penalty,
3553 * then default to those even if not requested.
3554 * Currently we only do this for btrfs.
3556 bool should_default_to_snapshot(struct lxc_container
*c0
,
3557 struct lxc_container
*c1
)
3560 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3561 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3562 char *p0
= alloca(l0
+ 1);
3563 char *p1
= alloca(l1
+ 1);
3564 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3566 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3567 if (ret
< 0 || ret
>= l0
)
3570 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3571 if (ret
< 0 || ret
>= l1
)
3574 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3577 if (is_btrfs_subvol(rootfs
) <= 0)
3580 return btrfs_same_fs(p0
, p1
) == 0;
3583 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3584 const char *newtype
, int flags
, const char *bdevdata
,
3587 struct lxc_storage
*bdev
;
3590 if (should_default_to_snapshot(c0
, c
))
3591 flags
|= LXC_CLONE_SNAPSHOT
;
3593 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3594 bdevdata
, newsize
, &need_rdep
);
3596 ERROR("Error copying storage.");
3600 /* Set new rootfs. */
3601 free(c
->lxc_conf
->rootfs
.path
);
3602 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3605 if (!c
->lxc_conf
->rootfs
.path
) {
3606 ERROR("Out of memory while setting storage path.");
3610 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3611 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3612 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3613 c
->lxc_conf
->rootfs
.path
)) {
3614 ERROR("Error saving new rootfs to cloned config.");
3618 if (flags
& LXC_CLONE_SNAPSHOT
)
3619 copy_rdepends(c
, c0
);
3622 if (!add_rdepends(c
, c0
))
3623 WARN("Error adding reverse dependency from %s to %s",
3627 mod_all_rdeps(c
, true);
3632 struct clone_update_data
{
3633 struct lxc_container
*c0
;
3634 struct lxc_container
*c1
;
3639 static int clone_update_rootfs(struct clone_update_data
*data
)
3641 struct lxc_container
*c0
= data
->c0
;
3642 struct lxc_container
*c
= data
->c1
;
3643 int flags
= data
->flags
;
3644 char **hookargs
= data
->hookargs
;
3646 char path
[PATH_MAX
];
3647 struct lxc_storage
*bdev
;
3649 struct lxc_conf
*conf
= c
->lxc_conf
;
3651 /* update hostname in rootfs */
3652 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3654 if (setgid(0) < 0) {
3655 ERROR("Failed to setgid to 0");
3659 if (setuid(0) < 0) {
3660 ERROR("Failed to setuid to 0");
3664 if (setgroups(0, NULL
) < 0)
3665 WARN("Failed to clear groups");
3667 if (unshare(CLONE_NEWNS
) < 0)
3670 bdev
= storage_init(c
->lxc_conf
);
3674 if (strcmp(bdev
->type
, "dir") != 0) {
3675 if (unshare(CLONE_NEWNS
) < 0) {
3676 ERROR("error unsharing mounts");
3681 if (detect_shared_rootfs()) {
3682 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3683 SYSERROR("Failed to make / rslave");
3684 ERROR("Continuing...");
3688 if (bdev
->ops
->mount(bdev
) < 0) {
3692 } else { /* TODO come up with a better way */
3694 bdev
->dest
= strdup(bdev
->src
);
3697 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3698 /* Start of environment variable setup for hooks */
3699 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3700 SYSERROR("failed to set environment variable for source container name");
3702 if (setenv("LXC_NAME", c
->name
, 1))
3703 SYSERROR("failed to set environment variable for container name");
3705 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3706 SYSERROR("failed to set environment variable for config path");
3708 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3709 SYSERROR("failed to set environment variable for rootfs mount");
3711 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3712 SYSERROR("failed to set environment variable for rootfs mount");
3714 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3715 ERROR("Error executing clone hook for %s", c
->name
);
3721 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3722 ret
= snprintf(path
, PATH_MAX
, "%s/etc/hostname", bdev
->dest
);
3725 if (ret
< 0 || ret
>= PATH_MAX
)
3728 if (!file_exists(path
))
3731 if (!(fout
= fopen(path
, "w"))) {
3732 SYSERROR("unable to open %s: ignoring", path
);
3736 if (fprintf(fout
, "%s", c
->name
) < 0) {
3741 if (fclose(fout
) < 0)
3750 static int clone_update_rootfs_wrapper(void *data
)
3752 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3753 return clone_update_rootfs(arg
);
3757 * We want to support:
3758 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3759 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3761 -s [ implies overlay]
3764 only rootfs gets converted (copied/snapshotted) on clone.
3767 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3769 char *p
= strrchr(path
, '/');
3776 ret
= do_create_container_dir(path
, conf
);
3782 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3783 const char *lxcpath
, int flags
,
3784 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3787 char newpath
[PATH_MAX
];
3789 struct clone_update_data data
;
3790 size_t saved_unexp_len
;
3792 int storage_copied
= 0;
3793 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3794 struct lxc_container
*c2
= NULL
;
3796 if (!c
|| !do_lxcapi_is_defined(c
))
3799 if (container_mem_lock(c
))
3801 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3802 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3806 /* Make sure the container doesn't yet exist. */
3811 lxcpath
= do_lxcapi_get_config_path(c
);
3813 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/config", lxcpath
, newname
);
3814 if (ret
< 0 || ret
>= PATH_MAX
) {
3815 SYSERROR("clone: failed making config pathname");
3819 if (file_exists(newpath
)) {
3820 ERROR("error: clone: %s exists", newpath
);
3824 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3825 if (ret
< 0 && errno
!= EEXIST
) {
3826 ERROR("Error creating container dir for %s", newpath
);
3830 /* Copy the configuration. Tweak it as needed. */
3831 if (c
->lxc_conf
->rootfs
.path
) {
3832 origroot
= c
->lxc_conf
->rootfs
.path
;
3833 c
->lxc_conf
->rootfs
.path
= NULL
;
3836 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3837 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3839 SYSERROR("Failed to open \"%s\"", newpath
);
3843 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3844 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3845 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3846 if (!c
->lxc_conf
->unexpanded_config
) {
3851 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3852 write_config(fd
, c
->lxc_conf
);
3855 c
->lxc_conf
->rootfs
.path
= origroot
;
3857 free(c
->lxc_conf
->unexpanded_config
);
3858 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3859 saved_unexp_conf
= NULL
;
3860 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3862 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, newname
);
3863 if (ret
< 0 || ret
>= PATH_MAX
) {
3864 SYSERROR("clone: failed making rootfs pathname");
3868 ret
= mkdir(newpath
, 0755);
3870 /* For an overlay container the rootfs is considered immutable
3871 * and will not have been removed when restoring from a
3874 if (errno
!= ENOENT
&&
3875 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3876 SYSERROR("Failed to create directory \"%s\"", newpath
);
3881 if (am_guest_unpriv()) {
3882 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3883 ERROR("Error chowning %s to container root", newpath
);
3888 c2
= lxc_container_new(newname
, lxcpath
);
3890 ERROR("clone: failed to create new container (%s %s)", newname
,
3895 /* copy/snapshot rootfs's */
3896 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3900 /* update utsname */
3901 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3902 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3903 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3905 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3906 ERROR("Error setting new hostname");
3912 ret
= copyhooks(c
, c2
);
3914 ERROR("error copying hooks");
3918 if (copy_fstab(c
, c2
) < 0) {
3919 ERROR("error copying fstab");
3923 /* update macaddrs */
3924 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3925 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3926 ERROR("Error updating mac addresses");
3931 /* Update absolute paths for overlay mount directories. */
3932 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3935 /* We've now successfully created c2's storage, so clear it out if we
3940 if (!c2
->save_config(c2
, NULL
))
3943 if ((pid
= fork()) < 0) {
3949 ret
= wait_for_pid(pid
);
3953 container_mem_unlock(c
);
3960 data
.hookargs
= hookargs
;
3962 if (am_guest_unpriv())
3963 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3964 &data
, "clone_update_rootfs_wrapper");
3966 ret
= clone_update_rootfs(&data
);
3968 _exit(EXIT_FAILURE
);
3970 container_mem_unlock(c
);
3971 _exit(EXIT_SUCCESS
);
3974 container_mem_unlock(c
);
3976 if (!storage_copied
)
3977 c2
->lxc_conf
->rootfs
.path
= NULL
;
3980 lxc_container_put(c2
);
3986 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3987 const char *lxcpath
, int flags
,
3988 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3991 struct lxc_container
* ret
;
3993 current_config
= c
? c
->lxc_conf
: NULL
;
3994 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3995 current_config
= NULL
;
4000 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4002 struct lxc_storage
*bdev
;
4003 struct lxc_container
*newc
;
4005 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4008 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4009 ERROR("Renaming a container with snapshots is not supported");
4013 bdev
= storage_init(c
->lxc_conf
);
4015 ERROR("Failed to find original backing store type");
4019 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4022 lxc_container_put(newc
);
4026 if (newc
&& lxcapi_is_defined(newc
))
4027 lxc_container_put(newc
);
4029 if (!container_destroy(c
, NULL
)) {
4030 ERROR("Could not destroy existing container %s", c
->name
);
4037 WRAP_API_1(bool, lxcapi_rename
, const char *)
4039 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
)
4046 current_config
= c
->lxc_conf
;
4048 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4049 current_config
= NULL
;
4053 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4055 lxc_attach_command_t command
;
4062 command
.program
= (char*)program
;
4063 command
.argv
= (char**)argv
;
4065 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4071 return lxc_wait_for_pid_status(pid
);
4074 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4078 current_config
= c
? c
->lxc_conf
: NULL
;
4079 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4080 current_config
= NULL
;
4085 static int get_next_index(const char *lxcpath
, char *cname
)
4091 fname
= alloca(strlen(lxcpath
) + 20);
4094 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4096 ret
= stat(fname
, &sb
);
4104 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4109 * If the old style snapshot path exists, use it
4110 * /var/lib/lxc -> /var/lib/lxcsnaps
4112 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4113 if (ret
< 0 || ret
>= PATH_MAX
)
4116 if (dir_exists(snappath
)) {
4117 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4118 if (ret
< 0 || ret
>= PATH_MAX
)
4125 * Use the new style path
4126 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4128 ret
= snprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4129 if (ret
< 0 || ret
>= PATH_MAX
)
4135 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4140 struct lxc_container
*c2
;
4141 char snappath
[PATH_MAX
], newname
[20];
4145 if (!c
|| !lxcapi_is_defined(c
))
4148 if (!storage_can_backup(c
->lxc_conf
)) {
4149 ERROR("%s's backing store cannot be backed up", c
->name
);
4150 ERROR("Your container must use another backing store type");
4154 if (!get_snappath_dir(c
, snappath
))
4157 i
= get_next_index(snappath
, c
->name
);
4159 if (mkdir_p(snappath
, 0755) < 0) {
4160 ERROR("Failed to create snapshot directory %s", snappath
);
4164 ret
= snprintf(newname
, 20, "snap%d", i
);
4165 if (ret
< 0 || ret
>= 20)
4169 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4170 * created in the original container
4172 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4173 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4174 if (storage_is_dir(c
->lxc_conf
)) {
4175 ERROR("Snapshot of directory-backed container requested");
4176 ERROR("Making a copy-clone. If you do want snapshots, then");
4177 ERROR("please create overlay clone first, snapshot that");
4178 ERROR("and keep the original container pristine");
4179 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4182 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4184 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4188 lxc_container_put(c2
);
4190 /* Now write down the creation time. */
4193 if (!localtime_r(&timer
, &tm_info
)) {
4194 ERROR("Failed to get localtime");
4198 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4200 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4201 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4202 f
= fopen(dfnam
, "w");
4204 ERROR("Failed to open %s", dfnam
);
4208 if (fprintf(f
, "%s", buffer
) < 0) {
4209 SYSERROR("Writing timestamp");
4216 SYSERROR("Writing timestamp");
4221 /* $p / $name / comment \0 */
4222 int len
= strlen(snappath
) + strlen(newname
) + 10;
4223 char *path
= alloca(len
);
4225 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4226 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4232 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4234 static void lxcsnap_free(struct lxc_snapshot
*s
)
4237 free(s
->comment_pathname
);
4242 static char *get_snapcomment_path(char* snappath
, char *name
)
4244 /* $snappath/$name/comment */
4245 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4246 char *s
= malloc(len
);
4249 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4250 if (ret
< 0 || ret
>= len
) {
4259 static char *get_timestamp(char* snappath
, char *name
)
4261 char path
[PATH_MAX
], *s
= NULL
;
4265 ret
= snprintf(path
, PATH_MAX
, "%s/%s/ts", snappath
, name
);
4266 if (ret
< 0 || ret
>= PATH_MAX
)
4269 fin
= fopen(path
, "r");
4273 (void) fseek(fin
, 0, SEEK_END
);
4275 (void) fseek(fin
, 0, SEEK_SET
);
4280 if (fread(s
, 1, len
, fin
) != len
) {
4281 SYSERROR("reading timestamp");
4292 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4294 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4296 struct dirent
*direntp
;
4297 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4300 if (!c
|| !lxcapi_is_defined(c
))
4303 if (!get_snappath_dir(c
, snappath
)) {
4304 ERROR("path name too long");
4308 dir
= opendir(snappath
);
4310 INFO("Failed to open %s - assuming no snapshots", snappath
);
4314 while ((direntp
= readdir(dir
))) {
4315 if (!strcmp(direntp
->d_name
, "."))
4318 if (!strcmp(direntp
->d_name
, ".."))
4321 ret
= snprintf(path2
, PATH_MAX
, "%s/%s/config", snappath
, direntp
->d_name
);
4322 if (ret
< 0 || ret
>= PATH_MAX
) {
4323 ERROR("pathname too long");
4327 if (!file_exists(path2
))
4330 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4332 SYSERROR("Out of memory");
4337 snaps
[count
].free
= lxcsnap_free
;
4338 snaps
[count
].name
= strdup(direntp
->d_name
);
4339 if (!snaps
[count
].name
)
4342 snaps
[count
].lxcpath
= strdup(snappath
);
4343 if (!snaps
[count
].lxcpath
) {
4344 free(snaps
[count
].name
);
4348 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4349 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4354 WARN("Failed to close directory");
4363 for (i
=0; i
<count
; i
++)
4364 lxcsnap_free(&snaps
[i
]);
4370 WARN("Failed to close directory");
4375 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4377 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4379 char clonelxcpath
[PATH_MAX
];
4381 struct lxc_container
*snap
, *rest
;
4382 struct lxc_storage
*bdev
;
4385 if (!c
|| !c
->name
|| !c
->config_path
)
4388 if (has_fs_snapshots(c
)) {
4389 ERROR("container rootfs has dependent snapshots");
4393 bdev
= storage_init(c
->lxc_conf
);
4395 ERROR("Failed to find original backing store type");
4399 /* For an overlay container the rootfs is considered immutable
4400 * and cannot be removed when restoring from a snapshot. We pass this
4401 * internal flag along to communicate this to various parts of the
4404 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4405 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4410 if (!get_snappath_dir(c
, clonelxcpath
)) {
4414 /* how should we lock this? */
4416 snap
= lxc_container_new(snapname
, clonelxcpath
);
4417 if (!snap
|| !lxcapi_is_defined(snap
)) {
4418 ERROR("Could not open snapshot %s", snapname
);
4421 lxc_container_put(snap
);
4427 if (!strcmp(c
->name
, newname
)) {
4428 if (!container_destroy(c
, bdev
)) {
4429 ERROR("Could not destroy existing container %s", newname
);
4430 lxc_container_put(snap
);
4436 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4437 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4439 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4440 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4442 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4445 if (rest
&& lxcapi_is_defined(rest
))
4449 lxc_container_put(rest
);
4451 lxc_container_put(snap
);
4455 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4457 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4459 struct lxc_container
*snap
= NULL
;
4462 snap
= lxc_container_new(snapname
, clonelxcpath
);
4464 ERROR("Could not find snapshot %s", snapname
);
4468 if (!do_lxcapi_destroy(snap
)) {
4469 ERROR("Could not destroy snapshot %s", snapname
);
4477 lxc_container_put(snap
);
4482 static bool remove_all_snapshots(const char *path
)
4485 struct dirent
*direntp
;
4488 dir
= opendir(path
);
4490 SYSERROR("opendir on snapshot path %s", path
);
4494 while ((direntp
= readdir(dir
))) {
4495 if (!strcmp(direntp
->d_name
, "."))
4498 if (!strcmp(direntp
->d_name
, ".."))
4501 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4510 SYSERROR("Error removing directory %s", path
);
4515 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4517 char clonelxcpath
[PATH_MAX
];
4519 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4522 if (!get_snappath_dir(c
, clonelxcpath
))
4525 return do_snapshot_destroy(snapname
, clonelxcpath
);
4528 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4530 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4532 char clonelxcpath
[PATH_MAX
];
4534 if (!c
|| !c
->name
|| !c
->config_path
)
4537 if (!get_snappath_dir(c
, clonelxcpath
))
4540 return remove_all_snapshots(clonelxcpath
);
4543 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4545 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4550 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4553 WRAP_API(bool, lxcapi_may_control
)
4555 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4561 char chrootpath
[PATH_MAX
];
4562 char *directory_path
= NULL
;
4566 SYSERROR("Failed to fork()");
4571 ret
= wait_for_pid(pid
);
4573 ERROR("Failed to create device node");
4580 /* prepare the path */
4581 ret
= snprintf(chrootpath
, PATH_MAX
, "/proc/%d/root", init_pid
);
4582 if (ret
< 0 || ret
>= PATH_MAX
)
4585 ret
= chroot(chrootpath
);
4587 _exit(EXIT_FAILURE
);
4591 _exit(EXIT_FAILURE
);
4593 /* remove path if it exists */
4594 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4598 SYSERROR("Failed to remove \"%s\"", path
);
4599 _exit(EXIT_FAILURE
);
4604 _exit(EXIT_SUCCESS
);
4606 /* create any missing directories */
4609 _exit(EXIT_FAILURE
);
4611 directory_path
= dirname(tmp
);
4612 ret
= mkdir_p(directory_path
, 0755);
4613 if (ret
< 0 && errno
!= EEXIST
) {
4614 SYSERROR("Failed to create path \"%s\"", directory_path
);
4616 _exit(EXIT_FAILURE
);
4619 /* create the device node */
4620 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4623 SYSERROR("Failed to create device node at \"%s\"", path
);
4624 _exit(EXIT_FAILURE
);
4627 _exit(EXIT_SUCCESS
);
4630 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4634 char value
[LXC_MAX_BUFFER
];
4637 /* make sure container is running */
4638 if (!do_lxcapi_is_running(c
)) {
4639 ERROR("container is not running");
4643 /* use src_path if dest_path is NULL otherwise use dest_path */
4644 p
= dest_path
? dest_path
: src_path
;
4646 /* make sure we can access p */
4647 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4650 /* continue if path is character device or block device */
4651 if (S_ISCHR(st
.st_mode
))
4652 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4653 else if (S_ISBLK(st
.st_mode
))
4654 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4658 /* check snprintf return code */
4659 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4662 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4665 /* add or remove device to/from cgroup access list */
4667 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4668 ERROR("set_cgroup_item failed while adding the device node");
4672 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4673 ERROR("set_cgroup_item failed while removing the device node");
4681 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4683 // cannot mknod if we're not privileged wrt init_user_ns
4684 if (am_host_unpriv()) {
4685 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4689 return add_remove_device_node(c
, src_path
, dest_path
, true);
4692 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4694 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4696 if (am_guest_unpriv()) {
4697 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4701 return add_remove_device_node(c
, src_path
, dest_path
, false);
4704 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4706 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4708 const char *dst_ifname
)
4713 if (am_guest_unpriv()) {
4714 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4719 ERROR("No source interface name given");
4723 ret
= lxc_netdev_isup(ifname
);
4725 /* netdev of ifname is up. */
4726 ret
= lxc_netdev_down(ifname
);
4731 init_pid
= do_lxcapi_init_pid(c
);
4732 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4736 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4743 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4745 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4747 const char *dst_ifname
)
4750 pid_t pid
, pid_outside
;
4753 * TODO - if this is a physical device, then we need am_host_unpriv.
4754 * But for other types guest privilege suffices.
4756 if (am_guest_unpriv()) {
4757 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4762 ERROR("No source interface name given");
4766 pid_outside
= lxc_raw_getpid();
4769 ERROR("Failed to fork");
4773 if (pid
== 0) { /* child */
4776 init_pid
= do_lxcapi_init_pid(c
);
4777 if (!switch_to_ns(init_pid
, "net")) {
4778 ERROR("Failed to enter network namespace");
4779 _exit(EXIT_FAILURE
);
4782 ret
= lxc_netdev_isup(ifname
);
4784 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4785 _exit(EXIT_FAILURE
);
4788 /* netdev of ifname is up. */
4790 ret
= lxc_netdev_down(ifname
);
4792 ERROR("Failed to set network device \"%s\" down", ifname
);
4793 _exit(EXIT_FAILURE
);
4797 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4798 /* -EINVAL means there is no netdev named as ifname. */
4801 ERROR("Network device \"%s\" not found", ifname
);
4803 ERROR("Failed to remove network device \"%s\"", ifname
);
4805 _exit(EXIT_FAILURE
);
4808 _exit(EXIT_SUCCESS
);
4811 ret
= wait_for_pid(pid
);
4815 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4819 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4821 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4822 struct migrate_opts
*opts
, unsigned int size
)
4825 struct migrate_opts
*valid_opts
= opts
;
4826 uint64_t features_to_check
= 0;
4828 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4829 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4830 * to do anything special.
4832 if (size
> sizeof(*opts
)) {
4833 unsigned char *addr
;
4836 addr
= (void *)opts
+ sizeof(*opts
);
4837 end
= (void *)opts
+ size
;
4839 for (; addr
< end
; addr
++)
4844 /* If the caller has a smaller struct, let's zero out the end for them
4845 * so we don't accidentally use bits of it that they didn't know about
4848 if (size
< sizeof(*opts
)) {
4849 valid_opts
= malloc(sizeof(*opts
));
4853 memset(valid_opts
, 0, sizeof(*opts
));
4854 memcpy(valid_opts
, opts
, size
);
4858 case MIGRATE_PRE_DUMP
:
4859 if (!do_lxcapi_is_running(c
)) {
4860 ERROR("container is not running");
4864 ret
= !__criu_pre_dump(c
, valid_opts
);
4867 if (!do_lxcapi_is_running(c
)) {
4868 ERROR("container is not running");
4872 ret
= !__criu_dump(c
, valid_opts
);
4874 case MIGRATE_RESTORE
:
4875 if (do_lxcapi_is_running(c
)) {
4876 ERROR("container is already running");
4880 ret
= !__criu_restore(c
, valid_opts
);
4882 case MIGRATE_FEATURE_CHECK
:
4883 features_to_check
= valid_opts
->features_to_check
;
4884 ret
= !__criu_check_feature(&features_to_check
);
4886 /* Something went wrong. Let's let the caller
4887 * know which feature checks failed. */
4888 valid_opts
->features_to_check
= features_to_check
;
4892 ERROR("invalid migrate command %u", cmd
);
4897 if (size
< sizeof(*opts
))
4903 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4905 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4907 struct migrate_opts opts
;
4909 memset(&opts
, 0, sizeof(opts
));
4911 opts
.directory
= directory
;
4913 opts
.verbose
= verbose
;
4915 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4918 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4920 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4922 struct migrate_opts opts
;
4924 memset(&opts
, 0, sizeof(opts
));
4926 opts
.directory
= directory
;
4927 opts
.verbose
= verbose
;
4929 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4932 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4934 /* @st_mode is the st_mode field of the stat(source) return struct */
4935 static int create_mount_target(const char *dest
, mode_t st_mode
)
4937 char *dirdup
, *destdirname
;
4940 dirdup
= strdup(dest
);
4942 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4945 destdirname
= dirname(dirdup
);
4947 ret
= mkdir_p(destdirname
, 0755);
4949 SYSERROR("Failed to create \"%s\"", destdirname
);
4957 if (S_ISDIR(st_mode
))
4958 ret
= mkdir(dest
, 0000);
4960 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4962 SYSERROR("Failed to create mount target \"%s\"", dest
);
4969 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4970 const char *target
, const char *filesystemtype
,
4971 unsigned long mountflags
, const void *data
,
4972 struct lxc_mount
*mnt
)
4975 char template[PATH_MAX
], path
[PATH_MAX
];
4976 pid_t pid
, init_pid
;
4979 int ret
= -1, fd
= -EBADF
;
4981 if (!c
|| !c
->lxc_conf
) {
4982 ERROR("Container or configuration is NULL");
4986 if (!c
->lxc_conf
->shmount
.path_host
) {
4987 ERROR("Host path to shared mountpoint must be specified in the config\n");
4991 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
4992 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
4993 SYSERROR("Error writing shmounts tempdir name");
4997 /* Create a temporary file / dir under the shared mountpoint */
4998 if (!source
|| strcmp(source
, "") == 0) {
4999 /* If source is not specified, maybe we want to mount a filesystem? */
5000 sb
.st_mode
= S_IFDIR
;
5002 ret
= stat(source
, &sb
);
5004 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5009 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5011 sret
= mkdtemp(template);
5013 SYSERROR("Could not create shmounts temporary dir");
5017 fd
= lxc_make_tmpfile(template, false);
5019 SYSERROR("Could not create shmounts temporary file");
5027 SYSERROR("Could not fork");
5033 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5035 SYSERROR("Failed to mount onto \"%s\"", template);
5036 _exit(EXIT_FAILURE
);
5038 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5040 init_pid
= do_lxcapi_init_pid(c
);
5042 ERROR("Failed to obtain container's init pid");
5043 _exit(EXIT_FAILURE
);
5046 /* Enter the container namespaces */
5047 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5048 if (!switch_to_ns(init_pid
, "user")){
5049 ERROR("Failed to enter user namespace");
5050 _exit(EXIT_FAILURE
);
5054 if (!switch_to_ns(init_pid
, "mnt")) {
5055 ERROR("Failed to enter mount namespace");
5056 _exit(EXIT_FAILURE
);
5059 ret
= create_mount_target(target
, sb
.st_mode
);
5061 _exit(EXIT_FAILURE
);
5062 TRACE("Created mount target \"%s\"", target
);
5064 suff
= strrchr(template, '/');
5066 _exit(EXIT_FAILURE
);
5068 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5069 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5070 SYSERROR("Error writing container mountpoint name");
5071 _exit(EXIT_FAILURE
);
5074 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5076 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5077 _exit(EXIT_FAILURE
);
5079 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5081 _exit(EXIT_SUCCESS
);
5084 ret
= wait_for_pid(pid
);
5086 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5092 (void)umount2(template, MNT_DETACH
);
5094 (void)rmdir(template);
5096 (void)unlink(template);
5105 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5106 unsigned long, const void *, struct lxc_mount
*)
5108 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5109 unsigned long flags
, struct lxc_mount
*mnt
)
5111 pid_t pid
, init_pid
;
5114 if (!c
|| !c
->lxc_conf
) {
5115 ERROR("Container or configuration is NULL");
5122 SYSERROR("Could not fork");
5127 init_pid
= do_lxcapi_init_pid(c
);
5129 ERROR("Failed to obtain container's init pid");
5130 _exit(EXIT_FAILURE
);
5133 /* Enter the container namespaces */
5134 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5135 if (!switch_to_ns(init_pid
, "user")) {
5136 ERROR("Failed to enter user namespace");
5137 _exit(EXIT_FAILURE
);
5141 if (!switch_to_ns(init_pid
, "mnt")) {
5142 ERROR("Failed to enter mount namespace");
5143 _exit(EXIT_FAILURE
);
5146 /* Do the unmount */
5147 ret
= umount2(target
, flags
);
5149 SYSERROR("Failed to umount \"%s\"", target
);
5150 _exit(EXIT_FAILURE
);
5153 _exit(EXIT_SUCCESS
);
5156 ret
= wait_for_pid(pid
);
5158 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5165 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5167 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5176 current_config
= c
->lxc_conf
;
5179 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5183 ERROR("Memory allocation error.");
5189 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5193 current_config
= NULL
;
5197 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5199 struct lxc_container
*c
;
5205 c
= malloc(sizeof(*c
));
5207 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5210 memset(c
, 0, sizeof(*c
));
5213 c
->config_path
= strdup(configpath
);
5215 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5216 if (!c
->config_path
) {
5217 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5221 remove_trailing_slashes(c
->config_path
);
5224 c
->name
= malloc(len
+ 1);
5226 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5229 (void)strlcpy(c
->name
, name
, len
+ 1);
5232 c
->slock
= lxc_newlock(c
->config_path
, name
);
5234 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5238 c
->privlock
= lxc_newlock(NULL
, NULL
);
5240 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5244 if (!set_config_filename(c
)) {
5245 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5249 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5250 fprintf(stderr
, "Failed to load config for %s\n", name
);
5254 if (ongoing_create(c
) == 2) {
5255 ERROR("Failed to complete container creation for %s", c
->name
);
5256 container_destroy(c
, NULL
);
5257 lxcapi_clear_config(c
);
5260 c
->daemonize
= true;
5263 /* Assign the member functions. */
5264 c
->is_defined
= lxcapi_is_defined
;
5265 c
->state
= lxcapi_state
;
5266 c
->is_running
= lxcapi_is_running
;
5267 c
->freeze
= lxcapi_freeze
;
5268 c
->unfreeze
= lxcapi_unfreeze
;
5269 c
->console
= lxcapi_console
;
5270 c
->console_getfd
= lxcapi_console_getfd
;
5271 c
->init_pid
= lxcapi_init_pid
;
5272 c
->load_config
= lxcapi_load_config
;
5273 c
->want_daemonize
= lxcapi_want_daemonize
;
5274 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5275 c
->start
= lxcapi_start
;
5276 c
->startl
= lxcapi_startl
;
5277 c
->stop
= lxcapi_stop
;
5278 c
->config_file_name
= lxcapi_config_file_name
;
5279 c
->wait
= lxcapi_wait
;
5280 c
->set_config_item
= lxcapi_set_config_item
;
5281 c
->destroy
= lxcapi_destroy
;
5282 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5283 c
->rename
= lxcapi_rename
;
5284 c
->save_config
= lxcapi_save_config
;
5285 c
->get_keys
= lxcapi_get_keys
;
5286 c
->create
= lxcapi_create
;
5287 c
->createl
= lxcapi_createl
;
5288 c
->shutdown
= lxcapi_shutdown
;
5289 c
->reboot
= lxcapi_reboot
;
5290 c
->reboot2
= lxcapi_reboot2
;
5291 c
->clear_config
= lxcapi_clear_config
;
5292 c
->clear_config_item
= lxcapi_clear_config_item
;
5293 c
->get_config_item
= lxcapi_get_config_item
;
5294 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5295 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5296 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5297 c
->get_config_path
= lxcapi_get_config_path
;
5298 c
->set_config_path
= lxcapi_set_config_path
;
5299 c
->clone
= lxcapi_clone
;
5300 c
->get_interfaces
= lxcapi_get_interfaces
;
5301 c
->get_ips
= lxcapi_get_ips
;
5302 c
->attach
= lxcapi_attach
;
5303 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5304 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5305 c
->snapshot
= lxcapi_snapshot
;
5306 c
->snapshot_list
= lxcapi_snapshot_list
;
5307 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5308 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5309 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5310 c
->may_control
= lxcapi_may_control
;
5311 c
->add_device_node
= lxcapi_add_device_node
;
5312 c
->remove_device_node
= lxcapi_remove_device_node
;
5313 c
->attach_interface
= lxcapi_attach_interface
;
5314 c
->detach_interface
= lxcapi_detach_interface
;
5315 c
->checkpoint
= lxcapi_checkpoint
;
5316 c
->restore
= lxcapi_restore
;
5317 c
->migrate
= lxcapi_migrate
;
5318 c
->console_log
= lxcapi_console_log
;
5319 c
->mount
= lxcapi_mount
;
5320 c
->umount
= lxcapi_umount
;
5325 lxc_container_free(c
);
5329 int lxc_get_wait_states(const char **states
)
5334 for (i
=0; i
<MAX_STATE
; i
++)
5335 states
[i
] = lxc_state2str(i
);
5341 * These next two could probably be done smarter with reusing a common function
5342 * with different iterators and tests...
5344 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5347 int i
, cfound
= 0, nfound
= 0;
5348 struct dirent
*direntp
;
5349 struct lxc_container
*c
;
5352 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5354 dir
= opendir(lxcpath
);
5356 SYSERROR("opendir on lxcpath");
5366 while ((direntp
= readdir(dir
))) {
5367 /* Ignore '.', '..' and any hidden directory. */
5368 if (!strncmp(direntp
->d_name
, ".", 1))
5371 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5375 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5385 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5387 INFO("Container %s:%s has a config but could not be loaded",
5388 lxcpath
, direntp
->d_name
);
5391 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5397 if (!do_lxcapi_is_defined(c
)) {
5398 INFO("Container %s:%s has a config but is not defined",
5399 lxcpath
, direntp
->d_name
);
5402 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5405 lxc_container_put(c
);
5409 if (!add_to_clist(cret
, c
, nfound
, true)) {
5410 lxc_container_put(c
);
5421 if (names
&& *names
) {
5422 for (i
=0; i
<cfound
; i
++)
5427 if (cret
&& *cret
) {
5428 for (i
=0; i
<nfound
; i
++)
5429 lxc_container_put((*cret
)[i
]);
5437 int list_active_containers(const char *lxcpath
, char ***nret
,
5438 struct lxc_container
***cret
)
5440 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5443 char **ct_name
= NULL
;
5445 struct lxc_container
*c
= NULL
;
5449 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5450 lxcpath_len
= strlen(lxcpath
);
5458 FILE *f
= fopen("/proc/net/unix", "r");
5462 while (getline(&line
, &len
, f
) != -1) {
5463 char *p
= strrchr(line
, ' '), *p2
;
5474 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5476 } else if (strncmp(p
, "lxc/", 4) == 0) {
5486 /* Now p is the start of lxc_name. */
5487 p2
= strchr(p
, '/');
5488 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5493 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5497 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5503 p
= lxc_cmd_get_name(p
);
5508 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5514 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5517 goto free_cret_list
;
5528 c
= lxc_container_new(p
, lxcpath
);
5530 INFO("Container %s:%s is running but could not be loaded",
5533 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5544 * If this is an anonymous container, then is_defined *can*
5545 * return false. So we don't do that check. Count on the
5546 * fact that the command socket exists.
5549 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5550 lxc_container_put(c
);
5551 goto free_cret_list
;
5557 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5559 lxc_container_put(c
);
5560 goto free_cret_list
;
5572 if (cret
&& *cret
) {
5573 for (i
= 0; i
< cret_cnt
; i
++)
5574 lxc_container_put((*cret
)[i
]);
5580 for (i
= 0; i
< ct_name_cnt
; i
++)
5591 int list_all_containers(const char *lxcpath
, char ***nret
,
5592 struct lxc_container
***cret
)
5594 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5597 struct lxc_container
**ct_list
= NULL
;
5599 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5603 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5604 if (active_cnt
< 0) {
5609 for (i
= 0; i
< active_cnt
; i
++) {
5610 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5611 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5613 goto free_active_name
;
5619 free(active_name
[i
]);
5620 active_name
[i
] = NULL
;
5627 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5628 struct lxc_container
*c
;
5630 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5632 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5633 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5637 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5638 lxc_container_put(c
);
5659 for (i
= 0; i
< ct_list_cnt
; i
++) {
5660 lxc_container_put(ct_list
[i
]);
5665 for (i
= 0; i
< active_cnt
; i
++) {
5666 free(active_name
[i
]);
5671 for (i
= 0; i
< ct_cnt
; i
++) {
5678 bool lxc_config_item_is_supported(const char *key
)
5680 return !!lxc_get_config(key
);
5683 bool lxc_has_api_extension(const char *extension
)
5685 /* The NULL API extension is always present. :) */
5689 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5690 if (strcmp(api_extensions
[i
], extension
) == 0)