1 /* SPDX-License-Identifier: LGPL-2.1+ */
20 #include <sys/mount.h>
22 #include <sys/syscall.h>
23 #include <sys/sysmacros.h>
24 #include <sys/types.h>
28 #include "../include/netns_ifaddrs.h"
30 #include "api_extensions.h"
35 #include "commands_utils.h"
39 #include "confile_utils.h"
42 #include "initutils.h"
45 #include "lxccontainer.h"
47 #include "memory_utils.h"
49 #include "namespace.h"
52 #include "raw_syscalls.h"
56 #include "storage/btrfs.h"
57 #include "storage/overlay.h"
58 #include "storage_utils.h"
60 #include "syscall_wrappers.h"
66 #include <openssl/evp.h>
71 #include <sys/mkdev.h>
75 #include <../include/lxcmntent.h>
81 #include "include/strlcpy.h"
84 /* Define faccessat() if missing from the C library */
85 #ifndef HAVE_FACCESSAT
86 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
89 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
97 lxc_log_define(lxccontainer
, lxc
);
99 static bool do_lxcapi_destroy(struct lxc_container
*c
);
100 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
101 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
102 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
103 static bool container_destroy(struct lxc_container
*c
,
104 struct lxc_storage
*storage
);
105 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
106 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
107 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
109 static bool config_file_exists(const char *lxcpath
, const char *cname
)
111 __do_free
char *fname
= NULL
;
115 /* $lxcpath + '/' + $cname + '/config' + \0 */
116 len
= strlen(lxcpath
) + 1 + strlen(cname
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
117 fname
= must_realloc(NULL
, len
);
118 ret
= snprintf(fname
, len
, "%s/%s/%s", lxcpath
, cname
, LXC_CONFIG_FNAME
);
119 if (ret
< 0 || (size_t)ret
>= len
)
122 return file_exists(fname
);
126 * A few functions to help detect when a container creation failed. If a
127 * container creation was killed partway through, then trying to actually start
128 * that container could harm the host. We detect this by creating a 'partial'
129 * file under the container directory, and keeping an advisory lock. When
130 * container creation completes, we remove that file. When we load or try to
131 * start a container, if we find that file, without a flock, we remove the
135 LXC_CREATE_FAILED
= -1,
136 LXC_CREATE_SUCCESS
= 0,
137 LXC_CREATE_ONGOING
= 1,
138 LXC_CREATE_INCOMPLETE
= 2,
141 static int ongoing_create(struct lxc_container
*c
)
143 __do_close
int fd
= -EBADF
;
144 __do_free
char *path
= NULL
;
145 struct flock lk
= {0};
149 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
150 path
= must_realloc(NULL
, len
);
151 ret
= snprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
152 if (ret
< 0 || (size_t)ret
>= len
)
153 return LXC_CREATE_FAILED
;
155 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
158 return LXC_CREATE_FAILED
;
160 return LXC_CREATE_SUCCESS
;
164 lk
.l_whence
= SEEK_SET
;
166 * F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
171 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
172 if (ret
< 0 && errno
== EINVAL
) {
173 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
174 if (ret
< 0 && errno
== EWOULDBLOCK
)
178 /* F_OFD_GETLK will not send us back a pid so don't check it. */
180 /* Create is still ongoing. */
181 return LXC_CREATE_ONGOING
;
183 /* Create completed but partial is still there. */
184 return LXC_CREATE_INCOMPLETE
;
187 static int create_partial(struct lxc_container
*c
)
189 __do_free
char *path
= NULL
;
192 struct flock lk
= {0};
194 /* $lxcpath + '/' + $name + '/partial' + \0 */
195 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
196 path
= must_realloc(NULL
, len
);
197 ret
= snprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
198 if (ret
< 0 || (size_t)ret
>= len
)
201 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
206 lk
.l_whence
= SEEK_SET
;
208 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
210 if (errno
== EINVAL
) {
211 ret
= flock(fd
, LOCK_EX
);
216 SYSERROR("Failed to lock partial file %s", path
);
224 static void remove_partial(struct lxc_container
*c
, int fd
)
226 __do_free
char *path
= NULL
;
232 /* $lxcpath + '/' + $name + '/partial' + \0 */
233 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_PARTIAL_FNAME
) + 1;
234 path
= must_realloc(NULL
, len
);
235 ret
= snprintf(path
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_PARTIAL_FNAME
);
236 if (ret
< 0 || (size_t)ret
>= len
)
241 SYSERROR("Failed to remove partial file %s", path
);
245 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
246 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
247 * container configuration file.
248 * The container_disk_lock also takes the container_mem_lock.
249 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
250 * NOTHING mutexes two independent programs with their own struct
251 * lxc_container for the same c->name, between API calls. For instance,
252 * c->config_read(); c->start(); Between those calls, data on disk
253 * could change (which shouldn't bother the caller unless for instance
254 * the rootfs get moved). c->config_read(); update; c->config_write();
255 * Two such updaters could race. The callers should therefore check their
256 * results. Trying to prevent that would necessarily expose us to deadlocks
257 * due to hung callers. So I prefer to keep the locks only within our own
258 * functions, not across functions.
260 * If you're going to clone while holding a lxccontainer, increment
261 * c->numthreads (under privlock) before forking. When deleting,
262 * decrement numthreads under privlock, then if it hits 0 you can delete.
263 * Do not ever use a lxccontainer whose numthreads you did not bump.
265 static void lxc_container_free(struct lxc_container
*c
)
271 c
->configfile
= NULL
;
273 free(c
->error_string
);
274 c
->error_string
= NULL
;
277 lxc_putlock(c
->slock
);
282 lxc_putlock(c
->privlock
);
290 lxc_conf_free(c
->lxc_conf
);
294 free(c
->config_path
);
295 c
->config_path
= NULL
;
300 /* Consider the following case:
302 * |====================================================================|
303 * | freer | racing get()er |
304 * |====================================================================|
305 * | lxc_container_put() | lxc_container_get() |
306 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
307 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
308 * | \ lxcunlock() | \ |
309 * | \ lxc_container_free() | \ lxclock() returns |
310 * | | \ c->numthreads < 1 -> return 0 |
311 * | \ \ (free stuff) | |
312 * | \ \ sem_destroy(privlock) | |
313 * |_______________________________|____________________________________|
315 * When the get()er checks numthreads the first time, one of the following
317 * 1. freer has set numthreads = 0. get() returns 0
318 * 2. freer is between lxclock and setting numthreads to 0. get()er will
319 * sem_wait on privlock, get lxclock after freer() drops it, then see
320 * numthreads is 0 and exit without touching lxclock again..
321 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
322 * will see --numthreads = 1 and not call lxc_container_free().
325 int lxc_container_get(struct lxc_container
*c
)
330 /* If someone else has already started freeing the container, don't try
331 * to take the lock, which may be invalid.
333 if (c
->numthreads
< 1)
336 if (container_mem_lock(c
))
339 /* Bail without trying to unlock, bc the privlock is now probably in
342 if (c
->numthreads
< 1)
346 container_mem_unlock(c
);
351 int lxc_container_put(struct lxc_container
*c
)
356 if (container_mem_lock(c
))
361 if (c
->numthreads
< 1) {
362 container_mem_unlock(c
);
363 lxc_container_free(c
);
367 container_mem_unlock(c
);
371 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
380 if (container_mem_lock(c
))
386 statret
= stat(c
->configfile
, &statbuf
);
393 container_mem_unlock(c
);
397 #define WRAP_API(rettype, fnname) \
398 static rettype fnname(struct lxc_container *c) \
401 bool reset_config = false; \
403 if (!current_config && c && c->lxc_conf) { \
404 current_config = c->lxc_conf; \
405 reset_config = true; \
408 ret = do_##fnname(c); \
410 current_config = NULL; \
415 #define WRAP_API_1(rettype, fnname, t1) \
416 static rettype fnname(struct lxc_container *c, t1 a1) \
419 bool reset_config = false; \
421 if (!current_config && c && c->lxc_conf) { \
422 current_config = c->lxc_conf; \
423 reset_config = true; \
426 ret = do_##fnname(c, a1); \
428 current_config = NULL; \
433 #define WRAP_API_2(rettype, fnname, t1, t2) \
434 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
437 bool reset_config = false; \
439 if (!current_config && c && c->lxc_conf) { \
440 current_config = c->lxc_conf; \
441 reset_config = true; \
444 ret = do_##fnname(c, a1, a2); \
446 current_config = NULL; \
451 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
452 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
455 bool reset_config = false; \
457 if (!current_config && c && c->lxc_conf) { \
458 current_config = c->lxc_conf; \
459 reset_config = true; \
462 ret = do_##fnname(c, a1, a2, a3); \
464 current_config = NULL; \
469 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
470 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
471 t4 a4, t5 a5, t6 a6) \
474 bool reset_config = false; \
476 if (!current_config && c && c->lxc_conf) { \
477 current_config = c->lxc_conf; \
478 reset_config = true; \
481 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
483 current_config = NULL; \
488 WRAP_API(bool, lxcapi_is_defined
)
490 static const char *do_lxcapi_state(struct lxc_container
*c
)
497 s
= lxc_getstate(c
->name
, c
->config_path
);
498 return lxc_state2str(s
);
501 WRAP_API(const char *, lxcapi_state
)
503 static bool is_stopped(struct lxc_container
*c
)
507 s
= lxc_getstate(c
->name
, c
->config_path
);
508 return (s
== STOPPED
);
511 static bool do_lxcapi_is_running(struct lxc_container
*c
)
516 return !is_stopped(c
);
519 WRAP_API(bool, lxcapi_is_running
)
521 static bool do_lxcapi_freeze(struct lxc_container
*c
)
525 if (!c
|| !c
->lxc_conf
)
528 s
= lxc_getstate(c
->name
, c
->config_path
);
530 return lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
535 WRAP_API(bool, lxcapi_freeze
)
537 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
541 if (!c
|| !c
->lxc_conf
)
544 s
= lxc_getstate(c
->name
, c
->config_path
);
546 return lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
551 WRAP_API(bool, lxcapi_unfreeze
)
553 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
558 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
561 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
563 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
564 int stdoutfd
, int stderrfd
, int escape
)
571 current_config
= c
->lxc_conf
;
572 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
573 current_config
= NULL
;
578 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
585 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
588 NOTICE("The console log is empty");
589 else if (ret
== -EFAULT
)
590 NOTICE("The container does not keep a console log");
591 else if (ret
== -ENOENT
)
592 NOTICE("The container does not keep a console log file");
593 else if (ret
== -EIO
)
594 NOTICE("Failed to write console log to log file");
596 ERROR("Failed to retrieve console log");
602 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
604 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
609 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
612 WRAP_API(pid_t
, lxcapi_init_pid
)
614 static int do_lxcapi_init_pidfd(struct lxc_container
*c
)
617 return ret_errno(EBADF
);
619 return lxc_cmd_get_init_pidfd(c
->name
, c
->config_path
);
622 WRAP_API(int, lxcapi_init_pidfd
)
624 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
627 c
->lxc_conf
= lxc_conf_init();
632 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
635 c
->lxc_conf
->name
= c
->name
;
639 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
643 bool need_disklock
= false, ret
= false;
648 fname
= c
->configfile
;
656 /* If we're reading something other than the container's config, we only
657 * need to lock the in-memory container. If loading the container's
658 * config file, take the disk lock.
660 if (strcmp(fname
, c
->configfile
) == 0)
661 need_disklock
= true;
664 lret
= container_disk_lock(c
);
666 lret
= container_mem_lock(c
);
670 ret
= load_config_locked(c
, fname
);
673 container_disk_unlock(c
);
675 container_mem_unlock(c
);
680 WRAP_API_1(bool, lxcapi_load_config
, const char *)
682 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
684 if (!c
|| !c
->lxc_conf
)
687 if (container_mem_lock(c
))
690 c
->daemonize
= state
;
692 container_mem_unlock(c
);
697 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
699 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
701 if (!c
|| !c
->lxc_conf
)
704 if (container_mem_lock(c
))
707 c
->lxc_conf
->close_all_fds
= state
;
709 container_mem_unlock(c
);
714 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
716 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
724 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
728 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
730 static bool am_single_threaded(void)
732 __do_closedir
DIR *dir
= NULL
;
733 struct dirent
*direntp
;
736 dir
= opendir("/proc/self/task");
740 while ((direntp
= readdir(dir
))) {
741 if (strcmp(direntp
->d_name
, ".") == 0)
744 if (strcmp(direntp
->d_name
, "..") == 0)
755 static void push_arg(char ***argp
, char *arg
, int *nargs
)
760 copy
= must_copy_string(arg
);
763 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
772 static char **split_init_cmd(const char *incmd
)
774 __do_free
char *copy
= NULL
;
782 copy
= must_copy_string(incmd
);
785 argv
= malloc(sizeof(char *));
789 lxc_iterate_parts (p
, copy
, " ")
790 push_arg(&argv
, p
, &nargs
);
800 static void free_init_cmd(char **argv
)
813 static int lxc_rcv_status(int state_socket
)
819 /* Receive container state. */
820 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
825 TRACE("Caught EINTR; retrying");
832 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
836 /* The first child is going to fork() again and then exits. So we reap
837 * the first child here.
839 ret
= wait_for_pid(pid
);
841 DEBUG("Failed waiting on first child %d", pid
);
843 DEBUG("First child %d exited", pid
);
845 /* Close write end of the socket pair. */
846 close(handler
->state_socket_pair
[1]);
847 handler
->state_socket_pair
[1] = -1;
849 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
851 /* Close read end of the socket pair. */
852 close(handler
->state_socket_pair
[0]);
853 handler
->state_socket_pair
[0] = -1;
856 SYSERROR("Failed to receive the container state");
860 /* If we receive anything else then running we know that the container
863 if (state
!= RUNNING
) {
864 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
865 lxc_state2str(state
));
869 TRACE("Container is in \"RUNNING\" state");
873 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
876 struct lxc_handler
*handler
;
877 struct lxc_conf
*conf
;
878 char *default_args
[] = {
882 char **init_cmd
= NULL
;
883 int keepfds
[3] = {-1, -1, -1};
885 /* container does exist */
889 /* If anything fails before we set error_num, we want an error in there.
893 /* Container has not been setup. */
897 ret
= ongoing_create(c
);
899 case LXC_CREATE_FAILED
:
900 ERROR("Failed checking for incomplete container creation");
902 case LXC_CREATE_ONGOING
:
903 ERROR("Ongoing container creation detected");
905 case LXC_CREATE_INCOMPLETE
:
906 ERROR("Failed to create container");
907 do_lxcapi_destroy(c
);
911 if (container_mem_lock(c
))
916 /* initialize handler */
917 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
919 container_mem_unlock(c
);
924 if (useinit
&& conf
->execute_cmd
)
925 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
927 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
930 /* ... otherwise use default_args. */
933 ERROR("No valid init detected");
934 lxc_free_handler(handler
);
940 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
941 * here to protect the on disk container? We don't want to exclude
942 * things like lxc_info while the container is running.
947 pid_t pid_first
, pid_second
;
951 free_init_cmd(init_cmd
);
952 lxc_free_handler(handler
);
957 if (pid_first
!= 0) {
958 /* Set to NULL because we don't want father unlink
959 * the PID file, child will do the free and unlink.
963 /* Wait for container to tell us whether it started
966 started
= wait_on_daemonized_start(handler
, pid_first
);
968 free_init_cmd(init_cmd
);
969 lxc_free_handler(handler
);
975 /* We don't really care if this doesn't print all the
976 * characters. All that it means is that the proctitle will be
977 * ugly. Similarly, we also don't care if setproctitle() fails.
979 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
981 ret
= setproctitle(title
);
983 INFO("Failed to set process title to %s", title
);
985 INFO("Set process title to %s", title
);
988 /* We fork() a second time to be reparented to init. Like
989 * POSIX's daemon() function we change to "/" and redirect
990 * std{in,out,err} to /dev/null.
993 if (pid_second
< 0) {
994 SYSERROR("Failed to fork first child process");
999 if (pid_second
!= 0) {
1000 free_init_cmd(init_cmd
);
1001 lxc_free_handler(handler
);
1002 _exit(EXIT_SUCCESS
);
1007 /* change to / directory */
1010 SYSERROR("Failed to change to \"/\" directory");
1011 _exit(EXIT_FAILURE
);
1014 keepfds
[0] = handler
->conf
->maincmd_fd
;
1015 keepfds
[1] = handler
->state_socket_pair
[0];
1016 keepfds
[2] = handler
->state_socket_pair
[1];
1017 ret
= lxc_check_inherited(conf
, true, keepfds
,
1018 sizeof(keepfds
) / sizeof(keepfds
[0]));
1020 _exit(EXIT_FAILURE
);
1022 /* redirect std{in,out,err} to /dev/null */
1023 ret
= null_stdfds();
1025 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1026 _exit(EXIT_FAILURE
);
1029 /* become session leader */
1032 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1033 } else if (!am_single_threaded()) {
1034 ERROR("Cannot start non-daemonized container when threaded");
1035 free_init_cmd(init_cmd
);
1036 lxc_free_handler(handler
);
1040 /* We need to write PID file after daemonize, so we always write the
1045 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1047 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1048 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1049 free_init_cmd(init_cmd
);
1050 lxc_free_handler(handler
);
1052 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1055 _exit(EXIT_FAILURE
);
1060 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1062 free_init_cmd(init_cmd
);
1063 lxc_free_handler(handler
);
1065 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1068 _exit(EXIT_FAILURE
);
1074 conf
->reboot
= REBOOT_NONE
;
1076 /* Unshare the mount namespace if requested */
1077 if (conf
->monitor_unshare
) {
1078 ret
= unshare(CLONE_NEWNS
);
1080 SYSERROR("Failed to unshare mount namespace");
1081 lxc_free_handler(handler
);
1086 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1088 SYSERROR("Failed to make / rslave at startup");
1089 lxc_free_handler(handler
);
1096 if (conf
->reboot
== REBOOT_INIT
) {
1097 /* initialize handler */
1098 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1105 keepfds
[0] = handler
->conf
->maincmd_fd
;
1106 keepfds
[1] = handler
->state_socket_pair
[0];
1107 keepfds
[2] = handler
->state_socket_pair
[1];
1108 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1109 sizeof(keepfds
) / sizeof(keepfds
[0]));
1111 lxc_free_handler(handler
);
1117 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1118 c
->daemonize
, &c
->error_num
);
1120 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1121 c
->daemonize
, &c
->error_num
);
1123 if (conf
->reboot
== REBOOT_REQ
) {
1124 INFO("Container requested reboot");
1125 conf
->reboot
= REBOOT_INIT
;
1135 free_init_cmd(init_cmd
);
1137 if (c
->daemonize
&& ret
!= 0)
1138 _exit(EXIT_FAILURE
);
1139 else if (c
->daemonize
)
1140 _exit(EXIT_SUCCESS
);
1148 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1153 current_config
= c
? c
->lxc_conf
: NULL
;
1154 ret
= do_lxcapi_start(c
, useinit
, argv
);
1155 current_config
= NULL
;
1160 /* Note, there MUST be an ending NULL. */
1161 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1164 char **inargs
= NULL
;
1167 /* container exists */
1171 current_config
= c
->lxc_conf
;
1173 va_start(ap
, useinit
);
1174 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1179 /* pass NULL if no arguments were supplied */
1180 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1186 for (arg
= inargs
; *arg
; arg
++)
1191 current_config
= NULL
;
1196 static bool do_lxcapi_stop(struct lxc_container
*c
)
1203 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1208 WRAP_API(bool, lxcapi_stop
)
1210 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1212 __do_free
char *p
= NULL
;
1216 mode_t mask
= umask(0002);
1217 ret
= mkdir(path
, 0770);
1222 if (errno
!= EEXIST
)
1228 p
= must_copy_string(path
);
1230 if (!lxc_list_empty(&conf
->id_map
)) {
1231 ret
= chown_mapped_root(p
, conf
);
1239 /* Create the standard expected container dir. */
1240 static bool create_container_dir(struct lxc_container
*c
)
1246 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1251 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1252 if (ret
< 0 || (size_t)ret
>= len
) {
1257 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1263 /* do_storage_create: thin wrapper around storage_create(). Like
1264 * storage_create(), it returns a mounted bdev on success, NULL on error.
1266 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1268 struct bdev_specs
*specs
)
1270 __do_free
char *dest
= NULL
;
1273 struct lxc_storage
*bdev
;
1275 /* rootfs.path or lxcpath/lxcname/rootfs */
1276 if (c
->lxc_conf
->rootfs
.path
&&
1277 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1278 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1279 len
= strlen(rpath
) + 1;
1280 dest
= must_realloc(NULL
, len
);
1281 ret
= snprintf(dest
, len
, "%s", rpath
);
1283 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1284 len
= strlen(c
->name
) + 1 + strlen(lxcpath
) + 1 + strlen(LXC_ROOTFS_DNAME
) + 1;
1285 dest
= must_realloc(NULL
, len
);
1286 ret
= snprintf(dest
, len
, "%s/%s/%s", lxcpath
, c
->name
, LXC_ROOTFS_DNAME
);
1288 if (ret
< 0 || (size_t)ret
>= len
)
1291 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1293 ERROR("Failed to create \"%s\" storage", type
);
1297 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1298 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1303 /* If we are not root, chown the rootfs dir to root in the target user
1307 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1308 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1310 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1311 suggest_default_idmap();
1320 /* Strip path and return name of file for argv[0] passed to execvp */
1321 static char *lxctemplatefilename(char *tpath
)
1325 p
= tpath
+ strlen(tpath
) - 1;
1326 while ( (p
-1) >= tpath
&& *(p
-1) != '/')
1332 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1333 bool need_null_stdfds
, char *const argv
[])
1343 SYSERROR("Failed to fork task for container creation template");
1347 if (pid
== 0) { /* child */
1349 char *namearg
, *patharg
, *rootfsarg
;
1352 struct lxc_storage
*bdev
= NULL
;
1353 struct lxc_conf
*conf
= c
->lxc_conf
;
1356 if (need_null_stdfds
) {
1357 ret
= null_stdfds();
1359 _exit(EXIT_FAILURE
);
1362 bdev
= storage_init(c
->lxc_conf
);
1364 ERROR("Failed to initialize storage");
1365 _exit(EXIT_FAILURE
);
1370 ret
= unshare(CLONE_NEWNS
);
1372 ERROR("Failed to unshare CLONE_NEWNS");
1373 _exit(EXIT_FAILURE
);
1376 ret
= detect_shared_rootfs();
1378 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1380 SYSERROR("Failed to make \"/\" rslave");
1381 ERROR("Continuing...");
1386 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1388 ERROR("Unprivileged users can only create "
1389 "btrfs and directory-backed containers");
1390 _exit(EXIT_FAILURE
);
1393 if (strcmp(bdev
->type
, "overlay") == 0 ||
1394 strcmp(bdev
->type
, "overlayfs") == 0) {
1395 /* If we create an overlay container we need to
1396 * rsync the contents into
1397 * <container-path>/<container-name>/rootfs.
1398 * However, the overlay mount function will
1400 * <container-path>/<container-name>/delta0
1402 * <container-path>/<container-name>/rootfs
1403 * which means we would rsync the rootfs into
1404 * the delta directory. That doesn't make sense
1405 * since the delta directory only exists to
1406 * record the differences to
1407 * <container-path>/<container-name>/rootfs. So
1408 * let's simply bind-mount here and then rsync
1410 * <container-path>/<container-name>/rootfs.
1414 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1416 ERROR("Failed to get rootfs");
1417 _exit(EXIT_FAILURE
);
1420 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1422 ERROR("Failed to mount rootfs");
1423 _exit(EXIT_FAILURE
);
1426 ret
= bdev
->ops
->mount(bdev
);
1428 ERROR("Failed to mount rootfs");
1429 _exit(EXIT_FAILURE
);
1432 } else { /* TODO come up with a better way here! */
1435 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1436 bdev
->dest
= strdup(src
);
1439 /* Create our new array, pre-pend the template name and base
1443 for (nargs
= 0; argv
[nargs
]; nargs
++)
1446 /* template, path, rootfs and name args */
1449 newargv
= malloc(nargs
* sizeof(*newargv
));
1451 _exit(EXIT_FAILURE
);
1452 newargv
[0] = lxctemplatefilename(tpath
);
1455 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1456 patharg
= malloc(len
);
1458 _exit(EXIT_FAILURE
);
1460 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1461 if (ret
< 0 || ret
>= len
)
1462 _exit(EXIT_FAILURE
);
1463 newargv
[1] = patharg
;
1466 len
= strlen("--name=") + strlen(c
->name
) + 1;
1467 namearg
= malloc(len
);
1469 _exit(EXIT_FAILURE
);
1471 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1472 if (ret
< 0 || ret
>= len
)
1473 _exit(EXIT_FAILURE
);
1474 newargv
[2] = namearg
;
1477 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1478 rootfsarg
= malloc(len
);
1480 _exit(EXIT_FAILURE
);
1482 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1483 if (ret
< 0 || ret
>= len
)
1484 _exit(EXIT_FAILURE
);
1485 newargv
[3] = rootfsarg
;
1487 /* add passed-in args */
1489 for (i
= 4; i
< nargs
; i
++)
1490 newargv
[i
] = argv
[i
- 4];
1492 /* add trailing NULL */
1494 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1496 _exit(EXIT_FAILURE
);
1497 newargv
[nargs
- 1] = NULL
;
1499 /* If we're running the template in a mapped userns, then we
1500 * prepend the template command with: lxc-usernsexec <-m map1>
1501 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1502 * the mapped uid for our geteuid()
1504 if (!lxc_list_empty(&conf
->id_map
)) {
1505 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1507 char txtuid
[20], txtgid
[20];
1508 struct lxc_list
*it
;
1512 n2
= malloc(n2args
* sizeof(*n2
));
1514 _exit(EXIT_FAILURE
);
1517 tpath
= "lxc-usernsexec";
1518 n2
[0] = "lxc-usernsexec";
1520 lxc_list_for_each(it
, &conf
->id_map
) {
1523 n2
= realloc(n2
, n2args
* sizeof(char *));
1525 _exit(EXIT_FAILURE
);
1527 n2
[n2args
- 2] = "-m";
1528 n2
[n2args
- 1] = malloc(200);
1529 if (!n2
[n2args
- 1])
1530 _exit(EXIT_FAILURE
);
1532 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1533 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1534 map
->nsid
, map
->hostid
, map
->range
);
1535 if (ret
< 0 || ret
>= 200)
1536 _exit(EXIT_FAILURE
);
1539 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1540 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1542 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1544 _exit(EXIT_FAILURE
);
1546 if (hostuid_mapped
< 0) {
1547 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1548 n2
[n2args
++] = "-m";
1549 if (hostuid_mapped
< 0) {
1550 ERROR("Failed to find free uid to map");
1551 _exit(EXIT_FAILURE
);
1554 n2
[n2args
++] = malloc(200);
1555 if (!n2
[n2args
- 1]) {
1556 SYSERROR("out of memory");
1557 _exit(EXIT_FAILURE
);
1560 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1561 hostuid_mapped
, geteuid());
1562 if (ret
< 0 || ret
>= 200)
1563 _exit(EXIT_FAILURE
);
1566 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1567 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1569 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1571 _exit(EXIT_FAILURE
);
1573 if (hostgid_mapped
< 0) {
1574 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1575 n2
[n2args
++] = "-m";
1576 if (hostgid_mapped
< 0) {
1577 ERROR("Failed to find free gid to map");
1578 _exit(EXIT_FAILURE
);
1581 n2
[n2args
++] = malloc(200);
1582 if (!n2
[n2args
- 1]) {
1583 SYSERROR("out of memory");
1584 _exit(EXIT_FAILURE
);
1587 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1588 hostgid_mapped
, getegid());
1589 if (ret
< 0 || ret
>= 200)
1590 _exit(EXIT_FAILURE
);
1593 n2
[n2args
++] = "--";
1595 for (i
= 0; i
< nargs
; i
++)
1596 n2
[i
+ n2args
] = newargv
[i
];
1599 /* Finally add "--mapped-uid $uid" to tell template what
1600 * to chown cached images to.
1603 n2
= realloc(n2
, n2args
* sizeof(char *));
1605 _exit(EXIT_FAILURE
);
1607 /* note n2[n2args-1] is NULL */
1608 n2
[n2args
- 5] = "--mapped-uid";
1610 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1611 if (ret
< 0 || ret
>= 20) {
1614 _exit(EXIT_FAILURE
);
1617 n2
[n2args
- 4] = txtuid
;
1618 n2
[n2args
- 3] = "--mapped-gid";
1620 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1621 if (ret
< 0 || ret
>= 20) {
1624 _exit(EXIT_FAILURE
);
1627 n2
[n2args
- 2] = txtgid
;
1628 n2
[n2args
- 1] = NULL
;
1633 execvp(tpath
, newargv
);
1634 SYSERROR("Failed to execute template %s", tpath
);
1635 _exit(EXIT_FAILURE
);
1638 ret
= wait_for_pid(pid
);
1640 ERROR("Failed to create container from template");
1647 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1656 unsigned int md_len
= 0;
1657 unsigned char md_value
[EVP_MAX_MD_SIZE
];
1661 f
= fopen(path
, "re");
1665 ret
= fseek(f
, 0, SEEK_END
);
1674 ret
= fseek(f
, 0, SEEK_SET
);
1678 ret
= fseek(f
, 0, SEEK_SET
);
1683 contents
= malloc(flen
+ 1);
1687 len
= fread(contents
, 1, flen
, f
);
1689 goto out_free_contents
;
1691 contents
[flen
] = '\0';
1696 goto out_free_contents
;
1699 tpath
= get_template_path(t
);
1701 ERROR("Invalid template \"%s\" specified", t
);
1702 goto out_free_contents
;
1705 ret
= sha1sum_file(tpath
, md_value
, &md_len
);
1707 ERROR("Failed to get sha1sum of %s", tpath
);
1709 goto out_free_contents
;
1714 f
= fopen(path
, "we");
1716 SYSERROR("Reopening config for writing");
1721 fprintf(f
, "# Template used to create this container: %s\n", t
);
1723 fprintf(f
, "# Parameters passed to the template:");
1725 fprintf(f
, " %s", *argv
);
1732 fprintf(f
, "# Template script checksum (SHA-1): ");
1733 for (i
=0; i
<md_len
; i
++)
1734 fprintf(f
, "%02x", md_value
[i
]);
1737 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1738 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1739 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1740 fprintf(f
, "# (Be aware this has security implications)\n\n");
1741 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1742 SYSERROR("Writing original contents");
1762 SYSERROR("Error prepending header");
1769 static void lxcapi_clear_config(struct lxc_container
*c
)
1771 if (!c
|| !c
->lxc_conf
)
1774 lxc_conf_free(c
->lxc_conf
);
1778 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1782 * create a container with the given parameters.
1783 * @c: container to be created. It has the lxcpath, name, and a starting
1784 * configuration already set
1785 * @t: the template to execute to instantiate the root filesystem and
1786 * adjust the configuration.
1787 * @bdevtype: backing store type to use. If NULL, dir will be used.
1788 * @specs: additional parameters for the backing store, i.e. LVM vg to
1791 * @argv: the arguments to pass to the template, terminated by NULL. If no
1792 * arguments, you can just pass NULL.
1794 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1795 const char *bdevtype
, struct bdev_specs
*specs
,
1796 int flags
, char *const argv
[])
1801 bool ret
= false, rootfs_managed
= true;
1808 tpath
= get_template_path(t
);
1810 ERROR("Unknown template \"%s\"", t
);
1815 /* If a template is passed in, and the rootfs already is defined in the
1816 * container config and exists, then the caller is trying to create an
1817 * existing container. Return an error, but do NOT delete the container.
1819 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1820 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1821 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1827 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1828 ERROR("Error loading default configuration file %s",
1829 lxc_global_config_value("lxc.default_config"));
1834 if (!create_container_dir(c
))
1837 if (c
->lxc_conf
->rootfs
.path
)
1838 rootfs_managed
= false;
1840 /* If both template and rootfs.path are set, template is setup as
1841 * rootfs.path. The container is already created if we have a config and
1842 * rootfs.path is accessible
1844 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1845 /* No template passed in and rootfs does not exist. */
1846 if (!c
->save_config(c
, NULL
)) {
1847 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1854 /* Rootfs passed into configuration, but does not exist. */
1855 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1858 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1859 /* Rootfs already existed, user just wanted to save the loaded
1862 if (!c
->save_config(c
, NULL
))
1863 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1869 /* Mark that this container is being created */
1870 partial_fd
= create_partial(c
);
1874 /* No need to get disk lock bc we have the partial lock. */
1878 /* Create the storage.
1879 * Note we can't do this in the same task as we use to execute the
1880 * template because of the way zfs works.
1881 * After you 'zfs create', zfs mounts the fs only in the initial
1886 SYSERROR("Failed to fork task for container creation template");
1890 if (pid
== 0) { /* child */
1891 struct lxc_storage
*bdev
= NULL
;
1893 bdev
= do_storage_create(c
, bdevtype
, specs
);
1895 ERROR("Failed to create %s storage for %s",
1896 bdevtype
? bdevtype
: "(none)", c
->name
);
1897 _exit(EXIT_FAILURE
);
1900 /* Save config file again to store the new rootfs location. */
1901 if (!do_lxcapi_save_config(c
, NULL
)) {
1902 ERROR("Failed to save initial config for %s", c
->name
);
1903 /* Parent task won't see the storage driver in the
1904 * config so we delete it.
1906 bdev
->ops
->umount(bdev
);
1907 bdev
->ops
->destroy(bdev
);
1908 _exit(EXIT_FAILURE
);
1911 _exit(EXIT_SUCCESS
);
1914 if (wait_for_pid(pid
) != 0)
1917 /* Reload config to get the rootfs. */
1918 lxc_conf_free(c
->lxc_conf
);
1921 if (!load_config_locked(c
, c
->configfile
))
1924 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1927 /* Now clear out the lxc_conf we have, reload from the created
1930 do_lxcapi_clear_config(c
);
1933 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1934 ERROR("Failed to prepend header to config file");
1939 ret
= load_config_locked(c
, c
->configfile
);
1943 remove_partial(c
, partial_fd
);
1947 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1950 * Ensure that we don't destroy storage we didn't create
1953 if (!rootfs_managed
)
1954 c
->lxc_conf
->rootfs
.managed
= false;
1955 container_destroy(c
, NULL
);
1956 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1964 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1965 const char *bdevtype
, struct bdev_specs
*specs
,
1966 int flags
, char *const argv
[])
1970 current_config
= c
? c
->lxc_conf
: NULL
;
1972 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1973 current_config
= NULL
;
1977 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1979 __do_close
int pidfd
= -EBADF
;
1982 int rebootsignal
= SIGINT
;
1987 if (!do_lxcapi_is_running(c
))
1990 pidfd
= do_lxcapi_init_pidfd(c
);
1992 pid
= do_lxcapi_init_pid(c
);
1997 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1998 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2001 ret
= lxc_raw_pidfd_send_signal(pidfd
, rebootsignal
, NULL
, 0);
2003 ret
= kill(pid
, rebootsignal
);
2005 return log_warn(false, "Failed to send signal %d to pid %d",
2011 WRAP_API(bool, lxcapi_reboot
)
2013 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
2015 __do_close
int pidfd
= -EBADF
, state_client_fd
= -EBADF
;
2016 int rebootsignal
= SIGINT
;
2018 lxc_state_t states
[MAX_STATE
] = {0};
2024 if (!do_lxcapi_is_running(c
))
2027 pidfd
= do_lxcapi_init_pidfd(c
);
2029 pid
= do_lxcapi_init_pid(c
);
2034 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2035 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2037 /* Add a new state client before sending the shutdown signal so that we
2038 * don't miss a state.
2041 states
[RUNNING
] = 2;
2042 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2047 if (state_client_fd
< 0)
2053 if (ret
< MAX_STATE
)
2057 /* Send reboot signal to container. */
2059 killret
= lxc_raw_pidfd_send_signal(pidfd
, rebootsignal
, NULL
, 0);
2061 killret
= kill(pid
, rebootsignal
);
2063 return log_warn(false, "Failed to send signal %d to pid %d", rebootsignal
, pid
);
2064 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2069 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2073 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2080 WRAP_API_1(bool, lxcapi_reboot2
, int)
2082 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2084 __do_close
int pidfd
= -EBADF
, state_client_fd
= -EBADF
;
2085 int haltsignal
= SIGPWR
;
2087 lxc_state_t states
[MAX_STATE
] = {0};
2093 if (!do_lxcapi_is_running(c
))
2096 pidfd
= do_lxcapi_init_pidfd(c
);
2097 pid
= do_lxcapi_init_pid(c
);
2101 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2102 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2103 haltsignal
= c
->lxc_conf
->haltsignal
;
2104 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2105 haltsignal
= (SIGRTMIN
+ 3);
2109 * Add a new state client before sending the shutdown signal so
2110 * that we don't miss a state.
2113 states
[STOPPED
] = 1;
2114 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2119 if (state_client_fd
< 0)
2125 if (ret
< MAX_STATE
)
2129 struct pollfd pidfd_poll
= {
2134 killret
= lxc_raw_pidfd_send_signal(pidfd
, haltsignal
,
2137 return log_warn(false, "Failed to send signal %d to pidfd %d",
2140 TRACE("Sent signal %d to pidfd %d", haltsignal
, pidfd
);
2143 * No need for going through all of the state server
2144 * complications anymore. We can just poll on pidfds. :)
2148 ret
= poll(&pidfd_poll
, 1, timeout
);
2149 if (ret
< 0 || !(pidfd_poll
.revents
& POLLIN
))
2152 TRACE("Pidfd polling detected container exit");
2155 killret
= kill(pid
, haltsignal
);
2157 return log_warn(false, "Failed to send signal %d to pid %d",
2160 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2167 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2171 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2178 WRAP_API_1(bool, lxcapi_shutdown
, int)
2180 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2181 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2190 current_config
= c
->lxc_conf
;
2193 * since we're going to wait for create to finish, I don't think we
2194 * need to get a copy of the arguments.
2196 va_start(ap
, flags
);
2197 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2200 ERROR("Failed to allocate memory");
2204 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2208 current_config
= NULL
;
2212 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2214 if (!strcmp(key
, "lxc.cgroup"))
2215 return clear_unexp_config_line(conf
, key
, true);
2217 if (!strcmp(key
, "lxc.network"))
2218 return clear_unexp_config_line(conf
, key
, true);
2220 if (!strcmp(key
, "lxc.net"))
2221 return clear_unexp_config_line(conf
, key
, true);
2223 /* Clear a network with a specific index. */
2224 if (!strncmp(key
, "lxc.net.", 8)) {
2229 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2231 return clear_unexp_config_line(conf
, key
, true);
2234 if (!strcmp(key
, "lxc.hook"))
2235 return clear_unexp_config_line(conf
, key
, true);
2237 return clear_unexp_config_line(conf
, key
, false);
2240 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2244 struct lxc_config_t
*config
;
2246 if (!c
|| !c
->lxc_conf
)
2249 if (container_mem_lock(c
))
2252 config
= lxc_get_config(key
);
2253 /* Verify that the config key exists and that it has a callback
2256 if (config
&& config
->clr
)
2257 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2260 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2262 container_mem_unlock(c
);
2266 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2268 static inline bool enter_net_ns(struct lxc_container
*c
)
2270 pid_t pid
= do_lxcapi_init_pid(c
);
2275 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2276 (access("/proc/self/ns/user", F_OK
) == 0))
2277 if (!switch_to_ns(pid
, "user"))
2280 return switch_to_ns(pid
, "net");
2283 /* Used by qsort and bsearch functions for comparing names. */
2284 static inline int string_cmp(char **first
, char **second
)
2286 return strcmp(*first
, *second
);
2289 /* Used by qsort and bsearch functions for comparing container names. */
2290 static inline int container_cmp(struct lxc_container
**first
,
2291 struct lxc_container
**second
)
2293 return strcmp((*first
)->name
, (*second
)->name
);
2296 static bool add_to_array(char ***names
, char *cname
, int pos
)
2298 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2300 ERROR("Out of memory");
2305 newnames
[pos
] = strdup(cname
);
2309 /* Sort the array as we will use binary search on it. */
2310 qsort(newnames
, pos
+ 1, sizeof(char *),
2311 (int (*)(const void *, const void *))string_cmp
);
2316 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2319 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2321 ERROR("Out of memory");
2328 /* Sort the array as we will use binary search on it. */
2330 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2331 (int (*)(const void *, const void *))container_cmp
);
2336 static char** get_from_array(char ***names
, char *cname
, int size
)
2338 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2341 static bool array_contains(char ***names
, char *cname
, int size
)
2343 if(get_from_array(names
, cname
, size
) != NULL
)
2349 static bool remove_from_array(char ***names
, char *cname
, int size
)
2351 char **result
= get_from_array(names
, cname
, size
);
2352 if (result
!= NULL
) {
2360 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2363 int i
, count
= 0, pipefd
[2];
2364 char **interfaces
= NULL
;
2365 char interface
[IFNAMSIZ
];
2367 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2372 SYSERROR("Failed to fork task to get interfaces information");
2378 if (pid
== 0) { /* child */
2379 int ret
= 1, nbytes
;
2380 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2382 /* close the read-end of the pipe */
2385 if (!enter_net_ns(c
)) {
2386 SYSERROR("Failed to enter network namespace");
2390 /* Grab the list of interfaces */
2391 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2392 SYSERROR("Failed to get interfaces list");
2396 /* Iterate through the interfaces */
2397 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2398 tempIfAddr
= tempIfAddr
->ifa_next
) {
2399 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2410 netns_freeifaddrs(interfaceArray
);
2412 /* close the write-end of the pipe, thus sending EOF to the reader */
2417 /* close the write-end of the pipe */
2420 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2421 interface
[IFNAMSIZ
- 1] = '\0';
2423 if (array_contains(&interfaces
, interface
, count
))
2426 if (!add_to_array(&interfaces
, interface
, count
))
2427 ERROR("Failed to add \"%s\" to array", interface
);
2432 if (wait_for_pid(pid
) != 0) {
2433 for (i
= 0; i
< count
; i
++)
2434 free(interfaces
[i
]);
2440 /* close the read-end of the pipe */
2443 /* Append NULL to the array */
2445 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2450 WRAP_API(char **, lxcapi_get_interfaces
)
2452 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2453 const char *family
, int scope
)
2458 char address
[INET6_ADDRSTRLEN
];
2460 char **addresses
= NULL
;
2462 ret
= pipe2(pipefd
, O_CLOEXEC
);
2464 SYSERROR("Failed to create pipe");
2470 SYSERROR("Failed to create new process");
2478 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2479 char *address_ptr
= NULL
;
2480 void *tempAddrPtr
= NULL
;
2481 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2483 /* close the read-end of the pipe */
2486 if (!enter_net_ns(c
)) {
2487 SYSERROR("Failed to attach to network namespace");
2491 /* Grab the list of interfaces */
2492 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2493 SYSERROR("Failed to get interfaces list");
2497 /* Iterate through the interfaces */
2498 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2499 tempIfAddr
= tempIfAddr
->ifa_next
) {
2500 if (tempIfAddr
->ifa_addr
== NULL
)
2503 #pragma GCC diagnostic push
2504 #pragma GCC diagnostic ignored "-Wcast-align"
2506 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2507 if (family
&& strcmp(family
, "inet"))
2510 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2512 if (family
&& strcmp(family
, "inet6"))
2515 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2518 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2521 #pragma GCC diagnostic pop
2523 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2525 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2528 address_ptr
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2529 tempAddrPtr
, addressOutputBuffer
,
2530 sizeof(addressOutputBuffer
));
2534 nbytes
= lxc_write_nointr(pipefd
[1], address_ptr
, INET6_ADDRSTRLEN
);
2535 if (nbytes
!= INET6_ADDRSTRLEN
) {
2536 SYSERROR("Failed to send ipv6 address \"%s\"",
2548 netns_freeifaddrs(interfaceArray
);
2550 /* close the write-end of the pipe, thus sending EOF to the reader */
2555 /* close the write-end of the pipe */
2558 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2559 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2561 if (!add_to_array(&addresses
, address
, count
))
2562 ERROR("PARENT: add_to_array failed");
2567 if (wait_for_pid(pid
) != 0) {
2568 for (i
= 0; i
< count
; i
++)
2575 /* close the read-end of the pipe */
2578 /* Append NULL to the array */
2580 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2585 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2587 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2590 struct lxc_config_t
*config
;
2592 if (!c
|| !c
->lxc_conf
)
2595 if (container_mem_lock(c
))
2598 config
= lxc_get_config(key
);
2599 /* Verify that the config key exists and that it has a callback
2602 if (config
&& config
->get
)
2603 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2605 container_mem_unlock(c
);
2609 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2611 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2615 if (!c
|| !c
->lxc_conf
)
2618 if (container_mem_lock(c
))
2621 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2622 container_mem_unlock(c
);
2626 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2628 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2632 /* List all config items. */
2634 return lxc_list_config_items(retv
, inlen
);
2636 if (!c
|| !c
->lxc_conf
)
2639 if (container_mem_lock(c
))
2642 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2643 * This is an intelligent result to show which keys are valid given the
2644 * type of nic it is.
2646 if (strncmp(key
, "lxc.net.", 8) == 0)
2647 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2649 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2651 container_mem_unlock(c
);
2655 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2657 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2660 bool ret
= false, need_disklock
= false;
2663 alt_file
= c
->configfile
;
2668 /* If we haven't yet loaded a config, load the stock config. */
2670 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2671 ERROR("Error loading default configuration file %s "
2673 lxc_global_config_value("lxc.default_config"),
2679 if (!create_container_dir(c
))
2682 /* If we're writing to the container's config file, take the disk lock.
2683 * Otherwise just take the memlock to protect the struct lxc_container
2684 * while we're traversing it.
2686 if (strcmp(c
->configfile
, alt_file
) == 0)
2687 need_disklock
= true;
2690 lret
= container_disk_lock(c
);
2692 lret
= container_mem_lock(c
);
2696 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2697 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2701 lret
= write_config(fd
, c
->lxc_conf
);
2710 container_disk_unlock(c
);
2712 container_mem_unlock(c
);
2717 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2720 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2726 char path
[PATH_MAX
];
2727 char newpath
[PATH_MAX
];
2728 int fd
, ret
, n
= 0, v
= 0;
2730 size_t len
= 0, bytes
= 0;
2732 if (container_disk_lock(c0
))
2735 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2736 if (ret
< 0 || ret
> PATH_MAX
)
2739 ret
= snprintf(newpath
, PATH_MAX
, "%s\n%s\n", c
->config_path
, c
->name
);
2740 if (ret
< 0 || ret
> PATH_MAX
)
2743 /* If we find an lxc-snapshot file using the old format only listing the
2744 * number of snapshots we will keep using it. */
2745 f1
= fopen(path
, "re");
2747 n
= fscanf(f1
, "%d", &v
);
2749 if (n
== 1 && v
== 0) {
2752 SYSERROR("Failed to remove \"%s\"", path
);
2760 f1
= fopen(path
, "we");
2764 if (fprintf(f1
, "%d\n", v
) < 0) {
2765 ERROR("Error writing new snapshots value");
2772 SYSERROR("Error writing to or closing snapshots file");
2776 /* Here we know that we have or can use an lxc-snapshot file
2777 * using the new format. */
2779 f1
= fopen(path
, "ae");
2783 if (fprintf(f1
, "%s", newpath
) < 0) {
2784 ERROR("Error writing new snapshots entry");
2787 SYSERROR("Error writing to or closing snapshots file");
2793 SYSERROR("Error writing to or closing snapshots file");
2797 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2800 if (fstat(fd
, &fbuf
) < 0) {
2805 if (fbuf
.st_size
!= 0) {
2806 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2807 if (buf
== MAP_FAILED
) {
2808 SYSERROR("Failed to create mapping %s", path
);
2813 len
= strlen(newpath
);
2814 while ((del
= strstr((char *)buf
, newpath
))) {
2815 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2819 lxc_strmunmap(buf
, fbuf
.st_size
);
2820 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2821 SYSERROR("Failed to truncate file %s", path
);
2830 /* If the lxc-snapshot file is empty, remove it. */
2831 if (stat(path
, &fbuf
) < 0)
2834 if (!fbuf
.st_size
) {
2837 SYSERROR("Failed to remove \"%s\"", path
);
2844 container_disk_unlock(c0
);
2848 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2850 __do_free
char *lxcpath
= NULL
, *lxcname
= NULL
;
2851 __do_fclose
FILE *f
= NULL
;
2852 size_t pathlen
= 0, namelen
= 0;
2853 struct lxc_container
*p
;
2854 char path
[PATH_MAX
];
2857 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends",
2858 c
->config_path
, c
->name
);
2859 if (ret
< 0 || ret
>= PATH_MAX
) {
2860 ERROR("Path name too long");
2864 f
= fopen(path
, "re");
2868 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2869 if (getline(&lxcname
, &namelen
, f
) == -1) {
2870 ERROR("badly formatted file %s", path
);
2874 remove_trailing_newlines(lxcpath
);
2875 remove_trailing_newlines(lxcname
);
2877 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2878 ERROR("Unable to find dependent container %s:%s",
2883 if (!mod_rdep(p
, c
, inc
))
2884 ERROR("Failed to update snapshots file for %s:%s",
2887 lxc_container_put(p
);
2891 static bool has_fs_snapshots(struct lxc_container
*c
)
2893 __do_fclose
FILE *f
= NULL
;
2894 char path
[PATH_MAX
];
2898 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c
->config_path
,
2900 if (ret
< 0 || ret
> PATH_MAX
)
2903 /* If the file doesn't exist there are no snapshots. */
2904 if (stat(path
, &fbuf
) < 0)
2909 f
= fopen(path
, "re");
2913 ret
= fscanf(f
, "%d", &v
);
2915 INFO("Container uses new lxc-snapshots format %s", path
);
2921 static bool has_snapshots(struct lxc_container
*c
)
2923 __do_closedir
DIR *dir
= NULL
;
2924 char path
[PATH_MAX
];
2925 struct dirent
*direntp
;
2928 if (!get_snappath_dir(c
, path
))
2931 dir
= opendir(path
);
2935 while ((direntp
= readdir(dir
))) {
2936 if (!strcmp(direntp
->d_name
, "."))
2939 if (!strcmp(direntp
->d_name
, ".."))
2948 static bool do_destroy_container(struct lxc_conf
*conf
) {
2951 if (am_guest_unpriv()) {
2952 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2953 "storage_destroy_wrapper");
2960 return storage_destroy(conf
);
2963 static int lxc_rmdir_onedev_wrapper(void *data
)
2965 char *arg
= (char *) data
;
2966 return lxc_rmdir_onedev(arg
, "snaps");
2969 static int lxc_unlink_exec_wrapper(void *data
)
2975 static bool container_destroy(struct lxc_container
*c
,
2976 struct lxc_storage
*storage
)
2980 struct lxc_conf
*conf
;
2985 if (!c
|| !do_lxcapi_is_defined(c
))
2989 if (container_disk_lock(c
))
2992 if (!is_stopped(c
)) {
2993 /* We should queue some sort of error - in c->error_string? */
2994 ERROR("container %s is not stopped", c
->name
);
2998 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2999 /* Start of environment variable setup for hooks */
3000 if (setenv("LXC_NAME", c
->name
, 1))
3001 SYSERROR("Failed to set environment variable for container name");
3003 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3004 SYSERROR("Failed to set environment variable for config path");
3006 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
3007 SYSERROR("Failed to set environment variable for rootfs mount");
3009 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3010 SYSERROR("Failed to set environment variable for rootfs mount");
3012 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
3013 SYSERROR("Failed to set environment variable for console path");
3015 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
3016 SYSERROR("Failed to set environment variable for console log");
3017 /* End of environment variable setup for hooks */
3019 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
3020 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
3025 if (current_config
&& conf
== current_config
) {
3026 current_config
= NULL
;
3028 if (conf
->logfd
!= -1) {
3034 /* LXC is not managing the storage of the container. */
3035 if (conf
&& !conf
->rootfs
.managed
)
3038 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
3039 if (!do_destroy_container(conf
)) {
3040 ERROR("Error destroying rootfs for %s", c
->name
);
3043 INFO("Destroyed rootfs for %s", c
->name
);
3046 mod_all_rdeps(c
, false);
3048 p1
= do_lxcapi_get_config_path(c
);
3057 * strlen("config") = 6
3061 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
3064 ERROR("Failed to allocate memory");
3068 /* For an overlay container the rootfs is considered immutable and
3069 * cannot be removed when restoring from a snapshot.
3071 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3072 !strcmp(storage
->type
, "overlayfs")) &&
3073 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3074 ret
= snprintf(path
, len
, "%s/%s/%s", p1
, c
->name
, LXC_CONFIG_FNAME
);
3075 if (ret
< 0 || (size_t)ret
>= len
)
3078 if (am_guest_unpriv())
3079 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3080 "lxc_unlink_exec_wrapper");
3084 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3088 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3094 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3095 if (ret
< 0 || (size_t)ret
>= len
)
3098 if (am_guest_unpriv())
3099 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3100 "lxc_rmdir_onedev_wrapper");
3102 ret
= lxc_rmdir_onedev(path
, "snaps");
3104 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3108 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3117 container_disk_unlock(c
);
3121 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3123 if (!c
|| !lxcapi_is_defined(c
))
3126 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3127 if (has_snapshots(c
)) {
3128 ERROR("Container %s has snapshots; not removing", c
->name
);
3132 if (has_fs_snapshots(c
)) {
3133 ERROR("container %s has snapshots on its rootfs", c
->name
);
3138 return container_destroy(c
, NULL
);
3141 WRAP_API(bool, lxcapi_destroy
)
3143 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3145 if (!c
|| !lxcapi_is_defined(c
))
3148 if (!lxcapi_snapshot_destroy_all(c
)) {
3149 ERROR("Error deleting all snapshots");
3153 return lxcapi_destroy(c
);
3156 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3158 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3162 struct lxc_config_t
*config
;
3165 config
= lxc_get_config(key
);
3169 ret
= config
->set(key
, v
, conf
, NULL
);
3173 if (lxc_config_value_empty(v
))
3174 do_clear_unexp_config_line(conf
, key
);
3176 bret
= do_append_unexp_config_line(conf
, key
, v
);
3183 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3189 c
->lxc_conf
= lxc_conf_init();
3194 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3201 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3208 if (container_mem_lock(c
))
3211 b
= do_set_config_item_locked(c
, key
, v
);
3213 container_mem_unlock(c
);
3217 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3219 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3221 if (!c
|| !c
->configfile
)
3224 return strdup(c
->configfile
);
3227 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3229 if (!c
|| !c
->config_path
)
3232 return (const char *)(c
->config_path
);
3237 * Just recalculate the c->configfile based on the
3238 * c->config_path, which must be set.
3239 * The lxc_container must be locked or not yet public.
3241 static bool set_config_filename(struct lxc_container
*c
)
3246 if (!c
->config_path
)
3249 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3250 len
= strlen(c
->config_path
) + 1 + strlen(c
->name
) + 1 + strlen(LXC_CONFIG_FNAME
) + 1;
3251 newpath
= malloc(len
);
3255 ret
= snprintf(newpath
, len
, "%s/%s/%s", c
->config_path
, c
->name
, LXC_CONFIG_FNAME
);
3256 if (ret
< 0 || ret
>= len
) {
3257 fprintf(stderr
, "Error printing out config file name\n");
3262 free(c
->configfile
);
3263 c
->configfile
= newpath
;
3268 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3272 char *oldpath
= NULL
;
3277 if (container_mem_lock(c
))
3282 ERROR("Out of memory setting new lxc path");
3288 oldpath
= c
->config_path
;
3291 /* Since we've changed the config path, we have to change the
3292 * config file name too */
3293 if (!set_config_filename(c
)) {
3294 ERROR("Out of memory setting new config filename");
3296 free(c
->config_path
);
3297 c
->config_path
= oldpath
;
3303 container_mem_unlock(c
);
3307 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3309 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3311 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
3319 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3323 return cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
,
3324 c
->config_path
) == 0;
3327 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3329 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3331 call_cleaner(cgroup_exit
) struct cgroup_ops
*cgroup_ops
= NULL
;
3339 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3343 return cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3347 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3349 const char *lxc_get_global_config_item(const char *key
)
3351 return lxc_global_config_value(key
);
3354 const char *lxc_get_version(void)
3359 static int copy_file(const char *old
, const char *new)
3366 if (file_exists(new)) {
3367 ERROR("copy destination %s exists", new);
3371 ret
= stat(old
, &sbuf
);
3373 INFO("Error stat'ing %s", old
);
3377 in
= open(old
, O_RDONLY
);
3379 SYSERROR("Error opening original file %s", old
);
3383 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3385 SYSERROR("Error opening new file %s", new);
3391 len
= lxc_read_nointr(in
, buf
, 8096);
3393 SYSERROR("Error reading old file %s", old
);
3400 ret
= lxc_write_nointr(out
, buf
, len
);
3401 if (ret
< len
) { /* should we retry? */
3402 SYSERROR("Error: write to new file %s was interrupted", new);
3410 /* We set mode, but not owner/group. */
3411 ret
= chmod(new, sbuf
.st_mode
);
3413 SYSERROR("Error setting mode on %s", new);
3425 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3427 __do_free
char *cpath
= NULL
;
3429 struct lxc_list
*it
;
3431 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3432 cpath
= must_realloc(NULL
, len
);
3433 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3434 if (ret
< 0 || ret
>= len
)
3437 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3438 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3439 char *hookname
= it
->elem
;
3440 char *fname
= strrchr(hookname
, '/');
3441 char tmppath
[PATH_MAX
];
3442 if (!fname
) /* relative path - we don't support, but maybe we should */
3445 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3446 /* this hook is public - ignore */
3450 /* copy the script, and change the entry in confile */
3451 ret
= snprintf(tmppath
, PATH_MAX
, "%s/%s/%s",
3452 c
->config_path
, c
->name
, fname
+1);
3453 if (ret
< 0 || ret
>= PATH_MAX
)
3456 ret
= copy_file(it
->elem
, tmppath
);
3462 it
->elem
= strdup(tmppath
);
3464 ERROR("out of memory copying hook path");
3470 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3471 c
->config_path
, oldc
->name
, c
->name
)) {
3472 ERROR("Error saving new hooks in clone");
3476 do_lxcapi_save_config(c
, NULL
);
3481 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3483 char newpath
[PATH_MAX
];
3484 char *oldpath
= oldc
->lxc_conf
->fstab
;
3490 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3492 char *p
= strrchr(oldpath
, '/');
3496 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s%s",
3497 c
->config_path
, c
->name
, p
);
3498 if (ret
< 0 || ret
>= PATH_MAX
) {
3499 ERROR("error printing new path for %s", oldpath
);
3503 if (file_exists(newpath
)) {
3504 ERROR("error: fstab file %s exists", newpath
);
3508 if (copy_file(oldpath
, newpath
) < 0) {
3509 ERROR("error: copying %s to %s", oldpath
, newpath
);
3513 free(c
->lxc_conf
->fstab
);
3515 c
->lxc_conf
->fstab
= strdup(newpath
);
3516 if (!c
->lxc_conf
->fstab
) {
3517 ERROR("error: allocating pathname");
3521 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3522 ERROR("error saving new lxctab");
3529 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3531 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3534 ret
= snprintf(path0
, PATH_MAX
, "%s/%s/lxc_rdepends", c0
->config_path
,
3536 if (ret
< 0 || ret
>= PATH_MAX
) {
3537 WARN("Error copying reverse dependencies");
3541 ret
= snprintf(path1
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3543 if (ret
< 0 || ret
>= PATH_MAX
) {
3544 WARN("Error copying reverse dependencies");
3548 if (copy_file(path0
, path1
) < 0) {
3549 INFO("Error copying reverse dependencies");
3554 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3556 __do_fclose
FILE *f
= NULL
;
3558 char path
[PATH_MAX
];
3560 ret
= snprintf(path
, sizeof(path
), "%s/%s/lxc_rdepends", c
->config_path
, c
->name
);
3561 if (ret
< 0 || ret
>= sizeof(path
))
3564 f
= fopen(path
, "ae");
3568 /* If anything goes wrong, just return an error. */
3569 return 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
)
3580 __do_free
char *p0
= NULL
, *p1
= NULL
;
3582 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3583 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3584 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3586 p0
= must_realloc(NULL
, l0
+ 1);
3587 p1
= must_realloc(NULL
, l1
+ 1);
3588 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3589 if (ret
< 0 || ret
>= l0
)
3592 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3593 if (ret
< 0 || ret
>= l1
)
3596 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3599 if (is_btrfs_subvol(rootfs
) <= 0)
3602 return btrfs_same_fs(p0
, p1
) == 0;
3605 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3606 const char *newtype
, int flags
, const char *bdevdata
,
3609 struct lxc_storage
*bdev
;
3612 if (should_default_to_snapshot(c0
, c
))
3613 flags
|= LXC_CLONE_SNAPSHOT
;
3615 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3616 bdevdata
, newsize
, &need_rdep
);
3618 ERROR("Error copying storage.");
3622 /* Set new rootfs. */
3623 free(c
->lxc_conf
->rootfs
.path
);
3624 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3627 if (!c
->lxc_conf
->rootfs
.path
) {
3628 ERROR("Out of memory while setting storage path.");
3632 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3633 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3634 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3635 c
->lxc_conf
->rootfs
.path
)) {
3636 ERROR("Error saving new rootfs to cloned config.");
3640 if (flags
& LXC_CLONE_SNAPSHOT
)
3641 copy_rdepends(c
, c0
);
3644 if (!add_rdepends(c
, c0
))
3645 WARN("Error adding reverse dependency from %s to %s",
3649 mod_all_rdeps(c
, true);
3654 struct clone_update_data
{
3655 struct lxc_container
*c0
;
3656 struct lxc_container
*c1
;
3661 static int clone_update_rootfs(struct clone_update_data
*data
)
3663 struct lxc_container
*c0
= data
->c0
;
3664 struct lxc_container
*c
= data
->c1
;
3665 int flags
= data
->flags
;
3666 char **hookargs
= data
->hookargs
;
3668 char path
[PATH_MAX
];
3669 struct lxc_storage
*bdev
;
3671 struct lxc_conf
*conf
= c
->lxc_conf
;
3673 /* update hostname in rootfs */
3674 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3676 (void)lxc_setgroups(0, NULL
);
3678 if (setgid(0) < 0) {
3679 ERROR("Failed to setgid to 0");
3683 if (setuid(0) < 0) {
3684 ERROR("Failed to setuid to 0");
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
, "we"))) {
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/%s", lxcpath
, newname
, LXC_CONFIG_FNAME
);
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/%s", lxcpath
, newname
, LXC_ROOTFS_DNAME
);
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
,
4061 lxc_attach_exec_t exec_function
, void *exec_payload
,
4062 lxc_attach_options_t
*options
, pid_t
*attached_process
)
4069 current_config
= c
->lxc_conf
;
4071 ret
= lxc_attach(c
, exec_function
, exec_payload
, options
,
4073 current_config
= NULL
;
4077 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
,
4078 lxc_attach_options_t
*options
,
4079 const char *program
,
4080 const char *const argv
[])
4082 lxc_attach_command_t command
;
4089 command
.program
= (char *)program
;
4090 command
.argv
= (char **)argv
;
4092 ret
= lxc_attach(c
, lxc_attach_run_command
, &command
, options
, &pid
);
4096 return lxc_wait_for_pid_status(pid
);
4099 static int lxcapi_attach_run_wait(struct lxc_container
*c
,
4100 lxc_attach_options_t
*options
,
4101 const char *program
, const char *const argv
[])
4105 current_config
= c
? c
->lxc_conf
: NULL
;
4106 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4107 current_config
= NULL
;
4112 static int get_next_index(const char *lxcpath
, char *cname
)
4114 __do_free
char *fname
= NULL
;
4118 fname
= must_realloc(NULL
, strlen(lxcpath
) + 20);
4121 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4123 ret
= stat(fname
, &sb
);
4131 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4136 * If the old style snapshot path exists, use it
4137 * /var/lib/lxc -> /var/lib/lxcsnaps
4139 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4140 if (ret
< 0 || ret
>= PATH_MAX
)
4143 if (dir_exists(snappath
)) {
4144 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4145 if (ret
< 0 || ret
>= PATH_MAX
)
4152 * Use the new style path
4153 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4155 ret
= snprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4156 if (ret
< 0 || ret
>= PATH_MAX
)
4162 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4164 __do_free
char *dfnam
= NULL
;
4169 struct lxc_container
*c2
;
4170 char snappath
[PATH_MAX
], newname
[20];
4174 if (!c
|| !lxcapi_is_defined(c
))
4177 if (!storage_can_backup(c
->lxc_conf
)) {
4178 ERROR("%s's backing store cannot be backed up", c
->name
);
4179 ERROR("Your container must use another backing store type");
4183 if (!get_snappath_dir(c
, snappath
))
4186 i
= get_next_index(snappath
, c
->name
);
4188 if (mkdir_p(snappath
, 0755) < 0) {
4189 ERROR("Failed to create snapshot directory %s", snappath
);
4193 ret
= snprintf(newname
, 20, "snap%d", i
);
4194 if (ret
< 0 || ret
>= 20)
4198 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4199 * created in the original container
4201 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4202 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4203 if (storage_is_dir(c
->lxc_conf
)) {
4204 ERROR("Snapshot of directory-backed container requested");
4205 ERROR("Making a copy-clone. If you do want snapshots, then");
4206 ERROR("please create overlay clone first, snapshot that");
4207 ERROR("and keep the original container pristine");
4208 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4211 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4213 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4217 lxc_container_put(c2
);
4219 /* Now write down the creation time. */
4222 if (!localtime_r(&timer
, &tm_info
)) {
4223 ERROR("Failed to get localtime");
4227 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4229 len
= strlen(snappath
) + 1 + strlen(newname
) + 1 + strlen(LXC_TIMESTAMP_FNAME
) + 1;
4230 dfnam
= must_realloc(NULL
, len
);
4231 snprintf(dfnam
, len
, "%s/%s/%s", snappath
, newname
, LXC_TIMESTAMP_FNAME
);
4232 f
= fopen(dfnam
, "we");
4234 ERROR("Failed to open %s", dfnam
);
4238 if (fprintf(f
, "%s", buffer
) < 0) {
4239 SYSERROR("Writing timestamp");
4246 SYSERROR("Writing timestamp");
4251 __do_free
char *path
= NULL
;
4252 /* $p / $name / comment \0 */
4253 len
= strlen(snappath
) + 1 + strlen(newname
) + 1 + strlen(LXC_COMMENT_FNAME
) + 1;
4255 path
= must_realloc(NULL
, len
);
4256 snprintf(path
, len
, "%s/%s/%s", snappath
, newname
, LXC_COMMENT_FNAME
);
4257 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4263 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4265 static void lxcsnap_free(struct lxc_snapshot
*s
)
4268 free(s
->comment_pathname
);
4273 static char *get_snapcomment_path(char* snappath
, char *name
)
4275 /* $snappath/$name/comment */
4276 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4277 char *s
= malloc(len
);
4280 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4281 if (ret
< 0 || ret
>= len
) {
4290 static char *get_timestamp(char* snappath
, char *name
)
4292 __do_free
char *s
= NULL
;
4293 __do_fclose
FILE *fin
= NULL
;
4294 char path
[PATH_MAX
];
4297 ret
= snprintf(path
, PATH_MAX
, "%s/%s/ts", snappath
, name
);
4298 if (ret
< 0 || ret
>= PATH_MAX
)
4301 fin
= fopen(path
, "re");
4305 (void) fseek(fin
, 0, SEEK_END
);
4307 (void) fseek(fin
, 0, SEEK_SET
);
4312 if (fread(s
, 1, len
, fin
) != len
)
4313 return log_error_errno(NULL
, errno
, "reading timestamp");
4320 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4322 __do_closedir
DIR *dir
= NULL
;
4323 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4325 struct dirent
*direntp
;
4326 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4328 if (!c
|| !lxcapi_is_defined(c
))
4331 if (!get_snappath_dir(c
, snappath
)) {
4332 ERROR("path name too long");
4336 dir
= opendir(snappath
);
4338 INFO("Failed to open %s - assuming no snapshots", snappath
);
4342 while ((direntp
= readdir(dir
))) {
4343 if (!strcmp(direntp
->d_name
, "."))
4346 if (!strcmp(direntp
->d_name
, ".."))
4349 ret
= snprintf(path2
, PATH_MAX
, "%s/%s/%s", snappath
, direntp
->d_name
, LXC_CONFIG_FNAME
);
4350 if (ret
< 0 || ret
>= PATH_MAX
) {
4351 ERROR("pathname too long");
4355 if (!file_exists(path2
))
4358 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4360 SYSERROR("Out of memory");
4365 snaps
[count
].free
= lxcsnap_free
;
4366 snaps
[count
].name
= strdup(direntp
->d_name
);
4367 if (!snaps
[count
].name
)
4370 snaps
[count
].lxcpath
= strdup(snappath
);
4371 if (!snaps
[count
].lxcpath
) {
4372 free(snaps
[count
].name
);
4376 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4377 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4386 for (int i
= 0; i
< count
; i
++)
4387 lxcsnap_free(&snaps
[i
]);
4395 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4397 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4399 char clonelxcpath
[PATH_MAX
];
4401 struct lxc_container
*snap
, *rest
;
4402 struct lxc_storage
*bdev
;
4405 if (!c
|| !c
->name
|| !c
->config_path
)
4408 if (has_fs_snapshots(c
)) {
4409 ERROR("container rootfs has dependent snapshots");
4413 bdev
= storage_init(c
->lxc_conf
);
4415 ERROR("Failed to find original backing store type");
4419 /* For an overlay container the rootfs is considered immutable
4420 * and cannot be removed when restoring from a snapshot. We pass this
4421 * internal flag along to communicate this to various parts of the
4424 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4425 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4430 if (!get_snappath_dir(c
, clonelxcpath
)) {
4434 /* how should we lock this? */
4436 snap
= lxc_container_new(snapname
, clonelxcpath
);
4437 if (!snap
|| !lxcapi_is_defined(snap
)) {
4438 ERROR("Could not open snapshot %s", snapname
);
4441 lxc_container_put(snap
);
4447 if (!strcmp(c
->name
, newname
)) {
4448 if (!container_destroy(c
, bdev
)) {
4449 ERROR("Could not destroy existing container %s", newname
);
4450 lxc_container_put(snap
);
4456 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4457 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4459 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4460 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4462 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4465 if (rest
&& lxcapi_is_defined(rest
))
4469 lxc_container_put(rest
);
4471 lxc_container_put(snap
);
4475 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4477 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4479 struct lxc_container
*snap
= NULL
;
4482 snap
= lxc_container_new(snapname
, clonelxcpath
);
4484 ERROR("Could not find snapshot %s", snapname
);
4488 if (!do_lxcapi_destroy(snap
)) {
4489 ERROR("Could not destroy snapshot %s", snapname
);
4497 lxc_container_put(snap
);
4502 static bool remove_all_snapshots(const char *path
)
4504 __do_closedir
DIR *dir
= NULL
;
4505 struct dirent
*direntp
;
4508 dir
= opendir(path
);
4510 SYSERROR("opendir on snapshot path %s", path
);
4514 while ((direntp
= readdir(dir
))) {
4515 if (!strcmp(direntp
->d_name
, "."))
4518 if (!strcmp(direntp
->d_name
, ".."))
4521 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4528 SYSERROR("Error removing directory %s", path
);
4533 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4535 char clonelxcpath
[PATH_MAX
];
4537 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4540 if (!get_snappath_dir(c
, clonelxcpath
))
4543 return do_snapshot_destroy(snapname
, clonelxcpath
);
4546 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4548 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4550 char clonelxcpath
[PATH_MAX
];
4552 if (!c
|| !c
->name
|| !c
->config_path
)
4555 if (!get_snappath_dir(c
, clonelxcpath
))
4558 return remove_all_snapshots(clonelxcpath
);
4561 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4563 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4568 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4571 WRAP_API(bool, lxcapi_may_control
)
4573 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4579 char chrootpath
[PATH_MAX
];
4580 char *directory_path
= NULL
;
4584 SYSERROR("Failed to fork()");
4589 ret
= wait_for_pid(pid
);
4591 ERROR("Failed to create device node");
4598 /* prepare the path */
4599 ret
= snprintf(chrootpath
, PATH_MAX
, "/proc/%d/root", init_pid
);
4600 if (ret
< 0 || ret
>= PATH_MAX
)
4603 ret
= chroot(chrootpath
);
4605 _exit(EXIT_FAILURE
);
4609 _exit(EXIT_FAILURE
);
4611 /* remove path if it exists */
4612 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4616 SYSERROR("Failed to remove \"%s\"", path
);
4617 _exit(EXIT_FAILURE
);
4622 _exit(EXIT_SUCCESS
);
4624 /* create any missing directories */
4627 _exit(EXIT_FAILURE
);
4629 directory_path
= dirname(tmp
);
4630 ret
= mkdir_p(directory_path
, 0755);
4631 if (ret
< 0 && errno
!= EEXIST
) {
4632 SYSERROR("Failed to create path \"%s\"", directory_path
);
4634 _exit(EXIT_FAILURE
);
4637 /* create the device node */
4638 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4641 SYSERROR("Failed to create device node at \"%s\"", path
);
4642 _exit(EXIT_FAILURE
);
4645 _exit(EXIT_SUCCESS
);
4648 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4652 char value
[LXC_MAX_BUFFER
];
4656 /* make sure container is running */
4657 if (!do_lxcapi_is_running(c
)) {
4658 ERROR("container is not running");
4662 /* use src_path if dest_path is NULL otherwise use dest_path */
4663 p
= dest_path
? dest_path
: src_path
;
4665 /* make sure we can access p */
4666 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4669 /* continue if path is character device or block device */
4670 if (S_ISCHR(st
.st_mode
))
4671 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4672 else if (S_ISBLK(st
.st_mode
))
4673 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4677 /* check snprintf return code */
4678 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4681 init_pid
= do_lxcapi_init_pid(c
);
4683 ERROR("Failed to get init pid");
4687 if (!do_add_remove_node(init_pid
, p
, add
, &st
))
4690 /* add or remove device to/from cgroup access list */
4692 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4693 ERROR("set_cgroup_item failed while adding the device node");
4697 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4698 ERROR("set_cgroup_item failed while removing the device node");
4706 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4708 // cannot mknod if we're not privileged wrt init_user_ns
4709 if (am_host_unpriv()) {
4710 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4714 return add_remove_device_node(c
, src_path
, dest_path
, true);
4717 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4719 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4721 if (am_guest_unpriv()) {
4722 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4726 return add_remove_device_node(c
, src_path
, dest_path
, false);
4729 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4731 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4733 const char *dst_ifname
)
4738 if (am_guest_unpriv()) {
4739 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4744 ERROR("No source interface name given");
4748 ret
= lxc_netdev_isup(ifname
);
4750 /* netdev of ifname is up. */
4751 ret
= lxc_netdev_down(ifname
);
4756 init_pid
= do_lxcapi_init_pid(c
);
4758 ERROR("Failed to get init pid");
4762 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4766 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4773 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4775 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4777 const char *dst_ifname
)
4780 pid_t pid
, pid_outside
;
4781 __do_free
char *physname
= NULL
;
4784 * TODO - if this is a physical device, then we need am_host_unpriv.
4785 * But for other types guest privilege suffices.
4787 if (am_guest_unpriv()) {
4788 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4793 ERROR("No source interface name given");
4797 pid_outside
= lxc_raw_getpid();
4800 ERROR("Failed to fork");
4804 if (pid
== 0) { /* child */
4807 init_pid
= do_lxcapi_init_pid(c
);
4809 ERROR("Failed to get init pid");
4810 _exit(EXIT_FAILURE
);
4812 if (!switch_to_ns(init_pid
, "net")) {
4813 ERROR("Failed to enter network namespace");
4814 _exit(EXIT_FAILURE
);
4817 /* create new mount namespace for use with remounting /sys and is_wlan() below. */
4818 ret
= unshare(CLONE_NEWNS
);
4820 ERROR("Failed to unshare mount namespace");
4821 _exit(EXIT_FAILURE
);
4824 /* set / recursively as private so that mount propagation doesn't affect us. */
4825 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
4826 ERROR("Failed to recursively set / as private in mount namespace");
4827 _exit(EXIT_FAILURE
);
4830 ret
= lxc_netdev_isup(ifname
);
4832 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4833 _exit(EXIT_FAILURE
);
4836 /* netdev of ifname is up. */
4838 ret
= lxc_netdev_down(ifname
);
4840 ERROR("Failed to set network device \"%s\" down", ifname
);
4841 _exit(EXIT_FAILURE
);
4845 /* remount /sys so is_wlan() can check if this device is a wlan device. */
4846 lxc_attach_remount_sys_proc();
4847 physname
= is_wlan(ifname
);
4849 ret
= lxc_netdev_move_wlan(physname
, ifname
, pid_outside
, dst_ifname
);
4851 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4853 /* -EINVAL means there is no netdev named as ifname. */
4856 ERROR("Network device \"%s\" not found", ifname
);
4858 ERROR("Failed to remove network device \"%s\"", ifname
);
4860 _exit(EXIT_FAILURE
);
4863 _exit(EXIT_SUCCESS
);
4866 ret
= wait_for_pid(pid
);
4870 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4874 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4876 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4877 struct migrate_opts
*opts
, unsigned int size
)
4880 struct migrate_opts
*valid_opts
= opts
;
4881 uint64_t features_to_check
= 0;
4883 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4884 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4885 * to do anything special.
4887 if (size
> sizeof(*opts
)) {
4888 unsigned char *addr
;
4891 addr
= (void *)opts
+ sizeof(*opts
);
4892 end
= (void *)opts
+ size
;
4894 for (; addr
< end
; addr
++)
4899 /* If the caller has a smaller struct, let's zero out the end for them
4900 * so we don't accidentally use bits of it that they didn't know about
4903 if (size
< sizeof(*opts
)) {
4904 valid_opts
= malloc(sizeof(*opts
));
4908 memset(valid_opts
, 0, sizeof(*opts
));
4909 memcpy(valid_opts
, opts
, size
);
4913 case MIGRATE_PRE_DUMP
:
4914 if (!do_lxcapi_is_running(c
)) {
4915 ERROR("container is not running");
4919 ret
= !__criu_pre_dump(c
, valid_opts
);
4922 if (!do_lxcapi_is_running(c
)) {
4923 ERROR("container is not running");
4927 ret
= !__criu_dump(c
, valid_opts
);
4929 case MIGRATE_RESTORE
:
4930 if (do_lxcapi_is_running(c
)) {
4931 ERROR("container is already running");
4935 ret
= !__criu_restore(c
, valid_opts
);
4937 case MIGRATE_FEATURE_CHECK
:
4938 features_to_check
= valid_opts
->features_to_check
;
4939 ret
= !__criu_check_feature(&features_to_check
);
4941 /* Something went wrong. Let's let the caller
4942 * know which feature checks failed. */
4943 valid_opts
->features_to_check
= features_to_check
;
4947 ERROR("invalid migrate command %u", cmd
);
4952 if (size
< sizeof(*opts
))
4958 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4960 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4962 struct migrate_opts opts
;
4964 memset(&opts
, 0, sizeof(opts
));
4966 opts
.directory
= directory
;
4968 opts
.verbose
= verbose
;
4970 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4973 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4975 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4977 struct migrate_opts opts
;
4979 memset(&opts
, 0, sizeof(opts
));
4981 opts
.directory
= directory
;
4982 opts
.verbose
= verbose
;
4984 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4987 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4989 /* @st_mode is the st_mode field of the stat(source) return struct */
4990 static int create_mount_target(const char *dest
, mode_t st_mode
)
4992 char *dirdup
, *destdirname
;
4995 dirdup
= strdup(dest
);
4997 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
5000 destdirname
= dirname(dirdup
);
5002 ret
= mkdir_p(destdirname
, 0755);
5004 SYSERROR("Failed to create \"%s\"", destdirname
);
5012 if (S_ISDIR(st_mode
))
5013 ret
= mkdir(dest
, 0000);
5015 ret
= mknod(dest
, S_IFREG
| 0000, 0);
5018 TRACE("Created mount target \"%s\"", dest
);
5019 else if (ret
< 0 && errno
!= EEXIST
) {
5020 SYSERROR("Failed to create mount target \"%s\"", dest
);
5027 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
5028 const char *target
, const char *filesystemtype
,
5029 unsigned long mountflags
, const void *data
,
5030 struct lxc_mount
*mnt
)
5033 char template[PATH_MAX
], path
[PATH_MAX
];
5034 pid_t pid
, init_pid
;
5037 int ret
= -1, fd
= -EBADF
;
5039 if (!c
|| !c
->lxc_conf
) {
5040 ERROR("Container or configuration is NULL");
5044 if (!c
->lxc_conf
->shmount
.path_host
) {
5045 ERROR("Host path to shared mountpoint must be specified in the config\n");
5049 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5050 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
5051 SYSERROR("Error writing shmounts tempdir name");
5055 /* Create a temporary file / dir under the shared mountpoint */
5056 if (!source
|| strcmp(source
, "") == 0) {
5057 /* If source is not specified, maybe we want to mount a filesystem? */
5058 sb
.st_mode
= S_IFDIR
;
5060 ret
= stat(source
, &sb
);
5062 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5067 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5069 sret
= mkdtemp(template);
5071 SYSERROR("Could not create shmounts temporary dir");
5075 fd
= lxc_make_tmpfile(template, false);
5077 SYSERROR("Could not create shmounts temporary file");
5085 SYSERROR("Could not fork");
5091 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5093 SYSERROR("Failed to mount onto \"%s\"", template);
5094 _exit(EXIT_FAILURE
);
5096 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5098 init_pid
= do_lxcapi_init_pid(c
);
5100 ERROR("Failed to obtain container's init pid");
5101 _exit(EXIT_FAILURE
);
5104 /* Enter the container namespaces */
5105 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5106 if (!switch_to_ns(init_pid
, "user")) {
5107 ERROR("Failed to enter user namespace");
5108 _exit(EXIT_FAILURE
);
5111 if (!lxc_switch_uid_gid(0, 0))
5112 _exit(EXIT_FAILURE
);
5115 if (!switch_to_ns(init_pid
, "mnt")) {
5116 ERROR("Failed to enter mount namespace");
5117 _exit(EXIT_FAILURE
);
5120 ret
= create_mount_target(target
, sb
.st_mode
);
5122 _exit(EXIT_FAILURE
);
5124 suff
= strrchr(template, '/');
5126 goto cleanup_target_in_child
;
5128 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5129 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5130 SYSERROR("Error writing container mountpoint name");
5131 goto cleanup_target_in_child
;
5134 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5136 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5137 goto cleanup_target_in_child
;
5139 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5141 _exit(EXIT_SUCCESS
);
5143 cleanup_target_in_child
:
5144 (void)remove(target
);
5145 _exit(EXIT_FAILURE
);
5148 ret
= wait_for_pid(pid
);
5150 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5154 if (umount2(template, MNT_DETACH
))
5155 SYSWARN("Failed to remove temporary mount \"%s\"", template);
5158 (void)rmdir(template);
5160 (void)unlink(template);
5169 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5170 unsigned long, const void *, struct lxc_mount
*)
5172 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5173 unsigned long flags
, struct lxc_mount
*mnt
)
5175 pid_t pid
, init_pid
;
5178 if (!c
|| !c
->lxc_conf
) {
5179 ERROR("Container or configuration is NULL");
5186 SYSERROR("Could not fork");
5191 init_pid
= do_lxcapi_init_pid(c
);
5193 ERROR("Failed to obtain container's init pid");
5194 _exit(EXIT_FAILURE
);
5197 /* Enter the container namespaces */
5198 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5199 if (!switch_to_ns(init_pid
, "user")) {
5200 ERROR("Failed to enter user namespace");
5201 _exit(EXIT_FAILURE
);
5205 if (!switch_to_ns(init_pid
, "mnt")) {
5206 ERROR("Failed to enter mount namespace");
5207 _exit(EXIT_FAILURE
);
5210 /* Do the unmount */
5211 ret
= umount2(target
, flags
);
5213 SYSERROR("Failed to umount \"%s\"", target
);
5214 _exit(EXIT_FAILURE
);
5217 _exit(EXIT_SUCCESS
);
5220 ret
= wait_for_pid(pid
);
5222 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5229 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5231 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5240 current_config
= c
->lxc_conf
;
5243 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5247 ERROR("Memory allocation error.");
5253 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5257 current_config
= NULL
;
5261 static int do_lxcapi_seccomp_notify_fd(struct lxc_container
*c
)
5263 if (!c
|| !c
->lxc_conf
)
5264 return ret_set_errno(-1, -EINVAL
);
5266 return lxc_seccomp_get_notify_fd(&c
->lxc_conf
->seccomp
);
5269 WRAP_API(int, lxcapi_seccomp_notify_fd
)
5271 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5273 struct lxc_container
*c
;
5280 c
= malloc(sizeof(*c
));
5282 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5285 memset(c
, 0, sizeof(*c
));
5288 c
->config_path
= strdup(configpath
);
5290 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5291 if (!c
->config_path
) {
5292 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5296 remove_trailing_slashes(c
->config_path
);
5299 c
->name
= malloc(len
+ 1);
5301 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5304 (void)strlcpy(c
->name
, name
, len
+ 1);
5307 c
->slock
= lxc_newlock(c
->config_path
, name
);
5309 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5313 c
->privlock
= lxc_newlock(NULL
, NULL
);
5315 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5319 if (!set_config_filename(c
)) {
5320 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5324 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5325 fprintf(stderr
, "Failed to load config for %s\n", name
);
5329 rc
= ongoing_create(c
);
5331 case LXC_CREATE_INCOMPLETE
:
5332 SYSERROR("Failed to complete container creation for %s", c
->name
);
5333 container_destroy(c
, NULL
);
5334 lxcapi_clear_config(c
);
5336 case LXC_CREATE_ONGOING
:
5337 /* container creation going on */
5339 case LXC_CREATE_FAILED
:
5340 /* container creation failed */
5341 if (errno
!= EACCES
&& errno
!= EPERM
) {
5342 /* insufficient privileges */
5343 SYSERROR("Failed checking for incomplete container %s creation", c
->name
);
5349 c
->daemonize
= true;
5352 /* Assign the member functions. */
5353 c
->is_defined
= lxcapi_is_defined
;
5354 c
->state
= lxcapi_state
;
5355 c
->is_running
= lxcapi_is_running
;
5356 c
->freeze
= lxcapi_freeze
;
5357 c
->unfreeze
= lxcapi_unfreeze
;
5358 c
->console
= lxcapi_console
;
5359 c
->console_getfd
= lxcapi_console_getfd
;
5360 c
->init_pid
= lxcapi_init_pid
;
5361 c
->init_pidfd
= lxcapi_init_pidfd
;
5362 c
->load_config
= lxcapi_load_config
;
5363 c
->want_daemonize
= lxcapi_want_daemonize
;
5364 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5365 c
->start
= lxcapi_start
;
5366 c
->startl
= lxcapi_startl
;
5367 c
->stop
= lxcapi_stop
;
5368 c
->config_file_name
= lxcapi_config_file_name
;
5369 c
->wait
= lxcapi_wait
;
5370 c
->set_config_item
= lxcapi_set_config_item
;
5371 c
->destroy
= lxcapi_destroy
;
5372 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5373 c
->rename
= lxcapi_rename
;
5374 c
->save_config
= lxcapi_save_config
;
5375 c
->get_keys
= lxcapi_get_keys
;
5376 c
->create
= lxcapi_create
;
5377 c
->createl
= lxcapi_createl
;
5378 c
->shutdown
= lxcapi_shutdown
;
5379 c
->reboot
= lxcapi_reboot
;
5380 c
->reboot2
= lxcapi_reboot2
;
5381 c
->clear_config
= lxcapi_clear_config
;
5382 c
->clear_config_item
= lxcapi_clear_config_item
;
5383 c
->get_config_item
= lxcapi_get_config_item
;
5384 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5385 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5386 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5387 c
->get_config_path
= lxcapi_get_config_path
;
5388 c
->set_config_path
= lxcapi_set_config_path
;
5389 c
->clone
= lxcapi_clone
;
5390 c
->get_interfaces
= lxcapi_get_interfaces
;
5391 c
->get_ips
= lxcapi_get_ips
;
5392 c
->attach
= lxcapi_attach
;
5393 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5394 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5395 c
->snapshot
= lxcapi_snapshot
;
5396 c
->snapshot_list
= lxcapi_snapshot_list
;
5397 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5398 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5399 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5400 c
->may_control
= lxcapi_may_control
;
5401 c
->add_device_node
= lxcapi_add_device_node
;
5402 c
->remove_device_node
= lxcapi_remove_device_node
;
5403 c
->attach_interface
= lxcapi_attach_interface
;
5404 c
->detach_interface
= lxcapi_detach_interface
;
5405 c
->checkpoint
= lxcapi_checkpoint
;
5406 c
->restore
= lxcapi_restore
;
5407 c
->migrate
= lxcapi_migrate
;
5408 c
->console_log
= lxcapi_console_log
;
5409 c
->mount
= lxcapi_mount
;
5410 c
->umount
= lxcapi_umount
;
5411 c
->seccomp_notify_fd
= lxcapi_seccomp_notify_fd
;
5416 lxc_container_free(c
);
5420 int lxc_get_wait_states(const char **states
)
5425 for (i
=0; i
<MAX_STATE
; i
++)
5426 states
[i
] = lxc_state2str(i
);
5432 * These next two could probably be done smarter with reusing a common function
5433 * with different iterators and tests...
5435 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5437 __do_closedir
DIR *dir
= NULL
;
5438 int i
, cfound
= 0, nfound
= 0;
5439 struct dirent
*direntp
;
5440 struct lxc_container
*c
;
5443 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5445 dir
= opendir(lxcpath
);
5447 SYSERROR("opendir on lxcpath");
5457 while ((direntp
= readdir(dir
))) {
5458 /* Ignore '.', '..' and any hidden directory. */
5459 if (!strncmp(direntp
->d_name
, ".", 1))
5462 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5466 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5476 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5478 INFO("Container %s:%s has a config but could not be loaded",
5479 lxcpath
, direntp
->d_name
);
5482 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5488 if (!do_lxcapi_is_defined(c
)) {
5489 INFO("Container %s:%s has a config but is not defined",
5490 lxcpath
, direntp
->d_name
);
5493 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5496 lxc_container_put(c
);
5500 if (!add_to_clist(cret
, c
, nfound
, true)) {
5501 lxc_container_put(c
);
5511 if (names
&& *names
) {
5512 for (i
= 0; i
< cfound
; i
++)
5517 if (cret
&& *cret
) {
5518 for (i
= 0; i
< nfound
; i
++)
5519 lxc_container_put((*cret
)[i
]);
5526 int list_active_containers(const char *lxcpath
, char ***nret
,
5527 struct lxc_container
***cret
)
5529 __do_free
char *line
= NULL
;
5530 __do_fclose
FILE *f
= NULL
;
5531 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5533 char **ct_name
= NULL
;
5535 struct lxc_container
*c
= NULL
;
5539 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5540 lxcpath_len
= strlen(lxcpath
);
5548 f
= fopen("/proc/net/unix", "re");
5552 while (getline(&line
, &len
, f
) != -1) {
5553 char *p
= strrchr(line
, ' '), *p2
;
5564 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5566 } else if (strncmp(p
, "lxc/", 4) == 0) {
5576 /* Now p is the start of lxc_name. */
5577 p2
= strchr(p
, '/');
5578 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5583 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5587 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5593 p
= lxc_cmd_get_name(p
);
5598 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5604 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5607 goto free_cret_list
;
5618 c
= lxc_container_new(p
, lxcpath
);
5620 INFO("Container %s:%s is running but could not be loaded",
5623 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5634 * If this is an anonymous container, then is_defined *can*
5635 * return false. So we don't do that check. Count on the
5636 * fact that the command socket exists.
5639 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5640 lxc_container_put(c
);
5641 goto free_cret_list
;
5647 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5649 lxc_container_put(c
);
5650 goto free_cret_list
;
5662 if (cret
&& *cret
) {
5663 for (i
= 0; i
< cret_cnt
; i
++)
5664 lxc_container_put((*cret
)[i
]);
5670 for (i
= 0; i
< ct_name_cnt
; i
++)
5679 int list_all_containers(const char *lxcpath
, char ***nret
,
5680 struct lxc_container
***cret
)
5682 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5685 struct lxc_container
**ct_list
= NULL
;
5687 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5691 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5692 if (active_cnt
< 0) {
5697 for (i
= 0; i
< active_cnt
; i
++) {
5698 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5699 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5701 goto free_active_name
;
5707 free(active_name
[i
]);
5708 active_name
[i
] = NULL
;
5715 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5716 struct lxc_container
*c
;
5718 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5720 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5721 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5725 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5726 lxc_container_put(c
);
5747 for (i
= 0; i
< ct_list_cnt
; i
++) {
5748 lxc_container_put(ct_list
[i
]);
5753 for (i
= 0; i
< active_cnt
; i
++) {
5754 free(active_name
[i
]);
5759 for (i
= 0; i
< ct_cnt
; i
++) {
5766 bool lxc_config_item_is_supported(const char *key
)
5768 return !!lxc_get_config(key
);
5771 bool lxc_has_api_extension(const char *extension
)
5773 /* The NULL API extension is always present. :) */
5777 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5778 if (strcmp(api_extensions
[i
], extension
) == 0)