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
)
533 s
= lxc_getstate(c
->name
, c
->config_path
);
535 ret
= lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
);
543 WRAP_API(bool, lxcapi_freeze
)
545 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
553 s
= lxc_getstate(c
->name
, c
->config_path
);
555 ret
= lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
);
563 WRAP_API(bool, lxcapi_unfreeze
)
565 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
570 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
573 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
575 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
576 int stdoutfd
, int stderrfd
, int escape
)
583 current_config
= c
->lxc_conf
;
584 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
585 current_config
= NULL
;
590 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
597 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
600 NOTICE("The console log is empty");
601 else if (ret
== -EFAULT
)
602 NOTICE("The container does not keep a console log");
603 else if (ret
== -ENOENT
)
604 NOTICE("The container does not keep a console log file");
605 else if (ret
== -EIO
)
606 NOTICE("Failed to write console log to log file");
608 ERROR("Failed to retrieve console log");
614 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
616 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
621 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
624 WRAP_API(pid_t
, lxcapi_init_pid
)
626 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
629 c
->lxc_conf
= lxc_conf_init();
634 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
637 c
->lxc_conf
->name
= c
->name
;
641 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
645 bool need_disklock
= false, ret
= false;
650 fname
= c
->configfile
;
658 /* If we're reading something other than the container's config, we only
659 * need to lock the in-memory container. If loading the container's
660 * config file, take the disk lock.
662 if (strcmp(fname
, c
->configfile
) == 0)
663 need_disklock
= true;
666 lret
= container_disk_lock(c
);
668 lret
= container_mem_lock(c
);
672 ret
= load_config_locked(c
, fname
);
675 container_disk_unlock(c
);
677 container_mem_unlock(c
);
682 WRAP_API_1(bool, lxcapi_load_config
, const char *)
684 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
686 if (!c
|| !c
->lxc_conf
)
689 if (container_mem_lock(c
))
692 c
->daemonize
= state
;
694 container_mem_unlock(c
);
699 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
701 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
703 if (!c
|| !c
->lxc_conf
)
706 if (container_mem_lock(c
))
709 c
->lxc_conf
->close_all_fds
= state
;
711 container_mem_unlock(c
);
716 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
718 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
726 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
730 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
732 static bool am_single_threaded(void)
735 struct dirent
*direntp
;
738 dir
= opendir("/proc/self/task");
742 while ((direntp
= readdir(dir
))) {
743 if (strcmp(direntp
->d_name
, ".") == 0)
746 if (strcmp(direntp
->d_name
, "..") == 0)
758 static void push_arg(char ***argp
, char *arg
, int *nargs
)
763 copy
= must_copy_string(arg
);
766 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
775 static char **split_init_cmd(const char *incmd
)
785 len
= strlen(incmd
) + 1;
787 retlen
= strlcpy(copy
, incmd
, len
);
792 argv
= malloc(sizeof(char *));
796 lxc_iterate_parts(p
, copy
, " ")
797 push_arg(&argv
, p
, &nargs
);
807 static void free_init_cmd(char **argv
)
820 static int lxc_rcv_status(int state_socket
)
826 /* Receive container state. */
827 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
832 TRACE("Caught EINTR; retrying");
839 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
843 /* Close write end of the socket pair. */
844 close(handler
->state_socket_pair
[1]);
845 handler
->state_socket_pair
[1] = -1;
847 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
849 /* Close read end of the socket pair. */
850 close(handler
->state_socket_pair
[0]);
851 handler
->state_socket_pair
[0] = -1;
853 /* The first child is going to fork() again and then exits. So we reap
854 * the first child here.
856 ret
= wait_for_pid(pid
);
858 DEBUG("Failed waiting on first child %d", pid
);
860 DEBUG("First child %d exited", pid
);
863 SYSERROR("Failed to receive the container state");
867 /* If we receive anything else then running we know that the container
870 if (state
!= RUNNING
) {
871 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
872 lxc_state2str(state
));
876 TRACE("Container is in \"RUNNING\" state");
880 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
883 struct lxc_handler
*handler
;
884 struct lxc_conf
*conf
;
885 char *default_args
[] = {
889 char **init_cmd
= NULL
;
890 int keepfds
[3] = {-1, -1, -1};
892 /* container does exist */
896 /* If anything fails before we set error_num, we want an error in there.
900 /* Container has not been setup. */
904 ret
= ongoing_create(c
);
906 ERROR("Failed checking for incomplete container creation");
908 } else if (ret
== 1) {
909 ERROR("Ongoing container creation detected");
911 } else if (ret
== 2) {
912 ERROR("Failed to create container");
913 do_lxcapi_destroy(c
);
917 if (container_mem_lock(c
))
922 /* initialize handler */
923 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
925 container_mem_unlock(c
);
930 if (useinit
&& conf
->execute_cmd
)
931 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
933 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
936 /* ... otherwise use default_args. */
939 ERROR("No valid init detected");
940 lxc_free_handler(handler
);
946 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
947 * here to protect the on disk container? We don't want to exclude
948 * things like lxc_info while the container is running.
957 free_init_cmd(init_cmd
);
958 lxc_free_handler(handler
);
964 /* Set to NULL because we don't want father unlink
965 * the PID file, child will do the free and unlink.
969 /* Wait for container to tell us whether it started
972 started
= wait_on_daemonized_start(handler
, pid
);
974 free_init_cmd(init_cmd
);
975 lxc_free_handler(handler
);
981 /* We don't really care if this doesn't print all the
982 * characters. All that it means is that the proctitle will be
983 * ugly. Similarly, we also don't care if setproctitle() fails.
985 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
987 ret
= setproctitle(title
);
989 INFO("Failed to set process title to %s", title
);
991 INFO("Set process title to %s", title
);
994 /* We fork() a second time to be reparented to init. Like
995 * POSIX's daemon() function we change to "/" and redirect
996 * std{in,out,err} to /dev/null.
1000 SYSERROR("Failed to fork first child process");
1001 _exit(EXIT_FAILURE
);
1006 free_init_cmd(init_cmd
);
1007 lxc_free_handler(handler
);
1008 _exit(EXIT_SUCCESS
);
1013 /* change to / directory */
1016 SYSERROR("Failed to change to \"/\" directory");
1017 _exit(EXIT_FAILURE
);
1020 keepfds
[0] = handler
->conf
->maincmd_fd
;
1021 keepfds
[1] = handler
->state_socket_pair
[0];
1022 keepfds
[2] = handler
->state_socket_pair
[1];
1023 ret
= lxc_check_inherited(conf
, true, keepfds
,
1024 sizeof(keepfds
) / sizeof(keepfds
[0]));
1026 _exit(EXIT_FAILURE
);
1028 /* redirect std{in,out,err} to /dev/null */
1029 ret
= null_stdfds();
1031 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1032 _exit(EXIT_FAILURE
);
1035 /* become session leader */
1038 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1039 } else if (!am_single_threaded()) {
1040 ERROR("Cannot start non-daemonized container when threaded");
1041 free_init_cmd(init_cmd
);
1042 lxc_free_handler(handler
);
1046 /* We need to write PID file after daemonize, so we always write the
1051 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1053 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1054 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1055 free_init_cmd(init_cmd
);
1056 lxc_free_handler(handler
);
1058 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1061 _exit(EXIT_FAILURE
);
1066 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1068 free_init_cmd(init_cmd
);
1069 lxc_free_handler(handler
);
1071 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1074 _exit(EXIT_FAILURE
);
1080 conf
->reboot
= REBOOT_NONE
;
1082 /* Unshare the mount namespace if requested */
1083 if (conf
->monitor_unshare
) {
1084 ret
= unshare(CLONE_NEWNS
);
1086 SYSERROR("Failed to unshare mount namespace");
1087 lxc_free_handler(handler
);
1092 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1094 SYSERROR("Failed to make / rslave at startup");
1095 lxc_free_handler(handler
);
1102 if (conf
->reboot
== REBOOT_INIT
) {
1103 /* initialize handler */
1104 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1111 keepfds
[0] = handler
->conf
->maincmd_fd
;
1112 keepfds
[1] = handler
->state_socket_pair
[0];
1113 keepfds
[2] = handler
->state_socket_pair
[1];
1114 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1115 sizeof(keepfds
) / sizeof(keepfds
[0]));
1117 lxc_free_handler(handler
);
1123 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1124 c
->daemonize
, &c
->error_num
);
1126 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1127 c
->daemonize
, &c
->error_num
);
1129 if (conf
->reboot
== REBOOT_REQ
) {
1130 INFO("Container requested reboot");
1131 conf
->reboot
= REBOOT_INIT
;
1141 free_init_cmd(init_cmd
);
1143 if (c
->daemonize
&& ret
!= 0)
1144 _exit(EXIT_FAILURE
);
1145 else if (c
->daemonize
)
1146 _exit(EXIT_SUCCESS
);
1154 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1159 current_config
= c
? c
->lxc_conf
: NULL
;
1160 ret
= do_lxcapi_start(c
, useinit
, argv
);
1161 current_config
= NULL
;
1166 /* Note, there MUST be an ending NULL. */
1167 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1170 char **inargs
= NULL
;
1173 /* container exists */
1177 current_config
= c
->lxc_conf
;
1179 va_start(ap
, useinit
);
1180 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1185 /* pass NULL if no arguments were supplied */
1186 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1192 for (arg
= inargs
; *arg
; arg
++)
1197 current_config
= NULL
;
1202 static bool do_lxcapi_stop(struct lxc_container
*c
)
1209 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1214 WRAP_API(bool, lxcapi_stop
)
1216 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1223 mode_t mask
= umask(0002);
1224 ret
= mkdir(path
, 0770);
1229 if (errno
!= EEXIST
)
1236 p
= alloca(len
+ 1);
1237 (void)strlcpy(p
, path
, len
+ 1);
1239 if (!lxc_list_empty(&conf
->id_map
)) {
1240 ret
= chown_mapped_root(p
, conf
);
1248 /* Create the standard expected container dir. */
1249 static bool create_container_dir(struct lxc_container
*c
)
1255 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1260 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1261 if (ret
< 0 || (size_t)ret
>= len
) {
1266 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1272 /* do_storage_create: thin wrapper around storage_create(). Like
1273 * storage_create(), it returns a mounted bdev on success, NULL on error.
1275 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1277 struct bdev_specs
*specs
)
1282 struct lxc_storage
*bdev
;
1284 /* rootfs.path or lxcpath/lxcname/rootfs */
1285 if (c
->lxc_conf
->rootfs
.path
&&
1286 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1287 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1288 len
= strlen(rpath
) + 1;
1290 ret
= snprintf(dest
, len
, "%s", rpath
);
1292 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1293 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1295 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1297 if (ret
< 0 || (size_t)ret
>= len
)
1300 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1302 ERROR("Failed to create \"%s\" storage", type
);
1306 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1307 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1311 /* If we are not root, chown the rootfs dir to root in the target user
1315 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1316 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1318 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1319 suggest_default_idmap();
1328 static char *lxcbasename(char *path
)
1332 p
= path
+ strlen(path
) - 1;
1333 while (*p
!= '/' && p
> path
)
1339 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1340 bool need_null_stdfds
, char *const argv
[])
1350 SYSERROR("Failed to fork task for container creation template");
1354 if (pid
== 0) { /* child */
1356 char *namearg
, *patharg
, *rootfsarg
;
1359 struct lxc_storage
*bdev
= NULL
;
1360 struct lxc_conf
*conf
= c
->lxc_conf
;
1363 if (need_null_stdfds
) {
1364 ret
= null_stdfds();
1366 _exit(EXIT_FAILURE
);
1369 bdev
= storage_init(c
->lxc_conf
);
1371 ERROR("Failed to initialize storage");
1372 _exit(EXIT_FAILURE
);
1377 ret
= unshare(CLONE_NEWNS
);
1379 ERROR("Failed to unshare CLONE_NEWNS");
1380 _exit(EXIT_FAILURE
);
1383 ret
= detect_shared_rootfs();
1385 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1387 SYSERROR("Failed to make \"/\" rslave");
1388 ERROR("Continuing...");
1393 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1395 ERROR("Unprivileged users can only create "
1396 "btrfs and directory-backed containers");
1397 _exit(EXIT_FAILURE
);
1400 if (strcmp(bdev
->type
, "overlay") == 0 ||
1401 strcmp(bdev
->type
, "overlayfs") == 0) {
1402 /* If we create an overlay container we need to
1403 * rsync the contents into
1404 * <container-path>/<container-name>/rootfs.
1405 * However, the overlay mount function will
1407 * <container-path>/<container-name>/delta0
1409 * <container-path>/<container-name>/rootfs
1410 * which means we would rsync the rootfs into
1411 * the delta directory. That doesn't make sense
1412 * since the delta directory only exists to
1413 * record the differences to
1414 * <container-path>/<container-name>/rootfs. So
1415 * let's simply bind-mount here and then rsync
1417 * <container-path>/<container-name>/rootfs.
1421 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1423 ERROR("Failed to get rootfs");
1424 _exit(EXIT_FAILURE
);
1427 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1429 ERROR("Failed to mount rootfs");
1430 _exit(EXIT_FAILURE
);
1433 ret
= bdev
->ops
->mount(bdev
);
1435 ERROR("Failed to mount rootfs");
1436 _exit(EXIT_FAILURE
);
1439 } else { /* TODO come up with a better way here! */
1442 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1443 bdev
->dest
= strdup(src
);
1446 /* Create our new array, pre-pend the template name and base
1450 for (nargs
= 0; argv
[nargs
]; nargs
++)
1453 /* template, path, rootfs and name args */
1456 newargv
= malloc(nargs
* sizeof(*newargv
));
1458 _exit(EXIT_FAILURE
);
1459 newargv
[0] = lxcbasename(tpath
);
1462 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1463 patharg
= malloc(len
);
1465 _exit(EXIT_FAILURE
);
1467 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1468 if (ret
< 0 || ret
>= len
)
1469 _exit(EXIT_FAILURE
);
1470 newargv
[1] = patharg
;
1473 len
= strlen("--name=") + strlen(c
->name
) + 1;
1474 namearg
= malloc(len
);
1476 _exit(EXIT_FAILURE
);
1478 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1479 if (ret
< 0 || ret
>= len
)
1480 _exit(EXIT_FAILURE
);
1481 newargv
[2] = namearg
;
1484 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1485 rootfsarg
= malloc(len
);
1487 _exit(EXIT_FAILURE
);
1489 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1490 if (ret
< 0 || ret
>= len
)
1491 _exit(EXIT_FAILURE
);
1492 newargv
[3] = rootfsarg
;
1494 /* add passed-in args */
1496 for (i
= 4; i
< nargs
; i
++)
1497 newargv
[i
] = argv
[i
- 4];
1499 /* add trailing NULL */
1501 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1503 _exit(EXIT_FAILURE
);
1504 newargv
[nargs
- 1] = NULL
;
1506 /* If we're running the template in a mapped userns, then we
1507 * prepend the template command with: lxc-usernsexec <-m map1>
1508 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1509 * the mapped uid for our geteuid()
1511 if (!lxc_list_empty(&conf
->id_map
)) {
1512 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1514 char txtuid
[20], txtgid
[20];
1515 struct lxc_list
*it
;
1519 n2
= malloc(n2args
* sizeof(*n2
));
1521 _exit(EXIT_FAILURE
);
1524 tpath
= "lxc-usernsexec";
1525 n2
[0] = "lxc-usernsexec";
1527 lxc_list_for_each(it
, &conf
->id_map
) {
1530 n2
= realloc(n2
, n2args
* sizeof(char *));
1532 _exit(EXIT_FAILURE
);
1534 n2
[n2args
- 2] = "-m";
1535 n2
[n2args
- 1] = malloc(200);
1536 if (!n2
[n2args
- 1])
1537 _exit(EXIT_FAILURE
);
1539 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1540 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1541 map
->nsid
, map
->hostid
, map
->range
);
1542 if (ret
< 0 || ret
>= 200)
1543 _exit(EXIT_FAILURE
);
1546 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1547 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1549 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1551 _exit(EXIT_FAILURE
);
1553 if (hostuid_mapped
< 0) {
1554 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1555 n2
[n2args
++] = "-m";
1556 if (hostuid_mapped
< 0) {
1557 ERROR("Failed to find free uid to map");
1558 _exit(EXIT_FAILURE
);
1561 n2
[n2args
++] = malloc(200);
1562 if (!n2
[n2args
- 1]) {
1563 SYSERROR("out of memory");
1564 _exit(EXIT_FAILURE
);
1567 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1568 hostuid_mapped
, geteuid());
1569 if (ret
< 0 || ret
>= 200)
1570 _exit(EXIT_FAILURE
);
1573 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1574 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1576 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1578 _exit(EXIT_FAILURE
);
1580 if (hostgid_mapped
< 0) {
1581 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1582 n2
[n2args
++] = "-m";
1583 if (hostgid_mapped
< 0) {
1584 ERROR("Failed to find free gid to map");
1585 _exit(EXIT_FAILURE
);
1588 n2
[n2args
++] = malloc(200);
1589 if (!n2
[n2args
- 1]) {
1590 SYSERROR("out of memory");
1591 _exit(EXIT_FAILURE
);
1594 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1595 hostgid_mapped
, getegid());
1596 if (ret
< 0 || ret
>= 200)
1597 _exit(EXIT_FAILURE
);
1600 n2
[n2args
++] = "--";
1602 for (i
= 0; i
< nargs
; i
++)
1603 n2
[i
+ n2args
] = newargv
[i
];
1606 /* Finally add "--mapped-uid $uid" to tell template what
1607 * to chown cached images to.
1610 n2
= realloc(n2
, n2args
* sizeof(char *));
1612 _exit(EXIT_FAILURE
);
1614 /* note n2[n2args-1] is NULL */
1615 n2
[n2args
- 5] = "--mapped-uid";
1617 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1618 if (ret
< 0 || ret
>= 20) {
1621 _exit(EXIT_FAILURE
);
1624 n2
[n2args
- 4] = txtuid
;
1625 n2
[n2args
- 3] = "--mapped-gid";
1627 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1628 if (ret
< 0 || ret
>= 20) {
1631 _exit(EXIT_FAILURE
);
1634 n2
[n2args
- 2] = txtgid
;
1635 n2
[n2args
- 1] = NULL
;
1640 execvp(tpath
, newargv
);
1641 SYSERROR("Failed to execute template %s", tpath
);
1642 _exit(EXIT_FAILURE
);
1645 ret
= wait_for_pid(pid
);
1647 ERROR("Failed to create container from template");
1654 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1663 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1667 f
= fopen(path
, "r");
1671 ret
= fseek(f
, 0, SEEK_END
);
1680 ret
= fseek(f
, 0, SEEK_SET
);
1684 ret
= fseek(f
, 0, SEEK_SET
);
1689 contents
= malloc(flen
+ 1);
1693 len
= fread(contents
, 1, flen
, f
);
1695 goto out_free_contents
;
1697 contents
[flen
] = '\0';
1702 goto out_free_contents
;
1705 tpath
= get_template_path(t
);
1707 ERROR("Invalid template \"%s\" specified", t
);
1708 goto out_free_contents
;
1711 ret
= sha1sum_file(tpath
, md_value
);
1713 ERROR("Failed to get sha1sum of %s", tpath
);
1715 goto out_free_contents
;
1720 f
= fopen(path
, "w");
1722 SYSERROR("Reopening config for writing");
1727 fprintf(f
, "# Template used to create this container: %s\n", t
);
1729 fprintf(f
, "# Parameters passed to the template:");
1731 fprintf(f
, " %s", *argv
);
1738 fprintf(f
, "# Template script checksum (SHA-1): ");
1739 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1740 fprintf(f
, "%02x", md_value
[i
]);
1743 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1744 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1745 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1746 fprintf(f
, "# (Be aware this has security implications)\n\n");
1747 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1748 SYSERROR("Writing original contents");
1768 SYSERROR("Error prepending header");
1775 static void lxcapi_clear_config(struct lxc_container
*c
)
1777 if (!c
|| !c
->lxc_conf
)
1780 lxc_conf_free(c
->lxc_conf
);
1784 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1788 * create a container with the given parameters.
1789 * @c: container to be created. It has the lxcpath, name, and a starting
1790 * configuration already set
1791 * @t: the template to execute to instantiate the root filesystem and
1792 * adjust the configuration.
1793 * @bdevtype: backing store type to use. If NULL, dir will be used.
1794 * @specs: additional parameters for the backing store, i.e. LVM vg to
1797 * @argv: the arguments to pass to the template, terminated by NULL. If no
1798 * arguments, you can just pass NULL.
1800 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1801 const char *bdevtype
, struct bdev_specs
*specs
,
1802 int flags
, char *const argv
[])
1807 bool ret
= false, rootfs_managed
= true;
1814 tpath
= get_template_path(t
);
1816 ERROR("Unknown template \"%s\"", t
);
1821 /* If a template is passed in, and the rootfs already is defined in the
1822 * container config and exists, then the caller is trying to create an
1823 * existing container. Return an error, but do NOT delete the container.
1825 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1826 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1827 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1833 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1834 ERROR("Error loading default configuration file %s",
1835 lxc_global_config_value("lxc.default_config"));
1840 if (!create_container_dir(c
))
1843 if (c
->lxc_conf
->rootfs
.path
)
1844 rootfs_managed
= false;
1846 /* If both template and rootfs.path are set, template is setup as
1847 * rootfs.path. The container is already created if we have a config and
1848 * rootfs.path is accessible
1850 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1851 /* No template passed in and rootfs does not exist. */
1852 if (!c
->save_config(c
, NULL
)) {
1853 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1860 /* Rootfs passed into configuration, but does not exist. */
1861 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1864 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1865 /* Rootfs already existed, user just wanted to save the loaded
1868 if (!c
->save_config(c
, NULL
))
1869 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1875 /* Mark that this container is being created */
1876 partial_fd
= create_partial(c
);
1880 /* No need to get disk lock bc we have the partial lock. */
1884 /* Create the storage.
1885 * Note we can't do this in the same task as we use to execute the
1886 * template because of the way zfs works.
1887 * After you 'zfs create', zfs mounts the fs only in the initial
1892 SYSERROR("Failed to fork task for container creation template");
1896 if (pid
== 0) { /* child */
1897 struct lxc_storage
*bdev
= NULL
;
1899 bdev
= do_storage_create(c
, bdevtype
, specs
);
1901 ERROR("Failed to create %s storage for %s",
1902 bdevtype
? bdevtype
: "(none)", c
->name
);
1903 _exit(EXIT_FAILURE
);
1906 /* Save config file again to store the new rootfs location. */
1907 if (!do_lxcapi_save_config(c
, NULL
)) {
1908 ERROR("Failed to save initial config for %s", c
->name
);
1909 /* Parent task won't see the storage driver in the
1910 * config so we delete it.
1912 bdev
->ops
->umount(bdev
);
1913 bdev
->ops
->destroy(bdev
);
1914 _exit(EXIT_FAILURE
);
1917 _exit(EXIT_SUCCESS
);
1920 if (wait_for_pid(pid
) != 0)
1923 /* Reload config to get the rootfs. */
1924 lxc_conf_free(c
->lxc_conf
);
1927 if (!load_config_locked(c
, c
->configfile
))
1930 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1933 /* Now clear out the lxc_conf we have, reload from the created
1936 do_lxcapi_clear_config(c
);
1939 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1940 ERROR("Failed to prepend header to config file");
1945 ret
= load_config_locked(c
, c
->configfile
);
1949 remove_partial(c
, partial_fd
);
1953 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1956 * Ensure that we don't destroy storage we didn't create
1959 if (!rootfs_managed
)
1960 c
->lxc_conf
->rootfs
.managed
= false;
1961 container_destroy(c
, NULL
);
1962 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1970 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1971 const char *bdevtype
, struct bdev_specs
*specs
,
1972 int flags
, char *const argv
[])
1976 current_config
= c
? c
->lxc_conf
: NULL
;
1978 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1979 current_config
= NULL
;
1983 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1987 int rebootsignal
= SIGINT
;
1992 if (!do_lxcapi_is_running(c
))
1995 pid
= do_lxcapi_init_pid(c
);
1999 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2000 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2002 ret
= kill(pid
, rebootsignal
);
2004 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2011 WRAP_API(bool, lxcapi_reboot
)
2013 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
2017 int rebootsignal
= SIGINT
, state_client_fd
= -1;
2018 lxc_state_t states
[MAX_STATE
] = {0};
2023 if (!do_lxcapi_is_running(c
))
2026 pid
= do_lxcapi_init_pid(c
);
2030 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2031 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2033 /* Add a new state client before sending the shutdown signal so that we
2034 * don't miss a state.
2037 states
[RUNNING
] = 2;
2038 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2043 if (state_client_fd
< 0)
2049 if (ret
< MAX_STATE
)
2053 /* Send reboot signal to container. */
2054 killret
= kill(pid
, rebootsignal
);
2056 if (state_client_fd
>= 0)
2057 close(state_client_fd
);
2059 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2062 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2067 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2068 close(state_client_fd
);
2072 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2079 WRAP_API_1(bool, lxcapi_reboot2
, int)
2081 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2085 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2086 lxc_state_t states
[MAX_STATE
] = {0};
2091 if (!do_lxcapi_is_running(c
))
2094 pid
= do_lxcapi_init_pid(c
);
2098 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2099 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2100 haltsignal
= c
->lxc_conf
->haltsignal
;
2101 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2102 haltsignal
= (SIGRTMIN
+ 3);
2104 /* Add a new state client before sending the shutdown signal so that we
2105 * don't miss a state.
2108 states
[STOPPED
] = 1;
2109 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2114 if (state_client_fd
< 0)
2120 if (ret
< MAX_STATE
)
2124 /* Send shutdown signal to container. */
2125 killret
= kill(pid
, haltsignal
);
2127 if (state_client_fd
>= 0)
2128 close(state_client_fd
);
2130 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2133 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2138 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2139 close(state_client_fd
);
2143 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2150 WRAP_API_1(bool, lxcapi_shutdown
, int)
2152 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2153 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2162 current_config
= c
->lxc_conf
;
2165 * since we're going to wait for create to finish, I don't think we
2166 * need to get a copy of the arguments.
2168 va_start(ap
, flags
);
2169 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2172 ERROR("Failed to allocate memory");
2176 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2180 current_config
= NULL
;
2184 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2186 if (!strcmp(key
, "lxc.cgroup"))
2187 return clear_unexp_config_line(conf
, key
, true);
2189 if (!strcmp(key
, "lxc.network"))
2190 return clear_unexp_config_line(conf
, key
, true);
2192 if (!strcmp(key
, "lxc.net"))
2193 return clear_unexp_config_line(conf
, key
, true);
2195 /* Clear a network with a specific index. */
2196 if (!strncmp(key
, "lxc.net.", 8)) {
2201 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2203 return clear_unexp_config_line(conf
, key
, true);
2206 if (!strcmp(key
, "lxc.hook"))
2207 return clear_unexp_config_line(conf
, key
, true);
2209 return clear_unexp_config_line(conf
, key
, false);
2212 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2216 struct lxc_config_t
*config
;
2218 if (!c
|| !c
->lxc_conf
)
2221 if (container_mem_lock(c
))
2224 config
= lxc_get_config(key
);
2225 /* Verify that the config key exists and that it has a callback
2228 if (config
&& config
->clr
)
2229 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2232 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2234 container_mem_unlock(c
);
2238 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2240 static inline bool enter_net_ns(struct lxc_container
*c
)
2242 pid_t pid
= do_lxcapi_init_pid(c
);
2244 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2245 (access("/proc/self/ns/user", F_OK
) == 0))
2246 if (!switch_to_ns(pid
, "user"))
2249 return switch_to_ns(pid
, "net");
2252 /* Used by qsort and bsearch functions for comparing names. */
2253 static inline int string_cmp(char **first
, char **second
)
2255 return strcmp(*first
, *second
);
2258 /* Used by qsort and bsearch functions for comparing container names. */
2259 static inline int container_cmp(struct lxc_container
**first
,
2260 struct lxc_container
**second
)
2262 return strcmp((*first
)->name
, (*second
)->name
);
2265 static bool add_to_array(char ***names
, char *cname
, int pos
)
2267 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2269 ERROR("Out of memory");
2274 newnames
[pos
] = strdup(cname
);
2278 /* Sort the array as we will use binary search on it. */
2279 qsort(newnames
, pos
+ 1, sizeof(char *),
2280 (int (*)(const void *, const void *))string_cmp
);
2285 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2288 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2290 ERROR("Out of memory");
2297 /* Sort the array as we will use binary search on it. */
2299 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2300 (int (*)(const void *, const void *))container_cmp
);
2305 static char** get_from_array(char ***names
, char *cname
, int size
)
2307 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2310 static bool array_contains(char ***names
, char *cname
, int size
)
2312 if(get_from_array(names
, cname
, size
) != NULL
)
2318 static bool remove_from_array(char ***names
, char *cname
, int size
)
2320 char **result
= get_from_array(names
, cname
, size
);
2321 if (result
!= NULL
) {
2329 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2332 int i
, count
= 0, pipefd
[2];
2333 char **interfaces
= NULL
;
2334 char interface
[IFNAMSIZ
];
2336 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2341 SYSERROR("Failed to fork task to get interfaces information");
2347 if (pid
== 0) { /* child */
2348 int ret
= 1, nbytes
;
2349 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2351 /* close the read-end of the pipe */
2354 if (!enter_net_ns(c
)) {
2355 SYSERROR("Failed to enter network namespace");
2359 /* Grab the list of interfaces */
2360 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2361 SYSERROR("Failed to get interfaces list");
2365 /* Iterate through the interfaces */
2366 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2367 tempIfAddr
= tempIfAddr
->ifa_next
) {
2368 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2379 netns_freeifaddrs(interfaceArray
);
2381 /* close the write-end of the pipe, thus sending EOF to the reader */
2386 /* close the write-end of the pipe */
2389 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2390 interface
[IFNAMSIZ
- 1] = '\0';
2392 if (array_contains(&interfaces
, interface
, count
))
2395 if (!add_to_array(&interfaces
, interface
, count
))
2396 ERROR("Failed to add \"%s\" to array", interface
);
2401 if (wait_for_pid(pid
) != 0) {
2402 for (i
= 0; i
< count
; i
++)
2403 free(interfaces
[i
]);
2409 /* close the read-end of the pipe */
2412 /* Append NULL to the array */
2414 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2419 WRAP_API(char **, lxcapi_get_interfaces
)
2421 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2422 const char *family
, int scope
)
2427 char address
[INET6_ADDRSTRLEN
];
2429 char **addresses
= NULL
;
2431 ret
= pipe2(pipefd
, O_CLOEXEC
);
2433 SYSERROR("Failed to create pipe");
2439 SYSERROR("Failed to create new process");
2447 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2449 char *address
= NULL
;
2450 void *tempAddrPtr
= NULL
;
2451 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2453 /* close the read-end of the pipe */
2456 if (!enter_net_ns(c
)) {
2457 SYSERROR("Failed to attach to network namespace");
2461 /* Grab the list of interfaces */
2462 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2463 SYSERROR("Failed to get interfaces list");
2467 /* Iterate through the interfaces */
2468 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2469 tempIfAddr
= tempIfAddr
->ifa_next
) {
2470 if (tempIfAddr
->ifa_addr
== NULL
)
2473 #pragma GCC diagnostic push
2474 #pragma GCC diagnostic ignored "-Wcast-align"
2476 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2477 if (family
&& strcmp(family
, "inet"))
2480 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2482 if (family
&& strcmp(family
, "inet6"))
2485 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2488 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2491 #pragma GCC diagnostic pop
2493 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2495 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2498 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2499 tempAddrPtr
, addressOutputBuffer
,
2500 sizeof(addressOutputBuffer
));
2504 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2505 if (nbytes
!= INET6_ADDRSTRLEN
) {
2506 SYSERROR("Failed to send ipv6 address \"%s\"",
2518 netns_freeifaddrs(interfaceArray
);
2520 /* close the write-end of the pipe, thus sending EOF to the reader */
2525 /* close the write-end of the pipe */
2528 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2529 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2531 if (!add_to_array(&addresses
, address
, count
))
2532 ERROR("PARENT: add_to_array failed");
2537 if (wait_for_pid(pid
) != 0) {
2538 for (i
= 0; i
< count
; i
++)
2545 /* close the read-end of the pipe */
2548 /* Append NULL to the array */
2550 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2555 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2557 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2560 struct lxc_config_t
*config
;
2562 if (!c
|| !c
->lxc_conf
)
2565 if (container_mem_lock(c
))
2568 config
= lxc_get_config(key
);
2569 /* Verify that the config key exists and that it has a callback
2572 if (config
&& config
->get
)
2573 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2575 container_mem_unlock(c
);
2579 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2581 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2585 if (!c
|| !c
->lxc_conf
)
2588 if (container_mem_lock(c
))
2591 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2592 container_mem_unlock(c
);
2596 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2598 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2602 /* List all config items. */
2604 return lxc_list_config_items(retv
, inlen
);
2606 if (!c
|| !c
->lxc_conf
)
2609 if (container_mem_lock(c
))
2612 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2613 * This is an intelligent result to show which keys are valid given the
2614 * type of nic it is.
2616 if (strncmp(key
, "lxc.net.", 8) == 0)
2617 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2619 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2621 container_mem_unlock(c
);
2625 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2627 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2630 bool ret
= false, need_disklock
= false;
2633 alt_file
= c
->configfile
;
2638 /* If we haven't yet loaded a config, load the stock config. */
2640 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2641 ERROR("Error loading default configuration file %s "
2643 lxc_global_config_value("lxc.default_config"),
2649 if (!create_container_dir(c
))
2652 /* If we're writing to the container's config file, take the disk lock.
2653 * Otherwise just take the memlock to protect the struct lxc_container
2654 * while we're traversing it.
2656 if (strcmp(c
->configfile
, alt_file
) == 0)
2657 need_disklock
= true;
2660 lret
= container_disk_lock(c
);
2662 lret
= container_mem_lock(c
);
2666 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2667 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2671 lret
= write_config(fd
, c
->lxc_conf
);
2680 container_disk_unlock(c
);
2682 container_mem_unlock(c
);
2687 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2690 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2696 char path
[PATH_MAX
];
2697 char newpath
[PATH_MAX
];
2698 int fd
, ret
, n
= 0, v
= 0;
2700 size_t len
= 0, bytes
= 0;
2702 if (container_disk_lock(c0
))
2705 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2706 if (ret
< 0 || ret
> PATH_MAX
)
2709 ret
= snprintf(newpath
, PATH_MAX
, "%s\n%s\n", c
->config_path
, c
->name
);
2710 if (ret
< 0 || ret
> PATH_MAX
)
2713 /* If we find an lxc-snapshot file using the old format only listing the
2714 * number of snapshots we will keep using it. */
2715 f1
= fopen(path
, "r");
2717 n
= fscanf(f1
, "%d", &v
);
2719 if (n
== 1 && v
== 0) {
2722 SYSERROR("Failed to remove \"%s\"", path
);
2730 f1
= fopen(path
, "w");
2734 if (fprintf(f1
, "%d\n", v
) < 0) {
2735 ERROR("Error writing new snapshots value");
2742 SYSERROR("Error writing to or closing snapshots file");
2746 /* Here we know that we have or can use an lxc-snapshot file
2747 * using the new format. */
2749 f1
= fopen(path
, "a");
2753 if (fprintf(f1
, "%s", newpath
) < 0) {
2754 ERROR("Error writing new snapshots entry");
2757 SYSERROR("Error writing to or closing snapshots file");
2763 SYSERROR("Error writing to or closing snapshots file");
2767 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2770 if (fstat(fd
, &fbuf
) < 0) {
2775 if (fbuf
.st_size
!= 0) {
2776 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2777 if (buf
== MAP_FAILED
) {
2778 SYSERROR("Failed to create mapping %s", path
);
2783 len
= strlen(newpath
);
2784 while ((del
= strstr((char *)buf
, newpath
))) {
2785 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2789 lxc_strmunmap(buf
, fbuf
.st_size
);
2790 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2791 SYSERROR("Failed to truncate file %s", path
);
2800 /* If the lxc-snapshot file is empty, remove it. */
2801 if (stat(path
, &fbuf
) < 0)
2804 if (!fbuf
.st_size
) {
2807 SYSERROR("Failed to remove \"%s\"", path
);
2814 container_disk_unlock(c0
);
2818 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2820 struct lxc_container
*p
;
2821 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[PATH_MAX
];
2822 size_t pathlen
= 0, namelen
= 0;
2826 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends",
2827 c
->config_path
, c
->name
);
2828 if (ret
< 0 || ret
>= PATH_MAX
) {
2829 ERROR("Path name too long");
2833 f
= fopen(path
, "r");
2837 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2838 if (getline(&lxcname
, &namelen
, f
) == -1) {
2839 ERROR("badly formatted file %s", path
);
2843 remove_trailing_newlines(lxcpath
);
2844 remove_trailing_newlines(lxcname
);
2846 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2847 ERROR("Unable to find dependent container %s:%s",
2852 if (!mod_rdep(p
, c
, inc
))
2853 ERROR("Failed to update snapshots file for %s:%s",
2856 lxc_container_put(p
);
2865 static bool has_fs_snapshots(struct lxc_container
*c
)
2868 char path
[PATH_MAX
];
2873 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c
->config_path
,
2875 if (ret
< 0 || ret
> PATH_MAX
)
2878 /* If the file doesn't exist there are no snapshots. */
2879 if (stat(path
, &fbuf
) < 0)
2884 f
= fopen(path
, "r");
2888 ret
= fscanf(f
, "%d", &v
);
2890 /* TODO: Figure out what to do with the return value of fscanf. */
2892 INFO("Container uses new lxc-snapshots format %s", path
);
2901 static bool has_snapshots(struct lxc_container
*c
)
2903 char path
[PATH_MAX
];
2904 struct dirent
*direntp
;
2908 if (!get_snappath_dir(c
, path
))
2911 dir
= opendir(path
);
2915 while ((direntp
= readdir(dir
))) {
2916 if (!strcmp(direntp
->d_name
, "."))
2919 if (!strcmp(direntp
->d_name
, ".."))
2929 static bool do_destroy_container(struct lxc_conf
*conf
) {
2932 if (am_guest_unpriv()) {
2933 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2934 "storage_destroy_wrapper");
2941 return storage_destroy(conf
);
2944 static int lxc_rmdir_onedev_wrapper(void *data
)
2946 char *arg
= (char *) data
;
2947 return lxc_rmdir_onedev(arg
, "snaps");
2950 static int lxc_unlink_exec_wrapper(void *data
)
2956 static bool container_destroy(struct lxc_container
*c
,
2957 struct lxc_storage
*storage
)
2961 struct lxc_conf
*conf
;
2966 if (!c
|| !do_lxcapi_is_defined(c
))
2970 if (container_disk_lock(c
))
2973 if (!is_stopped(c
)) {
2974 /* We should queue some sort of error - in c->error_string? */
2975 ERROR("container %s is not stopped", c
->name
);
2979 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2980 /* Start of environment variable setup for hooks */
2981 if (setenv("LXC_NAME", c
->name
, 1))
2982 SYSERROR("Failed to set environment variable for container name");
2984 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2985 SYSERROR("Failed to set environment variable for config path");
2987 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2988 SYSERROR("Failed to set environment variable for rootfs mount");
2990 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2991 SYSERROR("Failed to set environment variable for rootfs mount");
2993 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2994 SYSERROR("Failed to set environment variable for console path");
2996 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2997 SYSERROR("Failed to set environment variable for console log");
2998 /* End of environment variable setup for hooks */
3000 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
3001 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
3006 if (current_config
&& conf
== current_config
) {
3007 current_config
= NULL
;
3009 if (conf
->logfd
!= -1) {
3015 /* LXC is not managing the storage of the container. */
3016 if (conf
&& !conf
->rootfs
.managed
)
3019 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
3020 if (!do_destroy_container(conf
)) {
3021 ERROR("Error destroying rootfs for %s", c
->name
);
3024 INFO("Destroyed rootfs for %s", c
->name
);
3027 mod_all_rdeps(c
, false);
3029 p1
= do_lxcapi_get_config_path(c
);
3038 * strlen("config") = 6
3042 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3045 ERROR("Failed to allocate memory");
3049 /* For an overlay container the rootfs is considered immutable and
3050 * cannot be removed when restoring from a snapshot.
3052 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3053 !strcmp(storage
->type
, "overlayfs")) &&
3054 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3055 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3056 if (ret
< 0 || (size_t)ret
>= len
)
3059 if (am_guest_unpriv())
3060 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3061 "lxc_unlink_exec_wrapper");
3065 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3069 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3075 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3076 if (ret
< 0 || (size_t)ret
>= len
)
3079 if (am_guest_unpriv())
3080 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3081 "lxc_rmdir_onedev_wrapper");
3083 ret
= lxc_rmdir_onedev(path
, "snaps");
3085 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3089 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3098 container_disk_unlock(c
);
3102 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3104 if (!c
|| !lxcapi_is_defined(c
))
3107 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3108 if (has_snapshots(c
)) {
3109 ERROR("Container %s has snapshots; not removing", c
->name
);
3113 if (has_fs_snapshots(c
)) {
3114 ERROR("container %s has snapshots on its rootfs", c
->name
);
3119 return container_destroy(c
, NULL
);
3122 WRAP_API(bool, lxcapi_destroy
)
3124 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3126 if (!c
|| !lxcapi_is_defined(c
))
3129 if (!lxcapi_snapshot_destroy_all(c
)) {
3130 ERROR("Error deleting all snapshots");
3134 return lxcapi_destroy(c
);
3137 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3139 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3143 struct lxc_config_t
*config
;
3146 config
= lxc_get_config(key
);
3150 ret
= config
->set(key
, v
, conf
, NULL
);
3154 if (lxc_config_value_empty(v
))
3155 do_clear_unexp_config_line(conf
, key
);
3157 bret
= do_append_unexp_config_line(conf
, key
, v
);
3164 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3170 c
->lxc_conf
= lxc_conf_init();
3175 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3182 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3189 if (container_mem_lock(c
))
3192 b
= do_set_config_item_locked(c
, key
, v
);
3194 container_mem_unlock(c
);
3198 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3200 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3202 if (!c
|| !c
->configfile
)
3205 return strdup(c
->configfile
);
3208 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3210 if (!c
|| !c
->config_path
)
3213 return (const char *)(c
->config_path
);
3218 * Just recalculate the c->configfile based on the
3219 * c->config_path, which must be set.
3220 * The lxc_container must be locked or not yet public.
3222 static bool set_config_filename(struct lxc_container
*c
)
3227 if (!c
->config_path
)
3230 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3231 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3232 newpath
= malloc(len
);
3236 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3237 if (ret
< 0 || ret
>= len
) {
3238 fprintf(stderr
, "Error printing out config file name\n");
3243 free(c
->configfile
);
3244 c
->configfile
= newpath
;
3249 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3253 char *oldpath
= NULL
;
3258 if (container_mem_lock(c
))
3263 ERROR("Out of memory setting new lxc path");
3269 oldpath
= c
->config_path
;
3272 /* Since we've changed the config path, we have to change the
3273 * config file name too */
3274 if (!set_config_filename(c
)) {
3275 ERROR("Out of memory setting new config filename");
3277 free(c
->config_path
);
3278 c
->config_path
= oldpath
;
3284 container_mem_unlock(c
);
3288 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3290 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3293 struct cgroup_ops
*cgroup_ops
;
3301 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3305 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3307 cgroup_exit(cgroup_ops
);
3312 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3314 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3317 struct cgroup_ops
*cgroup_ops
;
3325 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3329 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3332 cgroup_exit(cgroup_ops
);
3337 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3339 const char *lxc_get_global_config_item(const char *key
)
3341 return lxc_global_config_value(key
);
3344 const char *lxc_get_version(void)
3349 static int copy_file(const char *old
, const char *new)
3356 if (file_exists(new)) {
3357 ERROR("copy destination %s exists", new);
3361 ret
= stat(old
, &sbuf
);
3363 INFO("Error stat'ing %s", old
);
3367 in
= open(old
, O_RDONLY
);
3369 SYSERROR("Error opening original file %s", old
);
3373 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3375 SYSERROR("Error opening new file %s", new);
3381 len
= lxc_read_nointr(in
, buf
, 8096);
3383 SYSERROR("Error reading old file %s", old
);
3390 ret
= lxc_write_nointr(out
, buf
, len
);
3391 if (ret
< len
) { /* should we retry? */
3392 SYSERROR("Error: write to new file %s was interrupted", new);
3400 /* We set mode, but not owner/group. */
3401 ret
= chmod(new, sbuf
.st_mode
);
3403 SYSERROR("Error setting mode on %s", new);
3415 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3418 struct lxc_list
*it
;
3421 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3422 cpath
= alloca(len
);
3423 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3424 if (ret
< 0 || ret
>= len
)
3427 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3428 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3429 char *hookname
= it
->elem
;
3430 char *fname
= strrchr(hookname
, '/');
3431 char tmppath
[PATH_MAX
];
3432 if (!fname
) /* relative path - we don't support, but maybe we should */
3435 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3436 /* this hook is public - ignore */
3440 /* copy the script, and change the entry in confile */
3441 ret
= snprintf(tmppath
, PATH_MAX
, "%s/%s/%s",
3442 c
->config_path
, c
->name
, fname
+1);
3443 if (ret
< 0 || ret
>= PATH_MAX
)
3446 ret
= copy_file(it
->elem
, tmppath
);
3452 it
->elem
= strdup(tmppath
);
3454 ERROR("out of memory copying hook path");
3460 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3461 c
->config_path
, oldc
->name
, c
->name
)) {
3462 ERROR("Error saving new hooks in clone");
3466 do_lxcapi_save_config(c
, NULL
);
3471 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3473 char newpath
[PATH_MAX
];
3474 char *oldpath
= oldc
->lxc_conf
->fstab
;
3480 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3482 char *p
= strrchr(oldpath
, '/');
3486 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s%s",
3487 c
->config_path
, c
->name
, p
);
3488 if (ret
< 0 || ret
>= PATH_MAX
) {
3489 ERROR("error printing new path for %s", oldpath
);
3493 if (file_exists(newpath
)) {
3494 ERROR("error: fstab file %s exists", newpath
);
3498 if (copy_file(oldpath
, newpath
) < 0) {
3499 ERROR("error: copying %s to %s", oldpath
, newpath
);
3503 free(c
->lxc_conf
->fstab
);
3505 c
->lxc_conf
->fstab
= strdup(newpath
);
3506 if (!c
->lxc_conf
->fstab
) {
3507 ERROR("error: allocating pathname");
3511 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3512 ERROR("error saving new lxctab");
3519 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3521 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3524 ret
= snprintf(path0
, PATH_MAX
, "%s/%s/lxc_rdepends", c0
->config_path
,
3526 if (ret
< 0 || ret
>= PATH_MAX
) {
3527 WARN("Error copying reverse dependencies");
3531 ret
= snprintf(path1
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3533 if (ret
< 0 || ret
>= PATH_MAX
) {
3534 WARN("Error copying reverse dependencies");
3538 if (copy_file(path0
, path1
) < 0) {
3539 INFO("Error copying reverse dependencies");
3544 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3547 char path
[PATH_MAX
];
3551 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3553 if (ret
< 0 || ret
>= PATH_MAX
)
3556 f
= fopen(path
, "a");
3562 /* If anything goes wrong, just return an error. */
3563 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3573 * If the fs natively supports snapshot clones with no penalty,
3574 * then default to those even if not requested.
3575 * Currently we only do this for btrfs.
3577 bool should_default_to_snapshot(struct lxc_container
*c0
,
3578 struct lxc_container
*c1
)
3581 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3582 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3583 char *p0
= alloca(l0
+ 1);
3584 char *p1
= alloca(l1
+ 1);
3585 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3587 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3588 if (ret
< 0 || ret
>= l0
)
3591 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3592 if (ret
< 0 || ret
>= l1
)
3595 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3598 if (is_btrfs_subvol(rootfs
) <= 0)
3601 return btrfs_same_fs(p0
, p1
) == 0;
3604 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3605 const char *newtype
, int flags
, const char *bdevdata
,
3608 struct lxc_storage
*bdev
;
3611 if (should_default_to_snapshot(c0
, c
))
3612 flags
|= LXC_CLONE_SNAPSHOT
;
3614 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3615 bdevdata
, newsize
, &need_rdep
);
3617 ERROR("Error copying storage.");
3621 /* Set new rootfs. */
3622 free(c
->lxc_conf
->rootfs
.path
);
3623 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3626 if (!c
->lxc_conf
->rootfs
.path
) {
3627 ERROR("Out of memory while setting storage path.");
3631 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3632 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3633 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3634 c
->lxc_conf
->rootfs
.path
)) {
3635 ERROR("Error saving new rootfs to cloned config.");
3639 if (flags
& LXC_CLONE_SNAPSHOT
)
3640 copy_rdepends(c
, c0
);
3643 if (!add_rdepends(c
, c0
))
3644 WARN("Error adding reverse dependency from %s to %s",
3648 mod_all_rdeps(c
, true);
3653 struct clone_update_data
{
3654 struct lxc_container
*c0
;
3655 struct lxc_container
*c1
;
3660 static int clone_update_rootfs(struct clone_update_data
*data
)
3662 struct lxc_container
*c0
= data
->c0
;
3663 struct lxc_container
*c
= data
->c1
;
3664 int flags
= data
->flags
;
3665 char **hookargs
= data
->hookargs
;
3667 char path
[PATH_MAX
];
3668 struct lxc_storage
*bdev
;
3670 struct lxc_conf
*conf
= c
->lxc_conf
;
3672 /* update hostname in rootfs */
3673 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3675 if (setgid(0) < 0) {
3676 ERROR("Failed to setgid to 0");
3680 if (setuid(0) < 0) {
3681 ERROR("Failed to setuid to 0");
3685 if (setgroups(0, NULL
) < 0)
3686 WARN("Failed to clear groups");
3688 if (unshare(CLONE_NEWNS
) < 0)
3691 bdev
= storage_init(c
->lxc_conf
);
3695 if (strcmp(bdev
->type
, "dir") != 0) {
3696 if (unshare(CLONE_NEWNS
) < 0) {
3697 ERROR("error unsharing mounts");
3702 if (detect_shared_rootfs()) {
3703 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3704 SYSERROR("Failed to make / rslave");
3705 ERROR("Continuing...");
3709 if (bdev
->ops
->mount(bdev
) < 0) {
3713 } else { /* TODO come up with a better way */
3715 bdev
->dest
= strdup(lxc_storage_get_path(bdev
->src
, bdev
->type
));
3718 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3719 /* Start of environment variable setup for hooks */
3720 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3721 SYSERROR("failed to set environment variable for source container name");
3723 if (setenv("LXC_NAME", c
->name
, 1))
3724 SYSERROR("failed to set environment variable for container name");
3726 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3727 SYSERROR("failed to set environment variable for config path");
3729 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3730 SYSERROR("failed to set environment variable for rootfs mount");
3732 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3733 SYSERROR("failed to set environment variable for rootfs mount");
3735 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3736 ERROR("Error executing clone hook for %s", c
->name
);
3742 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3743 ret
= snprintf(path
, PATH_MAX
, "%s/etc/hostname", bdev
->dest
);
3746 if (ret
< 0 || ret
>= PATH_MAX
)
3749 if (!file_exists(path
))
3752 if (!(fout
= fopen(path
, "w"))) {
3753 SYSERROR("unable to open %s: ignoring", path
);
3757 if (fprintf(fout
, "%s", c
->name
) < 0) {
3762 if (fclose(fout
) < 0)
3771 static int clone_update_rootfs_wrapper(void *data
)
3773 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3774 return clone_update_rootfs(arg
);
3778 * We want to support:
3779 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3780 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3782 -s [ implies overlay]
3785 only rootfs gets converted (copied/snapshotted) on clone.
3788 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3790 char *p
= strrchr(path
, '/');
3797 ret
= do_create_container_dir(path
, conf
);
3803 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3804 const char *lxcpath
, int flags
,
3805 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3808 char newpath
[PATH_MAX
];
3810 struct clone_update_data data
;
3811 size_t saved_unexp_len
;
3813 int storage_copied
= 0;
3814 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3815 struct lxc_container
*c2
= NULL
;
3817 if (!c
|| !do_lxcapi_is_defined(c
))
3820 if (container_mem_lock(c
))
3822 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3823 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3827 /* Make sure the container doesn't yet exist. */
3832 lxcpath
= do_lxcapi_get_config_path(c
);
3834 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/config", lxcpath
, newname
);
3835 if (ret
< 0 || ret
>= PATH_MAX
) {
3836 SYSERROR("clone: failed making config pathname");
3840 if (file_exists(newpath
)) {
3841 ERROR("error: clone: %s exists", newpath
);
3845 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3846 if (ret
< 0 && errno
!= EEXIST
) {
3847 ERROR("Error creating container dir for %s", newpath
);
3851 /* Copy the configuration. Tweak it as needed. */
3852 if (c
->lxc_conf
->rootfs
.path
) {
3853 origroot
= c
->lxc_conf
->rootfs
.path
;
3854 c
->lxc_conf
->rootfs
.path
= NULL
;
3857 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3858 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3860 SYSERROR("Failed to open \"%s\"", newpath
);
3864 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3865 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3866 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3867 if (!c
->lxc_conf
->unexpanded_config
) {
3872 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3873 write_config(fd
, c
->lxc_conf
);
3876 c
->lxc_conf
->rootfs
.path
= origroot
;
3878 free(c
->lxc_conf
->unexpanded_config
);
3879 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3880 saved_unexp_conf
= NULL
;
3881 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3883 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, newname
);
3884 if (ret
< 0 || ret
>= PATH_MAX
) {
3885 SYSERROR("clone: failed making rootfs pathname");
3889 ret
= mkdir(newpath
, 0755);
3891 /* For an overlay container the rootfs is considered immutable
3892 * and will not have been removed when restoring from a
3895 if (errno
!= ENOENT
&&
3896 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3897 SYSERROR("Failed to create directory \"%s\"", newpath
);
3902 if (am_guest_unpriv()) {
3903 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3904 ERROR("Error chowning %s to container root", newpath
);
3909 c2
= lxc_container_new(newname
, lxcpath
);
3911 ERROR("clone: failed to create new container (%s %s)", newname
,
3916 /* copy/snapshot rootfs's */
3917 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3921 /* update utsname */
3922 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3923 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3924 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3926 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3927 ERROR("Error setting new hostname");
3933 ret
= copyhooks(c
, c2
);
3935 ERROR("error copying hooks");
3939 if (copy_fstab(c
, c2
) < 0) {
3940 ERROR("error copying fstab");
3944 /* update macaddrs */
3945 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3946 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3947 ERROR("Error updating mac addresses");
3952 /* Update absolute paths for overlay mount directories. */
3953 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3956 /* We've now successfully created c2's storage, so clear it out if we
3961 if (!c2
->save_config(c2
, NULL
))
3964 if ((pid
= fork()) < 0) {
3970 ret
= wait_for_pid(pid
);
3974 container_mem_unlock(c
);
3981 data
.hookargs
= hookargs
;
3983 if (am_guest_unpriv())
3984 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3985 &data
, "clone_update_rootfs_wrapper");
3987 ret
= clone_update_rootfs(&data
);
3989 _exit(EXIT_FAILURE
);
3991 container_mem_unlock(c
);
3992 _exit(EXIT_SUCCESS
);
3995 container_mem_unlock(c
);
3997 if (!storage_copied
)
3998 c2
->lxc_conf
->rootfs
.path
= NULL
;
4001 lxc_container_put(c2
);
4007 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
4008 const char *lxcpath
, int flags
,
4009 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
4012 struct lxc_container
* ret
;
4014 current_config
= c
? c
->lxc_conf
: NULL
;
4015 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
4016 current_config
= NULL
;
4021 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4023 struct lxc_storage
*bdev
;
4024 struct lxc_container
*newc
;
4026 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4029 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4030 ERROR("Renaming a container with snapshots is not supported");
4034 bdev
= storage_init(c
->lxc_conf
);
4036 ERROR("Failed to find original backing store type");
4040 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4043 lxc_container_put(newc
);
4047 if (newc
&& lxcapi_is_defined(newc
))
4048 lxc_container_put(newc
);
4050 if (!container_destroy(c
, NULL
)) {
4051 ERROR("Could not destroy existing container %s", c
->name
);
4058 WRAP_API_1(bool, lxcapi_rename
, const char *)
4060 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
)
4067 current_config
= c
->lxc_conf
;
4069 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4070 current_config
= NULL
;
4074 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4076 lxc_attach_command_t command
;
4083 command
.program
= (char*)program
;
4084 command
.argv
= (char**)argv
;
4086 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4092 return lxc_wait_for_pid_status(pid
);
4095 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4099 current_config
= c
? c
->lxc_conf
: NULL
;
4100 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4101 current_config
= NULL
;
4106 static int get_next_index(const char *lxcpath
, char *cname
)
4112 fname
= alloca(strlen(lxcpath
) + 20);
4115 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4117 ret
= stat(fname
, &sb
);
4125 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4130 * If the old style snapshot path exists, use it
4131 * /var/lib/lxc -> /var/lib/lxcsnaps
4133 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4134 if (ret
< 0 || ret
>= PATH_MAX
)
4137 if (dir_exists(snappath
)) {
4138 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4139 if (ret
< 0 || ret
>= PATH_MAX
)
4146 * Use the new style path
4147 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4149 ret
= snprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4150 if (ret
< 0 || ret
>= PATH_MAX
)
4156 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4161 struct lxc_container
*c2
;
4162 char snappath
[PATH_MAX
], newname
[20];
4166 if (!c
|| !lxcapi_is_defined(c
))
4169 if (!storage_can_backup(c
->lxc_conf
)) {
4170 ERROR("%s's backing store cannot be backed up", c
->name
);
4171 ERROR("Your container must use another backing store type");
4175 if (!get_snappath_dir(c
, snappath
))
4178 i
= get_next_index(snappath
, c
->name
);
4180 if (mkdir_p(snappath
, 0755) < 0) {
4181 ERROR("Failed to create snapshot directory %s", snappath
);
4185 ret
= snprintf(newname
, 20, "snap%d", i
);
4186 if (ret
< 0 || ret
>= 20)
4190 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4191 * created in the original container
4193 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4194 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4195 if (storage_is_dir(c
->lxc_conf
)) {
4196 ERROR("Snapshot of directory-backed container requested");
4197 ERROR("Making a copy-clone. If you do want snapshots, then");
4198 ERROR("please create overlay clone first, snapshot that");
4199 ERROR("and keep the original container pristine");
4200 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4203 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4205 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4209 lxc_container_put(c2
);
4211 /* Now write down the creation time. */
4214 if (!localtime_r(&timer
, &tm_info
)) {
4215 ERROR("Failed to get localtime");
4219 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4221 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4222 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4223 f
= fopen(dfnam
, "w");
4225 ERROR("Failed to open %s", dfnam
);
4229 if (fprintf(f
, "%s", buffer
) < 0) {
4230 SYSERROR("Writing timestamp");
4237 SYSERROR("Writing timestamp");
4242 /* $p / $name / comment \0 */
4243 int len
= strlen(snappath
) + strlen(newname
) + 10;
4244 char *path
= alloca(len
);
4246 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4247 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4253 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4255 static void lxcsnap_free(struct lxc_snapshot
*s
)
4258 free(s
->comment_pathname
);
4263 static char *get_snapcomment_path(char* snappath
, char *name
)
4265 /* $snappath/$name/comment */
4266 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4267 char *s
= malloc(len
);
4270 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4271 if (ret
< 0 || ret
>= len
) {
4280 static char *get_timestamp(char* snappath
, char *name
)
4282 char path
[PATH_MAX
], *s
= NULL
;
4286 ret
= snprintf(path
, PATH_MAX
, "%s/%s/ts", snappath
, name
);
4287 if (ret
< 0 || ret
>= PATH_MAX
)
4290 fin
= fopen(path
, "r");
4294 (void) fseek(fin
, 0, SEEK_END
);
4296 (void) fseek(fin
, 0, SEEK_SET
);
4301 if (fread(s
, 1, len
, fin
) != len
) {
4302 SYSERROR("reading timestamp");
4313 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4315 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4317 struct dirent
*direntp
;
4318 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4321 if (!c
|| !lxcapi_is_defined(c
))
4324 if (!get_snappath_dir(c
, snappath
)) {
4325 ERROR("path name too long");
4329 dir
= opendir(snappath
);
4331 INFO("Failed to open %s - assuming no snapshots", snappath
);
4335 while ((direntp
= readdir(dir
))) {
4336 if (!strcmp(direntp
->d_name
, "."))
4339 if (!strcmp(direntp
->d_name
, ".."))
4342 ret
= snprintf(path2
, PATH_MAX
, "%s/%s/config", snappath
, direntp
->d_name
);
4343 if (ret
< 0 || ret
>= PATH_MAX
) {
4344 ERROR("pathname too long");
4348 if (!file_exists(path2
))
4351 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4353 SYSERROR("Out of memory");
4358 snaps
[count
].free
= lxcsnap_free
;
4359 snaps
[count
].name
= strdup(direntp
->d_name
);
4360 if (!snaps
[count
].name
)
4363 snaps
[count
].lxcpath
= strdup(snappath
);
4364 if (!snaps
[count
].lxcpath
) {
4365 free(snaps
[count
].name
);
4369 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4370 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4375 WARN("Failed to close directory");
4384 for (i
=0; i
<count
; i
++)
4385 lxcsnap_free(&snaps
[i
]);
4391 WARN("Failed to close directory");
4396 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4398 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4400 char clonelxcpath
[PATH_MAX
];
4402 struct lxc_container
*snap
, *rest
;
4403 struct lxc_storage
*bdev
;
4406 if (!c
|| !c
->name
|| !c
->config_path
)
4409 if (has_fs_snapshots(c
)) {
4410 ERROR("container rootfs has dependent snapshots");
4414 bdev
= storage_init(c
->lxc_conf
);
4416 ERROR("Failed to find original backing store type");
4420 /* For an overlay container the rootfs is considered immutable
4421 * and cannot be removed when restoring from a snapshot. We pass this
4422 * internal flag along to communicate this to various parts of the
4425 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4426 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4431 if (!get_snappath_dir(c
, clonelxcpath
)) {
4435 /* how should we lock this? */
4437 snap
= lxc_container_new(snapname
, clonelxcpath
);
4438 if (!snap
|| !lxcapi_is_defined(snap
)) {
4439 ERROR("Could not open snapshot %s", snapname
);
4442 lxc_container_put(snap
);
4448 if (!strcmp(c
->name
, newname
)) {
4449 if (!container_destroy(c
, bdev
)) {
4450 ERROR("Could not destroy existing container %s", newname
);
4451 lxc_container_put(snap
);
4457 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4458 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4460 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4461 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4463 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4466 if (rest
&& lxcapi_is_defined(rest
))
4470 lxc_container_put(rest
);
4472 lxc_container_put(snap
);
4476 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4478 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4480 struct lxc_container
*snap
= NULL
;
4483 snap
= lxc_container_new(snapname
, clonelxcpath
);
4485 ERROR("Could not find snapshot %s", snapname
);
4489 if (!do_lxcapi_destroy(snap
)) {
4490 ERROR("Could not destroy snapshot %s", snapname
);
4498 lxc_container_put(snap
);
4503 static bool remove_all_snapshots(const char *path
)
4506 struct dirent
*direntp
;
4509 dir
= opendir(path
);
4511 SYSERROR("opendir on snapshot path %s", path
);
4515 while ((direntp
= readdir(dir
))) {
4516 if (!strcmp(direntp
->d_name
, "."))
4519 if (!strcmp(direntp
->d_name
, ".."))
4522 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4531 SYSERROR("Error removing directory %s", path
);
4536 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4538 char clonelxcpath
[PATH_MAX
];
4540 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4543 if (!get_snappath_dir(c
, clonelxcpath
))
4546 return do_snapshot_destroy(snapname
, clonelxcpath
);
4549 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4551 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4553 char clonelxcpath
[PATH_MAX
];
4555 if (!c
|| !c
->name
|| !c
->config_path
)
4558 if (!get_snappath_dir(c
, clonelxcpath
))
4561 return remove_all_snapshots(clonelxcpath
);
4564 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4566 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4571 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4574 WRAP_API(bool, lxcapi_may_control
)
4576 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4582 char chrootpath
[PATH_MAX
];
4583 char *directory_path
= NULL
;
4587 SYSERROR("Failed to fork()");
4592 ret
= wait_for_pid(pid
);
4594 ERROR("Failed to create device node");
4601 /* prepare the path */
4602 ret
= snprintf(chrootpath
, PATH_MAX
, "/proc/%d/root", init_pid
);
4603 if (ret
< 0 || ret
>= PATH_MAX
)
4606 ret
= chroot(chrootpath
);
4608 _exit(EXIT_FAILURE
);
4612 _exit(EXIT_FAILURE
);
4614 /* remove path if it exists */
4615 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4619 SYSERROR("Failed to remove \"%s\"", path
);
4620 _exit(EXIT_FAILURE
);
4625 _exit(EXIT_SUCCESS
);
4627 /* create any missing directories */
4630 _exit(EXIT_FAILURE
);
4632 directory_path
= dirname(tmp
);
4633 ret
= mkdir_p(directory_path
, 0755);
4634 if (ret
< 0 && errno
!= EEXIST
) {
4635 SYSERROR("Failed to create path \"%s\"", directory_path
);
4637 _exit(EXIT_FAILURE
);
4640 /* create the device node */
4641 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4644 SYSERROR("Failed to create device node at \"%s\"", path
);
4645 _exit(EXIT_FAILURE
);
4648 _exit(EXIT_SUCCESS
);
4651 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4655 char value
[LXC_MAX_BUFFER
];
4658 /* make sure container is running */
4659 if (!do_lxcapi_is_running(c
)) {
4660 ERROR("container is not running");
4664 /* use src_path if dest_path is NULL otherwise use dest_path */
4665 p
= dest_path
? dest_path
: src_path
;
4667 /* make sure we can access p */
4668 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4671 /* continue if path is character device or block device */
4672 if (S_ISCHR(st
.st_mode
))
4673 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4674 else if (S_ISBLK(st
.st_mode
))
4675 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4679 /* check snprintf return code */
4680 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4683 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4686 /* add or remove device to/from cgroup access list */
4688 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4689 ERROR("set_cgroup_item failed while adding the device node");
4693 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4694 ERROR("set_cgroup_item failed while removing the device node");
4702 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4704 // cannot mknod if we're not privileged wrt init_user_ns
4705 if (am_host_unpriv()) {
4706 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4710 return add_remove_device_node(c
, src_path
, dest_path
, true);
4713 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4715 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4717 if (am_guest_unpriv()) {
4718 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4722 return add_remove_device_node(c
, src_path
, dest_path
, false);
4725 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4727 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4729 const char *dst_ifname
)
4734 if (am_guest_unpriv()) {
4735 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4740 ERROR("No source interface name given");
4744 ret
= lxc_netdev_isup(ifname
);
4746 /* netdev of ifname is up. */
4747 ret
= lxc_netdev_down(ifname
);
4752 init_pid
= do_lxcapi_init_pid(c
);
4753 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4757 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4764 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4766 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4768 const char *dst_ifname
)
4771 pid_t pid
, pid_outside
;
4774 * TODO - if this is a physical device, then we need am_host_unpriv.
4775 * But for other types guest privilege suffices.
4777 if (am_guest_unpriv()) {
4778 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4783 ERROR("No source interface name given");
4787 pid_outside
= lxc_raw_getpid();
4790 ERROR("Failed to fork");
4794 if (pid
== 0) { /* child */
4797 init_pid
= do_lxcapi_init_pid(c
);
4798 if (!switch_to_ns(init_pid
, "net")) {
4799 ERROR("Failed to enter network namespace");
4800 _exit(EXIT_FAILURE
);
4803 ret
= lxc_netdev_isup(ifname
);
4805 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4806 _exit(EXIT_FAILURE
);
4809 /* netdev of ifname is up. */
4811 ret
= lxc_netdev_down(ifname
);
4813 ERROR("Failed to set network device \"%s\" down", ifname
);
4814 _exit(EXIT_FAILURE
);
4818 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4819 /* -EINVAL means there is no netdev named as ifname. */
4822 ERROR("Network device \"%s\" not found", ifname
);
4824 ERROR("Failed to remove network device \"%s\"", ifname
);
4826 _exit(EXIT_FAILURE
);
4829 _exit(EXIT_SUCCESS
);
4832 ret
= wait_for_pid(pid
);
4836 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4840 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4842 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4843 struct migrate_opts
*opts
, unsigned int size
)
4846 struct migrate_opts
*valid_opts
= opts
;
4847 uint64_t features_to_check
= 0;
4849 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4850 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4851 * to do anything special.
4853 if (size
> sizeof(*opts
)) {
4854 unsigned char *addr
;
4857 addr
= (void *)opts
+ sizeof(*opts
);
4858 end
= (void *)opts
+ size
;
4860 for (; addr
< end
; addr
++)
4865 /* If the caller has a smaller struct, let's zero out the end for them
4866 * so we don't accidentally use bits of it that they didn't know about
4869 if (size
< sizeof(*opts
)) {
4870 valid_opts
= malloc(sizeof(*opts
));
4874 memset(valid_opts
, 0, sizeof(*opts
));
4875 memcpy(valid_opts
, opts
, size
);
4879 case MIGRATE_PRE_DUMP
:
4880 if (!do_lxcapi_is_running(c
)) {
4881 ERROR("container is not running");
4885 ret
= !__criu_pre_dump(c
, valid_opts
);
4888 if (!do_lxcapi_is_running(c
)) {
4889 ERROR("container is not running");
4893 ret
= !__criu_dump(c
, valid_opts
);
4895 case MIGRATE_RESTORE
:
4896 if (do_lxcapi_is_running(c
)) {
4897 ERROR("container is already running");
4901 ret
= !__criu_restore(c
, valid_opts
);
4903 case MIGRATE_FEATURE_CHECK
:
4904 features_to_check
= valid_opts
->features_to_check
;
4905 ret
= !__criu_check_feature(&features_to_check
);
4907 /* Something went wrong. Let's let the caller
4908 * know which feature checks failed. */
4909 valid_opts
->features_to_check
= features_to_check
;
4913 ERROR("invalid migrate command %u", cmd
);
4918 if (size
< sizeof(*opts
))
4924 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4926 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4928 struct migrate_opts opts
;
4930 memset(&opts
, 0, sizeof(opts
));
4932 opts
.directory
= directory
;
4934 opts
.verbose
= verbose
;
4936 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4939 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4941 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4943 struct migrate_opts opts
;
4945 memset(&opts
, 0, sizeof(opts
));
4947 opts
.directory
= directory
;
4948 opts
.verbose
= verbose
;
4950 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4953 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4955 /* @st_mode is the st_mode field of the stat(source) return struct */
4956 static int create_mount_target(const char *dest
, mode_t st_mode
)
4958 char *dirdup
, *destdirname
;
4961 dirdup
= strdup(dest
);
4963 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4966 destdirname
= dirname(dirdup
);
4968 ret
= mkdir_p(destdirname
, 0755);
4970 SYSERROR("Failed to create \"%s\"", destdirname
);
4978 if (S_ISDIR(st_mode
))
4979 ret
= mkdir(dest
, 0000);
4981 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4983 SYSERROR("Failed to create mount target \"%s\"", dest
);
4990 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4991 const char *target
, const char *filesystemtype
,
4992 unsigned long mountflags
, const void *data
,
4993 struct lxc_mount
*mnt
)
4996 char template[PATH_MAX
], path
[PATH_MAX
];
4997 pid_t pid
, init_pid
;
5000 int ret
= -1, fd
= -EBADF
;
5002 if (!c
|| !c
->lxc_conf
) {
5003 ERROR("Container or configuration is NULL");
5007 if (!c
->lxc_conf
->shmount
.path_host
) {
5008 ERROR("Host path to shared mountpoint must be specified in the config\n");
5012 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5013 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
5014 SYSERROR("Error writing shmounts tempdir name");
5018 /* Create a temporary file / dir under the shared mountpoint */
5019 if (!source
|| strcmp(source
, "") == 0) {
5020 /* If source is not specified, maybe we want to mount a filesystem? */
5021 sb
.st_mode
= S_IFDIR
;
5023 ret
= stat(source
, &sb
);
5025 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5030 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5032 sret
= mkdtemp(template);
5034 SYSERROR("Could not create shmounts temporary dir");
5038 fd
= lxc_make_tmpfile(template, false);
5040 SYSERROR("Could not create shmounts temporary file");
5048 SYSERROR("Could not fork");
5054 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5056 SYSERROR("Failed to mount onto \"%s\"", template);
5057 _exit(EXIT_FAILURE
);
5059 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5061 init_pid
= do_lxcapi_init_pid(c
);
5063 ERROR("Failed to obtain container's init pid");
5064 _exit(EXIT_FAILURE
);
5067 /* Enter the container namespaces */
5068 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5069 if (!switch_to_ns(init_pid
, "user")) {
5070 ERROR("Failed to enter user namespace");
5071 _exit(EXIT_FAILURE
);
5074 if (!lxc_switch_uid_gid(0, 0))
5075 _exit(EXIT_FAILURE
);
5078 if (!switch_to_ns(init_pid
, "mnt")) {
5079 ERROR("Failed to enter mount namespace");
5080 _exit(EXIT_FAILURE
);
5083 ret
= create_mount_target(target
, sb
.st_mode
);
5085 _exit(EXIT_FAILURE
);
5086 TRACE("Created mount target \"%s\"", target
);
5088 suff
= strrchr(template, '/');
5090 _exit(EXIT_FAILURE
);
5092 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5093 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5094 SYSERROR("Error writing container mountpoint name");
5095 _exit(EXIT_FAILURE
);
5098 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5100 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5101 _exit(EXIT_FAILURE
);
5103 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5105 _exit(EXIT_SUCCESS
);
5108 ret
= wait_for_pid(pid
);
5110 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5116 (void)umount2(template, MNT_DETACH
);
5118 (void)rmdir(template);
5120 (void)unlink(template);
5129 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5130 unsigned long, const void *, struct lxc_mount
*)
5132 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5133 unsigned long flags
, struct lxc_mount
*mnt
)
5135 pid_t pid
, init_pid
;
5138 if (!c
|| !c
->lxc_conf
) {
5139 ERROR("Container or configuration is NULL");
5146 SYSERROR("Could not fork");
5151 init_pid
= do_lxcapi_init_pid(c
);
5153 ERROR("Failed to obtain container's init pid");
5154 _exit(EXIT_FAILURE
);
5157 /* Enter the container namespaces */
5158 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5159 if (!switch_to_ns(init_pid
, "user")) {
5160 ERROR("Failed to enter user namespace");
5161 _exit(EXIT_FAILURE
);
5165 if (!switch_to_ns(init_pid
, "mnt")) {
5166 ERROR("Failed to enter mount namespace");
5167 _exit(EXIT_FAILURE
);
5170 /* Do the unmount */
5171 ret
= umount2(target
, flags
);
5173 SYSERROR("Failed to umount \"%s\"", target
);
5174 _exit(EXIT_FAILURE
);
5177 _exit(EXIT_SUCCESS
);
5180 ret
= wait_for_pid(pid
);
5182 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5189 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5191 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5200 current_config
= c
->lxc_conf
;
5203 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5207 ERROR("Memory allocation error.");
5213 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5217 current_config
= NULL
;
5221 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5223 struct lxc_container
*c
;
5229 c
= malloc(sizeof(*c
));
5231 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5234 memset(c
, 0, sizeof(*c
));
5237 c
->config_path
= strdup(configpath
);
5239 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5240 if (!c
->config_path
) {
5241 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5245 remove_trailing_slashes(c
->config_path
);
5248 c
->name
= malloc(len
+ 1);
5250 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5253 (void)strlcpy(c
->name
, name
, len
+ 1);
5256 c
->slock
= lxc_newlock(c
->config_path
, name
);
5258 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5262 c
->privlock
= lxc_newlock(NULL
, NULL
);
5264 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5268 if (!set_config_filename(c
)) {
5269 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5273 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5274 fprintf(stderr
, "Failed to load config for %s\n", name
);
5278 if (ongoing_create(c
) == 2) {
5279 ERROR("Failed to complete container creation for %s", c
->name
);
5280 container_destroy(c
, NULL
);
5281 lxcapi_clear_config(c
);
5284 c
->daemonize
= true;
5287 /* Assign the member functions. */
5288 c
->is_defined
= lxcapi_is_defined
;
5289 c
->state
= lxcapi_state
;
5290 c
->is_running
= lxcapi_is_running
;
5291 c
->freeze
= lxcapi_freeze
;
5292 c
->unfreeze
= lxcapi_unfreeze
;
5293 c
->console
= lxcapi_console
;
5294 c
->console_getfd
= lxcapi_console_getfd
;
5295 c
->init_pid
= lxcapi_init_pid
;
5296 c
->load_config
= lxcapi_load_config
;
5297 c
->want_daemonize
= lxcapi_want_daemonize
;
5298 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5299 c
->start
= lxcapi_start
;
5300 c
->startl
= lxcapi_startl
;
5301 c
->stop
= lxcapi_stop
;
5302 c
->config_file_name
= lxcapi_config_file_name
;
5303 c
->wait
= lxcapi_wait
;
5304 c
->set_config_item
= lxcapi_set_config_item
;
5305 c
->destroy
= lxcapi_destroy
;
5306 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5307 c
->rename
= lxcapi_rename
;
5308 c
->save_config
= lxcapi_save_config
;
5309 c
->get_keys
= lxcapi_get_keys
;
5310 c
->create
= lxcapi_create
;
5311 c
->createl
= lxcapi_createl
;
5312 c
->shutdown
= lxcapi_shutdown
;
5313 c
->reboot
= lxcapi_reboot
;
5314 c
->reboot2
= lxcapi_reboot2
;
5315 c
->clear_config
= lxcapi_clear_config
;
5316 c
->clear_config_item
= lxcapi_clear_config_item
;
5317 c
->get_config_item
= lxcapi_get_config_item
;
5318 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5319 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5320 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5321 c
->get_config_path
= lxcapi_get_config_path
;
5322 c
->set_config_path
= lxcapi_set_config_path
;
5323 c
->clone
= lxcapi_clone
;
5324 c
->get_interfaces
= lxcapi_get_interfaces
;
5325 c
->get_ips
= lxcapi_get_ips
;
5326 c
->attach
= lxcapi_attach
;
5327 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5328 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5329 c
->snapshot
= lxcapi_snapshot
;
5330 c
->snapshot_list
= lxcapi_snapshot_list
;
5331 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5332 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5333 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5334 c
->may_control
= lxcapi_may_control
;
5335 c
->add_device_node
= lxcapi_add_device_node
;
5336 c
->remove_device_node
= lxcapi_remove_device_node
;
5337 c
->attach_interface
= lxcapi_attach_interface
;
5338 c
->detach_interface
= lxcapi_detach_interface
;
5339 c
->checkpoint
= lxcapi_checkpoint
;
5340 c
->restore
= lxcapi_restore
;
5341 c
->migrate
= lxcapi_migrate
;
5342 c
->console_log
= lxcapi_console_log
;
5343 c
->mount
= lxcapi_mount
;
5344 c
->umount
= lxcapi_umount
;
5349 lxc_container_free(c
);
5353 int lxc_get_wait_states(const char **states
)
5358 for (i
=0; i
<MAX_STATE
; i
++)
5359 states
[i
] = lxc_state2str(i
);
5365 * These next two could probably be done smarter with reusing a common function
5366 * with different iterators and tests...
5368 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5371 int i
, cfound
= 0, nfound
= 0;
5372 struct dirent
*direntp
;
5373 struct lxc_container
*c
;
5376 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5378 dir
= opendir(lxcpath
);
5380 SYSERROR("opendir on lxcpath");
5390 while ((direntp
= readdir(dir
))) {
5391 /* Ignore '.', '..' and any hidden directory. */
5392 if (!strncmp(direntp
->d_name
, ".", 1))
5395 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5399 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5409 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5411 INFO("Container %s:%s has a config but could not be loaded",
5412 lxcpath
, direntp
->d_name
);
5415 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5421 if (!do_lxcapi_is_defined(c
)) {
5422 INFO("Container %s:%s has a config but is not defined",
5423 lxcpath
, direntp
->d_name
);
5426 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5429 lxc_container_put(c
);
5433 if (!add_to_clist(cret
, c
, nfound
, true)) {
5434 lxc_container_put(c
);
5445 if (names
&& *names
) {
5446 for (i
=0; i
<cfound
; i
++)
5451 if (cret
&& *cret
) {
5452 for (i
=0; i
<nfound
; i
++)
5453 lxc_container_put((*cret
)[i
]);
5461 int list_active_containers(const char *lxcpath
, char ***nret
,
5462 struct lxc_container
***cret
)
5464 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5467 char **ct_name
= NULL
;
5469 struct lxc_container
*c
= NULL
;
5473 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5474 lxcpath_len
= strlen(lxcpath
);
5482 FILE *f
= fopen("/proc/net/unix", "r");
5486 while (getline(&line
, &len
, f
) != -1) {
5487 char *p
= strrchr(line
, ' '), *p2
;
5498 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5500 } else if (strncmp(p
, "lxc/", 4) == 0) {
5510 /* Now p is the start of lxc_name. */
5511 p2
= strchr(p
, '/');
5512 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5517 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5521 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5527 p
= lxc_cmd_get_name(p
);
5532 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5538 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5541 goto free_cret_list
;
5552 c
= lxc_container_new(p
, lxcpath
);
5554 INFO("Container %s:%s is running but could not be loaded",
5557 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5568 * If this is an anonymous container, then is_defined *can*
5569 * return false. So we don't do that check. Count on the
5570 * fact that the command socket exists.
5573 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5574 lxc_container_put(c
);
5575 goto free_cret_list
;
5581 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5583 lxc_container_put(c
);
5584 goto free_cret_list
;
5596 if (cret
&& *cret
) {
5597 for (i
= 0; i
< cret_cnt
; i
++)
5598 lxc_container_put((*cret
)[i
]);
5604 for (i
= 0; i
< ct_name_cnt
; i
++)
5615 int list_all_containers(const char *lxcpath
, char ***nret
,
5616 struct lxc_container
***cret
)
5618 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5621 struct lxc_container
**ct_list
= NULL
;
5623 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5627 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5628 if (active_cnt
< 0) {
5633 for (i
= 0; i
< active_cnt
; i
++) {
5634 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5635 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5637 goto free_active_name
;
5643 free(active_name
[i
]);
5644 active_name
[i
] = NULL
;
5651 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5652 struct lxc_container
*c
;
5654 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5656 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5657 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5661 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5662 lxc_container_put(c
);
5683 for (i
= 0; i
< ct_list_cnt
; i
++) {
5684 lxc_container_put(ct_list
[i
]);
5689 for (i
= 0; i
< active_cnt
; i
++) {
5690 free(active_name
[i
]);
5695 for (i
= 0; i
< ct_cnt
; i
++) {
5702 bool lxc_config_item_is_supported(const char *key
)
5704 return !!lxc_get_config(key
);
5707 bool lxc_has_api_extension(const char *extension
)
5709 /* The NULL API extension is always present. :) */
5713 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5714 if (strcmp(api_extensions
[i
], extension
) == 0)