3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <arpa/inet.h>
38 #include <sys/mount.h>
40 #include <sys/syscall.h>
41 #include <sys/sysmacros.h>
42 #include <sys/types.h>
46 #include "../include/netns_ifaddrs.h"
48 #include "api_extensions.h"
52 #include "commands_utils.h"
56 #include "confile_utils.h"
59 #include "initutils.h"
62 #include "lxccontainer.h"
64 #include "memory_utils.h"
66 #include "namespace.h"
69 #include "raw_syscalls.h"
73 #include "storage/btrfs.h"
74 #include "storage/overlay.h"
75 #include "storage_utils.h"
77 #include "syscall_wrappers.h"
84 #include <sys/mkdev.h>
88 #include <../include/lxcmntent.h>
94 #include "include/strlcpy.h"
97 /* Define faccessat() if missing from the C library */
98 #ifndef HAVE_FACCESSAT
99 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
101 #ifdef __NR_faccessat
102 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
110 lxc_log_define(lxccontainer
, lxc
);
112 static bool do_lxcapi_destroy(struct lxc_container
*c
);
113 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
114 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
115 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
116 static bool container_destroy(struct lxc_container
*c
,
117 struct lxc_storage
*storage
);
118 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
119 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
120 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
122 static bool config_file_exists(const char *lxcpath
, const char *cname
)
124 __do_free
char *fname
= NULL
;
128 /* $lxcpath + '/' + $cname + '/config' + \0 */
129 len
= strlen(lxcpath
) + strlen(cname
) + 9;
130 fname
= must_realloc(NULL
, len
);
131 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
132 if (ret
< 0 || (size_t)ret
>= len
)
135 return file_exists(fname
);
139 * A few functions to help detect when a container creation failed. If a
140 * container creation was killed partway through, then trying to actually start
141 * that container could harm the host. We detect this by creating a 'partial'
142 * file under the container directory, and keeping an advisory lock. When
143 * container creation completes, we remove that file. When we load or try to
144 * start a container, if we find that file, without a flock, we remove the
148 LXC_CREATE_FAILED
= -1,
149 LXC_CREATE_SUCCESS
= 0,
150 LXC_CREATE_ONGOING
= 1,
151 LXC_CREATE_INCOMPLETE
= 2,
154 static int ongoing_create(struct lxc_container
*c
)
156 __do_close_prot_errno
int fd
= -EBADF
;
157 __do_free
char *path
= NULL
;
158 struct flock lk
= {0};
162 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
163 path
= must_realloc(NULL
, len
);
164 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
165 if (ret
< 0 || (size_t)ret
>= len
)
166 return LXC_CREATE_FAILED
;
168 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
171 return LXC_CREATE_FAILED
;
173 return LXC_CREATE_SUCCESS
;
177 lk
.l_whence
= SEEK_SET
;
179 * F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
184 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
185 if (ret
< 0 && errno
== EINVAL
) {
186 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
187 if (ret
< 0 && errno
== EWOULDBLOCK
)
191 /* F_OFD_GETLK will not send us back a pid so don't check it. */
193 /* Create is still ongoing. */
194 return LXC_CREATE_ONGOING
;
196 /* Create completed but partial is still there. */
197 return LXC_CREATE_INCOMPLETE
;
200 static int create_partial(struct lxc_container
*c
)
202 __do_free
char *path
= NULL
;
205 struct flock lk
= {0};
207 /* $lxcpath + '/' + $name + '/partial' + \0 */
208 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
209 path
= must_realloc(NULL
, len
);
210 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
211 if (ret
< 0 || (size_t)ret
>= len
)
214 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
219 lk
.l_whence
= SEEK_SET
;
221 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
223 if (errno
== EINVAL
) {
224 ret
= flock(fd
, LOCK_EX
);
229 SYSERROR("Failed to lock partial file %s", path
);
237 static void remove_partial(struct lxc_container
*c
, int fd
)
239 __do_free
char *path
= NULL
;
245 /* $lxcpath + '/' + $name + '/partial' + \0 */
246 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
247 path
= must_realloc(NULL
, len
);
248 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
249 if (ret
< 0 || (size_t)ret
>= len
)
254 SYSERROR("Failed to remove partial file %s", path
);
258 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
259 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
260 * container configuration file.
261 * The container_disk_lock also takes the container_mem_lock.
262 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
263 * NOTHING mutexes two independent programs with their own struct
264 * lxc_container for the same c->name, between API calls. For instance,
265 * c->config_read(); c->start(); Between those calls, data on disk
266 * could change (which shouldn't bother the caller unless for instance
267 * the rootfs get moved). c->config_read(); update; c->config_write();
268 * Two such updaters could race. The callers should therefore check their
269 * results. Trying to prevent that would necessarily expose us to deadlocks
270 * due to hung callers. So I prefer to keep the locks only within our own
271 * functions, not across functions.
273 * If you're going to clone while holding a lxccontainer, increment
274 * c->numthreads (under privlock) before forking. When deleting,
275 * decrement numthreads under privlock, then if it hits 0 you can delete.
276 * Do not ever use a lxccontainer whose numthreads you did not bump.
278 static void lxc_container_free(struct lxc_container
*c
)
284 c
->configfile
= NULL
;
286 free(c
->error_string
);
287 c
->error_string
= NULL
;
290 lxc_putlock(c
->slock
);
295 lxc_putlock(c
->privlock
);
303 lxc_conf_free(c
->lxc_conf
);
307 free(c
->config_path
);
308 c
->config_path
= NULL
;
313 /* Consider the following case:
315 * |====================================================================|
316 * | freer | racing get()er |
317 * |====================================================================|
318 * | lxc_container_put() | lxc_container_get() |
319 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
320 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
321 * | \ lxcunlock() | \ |
322 * | \ lxc_container_free() | \ lxclock() returns |
323 * | | \ c->numthreads < 1 -> return 0 |
324 * | \ \ (free stuff) | |
325 * | \ \ sem_destroy(privlock) | |
326 * |_______________________________|____________________________________|
328 * When the get()er checks numthreads the first time, one of the following
330 * 1. freer has set numthreads = 0. get() returns 0
331 * 2. freer is between lxclock and setting numthreads to 0. get()er will
332 * sem_wait on privlock, get lxclock after freer() drops it, then see
333 * numthreads is 0 and exit without touching lxclock again..
334 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
335 * will see --numthreads = 1 and not call lxc_container_free().
338 int lxc_container_get(struct lxc_container
*c
)
343 /* If someone else has already started freeing the container, don't try
344 * to take the lock, which may be invalid.
346 if (c
->numthreads
< 1)
349 if (container_mem_lock(c
))
352 /* Bail without trying to unlock, bc the privlock is now probably in
355 if (c
->numthreads
< 1)
359 container_mem_unlock(c
);
364 int lxc_container_put(struct lxc_container
*c
)
369 if (container_mem_lock(c
))
374 if (c
->numthreads
< 1) {
375 container_mem_unlock(c
);
376 lxc_container_free(c
);
380 container_mem_unlock(c
);
384 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
393 if (container_mem_lock(c
))
399 statret
= stat(c
->configfile
, &statbuf
);
406 container_mem_unlock(c
);
410 #define WRAP_API(rettype, fnname) \
411 static rettype fnname(struct lxc_container *c) \
414 bool reset_config = false; \
416 if (!current_config && c && c->lxc_conf) { \
417 current_config = c->lxc_conf; \
418 reset_config = true; \
421 ret = do_##fnname(c); \
423 current_config = NULL; \
428 #define WRAP_API_1(rettype, fnname, t1) \
429 static rettype fnname(struct lxc_container *c, t1 a1) \
432 bool reset_config = false; \
434 if (!current_config && c && c->lxc_conf) { \
435 current_config = c->lxc_conf; \
436 reset_config = true; \
439 ret = do_##fnname(c, a1); \
441 current_config = NULL; \
446 #define WRAP_API_2(rettype, fnname, t1, t2) \
447 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
450 bool reset_config = false; \
452 if (!current_config && c && c->lxc_conf) { \
453 current_config = c->lxc_conf; \
454 reset_config = true; \
457 ret = do_##fnname(c, a1, a2); \
459 current_config = NULL; \
464 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
465 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
468 bool reset_config = false; \
470 if (!current_config && c && c->lxc_conf) { \
471 current_config = c->lxc_conf; \
472 reset_config = true; \
475 ret = do_##fnname(c, a1, a2, a3); \
477 current_config = NULL; \
482 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
483 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
484 t4 a4, t5 a5, t6 a6) \
487 bool reset_config = false; \
489 if (!current_config && c && c->lxc_conf) { \
490 current_config = c->lxc_conf; \
491 reset_config = true; \
494 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
496 current_config = NULL; \
501 WRAP_API(bool, lxcapi_is_defined
)
503 static const char *do_lxcapi_state(struct lxc_container
*c
)
510 s
= lxc_getstate(c
->name
, c
->config_path
);
511 return lxc_state2str(s
);
514 WRAP_API(const char *, lxcapi_state
)
516 static bool is_stopped(struct lxc_container
*c
)
520 s
= lxc_getstate(c
->name
, c
->config_path
);
521 return (s
== STOPPED
);
524 static bool do_lxcapi_is_running(struct lxc_container
*c
)
529 return !is_stopped(c
);
532 WRAP_API(bool, lxcapi_is_running
)
534 static bool do_lxcapi_freeze(struct lxc_container
*c
)
538 if (!c
|| !c
->lxc_conf
)
541 s
= lxc_getstate(c
->name
, c
->config_path
);
543 return lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
548 WRAP_API(bool, lxcapi_freeze
)
550 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
554 if (!c
|| !c
->lxc_conf
)
557 s
= lxc_getstate(c
->name
, c
->config_path
);
559 return lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
564 WRAP_API(bool, lxcapi_unfreeze
)
566 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
571 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
574 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
576 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
577 int stdoutfd
, int stderrfd
, int escape
)
584 current_config
= c
->lxc_conf
;
585 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
586 current_config
= NULL
;
591 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
598 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
601 NOTICE("The console log is empty");
602 else if (ret
== -EFAULT
)
603 NOTICE("The container does not keep a console log");
604 else if (ret
== -ENOENT
)
605 NOTICE("The container does not keep a console log file");
606 else if (ret
== -EIO
)
607 NOTICE("Failed to write console log to log file");
609 ERROR("Failed to retrieve console log");
615 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
617 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
622 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
625 WRAP_API(pid_t
, lxcapi_init_pid
)
627 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
630 c
->lxc_conf
= lxc_conf_init();
635 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
638 c
->lxc_conf
->name
= c
->name
;
642 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
646 bool need_disklock
= false, ret
= false;
651 fname
= c
->configfile
;
659 /* If we're reading something other than the container's config, we only
660 * need to lock the in-memory container. If loading the container's
661 * config file, take the disk lock.
663 if (strcmp(fname
, c
->configfile
) == 0)
664 need_disklock
= true;
667 lret
= container_disk_lock(c
);
669 lret
= container_mem_lock(c
);
673 ret
= load_config_locked(c
, fname
);
676 container_disk_unlock(c
);
678 container_mem_unlock(c
);
683 WRAP_API_1(bool, lxcapi_load_config
, const char *)
685 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
687 if (!c
|| !c
->lxc_conf
)
690 if (container_mem_lock(c
))
693 c
->daemonize
= state
;
695 container_mem_unlock(c
);
700 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
702 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
704 if (!c
|| !c
->lxc_conf
)
707 if (container_mem_lock(c
))
710 c
->lxc_conf
->close_all_fds
= state
;
712 container_mem_unlock(c
);
717 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
719 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
727 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
731 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
733 static bool am_single_threaded(void)
736 struct dirent
*direntp
;
739 dir
= opendir("/proc/self/task");
743 while ((direntp
= readdir(dir
))) {
744 if (strcmp(direntp
->d_name
, ".") == 0)
747 if (strcmp(direntp
->d_name
, "..") == 0)
759 static void push_arg(char ***argp
, char *arg
, int *nargs
)
764 copy
= must_copy_string(arg
);
767 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
776 static char **split_init_cmd(const char *incmd
)
778 __do_free
char *copy
= NULL
;
786 copy
= must_copy_string(incmd
);
789 argv
= malloc(sizeof(char *));
793 lxc_iterate_parts (p
, copy
, " ")
794 push_arg(&argv
, p
, &nargs
);
804 static void free_init_cmd(char **argv
)
817 static int lxc_rcv_status(int state_socket
)
823 /* Receive container state. */
824 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
829 TRACE("Caught EINTR; retrying");
836 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
840 /* Close write end of the socket pair. */
841 close(handler
->state_socket_pair
[1]);
842 handler
->state_socket_pair
[1] = -1;
844 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
846 /* Close read end of the socket pair. */
847 close(handler
->state_socket_pair
[0]);
848 handler
->state_socket_pair
[0] = -1;
850 /* The first child is going to fork() again and then exits. So we reap
851 * the first child here.
853 ret
= wait_for_pid(pid
);
855 DEBUG("Failed waiting on first child %d", pid
);
857 DEBUG("First child %d exited", pid
);
860 SYSERROR("Failed to receive the container state");
864 /* If we receive anything else then running we know that the container
867 if (state
!= RUNNING
) {
868 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
869 lxc_state2str(state
));
873 TRACE("Container is in \"RUNNING\" state");
877 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
880 struct lxc_handler
*handler
;
881 struct lxc_conf
*conf
;
882 char *default_args
[] = {
886 char **init_cmd
= NULL
;
887 int keepfds
[3] = {-1, -1, -1};
889 /* container does exist */
893 /* If anything fails before we set error_num, we want an error in there.
897 /* Container has not been setup. */
901 ret
= ongoing_create(c
);
903 case LXC_CREATE_FAILED
:
904 ERROR("Failed checking for incomplete container creation");
906 case LXC_CREATE_ONGOING
:
907 ERROR("Ongoing container creation detected");
909 case LXC_CREATE_INCOMPLETE
:
910 ERROR("Failed to create container");
911 do_lxcapi_destroy(c
);
915 if (container_mem_lock(c
))
920 /* initialize handler */
921 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
923 container_mem_unlock(c
);
928 if (useinit
&& conf
->execute_cmd
)
929 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
931 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
934 /* ... otherwise use default_args. */
937 ERROR("No valid init detected");
938 lxc_free_handler(handler
);
944 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
945 * here to protect the on disk container? We don't want to exclude
946 * things like lxc_info while the container is running.
955 free_init_cmd(init_cmd
);
956 lxc_free_handler(handler
);
962 /* Set to NULL because we don't want father unlink
963 * the PID file, child will do the free and unlink.
967 /* Wait for container to tell us whether it started
970 started
= wait_on_daemonized_start(handler
, pid
);
972 free_init_cmd(init_cmd
);
973 lxc_free_handler(handler
);
979 /* We don't really care if this doesn't print all the
980 * characters. All that it means is that the proctitle will be
981 * ugly. Similarly, we also don't care if setproctitle() fails.
983 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
985 ret
= setproctitle(title
);
987 INFO("Failed to set process title to %s", title
);
989 INFO("Set process title to %s", title
);
992 /* We fork() a second time to be reparented to init. Like
993 * POSIX's daemon() function we change to "/" and redirect
994 * std{in,out,err} to /dev/null.
998 SYSERROR("Failed to fork first child process");
1004 free_init_cmd(init_cmd
);
1005 lxc_free_handler(handler
);
1006 _exit(EXIT_SUCCESS
);
1011 /* change to / directory */
1014 SYSERROR("Failed to change to \"/\" directory");
1015 _exit(EXIT_FAILURE
);
1018 keepfds
[0] = handler
->conf
->maincmd_fd
;
1019 keepfds
[1] = handler
->state_socket_pair
[0];
1020 keepfds
[2] = handler
->state_socket_pair
[1];
1021 ret
= lxc_check_inherited(conf
, true, keepfds
,
1022 sizeof(keepfds
) / sizeof(keepfds
[0]));
1024 _exit(EXIT_FAILURE
);
1026 /* redirect std{in,out,err} to /dev/null */
1027 ret
= null_stdfds();
1029 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1030 _exit(EXIT_FAILURE
);
1033 /* become session leader */
1036 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1037 } else if (!am_single_threaded()) {
1038 ERROR("Cannot start non-daemonized container when threaded");
1039 free_init_cmd(init_cmd
);
1040 lxc_free_handler(handler
);
1044 /* We need to write PID file after daemonize, so we always write the
1049 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1051 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1052 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1053 free_init_cmd(init_cmd
);
1054 lxc_free_handler(handler
);
1056 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1059 _exit(EXIT_FAILURE
);
1064 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1066 free_init_cmd(init_cmd
);
1067 lxc_free_handler(handler
);
1069 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1072 _exit(EXIT_FAILURE
);
1078 conf
->reboot
= REBOOT_NONE
;
1080 /* Unshare the mount namespace if requested */
1081 if (conf
->monitor_unshare
) {
1082 ret
= unshare(CLONE_NEWNS
);
1084 SYSERROR("Failed to unshare mount namespace");
1085 lxc_free_handler(handler
);
1090 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1092 SYSERROR("Failed to make / rslave at startup");
1093 lxc_free_handler(handler
);
1100 if (conf
->reboot
== REBOOT_INIT
) {
1101 /* initialize handler */
1102 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1109 keepfds
[0] = handler
->conf
->maincmd_fd
;
1110 keepfds
[1] = handler
->state_socket_pair
[0];
1111 keepfds
[2] = handler
->state_socket_pair
[1];
1112 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1113 sizeof(keepfds
) / sizeof(keepfds
[0]));
1115 lxc_free_handler(handler
);
1121 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1122 c
->daemonize
, &c
->error_num
);
1124 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1125 c
->daemonize
, &c
->error_num
);
1127 if (conf
->reboot
== REBOOT_REQ
) {
1128 INFO("Container requested reboot");
1129 conf
->reboot
= REBOOT_INIT
;
1139 free_init_cmd(init_cmd
);
1141 if (c
->daemonize
&& ret
!= 0)
1142 _exit(EXIT_FAILURE
);
1143 else if (c
->daemonize
)
1144 _exit(EXIT_SUCCESS
);
1152 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1157 current_config
= c
? c
->lxc_conf
: NULL
;
1158 ret
= do_lxcapi_start(c
, useinit
, argv
);
1159 current_config
= NULL
;
1164 /* Note, there MUST be an ending NULL. */
1165 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1168 char **inargs
= NULL
;
1171 /* container exists */
1175 current_config
= c
->lxc_conf
;
1177 va_start(ap
, useinit
);
1178 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1183 /* pass NULL if no arguments were supplied */
1184 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1190 for (arg
= inargs
; *arg
; arg
++)
1195 current_config
= NULL
;
1200 static bool do_lxcapi_stop(struct lxc_container
*c
)
1207 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1212 WRAP_API(bool, lxcapi_stop
)
1214 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1216 __do_free
char *p
= NULL
;
1220 mode_t mask
= umask(0002);
1221 ret
= mkdir(path
, 0770);
1226 if (errno
!= EEXIST
)
1232 p
= must_copy_string(path
);
1234 if (!lxc_list_empty(&conf
->id_map
)) {
1235 ret
= chown_mapped_root(p
, conf
);
1243 /* Create the standard expected container dir. */
1244 static bool create_container_dir(struct lxc_container
*c
)
1250 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1255 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1256 if (ret
< 0 || (size_t)ret
>= len
) {
1261 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1267 /* do_storage_create: thin wrapper around storage_create(). Like
1268 * storage_create(), it returns a mounted bdev on success, NULL on error.
1270 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1272 struct bdev_specs
*specs
)
1274 __do_free
char *dest
= NULL
;
1277 struct lxc_storage
*bdev
;
1279 /* rootfs.path or lxcpath/lxcname/rootfs */
1280 if (c
->lxc_conf
->rootfs
.path
&&
1281 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1282 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1283 len
= strlen(rpath
) + 1;
1284 dest
= must_realloc(NULL
, len
);
1285 ret
= snprintf(dest
, len
, "%s", rpath
);
1287 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1288 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1289 dest
= must_realloc(NULL
, len
);
1290 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1292 if (ret
< 0 || (size_t)ret
>= len
)
1295 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1297 ERROR("Failed to create \"%s\" storage", type
);
1301 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1302 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1306 /* If we are not root, chown the rootfs dir to root in the target user
1310 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1311 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1313 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1314 suggest_default_idmap();
1323 /* Strip path and return name of file for argv[0] passed to execvp */
1324 static char *lxctemplatefilename(char *tpath
)
1328 p
= tpath
+ strlen(tpath
) - 1;
1329 while ( (p
-1) >= tpath
&& *(p
-1) != '/')
1335 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1336 bool need_null_stdfds
, char *const argv
[])
1346 SYSERROR("Failed to fork task for container creation template");
1350 if (pid
== 0) { /* child */
1352 char *namearg
, *patharg
, *rootfsarg
;
1355 struct lxc_storage
*bdev
= NULL
;
1356 struct lxc_conf
*conf
= c
->lxc_conf
;
1359 if (need_null_stdfds
) {
1360 ret
= null_stdfds();
1362 _exit(EXIT_FAILURE
);
1365 bdev
= storage_init(c
->lxc_conf
);
1367 ERROR("Failed to initialize storage");
1368 _exit(EXIT_FAILURE
);
1373 ret
= unshare(CLONE_NEWNS
);
1375 ERROR("Failed to unshare CLONE_NEWNS");
1376 _exit(EXIT_FAILURE
);
1379 ret
= detect_shared_rootfs();
1381 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1383 SYSERROR("Failed to make \"/\" rslave");
1384 ERROR("Continuing...");
1389 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1391 ERROR("Unprivileged users can only create "
1392 "btrfs and directory-backed containers");
1393 _exit(EXIT_FAILURE
);
1396 if (strcmp(bdev
->type
, "overlay") == 0 ||
1397 strcmp(bdev
->type
, "overlayfs") == 0) {
1398 /* If we create an overlay container we need to
1399 * rsync the contents into
1400 * <container-path>/<container-name>/rootfs.
1401 * However, the overlay mount function will
1403 * <container-path>/<container-name>/delta0
1405 * <container-path>/<container-name>/rootfs
1406 * which means we would rsync the rootfs into
1407 * the delta directory. That doesn't make sense
1408 * since the delta directory only exists to
1409 * record the differences to
1410 * <container-path>/<container-name>/rootfs. So
1411 * let's simply bind-mount here and then rsync
1413 * <container-path>/<container-name>/rootfs.
1417 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1419 ERROR("Failed to get rootfs");
1420 _exit(EXIT_FAILURE
);
1423 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1425 ERROR("Failed to mount rootfs");
1426 _exit(EXIT_FAILURE
);
1429 ret
= bdev
->ops
->mount(bdev
);
1431 ERROR("Failed to mount rootfs");
1432 _exit(EXIT_FAILURE
);
1435 } else { /* TODO come up with a better way here! */
1438 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1439 bdev
->dest
= strdup(src
);
1442 /* Create our new array, pre-pend the template name and base
1446 for (nargs
= 0; argv
[nargs
]; nargs
++)
1449 /* template, path, rootfs and name args */
1452 newargv
= malloc(nargs
* sizeof(*newargv
));
1454 _exit(EXIT_FAILURE
);
1455 newargv
[0] = lxctemplatefilename(tpath
);
1458 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1459 patharg
= malloc(len
);
1461 _exit(EXIT_FAILURE
);
1463 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1464 if (ret
< 0 || ret
>= len
)
1465 _exit(EXIT_FAILURE
);
1466 newargv
[1] = patharg
;
1469 len
= strlen("--name=") + strlen(c
->name
) + 1;
1470 namearg
= malloc(len
);
1472 _exit(EXIT_FAILURE
);
1474 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1475 if (ret
< 0 || ret
>= len
)
1476 _exit(EXIT_FAILURE
);
1477 newargv
[2] = namearg
;
1480 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1481 rootfsarg
= malloc(len
);
1483 _exit(EXIT_FAILURE
);
1485 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1486 if (ret
< 0 || ret
>= len
)
1487 _exit(EXIT_FAILURE
);
1488 newargv
[3] = rootfsarg
;
1490 /* add passed-in args */
1492 for (i
= 4; i
< nargs
; i
++)
1493 newargv
[i
] = argv
[i
- 4];
1495 /* add trailing NULL */
1497 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1499 _exit(EXIT_FAILURE
);
1500 newargv
[nargs
- 1] = NULL
;
1502 /* If we're running the template in a mapped userns, then we
1503 * prepend the template command with: lxc-usernsexec <-m map1>
1504 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1505 * the mapped uid for our geteuid()
1507 if (!lxc_list_empty(&conf
->id_map
)) {
1508 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1510 char txtuid
[20], txtgid
[20];
1511 struct lxc_list
*it
;
1515 n2
= malloc(n2args
* sizeof(*n2
));
1517 _exit(EXIT_FAILURE
);
1520 tpath
= "lxc-usernsexec";
1521 n2
[0] = "lxc-usernsexec";
1523 lxc_list_for_each(it
, &conf
->id_map
) {
1526 n2
= realloc(n2
, n2args
* sizeof(char *));
1528 _exit(EXIT_FAILURE
);
1530 n2
[n2args
- 2] = "-m";
1531 n2
[n2args
- 1] = malloc(200);
1532 if (!n2
[n2args
- 1])
1533 _exit(EXIT_FAILURE
);
1535 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1536 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1537 map
->nsid
, map
->hostid
, map
->range
);
1538 if (ret
< 0 || ret
>= 200)
1539 _exit(EXIT_FAILURE
);
1542 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1543 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1545 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1547 _exit(EXIT_FAILURE
);
1549 if (hostuid_mapped
< 0) {
1550 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1551 n2
[n2args
++] = "-m";
1552 if (hostuid_mapped
< 0) {
1553 ERROR("Failed to find free uid to map");
1554 _exit(EXIT_FAILURE
);
1557 n2
[n2args
++] = malloc(200);
1558 if (!n2
[n2args
- 1]) {
1559 SYSERROR("out of memory");
1560 _exit(EXIT_FAILURE
);
1563 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1564 hostuid_mapped
, geteuid());
1565 if (ret
< 0 || ret
>= 200)
1566 _exit(EXIT_FAILURE
);
1569 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1570 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1572 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1574 _exit(EXIT_FAILURE
);
1576 if (hostgid_mapped
< 0) {
1577 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1578 n2
[n2args
++] = "-m";
1579 if (hostgid_mapped
< 0) {
1580 ERROR("Failed to find free gid to map");
1581 _exit(EXIT_FAILURE
);
1584 n2
[n2args
++] = malloc(200);
1585 if (!n2
[n2args
- 1]) {
1586 SYSERROR("out of memory");
1587 _exit(EXIT_FAILURE
);
1590 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1591 hostgid_mapped
, getegid());
1592 if (ret
< 0 || ret
>= 200)
1593 _exit(EXIT_FAILURE
);
1596 n2
[n2args
++] = "--";
1598 for (i
= 0; i
< nargs
; i
++)
1599 n2
[i
+ n2args
] = newargv
[i
];
1602 /* Finally add "--mapped-uid $uid" to tell template what
1603 * to chown cached images to.
1606 n2
= realloc(n2
, n2args
* sizeof(char *));
1608 _exit(EXIT_FAILURE
);
1610 /* note n2[n2args-1] is NULL */
1611 n2
[n2args
- 5] = "--mapped-uid";
1613 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1614 if (ret
< 0 || ret
>= 20) {
1617 _exit(EXIT_FAILURE
);
1620 n2
[n2args
- 4] = txtuid
;
1621 n2
[n2args
- 3] = "--mapped-gid";
1623 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1624 if (ret
< 0 || ret
>= 20) {
1627 _exit(EXIT_FAILURE
);
1630 n2
[n2args
- 2] = txtgid
;
1631 n2
[n2args
- 1] = NULL
;
1636 execvp(tpath
, newargv
);
1637 SYSERROR("Failed to execute template %s", tpath
);
1638 _exit(EXIT_FAILURE
);
1641 ret
= wait_for_pid(pid
);
1643 ERROR("Failed to create container from template");
1650 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1659 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1663 f
= fopen(path
, "r");
1667 ret
= fseek(f
, 0, SEEK_END
);
1676 ret
= fseek(f
, 0, SEEK_SET
);
1680 ret
= fseek(f
, 0, SEEK_SET
);
1685 contents
= malloc(flen
+ 1);
1689 len
= fread(contents
, 1, flen
, f
);
1691 goto out_free_contents
;
1693 contents
[flen
] = '\0';
1698 goto out_free_contents
;
1701 tpath
= get_template_path(t
);
1703 ERROR("Invalid template \"%s\" specified", t
);
1704 goto out_free_contents
;
1707 ret
= sha1sum_file(tpath
, md_value
);
1709 ERROR("Failed to get sha1sum of %s", tpath
);
1711 goto out_free_contents
;
1716 f
= fopen(path
, "w");
1718 SYSERROR("Reopening config for writing");
1723 fprintf(f
, "# Template used to create this container: %s\n", t
);
1725 fprintf(f
, "# Parameters passed to the template:");
1727 fprintf(f
, " %s", *argv
);
1734 fprintf(f
, "# Template script checksum (SHA-1): ");
1735 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1736 fprintf(f
, "%02x", md_value
[i
]);
1739 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1740 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1741 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1742 fprintf(f
, "# (Be aware this has security implications)\n\n");
1743 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1744 SYSERROR("Writing original contents");
1764 SYSERROR("Error prepending header");
1771 static void lxcapi_clear_config(struct lxc_container
*c
)
1773 if (!c
|| !c
->lxc_conf
)
1776 lxc_conf_free(c
->lxc_conf
);
1780 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1784 * create a container with the given parameters.
1785 * @c: container to be created. It has the lxcpath, name, and a starting
1786 * configuration already set
1787 * @t: the template to execute to instantiate the root filesystem and
1788 * adjust the configuration.
1789 * @bdevtype: backing store type to use. If NULL, dir will be used.
1790 * @specs: additional parameters for the backing store, i.e. LVM vg to
1793 * @argv: the arguments to pass to the template, terminated by NULL. If no
1794 * arguments, you can just pass NULL.
1796 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1797 const char *bdevtype
, struct bdev_specs
*specs
,
1798 int flags
, char *const argv
[])
1803 bool ret
= false, rootfs_managed
= true;
1810 tpath
= get_template_path(t
);
1812 ERROR("Unknown template \"%s\"", t
);
1817 /* If a template is passed in, and the rootfs already is defined in the
1818 * container config and exists, then the caller is trying to create an
1819 * existing container. Return an error, but do NOT delete the container.
1821 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1822 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1823 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1829 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1830 ERROR("Error loading default configuration file %s",
1831 lxc_global_config_value("lxc.default_config"));
1836 if (!create_container_dir(c
))
1839 if (c
->lxc_conf
->rootfs
.path
)
1840 rootfs_managed
= false;
1842 /* If both template and rootfs.path are set, template is setup as
1843 * rootfs.path. The container is already created if we have a config and
1844 * rootfs.path is accessible
1846 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1847 /* No template passed in and rootfs does not exist. */
1848 if (!c
->save_config(c
, NULL
)) {
1849 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1856 /* Rootfs passed into configuration, but does not exist. */
1857 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1860 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1861 /* Rootfs already existed, user just wanted to save the loaded
1864 if (!c
->save_config(c
, NULL
))
1865 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1871 /* Mark that this container is being created */
1872 partial_fd
= create_partial(c
);
1876 /* No need to get disk lock bc we have the partial lock. */
1880 /* Create the storage.
1881 * Note we can't do this in the same task as we use to execute the
1882 * template because of the way zfs works.
1883 * After you 'zfs create', zfs mounts the fs only in the initial
1888 SYSERROR("Failed to fork task for container creation template");
1892 if (pid
== 0) { /* child */
1893 struct lxc_storage
*bdev
= NULL
;
1895 bdev
= do_storage_create(c
, bdevtype
, specs
);
1897 ERROR("Failed to create %s storage for %s",
1898 bdevtype
? bdevtype
: "(none)", c
->name
);
1899 _exit(EXIT_FAILURE
);
1902 /* Save config file again to store the new rootfs location. */
1903 if (!do_lxcapi_save_config(c
, NULL
)) {
1904 ERROR("Failed to save initial config for %s", c
->name
);
1905 /* Parent task won't see the storage driver in the
1906 * config so we delete it.
1908 bdev
->ops
->umount(bdev
);
1909 bdev
->ops
->destroy(bdev
);
1910 _exit(EXIT_FAILURE
);
1913 _exit(EXIT_SUCCESS
);
1916 if (wait_for_pid(pid
) != 0)
1919 /* Reload config to get the rootfs. */
1920 lxc_conf_free(c
->lxc_conf
);
1923 if (!load_config_locked(c
, c
->configfile
))
1926 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1929 /* Now clear out the lxc_conf we have, reload from the created
1932 do_lxcapi_clear_config(c
);
1935 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1936 ERROR("Failed to prepend header to config file");
1941 ret
= load_config_locked(c
, c
->configfile
);
1945 remove_partial(c
, partial_fd
);
1949 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1952 * Ensure that we don't destroy storage we didn't create
1955 if (!rootfs_managed
)
1956 c
->lxc_conf
->rootfs
.managed
= false;
1957 container_destroy(c
, NULL
);
1958 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1966 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1967 const char *bdevtype
, struct bdev_specs
*specs
,
1968 int flags
, char *const argv
[])
1972 current_config
= c
? c
->lxc_conf
: NULL
;
1974 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1975 current_config
= NULL
;
1979 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1983 int rebootsignal
= SIGINT
;
1988 if (!do_lxcapi_is_running(c
))
1991 pid
= do_lxcapi_init_pid(c
);
1995 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1996 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1998 ret
= kill(pid
, rebootsignal
);
2000 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2007 WRAP_API(bool, lxcapi_reboot
)
2009 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
2013 int rebootsignal
= SIGINT
, state_client_fd
= -1;
2014 lxc_state_t states
[MAX_STATE
] = {0};
2019 if (!do_lxcapi_is_running(c
))
2022 pid
= do_lxcapi_init_pid(c
);
2026 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2027 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2029 /* Add a new state client before sending the shutdown signal so that we
2030 * don't miss a state.
2033 states
[RUNNING
] = 2;
2034 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2039 if (state_client_fd
< 0)
2045 if (ret
< MAX_STATE
)
2049 /* Send reboot signal to container. */
2050 killret
= kill(pid
, rebootsignal
);
2052 if (state_client_fd
>= 0)
2053 close(state_client_fd
);
2055 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2058 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2063 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2064 close(state_client_fd
);
2068 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2075 WRAP_API_1(bool, lxcapi_reboot2
, int)
2077 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2081 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2082 lxc_state_t states
[MAX_STATE
] = {0};
2087 if (!do_lxcapi_is_running(c
))
2090 pid
= do_lxcapi_init_pid(c
);
2094 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2095 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2096 haltsignal
= c
->lxc_conf
->haltsignal
;
2097 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2098 haltsignal
= (SIGRTMIN
+ 3);
2100 /* Add a new state client before sending the shutdown signal so that we
2101 * don't miss a state.
2104 states
[STOPPED
] = 1;
2105 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2110 if (state_client_fd
< 0)
2116 if (ret
< MAX_STATE
)
2120 /* Send shutdown signal to container. */
2121 killret
= kill(pid
, haltsignal
);
2123 if (state_client_fd
>= 0)
2124 close(state_client_fd
);
2126 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2129 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2134 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2135 close(state_client_fd
);
2139 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2146 WRAP_API_1(bool, lxcapi_shutdown
, int)
2148 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2149 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2158 current_config
= c
->lxc_conf
;
2161 * since we're going to wait for create to finish, I don't think we
2162 * need to get a copy of the arguments.
2164 va_start(ap
, flags
);
2165 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2168 ERROR("Failed to allocate memory");
2172 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2176 current_config
= NULL
;
2180 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2182 if (!strcmp(key
, "lxc.cgroup"))
2183 return clear_unexp_config_line(conf
, key
, true);
2185 if (!strcmp(key
, "lxc.network"))
2186 return clear_unexp_config_line(conf
, key
, true);
2188 if (!strcmp(key
, "lxc.net"))
2189 return clear_unexp_config_line(conf
, key
, true);
2191 /* Clear a network with a specific index. */
2192 if (!strncmp(key
, "lxc.net.", 8)) {
2197 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2199 return clear_unexp_config_line(conf
, key
, true);
2202 if (!strcmp(key
, "lxc.hook"))
2203 return clear_unexp_config_line(conf
, key
, true);
2205 return clear_unexp_config_line(conf
, key
, false);
2208 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2212 struct lxc_config_t
*config
;
2214 if (!c
|| !c
->lxc_conf
)
2217 if (container_mem_lock(c
))
2220 config
= lxc_get_config(key
);
2221 /* Verify that the config key exists and that it has a callback
2224 if (config
&& config
->clr
)
2225 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2228 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2230 container_mem_unlock(c
);
2234 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2236 static inline bool enter_net_ns(struct lxc_container
*c
)
2238 pid_t pid
= do_lxcapi_init_pid(c
);
2243 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2244 (access("/proc/self/ns/user", F_OK
) == 0))
2245 if (!switch_to_ns(pid
, "user"))
2248 return switch_to_ns(pid
, "net");
2251 /* Used by qsort and bsearch functions for comparing names. */
2252 static inline int string_cmp(char **first
, char **second
)
2254 return strcmp(*first
, *second
);
2257 /* Used by qsort and bsearch functions for comparing container names. */
2258 static inline int container_cmp(struct lxc_container
**first
,
2259 struct lxc_container
**second
)
2261 return strcmp((*first
)->name
, (*second
)->name
);
2264 static bool add_to_array(char ***names
, char *cname
, int pos
)
2266 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2268 ERROR("Out of memory");
2273 newnames
[pos
] = strdup(cname
);
2277 /* Sort the array as we will use binary search on it. */
2278 qsort(newnames
, pos
+ 1, sizeof(char *),
2279 (int (*)(const void *, const void *))string_cmp
);
2284 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2287 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2289 ERROR("Out of memory");
2296 /* Sort the array as we will use binary search on it. */
2298 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2299 (int (*)(const void *, const void *))container_cmp
);
2304 static char** get_from_array(char ***names
, char *cname
, int size
)
2306 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2309 static bool array_contains(char ***names
, char *cname
, int size
)
2311 if(get_from_array(names
, cname
, size
) != NULL
)
2317 static bool remove_from_array(char ***names
, char *cname
, int size
)
2319 char **result
= get_from_array(names
, cname
, size
);
2320 if (result
!= NULL
) {
2328 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2331 int i
, count
= 0, pipefd
[2];
2332 char **interfaces
= NULL
;
2333 char interface
[IFNAMSIZ
];
2335 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2340 SYSERROR("Failed to fork task to get interfaces information");
2346 if (pid
== 0) { /* child */
2347 int ret
= 1, nbytes
;
2348 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2350 /* close the read-end of the pipe */
2353 if (!enter_net_ns(c
)) {
2354 SYSERROR("Failed to enter network namespace");
2358 /* Grab the list of interfaces */
2359 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2360 SYSERROR("Failed to get interfaces list");
2364 /* Iterate through the interfaces */
2365 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2366 tempIfAddr
= tempIfAddr
->ifa_next
) {
2367 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2378 netns_freeifaddrs(interfaceArray
);
2380 /* close the write-end of the pipe, thus sending EOF to the reader */
2385 /* close the write-end of the pipe */
2388 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2389 interface
[IFNAMSIZ
- 1] = '\0';
2391 if (array_contains(&interfaces
, interface
, count
))
2394 if (!add_to_array(&interfaces
, interface
, count
))
2395 ERROR("Failed to add \"%s\" to array", interface
);
2400 if (wait_for_pid(pid
) != 0) {
2401 for (i
= 0; i
< count
; i
++)
2402 free(interfaces
[i
]);
2408 /* close the read-end of the pipe */
2411 /* Append NULL to the array */
2413 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2418 WRAP_API(char **, lxcapi_get_interfaces
)
2420 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2421 const char *family
, int scope
)
2426 char address
[INET6_ADDRSTRLEN
];
2428 char **addresses
= NULL
;
2430 ret
= pipe2(pipefd
, O_CLOEXEC
);
2432 SYSERROR("Failed to create pipe");
2438 SYSERROR("Failed to create new process");
2446 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2447 char *address_ptr
= NULL
;
2448 void *tempAddrPtr
= NULL
;
2449 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2451 /* close the read-end of the pipe */
2454 if (!enter_net_ns(c
)) {
2455 SYSERROR("Failed to attach to network namespace");
2459 /* Grab the list of interfaces */
2460 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2461 SYSERROR("Failed to get interfaces list");
2465 /* Iterate through the interfaces */
2466 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2467 tempIfAddr
= tempIfAddr
->ifa_next
) {
2468 if (tempIfAddr
->ifa_addr
== NULL
)
2471 #pragma GCC diagnostic push
2472 #pragma GCC diagnostic ignored "-Wcast-align"
2474 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2475 if (family
&& strcmp(family
, "inet"))
2478 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2480 if (family
&& strcmp(family
, "inet6"))
2483 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2486 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2489 #pragma GCC diagnostic pop
2491 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2493 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2496 address_ptr
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2497 tempAddrPtr
, addressOutputBuffer
,
2498 sizeof(addressOutputBuffer
));
2502 nbytes
= lxc_write_nointr(pipefd
[1], address_ptr
, INET6_ADDRSTRLEN
);
2503 if (nbytes
!= INET6_ADDRSTRLEN
) {
2504 SYSERROR("Failed to send ipv6 address \"%s\"",
2516 netns_freeifaddrs(interfaceArray
);
2518 /* close the write-end of the pipe, thus sending EOF to the reader */
2523 /* close the write-end of the pipe */
2526 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2527 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2529 if (!add_to_array(&addresses
, address
, count
))
2530 ERROR("PARENT: add_to_array failed");
2535 if (wait_for_pid(pid
) != 0) {
2536 for (i
= 0; i
< count
; i
++)
2543 /* close the read-end of the pipe */
2546 /* Append NULL to the array */
2548 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2553 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2555 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2558 struct lxc_config_t
*config
;
2560 if (!c
|| !c
->lxc_conf
)
2563 if (container_mem_lock(c
))
2566 config
= lxc_get_config(key
);
2567 /* Verify that the config key exists and that it has a callback
2570 if (config
&& config
->get
)
2571 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2573 container_mem_unlock(c
);
2577 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2579 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2583 if (!c
|| !c
->lxc_conf
)
2586 if (container_mem_lock(c
))
2589 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2590 container_mem_unlock(c
);
2594 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2596 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2600 /* List all config items. */
2602 return lxc_list_config_items(retv
, inlen
);
2604 if (!c
|| !c
->lxc_conf
)
2607 if (container_mem_lock(c
))
2610 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2611 * This is an intelligent result to show which keys are valid given the
2612 * type of nic it is.
2614 if (strncmp(key
, "lxc.net.", 8) == 0)
2615 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2617 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2619 container_mem_unlock(c
);
2623 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2625 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2628 bool ret
= false, need_disklock
= false;
2631 alt_file
= c
->configfile
;
2636 /* If we haven't yet loaded a config, load the stock config. */
2638 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2639 ERROR("Error loading default configuration file %s "
2641 lxc_global_config_value("lxc.default_config"),
2647 if (!create_container_dir(c
))
2650 /* If we're writing to the container's config file, take the disk lock.
2651 * Otherwise just take the memlock to protect the struct lxc_container
2652 * while we're traversing it.
2654 if (strcmp(c
->configfile
, alt_file
) == 0)
2655 need_disklock
= true;
2658 lret
= container_disk_lock(c
);
2660 lret
= container_mem_lock(c
);
2664 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2665 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2669 lret
= write_config(fd
, c
->lxc_conf
);
2678 container_disk_unlock(c
);
2680 container_mem_unlock(c
);
2685 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2688 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2694 char path
[PATH_MAX
];
2695 char newpath
[PATH_MAX
];
2696 int fd
, ret
, n
= 0, v
= 0;
2698 size_t len
= 0, bytes
= 0;
2700 if (container_disk_lock(c0
))
2703 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2704 if (ret
< 0 || ret
> PATH_MAX
)
2707 ret
= snprintf(newpath
, PATH_MAX
, "%s\n%s\n", c
->config_path
, c
->name
);
2708 if (ret
< 0 || ret
> PATH_MAX
)
2711 /* If we find an lxc-snapshot file using the old format only listing the
2712 * number of snapshots we will keep using it. */
2713 f1
= fopen(path
, "r");
2715 n
= fscanf(f1
, "%d", &v
);
2717 if (n
== 1 && v
== 0) {
2720 SYSERROR("Failed to remove \"%s\"", path
);
2728 f1
= fopen(path
, "w");
2732 if (fprintf(f1
, "%d\n", v
) < 0) {
2733 ERROR("Error writing new snapshots value");
2740 SYSERROR("Error writing to or closing snapshots file");
2744 /* Here we know that we have or can use an lxc-snapshot file
2745 * using the new format. */
2747 f1
= fopen(path
, "a");
2751 if (fprintf(f1
, "%s", newpath
) < 0) {
2752 ERROR("Error writing new snapshots entry");
2755 SYSERROR("Error writing to or closing snapshots file");
2761 SYSERROR("Error writing to or closing snapshots file");
2765 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2768 if (fstat(fd
, &fbuf
) < 0) {
2773 if (fbuf
.st_size
!= 0) {
2774 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2775 if (buf
== MAP_FAILED
) {
2776 SYSERROR("Failed to create mapping %s", path
);
2781 len
= strlen(newpath
);
2782 while ((del
= strstr((char *)buf
, newpath
))) {
2783 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2787 lxc_strmunmap(buf
, fbuf
.st_size
);
2788 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2789 SYSERROR("Failed to truncate file %s", path
);
2798 /* If the lxc-snapshot file is empty, remove it. */
2799 if (stat(path
, &fbuf
) < 0)
2802 if (!fbuf
.st_size
) {
2805 SYSERROR("Failed to remove \"%s\"", path
);
2812 container_disk_unlock(c0
);
2816 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2818 struct lxc_container
*p
;
2819 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[PATH_MAX
];
2820 size_t pathlen
= 0, namelen
= 0;
2824 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends",
2825 c
->config_path
, c
->name
);
2826 if (ret
< 0 || ret
>= PATH_MAX
) {
2827 ERROR("Path name too long");
2831 f
= fopen(path
, "r");
2835 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2836 if (getline(&lxcname
, &namelen
, f
) == -1) {
2837 ERROR("badly formatted file %s", path
);
2841 remove_trailing_newlines(lxcpath
);
2842 remove_trailing_newlines(lxcname
);
2844 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2845 ERROR("Unable to find dependent container %s:%s",
2850 if (!mod_rdep(p
, c
, inc
))
2851 ERROR("Failed to update snapshots file for %s:%s",
2854 lxc_container_put(p
);
2863 static bool has_fs_snapshots(struct lxc_container
*c
)
2866 char path
[PATH_MAX
];
2871 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c
->config_path
,
2873 if (ret
< 0 || ret
> PATH_MAX
)
2876 /* If the file doesn't exist there are no snapshots. */
2877 if (stat(path
, &fbuf
) < 0)
2882 f
= fopen(path
, "r");
2886 ret
= fscanf(f
, "%d", &v
);
2888 /* TODO: Figure out what to do with the return value of fscanf. */
2890 INFO("Container uses new lxc-snapshots format %s", path
);
2899 static bool has_snapshots(struct lxc_container
*c
)
2901 char path
[PATH_MAX
];
2902 struct dirent
*direntp
;
2906 if (!get_snappath_dir(c
, path
))
2909 dir
= opendir(path
);
2913 while ((direntp
= readdir(dir
))) {
2914 if (!strcmp(direntp
->d_name
, "."))
2917 if (!strcmp(direntp
->d_name
, ".."))
2927 static bool do_destroy_container(struct lxc_conf
*conf
) {
2930 if (am_guest_unpriv()) {
2931 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2932 "storage_destroy_wrapper");
2939 return storage_destroy(conf
);
2942 static int lxc_rmdir_onedev_wrapper(void *data
)
2944 char *arg
= (char *) data
;
2945 return lxc_rmdir_onedev(arg
, "snaps");
2948 static int lxc_unlink_exec_wrapper(void *data
)
2954 static bool container_destroy(struct lxc_container
*c
,
2955 struct lxc_storage
*storage
)
2959 struct lxc_conf
*conf
;
2964 if (!c
|| !do_lxcapi_is_defined(c
))
2968 if (container_disk_lock(c
))
2971 if (!is_stopped(c
)) {
2972 /* We should queue some sort of error - in c->error_string? */
2973 ERROR("container %s is not stopped", c
->name
);
2977 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2978 /* Start of environment variable setup for hooks */
2979 if (setenv("LXC_NAME", c
->name
, 1))
2980 SYSERROR("Failed to set environment variable for container name");
2982 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2983 SYSERROR("Failed to set environment variable for config path");
2985 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2986 SYSERROR("Failed to set environment variable for rootfs mount");
2988 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2989 SYSERROR("Failed to set environment variable for rootfs mount");
2991 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2992 SYSERROR("Failed to set environment variable for console path");
2994 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2995 SYSERROR("Failed to set environment variable for console log");
2996 /* End of environment variable setup for hooks */
2998 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2999 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
3004 if (current_config
&& conf
== current_config
) {
3005 current_config
= NULL
;
3007 if (conf
->logfd
!= -1) {
3013 /* LXC is not managing the storage of the container. */
3014 if (conf
&& !conf
->rootfs
.managed
)
3017 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
3018 if (!do_destroy_container(conf
)) {
3019 ERROR("Error destroying rootfs for %s", c
->name
);
3022 INFO("Destroyed rootfs for %s", c
->name
);
3025 mod_all_rdeps(c
, false);
3027 p1
= do_lxcapi_get_config_path(c
);
3036 * strlen("config") = 6
3040 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3043 ERROR("Failed to allocate memory");
3047 /* For an overlay container the rootfs is considered immutable and
3048 * cannot be removed when restoring from a snapshot.
3050 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3051 !strcmp(storage
->type
, "overlayfs")) &&
3052 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3053 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3054 if (ret
< 0 || (size_t)ret
>= len
)
3057 if (am_guest_unpriv())
3058 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3059 "lxc_unlink_exec_wrapper");
3063 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3067 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3073 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3074 if (ret
< 0 || (size_t)ret
>= len
)
3077 if (am_guest_unpriv())
3078 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3079 "lxc_rmdir_onedev_wrapper");
3081 ret
= lxc_rmdir_onedev(path
, "snaps");
3083 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3087 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3096 container_disk_unlock(c
);
3100 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3102 if (!c
|| !lxcapi_is_defined(c
))
3105 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3106 if (has_snapshots(c
)) {
3107 ERROR("Container %s has snapshots; not removing", c
->name
);
3111 if (has_fs_snapshots(c
)) {
3112 ERROR("container %s has snapshots on its rootfs", c
->name
);
3117 return container_destroy(c
, NULL
);
3120 WRAP_API(bool, lxcapi_destroy
)
3122 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3124 if (!c
|| !lxcapi_is_defined(c
))
3127 if (!lxcapi_snapshot_destroy_all(c
)) {
3128 ERROR("Error deleting all snapshots");
3132 return lxcapi_destroy(c
);
3135 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3137 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3141 struct lxc_config_t
*config
;
3144 config
= lxc_get_config(key
);
3148 ret
= config
->set(key
, v
, conf
, NULL
);
3152 if (lxc_config_value_empty(v
))
3153 do_clear_unexp_config_line(conf
, key
);
3155 bret
= do_append_unexp_config_line(conf
, key
, v
);
3162 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3168 c
->lxc_conf
= lxc_conf_init();
3173 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3180 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3187 if (container_mem_lock(c
))
3190 b
= do_set_config_item_locked(c
, key
, v
);
3192 container_mem_unlock(c
);
3196 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3198 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3200 if (!c
|| !c
->configfile
)
3203 return strdup(c
->configfile
);
3206 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3208 if (!c
|| !c
->config_path
)
3211 return (const char *)(c
->config_path
);
3216 * Just recalculate the c->configfile based on the
3217 * c->config_path, which must be set.
3218 * The lxc_container must be locked or not yet public.
3220 static bool set_config_filename(struct lxc_container
*c
)
3225 if (!c
->config_path
)
3228 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3229 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3230 newpath
= malloc(len
);
3234 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3235 if (ret
< 0 || ret
>= len
) {
3236 fprintf(stderr
, "Error printing out config file name\n");
3241 free(c
->configfile
);
3242 c
->configfile
= newpath
;
3247 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3251 char *oldpath
= NULL
;
3256 if (container_mem_lock(c
))
3261 ERROR("Out of memory setting new lxc path");
3267 oldpath
= c
->config_path
;
3270 /* Since we've changed the config path, we have to change the
3271 * config file name too */
3272 if (!set_config_filename(c
)) {
3273 ERROR("Out of memory setting new config filename");
3275 free(c
->config_path
);
3276 c
->config_path
= oldpath
;
3282 container_mem_unlock(c
);
3286 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3288 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3291 struct cgroup_ops
*cgroup_ops
;
3299 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3303 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3305 cgroup_exit(cgroup_ops
);
3310 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3312 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3315 struct cgroup_ops
*cgroup_ops
;
3323 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3327 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3330 cgroup_exit(cgroup_ops
);
3335 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3337 const char *lxc_get_global_config_item(const char *key
)
3339 return lxc_global_config_value(key
);
3342 const char *lxc_get_version(void)
3347 static int copy_file(const char *old
, const char *new)
3354 if (file_exists(new)) {
3355 ERROR("copy destination %s exists", new);
3359 ret
= stat(old
, &sbuf
);
3361 INFO("Error stat'ing %s", old
);
3365 in
= open(old
, O_RDONLY
);
3367 SYSERROR("Error opening original file %s", old
);
3371 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3373 SYSERROR("Error opening new file %s", new);
3379 len
= lxc_read_nointr(in
, buf
, 8096);
3381 SYSERROR("Error reading old file %s", old
);
3388 ret
= lxc_write_nointr(out
, buf
, len
);
3389 if (ret
< len
) { /* should we retry? */
3390 SYSERROR("Error: write to new file %s was interrupted", new);
3398 /* We set mode, but not owner/group. */
3399 ret
= chmod(new, sbuf
.st_mode
);
3401 SYSERROR("Error setting mode on %s", new);
3413 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3415 __do_free
char *cpath
= NULL
;
3417 struct lxc_list
*it
;
3419 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3420 cpath
= must_realloc(NULL
, len
);
3421 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3422 if (ret
< 0 || ret
>= len
)
3425 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3426 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3427 char *hookname
= it
->elem
;
3428 char *fname
= strrchr(hookname
, '/');
3429 char tmppath
[PATH_MAX
];
3430 if (!fname
) /* relative path - we don't support, but maybe we should */
3433 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3434 /* this hook is public - ignore */
3438 /* copy the script, and change the entry in confile */
3439 ret
= snprintf(tmppath
, PATH_MAX
, "%s/%s/%s",
3440 c
->config_path
, c
->name
, fname
+1);
3441 if (ret
< 0 || ret
>= PATH_MAX
)
3444 ret
= copy_file(it
->elem
, tmppath
);
3450 it
->elem
= strdup(tmppath
);
3452 ERROR("out of memory copying hook path");
3458 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3459 c
->config_path
, oldc
->name
, c
->name
)) {
3460 ERROR("Error saving new hooks in clone");
3464 do_lxcapi_save_config(c
, NULL
);
3469 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3471 char newpath
[PATH_MAX
];
3472 char *oldpath
= oldc
->lxc_conf
->fstab
;
3478 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3480 char *p
= strrchr(oldpath
, '/');
3484 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s%s",
3485 c
->config_path
, c
->name
, p
);
3486 if (ret
< 0 || ret
>= PATH_MAX
) {
3487 ERROR("error printing new path for %s", oldpath
);
3491 if (file_exists(newpath
)) {
3492 ERROR("error: fstab file %s exists", newpath
);
3496 if (copy_file(oldpath
, newpath
) < 0) {
3497 ERROR("error: copying %s to %s", oldpath
, newpath
);
3501 free(c
->lxc_conf
->fstab
);
3503 c
->lxc_conf
->fstab
= strdup(newpath
);
3504 if (!c
->lxc_conf
->fstab
) {
3505 ERROR("error: allocating pathname");
3509 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3510 ERROR("error saving new lxctab");
3517 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3519 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3522 ret
= snprintf(path0
, PATH_MAX
, "%s/%s/lxc_rdepends", c0
->config_path
,
3524 if (ret
< 0 || ret
>= PATH_MAX
) {
3525 WARN("Error copying reverse dependencies");
3529 ret
= snprintf(path1
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3531 if (ret
< 0 || ret
>= PATH_MAX
) {
3532 WARN("Error copying reverse dependencies");
3536 if (copy_file(path0
, path1
) < 0) {
3537 INFO("Error copying reverse dependencies");
3542 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3545 char path
[PATH_MAX
];
3549 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3551 if (ret
< 0 || ret
>= PATH_MAX
)
3554 f
= fopen(path
, "a");
3560 /* If anything goes wrong, just return an error. */
3561 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3571 * If the fs natively supports snapshot clones with no penalty,
3572 * then default to those even if not requested.
3573 * Currently we only do this for btrfs.
3575 bool should_default_to_snapshot(struct lxc_container
*c0
,
3576 struct lxc_container
*c1
)
3578 __do_free
char *p0
= NULL
, *p1
= NULL
;
3580 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3581 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3582 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3584 p0
= must_realloc(NULL
, l0
+ 1);
3585 p1
= must_realloc(NULL
, l1
+ 1);
3586 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3587 if (ret
< 0 || ret
>= l0
)
3590 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3591 if (ret
< 0 || ret
>= l1
)
3594 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3597 if (is_btrfs_subvol(rootfs
) <= 0)
3600 return btrfs_same_fs(p0
, p1
) == 0;
3603 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3604 const char *newtype
, int flags
, const char *bdevdata
,
3607 struct lxc_storage
*bdev
;
3610 if (should_default_to_snapshot(c0
, c
))
3611 flags
|= LXC_CLONE_SNAPSHOT
;
3613 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3614 bdevdata
, newsize
, &need_rdep
);
3616 ERROR("Error copying storage.");
3620 /* Set new rootfs. */
3621 free(c
->lxc_conf
->rootfs
.path
);
3622 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3625 if (!c
->lxc_conf
->rootfs
.path
) {
3626 ERROR("Out of memory while setting storage path.");
3630 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3631 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3632 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3633 c
->lxc_conf
->rootfs
.path
)) {
3634 ERROR("Error saving new rootfs to cloned config.");
3638 if (flags
& LXC_CLONE_SNAPSHOT
)
3639 copy_rdepends(c
, c0
);
3642 if (!add_rdepends(c
, c0
))
3643 WARN("Error adding reverse dependency from %s to %s",
3647 mod_all_rdeps(c
, true);
3652 struct clone_update_data
{
3653 struct lxc_container
*c0
;
3654 struct lxc_container
*c1
;
3659 static int clone_update_rootfs(struct clone_update_data
*data
)
3661 struct lxc_container
*c0
= data
->c0
;
3662 struct lxc_container
*c
= data
->c1
;
3663 int flags
= data
->flags
;
3664 char **hookargs
= data
->hookargs
;
3666 char path
[PATH_MAX
];
3667 struct lxc_storage
*bdev
;
3669 struct lxc_conf
*conf
= c
->lxc_conf
;
3671 /* update hostname in rootfs */
3672 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3674 if (setgid(0) < 0) {
3675 ERROR("Failed to setgid to 0");
3679 if (setuid(0) < 0) {
3680 ERROR("Failed to setuid to 0");
3684 if (setgroups(0, NULL
) < 0)
3685 WARN("Failed to clear groups");
3687 if (unshare(CLONE_NEWNS
) < 0)
3690 bdev
= storage_init(c
->lxc_conf
);
3694 if (strcmp(bdev
->type
, "dir") != 0) {
3695 if (unshare(CLONE_NEWNS
) < 0) {
3696 ERROR("error unsharing mounts");
3701 if (detect_shared_rootfs()) {
3702 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3703 SYSERROR("Failed to make / rslave");
3704 ERROR("Continuing...");
3708 if (bdev
->ops
->mount(bdev
) < 0) {
3712 } else { /* TODO come up with a better way */
3714 bdev
->dest
= strdup(lxc_storage_get_path(bdev
->src
, bdev
->type
));
3717 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3718 /* Start of environment variable setup for hooks */
3719 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3720 SYSERROR("failed to set environment variable for source container name");
3722 if (setenv("LXC_NAME", c
->name
, 1))
3723 SYSERROR("failed to set environment variable for container name");
3725 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3726 SYSERROR("failed to set environment variable for config path");
3728 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3729 SYSERROR("failed to set environment variable for rootfs mount");
3731 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3732 SYSERROR("failed to set environment variable for rootfs mount");
3734 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3735 ERROR("Error executing clone hook for %s", c
->name
);
3741 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3742 ret
= snprintf(path
, PATH_MAX
, "%s/etc/hostname", bdev
->dest
);
3745 if (ret
< 0 || ret
>= PATH_MAX
)
3748 if (!file_exists(path
))
3751 if (!(fout
= fopen(path
, "w"))) {
3752 SYSERROR("unable to open %s: ignoring", path
);
3756 if (fprintf(fout
, "%s", c
->name
) < 0) {
3761 if (fclose(fout
) < 0)
3770 static int clone_update_rootfs_wrapper(void *data
)
3772 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3773 return clone_update_rootfs(arg
);
3777 * We want to support:
3778 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3779 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3781 -s [ implies overlay]
3784 only rootfs gets converted (copied/snapshotted) on clone.
3787 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3789 char *p
= strrchr(path
, '/');
3796 ret
= do_create_container_dir(path
, conf
);
3802 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3803 const char *lxcpath
, int flags
,
3804 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3807 char newpath
[PATH_MAX
];
3809 struct clone_update_data data
;
3810 size_t saved_unexp_len
;
3812 int storage_copied
= 0;
3813 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3814 struct lxc_container
*c2
= NULL
;
3816 if (!c
|| !do_lxcapi_is_defined(c
))
3819 if (container_mem_lock(c
))
3821 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3822 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3826 /* Make sure the container doesn't yet exist. */
3831 lxcpath
= do_lxcapi_get_config_path(c
);
3833 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/config", lxcpath
, newname
);
3834 if (ret
< 0 || ret
>= PATH_MAX
) {
3835 SYSERROR("clone: failed making config pathname");
3839 if (file_exists(newpath
)) {
3840 ERROR("error: clone: %s exists", newpath
);
3844 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3845 if (ret
< 0 && errno
!= EEXIST
) {
3846 ERROR("Error creating container dir for %s", newpath
);
3850 /* Copy the configuration. Tweak it as needed. */
3851 if (c
->lxc_conf
->rootfs
.path
) {
3852 origroot
= c
->lxc_conf
->rootfs
.path
;
3853 c
->lxc_conf
->rootfs
.path
= NULL
;
3856 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3857 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3859 SYSERROR("Failed to open \"%s\"", newpath
);
3863 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3864 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3865 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3866 if (!c
->lxc_conf
->unexpanded_config
) {
3871 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3872 write_config(fd
, c
->lxc_conf
);
3875 c
->lxc_conf
->rootfs
.path
= origroot
;
3877 free(c
->lxc_conf
->unexpanded_config
);
3878 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3879 saved_unexp_conf
= NULL
;
3880 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3882 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, newname
);
3883 if (ret
< 0 || ret
>= PATH_MAX
) {
3884 SYSERROR("clone: failed making rootfs pathname");
3888 ret
= mkdir(newpath
, 0755);
3890 /* For an overlay container the rootfs is considered immutable
3891 * and will not have been removed when restoring from a
3894 if (errno
!= ENOENT
&&
3895 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3896 SYSERROR("Failed to create directory \"%s\"", newpath
);
3901 if (am_guest_unpriv()) {
3902 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3903 ERROR("Error chowning %s to container root", newpath
);
3908 c2
= lxc_container_new(newname
, lxcpath
);
3910 ERROR("clone: failed to create new container (%s %s)", newname
,
3915 /* copy/snapshot rootfs's */
3916 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3920 /* update utsname */
3921 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3922 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3923 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3925 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3926 ERROR("Error setting new hostname");
3932 ret
= copyhooks(c
, c2
);
3934 ERROR("error copying hooks");
3938 if (copy_fstab(c
, c2
) < 0) {
3939 ERROR("error copying fstab");
3943 /* update macaddrs */
3944 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3945 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3946 ERROR("Error updating mac addresses");
3951 /* Update absolute paths for overlay mount directories. */
3952 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3955 /* We've now successfully created c2's storage, so clear it out if we
3960 if (!c2
->save_config(c2
, NULL
))
3963 if ((pid
= fork()) < 0) {
3969 ret
= wait_for_pid(pid
);
3973 container_mem_unlock(c
);
3980 data
.hookargs
= hookargs
;
3982 if (am_guest_unpriv())
3983 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3984 &data
, "clone_update_rootfs_wrapper");
3986 ret
= clone_update_rootfs(&data
);
3988 _exit(EXIT_FAILURE
);
3990 container_mem_unlock(c
);
3991 _exit(EXIT_SUCCESS
);
3994 container_mem_unlock(c
);
3996 if (!storage_copied
)
3997 c2
->lxc_conf
->rootfs
.path
= NULL
;
4000 lxc_container_put(c2
);
4006 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
4007 const char *lxcpath
, int flags
,
4008 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
4011 struct lxc_container
* ret
;
4013 current_config
= c
? c
->lxc_conf
: NULL
;
4014 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
4015 current_config
= NULL
;
4020 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4022 struct lxc_storage
*bdev
;
4023 struct lxc_container
*newc
;
4025 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4028 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4029 ERROR("Renaming a container with snapshots is not supported");
4033 bdev
= storage_init(c
->lxc_conf
);
4035 ERROR("Failed to find original backing store type");
4039 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4042 lxc_container_put(newc
);
4046 if (newc
&& lxcapi_is_defined(newc
))
4047 lxc_container_put(newc
);
4049 if (!container_destroy(c
, NULL
)) {
4050 ERROR("Could not destroy existing container %s", c
->name
);
4057 WRAP_API_1(bool, lxcapi_rename
, const char *)
4059 static int lxcapi_attach(struct lxc_container
*c
,
4060 lxc_attach_exec_t exec_function
, void *exec_payload
,
4061 lxc_attach_options_t
*options
, pid_t
*attached_process
)
4068 current_config
= c
->lxc_conf
;
4070 ret
= lxc_attach(c
, exec_function
, exec_payload
, options
,
4072 current_config
= NULL
;
4076 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
,
4077 lxc_attach_options_t
*options
,
4078 const char *program
,
4079 const char *const argv
[])
4081 lxc_attach_command_t command
;
4088 command
.program
= (char *)program
;
4089 command
.argv
= (char **)argv
;
4091 ret
= lxc_attach(c
, lxc_attach_run_command
, &command
, options
, &pid
);
4095 return lxc_wait_for_pid_status(pid
);
4098 static int lxcapi_attach_run_wait(struct lxc_container
*c
,
4099 lxc_attach_options_t
*options
,
4100 const char *program
, const char *const argv
[])
4104 current_config
= c
? c
->lxc_conf
: NULL
;
4105 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4106 current_config
= NULL
;
4111 static int get_next_index(const char *lxcpath
, char *cname
)
4113 __do_free
char *fname
= NULL
;
4117 fname
= must_realloc(NULL
, strlen(lxcpath
) + 20);
4120 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4122 ret
= stat(fname
, &sb
);
4130 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4135 * If the old style snapshot path exists, use it
4136 * /var/lib/lxc -> /var/lib/lxcsnaps
4138 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4139 if (ret
< 0 || ret
>= PATH_MAX
)
4142 if (dir_exists(snappath
)) {
4143 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4144 if (ret
< 0 || ret
>= PATH_MAX
)
4151 * Use the new style path
4152 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4154 ret
= snprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4155 if (ret
< 0 || ret
>= PATH_MAX
)
4161 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4163 __do_free
char *dfnam
= NULL
;
4167 struct lxc_container
*c2
;
4168 char snappath
[PATH_MAX
], newname
[20];
4172 if (!c
|| !lxcapi_is_defined(c
))
4175 if (!storage_can_backup(c
->lxc_conf
)) {
4176 ERROR("%s's backing store cannot be backed up", c
->name
);
4177 ERROR("Your container must use another backing store type");
4181 if (!get_snappath_dir(c
, snappath
))
4184 i
= get_next_index(snappath
, c
->name
);
4186 if (mkdir_p(snappath
, 0755) < 0) {
4187 ERROR("Failed to create snapshot directory %s", snappath
);
4191 ret
= snprintf(newname
, 20, "snap%d", i
);
4192 if (ret
< 0 || ret
>= 20)
4196 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4197 * created in the original container
4199 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4200 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4201 if (storage_is_dir(c
->lxc_conf
)) {
4202 ERROR("Snapshot of directory-backed container requested");
4203 ERROR("Making a copy-clone. If you do want snapshots, then");
4204 ERROR("please create overlay clone first, snapshot that");
4205 ERROR("and keep the original container pristine");
4206 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4209 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4211 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4215 lxc_container_put(c2
);
4217 /* Now write down the creation time. */
4220 if (!localtime_r(&timer
, &tm_info
)) {
4221 ERROR("Failed to get localtime");
4225 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4227 dfnam
= must_realloc(NULL
, strlen(snappath
) + strlen(newname
) + 5);
4228 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4229 f
= fopen(dfnam
, "w");
4231 ERROR("Failed to open %s", dfnam
);
4235 if (fprintf(f
, "%s", buffer
) < 0) {
4236 SYSERROR("Writing timestamp");
4243 SYSERROR("Writing timestamp");
4248 __do_free
char *path
= NULL
;
4249 /* $p / $name / comment \0 */
4250 int len
= strlen(snappath
) + strlen(newname
) + 10;
4252 path
= must_realloc(NULL
, len
);
4253 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4254 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4260 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4262 static void lxcsnap_free(struct lxc_snapshot
*s
)
4265 free(s
->comment_pathname
);
4270 static char *get_snapcomment_path(char* snappath
, char *name
)
4272 /* $snappath/$name/comment */
4273 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4274 char *s
= malloc(len
);
4277 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4278 if (ret
< 0 || ret
>= len
) {
4287 static char *get_timestamp(char* snappath
, char *name
)
4289 char path
[PATH_MAX
], *s
= NULL
;
4293 ret
= snprintf(path
, PATH_MAX
, "%s/%s/ts", snappath
, name
);
4294 if (ret
< 0 || ret
>= PATH_MAX
)
4297 fin
= fopen(path
, "r");
4301 (void) fseek(fin
, 0, SEEK_END
);
4303 (void) fseek(fin
, 0, SEEK_SET
);
4308 if (fread(s
, 1, len
, fin
) != len
) {
4309 SYSERROR("reading timestamp");
4320 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4322 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4324 struct dirent
*direntp
;
4325 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/config", snappath
, direntp
->d_name
);
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
);
4382 WARN("Failed to close directory");
4391 for (i
=0; i
<count
; i
++)
4392 lxcsnap_free(&snaps
[i
]);
4398 WARN("Failed to close directory");
4403 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4405 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4407 char clonelxcpath
[PATH_MAX
];
4409 struct lxc_container
*snap
, *rest
;
4410 struct lxc_storage
*bdev
;
4413 if (!c
|| !c
->name
|| !c
->config_path
)
4416 if (has_fs_snapshots(c
)) {
4417 ERROR("container rootfs has dependent snapshots");
4421 bdev
= storage_init(c
->lxc_conf
);
4423 ERROR("Failed to find original backing store type");
4427 /* For an overlay container the rootfs is considered immutable
4428 * and cannot be removed when restoring from a snapshot. We pass this
4429 * internal flag along to communicate this to various parts of the
4432 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4433 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4438 if (!get_snappath_dir(c
, clonelxcpath
)) {
4442 /* how should we lock this? */
4444 snap
= lxc_container_new(snapname
, clonelxcpath
);
4445 if (!snap
|| !lxcapi_is_defined(snap
)) {
4446 ERROR("Could not open snapshot %s", snapname
);
4449 lxc_container_put(snap
);
4455 if (!strcmp(c
->name
, newname
)) {
4456 if (!container_destroy(c
, bdev
)) {
4457 ERROR("Could not destroy existing container %s", newname
);
4458 lxc_container_put(snap
);
4464 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4465 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4467 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4468 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4470 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4473 if (rest
&& lxcapi_is_defined(rest
))
4477 lxc_container_put(rest
);
4479 lxc_container_put(snap
);
4483 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4485 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4487 struct lxc_container
*snap
= NULL
;
4490 snap
= lxc_container_new(snapname
, clonelxcpath
);
4492 ERROR("Could not find snapshot %s", snapname
);
4496 if (!do_lxcapi_destroy(snap
)) {
4497 ERROR("Could not destroy snapshot %s", snapname
);
4505 lxc_container_put(snap
);
4510 static bool remove_all_snapshots(const char *path
)
4513 struct dirent
*direntp
;
4516 dir
= opendir(path
);
4518 SYSERROR("opendir on snapshot path %s", path
);
4522 while ((direntp
= readdir(dir
))) {
4523 if (!strcmp(direntp
->d_name
, "."))
4526 if (!strcmp(direntp
->d_name
, ".."))
4529 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4538 SYSERROR("Error removing directory %s", path
);
4543 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4545 char clonelxcpath
[PATH_MAX
];
4547 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4550 if (!get_snappath_dir(c
, clonelxcpath
))
4553 return do_snapshot_destroy(snapname
, clonelxcpath
);
4556 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4558 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4560 char clonelxcpath
[PATH_MAX
];
4562 if (!c
|| !c
->name
|| !c
->config_path
)
4565 if (!get_snappath_dir(c
, clonelxcpath
))
4568 return remove_all_snapshots(clonelxcpath
);
4571 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4573 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4578 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4581 WRAP_API(bool, lxcapi_may_control
)
4583 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4589 char chrootpath
[PATH_MAX
];
4590 char *directory_path
= NULL
;
4594 SYSERROR("Failed to fork()");
4599 ret
= wait_for_pid(pid
);
4601 ERROR("Failed to create device node");
4608 /* prepare the path */
4609 ret
= snprintf(chrootpath
, PATH_MAX
, "/proc/%d/root", init_pid
);
4610 if (ret
< 0 || ret
>= PATH_MAX
)
4613 ret
= chroot(chrootpath
);
4615 _exit(EXIT_FAILURE
);
4619 _exit(EXIT_FAILURE
);
4621 /* remove path if it exists */
4622 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4626 SYSERROR("Failed to remove \"%s\"", path
);
4627 _exit(EXIT_FAILURE
);
4632 _exit(EXIT_SUCCESS
);
4634 /* create any missing directories */
4637 _exit(EXIT_FAILURE
);
4639 directory_path
= dirname(tmp
);
4640 ret
= mkdir_p(directory_path
, 0755);
4641 if (ret
< 0 && errno
!= EEXIST
) {
4642 SYSERROR("Failed to create path \"%s\"", directory_path
);
4644 _exit(EXIT_FAILURE
);
4647 /* create the device node */
4648 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4651 SYSERROR("Failed to create device node at \"%s\"", path
);
4652 _exit(EXIT_FAILURE
);
4655 _exit(EXIT_SUCCESS
);
4658 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4662 char value
[LXC_MAX_BUFFER
];
4666 /* make sure container is running */
4667 if (!do_lxcapi_is_running(c
)) {
4668 ERROR("container is not running");
4672 /* use src_path if dest_path is NULL otherwise use dest_path */
4673 p
= dest_path
? dest_path
: src_path
;
4675 /* make sure we can access p */
4676 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4679 /* continue if path is character device or block device */
4680 if (S_ISCHR(st
.st_mode
))
4681 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4682 else if (S_ISBLK(st
.st_mode
))
4683 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4687 /* check snprintf return code */
4688 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4691 init_pid
= do_lxcapi_init_pid(c
);
4693 ERROR("Failed to get init pid");
4697 if (!do_add_remove_node(init_pid
, p
, add
, &st
))
4700 /* add or remove device to/from cgroup access list */
4702 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4703 ERROR("set_cgroup_item failed while adding the device node");
4707 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4708 ERROR("set_cgroup_item failed while removing the device node");
4716 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4718 // cannot mknod if we're not privileged wrt init_user_ns
4719 if (am_host_unpriv()) {
4720 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4724 return add_remove_device_node(c
, src_path
, dest_path
, true);
4727 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4729 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4731 if (am_guest_unpriv()) {
4732 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4736 return add_remove_device_node(c
, src_path
, dest_path
, false);
4739 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4741 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4743 const char *dst_ifname
)
4748 if (am_guest_unpriv()) {
4749 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4754 ERROR("No source interface name given");
4758 ret
= lxc_netdev_isup(ifname
);
4760 /* netdev of ifname is up. */
4761 ret
= lxc_netdev_down(ifname
);
4766 init_pid
= do_lxcapi_init_pid(c
);
4768 ERROR("Failed to get init pid");
4772 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4776 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4783 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4785 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4787 const char *dst_ifname
)
4790 pid_t pid
, pid_outside
;
4793 * TODO - if this is a physical device, then we need am_host_unpriv.
4794 * But for other types guest privilege suffices.
4796 if (am_guest_unpriv()) {
4797 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4802 ERROR("No source interface name given");
4806 pid_outside
= lxc_raw_getpid();
4809 ERROR("Failed to fork");
4813 if (pid
== 0) { /* child */
4816 init_pid
= do_lxcapi_init_pid(c
);
4818 ERROR("Failed to get init pid");
4819 _exit(EXIT_FAILURE
);
4821 if (!switch_to_ns(init_pid
, "net")) {
4822 ERROR("Failed to enter network namespace");
4823 _exit(EXIT_FAILURE
);
4826 ret
= lxc_netdev_isup(ifname
);
4828 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4829 _exit(EXIT_FAILURE
);
4832 /* netdev of ifname is up. */
4834 ret
= lxc_netdev_down(ifname
);
4836 ERROR("Failed to set network device \"%s\" down", ifname
);
4837 _exit(EXIT_FAILURE
);
4841 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4842 /* -EINVAL means there is no netdev named as ifname. */
4845 ERROR("Network device \"%s\" not found", ifname
);
4847 ERROR("Failed to remove network device \"%s\"", ifname
);
4849 _exit(EXIT_FAILURE
);
4852 _exit(EXIT_SUCCESS
);
4855 ret
= wait_for_pid(pid
);
4859 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4863 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4865 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4866 struct migrate_opts
*opts
, unsigned int size
)
4869 struct migrate_opts
*valid_opts
= opts
;
4870 uint64_t features_to_check
= 0;
4872 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4873 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4874 * to do anything special.
4876 if (size
> sizeof(*opts
)) {
4877 unsigned char *addr
;
4880 addr
= (void *)opts
+ sizeof(*opts
);
4881 end
= (void *)opts
+ size
;
4883 for (; addr
< end
; addr
++)
4888 /* If the caller has a smaller struct, let's zero out the end for them
4889 * so we don't accidentally use bits of it that they didn't know about
4892 if (size
< sizeof(*opts
)) {
4893 valid_opts
= malloc(sizeof(*opts
));
4897 memset(valid_opts
, 0, sizeof(*opts
));
4898 memcpy(valid_opts
, opts
, size
);
4902 case MIGRATE_PRE_DUMP
:
4903 if (!do_lxcapi_is_running(c
)) {
4904 ERROR("container is not running");
4908 ret
= !__criu_pre_dump(c
, valid_opts
);
4911 if (!do_lxcapi_is_running(c
)) {
4912 ERROR("container is not running");
4916 ret
= !__criu_dump(c
, valid_opts
);
4918 case MIGRATE_RESTORE
:
4919 if (do_lxcapi_is_running(c
)) {
4920 ERROR("container is already running");
4924 ret
= !__criu_restore(c
, valid_opts
);
4926 case MIGRATE_FEATURE_CHECK
:
4927 features_to_check
= valid_opts
->features_to_check
;
4928 ret
= !__criu_check_feature(&features_to_check
);
4930 /* Something went wrong. Let's let the caller
4931 * know which feature checks failed. */
4932 valid_opts
->features_to_check
= features_to_check
;
4936 ERROR("invalid migrate command %u", cmd
);
4941 if (size
< sizeof(*opts
))
4947 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4949 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4951 struct migrate_opts opts
;
4953 memset(&opts
, 0, sizeof(opts
));
4955 opts
.directory
= directory
;
4957 opts
.verbose
= verbose
;
4959 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4962 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4964 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4966 struct migrate_opts opts
;
4968 memset(&opts
, 0, sizeof(opts
));
4970 opts
.directory
= directory
;
4971 opts
.verbose
= verbose
;
4973 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4976 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4978 /* @st_mode is the st_mode field of the stat(source) return struct */
4979 static int create_mount_target(const char *dest
, mode_t st_mode
)
4981 char *dirdup
, *destdirname
;
4984 dirdup
= strdup(dest
);
4986 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4989 destdirname
= dirname(dirdup
);
4991 ret
= mkdir_p(destdirname
, 0755);
4993 SYSERROR("Failed to create \"%s\"", destdirname
);
5001 if (S_ISDIR(st_mode
))
5002 ret
= mkdir(dest
, 0000);
5004 ret
= mknod(dest
, S_IFREG
| 0000, 0);
5007 TRACE("Created mount target \"%s\"", dest
);
5008 else if (ret
< 0 && errno
!= EEXIST
) {
5009 SYSERROR("Failed to create mount target \"%s\"", dest
);
5016 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
5017 const char *target
, const char *filesystemtype
,
5018 unsigned long mountflags
, const void *data
,
5019 struct lxc_mount
*mnt
)
5022 char template[PATH_MAX
], path
[PATH_MAX
];
5023 pid_t pid
, init_pid
;
5026 int ret
= -1, fd
= -EBADF
;
5028 if (!c
|| !c
->lxc_conf
) {
5029 ERROR("Container or configuration is NULL");
5033 if (!c
->lxc_conf
->shmount
.path_host
) {
5034 ERROR("Host path to shared mountpoint must be specified in the config\n");
5038 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5039 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
5040 SYSERROR("Error writing shmounts tempdir name");
5044 /* Create a temporary file / dir under the shared mountpoint */
5045 if (!source
|| strcmp(source
, "") == 0) {
5046 /* If source is not specified, maybe we want to mount a filesystem? */
5047 sb
.st_mode
= S_IFDIR
;
5049 ret
= stat(source
, &sb
);
5051 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5056 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5058 sret
= mkdtemp(template);
5060 SYSERROR("Could not create shmounts temporary dir");
5064 fd
= lxc_make_tmpfile(template, false);
5066 SYSERROR("Could not create shmounts temporary file");
5074 SYSERROR("Could not fork");
5080 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5082 SYSERROR("Failed to mount onto \"%s\"", template);
5083 _exit(EXIT_FAILURE
);
5085 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5087 init_pid
= do_lxcapi_init_pid(c
);
5089 ERROR("Failed to obtain container's init pid");
5090 _exit(EXIT_FAILURE
);
5093 /* Enter the container namespaces */
5094 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5095 if (!switch_to_ns(init_pid
, "user")) {
5096 ERROR("Failed to enter user namespace");
5097 _exit(EXIT_FAILURE
);
5100 if (!lxc_switch_uid_gid(0, 0))
5101 _exit(EXIT_FAILURE
);
5104 if (!switch_to_ns(init_pid
, "mnt")) {
5105 ERROR("Failed to enter mount namespace");
5106 _exit(EXIT_FAILURE
);
5109 ret
= create_mount_target(target
, sb
.st_mode
);
5111 _exit(EXIT_FAILURE
);
5113 suff
= strrchr(template, '/');
5115 _exit(EXIT_FAILURE
);
5117 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5118 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5119 SYSERROR("Error writing container mountpoint name");
5120 _exit(EXIT_FAILURE
);
5123 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5125 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5126 _exit(EXIT_FAILURE
);
5128 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5130 _exit(EXIT_SUCCESS
);
5133 ret
= wait_for_pid(pid
);
5135 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5141 (void)umount2(template, MNT_DETACH
);
5143 (void)rmdir(template);
5145 (void)unlink(template);
5154 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5155 unsigned long, const void *, struct lxc_mount
*)
5157 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5158 unsigned long flags
, struct lxc_mount
*mnt
)
5160 pid_t pid
, init_pid
;
5163 if (!c
|| !c
->lxc_conf
) {
5164 ERROR("Container or configuration is NULL");
5171 SYSERROR("Could not fork");
5176 init_pid
= do_lxcapi_init_pid(c
);
5178 ERROR("Failed to obtain container's init pid");
5179 _exit(EXIT_FAILURE
);
5182 /* Enter the container namespaces */
5183 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5184 if (!switch_to_ns(init_pid
, "user")) {
5185 ERROR("Failed to enter user namespace");
5186 _exit(EXIT_FAILURE
);
5190 if (!switch_to_ns(init_pid
, "mnt")) {
5191 ERROR("Failed to enter mount namespace");
5192 _exit(EXIT_FAILURE
);
5195 /* Do the unmount */
5196 ret
= umount2(target
, flags
);
5198 SYSERROR("Failed to umount \"%s\"", target
);
5199 _exit(EXIT_FAILURE
);
5202 _exit(EXIT_SUCCESS
);
5205 ret
= wait_for_pid(pid
);
5207 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5214 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5216 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5225 current_config
= c
->lxc_conf
;
5228 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5232 ERROR("Memory allocation error.");
5238 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5242 current_config
= NULL
;
5246 static int do_lxcapi_seccomp_notify(struct lxc_container
*c
, unsigned int cmd
, int fd
)
5248 if (!c
|| !c
->lxc_conf
)
5249 return minus_one_set_errno(-EINVAL
);
5252 case LXC_SECCOMP_NOTIFY_GET_FD
:
5254 return minus_one_set_errno(EINVAL
);
5256 return lxc_seccomp_get_notify_fd(&c
->lxc_conf
->seccomp
);
5259 return minus_one_set_errno(EINVAL
);
5262 WRAP_API_2(int, lxcapi_seccomp_notify
, unsigned int, int)
5264 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5266 struct lxc_container
*c
;
5273 c
= malloc(sizeof(*c
));
5275 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5278 memset(c
, 0, sizeof(*c
));
5281 c
->config_path
= strdup(configpath
);
5283 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5284 if (!c
->config_path
) {
5285 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5289 remove_trailing_slashes(c
->config_path
);
5292 c
->name
= malloc(len
+ 1);
5294 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5297 (void)strlcpy(c
->name
, name
, len
+ 1);
5300 c
->slock
= lxc_newlock(c
->config_path
, name
);
5302 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5306 c
->privlock
= lxc_newlock(NULL
, NULL
);
5308 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5312 if (!set_config_filename(c
)) {
5313 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5317 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5318 fprintf(stderr
, "Failed to load config for %s\n", name
);
5322 rc
= ongoing_create(c
);
5324 case LXC_CREATE_INCOMPLETE
:
5325 SYSERROR("Failed to complete container creation for %s", c
->name
);
5326 container_destroy(c
, NULL
);
5327 lxcapi_clear_config(c
);
5329 case LXC_CREATE_ONGOING
:
5330 /* container creation going on */
5332 case LXC_CREATE_FAILED
:
5333 /* container creation failed */
5334 if (errno
!= EACCES
&& errno
!= EPERM
) {
5335 /* insufficient privileges */
5336 SYSERROR("Failed checking for incomplete container %s creation", c
->name
);
5342 c
->daemonize
= true;
5345 /* Assign the member functions. */
5346 c
->is_defined
= lxcapi_is_defined
;
5347 c
->state
= lxcapi_state
;
5348 c
->is_running
= lxcapi_is_running
;
5349 c
->freeze
= lxcapi_freeze
;
5350 c
->unfreeze
= lxcapi_unfreeze
;
5351 c
->console
= lxcapi_console
;
5352 c
->console_getfd
= lxcapi_console_getfd
;
5353 c
->init_pid
= lxcapi_init_pid
;
5354 c
->load_config
= lxcapi_load_config
;
5355 c
->want_daemonize
= lxcapi_want_daemonize
;
5356 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5357 c
->start
= lxcapi_start
;
5358 c
->startl
= lxcapi_startl
;
5359 c
->stop
= lxcapi_stop
;
5360 c
->config_file_name
= lxcapi_config_file_name
;
5361 c
->wait
= lxcapi_wait
;
5362 c
->set_config_item
= lxcapi_set_config_item
;
5363 c
->destroy
= lxcapi_destroy
;
5364 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5365 c
->rename
= lxcapi_rename
;
5366 c
->save_config
= lxcapi_save_config
;
5367 c
->get_keys
= lxcapi_get_keys
;
5368 c
->create
= lxcapi_create
;
5369 c
->createl
= lxcapi_createl
;
5370 c
->shutdown
= lxcapi_shutdown
;
5371 c
->reboot
= lxcapi_reboot
;
5372 c
->reboot2
= lxcapi_reboot2
;
5373 c
->clear_config
= lxcapi_clear_config
;
5374 c
->clear_config_item
= lxcapi_clear_config_item
;
5375 c
->get_config_item
= lxcapi_get_config_item
;
5376 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5377 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5378 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5379 c
->get_config_path
= lxcapi_get_config_path
;
5380 c
->set_config_path
= lxcapi_set_config_path
;
5381 c
->clone
= lxcapi_clone
;
5382 c
->get_interfaces
= lxcapi_get_interfaces
;
5383 c
->get_ips
= lxcapi_get_ips
;
5384 c
->attach
= lxcapi_attach
;
5385 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5386 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5387 c
->snapshot
= lxcapi_snapshot
;
5388 c
->snapshot_list
= lxcapi_snapshot_list
;
5389 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5390 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5391 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5392 c
->may_control
= lxcapi_may_control
;
5393 c
->add_device_node
= lxcapi_add_device_node
;
5394 c
->remove_device_node
= lxcapi_remove_device_node
;
5395 c
->attach_interface
= lxcapi_attach_interface
;
5396 c
->detach_interface
= lxcapi_detach_interface
;
5397 c
->checkpoint
= lxcapi_checkpoint
;
5398 c
->restore
= lxcapi_restore
;
5399 c
->migrate
= lxcapi_migrate
;
5400 c
->console_log
= lxcapi_console_log
;
5401 c
->mount
= lxcapi_mount
;
5402 c
->umount
= lxcapi_umount
;
5403 c
->seccomp_notify
= lxcapi_seccomp_notify
;
5408 lxc_container_free(c
);
5412 int lxc_get_wait_states(const char **states
)
5417 for (i
=0; i
<MAX_STATE
; i
++)
5418 states
[i
] = lxc_state2str(i
);
5424 * These next two could probably be done smarter with reusing a common function
5425 * with different iterators and tests...
5427 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5430 int i
, cfound
= 0, nfound
= 0;
5431 struct dirent
*direntp
;
5432 struct lxc_container
*c
;
5435 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5437 dir
= opendir(lxcpath
);
5439 SYSERROR("opendir on lxcpath");
5449 while ((direntp
= readdir(dir
))) {
5450 /* Ignore '.', '..' and any hidden directory. */
5451 if (!strncmp(direntp
->d_name
, ".", 1))
5454 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5458 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5468 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5470 INFO("Container %s:%s has a config but could not be loaded",
5471 lxcpath
, direntp
->d_name
);
5474 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5480 if (!do_lxcapi_is_defined(c
)) {
5481 INFO("Container %s:%s has a config but is not defined",
5482 lxcpath
, direntp
->d_name
);
5485 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5488 lxc_container_put(c
);
5492 if (!add_to_clist(cret
, c
, nfound
, true)) {
5493 lxc_container_put(c
);
5504 if (names
&& *names
) {
5505 for (i
=0; i
<cfound
; i
++)
5510 if (cret
&& *cret
) {
5511 for (i
=0; i
<nfound
; i
++)
5512 lxc_container_put((*cret
)[i
]);
5520 int list_active_containers(const char *lxcpath
, char ***nret
,
5521 struct lxc_container
***cret
)
5523 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5526 char **ct_name
= NULL
;
5528 struct lxc_container
*c
= NULL
;
5532 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5533 lxcpath_len
= strlen(lxcpath
);
5541 FILE *f
= fopen("/proc/net/unix", "r");
5545 while (getline(&line
, &len
, f
) != -1) {
5546 char *p
= strrchr(line
, ' '), *p2
;
5557 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5559 } else if (strncmp(p
, "lxc/", 4) == 0) {
5569 /* Now p is the start of lxc_name. */
5570 p2
= strchr(p
, '/');
5571 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5576 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5580 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5586 p
= lxc_cmd_get_name(p
);
5591 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5597 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5600 goto free_cret_list
;
5611 c
= lxc_container_new(p
, lxcpath
);
5613 INFO("Container %s:%s is running but could not be loaded",
5616 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5627 * If this is an anonymous container, then is_defined *can*
5628 * return false. So we don't do that check. Count on the
5629 * fact that the command socket exists.
5632 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5633 lxc_container_put(c
);
5634 goto free_cret_list
;
5640 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5642 lxc_container_put(c
);
5643 goto free_cret_list
;
5655 if (cret
&& *cret
) {
5656 for (i
= 0; i
< cret_cnt
; i
++)
5657 lxc_container_put((*cret
)[i
]);
5663 for (i
= 0; i
< ct_name_cnt
; i
++)
5674 int list_all_containers(const char *lxcpath
, char ***nret
,
5675 struct lxc_container
***cret
)
5677 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5680 struct lxc_container
**ct_list
= NULL
;
5682 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5686 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5687 if (active_cnt
< 0) {
5692 for (i
= 0; i
< active_cnt
; i
++) {
5693 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5694 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5696 goto free_active_name
;
5702 free(active_name
[i
]);
5703 active_name
[i
] = NULL
;
5710 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5711 struct lxc_container
*c
;
5713 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5715 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5716 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5720 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5721 lxc_container_put(c
);
5742 for (i
= 0; i
< ct_list_cnt
; i
++) {
5743 lxc_container_put(ct_list
[i
]);
5748 for (i
= 0; i
< active_cnt
; i
++) {
5749 free(active_name
[i
]);
5754 for (i
= 0; i
< ct_cnt
; i
++) {
5761 bool lxc_config_item_is_supported(const char *key
)
5763 return !!lxc_get_config(key
);
5766 bool lxc_has_api_extension(const char *extension
)
5768 /* The NULL API extension is always present. :) */
5772 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5773 if (strcmp(api_extensions
[i
], extension
) == 0)