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"
71 #include "storage/btrfs.h"
72 #include "storage/overlay.h"
73 #include "storage_utils.h"
81 #include <sys/mkdev.h>
85 #include <../include/lxcmntent.h>
91 #include "include/strlcpy.h"
94 /* Define faccessat() if missing from the C library */
95 #ifndef HAVE_FACCESSAT
96 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
99 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
107 lxc_log_define(lxccontainer
, lxc
);
109 static bool do_lxcapi_destroy(struct lxc_container
*c
);
110 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
111 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
112 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
113 static bool container_destroy(struct lxc_container
*c
,
114 struct lxc_storage
*storage
);
115 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
116 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
117 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
119 static bool config_file_exists(const char *lxcpath
, const char *cname
)
125 /* $lxcpath + '/' + $cname + '/config' + \0 */
126 len
= strlen(lxcpath
) + strlen(cname
) + 9;
128 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
129 if (ret
< 0 || (size_t)ret
>= len
)
132 return file_exists(fname
);
135 /* A few functions to help detect when a container creation failed. If a
136 * container creation was killed partway through, then trying to actually start
137 * that container could harm the host. We detect this by creating a 'partial'
138 * file under the container directory, and keeping an advisory lock. When
139 * container creation completes, we remove that file. When we load or try to
140 * start a container, if we find that file, without a flock, we remove the
143 static int ongoing_create(struct lxc_container
*c
)
148 struct flock lk
= {0};
150 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
152 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
153 if (ret
< 0 || (size_t)ret
>= len
)
156 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
165 lk
.l_whence
= SEEK_SET
;
166 /* F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
171 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
172 if (ret
< 0 && errno
== EINVAL
) {
173 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
174 if (ret
< 0 && errno
== EWOULDBLOCK
)
180 /* F_OFD_GETLK will not send us back a pid so don't check it. */
182 /* Create is still ongoing. */
185 /* Create completed but partial is still there. */
189 static int create_partial(struct lxc_container
*c
)
194 struct flock lk
= {0};
196 /* $lxcpath + '/' + $name + '/partial' + \0 */
197 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
199 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
200 if (ret
< 0 || (size_t)ret
>= len
)
203 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
208 lk
.l_whence
= SEEK_SET
;
210 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
212 if (errno
== EINVAL
) {
213 ret
= flock(fd
, LOCK_EX
);
218 SYSERROR("Failed to lock partial file %s", path
);
226 static void remove_partial(struct lxc_container
*c
, int fd
)
234 /* $lxcpath + '/' + $name + '/partial' + \0 */
235 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
237 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
238 if (ret
< 0 || (size_t)ret
>= len
)
243 SYSERROR("Failed to remove partial file %s", path
);
247 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
248 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
249 * container configuration file.
250 * The container_disk_lock also takes the container_mem_lock.
251 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
252 * NOTHING mutexes two independent programs with their own struct
253 * lxc_container for the same c->name, between API calls. For instance,
254 * c->config_read(); c->start(); Between those calls, data on disk
255 * could change (which shouldn't bother the caller unless for instance
256 * the rootfs get moved). c->config_read(); update; c->config_write();
257 * Two such updaters could race. The callers should therefore check their
258 * results. Trying to prevent that would necessarily expose us to deadlocks
259 * due to hung callers. So I prefer to keep the locks only within our own
260 * functions, not across functions.
262 * If you're going to clone while holding a lxccontainer, increment
263 * c->numthreads (under privlock) before forking. When deleting,
264 * decrement numthreads under privlock, then if it hits 0 you can delete.
265 * Do not ever use a lxccontainer whose numthreads you did not bump.
267 static void lxc_container_free(struct lxc_container
*c
)
273 c
->configfile
= NULL
;
275 free(c
->error_string
);
276 c
->error_string
= NULL
;
279 lxc_putlock(c
->slock
);
284 lxc_putlock(c
->privlock
);
292 lxc_conf_free(c
->lxc_conf
);
296 free(c
->config_path
);
297 c
->config_path
= NULL
;
302 /* Consider the following case:
304 * |====================================================================|
305 * | freer | racing get()er |
306 * |====================================================================|
307 * | lxc_container_put() | lxc_container_get() |
308 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
309 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
310 * | \ lxcunlock() | \ |
311 * | \ lxc_container_free() | \ lxclock() returns |
312 * | | \ c->numthreads < 1 -> return 0 |
313 * | \ \ (free stuff) | |
314 * | \ \ sem_destroy(privlock) | |
315 * |_______________________________|____________________________________|
317 * When the get()er checks numthreads the first time, one of the following
319 * 1. freer has set numthreads = 0. get() returns 0
320 * 2. freer is between lxclock and setting numthreads to 0. get()er will
321 * sem_wait on privlock, get lxclock after freer() drops it, then see
322 * numthreads is 0 and exit without touching lxclock again..
323 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
324 * will see --numthreads = 1 and not call lxc_container_free().
327 int lxc_container_get(struct lxc_container
*c
)
332 /* If someone else has already started freeing the container, don't try
333 * to take the lock, which may be invalid.
335 if (c
->numthreads
< 1)
338 if (container_mem_lock(c
))
341 /* Bail without trying to unlock, bc the privlock is now probably in
344 if (c
->numthreads
< 1)
348 container_mem_unlock(c
);
353 int lxc_container_put(struct lxc_container
*c
)
358 if (container_mem_lock(c
))
363 if (c
->numthreads
< 1) {
364 container_mem_unlock(c
);
365 lxc_container_free(c
);
369 container_mem_unlock(c
);
373 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
382 if (container_mem_lock(c
))
388 statret
= stat(c
->configfile
, &statbuf
);
395 container_mem_unlock(c
);
399 #define WRAP_API(rettype, fnname) \
400 static rettype fnname(struct lxc_container *c) \
403 bool reset_config = false; \
405 if (!current_config && c && c->lxc_conf) { \
406 current_config = c->lxc_conf; \
407 reset_config = true; \
410 ret = do_##fnname(c); \
412 current_config = NULL; \
417 #define WRAP_API_1(rettype, fnname, t1) \
418 static rettype fnname(struct lxc_container *c, t1 a1) \
421 bool reset_config = false; \
423 if (!current_config && c && c->lxc_conf) { \
424 current_config = c->lxc_conf; \
425 reset_config = true; \
428 ret = do_##fnname(c, a1); \
430 current_config = NULL; \
435 #define WRAP_API_2(rettype, fnname, t1, t2) \
436 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
439 bool reset_config = false; \
441 if (!current_config && c && c->lxc_conf) { \
442 current_config = c->lxc_conf; \
443 reset_config = true; \
446 ret = do_##fnname(c, a1, a2); \
448 current_config = NULL; \
453 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
454 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
457 bool reset_config = false; \
459 if (!current_config && c && c->lxc_conf) { \
460 current_config = c->lxc_conf; \
461 reset_config = true; \
464 ret = do_##fnname(c, a1, a2, a3); \
466 current_config = NULL; \
471 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
472 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
473 t4 a4, t5 a5, t6 a6) \
476 bool reset_config = false; \
478 if (!current_config && c && c->lxc_conf) { \
479 current_config = c->lxc_conf; \
480 reset_config = true; \
483 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
485 current_config = NULL; \
490 WRAP_API(bool, lxcapi_is_defined
)
492 static const char *do_lxcapi_state(struct lxc_container
*c
)
499 s
= lxc_getstate(c
->name
, c
->config_path
);
500 return lxc_state2str(s
);
503 WRAP_API(const char *, lxcapi_state
)
505 static bool is_stopped(struct lxc_container
*c
)
509 s
= lxc_getstate(c
->name
, c
->config_path
);
510 return (s
== STOPPED
);
513 static bool do_lxcapi_is_running(struct lxc_container
*c
)
518 return !is_stopped(c
);
521 WRAP_API(bool, lxcapi_is_running
)
523 static bool do_lxcapi_freeze(struct lxc_container
*c
)
530 ret
= lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
);
537 WRAP_API(bool, lxcapi_freeze
)
539 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
546 ret
= lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
);
553 WRAP_API(bool, lxcapi_unfreeze
)
555 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
560 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
563 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
565 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
566 int stdoutfd
, int stderrfd
, int escape
)
573 current_config
= c
->lxc_conf
;
574 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
575 current_config
= NULL
;
580 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
587 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
590 NOTICE("The console log is empty");
591 else if (ret
== -EFAULT
)
592 NOTICE("The container does not keep a console log");
593 else if (ret
== -ENOENT
)
594 NOTICE("The container does not keep a console log file");
595 else if (ret
== -EIO
)
596 NOTICE("Failed to write console log to log file");
598 ERROR("Failed to retrieve console log");
604 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
606 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
611 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
614 WRAP_API(pid_t
, lxcapi_init_pid
)
616 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
619 c
->lxc_conf
= lxc_conf_init();
624 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
627 c
->lxc_conf
->name
= c
->name
;
631 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
635 bool need_disklock
= false, ret
= false;
640 fname
= c
->configfile
;
648 /* If we're reading something other than the container's config, we only
649 * need to lock the in-memory container. If loading the container's
650 * config file, take the disk lock.
652 if (strcmp(fname
, c
->configfile
) == 0)
653 need_disklock
= true;
656 lret
= container_disk_lock(c
);
658 lret
= container_mem_lock(c
);
662 ret
= load_config_locked(c
, fname
);
665 container_disk_unlock(c
);
667 container_mem_unlock(c
);
672 WRAP_API_1(bool, lxcapi_load_config
, const char *)
674 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
676 if (!c
|| !c
->lxc_conf
)
679 if (container_mem_lock(c
))
682 c
->daemonize
= state
;
684 container_mem_unlock(c
);
689 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
691 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
693 if (!c
|| !c
->lxc_conf
)
696 if (container_mem_lock(c
))
699 c
->lxc_conf
->close_all_fds
= state
;
701 container_mem_unlock(c
);
706 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
708 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
716 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
720 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
722 static bool am_single_threaded(void)
725 struct dirent
*direntp
;
728 dir
= opendir("/proc/self/task");
732 while ((direntp
= readdir(dir
))) {
733 if (strcmp(direntp
->d_name
, ".") == 0)
736 if (strcmp(direntp
->d_name
, "..") == 0)
748 static void push_arg(char ***argp
, char *arg
, int *nargs
)
753 copy
= must_copy_string(arg
);
756 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
765 static char **split_init_cmd(const char *incmd
)
775 len
= strlen(incmd
) + 1;
777 retlen
= strlcpy(copy
, incmd
, len
);
782 argv
= malloc(sizeof(char *));
786 lxc_iterate_parts(p
, copy
, " ")
787 push_arg(&argv
, p
, &nargs
);
797 static void free_init_cmd(char **argv
)
810 static int lxc_rcv_status(int state_socket
)
816 /* Receive container state. */
817 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
822 TRACE("Caught EINTR; retrying");
829 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
833 /* Close write end of the socket pair. */
834 close(handler
->state_socket_pair
[1]);
835 handler
->state_socket_pair
[1] = -1;
837 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
839 /* Close read end of the socket pair. */
840 close(handler
->state_socket_pair
[0]);
841 handler
->state_socket_pair
[0] = -1;
843 /* The first child is going to fork() again and then exits. So we reap
844 * the first child here.
846 ret
= wait_for_pid(pid
);
848 DEBUG("Failed waiting on first child %d", pid
);
850 DEBUG("First child %d exited", pid
);
853 SYSERROR("Failed to receive the container state");
857 /* If we receive anything else then running we know that the container
860 if (state
!= RUNNING
) {
861 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
862 lxc_state2str(state
));
866 TRACE("Container is in \"RUNNING\" state");
870 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
873 struct lxc_handler
*handler
;
874 struct lxc_conf
*conf
;
875 char *default_args
[] = {
879 char **init_cmd
= NULL
;
880 int keepfds
[3] = {-1, -1, -1};
882 /* container does exist */
886 /* If anything fails before we set error_num, we want an error in there.
890 /* Container has not been setup. */
894 ret
= ongoing_create(c
);
896 ERROR("Failed checking for incomplete container creation");
898 } else if (ret
== 1) {
899 ERROR("Ongoing container creation detected");
901 } else if (ret
== 2) {
902 ERROR("Failed to create container");
903 do_lxcapi_destroy(c
);
907 if (container_mem_lock(c
))
912 /* initialize handler */
913 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
915 container_mem_unlock(c
);
920 if (useinit
&& conf
->execute_cmd
)
921 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
923 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
926 /* ... otherwise use default_args. */
929 ERROR("No valid init detected");
930 lxc_free_handler(handler
);
936 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
937 * here to protect the on disk container? We don't want to exclude
938 * things like lxc_info while the container is running.
947 free_init_cmd(init_cmd
);
948 lxc_free_handler(handler
);
954 /* Set to NULL because we don't want father unlink
955 * the PID file, child will do the free and unlink.
959 /* Wait for container to tell us whether it started
962 started
= wait_on_daemonized_start(handler
, pid
);
964 free_init_cmd(init_cmd
);
965 lxc_free_handler(handler
);
971 /* We don't really care if this doesn't print all the
972 * characters. All that it means is that the proctitle will be
973 * ugly. Similarly, we also don't care if setproctitle() fails.
975 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
977 ret
= setproctitle(title
);
979 INFO("Failed to set process title to %s", title
);
981 INFO("Set process title to %s", title
);
984 /* We fork() a second time to be reparented to init. Like
985 * POSIX's daemon() function we change to "/" and redirect
986 * std{in,out,err} to /dev/null.
990 SYSERROR("Failed to fork first child process");
996 free_init_cmd(init_cmd
);
997 lxc_free_handler(handler
);
1003 /* change to / directory */
1006 SYSERROR("Failed to change to \"/\" directory");
1007 _exit(EXIT_FAILURE
);
1010 keepfds
[0] = handler
->conf
->maincmd_fd
;
1011 keepfds
[1] = handler
->state_socket_pair
[0];
1012 keepfds
[2] = handler
->state_socket_pair
[1];
1013 ret
= lxc_check_inherited(conf
, true, keepfds
,
1014 sizeof(keepfds
) / sizeof(keepfds
[0]));
1016 _exit(EXIT_FAILURE
);
1018 /* redirect std{in,out,err} to /dev/null */
1019 ret
= null_stdfds();
1021 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1022 _exit(EXIT_FAILURE
);
1025 /* become session leader */
1028 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1029 } else if (!am_single_threaded()) {
1030 ERROR("Cannot start non-daemonized container when threaded");
1031 free_init_cmd(init_cmd
);
1032 lxc_free_handler(handler
);
1036 /* We need to write PID file after daemonize, so we always write the
1041 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1043 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1044 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1045 free_init_cmd(init_cmd
);
1046 lxc_free_handler(handler
);
1048 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1051 _exit(EXIT_FAILURE
);
1056 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1058 free_init_cmd(init_cmd
);
1059 lxc_free_handler(handler
);
1061 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1064 _exit(EXIT_FAILURE
);
1070 conf
->reboot
= REBOOT_NONE
;
1072 /* Unshare the mount namespace if requested */
1073 if (conf
->monitor_unshare
) {
1074 ret
= unshare(CLONE_NEWNS
);
1076 SYSERROR("Failed to unshare mount namespace");
1077 lxc_free_handler(handler
);
1082 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1084 SYSERROR("Failed to make / rslave at startup");
1085 lxc_free_handler(handler
);
1092 if (conf
->reboot
== REBOOT_INIT
) {
1093 /* initialize handler */
1094 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1101 keepfds
[0] = handler
->conf
->maincmd_fd
;
1102 keepfds
[1] = handler
->state_socket_pair
[0];
1103 keepfds
[2] = handler
->state_socket_pair
[1];
1104 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1105 sizeof(keepfds
) / sizeof(keepfds
[0]));
1107 lxc_free_handler(handler
);
1113 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1114 c
->daemonize
, &c
->error_num
);
1116 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1117 c
->daemonize
, &c
->error_num
);
1119 if (conf
->reboot
== REBOOT_REQ
) {
1120 INFO("Container requested reboot");
1121 conf
->reboot
= REBOOT_INIT
;
1131 free_init_cmd(init_cmd
);
1133 if (c
->daemonize
&& ret
!= 0)
1134 _exit(EXIT_FAILURE
);
1135 else if (c
->daemonize
)
1136 _exit(EXIT_SUCCESS
);
1144 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1149 current_config
= c
? c
->lxc_conf
: NULL
;
1150 ret
= do_lxcapi_start(c
, useinit
, argv
);
1151 current_config
= NULL
;
1156 /* Note, there MUST be an ending NULL. */
1157 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1160 char **inargs
= NULL
;
1163 /* container exists */
1167 current_config
= c
->lxc_conf
;
1169 va_start(ap
, useinit
);
1170 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1175 /* pass NULL if no arguments were supplied */
1176 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1182 for (arg
= inargs
; *arg
; arg
++)
1187 current_config
= NULL
;
1192 static bool do_lxcapi_stop(struct lxc_container
*c
)
1199 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1204 WRAP_API(bool, lxcapi_stop
)
1206 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1213 mode_t mask
= umask(0002);
1214 ret
= mkdir(path
, 0770);
1219 if (errno
!= EEXIST
)
1226 p
= alloca(len
+ 1);
1227 (void)strlcpy(p
, path
, len
+ 1);
1229 if (!lxc_list_empty(&conf
->id_map
)) {
1230 ret
= chown_mapped_root(p
, conf
);
1238 /* Create the standard expected container dir. */
1239 static bool create_container_dir(struct lxc_container
*c
)
1245 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1250 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1251 if (ret
< 0 || (size_t)ret
>= len
) {
1256 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1262 /* do_storage_create: thin wrapper around storage_create(). Like
1263 * storage_create(), it returns a mounted bdev on success, NULL on error.
1265 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1267 struct bdev_specs
*specs
)
1272 struct lxc_storage
*bdev
;
1274 /* rootfs.path or lxcpath/lxcname/rootfs */
1275 if (c
->lxc_conf
->rootfs
.path
&&
1276 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1277 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1278 len
= strlen(rpath
) + 1;
1280 ret
= snprintf(dest
, len
, "%s", rpath
);
1282 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1283 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1285 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1287 if (ret
< 0 || (size_t)ret
>= len
)
1290 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1292 ERROR("Failed to create \"%s\" storage", type
);
1296 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1297 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1301 /* If we are not root, chown the rootfs dir to root in the target user
1305 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1306 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1308 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1309 suggest_default_idmap();
1318 static char *lxcbasename(char *path
)
1322 p
= path
+ strlen(path
) - 1;
1323 while (*p
!= '/' && p
> path
)
1329 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1330 bool need_null_stdfds
, char *const argv
[])
1340 SYSERROR("Failed to fork task for container creation template");
1344 if (pid
== 0) { /* child */
1346 char *namearg
, *patharg
, *rootfsarg
;
1349 struct lxc_storage
*bdev
= NULL
;
1350 struct lxc_conf
*conf
= c
->lxc_conf
;
1353 if (need_null_stdfds
) {
1354 ret
= null_stdfds();
1356 _exit(EXIT_FAILURE
);
1359 bdev
= storage_init(c
->lxc_conf
);
1361 ERROR("Failed to initialize storage");
1362 _exit(EXIT_FAILURE
);
1367 ret
= unshare(CLONE_NEWNS
);
1369 ERROR("Failed to unshare CLONE_NEWNS");
1370 _exit(EXIT_FAILURE
);
1373 ret
= detect_shared_rootfs();
1375 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1377 SYSERROR("Failed to make \"/\" rslave");
1378 ERROR("Continuing...");
1383 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1385 ERROR("Unprivileged users can only create "
1386 "btrfs and directory-backed containers");
1387 _exit(EXIT_FAILURE
);
1390 if (strcmp(bdev
->type
, "overlay") == 0 ||
1391 strcmp(bdev
->type
, "overlayfs") == 0) {
1392 /* If we create an overlay container we need to
1393 * rsync the contents into
1394 * <container-path>/<container-name>/rootfs.
1395 * However, the overlay mount function will
1397 * <container-path>/<container-name>/delta0
1399 * <container-path>/<container-name>/rootfs
1400 * which means we would rsync the rootfs into
1401 * the delta directory. That doesn't make sense
1402 * since the delta directory only exists to
1403 * record the differences to
1404 * <container-path>/<container-name>/rootfs. So
1405 * let's simply bind-mount here and then rsync
1407 * <container-path>/<container-name>/rootfs.
1411 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1413 ERROR("Failed to get rootfs");
1414 _exit(EXIT_FAILURE
);
1417 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1419 ERROR("Failed to mount rootfs");
1420 _exit(EXIT_FAILURE
);
1423 ret
= bdev
->ops
->mount(bdev
);
1425 ERROR("Failed to mount rootfs");
1426 _exit(EXIT_FAILURE
);
1429 } else { /* TODO come up with a better way here! */
1432 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1433 bdev
->dest
= strdup(src
);
1436 /* Create our new array, pre-pend the template name and base
1440 for (nargs
= 0; argv
[nargs
]; nargs
++)
1443 /* template, path, rootfs and name args */
1446 newargv
= malloc(nargs
* sizeof(*newargv
));
1448 _exit(EXIT_FAILURE
);
1449 newargv
[0] = lxcbasename(tpath
);
1452 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1453 patharg
= malloc(len
);
1455 _exit(EXIT_FAILURE
);
1457 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1458 if (ret
< 0 || ret
>= len
)
1459 _exit(EXIT_FAILURE
);
1460 newargv
[1] = patharg
;
1463 len
= strlen("--name=") + strlen(c
->name
) + 1;
1464 namearg
= malloc(len
);
1466 _exit(EXIT_FAILURE
);
1468 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1469 if (ret
< 0 || ret
>= len
)
1470 _exit(EXIT_FAILURE
);
1471 newargv
[2] = namearg
;
1474 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1475 rootfsarg
= malloc(len
);
1477 _exit(EXIT_FAILURE
);
1479 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1480 if (ret
< 0 || ret
>= len
)
1481 _exit(EXIT_FAILURE
);
1482 newargv
[3] = rootfsarg
;
1484 /* add passed-in args */
1486 for (i
= 4; i
< nargs
; i
++)
1487 newargv
[i
] = argv
[i
- 4];
1489 /* add trailing NULL */
1491 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1493 _exit(EXIT_FAILURE
);
1494 newargv
[nargs
- 1] = NULL
;
1496 /* If we're running the template in a mapped userns, then we
1497 * prepend the template command with: lxc-usernsexec <-m map1>
1498 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1499 * the mapped uid for our geteuid()
1501 if (!lxc_list_empty(&conf
->id_map
)) {
1502 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1504 char txtuid
[20], txtgid
[20];
1505 struct lxc_list
*it
;
1509 n2
= malloc(n2args
* sizeof(*n2
));
1511 _exit(EXIT_FAILURE
);
1514 tpath
= "lxc-usernsexec";
1515 n2
[0] = "lxc-usernsexec";
1517 lxc_list_for_each(it
, &conf
->id_map
) {
1520 n2
= realloc(n2
, n2args
* sizeof(char *));
1522 _exit(EXIT_FAILURE
);
1524 n2
[n2args
- 2] = "-m";
1525 n2
[n2args
- 1] = malloc(200);
1526 if (!n2
[n2args
- 1])
1527 _exit(EXIT_FAILURE
);
1529 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1530 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1531 map
->nsid
, map
->hostid
, map
->range
);
1532 if (ret
< 0 || ret
>= 200)
1533 _exit(EXIT_FAILURE
);
1536 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1537 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1539 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1541 _exit(EXIT_FAILURE
);
1543 if (hostuid_mapped
< 0) {
1544 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1545 n2
[n2args
++] = "-m";
1546 if (hostuid_mapped
< 0) {
1547 ERROR("Failed to find free uid to map");
1548 _exit(EXIT_FAILURE
);
1551 n2
[n2args
++] = malloc(200);
1552 if (!n2
[n2args
- 1]) {
1553 SYSERROR("out of memory");
1554 _exit(EXIT_FAILURE
);
1557 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1558 hostuid_mapped
, geteuid());
1559 if (ret
< 0 || ret
>= 200)
1560 _exit(EXIT_FAILURE
);
1563 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1564 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1566 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1568 _exit(EXIT_FAILURE
);
1570 if (hostgid_mapped
< 0) {
1571 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1572 n2
[n2args
++] = "-m";
1573 if (hostgid_mapped
< 0) {
1574 ERROR("Failed to find free gid to map");
1575 _exit(EXIT_FAILURE
);
1578 n2
[n2args
++] = malloc(200);
1579 if (!n2
[n2args
- 1]) {
1580 SYSERROR("out of memory");
1581 _exit(EXIT_FAILURE
);
1584 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1585 hostgid_mapped
, getegid());
1586 if (ret
< 0 || ret
>= 200)
1587 _exit(EXIT_FAILURE
);
1590 n2
[n2args
++] = "--";
1592 for (i
= 0; i
< nargs
; i
++)
1593 n2
[i
+ n2args
] = newargv
[i
];
1596 /* Finally add "--mapped-uid $uid" to tell template what
1597 * to chown cached images to.
1600 n2
= realloc(n2
, n2args
* sizeof(char *));
1602 _exit(EXIT_FAILURE
);
1604 /* note n2[n2args-1] is NULL */
1605 n2
[n2args
- 5] = "--mapped-uid";
1607 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1608 if (ret
< 0 || ret
>= 20) {
1611 _exit(EXIT_FAILURE
);
1614 n2
[n2args
- 4] = txtuid
;
1615 n2
[n2args
- 3] = "--mapped-gid";
1617 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1618 if (ret
< 0 || ret
>= 20) {
1621 _exit(EXIT_FAILURE
);
1624 n2
[n2args
- 2] = txtgid
;
1625 n2
[n2args
- 1] = NULL
;
1630 execvp(tpath
, newargv
);
1631 SYSERROR("Failed to execute template %s", tpath
);
1632 _exit(EXIT_FAILURE
);
1635 ret
= wait_for_pid(pid
);
1637 ERROR("Failed to create container from template");
1644 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1653 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1657 f
= fopen(path
, "r");
1661 ret
= fseek(f
, 0, SEEK_END
);
1670 ret
= fseek(f
, 0, SEEK_SET
);
1674 ret
= fseek(f
, 0, SEEK_SET
);
1679 contents
= malloc(flen
+ 1);
1683 len
= fread(contents
, 1, flen
, f
);
1685 goto out_free_contents
;
1687 contents
[flen
] = '\0';
1692 goto out_free_contents
;
1695 tpath
= get_template_path(t
);
1697 ERROR("Invalid template \"%s\" specified", t
);
1698 goto out_free_contents
;
1701 ret
= sha1sum_file(tpath
, md_value
);
1703 ERROR("Failed to get sha1sum of %s", tpath
);
1705 goto out_free_contents
;
1710 f
= fopen(path
, "w");
1712 SYSERROR("Reopening config for writing");
1717 fprintf(f
, "# Template used to create this container: %s\n", t
);
1719 fprintf(f
, "# Parameters passed to the template:");
1721 fprintf(f
, " %s", *argv
);
1728 fprintf(f
, "# Template script checksum (SHA-1): ");
1729 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1730 fprintf(f
, "%02x", md_value
[i
]);
1733 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1734 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1735 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1736 fprintf(f
, "# (Be aware this has security implications)\n\n");
1737 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1738 SYSERROR("Writing original contents");
1758 SYSERROR("Error prepending header");
1765 static void lxcapi_clear_config(struct lxc_container
*c
)
1767 if (!c
|| !c
->lxc_conf
)
1770 lxc_conf_free(c
->lxc_conf
);
1774 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1778 * create a container with the given parameters.
1779 * @c: container to be created. It has the lxcpath, name, and a starting
1780 * configuration already set
1781 * @t: the template to execute to instantiate the root filesystem and
1782 * adjust the configuration.
1783 * @bdevtype: backing store type to use. If NULL, dir will be used.
1784 * @specs: additional parameters for the backing store, i.e. LVM vg to
1787 * @argv: the arguments to pass to the template, terminated by NULL. If no
1788 * arguments, you can just pass NULL.
1790 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1791 const char *bdevtype
, struct bdev_specs
*specs
,
1792 int flags
, char *const argv
[])
1804 tpath
= get_template_path(t
);
1806 ERROR("Unknown template \"%s\"", t
);
1811 /* If a template is passed in, and the rootfs already is defined in the
1812 * container config and exists, then the caller is trying to create an
1813 * existing container. Return an error, but do NOT delete the container.
1815 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1816 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1817 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1823 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1824 ERROR("Error loading default configuration file %s",
1825 lxc_global_config_value("lxc.default_config"));
1830 if (!create_container_dir(c
))
1833 /* If both template and rootfs.path are set, template is setup as
1834 * rootfs.path. The container is already created if we have a config and
1835 * rootfs.path is accessible
1837 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1838 /* No template passed in and rootfs does not exist. */
1839 if (!c
->save_config(c
, NULL
)) {
1840 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1847 /* Rootfs passed into configuration, but does not exist. */
1848 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1851 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1852 /* Rootfs already existed, user just wanted to save the loaded
1855 if (!c
->save_config(c
, NULL
))
1856 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1862 /* Mark that this container is being created */
1863 partial_fd
= create_partial(c
);
1867 /* No need to get disk lock bc we have the partial lock. */
1871 /* Create the storage.
1872 * Note we can't do this in the same task as we use to execute the
1873 * template because of the way zfs works.
1874 * After you 'zfs create', zfs mounts the fs only in the initial
1879 SYSERROR("Failed to fork task for container creation template");
1883 if (pid
== 0) { /* child */
1884 struct lxc_storage
*bdev
= NULL
;
1886 bdev
= do_storage_create(c
, bdevtype
, specs
);
1888 ERROR("Failed to create %s storage for %s",
1889 bdevtype
? bdevtype
: "(none)", c
->name
);
1890 _exit(EXIT_FAILURE
);
1893 /* Save config file again to store the new rootfs location. */
1894 if (!do_lxcapi_save_config(c
, NULL
)) {
1895 ERROR("Failed to save initial config for %s", c
->name
);
1896 /* Parent task won't see the storage driver in the
1897 * config so we delete it.
1899 bdev
->ops
->umount(bdev
);
1900 bdev
->ops
->destroy(bdev
);
1901 _exit(EXIT_FAILURE
);
1904 _exit(EXIT_SUCCESS
);
1907 if (wait_for_pid(pid
) != 0)
1910 /* Reload config to get the rootfs. */
1911 lxc_conf_free(c
->lxc_conf
);
1914 if (!load_config_locked(c
, c
->configfile
))
1917 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1920 /* Now clear out the lxc_conf we have, reload from the created
1923 do_lxcapi_clear_config(c
);
1926 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1927 ERROR("Failed to prepend header to config file");
1932 ret
= load_config_locked(c
, c
->configfile
);
1936 if (partial_fd
>= 0)
1937 remove_partial(c
, partial_fd
);
1941 container_destroy(c
, NULL
);
1948 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1949 const char *bdevtype
, struct bdev_specs
*specs
,
1950 int flags
, char *const argv
[])
1954 current_config
= c
? c
->lxc_conf
: NULL
;
1956 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1957 current_config
= NULL
;
1961 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1965 int rebootsignal
= SIGINT
;
1970 if (!do_lxcapi_is_running(c
))
1973 pid
= do_lxcapi_init_pid(c
);
1977 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1978 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1980 ret
= kill(pid
, rebootsignal
);
1982 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
1989 WRAP_API(bool, lxcapi_reboot
)
1991 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1995 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1996 lxc_state_t states
[MAX_STATE
] = {0};
2001 if (!do_lxcapi_is_running(c
))
2004 pid
= do_lxcapi_init_pid(c
);
2008 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2009 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2011 /* Add a new state client before sending the shutdown signal so that we
2012 * don't miss a state.
2015 states
[RUNNING
] = 2;
2016 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2021 if (state_client_fd
< 0)
2027 if (ret
< MAX_STATE
)
2031 /* Send reboot signal to container. */
2032 killret
= kill(pid
, rebootsignal
);
2034 if (state_client_fd
>= 0)
2035 close(state_client_fd
);
2037 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2040 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2045 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2046 close(state_client_fd
);
2050 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2057 WRAP_API_1(bool, lxcapi_reboot2
, int)
2059 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2063 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2064 lxc_state_t states
[MAX_STATE
] = {0};
2069 if (!do_lxcapi_is_running(c
))
2072 pid
= do_lxcapi_init_pid(c
);
2076 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2077 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2078 haltsignal
= c
->lxc_conf
->haltsignal
;
2079 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2080 haltsignal
= (SIGRTMIN
+ 3);
2082 /* Add a new state client before sending the shutdown signal so that we
2083 * don't miss a state.
2086 states
[STOPPED
] = 1;
2087 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2092 if (state_client_fd
< 0)
2098 if (ret
< MAX_STATE
)
2102 /* Send shutdown signal to container. */
2103 killret
= kill(pid
, haltsignal
);
2105 if (state_client_fd
>= 0)
2106 close(state_client_fd
);
2108 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2111 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2116 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2117 close(state_client_fd
);
2121 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2128 WRAP_API_1(bool, lxcapi_shutdown
, int)
2130 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2131 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2140 current_config
= c
->lxc_conf
;
2143 * since we're going to wait for create to finish, I don't think we
2144 * need to get a copy of the arguments.
2146 va_start(ap
, flags
);
2147 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2150 ERROR("Failed to allocate memory");
2154 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2158 current_config
= NULL
;
2162 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2164 if (!strcmp(key
, "lxc.cgroup"))
2165 return clear_unexp_config_line(conf
, key
, true);
2167 if (!strcmp(key
, "lxc.network"))
2168 return clear_unexp_config_line(conf
, key
, true);
2170 if (!strcmp(key
, "lxc.net"))
2171 return clear_unexp_config_line(conf
, key
, true);
2173 /* Clear a network with a specific index. */
2174 if (!strncmp(key
, "lxc.net.", 8)) {
2179 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2181 return clear_unexp_config_line(conf
, key
, true);
2184 if (!strcmp(key
, "lxc.hook"))
2185 return clear_unexp_config_line(conf
, key
, true);
2187 return clear_unexp_config_line(conf
, key
, false);
2190 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2194 struct lxc_config_t
*config
;
2196 if (!c
|| !c
->lxc_conf
)
2199 if (container_mem_lock(c
))
2202 config
= lxc_get_config(key
);
2203 /* Verify that the config key exists and that it has a callback
2206 if (config
&& config
->clr
)
2207 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2210 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2212 container_mem_unlock(c
);
2216 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2218 static inline bool enter_net_ns(struct lxc_container
*c
)
2220 pid_t pid
= do_lxcapi_init_pid(c
);
2222 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2223 (access("/proc/self/ns/user", F_OK
) == 0))
2224 if (!switch_to_ns(pid
, "user"))
2227 return switch_to_ns(pid
, "net");
2230 /* Used by qsort and bsearch functions for comparing names. */
2231 static inline int string_cmp(char **first
, char **second
)
2233 return strcmp(*first
, *second
);
2236 /* Used by qsort and bsearch functions for comparing container names. */
2237 static inline int container_cmp(struct lxc_container
**first
,
2238 struct lxc_container
**second
)
2240 return strcmp((*first
)->name
, (*second
)->name
);
2243 static bool add_to_array(char ***names
, char *cname
, int pos
)
2245 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2247 ERROR("Out of memory");
2252 newnames
[pos
] = strdup(cname
);
2256 /* Sort the arrray as we will use binary search on it. */
2257 qsort(newnames
, pos
+ 1, sizeof(char *),
2258 (int (*)(const void *, const void *))string_cmp
);
2263 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2266 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2268 ERROR("Out of memory");
2275 /* Sort the arrray as we will use binary search on it. */
2277 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2278 (int (*)(const void *, const void *))container_cmp
);
2283 static char** get_from_array(char ***names
, char *cname
, int size
)
2285 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2288 static bool array_contains(char ***names
, char *cname
, int size
)
2290 if(get_from_array(names
, cname
, size
) != NULL
)
2296 static bool remove_from_array(char ***names
, char *cname
, int size
)
2298 char **result
= get_from_array(names
, cname
, size
);
2299 if (result
!= NULL
) {
2307 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2310 int i
, count
= 0, pipefd
[2];
2311 char **interfaces
= NULL
;
2312 char interface
[IFNAMSIZ
];
2314 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2319 SYSERROR("Failed to fork task to get interfaces information");
2325 if (pid
== 0) { /* child */
2326 int ret
= 1, nbytes
;
2327 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2329 /* close the read-end of the pipe */
2332 if (!enter_net_ns(c
)) {
2333 SYSERROR("Failed to enter network namespace");
2337 /* Grab the list of interfaces */
2338 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2339 SYSERROR("Failed to get interfaces list");
2343 /* Iterate through the interfaces */
2344 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2345 tempIfAddr
= tempIfAddr
->ifa_next
) {
2346 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2357 netns_freeifaddrs(interfaceArray
);
2359 /* close the write-end of the pipe, thus sending EOF to the reader */
2364 /* close the write-end of the pipe */
2367 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2368 interface
[IFNAMSIZ
- 1] = '\0';
2370 if (array_contains(&interfaces
, interface
, count
))
2373 if (!add_to_array(&interfaces
, interface
, count
))
2374 ERROR("Failed to add \"%s\" to array", interface
);
2379 if (wait_for_pid(pid
) != 0) {
2380 for (i
= 0; i
< count
; i
++)
2381 free(interfaces
[i
]);
2387 /* close the read-end of the pipe */
2390 /* Append NULL to the array */
2392 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2397 WRAP_API(char **, lxcapi_get_interfaces
)
2399 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2400 const char *family
, int scope
)
2405 char address
[INET6_ADDRSTRLEN
];
2407 char **addresses
= NULL
;
2409 ret
= pipe2(pipefd
, O_CLOEXEC
);
2411 SYSERROR("Failed to create pipe");
2417 SYSERROR("Failed to create new process");
2425 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2427 char *address
= NULL
;
2428 void *tempAddrPtr
= NULL
;
2429 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2431 /* close the read-end of the pipe */
2434 if (!enter_net_ns(c
)) {
2435 SYSERROR("Failed to attach to network namespace");
2439 /* Grab the list of interfaces */
2440 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2441 SYSERROR("Failed to get interfaces list");
2445 /* Iterate through the interfaces */
2446 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2447 tempIfAddr
= tempIfAddr
->ifa_next
) {
2448 if (tempIfAddr
->ifa_addr
== NULL
)
2451 #pragma GCC diagnostic push
2452 #pragma GCC diagnostic ignored "-Wcast-align"
2454 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2455 if (family
&& strcmp(family
, "inet"))
2458 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2460 if (family
&& strcmp(family
, "inet6"))
2463 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2466 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2469 #pragma GCC diagnostic pop
2471 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2473 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2476 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2477 tempAddrPtr
, addressOutputBuffer
,
2478 sizeof(addressOutputBuffer
));
2482 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2483 if (nbytes
!= INET6_ADDRSTRLEN
) {
2484 SYSERROR("Failed to send ipv6 address \"%s\"",
2496 netns_freeifaddrs(interfaceArray
);
2498 /* close the write-end of the pipe, thus sending EOF to the reader */
2503 /* close the write-end of the pipe */
2506 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2507 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2509 if (!add_to_array(&addresses
, address
, count
))
2510 ERROR("PARENT: add_to_array failed");
2515 if (wait_for_pid(pid
) != 0) {
2516 for (i
= 0; i
< count
; i
++)
2523 /* close the read-end of the pipe */
2526 /* Append NULL to the array */
2528 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2533 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2535 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2538 struct lxc_config_t
*config
;
2540 if (!c
|| !c
->lxc_conf
)
2543 if (container_mem_lock(c
))
2546 config
= lxc_get_config(key
);
2547 /* Verify that the config key exists and that it has a callback
2550 if (config
&& config
->get
)
2551 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2553 container_mem_unlock(c
);
2557 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2559 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2563 if (!c
|| !c
->lxc_conf
)
2566 if (container_mem_lock(c
))
2569 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2570 container_mem_unlock(c
);
2574 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2576 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2580 /* List all config items. */
2582 return lxc_list_config_items(retv
, inlen
);
2584 if (!c
|| !c
->lxc_conf
)
2587 if (container_mem_lock(c
))
2590 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2591 * This is an intelligent result to show which keys are valid given the
2592 * type of nic it is.
2594 if (strncmp(key
, "lxc.net.", 8) == 0)
2595 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2597 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2599 container_mem_unlock(c
);
2603 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2605 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2608 bool ret
= false, need_disklock
= false;
2611 alt_file
= c
->configfile
;
2616 /* If we haven't yet loaded a config, load the stock config. */
2618 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2619 ERROR("Error loading default configuration file %s "
2621 lxc_global_config_value("lxc.default_config"),
2627 if (!create_container_dir(c
))
2630 /* If we're writing to the container's config file, take the disk lock.
2631 * Otherwise just take the memlock to protect the struct lxc_container
2632 * while we're traversing it.
2634 if (strcmp(c
->configfile
, alt_file
) == 0)
2635 need_disklock
= true;
2638 lret
= container_disk_lock(c
);
2640 lret
= container_mem_lock(c
);
2644 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2645 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2649 lret
= write_config(fd
, c
->lxc_conf
);
2658 container_disk_unlock(c
);
2660 container_mem_unlock(c
);
2665 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2668 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2674 char path
[MAXPATHLEN
];
2675 char newpath
[MAXPATHLEN
];
2676 int fd
, ret
, n
= 0, v
= 0;
2678 size_t len
= 0, bytes
= 0;
2680 if (container_disk_lock(c0
))
2683 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2684 if (ret
< 0 || ret
> MAXPATHLEN
)
2687 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2688 if (ret
< 0 || ret
> MAXPATHLEN
)
2691 /* If we find an lxc-snapshot file using the old format only listing the
2692 * number of snapshots we will keep using it. */
2693 f1
= fopen(path
, "r");
2695 n
= fscanf(f1
, "%d", &v
);
2697 if (n
== 1 && v
== 0) {
2700 SYSERROR("Failed to remove \"%s\"", path
);
2708 f1
= fopen(path
, "w");
2712 if (fprintf(f1
, "%d\n", v
) < 0) {
2713 ERROR("Error writing new snapshots value");
2720 SYSERROR("Error writing to or closing snapshots file");
2724 /* Here we know that we have or can use an lxc-snapshot file
2725 * using the new format. */
2727 f1
= fopen(path
, "a");
2731 if (fprintf(f1
, "%s", newpath
) < 0) {
2732 ERROR("Error writing new snapshots entry");
2735 SYSERROR("Error writing to or closing snapshots file");
2741 SYSERROR("Error writing to or closing snapshots file");
2745 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2748 if (fstat(fd
, &fbuf
) < 0) {
2753 if (fbuf
.st_size
!= 0) {
2754 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2755 if (buf
== MAP_FAILED
) {
2756 SYSERROR("Failed to create mapping %s", path
);
2761 len
= strlen(newpath
);
2762 while ((del
= strstr((char *)buf
, newpath
))) {
2763 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2767 lxc_strmunmap(buf
, fbuf
.st_size
);
2768 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2769 SYSERROR("Failed to truncate file %s", path
);
2778 /* If the lxc-snapshot file is empty, remove it. */
2779 if (stat(path
, &fbuf
) < 0)
2782 if (!fbuf
.st_size
) {
2785 SYSERROR("Failed to remove \"%s\"", path
);
2792 container_disk_unlock(c0
);
2796 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2798 struct lxc_container
*p
;
2799 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2800 size_t pathlen
= 0, namelen
= 0;
2804 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2805 c
->config_path
, c
->name
);
2806 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2807 ERROR("Path name too long");
2811 f
= fopen(path
, "r");
2815 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2816 if (getline(&lxcname
, &namelen
, f
) == -1) {
2817 ERROR("badly formatted file %s", path
);
2821 remove_trailing_newlines(lxcpath
);
2822 remove_trailing_newlines(lxcname
);
2824 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2825 ERROR("Unable to find dependent container %s:%s",
2830 if (!mod_rdep(p
, c
, inc
))
2831 ERROR("Failed to update snapshots file for %s:%s",
2834 lxc_container_put(p
);
2843 static bool has_fs_snapshots(struct lxc_container
*c
)
2846 char path
[MAXPATHLEN
];
2851 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2853 if (ret
< 0 || ret
> MAXPATHLEN
)
2856 /* If the file doesn't exist there are no snapshots. */
2857 if (stat(path
, &fbuf
) < 0)
2862 f
= fopen(path
, "r");
2866 ret
= fscanf(f
, "%d", &v
);
2868 /* TODO: Figure out what to do with the return value of fscanf. */
2870 INFO("Container uses new lxc-snapshots format %s", path
);
2879 static bool has_snapshots(struct lxc_container
*c
)
2881 char path
[MAXPATHLEN
];
2882 struct dirent
*direntp
;
2886 if (!get_snappath_dir(c
, path
))
2889 dir
= opendir(path
);
2893 while ((direntp
= readdir(dir
))) {
2894 if (!strcmp(direntp
->d_name
, "."))
2897 if (!strcmp(direntp
->d_name
, ".."))
2907 static bool do_destroy_container(struct lxc_conf
*conf
) {
2910 if (am_guest_unpriv()) {
2911 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2912 "storage_destroy_wrapper");
2919 return storage_destroy(conf
);
2922 static int lxc_rmdir_onedev_wrapper(void *data
)
2924 char *arg
= (char *) data
;
2925 return lxc_rmdir_onedev(arg
, "snaps");
2928 static int lxc_unlink_exec_wrapper(void *data
)
2934 static bool container_destroy(struct lxc_container
*c
,
2935 struct lxc_storage
*storage
)
2939 struct lxc_conf
*conf
;
2944 if (!c
|| !do_lxcapi_is_defined(c
))
2948 if (container_disk_lock(c
))
2951 if (!is_stopped(c
)) {
2952 /* We should queue some sort of error - in c->error_string? */
2953 ERROR("container %s is not stopped", c
->name
);
2957 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2958 /* Start of environment variable setup for hooks */
2959 if (setenv("LXC_NAME", c
->name
, 1))
2960 SYSERROR("Failed to set environment variable for container name");
2962 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2963 SYSERROR("Failed to set environment variable for config path");
2965 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2966 SYSERROR("Failed to set environment variable for rootfs mount");
2968 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2969 SYSERROR("Failed to set environment variable for rootfs mount");
2971 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2972 SYSERROR("Failed to set environment variable for console path");
2974 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2975 SYSERROR("Failed to set environment variable for console log");
2976 /* End of environment variable setup for hooks */
2978 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2979 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2984 if (current_config
&& conf
== current_config
) {
2985 current_config
= NULL
;
2987 if (conf
->logfd
!= -1) {
2993 /* LXC is not managing the storage of the container. */
2994 if (conf
&& !conf
->rootfs
.managed
)
2997 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2998 if (!do_destroy_container(conf
)) {
2999 ERROR("Error destroying rootfs for %s", c
->name
);
3002 INFO("Destroyed rootfs for %s", c
->name
);
3005 mod_all_rdeps(c
, false);
3007 p1
= do_lxcapi_get_config_path(c
);
3016 * strlen("config") = 6
3020 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3023 ERROR("Failed to allocate memory");
3027 /* For an overlay container the rootfs is considered immutable and
3028 * cannot be removed when restoring from a snapshot.
3030 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3031 !strcmp(storage
->type
, "overlayfs")) &&
3032 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3033 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3034 if (ret
< 0 || (size_t)ret
>= len
)
3037 if (am_guest_unpriv())
3038 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3039 "lxc_unlink_exec_wrapper");
3043 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3047 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3053 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3054 if (ret
< 0 || (size_t)ret
>= len
)
3057 if (am_guest_unpriv())
3058 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3059 "lxc_rmdir_onedev_wrapper");
3061 ret
= lxc_rmdir_onedev(path
, "snaps");
3063 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3067 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3076 container_disk_unlock(c
);
3080 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3082 if (!c
|| !lxcapi_is_defined(c
))
3085 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3086 if (has_snapshots(c
)) {
3087 ERROR("Container %s has snapshots; not removing", c
->name
);
3091 if (has_fs_snapshots(c
)) {
3092 ERROR("container %s has snapshots on its rootfs", c
->name
);
3097 return container_destroy(c
, NULL
);
3100 WRAP_API(bool, lxcapi_destroy
)
3102 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3104 if (!c
|| !lxcapi_is_defined(c
))
3107 if (!lxcapi_snapshot_destroy_all(c
)) {
3108 ERROR("Error deleting all snapshots");
3112 return lxcapi_destroy(c
);
3115 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3117 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3121 struct lxc_config_t
*config
;
3124 config
= lxc_get_config(key
);
3128 ret
= config
->set(key
, v
, conf
, NULL
);
3132 if (lxc_config_value_empty(v
))
3133 do_clear_unexp_config_line(conf
, key
);
3135 bret
= do_append_unexp_config_line(conf
, key
, v
);
3142 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3148 c
->lxc_conf
= lxc_conf_init();
3153 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3160 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3167 if (container_mem_lock(c
))
3170 b
= do_set_config_item_locked(c
, key
, v
);
3172 container_mem_unlock(c
);
3176 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3178 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3180 if (!c
|| !c
->configfile
)
3183 return strdup(c
->configfile
);
3186 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3188 if (!c
|| !c
->config_path
)
3191 return (const char *)(c
->config_path
);
3196 * Just recalculate the c->configfile based on the
3197 * c->config_path, which must be set.
3198 * The lxc_container must be locked or not yet public.
3200 static bool set_config_filename(struct lxc_container
*c
)
3205 if (!c
->config_path
)
3208 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3209 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3210 newpath
= malloc(len
);
3214 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3215 if (ret
< 0 || ret
>= len
) {
3216 fprintf(stderr
, "Error printing out config file name\n");
3221 free(c
->configfile
);
3222 c
->configfile
= newpath
;
3227 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3231 char *oldpath
= NULL
;
3236 if (container_mem_lock(c
))
3241 ERROR("Out of memory setting new lxc path");
3247 oldpath
= c
->config_path
;
3250 /* Since we've changed the config path, we have to change the
3251 * config file name too */
3252 if (!set_config_filename(c
)) {
3253 ERROR("Out of memory setting new config filename");
3255 free(c
->config_path
);
3256 c
->config_path
= oldpath
;
3262 container_mem_unlock(c
);
3266 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3268 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3271 struct cgroup_ops
*cgroup_ops
;
3279 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3283 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3285 cgroup_exit(cgroup_ops
);
3290 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3292 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3295 struct cgroup_ops
*cgroup_ops
;
3303 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3307 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3310 cgroup_exit(cgroup_ops
);
3315 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3317 const char *lxc_get_global_config_item(const char *key
)
3319 return lxc_global_config_value(key
);
3322 const char *lxc_get_version(void)
3327 static int copy_file(const char *old
, const char *new)
3334 if (file_exists(new)) {
3335 ERROR("copy destination %s exists", new);
3339 ret
= stat(old
, &sbuf
);
3341 INFO("Error stat'ing %s", old
);
3345 in
= open(old
, O_RDONLY
);
3347 SYSERROR("Error opening original file %s", old
);
3351 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3353 SYSERROR("Error opening new file %s", new);
3359 len
= lxc_read_nointr(in
, buf
, 8096);
3361 SYSERROR("Error reading old file %s", old
);
3368 ret
= lxc_write_nointr(out
, buf
, len
);
3369 if (ret
< len
) { /* should we retry? */
3370 SYSERROR("Error: write to new file %s was interrupted", new);
3378 /* We set mode, but not owner/group. */
3379 ret
= chmod(new, sbuf
.st_mode
);
3381 SYSERROR("Error setting mode on %s", new);
3393 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3396 struct lxc_list
*it
;
3399 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3400 cpath
= alloca(len
);
3401 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3402 if (ret
< 0 || ret
>= len
)
3405 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3406 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3407 char *hookname
= it
->elem
;
3408 char *fname
= strrchr(hookname
, '/');
3409 char tmppath
[MAXPATHLEN
];
3410 if (!fname
) /* relative path - we don't support, but maybe we should */
3413 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3414 /* this hook is public - ignore */
3418 /* copy the script, and change the entry in confile */
3419 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3420 c
->config_path
, c
->name
, fname
+1);
3421 if (ret
< 0 || ret
>= MAXPATHLEN
)
3424 ret
= copy_file(it
->elem
, tmppath
);
3430 it
->elem
= strdup(tmppath
);
3432 ERROR("out of memory copying hook path");
3438 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3439 c
->config_path
, oldc
->name
, c
->name
)) {
3440 ERROR("Error saving new hooks in clone");
3444 do_lxcapi_save_config(c
, NULL
);
3449 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3451 char newpath
[MAXPATHLEN
];
3452 char *oldpath
= oldc
->lxc_conf
->fstab
;
3458 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3460 char *p
= strrchr(oldpath
, '/');
3464 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3465 c
->config_path
, c
->name
, p
);
3466 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3467 ERROR("error printing new path for %s", oldpath
);
3471 if (file_exists(newpath
)) {
3472 ERROR("error: fstab file %s exists", newpath
);
3476 if (copy_file(oldpath
, newpath
) < 0) {
3477 ERROR("error: copying %s to %s", oldpath
, newpath
);
3481 free(c
->lxc_conf
->fstab
);
3483 c
->lxc_conf
->fstab
= strdup(newpath
);
3484 if (!c
->lxc_conf
->fstab
) {
3485 ERROR("error: allocating pathname");
3489 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3490 ERROR("error saving new lxctab");
3497 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3499 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3502 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3504 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3505 WARN("Error copying reverse dependencies");
3509 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3511 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3512 WARN("Error copying reverse dependencies");
3516 if (copy_file(path0
, path1
) < 0) {
3517 INFO("Error copying reverse dependencies");
3522 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3525 char path
[MAXPATHLEN
];
3529 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3531 if (ret
< 0 || ret
>= MAXPATHLEN
)
3534 f
= fopen(path
, "a");
3540 /* If anything goes wrong, just return an error. */
3541 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3551 * If the fs natively supports snapshot clones with no penalty,
3552 * then default to those even if not requested.
3553 * Currently we only do this for btrfs.
3555 bool should_default_to_snapshot(struct lxc_container
*c0
,
3556 struct lxc_container
*c1
)
3559 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3560 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3561 char *p0
= alloca(l0
+ 1);
3562 char *p1
= alloca(l1
+ 1);
3563 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3565 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3566 if (ret
< 0 || ret
>= l0
)
3569 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3570 if (ret
< 0 || ret
>= l1
)
3573 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3576 if (is_btrfs_subvol(rootfs
) <= 0)
3579 return btrfs_same_fs(p0
, p1
) == 0;
3582 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3583 const char *newtype
, int flags
, const char *bdevdata
,
3586 struct lxc_storage
*bdev
;
3589 if (should_default_to_snapshot(c0
, c
))
3590 flags
|= LXC_CLONE_SNAPSHOT
;
3592 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3593 bdevdata
, newsize
, &need_rdep
);
3595 ERROR("Error copying storage.");
3599 /* Set new rootfs. */
3600 free(c
->lxc_conf
->rootfs
.path
);
3601 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3604 if (!c
->lxc_conf
->rootfs
.path
) {
3605 ERROR("Out of memory while setting storage path.");
3609 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3610 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3611 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3612 c
->lxc_conf
->rootfs
.path
)) {
3613 ERROR("Error saving new rootfs to cloned config.");
3617 if (flags
& LXC_CLONE_SNAPSHOT
)
3618 copy_rdepends(c
, c0
);
3621 if (!add_rdepends(c
, c0
))
3622 WARN("Error adding reverse dependency from %s to %s",
3626 mod_all_rdeps(c
, true);
3631 struct clone_update_data
{
3632 struct lxc_container
*c0
;
3633 struct lxc_container
*c1
;
3638 static int clone_update_rootfs(struct clone_update_data
*data
)
3640 struct lxc_container
*c0
= data
->c0
;
3641 struct lxc_container
*c
= data
->c1
;
3642 int flags
= data
->flags
;
3643 char **hookargs
= data
->hookargs
;
3645 char path
[MAXPATHLEN
];
3646 struct lxc_storage
*bdev
;
3648 struct lxc_conf
*conf
= c
->lxc_conf
;
3650 /* update hostname in rootfs */
3651 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3653 if (setgid(0) < 0) {
3654 ERROR("Failed to setgid to 0");
3658 if (setuid(0) < 0) {
3659 ERROR("Failed to setuid to 0");
3663 if (setgroups(0, NULL
) < 0)
3664 WARN("Failed to clear groups");
3666 if (unshare(CLONE_NEWNS
) < 0)
3669 bdev
= storage_init(c
->lxc_conf
);
3673 if (strcmp(bdev
->type
, "dir") != 0) {
3674 if (unshare(CLONE_NEWNS
) < 0) {
3675 ERROR("error unsharing mounts");
3680 if (detect_shared_rootfs()) {
3681 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3682 SYSERROR("Failed to make / rslave");
3683 ERROR("Continuing...");
3687 if (bdev
->ops
->mount(bdev
) < 0) {
3691 } else { /* TODO come up with a better way */
3693 bdev
->dest
= strdup(bdev
->src
);
3696 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3697 /* Start of environment variable setup for hooks */
3698 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3699 SYSERROR("failed to set environment variable for source container name");
3701 if (setenv("LXC_NAME", c
->name
, 1))
3702 SYSERROR("failed to set environment variable for container name");
3704 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3705 SYSERROR("failed to set environment variable for config path");
3707 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3708 SYSERROR("failed to set environment variable for rootfs mount");
3710 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3711 SYSERROR("failed to set environment variable for rootfs mount");
3713 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3714 ERROR("Error executing clone hook for %s", c
->name
);
3720 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3721 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3724 if (ret
< 0 || ret
>= MAXPATHLEN
)
3727 if (!file_exists(path
))
3730 if (!(fout
= fopen(path
, "w"))) {
3731 SYSERROR("unable to open %s: ignoring", path
);
3735 if (fprintf(fout
, "%s", c
->name
) < 0) {
3740 if (fclose(fout
) < 0)
3749 static int clone_update_rootfs_wrapper(void *data
)
3751 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3752 return clone_update_rootfs(arg
);
3756 * We want to support:
3757 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3758 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3760 -s [ implies overlay]
3763 only rootfs gets converted (copied/snapshotted) on clone.
3766 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3768 char *p
= strrchr(path
, '/');
3775 ret
= do_create_container_dir(path
, conf
);
3781 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3782 const char *lxcpath
, int flags
,
3783 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3786 char newpath
[MAXPATHLEN
];
3788 struct clone_update_data data
;
3789 size_t saved_unexp_len
;
3791 int storage_copied
= 0;
3792 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3793 struct lxc_container
*c2
= NULL
;
3795 if (!c
|| !do_lxcapi_is_defined(c
))
3798 if (container_mem_lock(c
))
3801 if (!is_stopped(c
)) {
3802 ERROR("error: Original container (%s) is running", c
->name
);
3806 /* Make sure the container doesn't yet exist. */
3811 lxcpath
= do_lxcapi_get_config_path(c
);
3813 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3814 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3815 SYSERROR("clone: failed making config pathname");
3819 if (file_exists(newpath
)) {
3820 ERROR("error: clone: %s exists", newpath
);
3824 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3825 if (ret
< 0 && errno
!= EEXIST
) {
3826 ERROR("Error creating container dir for %s", newpath
);
3830 /* Copy the configuration. Tweak it as needed. */
3831 if (c
->lxc_conf
->rootfs
.path
) {
3832 origroot
= c
->lxc_conf
->rootfs
.path
;
3833 c
->lxc_conf
->rootfs
.path
= NULL
;
3836 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3837 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3839 SYSERROR("Failed to open \"%s\"", newpath
);
3843 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3844 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3845 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3846 if (!c
->lxc_conf
->unexpanded_config
) {
3851 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3852 write_config(fd
, c
->lxc_conf
);
3855 c
->lxc_conf
->rootfs
.path
= origroot
;
3857 free(c
->lxc_conf
->unexpanded_config
);
3858 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3859 saved_unexp_conf
= NULL
;
3860 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3862 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3863 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3864 SYSERROR("clone: failed making rootfs pathname");
3868 ret
= mkdir(newpath
, 0755);
3870 /* For an overlay container the rootfs is considered immutable
3871 * and will not have been removed when restoring from a
3874 if (errno
!= ENOENT
&&
3875 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3876 SYSERROR("Failed to create directory \"%s\"", newpath
);
3881 if (am_guest_unpriv()) {
3882 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3883 ERROR("Error chowning %s to container root", newpath
);
3888 c2
= lxc_container_new(newname
, lxcpath
);
3890 ERROR("clone: failed to create new container (%s %s)", newname
,
3895 /* copy/snapshot rootfs's */
3896 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3900 /* update utsname */
3901 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3902 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3903 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3905 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3906 ERROR("Error setting new hostname");
3912 ret
= copyhooks(c
, c2
);
3914 ERROR("error copying hooks");
3918 if (copy_fstab(c
, c2
) < 0) {
3919 ERROR("error copying fstab");
3923 /* update macaddrs */
3924 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3925 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3926 ERROR("Error updating mac addresses");
3931 /* Update absolute paths for overlay mount directories. */
3932 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3935 /* We've now successfully created c2's storage, so clear it out if we
3940 if (!c2
->save_config(c2
, NULL
))
3943 if ((pid
= fork()) < 0) {
3949 ret
= wait_for_pid(pid
);
3953 container_mem_unlock(c
);
3960 data
.hookargs
= hookargs
;
3962 if (am_guest_unpriv())
3963 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3964 &data
, "clone_update_rootfs_wrapper");
3966 ret
= clone_update_rootfs(&data
);
3968 _exit(EXIT_FAILURE
);
3970 container_mem_unlock(c
);
3971 _exit(EXIT_SUCCESS
);
3974 container_mem_unlock(c
);
3976 if (!storage_copied
)
3977 c2
->lxc_conf
->rootfs
.path
= NULL
;
3980 lxc_container_put(c2
);
3986 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3987 const char *lxcpath
, int flags
,
3988 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3991 struct lxc_container
* ret
;
3993 current_config
= c
? c
->lxc_conf
: NULL
;
3994 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3995 current_config
= NULL
;
4000 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4002 struct lxc_storage
*bdev
;
4003 struct lxc_container
*newc
;
4005 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4008 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4009 ERROR("Renaming a container with snapshots is not supported");
4013 bdev
= storage_init(c
->lxc_conf
);
4015 ERROR("Failed to find original backing store type");
4019 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4022 lxc_container_put(newc
);
4026 if (newc
&& lxcapi_is_defined(newc
))
4027 lxc_container_put(newc
);
4029 if (!container_destroy(c
, NULL
)) {
4030 ERROR("Could not destroy existing container %s", c
->name
);
4037 WRAP_API_1(bool, lxcapi_rename
, const char *)
4039 static int lxcapi_attach(struct lxc_container
*c
, lxc_attach_exec_t exec_function
, void *exec_payload
, lxc_attach_options_t
*options
, pid_t
*attached_process
)
4046 current_config
= c
->lxc_conf
;
4048 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4049 current_config
= NULL
;
4053 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4055 lxc_attach_command_t command
;
4062 command
.program
= (char*)program
;
4063 command
.argv
= (char**)argv
;
4065 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4071 return lxc_wait_for_pid_status(pid
);
4074 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4078 current_config
= c
? c
->lxc_conf
: NULL
;
4079 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4080 current_config
= NULL
;
4085 static int get_next_index(const char *lxcpath
, char *cname
)
4091 fname
= alloca(strlen(lxcpath
) + 20);
4094 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4096 ret
= stat(fname
, &sb
);
4104 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4109 * If the old style snapshot path exists, use it
4110 * /var/lib/lxc -> /var/lib/lxcsnaps
4112 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
4113 if (ret
< 0 || ret
>= MAXPATHLEN
)
4116 if (dir_exists(snappath
)) {
4117 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
4118 if (ret
< 0 || ret
>= MAXPATHLEN
)
4125 * Use the new style path
4126 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4128 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
4129 if (ret
< 0 || ret
>= MAXPATHLEN
)
4135 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4140 struct lxc_container
*c2
;
4141 char snappath
[MAXPATHLEN
], newname
[20];
4145 if (!c
|| !lxcapi_is_defined(c
))
4148 if (!storage_can_backup(c
->lxc_conf
)) {
4149 ERROR("%s's backing store cannot be backed up", c
->name
);
4150 ERROR("Your container must use another backing store type");
4154 if (!get_snappath_dir(c
, snappath
))
4157 i
= get_next_index(snappath
, c
->name
);
4159 if (mkdir_p(snappath
, 0755) < 0) {
4160 ERROR("Failed to create snapshot directory %s", snappath
);
4164 ret
= snprintf(newname
, 20, "snap%d", i
);
4165 if (ret
< 0 || ret
>= 20)
4169 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4170 * created in the original container
4172 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4173 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4174 if (storage_is_dir(c
->lxc_conf
)) {
4175 ERROR("Snapshot of directory-backed container requested");
4176 ERROR("Making a copy-clone. If you do want snapshots, then");
4177 ERROR("please create overlay clone first, snapshot that");
4178 ERROR("and keep the original container pristine");
4179 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4182 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4184 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4188 lxc_container_put(c2
);
4190 /* Now write down the creation time. */
4193 if (!localtime_r(&timer
, &tm_info
)) {
4194 ERROR("Failed to get localtime");
4198 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4200 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4201 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4202 f
= fopen(dfnam
, "w");
4204 ERROR("Failed to open %s", dfnam
);
4208 if (fprintf(f
, "%s", buffer
) < 0) {
4209 SYSERROR("Writing timestamp");
4216 SYSERROR("Writing timestamp");
4221 /* $p / $name / comment \0 */
4222 int len
= strlen(snappath
) + strlen(newname
) + 10;
4223 char *path
= alloca(len
);
4225 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4226 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4232 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4234 static void lxcsnap_free(struct lxc_snapshot
*s
)
4237 free(s
->comment_pathname
);
4242 static char *get_snapcomment_path(char* snappath
, char *name
)
4244 /* $snappath/$name/comment */
4245 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4246 char *s
= malloc(len
);
4249 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4250 if (ret
< 0 || ret
>= len
) {
4259 static char *get_timestamp(char* snappath
, char *name
)
4261 char path
[MAXPATHLEN
], *s
= NULL
;
4265 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4266 if (ret
< 0 || ret
>= MAXPATHLEN
)
4269 fin
= fopen(path
, "r");
4273 (void) fseek(fin
, 0, SEEK_END
);
4275 (void) fseek(fin
, 0, SEEK_SET
);
4280 if (fread(s
, 1, len
, fin
) != len
) {
4281 SYSERROR("reading timestamp");
4292 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4294 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4296 struct dirent
*direntp
;
4297 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4300 if (!c
|| !lxcapi_is_defined(c
))
4303 if (!get_snappath_dir(c
, snappath
)) {
4304 ERROR("path name too long");
4308 dir
= opendir(snappath
);
4310 INFO("Failed to open %s - assuming no snapshots", snappath
);
4314 while ((direntp
= readdir(dir
))) {
4315 if (!strcmp(direntp
->d_name
, "."))
4318 if (!strcmp(direntp
->d_name
, ".."))
4321 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4322 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4323 ERROR("pathname too long");
4327 if (!file_exists(path2
))
4330 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4332 SYSERROR("Out of memory");
4337 snaps
[count
].free
= lxcsnap_free
;
4338 snaps
[count
].name
= strdup(direntp
->d_name
);
4339 if (!snaps
[count
].name
)
4342 snaps
[count
].lxcpath
= strdup(snappath
);
4343 if (!snaps
[count
].lxcpath
) {
4344 free(snaps
[count
].name
);
4348 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4349 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4354 WARN("Failed to close directory");
4363 for (i
=0; i
<count
; i
++)
4364 lxcsnap_free(&snaps
[i
]);
4370 WARN("Failed to close directory");
4375 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4377 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4379 char clonelxcpath
[MAXPATHLEN
];
4381 struct lxc_container
*snap
, *rest
;
4382 struct lxc_storage
*bdev
;
4385 if (!c
|| !c
->name
|| !c
->config_path
)
4388 if (has_fs_snapshots(c
)) {
4389 ERROR("container rootfs has dependent snapshots");
4393 bdev
= storage_init(c
->lxc_conf
);
4395 ERROR("Failed to find original backing store type");
4399 /* For an overlay container the rootfs is considered immutable
4400 * and cannot be removed when restoring from a snapshot. We pass this
4401 * internal flag along to communicate this to various parts of the
4404 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4405 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4410 if (!get_snappath_dir(c
, clonelxcpath
)) {
4414 /* how should we lock this? */
4416 snap
= lxc_container_new(snapname
, clonelxcpath
);
4417 if (!snap
|| !lxcapi_is_defined(snap
)) {
4418 ERROR("Could not open snapshot %s", snapname
);
4421 lxc_container_put(snap
);
4427 if (!strcmp(c
->name
, newname
)) {
4428 if (!container_destroy(c
, bdev
)) {
4429 ERROR("Could not destroy existing container %s", newname
);
4430 lxc_container_put(snap
);
4436 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4437 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4439 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4440 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4442 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4445 if (rest
&& lxcapi_is_defined(rest
))
4449 lxc_container_put(rest
);
4451 lxc_container_put(snap
);
4455 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4457 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4459 struct lxc_container
*snap
= NULL
;
4462 snap
= lxc_container_new(snapname
, clonelxcpath
);
4464 ERROR("Could not find snapshot %s", snapname
);
4468 if (!do_lxcapi_destroy(snap
)) {
4469 ERROR("Could not destroy snapshot %s", snapname
);
4477 lxc_container_put(snap
);
4482 static bool remove_all_snapshots(const char *path
)
4485 struct dirent
*direntp
;
4488 dir
= opendir(path
);
4490 SYSERROR("opendir on snapshot path %s", path
);
4494 while ((direntp
= readdir(dir
))) {
4495 if (!strcmp(direntp
->d_name
, "."))
4498 if (!strcmp(direntp
->d_name
, ".."))
4501 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4510 SYSERROR("Error removing directory %s", path
);
4515 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4517 char clonelxcpath
[MAXPATHLEN
];
4519 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4522 if (!get_snappath_dir(c
, clonelxcpath
))
4525 return do_snapshot_destroy(snapname
, clonelxcpath
);
4528 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4530 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4532 char clonelxcpath
[MAXPATHLEN
];
4534 if (!c
|| !c
->name
|| !c
->config_path
)
4537 if (!get_snappath_dir(c
, clonelxcpath
))
4540 return remove_all_snapshots(clonelxcpath
);
4543 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4545 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4550 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4553 WRAP_API(bool, lxcapi_may_control
)
4555 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4561 char chrootpath
[MAXPATHLEN
];
4562 char *directory_path
= NULL
;
4566 SYSERROR("Failed to fork()");
4571 ret
= wait_for_pid(pid
);
4573 ERROR("Failed to create device node");
4580 /* prepare the path */
4581 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4582 if (ret
< 0 || ret
>= MAXPATHLEN
)
4585 ret
= chroot(chrootpath
);
4587 _exit(EXIT_FAILURE
);
4591 _exit(EXIT_FAILURE
);
4593 /* remove path if it exists */
4594 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4598 SYSERROR("Failed to remove \"%s\"", path
);
4599 _exit(EXIT_FAILURE
);
4604 _exit(EXIT_SUCCESS
);
4606 /* create any missing directories */
4609 _exit(EXIT_FAILURE
);
4611 directory_path
= dirname(tmp
);
4612 ret
= mkdir_p(directory_path
, 0755);
4613 if (ret
< 0 && errno
!= EEXIST
) {
4614 SYSERROR("Failed to create path \"%s\"", directory_path
);
4616 _exit(EXIT_FAILURE
);
4619 /* create the device node */
4620 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4623 SYSERROR("Failed to create device node at \"%s\"", path
);
4624 _exit(EXIT_FAILURE
);
4627 _exit(EXIT_SUCCESS
);
4630 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4634 char value
[LXC_MAX_BUFFER
];
4637 /* make sure container is running */
4638 if (!do_lxcapi_is_running(c
)) {
4639 ERROR("container is not running");
4643 /* use src_path if dest_path is NULL otherwise use dest_path */
4644 p
= dest_path
? dest_path
: src_path
;
4646 /* make sure we can access p */
4647 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4650 /* continue if path is character device or block device */
4651 if (S_ISCHR(st
.st_mode
))
4652 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4653 else if (S_ISBLK(st
.st_mode
))
4654 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4658 /* check snprintf return code */
4659 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4662 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4665 /* add or remove device to/from cgroup access list */
4667 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4668 ERROR("set_cgroup_item failed while adding the device node");
4672 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4673 ERROR("set_cgroup_item failed while removing the device node");
4681 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4683 // cannot mknod if we're not privileged wrt init_user_ns
4684 if (am_host_unpriv()) {
4685 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4689 return add_remove_device_node(c
, src_path
, dest_path
, true);
4692 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4694 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4696 if (am_guest_unpriv()) {
4697 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4701 return add_remove_device_node(c
, src_path
, dest_path
, false);
4704 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4706 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4708 const char *dst_ifname
)
4713 if (am_guest_unpriv()) {
4714 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4719 ERROR("No source interface name given");
4723 ret
= lxc_netdev_isup(ifname
);
4725 /* netdev of ifname is up. */
4726 ret
= lxc_netdev_down(ifname
);
4731 init_pid
= do_lxcapi_init_pid(c
);
4732 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4736 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4743 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4745 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4747 const char *dst_ifname
)
4750 pid_t pid
, pid_outside
;
4753 * TODO - if this is a physical device, then we need am_host_unpriv.
4754 * But for other types guest privilege suffices.
4756 if (am_guest_unpriv()) {
4757 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4762 ERROR("No source interface name given");
4766 pid_outside
= lxc_raw_getpid();
4769 ERROR("Failed to fork");
4773 if (pid
== 0) { /* child */
4776 init_pid
= do_lxcapi_init_pid(c
);
4777 if (!switch_to_ns(init_pid
, "net")) {
4778 ERROR("Failed to enter network namespace");
4779 _exit(EXIT_FAILURE
);
4782 ret
= lxc_netdev_isup(ifname
);
4784 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4785 _exit(EXIT_FAILURE
);
4788 /* netdev of ifname is up. */
4790 ret
= lxc_netdev_down(ifname
);
4792 ERROR("Failed to set network device \"%s\" down", ifname
);
4793 _exit(EXIT_FAILURE
);
4797 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4798 /* -EINVAL means there is no netdev named as ifname. */
4801 ERROR("Network device \"%s\" not found", ifname
);
4803 ERROR("Failed to remove network device \"%s\"", ifname
);
4805 _exit(EXIT_FAILURE
);
4808 _exit(EXIT_SUCCESS
);
4811 ret
= wait_for_pid(pid
);
4815 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4819 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4821 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4822 struct migrate_opts
*opts
, unsigned int size
)
4825 struct migrate_opts
*valid_opts
= opts
;
4826 uint64_t features_to_check
= 0;
4828 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4829 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4830 * to do anything special.
4832 if (size
> sizeof(*opts
)) {
4833 unsigned char *addr
;
4836 addr
= (void *)opts
+ sizeof(*opts
);
4837 end
= (void *)opts
+ size
;
4839 for (; addr
< end
; addr
++)
4844 /* If the caller has a smaller struct, let's zero out the end for them
4845 * so we don't accidentally use bits of it that they didn't know about
4848 if (size
< sizeof(*opts
)) {
4849 valid_opts
= malloc(sizeof(*opts
));
4853 memset(valid_opts
, 0, sizeof(*opts
));
4854 memcpy(valid_opts
, opts
, size
);
4858 case MIGRATE_PRE_DUMP
:
4859 if (!do_lxcapi_is_running(c
)) {
4860 ERROR("container is not running");
4864 ret
= !__criu_pre_dump(c
, valid_opts
);
4867 if (!do_lxcapi_is_running(c
)) {
4868 ERROR("container is not running");
4872 ret
= !__criu_dump(c
, valid_opts
);
4874 case MIGRATE_RESTORE
:
4875 if (do_lxcapi_is_running(c
)) {
4876 ERROR("container is already running");
4880 ret
= !__criu_restore(c
, valid_opts
);
4882 case MIGRATE_FEATURE_CHECK
:
4883 features_to_check
= valid_opts
->features_to_check
;
4884 ret
= !__criu_check_feature(&features_to_check
);
4886 /* Something went wrong. Let's let the caller
4887 * know which feature checks failed. */
4888 valid_opts
->features_to_check
= features_to_check
;
4892 ERROR("invalid migrate command %u", cmd
);
4897 if (size
< sizeof(*opts
))
4903 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4905 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4907 struct migrate_opts opts
;
4909 memset(&opts
, 0, sizeof(opts
));
4911 opts
.directory
= directory
;
4913 opts
.verbose
= verbose
;
4915 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4918 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4920 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4922 struct migrate_opts opts
;
4924 memset(&opts
, 0, sizeof(opts
));
4926 opts
.directory
= directory
;
4927 opts
.verbose
= verbose
;
4929 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4932 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4934 /* @st_mode is the st_mode field of the stat(source) return struct */
4935 static int create_mount_target(const char *dest
, mode_t st_mode
)
4937 char *dirdup
, *destdirname
;
4940 dirdup
= strdup(dest
);
4942 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4945 destdirname
= dirname(dirdup
);
4947 ret
= mkdir_p(destdirname
, 0755);
4949 SYSERROR("Failed to create \"%s\"", destdirname
);
4957 if (S_ISDIR(st_mode
))
4958 ret
= mkdir(dest
, 0000);
4960 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4962 SYSERROR("Failed to create mount target \"%s\"", dest
);
4969 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4970 const char *target
, const char *filesystemtype
,
4971 unsigned long mountflags
, const void *data
,
4972 struct lxc_mount
*mnt
)
4975 char template[MAXPATHLEN
], path
[MAXPATHLEN
];
4976 pid_t pid
, init_pid
;
4978 int ret
= -1, fd
= -EBADF
;
4980 if (!c
|| !c
->lxc_conf
) {
4981 ERROR("Container or configuration is NULL");
4985 if (!c
->lxc_conf
->shmount
.path_host
) {
4986 ERROR("Host path to shared mountpoint must be specified in the config\n");
4990 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
4991 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
4992 SYSERROR("Error writing shmounts tempdir name");
4996 /* Create a temporary file / dir under the shared mountpoint */
4997 if (!source
|| strcmp(source
, "") == 0) {
4998 /* If source is not specified, maybe we want to mount a filesystem? */
4999 sb
.st_mode
= S_IFDIR
;
5001 ret
= stat(source
, &sb
);
5003 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5008 if (S_ISDIR(sb
.st_mode
)) {
5009 sret
= mkdtemp(template);
5011 SYSERROR("Could not create shmounts temporary dir");
5015 fd
= lxc_make_tmpfile(template, false);
5017 SYSERROR("Could not create shmounts temporary file");
5025 SYSERROR("Could not fork");
5031 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5033 SYSERROR("Failed to mount onto \"%s\"", template);
5034 _exit(EXIT_FAILURE
);
5036 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5038 init_pid
= do_lxcapi_init_pid(c
);
5040 ERROR("Failed to obtain container's init pid");
5041 _exit(EXIT_FAILURE
);
5044 /* Enter the container namespaces */
5045 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5046 if (!switch_to_ns(init_pid
, "user")){
5047 ERROR("Failed to enter user namespace");
5048 _exit(EXIT_FAILURE
);
5052 if (!switch_to_ns(init_pid
, "mnt")) {
5053 ERROR("Failed to enter mount namespace");
5054 _exit(EXIT_FAILURE
);
5057 ret
= create_mount_target(target
, sb
.st_mode
);
5059 _exit(EXIT_FAILURE
);
5060 TRACE("Created mount target \"%s\"", target
);
5062 suff
= strrchr(template, '/');
5064 _exit(EXIT_FAILURE
);
5066 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5067 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5068 SYSERROR("Error writing container mountpoint name");
5069 _exit(EXIT_FAILURE
);
5072 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5074 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5075 _exit(EXIT_FAILURE
);
5077 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5079 _exit(EXIT_SUCCESS
);
5082 ret
= wait_for_pid(pid
);
5084 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5090 (void)umount2(template, MNT_DETACH
);
5091 (void)unlink(template);
5100 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5101 unsigned long, const void *, struct lxc_mount
*)
5103 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5104 unsigned long flags
, struct lxc_mount
*mnt
)
5106 pid_t pid
, init_pid
;
5109 if (!c
|| !c
->lxc_conf
) {
5110 ERROR("Container or configuration is NULL");
5117 SYSERROR("Could not fork");
5122 init_pid
= do_lxcapi_init_pid(c
);
5124 ERROR("Failed to obtain container's init pid");
5125 _exit(EXIT_FAILURE
);
5128 /* Enter the container namespaces */
5129 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5130 if (!switch_to_ns(init_pid
, "user")) {
5131 ERROR("Failed to enter user namespace");
5132 _exit(EXIT_FAILURE
);
5136 if (!switch_to_ns(init_pid
, "mnt")) {
5137 ERROR("Failed to enter mount namespace");
5138 _exit(EXIT_FAILURE
);
5141 /* Do the unmount */
5142 ret
= umount2(target
, flags
);
5144 SYSERROR("Failed to umount \"%s\"", target
);
5145 _exit(EXIT_FAILURE
);
5148 _exit(EXIT_SUCCESS
);
5151 ret
= wait_for_pid(pid
);
5153 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5160 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5162 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5171 current_config
= c
->lxc_conf
;
5174 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5178 ERROR("Memory allocation error.");
5184 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5188 current_config
= NULL
;
5192 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5194 struct lxc_container
*c
;
5200 c
= malloc(sizeof(*c
));
5202 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5205 memset(c
, 0, sizeof(*c
));
5208 c
->config_path
= strdup(configpath
);
5210 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5211 if (!c
->config_path
) {
5212 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5216 remove_trailing_slashes(c
->config_path
);
5219 c
->name
= malloc(len
+ 1);
5221 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5224 (void)strlcpy(c
->name
, name
, len
+ 1);
5227 c
->slock
= lxc_newlock(c
->config_path
, name
);
5229 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5233 c
->privlock
= lxc_newlock(NULL
, NULL
);
5235 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5239 if (!set_config_filename(c
)) {
5240 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5244 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5245 fprintf(stderr
, "Failed to load config for %s\n", name
);
5249 if (ongoing_create(c
) == 2) {
5250 ERROR("Failed to complete container creation for %s", c
->name
);
5251 container_destroy(c
, NULL
);
5252 lxcapi_clear_config(c
);
5255 c
->daemonize
= true;
5258 /* Assign the member functions. */
5259 c
->is_defined
= lxcapi_is_defined
;
5260 c
->state
= lxcapi_state
;
5261 c
->is_running
= lxcapi_is_running
;
5262 c
->freeze
= lxcapi_freeze
;
5263 c
->unfreeze
= lxcapi_unfreeze
;
5264 c
->console
= lxcapi_console
;
5265 c
->console_getfd
= lxcapi_console_getfd
;
5266 c
->init_pid
= lxcapi_init_pid
;
5267 c
->load_config
= lxcapi_load_config
;
5268 c
->want_daemonize
= lxcapi_want_daemonize
;
5269 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5270 c
->start
= lxcapi_start
;
5271 c
->startl
= lxcapi_startl
;
5272 c
->stop
= lxcapi_stop
;
5273 c
->config_file_name
= lxcapi_config_file_name
;
5274 c
->wait
= lxcapi_wait
;
5275 c
->set_config_item
= lxcapi_set_config_item
;
5276 c
->destroy
= lxcapi_destroy
;
5277 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5278 c
->rename
= lxcapi_rename
;
5279 c
->save_config
= lxcapi_save_config
;
5280 c
->get_keys
= lxcapi_get_keys
;
5281 c
->create
= lxcapi_create
;
5282 c
->createl
= lxcapi_createl
;
5283 c
->shutdown
= lxcapi_shutdown
;
5284 c
->reboot
= lxcapi_reboot
;
5285 c
->reboot2
= lxcapi_reboot2
;
5286 c
->clear_config
= lxcapi_clear_config
;
5287 c
->clear_config_item
= lxcapi_clear_config_item
;
5288 c
->get_config_item
= lxcapi_get_config_item
;
5289 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5290 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5291 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5292 c
->get_config_path
= lxcapi_get_config_path
;
5293 c
->set_config_path
= lxcapi_set_config_path
;
5294 c
->clone
= lxcapi_clone
;
5295 c
->get_interfaces
= lxcapi_get_interfaces
;
5296 c
->get_ips
= lxcapi_get_ips
;
5297 c
->attach
= lxcapi_attach
;
5298 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5299 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5300 c
->snapshot
= lxcapi_snapshot
;
5301 c
->snapshot_list
= lxcapi_snapshot_list
;
5302 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5303 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5304 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5305 c
->may_control
= lxcapi_may_control
;
5306 c
->add_device_node
= lxcapi_add_device_node
;
5307 c
->remove_device_node
= lxcapi_remove_device_node
;
5308 c
->attach_interface
= lxcapi_attach_interface
;
5309 c
->detach_interface
= lxcapi_detach_interface
;
5310 c
->checkpoint
= lxcapi_checkpoint
;
5311 c
->restore
= lxcapi_restore
;
5312 c
->migrate
= lxcapi_migrate
;
5313 c
->console_log
= lxcapi_console_log
;
5314 c
->mount
= lxcapi_mount
;
5315 c
->umount
= lxcapi_umount
;
5320 lxc_container_free(c
);
5324 int lxc_get_wait_states(const char **states
)
5329 for (i
=0; i
<MAX_STATE
; i
++)
5330 states
[i
] = lxc_state2str(i
);
5336 * These next two could probably be done smarter with reusing a common function
5337 * with different iterators and tests...
5339 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5342 int i
, cfound
= 0, nfound
= 0;
5343 struct dirent
*direntp
;
5344 struct lxc_container
*c
;
5347 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5349 dir
= opendir(lxcpath
);
5351 SYSERROR("opendir on lxcpath");
5361 while ((direntp
= readdir(dir
))) {
5362 /* Ignore '.', '..' and any hidden directory. */
5363 if (!strncmp(direntp
->d_name
, ".", 1))
5366 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5370 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5380 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5382 INFO("Container %s:%s has a config but could not be loaded",
5383 lxcpath
, direntp
->d_name
);
5386 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5392 if (!do_lxcapi_is_defined(c
)) {
5393 INFO("Container %s:%s has a config but is not defined",
5394 lxcpath
, direntp
->d_name
);
5397 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5400 lxc_container_put(c
);
5404 if (!add_to_clist(cret
, c
, nfound
, true)) {
5405 lxc_container_put(c
);
5416 if (names
&& *names
) {
5417 for (i
=0; i
<cfound
; i
++)
5422 if (cret
&& *cret
) {
5423 for (i
=0; i
<nfound
; i
++)
5424 lxc_container_put((*cret
)[i
]);
5432 int list_active_containers(const char *lxcpath
, char ***nret
,
5433 struct lxc_container
***cret
)
5435 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5438 char **ct_name
= NULL
;
5440 struct lxc_container
*c
= NULL
;
5444 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5445 lxcpath_len
= strlen(lxcpath
);
5453 FILE *f
= fopen("/proc/net/unix", "r");
5457 while (getline(&line
, &len
, f
) != -1) {
5458 char *p
= strrchr(line
, ' '), *p2
;
5469 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5471 } else if (strncmp(p
, "lxc/", 4) == 0) {
5481 /* Now p is the start of lxc_name. */
5482 p2
= strchr(p
, '/');
5483 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5488 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5492 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5498 p
= lxc_cmd_get_name(p
);
5503 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5509 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5512 goto free_cret_list
;
5523 c
= lxc_container_new(p
, lxcpath
);
5525 INFO("Container %s:%s is running but could not be loaded",
5528 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5539 * If this is an anonymous container, then is_defined *can*
5540 * return false. So we don't do that check. Count on the
5541 * fact that the command socket exists.
5544 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5545 lxc_container_put(c
);
5546 goto free_cret_list
;
5552 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5554 lxc_container_put(c
);
5555 goto free_cret_list
;
5567 if (cret
&& *cret
) {
5568 for (i
= 0; i
< cret_cnt
; i
++)
5569 lxc_container_put((*cret
)[i
]);
5575 for (i
= 0; i
< ct_name_cnt
; i
++)
5586 int list_all_containers(const char *lxcpath
, char ***nret
,
5587 struct lxc_container
***cret
)
5589 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5592 struct lxc_container
**ct_list
= NULL
;
5594 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5598 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5599 if (active_cnt
< 0) {
5604 for (i
= 0; i
< active_cnt
; i
++) {
5605 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5606 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5608 goto free_active_name
;
5614 free(active_name
[i
]);
5615 active_name
[i
] = NULL
;
5622 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5623 struct lxc_container
*c
;
5625 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5627 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5628 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5632 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5633 lxc_container_put(c
);
5654 for (i
= 0; i
< ct_list_cnt
; i
++) {
5655 lxc_container_put(ct_list
[i
]);
5660 for (i
= 0; i
< active_cnt
; i
++) {
5661 free(active_name
[i
]);
5666 for (i
= 0; i
< ct_cnt
; i
++) {
5673 bool lxc_config_item_is_supported(const char *key
)
5675 return !!lxc_get_config(key
);
5678 bool lxc_has_api_extension(const char *extension
)
5680 /* The NULL API extension is always present. :) */
5684 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5685 if (strcmp(api_extensions
[i
], extension
) == 0)