3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <arpa/inet.h>
38 #include <sys/mount.h>
40 #include <sys/syscall.h>
41 #include <sys/sysmacros.h>
42 #include <sys/types.h>
46 #include "../include/netns_ifaddrs.h"
48 #include "api_extensions.h"
52 #include "commands_utils.h"
56 #include "confile_utils.h"
59 #include "initutils.h"
62 #include "lxccontainer.h"
65 #include "namespace.h"
68 #include "raw_syscalls.h"
72 #include "storage/btrfs.h"
73 #include "storage/overlay.h"
74 #include "storage_utils.h"
76 #include "syscall_wrappers.h"
83 #include <sys/mkdev.h>
87 #include <../include/lxcmntent.h>
93 #include "include/strlcpy.h"
96 /* Define faccessat() if missing from the C library */
97 #ifndef HAVE_FACCESSAT
98 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
100 #ifdef __NR_faccessat
101 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
109 lxc_log_define(lxccontainer
, lxc
);
111 static bool do_lxcapi_destroy(struct lxc_container
*c
);
112 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
113 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
114 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
115 static bool container_destroy(struct lxc_container
*c
,
116 struct lxc_storage
*storage
);
117 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
118 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
119 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
121 static bool config_file_exists(const char *lxcpath
, const char *cname
)
127 /* $lxcpath + '/' + $cname + '/config' + \0 */
128 len
= strlen(lxcpath
) + strlen(cname
) + 9;
130 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
131 if (ret
< 0 || (size_t)ret
>= len
)
134 return file_exists(fname
);
137 /* A few functions to help detect when a container creation failed. If a
138 * container creation was killed partway through, then trying to actually start
139 * that container could harm the host. We detect this by creating a 'partial'
140 * file under the container directory, and keeping an advisory lock. When
141 * container creation completes, we remove that file. When we load or try to
142 * start a container, if we find that file, without a flock, we remove the
145 static int ongoing_create(struct lxc_container
*c
)
150 struct flock lk
= {0};
152 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
154 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
155 if (ret
< 0 || (size_t)ret
>= len
)
158 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
167 lk
.l_whence
= SEEK_SET
;
168 /* F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
173 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
174 if (ret
< 0 && errno
== EINVAL
) {
175 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
176 if (ret
< 0 && errno
== EWOULDBLOCK
)
182 /* F_OFD_GETLK will not send us back a pid so don't check it. */
184 /* Create is still ongoing. */
187 /* Create completed but partial is still there. */
191 static int create_partial(struct lxc_container
*c
)
196 struct flock lk
= {0};
198 /* $lxcpath + '/' + $name + '/partial' + \0 */
199 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
201 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
202 if (ret
< 0 || (size_t)ret
>= len
)
205 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
210 lk
.l_whence
= SEEK_SET
;
212 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
214 if (errno
== EINVAL
) {
215 ret
= flock(fd
, LOCK_EX
);
220 SYSERROR("Failed to lock partial file %s", path
);
228 static void remove_partial(struct lxc_container
*c
, int fd
)
236 /* $lxcpath + '/' + $name + '/partial' + \0 */
237 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
239 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
240 if (ret
< 0 || (size_t)ret
>= len
)
245 SYSERROR("Failed to remove partial file %s", path
);
249 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
250 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
251 * container configuration file.
252 * The container_disk_lock also takes the container_mem_lock.
253 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
254 * NOTHING mutexes two independent programs with their own struct
255 * lxc_container for the same c->name, between API calls. For instance,
256 * c->config_read(); c->start(); Between those calls, data on disk
257 * could change (which shouldn't bother the caller unless for instance
258 * the rootfs get moved). c->config_read(); update; c->config_write();
259 * Two such updaters could race. The callers should therefore check their
260 * results. Trying to prevent that would necessarily expose us to deadlocks
261 * due to hung callers. So I prefer to keep the locks only within our own
262 * functions, not across functions.
264 * If you're going to clone while holding a lxccontainer, increment
265 * c->numthreads (under privlock) before forking. When deleting,
266 * decrement numthreads under privlock, then if it hits 0 you can delete.
267 * Do not ever use a lxccontainer whose numthreads you did not bump.
269 static void lxc_container_free(struct lxc_container
*c
)
275 c
->configfile
= NULL
;
277 free(c
->error_string
);
278 c
->error_string
= NULL
;
281 lxc_putlock(c
->slock
);
286 lxc_putlock(c
->privlock
);
294 lxc_conf_free(c
->lxc_conf
);
298 free(c
->config_path
);
299 c
->config_path
= NULL
;
304 /* Consider the following case:
306 * |====================================================================|
307 * | freer | racing get()er |
308 * |====================================================================|
309 * | lxc_container_put() | lxc_container_get() |
310 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
311 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
312 * | \ lxcunlock() | \ |
313 * | \ lxc_container_free() | \ lxclock() returns |
314 * | | \ c->numthreads < 1 -> return 0 |
315 * | \ \ (free stuff) | |
316 * | \ \ sem_destroy(privlock) | |
317 * |_______________________________|____________________________________|
319 * When the get()er checks numthreads the first time, one of the following
321 * 1. freer has set numthreads = 0. get() returns 0
322 * 2. freer is between lxclock and setting numthreads to 0. get()er will
323 * sem_wait on privlock, get lxclock after freer() drops it, then see
324 * numthreads is 0 and exit without touching lxclock again..
325 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
326 * will see --numthreads = 1 and not call lxc_container_free().
329 int lxc_container_get(struct lxc_container
*c
)
334 /* If someone else has already started freeing the container, don't try
335 * to take the lock, which may be invalid.
337 if (c
->numthreads
< 1)
340 if (container_mem_lock(c
))
343 /* Bail without trying to unlock, bc the privlock is now probably in
346 if (c
->numthreads
< 1)
350 container_mem_unlock(c
);
355 int lxc_container_put(struct lxc_container
*c
)
360 if (container_mem_lock(c
))
365 if (c
->numthreads
< 1) {
366 container_mem_unlock(c
);
367 lxc_container_free(c
);
371 container_mem_unlock(c
);
375 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
384 if (container_mem_lock(c
))
390 statret
= stat(c
->configfile
, &statbuf
);
397 container_mem_unlock(c
);
401 #define WRAP_API(rettype, fnname) \
402 static rettype fnname(struct lxc_container *c) \
405 bool reset_config = false; \
407 if (!current_config && c && c->lxc_conf) { \
408 current_config = c->lxc_conf; \
409 reset_config = true; \
412 ret = do_##fnname(c); \
414 current_config = NULL; \
419 #define WRAP_API_1(rettype, fnname, t1) \
420 static rettype fnname(struct lxc_container *c, t1 a1) \
423 bool reset_config = false; \
425 if (!current_config && c && c->lxc_conf) { \
426 current_config = c->lxc_conf; \
427 reset_config = true; \
430 ret = do_##fnname(c, a1); \
432 current_config = NULL; \
437 #define WRAP_API_2(rettype, fnname, t1, t2) \
438 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
441 bool reset_config = false; \
443 if (!current_config && c && c->lxc_conf) { \
444 current_config = c->lxc_conf; \
445 reset_config = true; \
448 ret = do_##fnname(c, a1, a2); \
450 current_config = NULL; \
455 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
456 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
459 bool reset_config = false; \
461 if (!current_config && c && c->lxc_conf) { \
462 current_config = c->lxc_conf; \
463 reset_config = true; \
466 ret = do_##fnname(c, a1, a2, a3); \
468 current_config = NULL; \
473 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
474 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
475 t4 a4, t5 a5, t6 a6) \
478 bool reset_config = false; \
480 if (!current_config && c && c->lxc_conf) { \
481 current_config = c->lxc_conf; \
482 reset_config = true; \
485 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
487 current_config = NULL; \
492 WRAP_API(bool, lxcapi_is_defined
)
494 static const char *do_lxcapi_state(struct lxc_container
*c
)
501 s
= lxc_getstate(c
->name
, c
->config_path
);
502 return lxc_state2str(s
);
505 WRAP_API(const char *, lxcapi_state
)
507 static bool is_stopped(struct lxc_container
*c
)
511 s
= lxc_getstate(c
->name
, c
->config_path
);
512 return (s
== STOPPED
);
515 static bool do_lxcapi_is_running(struct lxc_container
*c
)
520 return !is_stopped(c
);
523 WRAP_API(bool, lxcapi_is_running
)
525 static bool do_lxcapi_freeze(struct lxc_container
*c
)
530 if (!c
|| !c
->lxc_conf
)
533 s
= lxc_getstate(c
->name
, c
->config_path
);
535 return lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
540 WRAP_API(bool, lxcapi_freeze
)
542 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
547 if (!c
|| !c
->lxc_conf
)
550 s
= lxc_getstate(c
->name
, c
->config_path
);
552 return lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
557 WRAP_API(bool, lxcapi_unfreeze
)
559 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
564 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
567 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
569 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
570 int stdoutfd
, int stderrfd
, int escape
)
577 current_config
= c
->lxc_conf
;
578 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
579 current_config
= NULL
;
584 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
591 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
594 NOTICE("The console log is empty");
595 else if (ret
== -EFAULT
)
596 NOTICE("The container does not keep a console log");
597 else if (ret
== -ENOENT
)
598 NOTICE("The container does not keep a console log file");
599 else if (ret
== -EIO
)
600 NOTICE("Failed to write console log to log file");
602 ERROR("Failed to retrieve console log");
608 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
610 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
615 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
618 WRAP_API(pid_t
, lxcapi_init_pid
)
620 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
623 c
->lxc_conf
= lxc_conf_init();
628 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
631 c
->lxc_conf
->name
= c
->name
;
635 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
639 bool need_disklock
= false, ret
= false;
644 fname
= c
->configfile
;
652 /* If we're reading something other than the container's config, we only
653 * need to lock the in-memory container. If loading the container's
654 * config file, take the disk lock.
656 if (strcmp(fname
, c
->configfile
) == 0)
657 need_disklock
= true;
660 lret
= container_disk_lock(c
);
662 lret
= container_mem_lock(c
);
666 ret
= load_config_locked(c
, fname
);
669 container_disk_unlock(c
);
671 container_mem_unlock(c
);
676 WRAP_API_1(bool, lxcapi_load_config
, const char *)
678 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
680 if (!c
|| !c
->lxc_conf
)
683 if (container_mem_lock(c
))
686 c
->daemonize
= state
;
688 container_mem_unlock(c
);
693 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
695 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
697 if (!c
|| !c
->lxc_conf
)
700 if (container_mem_lock(c
))
703 c
->lxc_conf
->close_all_fds
= state
;
705 container_mem_unlock(c
);
710 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
712 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
720 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
724 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
726 static bool am_single_threaded(void)
729 struct dirent
*direntp
;
732 dir
= opendir("/proc/self/task");
736 while ((direntp
= readdir(dir
))) {
737 if (strcmp(direntp
->d_name
, ".") == 0)
740 if (strcmp(direntp
->d_name
, "..") == 0)
752 static void push_arg(char ***argp
, char *arg
, int *nargs
)
757 copy
= must_copy_string(arg
);
760 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
769 static char **split_init_cmd(const char *incmd
)
779 len
= strlen(incmd
) + 1;
781 retlen
= strlcpy(copy
, incmd
, len
);
786 argv
= malloc(sizeof(char *));
790 lxc_iterate_parts(p
, copy
, " ")
791 push_arg(&argv
, p
, &nargs
);
801 static void free_init_cmd(char **argv
)
814 static int lxc_rcv_status(int state_socket
)
820 /* Receive container state. */
821 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
826 TRACE("Caught EINTR; retrying");
833 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
837 /* Close write end of the socket pair. */
838 close(handler
->state_socket_pair
[1]);
839 handler
->state_socket_pair
[1] = -1;
841 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
843 /* Close read end of the socket pair. */
844 close(handler
->state_socket_pair
[0]);
845 handler
->state_socket_pair
[0] = -1;
847 /* The first child is going to fork() again and then exits. So we reap
848 * the first child here.
850 ret
= wait_for_pid(pid
);
852 DEBUG("Failed waiting on first child %d", pid
);
854 DEBUG("First child %d exited", pid
);
857 SYSERROR("Failed to receive the container state");
861 /* If we receive anything else then running we know that the container
864 if (state
!= RUNNING
) {
865 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
866 lxc_state2str(state
));
870 TRACE("Container is in \"RUNNING\" state");
874 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
877 struct lxc_handler
*handler
;
878 struct lxc_conf
*conf
;
879 char *default_args
[] = {
883 char **init_cmd
= NULL
;
884 int keepfds
[3] = {-1, -1, -1};
886 /* container does exist */
890 /* If anything fails before we set error_num, we want an error in there.
894 /* Container has not been setup. */
898 ret
= ongoing_create(c
);
900 ERROR("Failed checking for incomplete container creation");
902 } else if (ret
== 1) {
903 ERROR("Ongoing container creation detected");
905 } else if (ret
== 2) {
906 ERROR("Failed to create container");
907 do_lxcapi_destroy(c
);
911 if (container_mem_lock(c
))
916 /* initialize handler */
917 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
919 container_mem_unlock(c
);
924 if (useinit
&& conf
->execute_cmd
)
925 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
927 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
930 /* ... otherwise use default_args. */
933 ERROR("No valid init detected");
934 lxc_free_handler(handler
);
940 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
941 * here to protect the on disk container? We don't want to exclude
942 * things like lxc_info while the container is running.
951 free_init_cmd(init_cmd
);
952 lxc_free_handler(handler
);
958 /* Set to NULL because we don't want father unlink
959 * the PID file, child will do the free and unlink.
963 /* Wait for container to tell us whether it started
966 started
= wait_on_daemonized_start(handler
, pid
);
968 free_init_cmd(init_cmd
);
969 lxc_free_handler(handler
);
975 /* We don't really care if this doesn't print all the
976 * characters. All that it means is that the proctitle will be
977 * ugly. Similarly, we also don't care if setproctitle() fails.
979 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
981 ret
= setproctitle(title
);
983 INFO("Failed to set process title to %s", title
);
985 INFO("Set process title to %s", title
);
988 /* We fork() a second time to be reparented to init. Like
989 * POSIX's daemon() function we change to "/" and redirect
990 * std{in,out,err} to /dev/null.
994 SYSERROR("Failed to fork first child process");
1000 free_init_cmd(init_cmd
);
1001 lxc_free_handler(handler
);
1002 _exit(EXIT_SUCCESS
);
1007 /* change to / directory */
1010 SYSERROR("Failed to change to \"/\" directory");
1011 _exit(EXIT_FAILURE
);
1014 keepfds
[0] = handler
->conf
->maincmd_fd
;
1015 keepfds
[1] = handler
->state_socket_pair
[0];
1016 keepfds
[2] = handler
->state_socket_pair
[1];
1017 ret
= lxc_check_inherited(conf
, true, keepfds
,
1018 sizeof(keepfds
) / sizeof(keepfds
[0]));
1020 _exit(EXIT_FAILURE
);
1022 /* redirect std{in,out,err} to /dev/null */
1023 ret
= null_stdfds();
1025 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1026 _exit(EXIT_FAILURE
);
1029 /* become session leader */
1032 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1033 } else if (!am_single_threaded()) {
1034 ERROR("Cannot start non-daemonized container when threaded");
1035 free_init_cmd(init_cmd
);
1036 lxc_free_handler(handler
);
1040 /* We need to write PID file after daemonize, so we always write the
1045 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1047 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1048 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1049 free_init_cmd(init_cmd
);
1050 lxc_free_handler(handler
);
1052 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1055 _exit(EXIT_FAILURE
);
1060 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1062 free_init_cmd(init_cmd
);
1063 lxc_free_handler(handler
);
1065 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1068 _exit(EXIT_FAILURE
);
1074 conf
->reboot
= REBOOT_NONE
;
1076 /* Unshare the mount namespace if requested */
1077 if (conf
->monitor_unshare
) {
1078 ret
= unshare(CLONE_NEWNS
);
1080 SYSERROR("Failed to unshare mount namespace");
1081 lxc_free_handler(handler
);
1086 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1088 SYSERROR("Failed to make / rslave at startup");
1089 lxc_free_handler(handler
);
1096 if (conf
->reboot
== REBOOT_INIT
) {
1097 /* initialize handler */
1098 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1105 keepfds
[0] = handler
->conf
->maincmd_fd
;
1106 keepfds
[1] = handler
->state_socket_pair
[0];
1107 keepfds
[2] = handler
->state_socket_pair
[1];
1108 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1109 sizeof(keepfds
) / sizeof(keepfds
[0]));
1111 lxc_free_handler(handler
);
1117 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1118 c
->daemonize
, &c
->error_num
);
1120 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1121 c
->daemonize
, &c
->error_num
);
1123 if (conf
->reboot
== REBOOT_REQ
) {
1124 INFO("Container requested reboot");
1125 conf
->reboot
= REBOOT_INIT
;
1135 free_init_cmd(init_cmd
);
1137 if (c
->daemonize
&& ret
!= 0)
1138 _exit(EXIT_FAILURE
);
1139 else if (c
->daemonize
)
1140 _exit(EXIT_SUCCESS
);
1148 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1153 current_config
= c
? c
->lxc_conf
: NULL
;
1154 ret
= do_lxcapi_start(c
, useinit
, argv
);
1155 current_config
= NULL
;
1160 /* Note, there MUST be an ending NULL. */
1161 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1164 char **inargs
= NULL
;
1167 /* container exists */
1171 current_config
= c
->lxc_conf
;
1173 va_start(ap
, useinit
);
1174 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1179 /* pass NULL if no arguments were supplied */
1180 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1186 for (arg
= inargs
; *arg
; arg
++)
1191 current_config
= NULL
;
1196 static bool do_lxcapi_stop(struct lxc_container
*c
)
1203 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1208 WRAP_API(bool, lxcapi_stop
)
1210 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1217 mode_t mask
= umask(0002);
1218 ret
= mkdir(path
, 0770);
1223 if (errno
!= EEXIST
)
1230 p
= alloca(len
+ 1);
1231 (void)strlcpy(p
, path
, len
+ 1);
1233 if (!lxc_list_empty(&conf
->id_map
)) {
1234 ret
= chown_mapped_root(p
, conf
);
1242 /* Create the standard expected container dir. */
1243 static bool create_container_dir(struct lxc_container
*c
)
1249 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1254 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1255 if (ret
< 0 || (size_t)ret
>= len
) {
1260 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1266 /* do_storage_create: thin wrapper around storage_create(). Like
1267 * storage_create(), it returns a mounted bdev on success, NULL on error.
1269 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1271 struct bdev_specs
*specs
)
1276 struct lxc_storage
*bdev
;
1278 /* rootfs.path or lxcpath/lxcname/rootfs */
1279 if (c
->lxc_conf
->rootfs
.path
&&
1280 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1281 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1282 len
= strlen(rpath
) + 1;
1284 ret
= snprintf(dest
, len
, "%s", rpath
);
1286 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1287 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1289 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1291 if (ret
< 0 || (size_t)ret
>= len
)
1294 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1296 ERROR("Failed to create \"%s\" storage", type
);
1300 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1301 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1305 /* If we are not root, chown the rootfs dir to root in the target user
1309 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1310 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1312 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1313 suggest_default_idmap();
1322 static char *lxcbasename(char *path
)
1326 p
= path
+ strlen(path
) - 1;
1327 while (*p
!= '/' && p
> path
)
1333 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1334 bool need_null_stdfds
, char *const argv
[])
1344 SYSERROR("Failed to fork task for container creation template");
1348 if (pid
== 0) { /* child */
1350 char *namearg
, *patharg
, *rootfsarg
;
1353 struct lxc_storage
*bdev
= NULL
;
1354 struct lxc_conf
*conf
= c
->lxc_conf
;
1357 if (need_null_stdfds
) {
1358 ret
= null_stdfds();
1360 _exit(EXIT_FAILURE
);
1363 bdev
= storage_init(c
->lxc_conf
);
1365 ERROR("Failed to initialize storage");
1366 _exit(EXIT_FAILURE
);
1371 ret
= unshare(CLONE_NEWNS
);
1373 ERROR("Failed to unshare CLONE_NEWNS");
1374 _exit(EXIT_FAILURE
);
1377 ret
= detect_shared_rootfs();
1379 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1381 SYSERROR("Failed to make \"/\" rslave");
1382 ERROR("Continuing...");
1387 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1389 ERROR("Unprivileged users can only create "
1390 "btrfs and directory-backed containers");
1391 _exit(EXIT_FAILURE
);
1394 if (strcmp(bdev
->type
, "overlay") == 0 ||
1395 strcmp(bdev
->type
, "overlayfs") == 0) {
1396 /* If we create an overlay container we need to
1397 * rsync the contents into
1398 * <container-path>/<container-name>/rootfs.
1399 * However, the overlay mount function will
1401 * <container-path>/<container-name>/delta0
1403 * <container-path>/<container-name>/rootfs
1404 * which means we would rsync the rootfs into
1405 * the delta directory. That doesn't make sense
1406 * since the delta directory only exists to
1407 * record the differences to
1408 * <container-path>/<container-name>/rootfs. So
1409 * let's simply bind-mount here and then rsync
1411 * <container-path>/<container-name>/rootfs.
1415 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1417 ERROR("Failed to get rootfs");
1418 _exit(EXIT_FAILURE
);
1421 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1423 ERROR("Failed to mount rootfs");
1424 _exit(EXIT_FAILURE
);
1427 ret
= bdev
->ops
->mount(bdev
);
1429 ERROR("Failed to mount rootfs");
1430 _exit(EXIT_FAILURE
);
1433 } else { /* TODO come up with a better way here! */
1436 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1437 bdev
->dest
= strdup(src
);
1440 /* Create our new array, pre-pend the template name and base
1444 for (nargs
= 0; argv
[nargs
]; nargs
++)
1447 /* template, path, rootfs and name args */
1450 newargv
= malloc(nargs
* sizeof(*newargv
));
1452 _exit(EXIT_FAILURE
);
1453 newargv
[0] = lxcbasename(tpath
);
1456 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1457 patharg
= malloc(len
);
1459 _exit(EXIT_FAILURE
);
1461 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1462 if (ret
< 0 || ret
>= len
)
1463 _exit(EXIT_FAILURE
);
1464 newargv
[1] = patharg
;
1467 len
= strlen("--name=") + strlen(c
->name
) + 1;
1468 namearg
= malloc(len
);
1470 _exit(EXIT_FAILURE
);
1472 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1473 if (ret
< 0 || ret
>= len
)
1474 _exit(EXIT_FAILURE
);
1475 newargv
[2] = namearg
;
1478 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1479 rootfsarg
= malloc(len
);
1481 _exit(EXIT_FAILURE
);
1483 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1484 if (ret
< 0 || ret
>= len
)
1485 _exit(EXIT_FAILURE
);
1486 newargv
[3] = rootfsarg
;
1488 /* add passed-in args */
1490 for (i
= 4; i
< nargs
; i
++)
1491 newargv
[i
] = argv
[i
- 4];
1493 /* add trailing NULL */
1495 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1497 _exit(EXIT_FAILURE
);
1498 newargv
[nargs
- 1] = NULL
;
1500 /* If we're running the template in a mapped userns, then we
1501 * prepend the template command with: lxc-usernsexec <-m map1>
1502 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1503 * the mapped uid for our geteuid()
1505 if (!lxc_list_empty(&conf
->id_map
)) {
1506 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1508 char txtuid
[20], txtgid
[20];
1509 struct lxc_list
*it
;
1513 n2
= malloc(n2args
* sizeof(*n2
));
1515 _exit(EXIT_FAILURE
);
1518 tpath
= "lxc-usernsexec";
1519 n2
[0] = "lxc-usernsexec";
1521 lxc_list_for_each(it
, &conf
->id_map
) {
1524 n2
= realloc(n2
, n2args
* sizeof(char *));
1526 _exit(EXIT_FAILURE
);
1528 n2
[n2args
- 2] = "-m";
1529 n2
[n2args
- 1] = malloc(200);
1530 if (!n2
[n2args
- 1])
1531 _exit(EXIT_FAILURE
);
1533 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1534 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1535 map
->nsid
, map
->hostid
, map
->range
);
1536 if (ret
< 0 || ret
>= 200)
1537 _exit(EXIT_FAILURE
);
1540 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1541 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1543 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1545 _exit(EXIT_FAILURE
);
1547 if (hostuid_mapped
< 0) {
1548 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1549 n2
[n2args
++] = "-m";
1550 if (hostuid_mapped
< 0) {
1551 ERROR("Failed to find free uid to map");
1552 _exit(EXIT_FAILURE
);
1555 n2
[n2args
++] = malloc(200);
1556 if (!n2
[n2args
- 1]) {
1557 SYSERROR("out of memory");
1558 _exit(EXIT_FAILURE
);
1561 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1562 hostuid_mapped
, geteuid());
1563 if (ret
< 0 || ret
>= 200)
1564 _exit(EXIT_FAILURE
);
1567 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1568 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1570 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1572 _exit(EXIT_FAILURE
);
1574 if (hostgid_mapped
< 0) {
1575 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1576 n2
[n2args
++] = "-m";
1577 if (hostgid_mapped
< 0) {
1578 ERROR("Failed to find free gid to map");
1579 _exit(EXIT_FAILURE
);
1582 n2
[n2args
++] = malloc(200);
1583 if (!n2
[n2args
- 1]) {
1584 SYSERROR("out of memory");
1585 _exit(EXIT_FAILURE
);
1588 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1589 hostgid_mapped
, getegid());
1590 if (ret
< 0 || ret
>= 200)
1591 _exit(EXIT_FAILURE
);
1594 n2
[n2args
++] = "--";
1596 for (i
= 0; i
< nargs
; i
++)
1597 n2
[i
+ n2args
] = newargv
[i
];
1600 /* Finally add "--mapped-uid $uid" to tell template what
1601 * to chown cached images to.
1604 n2
= realloc(n2
, n2args
* sizeof(char *));
1606 _exit(EXIT_FAILURE
);
1608 /* note n2[n2args-1] is NULL */
1609 n2
[n2args
- 5] = "--mapped-uid";
1611 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1612 if (ret
< 0 || ret
>= 20) {
1615 _exit(EXIT_FAILURE
);
1618 n2
[n2args
- 4] = txtuid
;
1619 n2
[n2args
- 3] = "--mapped-gid";
1621 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1622 if (ret
< 0 || ret
>= 20) {
1625 _exit(EXIT_FAILURE
);
1628 n2
[n2args
- 2] = txtgid
;
1629 n2
[n2args
- 1] = NULL
;
1634 execvp(tpath
, newargv
);
1635 SYSERROR("Failed to execute template %s", tpath
);
1636 _exit(EXIT_FAILURE
);
1639 ret
= wait_for_pid(pid
);
1641 ERROR("Failed to create container from template");
1648 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1657 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1661 f
= fopen(path
, "r");
1665 ret
= fseek(f
, 0, SEEK_END
);
1674 ret
= fseek(f
, 0, SEEK_SET
);
1678 ret
= fseek(f
, 0, SEEK_SET
);
1683 contents
= malloc(flen
+ 1);
1687 len
= fread(contents
, 1, flen
, f
);
1689 goto out_free_contents
;
1691 contents
[flen
] = '\0';
1696 goto out_free_contents
;
1699 tpath
= get_template_path(t
);
1701 ERROR("Invalid template \"%s\" specified", t
);
1702 goto out_free_contents
;
1705 ret
= sha1sum_file(tpath
, md_value
);
1707 ERROR("Failed to get sha1sum of %s", tpath
);
1709 goto out_free_contents
;
1714 f
= fopen(path
, "w");
1716 SYSERROR("Reopening config for writing");
1721 fprintf(f
, "# Template used to create this container: %s\n", t
);
1723 fprintf(f
, "# Parameters passed to the template:");
1725 fprintf(f
, " %s", *argv
);
1732 fprintf(f
, "# Template script checksum (SHA-1): ");
1733 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1734 fprintf(f
, "%02x", md_value
[i
]);
1737 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1738 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1739 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1740 fprintf(f
, "# (Be aware this has security implications)\n\n");
1741 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1742 SYSERROR("Writing original contents");
1762 SYSERROR("Error prepending header");
1769 static void lxcapi_clear_config(struct lxc_container
*c
)
1771 if (!c
|| !c
->lxc_conf
)
1774 lxc_conf_free(c
->lxc_conf
);
1778 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1782 * create a container with the given parameters.
1783 * @c: container to be created. It has the lxcpath, name, and a starting
1784 * configuration already set
1785 * @t: the template to execute to instantiate the root filesystem and
1786 * adjust the configuration.
1787 * @bdevtype: backing store type to use. If NULL, dir will be used.
1788 * @specs: additional parameters for the backing store, i.e. LVM vg to
1791 * @argv: the arguments to pass to the template, terminated by NULL. If no
1792 * arguments, you can just pass NULL.
1794 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1795 const char *bdevtype
, struct bdev_specs
*specs
,
1796 int flags
, char *const argv
[])
1801 bool ret
= false, rootfs_managed
= true;
1808 tpath
= get_template_path(t
);
1810 ERROR("Unknown template \"%s\"", t
);
1815 /* If a template is passed in, and the rootfs already is defined in the
1816 * container config and exists, then the caller is trying to create an
1817 * existing container. Return an error, but do NOT delete the container.
1819 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1820 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1821 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1827 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1828 ERROR("Error loading default configuration file %s",
1829 lxc_global_config_value("lxc.default_config"));
1834 if (!create_container_dir(c
))
1837 if (c
->lxc_conf
->rootfs
.path
)
1838 rootfs_managed
= false;
1840 /* If both template and rootfs.path are set, template is setup as
1841 * rootfs.path. The container is already created if we have a config and
1842 * rootfs.path is accessible
1844 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1845 /* No template passed in and rootfs does not exist. */
1846 if (!c
->save_config(c
, NULL
)) {
1847 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1854 /* Rootfs passed into configuration, but does not exist. */
1855 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1858 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1859 /* Rootfs already existed, user just wanted to save the loaded
1862 if (!c
->save_config(c
, NULL
))
1863 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1869 /* Mark that this container is being created */
1870 partial_fd
= create_partial(c
);
1874 /* No need to get disk lock bc we have the partial lock. */
1878 /* Create the storage.
1879 * Note we can't do this in the same task as we use to execute the
1880 * template because of the way zfs works.
1881 * After you 'zfs create', zfs mounts the fs only in the initial
1886 SYSERROR("Failed to fork task for container creation template");
1890 if (pid
== 0) { /* child */
1891 struct lxc_storage
*bdev
= NULL
;
1893 bdev
= do_storage_create(c
, bdevtype
, specs
);
1895 ERROR("Failed to create %s storage for %s",
1896 bdevtype
? bdevtype
: "(none)", c
->name
);
1897 _exit(EXIT_FAILURE
);
1900 /* Save config file again to store the new rootfs location. */
1901 if (!do_lxcapi_save_config(c
, NULL
)) {
1902 ERROR("Failed to save initial config for %s", c
->name
);
1903 /* Parent task won't see the storage driver in the
1904 * config so we delete it.
1906 bdev
->ops
->umount(bdev
);
1907 bdev
->ops
->destroy(bdev
);
1908 _exit(EXIT_FAILURE
);
1911 _exit(EXIT_SUCCESS
);
1914 if (wait_for_pid(pid
) != 0)
1917 /* Reload config to get the rootfs. */
1918 lxc_conf_free(c
->lxc_conf
);
1921 if (!load_config_locked(c
, c
->configfile
))
1924 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1927 /* Now clear out the lxc_conf we have, reload from the created
1930 do_lxcapi_clear_config(c
);
1933 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1934 ERROR("Failed to prepend header to config file");
1939 ret
= load_config_locked(c
, c
->configfile
);
1943 remove_partial(c
, partial_fd
);
1947 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1950 * Ensure that we don't destroy storage we didn't create
1953 if (!rootfs_managed
)
1954 c
->lxc_conf
->rootfs
.managed
= false;
1955 container_destroy(c
, NULL
);
1956 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1964 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1965 const char *bdevtype
, struct bdev_specs
*specs
,
1966 int flags
, char *const argv
[])
1970 current_config
= c
? c
->lxc_conf
: NULL
;
1972 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1973 current_config
= NULL
;
1977 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1981 int rebootsignal
= SIGINT
;
1986 if (!do_lxcapi_is_running(c
))
1989 pid
= do_lxcapi_init_pid(c
);
1993 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1994 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1996 ret
= kill(pid
, rebootsignal
);
1998 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2005 WRAP_API(bool, lxcapi_reboot
)
2007 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
2011 int rebootsignal
= SIGINT
, state_client_fd
= -1;
2012 lxc_state_t states
[MAX_STATE
] = {0};
2017 if (!do_lxcapi_is_running(c
))
2020 pid
= do_lxcapi_init_pid(c
);
2024 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2025 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2027 /* Add a new state client before sending the shutdown signal so that we
2028 * don't miss a state.
2031 states
[RUNNING
] = 2;
2032 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2037 if (state_client_fd
< 0)
2043 if (ret
< MAX_STATE
)
2047 /* Send reboot signal to container. */
2048 killret
= kill(pid
, rebootsignal
);
2050 if (state_client_fd
>= 0)
2051 close(state_client_fd
);
2053 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2056 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2061 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2062 close(state_client_fd
);
2066 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2073 WRAP_API_1(bool, lxcapi_reboot2
, int)
2075 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2079 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2080 lxc_state_t states
[MAX_STATE
] = {0};
2085 if (!do_lxcapi_is_running(c
))
2088 pid
= do_lxcapi_init_pid(c
);
2092 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2093 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2094 haltsignal
= c
->lxc_conf
->haltsignal
;
2095 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2096 haltsignal
= (SIGRTMIN
+ 3);
2098 /* Add a new state client before sending the shutdown signal so that we
2099 * don't miss a state.
2102 states
[STOPPED
] = 1;
2103 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2108 if (state_client_fd
< 0)
2114 if (ret
< MAX_STATE
)
2118 /* Send shutdown signal to container. */
2119 killret
= kill(pid
, haltsignal
);
2121 if (state_client_fd
>= 0)
2122 close(state_client_fd
);
2124 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2127 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2132 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2133 close(state_client_fd
);
2137 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2144 WRAP_API_1(bool, lxcapi_shutdown
, int)
2146 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2147 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2156 current_config
= c
->lxc_conf
;
2159 * since we're going to wait for create to finish, I don't think we
2160 * need to get a copy of the arguments.
2162 va_start(ap
, flags
);
2163 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2166 ERROR("Failed to allocate memory");
2170 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2174 current_config
= NULL
;
2178 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2180 if (!strcmp(key
, "lxc.cgroup"))
2181 return clear_unexp_config_line(conf
, key
, true);
2183 if (!strcmp(key
, "lxc.network"))
2184 return clear_unexp_config_line(conf
, key
, true);
2186 if (!strcmp(key
, "lxc.net"))
2187 return clear_unexp_config_line(conf
, key
, true);
2189 /* Clear a network with a specific index. */
2190 if (!strncmp(key
, "lxc.net.", 8)) {
2195 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2197 return clear_unexp_config_line(conf
, key
, true);
2200 if (!strcmp(key
, "lxc.hook"))
2201 return clear_unexp_config_line(conf
, key
, true);
2203 return clear_unexp_config_line(conf
, key
, false);
2206 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2210 struct lxc_config_t
*config
;
2212 if (!c
|| !c
->lxc_conf
)
2215 if (container_mem_lock(c
))
2218 config
= lxc_get_config(key
);
2219 /* Verify that the config key exists and that it has a callback
2222 if (config
&& config
->clr
)
2223 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2226 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2228 container_mem_unlock(c
);
2232 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2234 static inline bool enter_net_ns(struct lxc_container
*c
)
2236 pid_t pid
= do_lxcapi_init_pid(c
);
2238 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2239 (access("/proc/self/ns/user", F_OK
) == 0))
2240 if (!switch_to_ns(pid
, "user"))
2243 return switch_to_ns(pid
, "net");
2246 /* Used by qsort and bsearch functions for comparing names. */
2247 static inline int string_cmp(char **first
, char **second
)
2249 return strcmp(*first
, *second
);
2252 /* Used by qsort and bsearch functions for comparing container names. */
2253 static inline int container_cmp(struct lxc_container
**first
,
2254 struct lxc_container
**second
)
2256 return strcmp((*first
)->name
, (*second
)->name
);
2259 static bool add_to_array(char ***names
, char *cname
, int pos
)
2261 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2263 ERROR("Out of memory");
2268 newnames
[pos
] = strdup(cname
);
2272 /* Sort the array as we will use binary search on it. */
2273 qsort(newnames
, pos
+ 1, sizeof(char *),
2274 (int (*)(const void *, const void *))string_cmp
);
2279 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2282 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2284 ERROR("Out of memory");
2291 /* Sort the array as we will use binary search on it. */
2293 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2294 (int (*)(const void *, const void *))container_cmp
);
2299 static char** get_from_array(char ***names
, char *cname
, int size
)
2301 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2304 static bool array_contains(char ***names
, char *cname
, int size
)
2306 if(get_from_array(names
, cname
, size
) != NULL
)
2312 static bool remove_from_array(char ***names
, char *cname
, int size
)
2314 char **result
= get_from_array(names
, cname
, size
);
2315 if (result
!= NULL
) {
2323 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2326 int i
, count
= 0, pipefd
[2];
2327 char **interfaces
= NULL
;
2328 char interface
[IFNAMSIZ
];
2330 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2335 SYSERROR("Failed to fork task to get interfaces information");
2341 if (pid
== 0) { /* child */
2342 int ret
= 1, nbytes
;
2343 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2345 /* close the read-end of the pipe */
2348 if (!enter_net_ns(c
)) {
2349 SYSERROR("Failed to enter network namespace");
2353 /* Grab the list of interfaces */
2354 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2355 SYSERROR("Failed to get interfaces list");
2359 /* Iterate through the interfaces */
2360 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2361 tempIfAddr
= tempIfAddr
->ifa_next
) {
2362 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2373 netns_freeifaddrs(interfaceArray
);
2375 /* close the write-end of the pipe, thus sending EOF to the reader */
2380 /* close the write-end of the pipe */
2383 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2384 interface
[IFNAMSIZ
- 1] = '\0';
2386 if (array_contains(&interfaces
, interface
, count
))
2389 if (!add_to_array(&interfaces
, interface
, count
))
2390 ERROR("Failed to add \"%s\" to array", interface
);
2395 if (wait_for_pid(pid
) != 0) {
2396 for (i
= 0; i
< count
; i
++)
2397 free(interfaces
[i
]);
2403 /* close the read-end of the pipe */
2406 /* Append NULL to the array */
2408 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2413 WRAP_API(char **, lxcapi_get_interfaces
)
2415 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2416 const char *family
, int scope
)
2421 char address
[INET6_ADDRSTRLEN
];
2423 char **addresses
= NULL
;
2425 ret
= pipe2(pipefd
, O_CLOEXEC
);
2427 SYSERROR("Failed to create pipe");
2433 SYSERROR("Failed to create new process");
2441 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2442 char *address_ptr
= NULL
;
2443 void *tempAddrPtr
= NULL
;
2444 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2446 /* close the read-end of the pipe */
2449 if (!enter_net_ns(c
)) {
2450 SYSERROR("Failed to attach to network namespace");
2454 /* Grab the list of interfaces */
2455 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2456 SYSERROR("Failed to get interfaces list");
2460 /* Iterate through the interfaces */
2461 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2462 tempIfAddr
= tempIfAddr
->ifa_next
) {
2463 if (tempIfAddr
->ifa_addr
== NULL
)
2466 #pragma GCC diagnostic push
2467 #pragma GCC diagnostic ignored "-Wcast-align"
2469 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2470 if (family
&& strcmp(family
, "inet"))
2473 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2475 if (family
&& strcmp(family
, "inet6"))
2478 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2481 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2484 #pragma GCC diagnostic pop
2486 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2488 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2491 address_ptr
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2492 tempAddrPtr
, addressOutputBuffer
,
2493 sizeof(addressOutputBuffer
));
2497 nbytes
= lxc_write_nointr(pipefd
[1], address_ptr
, INET6_ADDRSTRLEN
);
2498 if (nbytes
!= INET6_ADDRSTRLEN
) {
2499 SYSERROR("Failed to send ipv6 address \"%s\"",
2511 netns_freeifaddrs(interfaceArray
);
2513 /* close the write-end of the pipe, thus sending EOF to the reader */
2518 /* close the write-end of the pipe */
2521 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2522 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2524 if (!add_to_array(&addresses
, address
, count
))
2525 ERROR("PARENT: add_to_array failed");
2530 if (wait_for_pid(pid
) != 0) {
2531 for (i
= 0; i
< count
; i
++)
2538 /* close the read-end of the pipe */
2541 /* Append NULL to the array */
2543 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2548 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2550 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2553 struct lxc_config_t
*config
;
2555 if (!c
|| !c
->lxc_conf
)
2558 if (container_mem_lock(c
))
2561 config
= lxc_get_config(key
);
2562 /* Verify that the config key exists and that it has a callback
2565 if (config
&& config
->get
)
2566 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2568 container_mem_unlock(c
);
2572 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2574 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2578 if (!c
|| !c
->lxc_conf
)
2581 if (container_mem_lock(c
))
2584 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2585 container_mem_unlock(c
);
2589 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2591 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2595 /* List all config items. */
2597 return lxc_list_config_items(retv
, inlen
);
2599 if (!c
|| !c
->lxc_conf
)
2602 if (container_mem_lock(c
))
2605 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2606 * This is an intelligent result to show which keys are valid given the
2607 * type of nic it is.
2609 if (strncmp(key
, "lxc.net.", 8) == 0)
2610 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2612 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2614 container_mem_unlock(c
);
2618 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2620 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2623 bool ret
= false, need_disklock
= false;
2626 alt_file
= c
->configfile
;
2631 /* If we haven't yet loaded a config, load the stock config. */
2633 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2634 ERROR("Error loading default configuration file %s "
2636 lxc_global_config_value("lxc.default_config"),
2642 if (!create_container_dir(c
))
2645 /* If we're writing to the container's config file, take the disk lock.
2646 * Otherwise just take the memlock to protect the struct lxc_container
2647 * while we're traversing it.
2649 if (strcmp(c
->configfile
, alt_file
) == 0)
2650 need_disklock
= true;
2653 lret
= container_disk_lock(c
);
2655 lret
= container_mem_lock(c
);
2659 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2660 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2664 lret
= write_config(fd
, c
->lxc_conf
);
2673 container_disk_unlock(c
);
2675 container_mem_unlock(c
);
2680 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2683 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2689 char path
[PATH_MAX
];
2690 char newpath
[PATH_MAX
];
2691 int fd
, ret
, n
= 0, v
= 0;
2693 size_t len
= 0, bytes
= 0;
2695 if (container_disk_lock(c0
))
2698 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2699 if (ret
< 0 || ret
> PATH_MAX
)
2702 ret
= snprintf(newpath
, PATH_MAX
, "%s\n%s\n", c
->config_path
, c
->name
);
2703 if (ret
< 0 || ret
> PATH_MAX
)
2706 /* If we find an lxc-snapshot file using the old format only listing the
2707 * number of snapshots we will keep using it. */
2708 f1
= fopen(path
, "r");
2710 n
= fscanf(f1
, "%d", &v
);
2712 if (n
== 1 && v
== 0) {
2715 SYSERROR("Failed to remove \"%s\"", path
);
2723 f1
= fopen(path
, "w");
2727 if (fprintf(f1
, "%d\n", v
) < 0) {
2728 ERROR("Error writing new snapshots value");
2735 SYSERROR("Error writing to or closing snapshots file");
2739 /* Here we know that we have or can use an lxc-snapshot file
2740 * using the new format. */
2742 f1
= fopen(path
, "a");
2746 if (fprintf(f1
, "%s", newpath
) < 0) {
2747 ERROR("Error writing new snapshots entry");
2750 SYSERROR("Error writing to or closing snapshots file");
2756 SYSERROR("Error writing to or closing snapshots file");
2760 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2763 if (fstat(fd
, &fbuf
) < 0) {
2768 if (fbuf
.st_size
!= 0) {
2769 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2770 if (buf
== MAP_FAILED
) {
2771 SYSERROR("Failed to create mapping %s", path
);
2776 len
= strlen(newpath
);
2777 while ((del
= strstr((char *)buf
, newpath
))) {
2778 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2782 lxc_strmunmap(buf
, fbuf
.st_size
);
2783 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2784 SYSERROR("Failed to truncate file %s", path
);
2793 /* If the lxc-snapshot file is empty, remove it. */
2794 if (stat(path
, &fbuf
) < 0)
2797 if (!fbuf
.st_size
) {
2800 SYSERROR("Failed to remove \"%s\"", path
);
2807 container_disk_unlock(c0
);
2811 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2813 struct lxc_container
*p
;
2814 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[PATH_MAX
];
2815 size_t pathlen
= 0, namelen
= 0;
2819 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends",
2820 c
->config_path
, c
->name
);
2821 if (ret
< 0 || ret
>= PATH_MAX
) {
2822 ERROR("Path name too long");
2826 f
= fopen(path
, "r");
2830 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2831 if (getline(&lxcname
, &namelen
, f
) == -1) {
2832 ERROR("badly formatted file %s", path
);
2836 remove_trailing_newlines(lxcpath
);
2837 remove_trailing_newlines(lxcname
);
2839 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2840 ERROR("Unable to find dependent container %s:%s",
2845 if (!mod_rdep(p
, c
, inc
))
2846 ERROR("Failed to update snapshots file for %s:%s",
2849 lxc_container_put(p
);
2858 static bool has_fs_snapshots(struct lxc_container
*c
)
2861 char path
[PATH_MAX
];
2866 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c
->config_path
,
2868 if (ret
< 0 || ret
> PATH_MAX
)
2871 /* If the file doesn't exist there are no snapshots. */
2872 if (stat(path
, &fbuf
) < 0)
2877 f
= fopen(path
, "r");
2881 ret
= fscanf(f
, "%d", &v
);
2883 /* TODO: Figure out what to do with the return value of fscanf. */
2885 INFO("Container uses new lxc-snapshots format %s", path
);
2894 static bool has_snapshots(struct lxc_container
*c
)
2896 char path
[PATH_MAX
];
2897 struct dirent
*direntp
;
2901 if (!get_snappath_dir(c
, path
))
2904 dir
= opendir(path
);
2908 while ((direntp
= readdir(dir
))) {
2909 if (!strcmp(direntp
->d_name
, "."))
2912 if (!strcmp(direntp
->d_name
, ".."))
2922 static bool do_destroy_container(struct lxc_conf
*conf
) {
2925 if (am_guest_unpriv()) {
2926 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2927 "storage_destroy_wrapper");
2934 return storage_destroy(conf
);
2937 static int lxc_rmdir_onedev_wrapper(void *data
)
2939 char *arg
= (char *) data
;
2940 return lxc_rmdir_onedev(arg
, "snaps");
2943 static int lxc_unlink_exec_wrapper(void *data
)
2949 static bool container_destroy(struct lxc_container
*c
,
2950 struct lxc_storage
*storage
)
2954 struct lxc_conf
*conf
;
2959 if (!c
|| !do_lxcapi_is_defined(c
))
2963 if (container_disk_lock(c
))
2966 if (!is_stopped(c
)) {
2967 /* We should queue some sort of error - in c->error_string? */
2968 ERROR("container %s is not stopped", c
->name
);
2972 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2973 /* Start of environment variable setup for hooks */
2974 if (setenv("LXC_NAME", c
->name
, 1))
2975 SYSERROR("Failed to set environment variable for container name");
2977 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2978 SYSERROR("Failed to set environment variable for config path");
2980 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2981 SYSERROR("Failed to set environment variable for rootfs mount");
2983 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2984 SYSERROR("Failed to set environment variable for rootfs mount");
2986 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2987 SYSERROR("Failed to set environment variable for console path");
2989 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2990 SYSERROR("Failed to set environment variable for console log");
2991 /* End of environment variable setup for hooks */
2993 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2994 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2999 if (current_config
&& conf
== current_config
) {
3000 current_config
= NULL
;
3002 if (conf
->logfd
!= -1) {
3008 /* LXC is not managing the storage of the container. */
3009 if (conf
&& !conf
->rootfs
.managed
)
3012 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
3013 if (!do_destroy_container(conf
)) {
3014 ERROR("Error destroying rootfs for %s", c
->name
);
3017 INFO("Destroyed rootfs for %s", c
->name
);
3020 mod_all_rdeps(c
, false);
3022 p1
= do_lxcapi_get_config_path(c
);
3031 * strlen("config") = 6
3035 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3038 ERROR("Failed to allocate memory");
3042 /* For an overlay container the rootfs is considered immutable and
3043 * cannot be removed when restoring from a snapshot.
3045 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3046 !strcmp(storage
->type
, "overlayfs")) &&
3047 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3048 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3049 if (ret
< 0 || (size_t)ret
>= len
)
3052 if (am_guest_unpriv())
3053 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3054 "lxc_unlink_exec_wrapper");
3058 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3062 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3068 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3069 if (ret
< 0 || (size_t)ret
>= len
)
3072 if (am_guest_unpriv())
3073 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3074 "lxc_rmdir_onedev_wrapper");
3076 ret
= lxc_rmdir_onedev(path
, "snaps");
3078 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3082 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3091 container_disk_unlock(c
);
3095 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3097 if (!c
|| !lxcapi_is_defined(c
))
3100 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3101 if (has_snapshots(c
)) {
3102 ERROR("Container %s has snapshots; not removing", c
->name
);
3106 if (has_fs_snapshots(c
)) {
3107 ERROR("container %s has snapshots on its rootfs", c
->name
);
3112 return container_destroy(c
, NULL
);
3115 WRAP_API(bool, lxcapi_destroy
)
3117 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3119 if (!c
|| !lxcapi_is_defined(c
))
3122 if (!lxcapi_snapshot_destroy_all(c
)) {
3123 ERROR("Error deleting all snapshots");
3127 return lxcapi_destroy(c
);
3130 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3132 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3136 struct lxc_config_t
*config
;
3139 config
= lxc_get_config(key
);
3143 ret
= config
->set(key
, v
, conf
, NULL
);
3147 if (lxc_config_value_empty(v
))
3148 do_clear_unexp_config_line(conf
, key
);
3150 bret
= do_append_unexp_config_line(conf
, key
, v
);
3157 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3163 c
->lxc_conf
= lxc_conf_init();
3168 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3175 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3182 if (container_mem_lock(c
))
3185 b
= do_set_config_item_locked(c
, key
, v
);
3187 container_mem_unlock(c
);
3191 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3193 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3195 if (!c
|| !c
->configfile
)
3198 return strdup(c
->configfile
);
3201 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3203 if (!c
|| !c
->config_path
)
3206 return (const char *)(c
->config_path
);
3211 * Just recalculate the c->configfile based on the
3212 * c->config_path, which must be set.
3213 * The lxc_container must be locked or not yet public.
3215 static bool set_config_filename(struct lxc_container
*c
)
3220 if (!c
->config_path
)
3223 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3224 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3225 newpath
= malloc(len
);
3229 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3230 if (ret
< 0 || ret
>= len
) {
3231 fprintf(stderr
, "Error printing out config file name\n");
3236 free(c
->configfile
);
3237 c
->configfile
= newpath
;
3242 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3246 char *oldpath
= NULL
;
3251 if (container_mem_lock(c
))
3256 ERROR("Out of memory setting new lxc path");
3262 oldpath
= c
->config_path
;
3265 /* Since we've changed the config path, we have to change the
3266 * config file name too */
3267 if (!set_config_filename(c
)) {
3268 ERROR("Out of memory setting new config filename");
3270 free(c
->config_path
);
3271 c
->config_path
= oldpath
;
3277 container_mem_unlock(c
);
3281 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3283 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3286 struct cgroup_ops
*cgroup_ops
;
3294 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3298 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3300 cgroup_exit(cgroup_ops
);
3305 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3307 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3310 struct cgroup_ops
*cgroup_ops
;
3318 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3322 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3325 cgroup_exit(cgroup_ops
);
3330 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3332 const char *lxc_get_global_config_item(const char *key
)
3334 return lxc_global_config_value(key
);
3337 const char *lxc_get_version(void)
3342 static int copy_file(const char *old
, const char *new)
3349 if (file_exists(new)) {
3350 ERROR("copy destination %s exists", new);
3354 ret
= stat(old
, &sbuf
);
3356 INFO("Error stat'ing %s", old
);
3360 in
= open(old
, O_RDONLY
);
3362 SYSERROR("Error opening original file %s", old
);
3366 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3368 SYSERROR("Error opening new file %s", new);
3374 len
= lxc_read_nointr(in
, buf
, 8096);
3376 SYSERROR("Error reading old file %s", old
);
3383 ret
= lxc_write_nointr(out
, buf
, len
);
3384 if (ret
< len
) { /* should we retry? */
3385 SYSERROR("Error: write to new file %s was interrupted", new);
3393 /* We set mode, but not owner/group. */
3394 ret
= chmod(new, sbuf
.st_mode
);
3396 SYSERROR("Error setting mode on %s", new);
3408 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3411 struct lxc_list
*it
;
3414 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3415 cpath
= alloca(len
);
3416 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3417 if (ret
< 0 || ret
>= len
)
3420 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3421 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3422 char *hookname
= it
->elem
;
3423 char *fname
= strrchr(hookname
, '/');
3424 char tmppath
[PATH_MAX
];
3425 if (!fname
) /* relative path - we don't support, but maybe we should */
3428 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3429 /* this hook is public - ignore */
3433 /* copy the script, and change the entry in confile */
3434 ret
= snprintf(tmppath
, PATH_MAX
, "%s/%s/%s",
3435 c
->config_path
, c
->name
, fname
+1);
3436 if (ret
< 0 || ret
>= PATH_MAX
)
3439 ret
= copy_file(it
->elem
, tmppath
);
3445 it
->elem
= strdup(tmppath
);
3447 ERROR("out of memory copying hook path");
3453 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3454 c
->config_path
, oldc
->name
, c
->name
)) {
3455 ERROR("Error saving new hooks in clone");
3459 do_lxcapi_save_config(c
, NULL
);
3464 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3466 char newpath
[PATH_MAX
];
3467 char *oldpath
= oldc
->lxc_conf
->fstab
;
3473 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3475 char *p
= strrchr(oldpath
, '/');
3479 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s%s",
3480 c
->config_path
, c
->name
, p
);
3481 if (ret
< 0 || ret
>= PATH_MAX
) {
3482 ERROR("error printing new path for %s", oldpath
);
3486 if (file_exists(newpath
)) {
3487 ERROR("error: fstab file %s exists", newpath
);
3491 if (copy_file(oldpath
, newpath
) < 0) {
3492 ERROR("error: copying %s to %s", oldpath
, newpath
);
3496 free(c
->lxc_conf
->fstab
);
3498 c
->lxc_conf
->fstab
= strdup(newpath
);
3499 if (!c
->lxc_conf
->fstab
) {
3500 ERROR("error: allocating pathname");
3504 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3505 ERROR("error saving new lxctab");
3512 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3514 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3517 ret
= snprintf(path0
, PATH_MAX
, "%s/%s/lxc_rdepends", c0
->config_path
,
3519 if (ret
< 0 || ret
>= PATH_MAX
) {
3520 WARN("Error copying reverse dependencies");
3524 ret
= snprintf(path1
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3526 if (ret
< 0 || ret
>= PATH_MAX
) {
3527 WARN("Error copying reverse dependencies");
3531 if (copy_file(path0
, path1
) < 0) {
3532 INFO("Error copying reverse dependencies");
3537 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3540 char path
[PATH_MAX
];
3544 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3546 if (ret
< 0 || ret
>= PATH_MAX
)
3549 f
= fopen(path
, "a");
3555 /* If anything goes wrong, just return an error. */
3556 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3566 * If the fs natively supports snapshot clones with no penalty,
3567 * then default to those even if not requested.
3568 * Currently we only do this for btrfs.
3570 bool should_default_to_snapshot(struct lxc_container
*c0
,
3571 struct lxc_container
*c1
)
3574 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3575 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3576 char *p0
= alloca(l0
+ 1);
3577 char *p1
= alloca(l1
+ 1);
3578 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3580 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3581 if (ret
< 0 || ret
>= l0
)
3584 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3585 if (ret
< 0 || ret
>= l1
)
3588 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3591 if (is_btrfs_subvol(rootfs
) <= 0)
3594 return btrfs_same_fs(p0
, p1
) == 0;
3597 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3598 const char *newtype
, int flags
, const char *bdevdata
,
3601 struct lxc_storage
*bdev
;
3604 if (should_default_to_snapshot(c0
, c
))
3605 flags
|= LXC_CLONE_SNAPSHOT
;
3607 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3608 bdevdata
, newsize
, &need_rdep
);
3610 ERROR("Error copying storage.");
3614 /* Set new rootfs. */
3615 free(c
->lxc_conf
->rootfs
.path
);
3616 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3619 if (!c
->lxc_conf
->rootfs
.path
) {
3620 ERROR("Out of memory while setting storage path.");
3624 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3625 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3626 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3627 c
->lxc_conf
->rootfs
.path
)) {
3628 ERROR("Error saving new rootfs to cloned config.");
3632 if (flags
& LXC_CLONE_SNAPSHOT
)
3633 copy_rdepends(c
, c0
);
3636 if (!add_rdepends(c
, c0
))
3637 WARN("Error adding reverse dependency from %s to %s",
3641 mod_all_rdeps(c
, true);
3646 struct clone_update_data
{
3647 struct lxc_container
*c0
;
3648 struct lxc_container
*c1
;
3653 static int clone_update_rootfs(struct clone_update_data
*data
)
3655 struct lxc_container
*c0
= data
->c0
;
3656 struct lxc_container
*c
= data
->c1
;
3657 int flags
= data
->flags
;
3658 char **hookargs
= data
->hookargs
;
3660 char path
[PATH_MAX
];
3661 struct lxc_storage
*bdev
;
3663 struct lxc_conf
*conf
= c
->lxc_conf
;
3665 /* update hostname in rootfs */
3666 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3668 if (setgid(0) < 0) {
3669 ERROR("Failed to setgid to 0");
3673 if (setuid(0) < 0) {
3674 ERROR("Failed to setuid to 0");
3678 if (setgroups(0, NULL
) < 0)
3679 WARN("Failed to clear groups");
3681 if (unshare(CLONE_NEWNS
) < 0)
3684 bdev
= storage_init(c
->lxc_conf
);
3688 if (strcmp(bdev
->type
, "dir") != 0) {
3689 if (unshare(CLONE_NEWNS
) < 0) {
3690 ERROR("error unsharing mounts");
3695 if (detect_shared_rootfs()) {
3696 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3697 SYSERROR("Failed to make / rslave");
3698 ERROR("Continuing...");
3702 if (bdev
->ops
->mount(bdev
) < 0) {
3706 } else { /* TODO come up with a better way */
3708 bdev
->dest
= strdup(lxc_storage_get_path(bdev
->src
, bdev
->type
));
3711 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3712 /* Start of environment variable setup for hooks */
3713 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3714 SYSERROR("failed to set environment variable for source container name");
3716 if (setenv("LXC_NAME", c
->name
, 1))
3717 SYSERROR("failed to set environment variable for container name");
3719 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3720 SYSERROR("failed to set environment variable for config path");
3722 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3723 SYSERROR("failed to set environment variable for rootfs mount");
3725 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3726 SYSERROR("failed to set environment variable for rootfs mount");
3728 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3729 ERROR("Error executing clone hook for %s", c
->name
);
3735 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3736 ret
= snprintf(path
, PATH_MAX
, "%s/etc/hostname", bdev
->dest
);
3739 if (ret
< 0 || ret
>= PATH_MAX
)
3742 if (!file_exists(path
))
3745 if (!(fout
= fopen(path
, "w"))) {
3746 SYSERROR("unable to open %s: ignoring", path
);
3750 if (fprintf(fout
, "%s", c
->name
) < 0) {
3755 if (fclose(fout
) < 0)
3764 static int clone_update_rootfs_wrapper(void *data
)
3766 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3767 return clone_update_rootfs(arg
);
3771 * We want to support:
3772 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3773 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3775 -s [ implies overlay]
3778 only rootfs gets converted (copied/snapshotted) on clone.
3781 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3783 char *p
= strrchr(path
, '/');
3790 ret
= do_create_container_dir(path
, conf
);
3796 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3797 const char *lxcpath
, int flags
,
3798 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3801 char newpath
[PATH_MAX
];
3803 struct clone_update_data data
;
3804 size_t saved_unexp_len
;
3806 int storage_copied
= 0;
3807 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3808 struct lxc_container
*c2
= NULL
;
3810 if (!c
|| !do_lxcapi_is_defined(c
))
3813 if (container_mem_lock(c
))
3815 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3816 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3820 /* Make sure the container doesn't yet exist. */
3825 lxcpath
= do_lxcapi_get_config_path(c
);
3827 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/config", lxcpath
, newname
);
3828 if (ret
< 0 || ret
>= PATH_MAX
) {
3829 SYSERROR("clone: failed making config pathname");
3833 if (file_exists(newpath
)) {
3834 ERROR("error: clone: %s exists", newpath
);
3838 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3839 if (ret
< 0 && errno
!= EEXIST
) {
3840 ERROR("Error creating container dir for %s", newpath
);
3844 /* Copy the configuration. Tweak it as needed. */
3845 if (c
->lxc_conf
->rootfs
.path
) {
3846 origroot
= c
->lxc_conf
->rootfs
.path
;
3847 c
->lxc_conf
->rootfs
.path
= NULL
;
3850 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3851 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3853 SYSERROR("Failed to open \"%s\"", newpath
);
3857 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3858 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3859 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3860 if (!c
->lxc_conf
->unexpanded_config
) {
3865 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3866 write_config(fd
, c
->lxc_conf
);
3869 c
->lxc_conf
->rootfs
.path
= origroot
;
3871 free(c
->lxc_conf
->unexpanded_config
);
3872 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3873 saved_unexp_conf
= NULL
;
3874 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3876 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, newname
);
3877 if (ret
< 0 || ret
>= PATH_MAX
) {
3878 SYSERROR("clone: failed making rootfs pathname");
3882 ret
= mkdir(newpath
, 0755);
3884 /* For an overlay container the rootfs is considered immutable
3885 * and will not have been removed when restoring from a
3888 if (errno
!= ENOENT
&&
3889 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3890 SYSERROR("Failed to create directory \"%s\"", newpath
);
3895 if (am_guest_unpriv()) {
3896 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3897 ERROR("Error chowning %s to container root", newpath
);
3902 c2
= lxc_container_new(newname
, lxcpath
);
3904 ERROR("clone: failed to create new container (%s %s)", newname
,
3909 /* copy/snapshot rootfs's */
3910 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3914 /* update utsname */
3915 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3916 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3917 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3919 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3920 ERROR("Error setting new hostname");
3926 ret
= copyhooks(c
, c2
);
3928 ERROR("error copying hooks");
3932 if (copy_fstab(c
, c2
) < 0) {
3933 ERROR("error copying fstab");
3937 /* update macaddrs */
3938 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3939 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3940 ERROR("Error updating mac addresses");
3945 /* Update absolute paths for overlay mount directories. */
3946 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3949 /* We've now successfully created c2's storage, so clear it out if we
3954 if (!c2
->save_config(c2
, NULL
))
3957 if ((pid
= fork()) < 0) {
3963 ret
= wait_for_pid(pid
);
3967 container_mem_unlock(c
);
3974 data
.hookargs
= hookargs
;
3976 if (am_guest_unpriv())
3977 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3978 &data
, "clone_update_rootfs_wrapper");
3980 ret
= clone_update_rootfs(&data
);
3982 _exit(EXIT_FAILURE
);
3984 container_mem_unlock(c
);
3985 _exit(EXIT_SUCCESS
);
3988 container_mem_unlock(c
);
3990 if (!storage_copied
)
3991 c2
->lxc_conf
->rootfs
.path
= NULL
;
3994 lxc_container_put(c2
);
4000 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
4001 const char *lxcpath
, int flags
,
4002 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
4005 struct lxc_container
* ret
;
4007 current_config
= c
? c
->lxc_conf
: NULL
;
4008 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
4009 current_config
= NULL
;
4014 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4016 struct lxc_storage
*bdev
;
4017 struct lxc_container
*newc
;
4019 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4022 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4023 ERROR("Renaming a container with snapshots is not supported");
4027 bdev
= storage_init(c
->lxc_conf
);
4029 ERROR("Failed to find original backing store type");
4033 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4036 lxc_container_put(newc
);
4040 if (newc
&& lxcapi_is_defined(newc
))
4041 lxc_container_put(newc
);
4043 if (!container_destroy(c
, NULL
)) {
4044 ERROR("Could not destroy existing container %s", c
->name
);
4051 WRAP_API_1(bool, lxcapi_rename
, const char *)
4053 static int lxcapi_attach(struct lxc_container
*c
, lxc_attach_exec_t exec_function
, void *exec_payload
, lxc_attach_options_t
*options
, pid_t
*attached_process
)
4060 current_config
= c
->lxc_conf
;
4062 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4063 current_config
= NULL
;
4067 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4069 lxc_attach_command_t command
;
4076 command
.program
= (char*)program
;
4077 command
.argv
= (char**)argv
;
4079 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4085 return lxc_wait_for_pid_status(pid
);
4088 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4092 current_config
= c
? c
->lxc_conf
: NULL
;
4093 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4094 current_config
= NULL
;
4099 static int get_next_index(const char *lxcpath
, char *cname
)
4105 fname
= alloca(strlen(lxcpath
) + 20);
4108 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4110 ret
= stat(fname
, &sb
);
4118 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4123 * If the old style snapshot path exists, use it
4124 * /var/lib/lxc -> /var/lib/lxcsnaps
4126 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4127 if (ret
< 0 || ret
>= PATH_MAX
)
4130 if (dir_exists(snappath
)) {
4131 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4132 if (ret
< 0 || ret
>= PATH_MAX
)
4139 * Use the new style path
4140 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4142 ret
= snprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4143 if (ret
< 0 || ret
>= PATH_MAX
)
4149 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4154 struct lxc_container
*c2
;
4155 char snappath
[PATH_MAX
], newname
[20];
4159 if (!c
|| !lxcapi_is_defined(c
))
4162 if (!storage_can_backup(c
->lxc_conf
)) {
4163 ERROR("%s's backing store cannot be backed up", c
->name
);
4164 ERROR("Your container must use another backing store type");
4168 if (!get_snappath_dir(c
, snappath
))
4171 i
= get_next_index(snappath
, c
->name
);
4173 if (mkdir_p(snappath
, 0755) < 0) {
4174 ERROR("Failed to create snapshot directory %s", snappath
);
4178 ret
= snprintf(newname
, 20, "snap%d", i
);
4179 if (ret
< 0 || ret
>= 20)
4183 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4184 * created in the original container
4186 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4187 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4188 if (storage_is_dir(c
->lxc_conf
)) {
4189 ERROR("Snapshot of directory-backed container requested");
4190 ERROR("Making a copy-clone. If you do want snapshots, then");
4191 ERROR("please create overlay clone first, snapshot that");
4192 ERROR("and keep the original container pristine");
4193 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4196 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4198 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4202 lxc_container_put(c2
);
4204 /* Now write down the creation time. */
4207 if (!localtime_r(&timer
, &tm_info
)) {
4208 ERROR("Failed to get localtime");
4212 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4214 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4215 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4216 f
= fopen(dfnam
, "w");
4218 ERROR("Failed to open %s", dfnam
);
4222 if (fprintf(f
, "%s", buffer
) < 0) {
4223 SYSERROR("Writing timestamp");
4230 SYSERROR("Writing timestamp");
4235 /* $p / $name / comment \0 */
4236 int len
= strlen(snappath
) + strlen(newname
) + 10;
4237 char *path
= alloca(len
);
4239 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4240 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4246 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4248 static void lxcsnap_free(struct lxc_snapshot
*s
)
4251 free(s
->comment_pathname
);
4256 static char *get_snapcomment_path(char* snappath
, char *name
)
4258 /* $snappath/$name/comment */
4259 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4260 char *s
= malloc(len
);
4263 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4264 if (ret
< 0 || ret
>= len
) {
4273 static char *get_timestamp(char* snappath
, char *name
)
4275 char path
[PATH_MAX
], *s
= NULL
;
4279 ret
= snprintf(path
, PATH_MAX
, "%s/%s/ts", snappath
, name
);
4280 if (ret
< 0 || ret
>= PATH_MAX
)
4283 fin
= fopen(path
, "r");
4287 (void) fseek(fin
, 0, SEEK_END
);
4289 (void) fseek(fin
, 0, SEEK_SET
);
4294 if (fread(s
, 1, len
, fin
) != len
) {
4295 SYSERROR("reading timestamp");
4306 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4308 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4310 struct dirent
*direntp
;
4311 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4314 if (!c
|| !lxcapi_is_defined(c
))
4317 if (!get_snappath_dir(c
, snappath
)) {
4318 ERROR("path name too long");
4322 dir
= opendir(snappath
);
4324 INFO("Failed to open %s - assuming no snapshots", snappath
);
4328 while ((direntp
= readdir(dir
))) {
4329 if (!strcmp(direntp
->d_name
, "."))
4332 if (!strcmp(direntp
->d_name
, ".."))
4335 ret
= snprintf(path2
, PATH_MAX
, "%s/%s/config", snappath
, direntp
->d_name
);
4336 if (ret
< 0 || ret
>= PATH_MAX
) {
4337 ERROR("pathname too long");
4341 if (!file_exists(path2
))
4344 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4346 SYSERROR("Out of memory");
4351 snaps
[count
].free
= lxcsnap_free
;
4352 snaps
[count
].name
= strdup(direntp
->d_name
);
4353 if (!snaps
[count
].name
)
4356 snaps
[count
].lxcpath
= strdup(snappath
);
4357 if (!snaps
[count
].lxcpath
) {
4358 free(snaps
[count
].name
);
4362 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4363 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4368 WARN("Failed to close directory");
4377 for (i
=0; i
<count
; i
++)
4378 lxcsnap_free(&snaps
[i
]);
4384 WARN("Failed to close directory");
4389 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4391 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4393 char clonelxcpath
[PATH_MAX
];
4395 struct lxc_container
*snap
, *rest
;
4396 struct lxc_storage
*bdev
;
4399 if (!c
|| !c
->name
|| !c
->config_path
)
4402 if (has_fs_snapshots(c
)) {
4403 ERROR("container rootfs has dependent snapshots");
4407 bdev
= storage_init(c
->lxc_conf
);
4409 ERROR("Failed to find original backing store type");
4413 /* For an overlay container the rootfs is considered immutable
4414 * and cannot be removed when restoring from a snapshot. We pass this
4415 * internal flag along to communicate this to various parts of the
4418 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4419 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4424 if (!get_snappath_dir(c
, clonelxcpath
)) {
4428 /* how should we lock this? */
4430 snap
= lxc_container_new(snapname
, clonelxcpath
);
4431 if (!snap
|| !lxcapi_is_defined(snap
)) {
4432 ERROR("Could not open snapshot %s", snapname
);
4435 lxc_container_put(snap
);
4441 if (!strcmp(c
->name
, newname
)) {
4442 if (!container_destroy(c
, bdev
)) {
4443 ERROR("Could not destroy existing container %s", newname
);
4444 lxc_container_put(snap
);
4450 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4451 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4453 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4454 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4456 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4459 if (rest
&& lxcapi_is_defined(rest
))
4463 lxc_container_put(rest
);
4465 lxc_container_put(snap
);
4469 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4471 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4473 struct lxc_container
*snap
= NULL
;
4476 snap
= lxc_container_new(snapname
, clonelxcpath
);
4478 ERROR("Could not find snapshot %s", snapname
);
4482 if (!do_lxcapi_destroy(snap
)) {
4483 ERROR("Could not destroy snapshot %s", snapname
);
4491 lxc_container_put(snap
);
4496 static bool remove_all_snapshots(const char *path
)
4499 struct dirent
*direntp
;
4502 dir
= opendir(path
);
4504 SYSERROR("opendir on snapshot path %s", path
);
4508 while ((direntp
= readdir(dir
))) {
4509 if (!strcmp(direntp
->d_name
, "."))
4512 if (!strcmp(direntp
->d_name
, ".."))
4515 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4524 SYSERROR("Error removing directory %s", path
);
4529 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4531 char clonelxcpath
[PATH_MAX
];
4533 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4536 if (!get_snappath_dir(c
, clonelxcpath
))
4539 return do_snapshot_destroy(snapname
, clonelxcpath
);
4542 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4544 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4546 char clonelxcpath
[PATH_MAX
];
4548 if (!c
|| !c
->name
|| !c
->config_path
)
4551 if (!get_snappath_dir(c
, clonelxcpath
))
4554 return remove_all_snapshots(clonelxcpath
);
4557 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4559 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4564 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4567 WRAP_API(bool, lxcapi_may_control
)
4569 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4575 char chrootpath
[PATH_MAX
];
4576 char *directory_path
= NULL
;
4580 SYSERROR("Failed to fork()");
4585 ret
= wait_for_pid(pid
);
4587 ERROR("Failed to create device node");
4594 /* prepare the path */
4595 ret
= snprintf(chrootpath
, PATH_MAX
, "/proc/%d/root", init_pid
);
4596 if (ret
< 0 || ret
>= PATH_MAX
)
4599 ret
= chroot(chrootpath
);
4601 _exit(EXIT_FAILURE
);
4605 _exit(EXIT_FAILURE
);
4607 /* remove path if it exists */
4608 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4612 SYSERROR("Failed to remove \"%s\"", path
);
4613 _exit(EXIT_FAILURE
);
4618 _exit(EXIT_SUCCESS
);
4620 /* create any missing directories */
4623 _exit(EXIT_FAILURE
);
4625 directory_path
= dirname(tmp
);
4626 ret
= mkdir_p(directory_path
, 0755);
4627 if (ret
< 0 && errno
!= EEXIST
) {
4628 SYSERROR("Failed to create path \"%s\"", directory_path
);
4630 _exit(EXIT_FAILURE
);
4633 /* create the device node */
4634 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4637 SYSERROR("Failed to create device node at \"%s\"", path
);
4638 _exit(EXIT_FAILURE
);
4641 _exit(EXIT_SUCCESS
);
4644 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4648 char value
[LXC_MAX_BUFFER
];
4651 /* make sure container is running */
4652 if (!do_lxcapi_is_running(c
)) {
4653 ERROR("container is not running");
4657 /* use src_path if dest_path is NULL otherwise use dest_path */
4658 p
= dest_path
? dest_path
: src_path
;
4660 /* make sure we can access p */
4661 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4664 /* continue if path is character device or block device */
4665 if (S_ISCHR(st
.st_mode
))
4666 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4667 else if (S_ISBLK(st
.st_mode
))
4668 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4672 /* check snprintf return code */
4673 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4676 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4679 /* add or remove device to/from cgroup access list */
4681 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4682 ERROR("set_cgroup_item failed while adding the device node");
4686 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4687 ERROR("set_cgroup_item failed while removing the device node");
4695 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4697 // cannot mknod if we're not privileged wrt init_user_ns
4698 if (am_host_unpriv()) {
4699 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4703 return add_remove_device_node(c
, src_path
, dest_path
, true);
4706 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4708 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4710 if (am_guest_unpriv()) {
4711 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4715 return add_remove_device_node(c
, src_path
, dest_path
, false);
4718 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4720 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4722 const char *dst_ifname
)
4727 if (am_guest_unpriv()) {
4728 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4733 ERROR("No source interface name given");
4737 ret
= lxc_netdev_isup(ifname
);
4739 /* netdev of ifname is up. */
4740 ret
= lxc_netdev_down(ifname
);
4745 init_pid
= do_lxcapi_init_pid(c
);
4746 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4750 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4757 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4759 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4761 const char *dst_ifname
)
4764 pid_t pid
, pid_outside
;
4767 * TODO - if this is a physical device, then we need am_host_unpriv.
4768 * But for other types guest privilege suffices.
4770 if (am_guest_unpriv()) {
4771 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4776 ERROR("No source interface name given");
4780 pid_outside
= lxc_raw_getpid();
4783 ERROR("Failed to fork");
4787 if (pid
== 0) { /* child */
4790 init_pid
= do_lxcapi_init_pid(c
);
4791 if (!switch_to_ns(init_pid
, "net")) {
4792 ERROR("Failed to enter network namespace");
4793 _exit(EXIT_FAILURE
);
4796 ret
= lxc_netdev_isup(ifname
);
4798 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4799 _exit(EXIT_FAILURE
);
4802 /* netdev of ifname is up. */
4804 ret
= lxc_netdev_down(ifname
);
4806 ERROR("Failed to set network device \"%s\" down", ifname
);
4807 _exit(EXIT_FAILURE
);
4811 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4812 /* -EINVAL means there is no netdev named as ifname. */
4815 ERROR("Network device \"%s\" not found", ifname
);
4817 ERROR("Failed to remove network device \"%s\"", ifname
);
4819 _exit(EXIT_FAILURE
);
4822 _exit(EXIT_SUCCESS
);
4825 ret
= wait_for_pid(pid
);
4829 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4833 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4835 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4836 struct migrate_opts
*opts
, unsigned int size
)
4839 struct migrate_opts
*valid_opts
= opts
;
4840 uint64_t features_to_check
= 0;
4842 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4843 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4844 * to do anything special.
4846 if (size
> sizeof(*opts
)) {
4847 unsigned char *addr
;
4850 addr
= (void *)opts
+ sizeof(*opts
);
4851 end
= (void *)opts
+ size
;
4853 for (; addr
< end
; addr
++)
4858 /* If the caller has a smaller struct, let's zero out the end for them
4859 * so we don't accidentally use bits of it that they didn't know about
4862 if (size
< sizeof(*opts
)) {
4863 valid_opts
= malloc(sizeof(*opts
));
4867 memset(valid_opts
, 0, sizeof(*opts
));
4868 memcpy(valid_opts
, opts
, size
);
4872 case MIGRATE_PRE_DUMP
:
4873 if (!do_lxcapi_is_running(c
)) {
4874 ERROR("container is not running");
4878 ret
= !__criu_pre_dump(c
, valid_opts
);
4881 if (!do_lxcapi_is_running(c
)) {
4882 ERROR("container is not running");
4886 ret
= !__criu_dump(c
, valid_opts
);
4888 case MIGRATE_RESTORE
:
4889 if (do_lxcapi_is_running(c
)) {
4890 ERROR("container is already running");
4894 ret
= !__criu_restore(c
, valid_opts
);
4896 case MIGRATE_FEATURE_CHECK
:
4897 features_to_check
= valid_opts
->features_to_check
;
4898 ret
= !__criu_check_feature(&features_to_check
);
4900 /* Something went wrong. Let's let the caller
4901 * know which feature checks failed. */
4902 valid_opts
->features_to_check
= features_to_check
;
4906 ERROR("invalid migrate command %u", cmd
);
4911 if (size
< sizeof(*opts
))
4917 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4919 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4921 struct migrate_opts opts
;
4923 memset(&opts
, 0, sizeof(opts
));
4925 opts
.directory
= directory
;
4927 opts
.verbose
= verbose
;
4929 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4932 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4934 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4936 struct migrate_opts opts
;
4938 memset(&opts
, 0, sizeof(opts
));
4940 opts
.directory
= directory
;
4941 opts
.verbose
= verbose
;
4943 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4946 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4948 /* @st_mode is the st_mode field of the stat(source) return struct */
4949 static int create_mount_target(const char *dest
, mode_t st_mode
)
4951 char *dirdup
, *destdirname
;
4954 dirdup
= strdup(dest
);
4956 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4959 destdirname
= dirname(dirdup
);
4961 ret
= mkdir_p(destdirname
, 0755);
4963 SYSERROR("Failed to create \"%s\"", destdirname
);
4971 if (S_ISDIR(st_mode
))
4972 ret
= mkdir(dest
, 0000);
4974 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4976 SYSERROR("Failed to create mount target \"%s\"", dest
);
4983 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4984 const char *target
, const char *filesystemtype
,
4985 unsigned long mountflags
, const void *data
,
4986 struct lxc_mount
*mnt
)
4989 char template[PATH_MAX
], path
[PATH_MAX
];
4990 pid_t pid
, init_pid
;
4993 int ret
= -1, fd
= -EBADF
;
4995 if (!c
|| !c
->lxc_conf
) {
4996 ERROR("Container or configuration is NULL");
5000 if (!c
->lxc_conf
->shmount
.path_host
) {
5001 ERROR("Host path to shared mountpoint must be specified in the config\n");
5005 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5006 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
5007 SYSERROR("Error writing shmounts tempdir name");
5011 /* Create a temporary file / dir under the shared mountpoint */
5012 if (!source
|| strcmp(source
, "") == 0) {
5013 /* If source is not specified, maybe we want to mount a filesystem? */
5014 sb
.st_mode
= S_IFDIR
;
5016 ret
= stat(source
, &sb
);
5018 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5023 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5025 sret
= mkdtemp(template);
5027 SYSERROR("Could not create shmounts temporary dir");
5031 fd
= lxc_make_tmpfile(template, false);
5033 SYSERROR("Could not create shmounts temporary file");
5041 SYSERROR("Could not fork");
5047 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5049 SYSERROR("Failed to mount onto \"%s\"", template);
5050 _exit(EXIT_FAILURE
);
5052 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5054 init_pid
= do_lxcapi_init_pid(c
);
5056 ERROR("Failed to obtain container's init pid");
5057 _exit(EXIT_FAILURE
);
5060 /* Enter the container namespaces */
5061 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5062 if (!switch_to_ns(init_pid
, "user")) {
5063 ERROR("Failed to enter user namespace");
5064 _exit(EXIT_FAILURE
);
5067 if (!lxc_switch_uid_gid(0, 0))
5068 _exit(EXIT_FAILURE
);
5071 if (!switch_to_ns(init_pid
, "mnt")) {
5072 ERROR("Failed to enter mount namespace");
5073 _exit(EXIT_FAILURE
);
5076 ret
= create_mount_target(target
, sb
.st_mode
);
5078 _exit(EXIT_FAILURE
);
5079 TRACE("Created mount target \"%s\"", target
);
5081 suff
= strrchr(template, '/');
5083 _exit(EXIT_FAILURE
);
5085 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5086 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5087 SYSERROR("Error writing container mountpoint name");
5088 _exit(EXIT_FAILURE
);
5091 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5093 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5094 _exit(EXIT_FAILURE
);
5096 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5098 _exit(EXIT_SUCCESS
);
5101 ret
= wait_for_pid(pid
);
5103 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5109 (void)umount2(template, MNT_DETACH
);
5111 (void)rmdir(template);
5113 (void)unlink(template);
5122 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5123 unsigned long, const void *, struct lxc_mount
*)
5125 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5126 unsigned long flags
, struct lxc_mount
*mnt
)
5128 pid_t pid
, init_pid
;
5131 if (!c
|| !c
->lxc_conf
) {
5132 ERROR("Container or configuration is NULL");
5139 SYSERROR("Could not fork");
5144 init_pid
= do_lxcapi_init_pid(c
);
5146 ERROR("Failed to obtain container's init pid");
5147 _exit(EXIT_FAILURE
);
5150 /* Enter the container namespaces */
5151 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5152 if (!switch_to_ns(init_pid
, "user")) {
5153 ERROR("Failed to enter user namespace");
5154 _exit(EXIT_FAILURE
);
5158 if (!switch_to_ns(init_pid
, "mnt")) {
5159 ERROR("Failed to enter mount namespace");
5160 _exit(EXIT_FAILURE
);
5163 /* Do the unmount */
5164 ret
= umount2(target
, flags
);
5166 SYSERROR("Failed to umount \"%s\"", target
);
5167 _exit(EXIT_FAILURE
);
5170 _exit(EXIT_SUCCESS
);
5173 ret
= wait_for_pid(pid
);
5175 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5182 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5184 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5193 current_config
= c
->lxc_conf
;
5196 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5200 ERROR("Memory allocation error.");
5206 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5210 current_config
= NULL
;
5214 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5216 struct lxc_container
*c
;
5222 c
= malloc(sizeof(*c
));
5224 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5227 memset(c
, 0, sizeof(*c
));
5230 c
->config_path
= strdup(configpath
);
5232 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5233 if (!c
->config_path
) {
5234 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5238 remove_trailing_slashes(c
->config_path
);
5241 c
->name
= malloc(len
+ 1);
5243 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5246 (void)strlcpy(c
->name
, name
, len
+ 1);
5249 c
->slock
= lxc_newlock(c
->config_path
, name
);
5251 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5255 c
->privlock
= lxc_newlock(NULL
, NULL
);
5257 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5261 if (!set_config_filename(c
)) {
5262 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5266 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5267 fprintf(stderr
, "Failed to load config for %s\n", name
);
5271 if (ongoing_create(c
) == 2) {
5272 ERROR("Failed to complete container creation for %s", c
->name
);
5273 container_destroy(c
, NULL
);
5274 lxcapi_clear_config(c
);
5277 c
->daemonize
= true;
5280 /* Assign the member functions. */
5281 c
->is_defined
= lxcapi_is_defined
;
5282 c
->state
= lxcapi_state
;
5283 c
->is_running
= lxcapi_is_running
;
5284 c
->freeze
= lxcapi_freeze
;
5285 c
->unfreeze
= lxcapi_unfreeze
;
5286 c
->console
= lxcapi_console
;
5287 c
->console_getfd
= lxcapi_console_getfd
;
5288 c
->init_pid
= lxcapi_init_pid
;
5289 c
->load_config
= lxcapi_load_config
;
5290 c
->want_daemonize
= lxcapi_want_daemonize
;
5291 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5292 c
->start
= lxcapi_start
;
5293 c
->startl
= lxcapi_startl
;
5294 c
->stop
= lxcapi_stop
;
5295 c
->config_file_name
= lxcapi_config_file_name
;
5296 c
->wait
= lxcapi_wait
;
5297 c
->set_config_item
= lxcapi_set_config_item
;
5298 c
->destroy
= lxcapi_destroy
;
5299 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5300 c
->rename
= lxcapi_rename
;
5301 c
->save_config
= lxcapi_save_config
;
5302 c
->get_keys
= lxcapi_get_keys
;
5303 c
->create
= lxcapi_create
;
5304 c
->createl
= lxcapi_createl
;
5305 c
->shutdown
= lxcapi_shutdown
;
5306 c
->reboot
= lxcapi_reboot
;
5307 c
->reboot2
= lxcapi_reboot2
;
5308 c
->clear_config
= lxcapi_clear_config
;
5309 c
->clear_config_item
= lxcapi_clear_config_item
;
5310 c
->get_config_item
= lxcapi_get_config_item
;
5311 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5312 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5313 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5314 c
->get_config_path
= lxcapi_get_config_path
;
5315 c
->set_config_path
= lxcapi_set_config_path
;
5316 c
->clone
= lxcapi_clone
;
5317 c
->get_interfaces
= lxcapi_get_interfaces
;
5318 c
->get_ips
= lxcapi_get_ips
;
5319 c
->attach
= lxcapi_attach
;
5320 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5321 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5322 c
->snapshot
= lxcapi_snapshot
;
5323 c
->snapshot_list
= lxcapi_snapshot_list
;
5324 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5325 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5326 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5327 c
->may_control
= lxcapi_may_control
;
5328 c
->add_device_node
= lxcapi_add_device_node
;
5329 c
->remove_device_node
= lxcapi_remove_device_node
;
5330 c
->attach_interface
= lxcapi_attach_interface
;
5331 c
->detach_interface
= lxcapi_detach_interface
;
5332 c
->checkpoint
= lxcapi_checkpoint
;
5333 c
->restore
= lxcapi_restore
;
5334 c
->migrate
= lxcapi_migrate
;
5335 c
->console_log
= lxcapi_console_log
;
5336 c
->mount
= lxcapi_mount
;
5337 c
->umount
= lxcapi_umount
;
5342 lxc_container_free(c
);
5346 int lxc_get_wait_states(const char **states
)
5351 for (i
=0; i
<MAX_STATE
; i
++)
5352 states
[i
] = lxc_state2str(i
);
5358 * These next two could probably be done smarter with reusing a common function
5359 * with different iterators and tests...
5361 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5364 int i
, cfound
= 0, nfound
= 0;
5365 struct dirent
*direntp
;
5366 struct lxc_container
*c
;
5369 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5371 dir
= opendir(lxcpath
);
5373 SYSERROR("opendir on lxcpath");
5383 while ((direntp
= readdir(dir
))) {
5384 /* Ignore '.', '..' and any hidden directory. */
5385 if (!strncmp(direntp
->d_name
, ".", 1))
5388 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5392 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5402 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5404 INFO("Container %s:%s has a config but could not be loaded",
5405 lxcpath
, direntp
->d_name
);
5408 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5414 if (!do_lxcapi_is_defined(c
)) {
5415 INFO("Container %s:%s has a config but is not defined",
5416 lxcpath
, direntp
->d_name
);
5419 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5422 lxc_container_put(c
);
5426 if (!add_to_clist(cret
, c
, nfound
, true)) {
5427 lxc_container_put(c
);
5438 if (names
&& *names
) {
5439 for (i
=0; i
<cfound
; i
++)
5444 if (cret
&& *cret
) {
5445 for (i
=0; i
<nfound
; i
++)
5446 lxc_container_put((*cret
)[i
]);
5454 int list_active_containers(const char *lxcpath
, char ***nret
,
5455 struct lxc_container
***cret
)
5457 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5460 char **ct_name
= NULL
;
5462 struct lxc_container
*c
= NULL
;
5466 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5467 lxcpath_len
= strlen(lxcpath
);
5475 FILE *f
= fopen("/proc/net/unix", "r");
5479 while (getline(&line
, &len
, f
) != -1) {
5480 char *p
= strrchr(line
, ' '), *p2
;
5491 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5493 } else if (strncmp(p
, "lxc/", 4) == 0) {
5503 /* Now p is the start of lxc_name. */
5504 p2
= strchr(p
, '/');
5505 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5510 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5514 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5520 p
= lxc_cmd_get_name(p
);
5525 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5531 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5534 goto free_cret_list
;
5545 c
= lxc_container_new(p
, lxcpath
);
5547 INFO("Container %s:%s is running but could not be loaded",
5550 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5561 * If this is an anonymous container, then is_defined *can*
5562 * return false. So we don't do that check. Count on the
5563 * fact that the command socket exists.
5566 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5567 lxc_container_put(c
);
5568 goto free_cret_list
;
5574 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5576 lxc_container_put(c
);
5577 goto free_cret_list
;
5589 if (cret
&& *cret
) {
5590 for (i
= 0; i
< cret_cnt
; i
++)
5591 lxc_container_put((*cret
)[i
]);
5597 for (i
= 0; i
< ct_name_cnt
; i
++)
5608 int list_all_containers(const char *lxcpath
, char ***nret
,
5609 struct lxc_container
***cret
)
5611 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5614 struct lxc_container
**ct_list
= NULL
;
5616 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5620 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5621 if (active_cnt
< 0) {
5626 for (i
= 0; i
< active_cnt
; i
++) {
5627 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5628 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5630 goto free_active_name
;
5636 free(active_name
[i
]);
5637 active_name
[i
] = NULL
;
5644 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5645 struct lxc_container
*c
;
5647 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5649 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5650 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5654 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5655 lxc_container_put(c
);
5676 for (i
= 0; i
< ct_list_cnt
; i
++) {
5677 lxc_container_put(ct_list
[i
]);
5682 for (i
= 0; i
< active_cnt
; i
++) {
5683 free(active_name
[i
]);
5688 for (i
= 0; i
< ct_cnt
; i
++) {
5695 bool lxc_config_item_is_supported(const char *key
)
5697 return !!lxc_get_config(key
);
5700 bool lxc_has_api_extension(const char *extension
)
5702 /* The NULL API extension is always present. :) */
5706 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5707 if (strcmp(api_extensions
[i
], extension
) == 0)