3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <arpa/inet.h>
38 #include <sys/mount.h>
40 #include <sys/syscall.h>
41 #include <sys/sysmacros.h>
42 #include <sys/types.h>
46 #include "../include/netns_ifaddrs.h"
48 #include "api_extensions.h"
52 #include "commands_utils.h"
56 #include "confile_utils.h"
59 #include "initutils.h"
62 #include "lxccontainer.h"
64 #include "memory_utils.h"
66 #include "namespace.h"
69 #include "raw_syscalls.h"
73 #include "storage/btrfs.h"
74 #include "storage/overlay.h"
75 #include "storage_utils.h"
77 #include "syscall_wrappers.h"
83 #include <openssl/evp.h>
88 #include <sys/mkdev.h>
92 #include <../include/lxcmntent.h>
98 #include "include/strlcpy.h"
101 /* Define faccessat() if missing from the C library */
102 #ifndef HAVE_FACCESSAT
103 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
105 #ifdef __NR_faccessat
106 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
114 lxc_log_define(lxccontainer
, lxc
);
116 static bool do_lxcapi_destroy(struct lxc_container
*c
);
117 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
118 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
119 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
120 static bool container_destroy(struct lxc_container
*c
,
121 struct lxc_storage
*storage
);
122 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
123 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
124 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
126 static bool config_file_exists(const char *lxcpath
, const char *cname
)
128 __do_free
char *fname
= NULL
;
132 /* $lxcpath + '/' + $cname + '/config' + \0 */
133 len
= strlen(lxcpath
) + strlen(cname
) + 9;
134 fname
= must_realloc(NULL
, len
);
135 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
136 if (ret
< 0 || (size_t)ret
>= len
)
139 return file_exists(fname
);
143 * A few functions to help detect when a container creation failed. If a
144 * container creation was killed partway through, then trying to actually start
145 * that container could harm the host. We detect this by creating a 'partial'
146 * file under the container directory, and keeping an advisory lock. When
147 * container creation completes, we remove that file. When we load or try to
148 * start a container, if we find that file, without a flock, we remove the
152 LXC_CREATE_FAILED
= -1,
153 LXC_CREATE_SUCCESS
= 0,
154 LXC_CREATE_ONGOING
= 1,
155 LXC_CREATE_INCOMPLETE
= 2,
158 static int ongoing_create(struct lxc_container
*c
)
160 __do_close_prot_errno
int fd
= -EBADF
;
161 __do_free
char *path
= NULL
;
162 struct flock lk
= {0};
166 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
167 path
= must_realloc(NULL
, len
);
168 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
169 if (ret
< 0 || (size_t)ret
>= len
)
170 return LXC_CREATE_FAILED
;
172 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
175 return LXC_CREATE_FAILED
;
177 return LXC_CREATE_SUCCESS
;
181 lk
.l_whence
= SEEK_SET
;
183 * F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
188 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
189 if (ret
< 0 && errno
== EINVAL
) {
190 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
191 if (ret
< 0 && errno
== EWOULDBLOCK
)
195 /* F_OFD_GETLK will not send us back a pid so don't check it. */
197 /* Create is still ongoing. */
198 return LXC_CREATE_ONGOING
;
200 /* Create completed but partial is still there. */
201 return LXC_CREATE_INCOMPLETE
;
204 static int create_partial(struct lxc_container
*c
)
206 __do_free
char *path
= NULL
;
209 struct flock lk
= {0};
211 /* $lxcpath + '/' + $name + '/partial' + \0 */
212 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
213 path
= must_realloc(NULL
, len
);
214 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
215 if (ret
< 0 || (size_t)ret
>= len
)
218 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
223 lk
.l_whence
= SEEK_SET
;
225 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
227 if (errno
== EINVAL
) {
228 ret
= flock(fd
, LOCK_EX
);
233 SYSERROR("Failed to lock partial file %s", path
);
241 static void remove_partial(struct lxc_container
*c
, int fd
)
243 __do_free
char *path
= NULL
;
249 /* $lxcpath + '/' + $name + '/partial' + \0 */
250 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
251 path
= must_realloc(NULL
, len
);
252 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
253 if (ret
< 0 || (size_t)ret
>= len
)
258 SYSERROR("Failed to remove partial file %s", path
);
262 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
263 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
264 * container configuration file.
265 * The container_disk_lock also takes the container_mem_lock.
266 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
267 * NOTHING mutexes two independent programs with their own struct
268 * lxc_container for the same c->name, between API calls. For instance,
269 * c->config_read(); c->start(); Between those calls, data on disk
270 * could change (which shouldn't bother the caller unless for instance
271 * the rootfs get moved). c->config_read(); update; c->config_write();
272 * Two such updaters could race. The callers should therefore check their
273 * results. Trying to prevent that would necessarily expose us to deadlocks
274 * due to hung callers. So I prefer to keep the locks only within our own
275 * functions, not across functions.
277 * If you're going to clone while holding a lxccontainer, increment
278 * c->numthreads (under privlock) before forking. When deleting,
279 * decrement numthreads under privlock, then if it hits 0 you can delete.
280 * Do not ever use a lxccontainer whose numthreads you did not bump.
282 static void lxc_container_free(struct lxc_container
*c
)
288 c
->configfile
= NULL
;
290 free(c
->error_string
);
291 c
->error_string
= NULL
;
294 lxc_putlock(c
->slock
);
299 lxc_putlock(c
->privlock
);
307 lxc_conf_free(c
->lxc_conf
);
311 free(c
->config_path
);
312 c
->config_path
= NULL
;
317 /* Consider the following case:
319 * |====================================================================|
320 * | freer | racing get()er |
321 * |====================================================================|
322 * | lxc_container_put() | lxc_container_get() |
323 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
324 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
325 * | \ lxcunlock() | \ |
326 * | \ lxc_container_free() | \ lxclock() returns |
327 * | | \ c->numthreads < 1 -> return 0 |
328 * | \ \ (free stuff) | |
329 * | \ \ sem_destroy(privlock) | |
330 * |_______________________________|____________________________________|
332 * When the get()er checks numthreads the first time, one of the following
334 * 1. freer has set numthreads = 0. get() returns 0
335 * 2. freer is between lxclock and setting numthreads to 0. get()er will
336 * sem_wait on privlock, get lxclock after freer() drops it, then see
337 * numthreads is 0 and exit without touching lxclock again..
338 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
339 * will see --numthreads = 1 and not call lxc_container_free().
342 int lxc_container_get(struct lxc_container
*c
)
347 /* If someone else has already started freeing the container, don't try
348 * to take the lock, which may be invalid.
350 if (c
->numthreads
< 1)
353 if (container_mem_lock(c
))
356 /* Bail without trying to unlock, bc the privlock is now probably in
359 if (c
->numthreads
< 1)
363 container_mem_unlock(c
);
368 int lxc_container_put(struct lxc_container
*c
)
373 if (container_mem_lock(c
))
378 if (c
->numthreads
< 1) {
379 container_mem_unlock(c
);
380 lxc_container_free(c
);
384 container_mem_unlock(c
);
388 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
397 if (container_mem_lock(c
))
403 statret
= stat(c
->configfile
, &statbuf
);
410 container_mem_unlock(c
);
414 #define WRAP_API(rettype, fnname) \
415 static rettype fnname(struct lxc_container *c) \
418 bool reset_config = false; \
420 if (!current_config && c && c->lxc_conf) { \
421 current_config = c->lxc_conf; \
422 reset_config = true; \
425 ret = do_##fnname(c); \
427 current_config = NULL; \
432 #define WRAP_API_1(rettype, fnname, t1) \
433 static rettype fnname(struct lxc_container *c, t1 a1) \
436 bool reset_config = false; \
438 if (!current_config && c && c->lxc_conf) { \
439 current_config = c->lxc_conf; \
440 reset_config = true; \
443 ret = do_##fnname(c, a1); \
445 current_config = NULL; \
450 #define WRAP_API_2(rettype, fnname, t1, t2) \
451 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
454 bool reset_config = false; \
456 if (!current_config && c && c->lxc_conf) { \
457 current_config = c->lxc_conf; \
458 reset_config = true; \
461 ret = do_##fnname(c, a1, a2); \
463 current_config = NULL; \
468 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
469 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
472 bool reset_config = false; \
474 if (!current_config && c && c->lxc_conf) { \
475 current_config = c->lxc_conf; \
476 reset_config = true; \
479 ret = do_##fnname(c, a1, a2, a3); \
481 current_config = NULL; \
486 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
487 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
488 t4 a4, t5 a5, t6 a6) \
491 bool reset_config = false; \
493 if (!current_config && c && c->lxc_conf) { \
494 current_config = c->lxc_conf; \
495 reset_config = true; \
498 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
500 current_config = NULL; \
505 WRAP_API(bool, lxcapi_is_defined
)
507 static const char *do_lxcapi_state(struct lxc_container
*c
)
514 s
= lxc_getstate(c
->name
, c
->config_path
);
515 return lxc_state2str(s
);
518 WRAP_API(const char *, lxcapi_state
)
520 static bool is_stopped(struct lxc_container
*c
)
524 s
= lxc_getstate(c
->name
, c
->config_path
);
525 return (s
== STOPPED
);
528 static bool do_lxcapi_is_running(struct lxc_container
*c
)
533 return !is_stopped(c
);
536 WRAP_API(bool, lxcapi_is_running
)
538 static bool do_lxcapi_freeze(struct lxc_container
*c
)
542 if (!c
|| !c
->lxc_conf
)
545 s
= lxc_getstate(c
->name
, c
->config_path
);
547 return lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
552 WRAP_API(bool, lxcapi_freeze
)
554 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
558 if (!c
|| !c
->lxc_conf
)
561 s
= lxc_getstate(c
->name
, c
->config_path
);
563 return lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
) == 0;
568 WRAP_API(bool, lxcapi_unfreeze
)
570 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
575 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
578 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
580 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
581 int stdoutfd
, int stderrfd
, int escape
)
588 current_config
= c
->lxc_conf
;
589 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
590 current_config
= NULL
;
595 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
602 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
605 NOTICE("The console log is empty");
606 else if (ret
== -EFAULT
)
607 NOTICE("The container does not keep a console log");
608 else if (ret
== -ENOENT
)
609 NOTICE("The container does not keep a console log file");
610 else if (ret
== -EIO
)
611 NOTICE("Failed to write console log to log file");
613 ERROR("Failed to retrieve console log");
619 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
621 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
626 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
629 WRAP_API(pid_t
, lxcapi_init_pid
)
631 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
634 c
->lxc_conf
= lxc_conf_init();
639 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
642 c
->lxc_conf
->name
= c
->name
;
646 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
650 bool need_disklock
= false, ret
= false;
655 fname
= c
->configfile
;
663 /* If we're reading something other than the container's config, we only
664 * need to lock the in-memory container. If loading the container's
665 * config file, take the disk lock.
667 if (strcmp(fname
, c
->configfile
) == 0)
668 need_disklock
= true;
671 lret
= container_disk_lock(c
);
673 lret
= container_mem_lock(c
);
677 ret
= load_config_locked(c
, fname
);
680 container_disk_unlock(c
);
682 container_mem_unlock(c
);
687 WRAP_API_1(bool, lxcapi_load_config
, const char *)
689 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
691 if (!c
|| !c
->lxc_conf
)
694 if (container_mem_lock(c
))
697 c
->daemonize
= state
;
699 container_mem_unlock(c
);
704 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
706 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
708 if (!c
|| !c
->lxc_conf
)
711 if (container_mem_lock(c
))
714 c
->lxc_conf
->close_all_fds
= state
;
716 container_mem_unlock(c
);
721 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
723 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
731 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
735 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
737 static bool am_single_threaded(void)
740 struct dirent
*direntp
;
743 dir
= opendir("/proc/self/task");
747 while ((direntp
= readdir(dir
))) {
748 if (strcmp(direntp
->d_name
, ".") == 0)
751 if (strcmp(direntp
->d_name
, "..") == 0)
763 static void push_arg(char ***argp
, char *arg
, int *nargs
)
768 copy
= must_copy_string(arg
);
771 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
780 static char **split_init_cmd(const char *incmd
)
782 __do_free
char *copy
= NULL
;
790 copy
= must_copy_string(incmd
);
793 argv
= malloc(sizeof(char *));
797 lxc_iterate_parts (p
, copy
, " ")
798 push_arg(&argv
, p
, &nargs
);
808 static void free_init_cmd(char **argv
)
821 static int lxc_rcv_status(int state_socket
)
827 /* Receive container state. */
828 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
833 TRACE("Caught EINTR; retrying");
840 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
844 /* Close write end of the socket pair. */
845 close(handler
->state_socket_pair
[1]);
846 handler
->state_socket_pair
[1] = -1;
848 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
850 /* Close read end of the socket pair. */
851 close(handler
->state_socket_pair
[0]);
852 handler
->state_socket_pair
[0] = -1;
854 /* The first child is going to fork() again and then exits. So we reap
855 * the first child here.
857 ret
= wait_for_pid(pid
);
859 DEBUG("Failed waiting on first child %d", pid
);
861 DEBUG("First child %d exited", pid
);
864 SYSERROR("Failed to receive the container state");
868 /* If we receive anything else then running we know that the container
871 if (state
!= RUNNING
) {
872 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
873 lxc_state2str(state
));
877 TRACE("Container is in \"RUNNING\" state");
881 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
884 struct lxc_handler
*handler
;
885 struct lxc_conf
*conf
;
886 char *default_args
[] = {
890 char **init_cmd
= NULL
;
891 int keepfds
[3] = {-1, -1, -1};
893 /* container does exist */
897 /* If anything fails before we set error_num, we want an error in there.
901 /* Container has not been setup. */
905 ret
= ongoing_create(c
);
907 case LXC_CREATE_FAILED
:
908 ERROR("Failed checking for incomplete container creation");
910 case LXC_CREATE_ONGOING
:
911 ERROR("Ongoing container creation detected");
913 case LXC_CREATE_INCOMPLETE
:
914 ERROR("Failed to create container");
915 do_lxcapi_destroy(c
);
919 if (container_mem_lock(c
))
924 /* initialize handler */
925 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
927 container_mem_unlock(c
);
932 if (useinit
&& conf
->execute_cmd
)
933 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
935 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
938 /* ... otherwise use default_args. */
941 ERROR("No valid init detected");
942 lxc_free_handler(handler
);
948 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
949 * here to protect the on disk container? We don't want to exclude
950 * things like lxc_info while the container is running.
959 free_init_cmd(init_cmd
);
960 lxc_free_handler(handler
);
966 /* Set to NULL because we don't want father unlink
967 * the PID file, child will do the free and unlink.
971 /* Wait for container to tell us whether it started
974 started
= wait_on_daemonized_start(handler
, pid
);
976 free_init_cmd(init_cmd
);
977 lxc_free_handler(handler
);
983 /* We don't really care if this doesn't print all the
984 * characters. All that it means is that the proctitle will be
985 * ugly. Similarly, we also don't care if setproctitle() fails.
987 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
989 ret
= setproctitle(title
);
991 INFO("Failed to set process title to %s", title
);
993 INFO("Set process title to %s", title
);
996 /* We fork() a second time to be reparented to init. Like
997 * POSIX's daemon() function we change to "/" and redirect
998 * std{in,out,err} to /dev/null.
1002 SYSERROR("Failed to fork first child process");
1003 _exit(EXIT_FAILURE
);
1008 free_init_cmd(init_cmd
);
1009 lxc_free_handler(handler
);
1010 _exit(EXIT_SUCCESS
);
1015 /* change to / directory */
1018 SYSERROR("Failed to change to \"/\" directory");
1019 _exit(EXIT_FAILURE
);
1022 keepfds
[0] = handler
->conf
->maincmd_fd
;
1023 keepfds
[1] = handler
->state_socket_pair
[0];
1024 keepfds
[2] = handler
->state_socket_pair
[1];
1025 ret
= lxc_check_inherited(conf
, true, keepfds
,
1026 sizeof(keepfds
) / sizeof(keepfds
[0]));
1028 _exit(EXIT_FAILURE
);
1030 /* redirect std{in,out,err} to /dev/null */
1031 ret
= null_stdfds();
1033 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1034 _exit(EXIT_FAILURE
);
1037 /* become session leader */
1040 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1041 } else if (!am_single_threaded()) {
1042 ERROR("Cannot start non-daemonized container when threaded");
1043 free_init_cmd(init_cmd
);
1044 lxc_free_handler(handler
);
1048 /* We need to write PID file after daemonize, so we always write the
1053 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1055 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1056 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1057 free_init_cmd(init_cmd
);
1058 lxc_free_handler(handler
);
1060 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1063 _exit(EXIT_FAILURE
);
1068 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1070 free_init_cmd(init_cmd
);
1071 lxc_free_handler(handler
);
1073 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1076 _exit(EXIT_FAILURE
);
1082 conf
->reboot
= REBOOT_NONE
;
1084 /* Unshare the mount namespace if requested */
1085 if (conf
->monitor_unshare
) {
1086 ret
= unshare(CLONE_NEWNS
);
1088 SYSERROR("Failed to unshare mount namespace");
1089 lxc_free_handler(handler
);
1094 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1096 SYSERROR("Failed to make / rslave at startup");
1097 lxc_free_handler(handler
);
1104 if (conf
->reboot
== REBOOT_INIT
) {
1105 /* initialize handler */
1106 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1113 keepfds
[0] = handler
->conf
->maincmd_fd
;
1114 keepfds
[1] = handler
->state_socket_pair
[0];
1115 keepfds
[2] = handler
->state_socket_pair
[1];
1116 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1117 sizeof(keepfds
) / sizeof(keepfds
[0]));
1119 lxc_free_handler(handler
);
1125 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1126 c
->daemonize
, &c
->error_num
);
1128 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1129 c
->daemonize
, &c
->error_num
);
1131 if (conf
->reboot
== REBOOT_REQ
) {
1132 INFO("Container requested reboot");
1133 conf
->reboot
= REBOOT_INIT
;
1143 free_init_cmd(init_cmd
);
1145 if (c
->daemonize
&& ret
!= 0)
1146 _exit(EXIT_FAILURE
);
1147 else if (c
->daemonize
)
1148 _exit(EXIT_SUCCESS
);
1156 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1161 current_config
= c
? c
->lxc_conf
: NULL
;
1162 ret
= do_lxcapi_start(c
, useinit
, argv
);
1163 current_config
= NULL
;
1168 /* Note, there MUST be an ending NULL. */
1169 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1172 char **inargs
= NULL
;
1175 /* container exists */
1179 current_config
= c
->lxc_conf
;
1181 va_start(ap
, useinit
);
1182 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1187 /* pass NULL if no arguments were supplied */
1188 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1194 for (arg
= inargs
; *arg
; arg
++)
1199 current_config
= NULL
;
1204 static bool do_lxcapi_stop(struct lxc_container
*c
)
1211 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1216 WRAP_API(bool, lxcapi_stop
)
1218 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1220 __do_free
char *p
= NULL
;
1224 mode_t mask
= umask(0002);
1225 ret
= mkdir(path
, 0770);
1230 if (errno
!= EEXIST
)
1236 p
= must_copy_string(path
);
1238 if (!lxc_list_empty(&conf
->id_map
)) {
1239 ret
= chown_mapped_root(p
, conf
);
1247 /* Create the standard expected container dir. */
1248 static bool create_container_dir(struct lxc_container
*c
)
1254 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1259 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1260 if (ret
< 0 || (size_t)ret
>= len
) {
1265 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1271 /* do_storage_create: thin wrapper around storage_create(). Like
1272 * storage_create(), it returns a mounted bdev on success, NULL on error.
1274 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1276 struct bdev_specs
*specs
)
1278 __do_free
char *dest
= NULL
;
1281 struct lxc_storage
*bdev
;
1283 /* rootfs.path or lxcpath/lxcname/rootfs */
1284 if (c
->lxc_conf
->rootfs
.path
&&
1285 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1286 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1287 len
= strlen(rpath
) + 1;
1288 dest
= must_realloc(NULL
, len
);
1289 ret
= snprintf(dest
, len
, "%s", rpath
);
1291 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1292 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1293 dest
= must_realloc(NULL
, len
);
1294 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1296 if (ret
< 0 || (size_t)ret
>= len
)
1299 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1301 ERROR("Failed to create \"%s\" storage", type
);
1305 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1306 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1310 /* If we are not root, chown the rootfs dir to root in the target user
1314 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1315 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1317 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1318 suggest_default_idmap();
1327 /* Strip path and return name of file for argv[0] passed to execvp */
1328 static char *lxctemplatefilename(char *tpath
)
1332 p
= tpath
+ strlen(tpath
) - 1;
1333 while ( (p
-1) >= tpath
&& *(p
-1) != '/')
1339 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1340 bool need_null_stdfds
, char *const argv
[])
1350 SYSERROR("Failed to fork task for container creation template");
1354 if (pid
== 0) { /* child */
1356 char *namearg
, *patharg
, *rootfsarg
;
1359 struct lxc_storage
*bdev
= NULL
;
1360 struct lxc_conf
*conf
= c
->lxc_conf
;
1363 if (need_null_stdfds
) {
1364 ret
= null_stdfds();
1366 _exit(EXIT_FAILURE
);
1369 bdev
= storage_init(c
->lxc_conf
);
1371 ERROR("Failed to initialize storage");
1372 _exit(EXIT_FAILURE
);
1377 ret
= unshare(CLONE_NEWNS
);
1379 ERROR("Failed to unshare CLONE_NEWNS");
1380 _exit(EXIT_FAILURE
);
1383 ret
= detect_shared_rootfs();
1385 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1387 SYSERROR("Failed to make \"/\" rslave");
1388 ERROR("Continuing...");
1393 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1395 ERROR("Unprivileged users can only create "
1396 "btrfs and directory-backed containers");
1397 _exit(EXIT_FAILURE
);
1400 if (strcmp(bdev
->type
, "overlay") == 0 ||
1401 strcmp(bdev
->type
, "overlayfs") == 0) {
1402 /* If we create an overlay container we need to
1403 * rsync the contents into
1404 * <container-path>/<container-name>/rootfs.
1405 * However, the overlay mount function will
1407 * <container-path>/<container-name>/delta0
1409 * <container-path>/<container-name>/rootfs
1410 * which means we would rsync the rootfs into
1411 * the delta directory. That doesn't make sense
1412 * since the delta directory only exists to
1413 * record the differences to
1414 * <container-path>/<container-name>/rootfs. So
1415 * let's simply bind-mount here and then rsync
1417 * <container-path>/<container-name>/rootfs.
1421 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1423 ERROR("Failed to get rootfs");
1424 _exit(EXIT_FAILURE
);
1427 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1429 ERROR("Failed to mount rootfs");
1430 _exit(EXIT_FAILURE
);
1433 ret
= bdev
->ops
->mount(bdev
);
1435 ERROR("Failed to mount rootfs");
1436 _exit(EXIT_FAILURE
);
1439 } else { /* TODO come up with a better way here! */
1442 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1443 bdev
->dest
= strdup(src
);
1446 /* Create our new array, pre-pend the template name and base
1450 for (nargs
= 0; argv
[nargs
]; nargs
++)
1453 /* template, path, rootfs and name args */
1456 newargv
= malloc(nargs
* sizeof(*newargv
));
1458 _exit(EXIT_FAILURE
);
1459 newargv
[0] = lxctemplatefilename(tpath
);
1462 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1463 patharg
= malloc(len
);
1465 _exit(EXIT_FAILURE
);
1467 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1468 if (ret
< 0 || ret
>= len
)
1469 _exit(EXIT_FAILURE
);
1470 newargv
[1] = patharg
;
1473 len
= strlen("--name=") + strlen(c
->name
) + 1;
1474 namearg
= malloc(len
);
1476 _exit(EXIT_FAILURE
);
1478 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1479 if (ret
< 0 || ret
>= len
)
1480 _exit(EXIT_FAILURE
);
1481 newargv
[2] = namearg
;
1484 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1485 rootfsarg
= malloc(len
);
1487 _exit(EXIT_FAILURE
);
1489 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1490 if (ret
< 0 || ret
>= len
)
1491 _exit(EXIT_FAILURE
);
1492 newargv
[3] = rootfsarg
;
1494 /* add passed-in args */
1496 for (i
= 4; i
< nargs
; i
++)
1497 newargv
[i
] = argv
[i
- 4];
1499 /* add trailing NULL */
1501 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1503 _exit(EXIT_FAILURE
);
1504 newargv
[nargs
- 1] = NULL
;
1506 /* If we're running the template in a mapped userns, then we
1507 * prepend the template command with: lxc-usernsexec <-m map1>
1508 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1509 * the mapped uid for our geteuid()
1511 if (!lxc_list_empty(&conf
->id_map
)) {
1512 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1514 char txtuid
[20], txtgid
[20];
1515 struct lxc_list
*it
;
1519 n2
= malloc(n2args
* sizeof(*n2
));
1521 _exit(EXIT_FAILURE
);
1524 tpath
= "lxc-usernsexec";
1525 n2
[0] = "lxc-usernsexec";
1527 lxc_list_for_each(it
, &conf
->id_map
) {
1530 n2
= realloc(n2
, n2args
* sizeof(char *));
1532 _exit(EXIT_FAILURE
);
1534 n2
[n2args
- 2] = "-m";
1535 n2
[n2args
- 1] = malloc(200);
1536 if (!n2
[n2args
- 1])
1537 _exit(EXIT_FAILURE
);
1539 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1540 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1541 map
->nsid
, map
->hostid
, map
->range
);
1542 if (ret
< 0 || ret
>= 200)
1543 _exit(EXIT_FAILURE
);
1546 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1547 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1549 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1551 _exit(EXIT_FAILURE
);
1553 if (hostuid_mapped
< 0) {
1554 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1555 n2
[n2args
++] = "-m";
1556 if (hostuid_mapped
< 0) {
1557 ERROR("Failed to find free uid to map");
1558 _exit(EXIT_FAILURE
);
1561 n2
[n2args
++] = malloc(200);
1562 if (!n2
[n2args
- 1]) {
1563 SYSERROR("out of memory");
1564 _exit(EXIT_FAILURE
);
1567 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1568 hostuid_mapped
, geteuid());
1569 if (ret
< 0 || ret
>= 200)
1570 _exit(EXIT_FAILURE
);
1573 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1574 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1576 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1578 _exit(EXIT_FAILURE
);
1580 if (hostgid_mapped
< 0) {
1581 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1582 n2
[n2args
++] = "-m";
1583 if (hostgid_mapped
< 0) {
1584 ERROR("Failed to find free gid to map");
1585 _exit(EXIT_FAILURE
);
1588 n2
[n2args
++] = malloc(200);
1589 if (!n2
[n2args
- 1]) {
1590 SYSERROR("out of memory");
1591 _exit(EXIT_FAILURE
);
1594 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1595 hostgid_mapped
, getegid());
1596 if (ret
< 0 || ret
>= 200)
1597 _exit(EXIT_FAILURE
);
1600 n2
[n2args
++] = "--";
1602 for (i
= 0; i
< nargs
; i
++)
1603 n2
[i
+ n2args
] = newargv
[i
];
1606 /* Finally add "--mapped-uid $uid" to tell template what
1607 * to chown cached images to.
1610 n2
= realloc(n2
, n2args
* sizeof(char *));
1612 _exit(EXIT_FAILURE
);
1614 /* note n2[n2args-1] is NULL */
1615 n2
[n2args
- 5] = "--mapped-uid";
1617 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1618 if (ret
< 0 || ret
>= 20) {
1621 _exit(EXIT_FAILURE
);
1624 n2
[n2args
- 4] = txtuid
;
1625 n2
[n2args
- 3] = "--mapped-gid";
1627 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1628 if (ret
< 0 || ret
>= 20) {
1631 _exit(EXIT_FAILURE
);
1634 n2
[n2args
- 2] = txtgid
;
1635 n2
[n2args
- 1] = NULL
;
1640 execvp(tpath
, newargv
);
1641 SYSERROR("Failed to execute template %s", tpath
);
1642 _exit(EXIT_FAILURE
);
1645 ret
= wait_for_pid(pid
);
1647 ERROR("Failed to create container from template");
1654 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1663 unsigned char md_value
[EVP_MAX_MD_SIZE
];
1667 f
= fopen(path
, "r");
1671 ret
= fseek(f
, 0, SEEK_END
);
1680 ret
= fseek(f
, 0, SEEK_SET
);
1684 ret
= fseek(f
, 0, SEEK_SET
);
1689 contents
= malloc(flen
+ 1);
1693 len
= fread(contents
, 1, flen
, f
);
1695 goto out_free_contents
;
1697 contents
[flen
] = '\0';
1702 goto out_free_contents
;
1705 tpath
= get_template_path(t
);
1707 ERROR("Invalid template \"%s\" specified", t
);
1708 goto out_free_contents
;
1711 ret
= sha1sum_file(tpath
, md_value
, &md_len
);
1713 ERROR("Failed to get sha1sum of %s", tpath
);
1715 goto out_free_contents
;
1720 f
= fopen(path
, "w");
1722 SYSERROR("Reopening config for writing");
1727 fprintf(f
, "# Template used to create this container: %s\n", t
);
1729 fprintf(f
, "# Parameters passed to the template:");
1731 fprintf(f
, " %s", *argv
);
1738 fprintf(f
, "# Template script checksum (SHA-1): ");
1739 for (i
=0; i
<md_len
; i
++)
1740 fprintf(f
, "%02x", md_value
[i
]);
1743 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1744 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1745 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1746 fprintf(f
, "# (Be aware this has security implications)\n\n");
1747 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1748 SYSERROR("Writing original contents");
1768 SYSERROR("Error prepending header");
1775 static void lxcapi_clear_config(struct lxc_container
*c
)
1777 if (!c
|| !c
->lxc_conf
)
1780 lxc_conf_free(c
->lxc_conf
);
1784 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1788 * create a container with the given parameters.
1789 * @c: container to be created. It has the lxcpath, name, and a starting
1790 * configuration already set
1791 * @t: the template to execute to instantiate the root filesystem and
1792 * adjust the configuration.
1793 * @bdevtype: backing store type to use. If NULL, dir will be used.
1794 * @specs: additional parameters for the backing store, i.e. LVM vg to
1797 * @argv: the arguments to pass to the template, terminated by NULL. If no
1798 * arguments, you can just pass NULL.
1800 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1801 const char *bdevtype
, struct bdev_specs
*specs
,
1802 int flags
, char *const argv
[])
1807 bool ret
= false, rootfs_managed
= true;
1814 tpath
= get_template_path(t
);
1816 ERROR("Unknown template \"%s\"", t
);
1821 /* If a template is passed in, and the rootfs already is defined in the
1822 * container config and exists, then the caller is trying to create an
1823 * existing container. Return an error, but do NOT delete the container.
1825 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1826 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1827 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1833 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1834 ERROR("Error loading default configuration file %s",
1835 lxc_global_config_value("lxc.default_config"));
1840 if (!create_container_dir(c
))
1843 if (c
->lxc_conf
->rootfs
.path
)
1844 rootfs_managed
= false;
1846 /* If both template and rootfs.path are set, template is setup as
1847 * rootfs.path. The container is already created if we have a config and
1848 * rootfs.path is accessible
1850 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1851 /* No template passed in and rootfs does not exist. */
1852 if (!c
->save_config(c
, NULL
)) {
1853 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1860 /* Rootfs passed into configuration, but does not exist. */
1861 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1864 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1865 /* Rootfs already existed, user just wanted to save the loaded
1868 if (!c
->save_config(c
, NULL
))
1869 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1875 /* Mark that this container is being created */
1876 partial_fd
= create_partial(c
);
1880 /* No need to get disk lock bc we have the partial lock. */
1884 /* Create the storage.
1885 * Note we can't do this in the same task as we use to execute the
1886 * template because of the way zfs works.
1887 * After you 'zfs create', zfs mounts the fs only in the initial
1892 SYSERROR("Failed to fork task for container creation template");
1896 if (pid
== 0) { /* child */
1897 struct lxc_storage
*bdev
= NULL
;
1899 bdev
= do_storage_create(c
, bdevtype
, specs
);
1901 ERROR("Failed to create %s storage for %s",
1902 bdevtype
? bdevtype
: "(none)", c
->name
);
1903 _exit(EXIT_FAILURE
);
1906 /* Save config file again to store the new rootfs location. */
1907 if (!do_lxcapi_save_config(c
, NULL
)) {
1908 ERROR("Failed to save initial config for %s", c
->name
);
1909 /* Parent task won't see the storage driver in the
1910 * config so we delete it.
1912 bdev
->ops
->umount(bdev
);
1913 bdev
->ops
->destroy(bdev
);
1914 _exit(EXIT_FAILURE
);
1917 _exit(EXIT_SUCCESS
);
1920 if (wait_for_pid(pid
) != 0)
1923 /* Reload config to get the rootfs. */
1924 lxc_conf_free(c
->lxc_conf
);
1927 if (!load_config_locked(c
, c
->configfile
))
1930 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1933 /* Now clear out the lxc_conf we have, reload from the created
1936 do_lxcapi_clear_config(c
);
1939 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1940 ERROR("Failed to prepend header to config file");
1945 ret
= load_config_locked(c
, c
->configfile
);
1949 remove_partial(c
, partial_fd
);
1953 bool reset_managed
= c
->lxc_conf
->rootfs
.managed
;
1956 * Ensure that we don't destroy storage we didn't create
1959 if (!rootfs_managed
)
1960 c
->lxc_conf
->rootfs
.managed
= false;
1961 container_destroy(c
, NULL
);
1962 c
->lxc_conf
->rootfs
.managed
= reset_managed
;
1970 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1971 const char *bdevtype
, struct bdev_specs
*specs
,
1972 int flags
, char *const argv
[])
1976 current_config
= c
? c
->lxc_conf
: NULL
;
1978 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1979 current_config
= NULL
;
1983 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1987 int rebootsignal
= SIGINT
;
1992 if (!do_lxcapi_is_running(c
))
1995 pid
= do_lxcapi_init_pid(c
);
1999 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2000 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2002 ret
= kill(pid
, rebootsignal
);
2004 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2011 WRAP_API(bool, lxcapi_reboot
)
2013 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
2017 int rebootsignal
= SIGINT
, state_client_fd
= -1;
2018 lxc_state_t states
[MAX_STATE
] = {0};
2023 if (!do_lxcapi_is_running(c
))
2026 pid
= do_lxcapi_init_pid(c
);
2030 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2031 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2033 /* Add a new state client before sending the shutdown signal so that we
2034 * don't miss a state.
2037 states
[RUNNING
] = 2;
2038 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2043 if (state_client_fd
< 0)
2049 if (ret
< MAX_STATE
)
2053 /* Send reboot signal to container. */
2054 killret
= kill(pid
, rebootsignal
);
2056 if (state_client_fd
>= 0)
2057 close(state_client_fd
);
2059 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2062 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2067 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2068 close(state_client_fd
);
2072 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2079 WRAP_API_1(bool, lxcapi_reboot2
, int)
2081 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2085 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2086 lxc_state_t states
[MAX_STATE
] = {0};
2091 if (!do_lxcapi_is_running(c
))
2094 pid
= do_lxcapi_init_pid(c
);
2098 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2099 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2100 haltsignal
= c
->lxc_conf
->haltsignal
;
2101 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2102 haltsignal
= (SIGRTMIN
+ 3);
2104 /* Add a new state client before sending the shutdown signal so that we
2105 * don't miss a state.
2108 states
[STOPPED
] = 1;
2109 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2114 if (state_client_fd
< 0)
2120 if (ret
< MAX_STATE
)
2124 /* Send shutdown signal to container. */
2125 killret
= kill(pid
, haltsignal
);
2127 if (state_client_fd
>= 0)
2128 close(state_client_fd
);
2130 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2133 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2138 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2139 close(state_client_fd
);
2143 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2150 WRAP_API_1(bool, lxcapi_shutdown
, int)
2152 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2153 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2162 current_config
= c
->lxc_conf
;
2165 * since we're going to wait for create to finish, I don't think we
2166 * need to get a copy of the arguments.
2168 va_start(ap
, flags
);
2169 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2172 ERROR("Failed to allocate memory");
2176 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2180 current_config
= NULL
;
2184 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2186 if (!strcmp(key
, "lxc.cgroup"))
2187 return clear_unexp_config_line(conf
, key
, true);
2189 if (!strcmp(key
, "lxc.network"))
2190 return clear_unexp_config_line(conf
, key
, true);
2192 if (!strcmp(key
, "lxc.net"))
2193 return clear_unexp_config_line(conf
, key
, true);
2195 /* Clear a network with a specific index. */
2196 if (!strncmp(key
, "lxc.net.", 8)) {
2201 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2203 return clear_unexp_config_line(conf
, key
, true);
2206 if (!strcmp(key
, "lxc.hook"))
2207 return clear_unexp_config_line(conf
, key
, true);
2209 return clear_unexp_config_line(conf
, key
, false);
2212 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2216 struct lxc_config_t
*config
;
2218 if (!c
|| !c
->lxc_conf
)
2221 if (container_mem_lock(c
))
2224 config
= lxc_get_config(key
);
2225 /* Verify that the config key exists and that it has a callback
2228 if (config
&& config
->clr
)
2229 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2232 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2234 container_mem_unlock(c
);
2238 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2240 static inline bool enter_net_ns(struct lxc_container
*c
)
2242 pid_t pid
= do_lxcapi_init_pid(c
);
2247 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2248 (access("/proc/self/ns/user", F_OK
) == 0))
2249 if (!switch_to_ns(pid
, "user"))
2252 return switch_to_ns(pid
, "net");
2255 /* Used by qsort and bsearch functions for comparing names. */
2256 static inline int string_cmp(char **first
, char **second
)
2258 return strcmp(*first
, *second
);
2261 /* Used by qsort and bsearch functions for comparing container names. */
2262 static inline int container_cmp(struct lxc_container
**first
,
2263 struct lxc_container
**second
)
2265 return strcmp((*first
)->name
, (*second
)->name
);
2268 static bool add_to_array(char ***names
, char *cname
, int pos
)
2270 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2272 ERROR("Out of memory");
2277 newnames
[pos
] = strdup(cname
);
2281 /* Sort the array as we will use binary search on it. */
2282 qsort(newnames
, pos
+ 1, sizeof(char *),
2283 (int (*)(const void *, const void *))string_cmp
);
2288 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2291 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2293 ERROR("Out of memory");
2300 /* Sort the array as we will use binary search on it. */
2302 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2303 (int (*)(const void *, const void *))container_cmp
);
2308 static char** get_from_array(char ***names
, char *cname
, int size
)
2310 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2313 static bool array_contains(char ***names
, char *cname
, int size
)
2315 if(get_from_array(names
, cname
, size
) != NULL
)
2321 static bool remove_from_array(char ***names
, char *cname
, int size
)
2323 char **result
= get_from_array(names
, cname
, size
);
2324 if (result
!= NULL
) {
2332 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2335 int i
, count
= 0, pipefd
[2];
2336 char **interfaces
= NULL
;
2337 char interface
[IFNAMSIZ
];
2339 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2344 SYSERROR("Failed to fork task to get interfaces information");
2350 if (pid
== 0) { /* child */
2351 int ret
= 1, nbytes
;
2352 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2354 /* close the read-end of the pipe */
2357 if (!enter_net_ns(c
)) {
2358 SYSERROR("Failed to enter network namespace");
2362 /* Grab the list of interfaces */
2363 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2364 SYSERROR("Failed to get interfaces list");
2368 /* Iterate through the interfaces */
2369 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2370 tempIfAddr
= tempIfAddr
->ifa_next
) {
2371 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2382 netns_freeifaddrs(interfaceArray
);
2384 /* close the write-end of the pipe, thus sending EOF to the reader */
2389 /* close the write-end of the pipe */
2392 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2393 interface
[IFNAMSIZ
- 1] = '\0';
2395 if (array_contains(&interfaces
, interface
, count
))
2398 if (!add_to_array(&interfaces
, interface
, count
))
2399 ERROR("Failed to add \"%s\" to array", interface
);
2404 if (wait_for_pid(pid
) != 0) {
2405 for (i
= 0; i
< count
; i
++)
2406 free(interfaces
[i
]);
2412 /* close the read-end of the pipe */
2415 /* Append NULL to the array */
2417 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2422 WRAP_API(char **, lxcapi_get_interfaces
)
2424 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2425 const char *family
, int scope
)
2430 char address
[INET6_ADDRSTRLEN
];
2432 char **addresses
= NULL
;
2434 ret
= pipe2(pipefd
, O_CLOEXEC
);
2436 SYSERROR("Failed to create pipe");
2442 SYSERROR("Failed to create new process");
2450 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2451 char *address_ptr
= NULL
;
2452 void *tempAddrPtr
= NULL
;
2453 struct netns_ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2455 /* close the read-end of the pipe */
2458 if (!enter_net_ns(c
)) {
2459 SYSERROR("Failed to attach to network namespace");
2463 /* Grab the list of interfaces */
2464 if (netns_getifaddrs(&interfaceArray
, -1, &(bool){false})) {
2465 SYSERROR("Failed to get interfaces list");
2469 /* Iterate through the interfaces */
2470 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2471 tempIfAddr
= tempIfAddr
->ifa_next
) {
2472 if (tempIfAddr
->ifa_addr
== NULL
)
2475 #pragma GCC diagnostic push
2476 #pragma GCC diagnostic ignored "-Wcast-align"
2478 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2479 if (family
&& strcmp(family
, "inet"))
2482 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2484 if (family
&& strcmp(family
, "inet6"))
2487 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2490 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2493 #pragma GCC diagnostic pop
2495 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2497 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2500 address_ptr
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2501 tempAddrPtr
, addressOutputBuffer
,
2502 sizeof(addressOutputBuffer
));
2506 nbytes
= lxc_write_nointr(pipefd
[1], address_ptr
, INET6_ADDRSTRLEN
);
2507 if (nbytes
!= INET6_ADDRSTRLEN
) {
2508 SYSERROR("Failed to send ipv6 address \"%s\"",
2520 netns_freeifaddrs(interfaceArray
);
2522 /* close the write-end of the pipe, thus sending EOF to the reader */
2527 /* close the write-end of the pipe */
2530 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2531 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2533 if (!add_to_array(&addresses
, address
, count
))
2534 ERROR("PARENT: add_to_array failed");
2539 if (wait_for_pid(pid
) != 0) {
2540 for (i
= 0; i
< count
; i
++)
2547 /* close the read-end of the pipe */
2550 /* Append NULL to the array */
2552 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2557 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2559 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2562 struct lxc_config_t
*config
;
2564 if (!c
|| !c
->lxc_conf
)
2567 if (container_mem_lock(c
))
2570 config
= lxc_get_config(key
);
2571 /* Verify that the config key exists and that it has a callback
2574 if (config
&& config
->get
)
2575 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2577 container_mem_unlock(c
);
2581 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2583 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2587 if (!c
|| !c
->lxc_conf
)
2590 if (container_mem_lock(c
))
2593 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2594 container_mem_unlock(c
);
2598 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2600 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2604 /* List all config items. */
2606 return lxc_list_config_items(retv
, inlen
);
2608 if (!c
|| !c
->lxc_conf
)
2611 if (container_mem_lock(c
))
2614 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2615 * This is an intelligent result to show which keys are valid given the
2616 * type of nic it is.
2618 if (strncmp(key
, "lxc.net.", 8) == 0)
2619 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2621 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2623 container_mem_unlock(c
);
2627 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2629 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2632 bool ret
= false, need_disklock
= false;
2635 alt_file
= c
->configfile
;
2640 /* If we haven't yet loaded a config, load the stock config. */
2642 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2643 ERROR("Error loading default configuration file %s "
2645 lxc_global_config_value("lxc.default_config"),
2651 if (!create_container_dir(c
))
2654 /* If we're writing to the container's config file, take the disk lock.
2655 * Otherwise just take the memlock to protect the struct lxc_container
2656 * while we're traversing it.
2658 if (strcmp(c
->configfile
, alt_file
) == 0)
2659 need_disklock
= true;
2662 lret
= container_disk_lock(c
);
2664 lret
= container_mem_lock(c
);
2668 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2669 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2673 lret
= write_config(fd
, c
->lxc_conf
);
2682 container_disk_unlock(c
);
2684 container_mem_unlock(c
);
2689 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2692 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2698 char path
[PATH_MAX
];
2699 char newpath
[PATH_MAX
];
2700 int fd
, ret
, n
= 0, v
= 0;
2702 size_t len
= 0, bytes
= 0;
2704 if (container_disk_lock(c0
))
2707 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2708 if (ret
< 0 || ret
> PATH_MAX
)
2711 ret
= snprintf(newpath
, PATH_MAX
, "%s\n%s\n", c
->config_path
, c
->name
);
2712 if (ret
< 0 || ret
> PATH_MAX
)
2715 /* If we find an lxc-snapshot file using the old format only listing the
2716 * number of snapshots we will keep using it. */
2717 f1
= fopen(path
, "r");
2719 n
= fscanf(f1
, "%d", &v
);
2721 if (n
== 1 && v
== 0) {
2724 SYSERROR("Failed to remove \"%s\"", path
);
2732 f1
= fopen(path
, "w");
2736 if (fprintf(f1
, "%d\n", v
) < 0) {
2737 ERROR("Error writing new snapshots value");
2744 SYSERROR("Error writing to or closing snapshots file");
2748 /* Here we know that we have or can use an lxc-snapshot file
2749 * using the new format. */
2751 f1
= fopen(path
, "a");
2755 if (fprintf(f1
, "%s", newpath
) < 0) {
2756 ERROR("Error writing new snapshots entry");
2759 SYSERROR("Error writing to or closing snapshots file");
2765 SYSERROR("Error writing to or closing snapshots file");
2769 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2772 if (fstat(fd
, &fbuf
) < 0) {
2777 if (fbuf
.st_size
!= 0) {
2778 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2779 if (buf
== MAP_FAILED
) {
2780 SYSERROR("Failed to create mapping %s", path
);
2785 len
= strlen(newpath
);
2786 while ((del
= strstr((char *)buf
, newpath
))) {
2787 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2791 lxc_strmunmap(buf
, fbuf
.st_size
);
2792 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2793 SYSERROR("Failed to truncate file %s", path
);
2802 /* If the lxc-snapshot file is empty, remove it. */
2803 if (stat(path
, &fbuf
) < 0)
2806 if (!fbuf
.st_size
) {
2809 SYSERROR("Failed to remove \"%s\"", path
);
2816 container_disk_unlock(c0
);
2820 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2822 struct lxc_container
*p
;
2823 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[PATH_MAX
];
2824 size_t pathlen
= 0, namelen
= 0;
2828 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends",
2829 c
->config_path
, c
->name
);
2830 if (ret
< 0 || ret
>= PATH_MAX
) {
2831 ERROR("Path name too long");
2835 f
= fopen(path
, "r");
2839 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2840 if (getline(&lxcname
, &namelen
, f
) == -1) {
2841 ERROR("badly formatted file %s", path
);
2845 remove_trailing_newlines(lxcpath
);
2846 remove_trailing_newlines(lxcname
);
2848 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2849 ERROR("Unable to find dependent container %s:%s",
2854 if (!mod_rdep(p
, c
, inc
))
2855 ERROR("Failed to update snapshots file for %s:%s",
2858 lxc_container_put(p
);
2867 static bool has_fs_snapshots(struct lxc_container
*c
)
2870 char path
[PATH_MAX
];
2875 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_snapshots", c
->config_path
,
2877 if (ret
< 0 || ret
> PATH_MAX
)
2880 /* If the file doesn't exist there are no snapshots. */
2881 if (stat(path
, &fbuf
) < 0)
2886 f
= fopen(path
, "r");
2890 ret
= fscanf(f
, "%d", &v
);
2892 /* TODO: Figure out what to do with the return value of fscanf. */
2894 INFO("Container uses new lxc-snapshots format %s", path
);
2903 static bool has_snapshots(struct lxc_container
*c
)
2905 char path
[PATH_MAX
];
2906 struct dirent
*direntp
;
2910 if (!get_snappath_dir(c
, path
))
2913 dir
= opendir(path
);
2917 while ((direntp
= readdir(dir
))) {
2918 if (!strcmp(direntp
->d_name
, "."))
2921 if (!strcmp(direntp
->d_name
, ".."))
2931 static bool do_destroy_container(struct lxc_conf
*conf
) {
2934 if (am_guest_unpriv()) {
2935 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2936 "storage_destroy_wrapper");
2943 return storage_destroy(conf
);
2946 static int lxc_rmdir_onedev_wrapper(void *data
)
2948 char *arg
= (char *) data
;
2949 return lxc_rmdir_onedev(arg
, "snaps");
2952 static int lxc_unlink_exec_wrapper(void *data
)
2958 static bool container_destroy(struct lxc_container
*c
,
2959 struct lxc_storage
*storage
)
2963 struct lxc_conf
*conf
;
2968 if (!c
|| !do_lxcapi_is_defined(c
))
2972 if (container_disk_lock(c
))
2975 if (!is_stopped(c
)) {
2976 /* We should queue some sort of error - in c->error_string? */
2977 ERROR("container %s is not stopped", c
->name
);
2981 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2982 /* Start of environment variable setup for hooks */
2983 if (setenv("LXC_NAME", c
->name
, 1))
2984 SYSERROR("Failed to set environment variable for container name");
2986 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2987 SYSERROR("Failed to set environment variable for config path");
2989 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2990 SYSERROR("Failed to set environment variable for rootfs mount");
2992 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2993 SYSERROR("Failed to set environment variable for rootfs mount");
2995 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2996 SYSERROR("Failed to set environment variable for console path");
2998 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2999 SYSERROR("Failed to set environment variable for console log");
3000 /* End of environment variable setup for hooks */
3002 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
3003 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
3008 if (current_config
&& conf
== current_config
) {
3009 current_config
= NULL
;
3011 if (conf
->logfd
!= -1) {
3017 /* LXC is not managing the storage of the container. */
3018 if (conf
&& !conf
->rootfs
.managed
)
3021 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
3022 if (!do_destroy_container(conf
)) {
3023 ERROR("Error destroying rootfs for %s", c
->name
);
3026 INFO("Destroyed rootfs for %s", c
->name
);
3029 mod_all_rdeps(c
, false);
3031 p1
= do_lxcapi_get_config_path(c
);
3040 * strlen("config") = 6
3044 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3047 ERROR("Failed to allocate memory");
3051 /* For an overlay container the rootfs is considered immutable and
3052 * cannot be removed when restoring from a snapshot.
3054 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3055 !strcmp(storage
->type
, "overlayfs")) &&
3056 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3057 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3058 if (ret
< 0 || (size_t)ret
>= len
)
3061 if (am_guest_unpriv())
3062 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3063 "lxc_unlink_exec_wrapper");
3067 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3071 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3077 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3078 if (ret
< 0 || (size_t)ret
>= len
)
3081 if (am_guest_unpriv())
3082 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3083 "lxc_rmdir_onedev_wrapper");
3085 ret
= lxc_rmdir_onedev(path
, "snaps");
3087 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3091 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3100 container_disk_unlock(c
);
3104 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3106 if (!c
|| !lxcapi_is_defined(c
))
3109 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3110 if (has_snapshots(c
)) {
3111 ERROR("Container %s has snapshots; not removing", c
->name
);
3115 if (has_fs_snapshots(c
)) {
3116 ERROR("container %s has snapshots on its rootfs", c
->name
);
3121 return container_destroy(c
, NULL
);
3124 WRAP_API(bool, lxcapi_destroy
)
3126 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3128 if (!c
|| !lxcapi_is_defined(c
))
3131 if (!lxcapi_snapshot_destroy_all(c
)) {
3132 ERROR("Error deleting all snapshots");
3136 return lxcapi_destroy(c
);
3139 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3141 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3145 struct lxc_config_t
*config
;
3148 config
= lxc_get_config(key
);
3152 ret
= config
->set(key
, v
, conf
, NULL
);
3156 if (lxc_config_value_empty(v
))
3157 do_clear_unexp_config_line(conf
, key
);
3159 bret
= do_append_unexp_config_line(conf
, key
, v
);
3166 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3172 c
->lxc_conf
= lxc_conf_init();
3177 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3184 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3191 if (container_mem_lock(c
))
3194 b
= do_set_config_item_locked(c
, key
, v
);
3196 container_mem_unlock(c
);
3200 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3202 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3204 if (!c
|| !c
->configfile
)
3207 return strdup(c
->configfile
);
3210 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3212 if (!c
|| !c
->config_path
)
3215 return (const char *)(c
->config_path
);
3220 * Just recalculate the c->configfile based on the
3221 * c->config_path, which must be set.
3222 * The lxc_container must be locked or not yet public.
3224 static bool set_config_filename(struct lxc_container
*c
)
3229 if (!c
->config_path
)
3232 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3233 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3234 newpath
= malloc(len
);
3238 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3239 if (ret
< 0 || ret
>= len
) {
3240 fprintf(stderr
, "Error printing out config file name\n");
3245 free(c
->configfile
);
3246 c
->configfile
= newpath
;
3251 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3255 char *oldpath
= NULL
;
3260 if (container_mem_lock(c
))
3265 ERROR("Out of memory setting new lxc path");
3271 oldpath
= c
->config_path
;
3274 /* Since we've changed the config path, we have to change the
3275 * config file name too */
3276 if (!set_config_filename(c
)) {
3277 ERROR("Out of memory setting new config filename");
3279 free(c
->config_path
);
3280 c
->config_path
= oldpath
;
3286 container_mem_unlock(c
);
3290 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3292 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3295 struct cgroup_ops
*cgroup_ops
;
3303 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3307 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3309 cgroup_exit(cgroup_ops
);
3314 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3316 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3319 struct cgroup_ops
*cgroup_ops
;
3327 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3331 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3334 cgroup_exit(cgroup_ops
);
3339 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3341 const char *lxc_get_global_config_item(const char *key
)
3343 return lxc_global_config_value(key
);
3346 const char *lxc_get_version(void)
3351 static int copy_file(const char *old
, const char *new)
3358 if (file_exists(new)) {
3359 ERROR("copy destination %s exists", new);
3363 ret
= stat(old
, &sbuf
);
3365 INFO("Error stat'ing %s", old
);
3369 in
= open(old
, O_RDONLY
);
3371 SYSERROR("Error opening original file %s", old
);
3375 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3377 SYSERROR("Error opening new file %s", new);
3383 len
= lxc_read_nointr(in
, buf
, 8096);
3385 SYSERROR("Error reading old file %s", old
);
3392 ret
= lxc_write_nointr(out
, buf
, len
);
3393 if (ret
< len
) { /* should we retry? */
3394 SYSERROR("Error: write to new file %s was interrupted", new);
3402 /* We set mode, but not owner/group. */
3403 ret
= chmod(new, sbuf
.st_mode
);
3405 SYSERROR("Error setting mode on %s", new);
3417 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3419 __do_free
char *cpath
= NULL
;
3421 struct lxc_list
*it
;
3423 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3424 cpath
= must_realloc(NULL
, len
);
3425 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3426 if (ret
< 0 || ret
>= len
)
3429 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3430 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3431 char *hookname
= it
->elem
;
3432 char *fname
= strrchr(hookname
, '/');
3433 char tmppath
[PATH_MAX
];
3434 if (!fname
) /* relative path - we don't support, but maybe we should */
3437 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3438 /* this hook is public - ignore */
3442 /* copy the script, and change the entry in confile */
3443 ret
= snprintf(tmppath
, PATH_MAX
, "%s/%s/%s",
3444 c
->config_path
, c
->name
, fname
+1);
3445 if (ret
< 0 || ret
>= PATH_MAX
)
3448 ret
= copy_file(it
->elem
, tmppath
);
3454 it
->elem
= strdup(tmppath
);
3456 ERROR("out of memory copying hook path");
3462 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3463 c
->config_path
, oldc
->name
, c
->name
)) {
3464 ERROR("Error saving new hooks in clone");
3468 do_lxcapi_save_config(c
, NULL
);
3473 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3475 char newpath
[PATH_MAX
];
3476 char *oldpath
= oldc
->lxc_conf
->fstab
;
3482 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3484 char *p
= strrchr(oldpath
, '/');
3488 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s%s",
3489 c
->config_path
, c
->name
, p
);
3490 if (ret
< 0 || ret
>= PATH_MAX
) {
3491 ERROR("error printing new path for %s", oldpath
);
3495 if (file_exists(newpath
)) {
3496 ERROR("error: fstab file %s exists", newpath
);
3500 if (copy_file(oldpath
, newpath
) < 0) {
3501 ERROR("error: copying %s to %s", oldpath
, newpath
);
3505 free(c
->lxc_conf
->fstab
);
3507 c
->lxc_conf
->fstab
= strdup(newpath
);
3508 if (!c
->lxc_conf
->fstab
) {
3509 ERROR("error: allocating pathname");
3513 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3514 ERROR("error saving new lxctab");
3521 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3523 char path0
[PATH_MAX
], path1
[PATH_MAX
];
3526 ret
= snprintf(path0
, PATH_MAX
, "%s/%s/lxc_rdepends", c0
->config_path
,
3528 if (ret
< 0 || ret
>= PATH_MAX
) {
3529 WARN("Error copying reverse dependencies");
3533 ret
= snprintf(path1
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3535 if (ret
< 0 || ret
>= PATH_MAX
) {
3536 WARN("Error copying reverse dependencies");
3540 if (copy_file(path0
, path1
) < 0) {
3541 INFO("Error copying reverse dependencies");
3546 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3549 char path
[PATH_MAX
];
3553 ret
= snprintf(path
, PATH_MAX
, "%s/%s/lxc_rdepends", c
->config_path
,
3555 if (ret
< 0 || ret
>= PATH_MAX
)
3558 f
= fopen(path
, "a");
3564 /* If anything goes wrong, just return an error. */
3565 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3575 * If the fs natively supports snapshot clones with no penalty,
3576 * then default to those even if not requested.
3577 * Currently we only do this for btrfs.
3579 bool should_default_to_snapshot(struct lxc_container
*c0
,
3580 struct lxc_container
*c1
)
3582 __do_free
char *p0
= NULL
, *p1
= NULL
;
3584 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3585 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3586 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3588 p0
= must_realloc(NULL
, l0
+ 1);
3589 p1
= must_realloc(NULL
, l1
+ 1);
3590 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3591 if (ret
< 0 || ret
>= l0
)
3594 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3595 if (ret
< 0 || ret
>= l1
)
3598 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3601 if (is_btrfs_subvol(rootfs
) <= 0)
3604 return btrfs_same_fs(p0
, p1
) == 0;
3607 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3608 const char *newtype
, int flags
, const char *bdevdata
,
3611 struct lxc_storage
*bdev
;
3614 if (should_default_to_snapshot(c0
, c
))
3615 flags
|= LXC_CLONE_SNAPSHOT
;
3617 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3618 bdevdata
, newsize
, &need_rdep
);
3620 ERROR("Error copying storage.");
3624 /* Set new rootfs. */
3625 free(c
->lxc_conf
->rootfs
.path
);
3626 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3629 if (!c
->lxc_conf
->rootfs
.path
) {
3630 ERROR("Out of memory while setting storage path.");
3634 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3635 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3636 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3637 c
->lxc_conf
->rootfs
.path
)) {
3638 ERROR("Error saving new rootfs to cloned config.");
3642 if (flags
& LXC_CLONE_SNAPSHOT
)
3643 copy_rdepends(c
, c0
);
3646 if (!add_rdepends(c
, c0
))
3647 WARN("Error adding reverse dependency from %s to %s",
3651 mod_all_rdeps(c
, true);
3656 struct clone_update_data
{
3657 struct lxc_container
*c0
;
3658 struct lxc_container
*c1
;
3663 static int clone_update_rootfs(struct clone_update_data
*data
)
3665 struct lxc_container
*c0
= data
->c0
;
3666 struct lxc_container
*c
= data
->c1
;
3667 int flags
= data
->flags
;
3668 char **hookargs
= data
->hookargs
;
3670 char path
[PATH_MAX
];
3671 struct lxc_storage
*bdev
;
3673 struct lxc_conf
*conf
= c
->lxc_conf
;
3675 /* update hostname in rootfs */
3676 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3678 if (setgid(0) < 0) {
3679 ERROR("Failed to setgid to 0");
3683 if (setuid(0) < 0) {
3684 ERROR("Failed to setuid to 0");
3688 if (setgroups(0, NULL
) < 0)
3689 WARN("Failed to clear groups");
3691 if (unshare(CLONE_NEWNS
) < 0)
3694 bdev
= storage_init(c
->lxc_conf
);
3698 if (strcmp(bdev
->type
, "dir") != 0) {
3699 if (unshare(CLONE_NEWNS
) < 0) {
3700 ERROR("error unsharing mounts");
3705 if (detect_shared_rootfs()) {
3706 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3707 SYSERROR("Failed to make / rslave");
3708 ERROR("Continuing...");
3712 if (bdev
->ops
->mount(bdev
) < 0) {
3716 } else { /* TODO come up with a better way */
3718 bdev
->dest
= strdup(lxc_storage_get_path(bdev
->src
, bdev
->type
));
3721 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3722 /* Start of environment variable setup for hooks */
3723 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3724 SYSERROR("failed to set environment variable for source container name");
3726 if (setenv("LXC_NAME", c
->name
, 1))
3727 SYSERROR("failed to set environment variable for container name");
3729 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3730 SYSERROR("failed to set environment variable for config path");
3732 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3733 SYSERROR("failed to set environment variable for rootfs mount");
3735 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3736 SYSERROR("failed to set environment variable for rootfs mount");
3738 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3739 ERROR("Error executing clone hook for %s", c
->name
);
3745 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3746 ret
= snprintf(path
, PATH_MAX
, "%s/etc/hostname", bdev
->dest
);
3749 if (ret
< 0 || ret
>= PATH_MAX
)
3752 if (!file_exists(path
))
3755 if (!(fout
= fopen(path
, "w"))) {
3756 SYSERROR("unable to open %s: ignoring", path
);
3760 if (fprintf(fout
, "%s", c
->name
) < 0) {
3765 if (fclose(fout
) < 0)
3774 static int clone_update_rootfs_wrapper(void *data
)
3776 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3777 return clone_update_rootfs(arg
);
3781 * We want to support:
3782 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3783 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3785 -s [ implies overlay]
3788 only rootfs gets converted (copied/snapshotted) on clone.
3791 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3793 char *p
= strrchr(path
, '/');
3800 ret
= do_create_container_dir(path
, conf
);
3806 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3807 const char *lxcpath
, int flags
,
3808 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3811 char newpath
[PATH_MAX
];
3813 struct clone_update_data data
;
3814 size_t saved_unexp_len
;
3816 int storage_copied
= 0;
3817 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3818 struct lxc_container
*c2
= NULL
;
3820 if (!c
|| !do_lxcapi_is_defined(c
))
3823 if (container_mem_lock(c
))
3825 if (!is_stopped(c
) && !(flags
& LXC_CLONE_ALLOW_RUNNING
)) {
3826 ERROR("error: Original container (%s) is running. Use --allowrunning if you want to force a snapshot of the running container.", c
->name
);
3830 /* Make sure the container doesn't yet exist. */
3835 lxcpath
= do_lxcapi_get_config_path(c
);
3837 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/config", lxcpath
, newname
);
3838 if (ret
< 0 || ret
>= PATH_MAX
) {
3839 SYSERROR("clone: failed making config pathname");
3843 if (file_exists(newpath
)) {
3844 ERROR("error: clone: %s exists", newpath
);
3848 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3849 if (ret
< 0 && errno
!= EEXIST
) {
3850 ERROR("Error creating container dir for %s", newpath
);
3854 /* Copy the configuration. Tweak it as needed. */
3855 if (c
->lxc_conf
->rootfs
.path
) {
3856 origroot
= c
->lxc_conf
->rootfs
.path
;
3857 c
->lxc_conf
->rootfs
.path
= NULL
;
3860 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3861 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3863 SYSERROR("Failed to open \"%s\"", newpath
);
3867 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3868 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3869 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3870 if (!c
->lxc_conf
->unexpanded_config
) {
3875 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3876 write_config(fd
, c
->lxc_conf
);
3879 c
->lxc_conf
->rootfs
.path
= origroot
;
3881 free(c
->lxc_conf
->unexpanded_config
);
3882 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3883 saved_unexp_conf
= NULL
;
3884 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3886 ret
= snprintf(newpath
, PATH_MAX
, "%s/%s/rootfs", lxcpath
, newname
);
3887 if (ret
< 0 || ret
>= PATH_MAX
) {
3888 SYSERROR("clone: failed making rootfs pathname");
3892 ret
= mkdir(newpath
, 0755);
3894 /* For an overlay container the rootfs is considered immutable
3895 * and will not have been removed when restoring from a
3898 if (errno
!= ENOENT
&&
3899 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3900 SYSERROR("Failed to create directory \"%s\"", newpath
);
3905 if (am_guest_unpriv()) {
3906 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3907 ERROR("Error chowning %s to container root", newpath
);
3912 c2
= lxc_container_new(newname
, lxcpath
);
3914 ERROR("clone: failed to create new container (%s %s)", newname
,
3919 /* copy/snapshot rootfs's */
3920 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3924 /* update utsname */
3925 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3926 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3927 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3929 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3930 ERROR("Error setting new hostname");
3936 ret
= copyhooks(c
, c2
);
3938 ERROR("error copying hooks");
3942 if (copy_fstab(c
, c2
) < 0) {
3943 ERROR("error copying fstab");
3947 /* update macaddrs */
3948 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3949 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3950 ERROR("Error updating mac addresses");
3955 /* Update absolute paths for overlay mount directories. */
3956 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3959 /* We've now successfully created c2's storage, so clear it out if we
3964 if (!c2
->save_config(c2
, NULL
))
3967 if ((pid
= fork()) < 0) {
3973 ret
= wait_for_pid(pid
);
3977 container_mem_unlock(c
);
3984 data
.hookargs
= hookargs
;
3986 if (am_guest_unpriv())
3987 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3988 &data
, "clone_update_rootfs_wrapper");
3990 ret
= clone_update_rootfs(&data
);
3992 _exit(EXIT_FAILURE
);
3994 container_mem_unlock(c
);
3995 _exit(EXIT_SUCCESS
);
3998 container_mem_unlock(c
);
4000 if (!storage_copied
)
4001 c2
->lxc_conf
->rootfs
.path
= NULL
;
4004 lxc_container_put(c2
);
4010 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
4011 const char *lxcpath
, int flags
,
4012 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
4015 struct lxc_container
* ret
;
4017 current_config
= c
? c
->lxc_conf
: NULL
;
4018 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
4019 current_config
= NULL
;
4024 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4026 struct lxc_storage
*bdev
;
4027 struct lxc_container
*newc
;
4029 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4032 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4033 ERROR("Renaming a container with snapshots is not supported");
4037 bdev
= storage_init(c
->lxc_conf
);
4039 ERROR("Failed to find original backing store type");
4043 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4046 lxc_container_put(newc
);
4050 if (newc
&& lxcapi_is_defined(newc
))
4051 lxc_container_put(newc
);
4053 if (!container_destroy(c
, NULL
)) {
4054 ERROR("Could not destroy existing container %s", c
->name
);
4061 WRAP_API_1(bool, lxcapi_rename
, const char *)
4063 static int lxcapi_attach(struct lxc_container
*c
,
4064 lxc_attach_exec_t exec_function
, void *exec_payload
,
4065 lxc_attach_options_t
*options
, pid_t
*attached_process
)
4072 current_config
= c
->lxc_conf
;
4074 ret
= lxc_attach(c
, exec_function
, exec_payload
, options
,
4076 current_config
= NULL
;
4080 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
,
4081 lxc_attach_options_t
*options
,
4082 const char *program
,
4083 const char *const argv
[])
4085 lxc_attach_command_t command
;
4092 command
.program
= (char *)program
;
4093 command
.argv
= (char **)argv
;
4095 ret
= lxc_attach(c
, lxc_attach_run_command
, &command
, options
, &pid
);
4099 return lxc_wait_for_pid_status(pid
);
4102 static int lxcapi_attach_run_wait(struct lxc_container
*c
,
4103 lxc_attach_options_t
*options
,
4104 const char *program
, const char *const argv
[])
4108 current_config
= c
? c
->lxc_conf
: NULL
;
4109 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4110 current_config
= NULL
;
4115 static int get_next_index(const char *lxcpath
, char *cname
)
4117 __do_free
char *fname
= NULL
;
4121 fname
= must_realloc(NULL
, strlen(lxcpath
) + 20);
4124 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4126 ret
= stat(fname
, &sb
);
4134 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4139 * If the old style snapshot path exists, use it
4140 * /var/lib/lxc -> /var/lib/lxcsnaps
4142 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps", c
->config_path
);
4143 if (ret
< 0 || ret
>= PATH_MAX
)
4146 if (dir_exists(snappath
)) {
4147 ret
= snprintf(snappath
, PATH_MAX
, "%ssnaps/%s", c
->config_path
, c
->name
);
4148 if (ret
< 0 || ret
>= PATH_MAX
)
4155 * Use the new style path
4156 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4158 ret
= snprintf(snappath
, PATH_MAX
, "%s/%s/snaps", c
->config_path
, c
->name
);
4159 if (ret
< 0 || ret
>= PATH_MAX
)
4165 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4167 __do_free
char *dfnam
= NULL
;
4171 struct lxc_container
*c2
;
4172 char snappath
[PATH_MAX
], newname
[20];
4176 if (!c
|| !lxcapi_is_defined(c
))
4179 if (!storage_can_backup(c
->lxc_conf
)) {
4180 ERROR("%s's backing store cannot be backed up", c
->name
);
4181 ERROR("Your container must use another backing store type");
4185 if (!get_snappath_dir(c
, snappath
))
4188 i
= get_next_index(snappath
, c
->name
);
4190 if (mkdir_p(snappath
, 0755) < 0) {
4191 ERROR("Failed to create snapshot directory %s", snappath
);
4195 ret
= snprintf(newname
, 20, "snap%d", i
);
4196 if (ret
< 0 || ret
>= 20)
4200 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4201 * created in the original container
4203 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4204 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4205 if (storage_is_dir(c
->lxc_conf
)) {
4206 ERROR("Snapshot of directory-backed container requested");
4207 ERROR("Making a copy-clone. If you do want snapshots, then");
4208 ERROR("please create overlay clone first, snapshot that");
4209 ERROR("and keep the original container pristine");
4210 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4213 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4215 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4219 lxc_container_put(c2
);
4221 /* Now write down the creation time. */
4224 if (!localtime_r(&timer
, &tm_info
)) {
4225 ERROR("Failed to get localtime");
4229 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4231 dfnam
= must_realloc(NULL
, strlen(snappath
) + strlen(newname
) + 5);
4232 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4233 f
= fopen(dfnam
, "w");
4235 ERROR("Failed to open %s", dfnam
);
4239 if (fprintf(f
, "%s", buffer
) < 0) {
4240 SYSERROR("Writing timestamp");
4247 SYSERROR("Writing timestamp");
4252 __do_free
char *path
= NULL
;
4253 /* $p / $name / comment \0 */
4254 int len
= strlen(snappath
) + strlen(newname
) + 10;
4256 path
= must_realloc(NULL
, len
);
4257 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4258 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4264 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4266 static void lxcsnap_free(struct lxc_snapshot
*s
)
4269 free(s
->comment_pathname
);
4274 static char *get_snapcomment_path(char* snappath
, char *name
)
4276 /* $snappath/$name/comment */
4277 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4278 char *s
= malloc(len
);
4281 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4282 if (ret
< 0 || ret
>= len
) {
4291 static char *get_timestamp(char* snappath
, char *name
)
4293 char path
[PATH_MAX
], *s
= NULL
;
4297 ret
= snprintf(path
, PATH_MAX
, "%s/%s/ts", snappath
, name
);
4298 if (ret
< 0 || ret
>= PATH_MAX
)
4301 fin
= fopen(path
, "r");
4305 (void) fseek(fin
, 0, SEEK_END
);
4307 (void) fseek(fin
, 0, SEEK_SET
);
4312 if (fread(s
, 1, len
, fin
) != len
) {
4313 SYSERROR("reading timestamp");
4324 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4326 char snappath
[PATH_MAX
], path2
[PATH_MAX
];
4328 struct dirent
*direntp
;
4329 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4332 if (!c
|| !lxcapi_is_defined(c
))
4335 if (!get_snappath_dir(c
, snappath
)) {
4336 ERROR("path name too long");
4340 dir
= opendir(snappath
);
4342 INFO("Failed to open %s - assuming no snapshots", snappath
);
4346 while ((direntp
= readdir(dir
))) {
4347 if (!strcmp(direntp
->d_name
, "."))
4350 if (!strcmp(direntp
->d_name
, ".."))
4353 ret
= snprintf(path2
, PATH_MAX
, "%s/%s/config", snappath
, direntp
->d_name
);
4354 if (ret
< 0 || ret
>= PATH_MAX
) {
4355 ERROR("pathname too long");
4359 if (!file_exists(path2
))
4362 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4364 SYSERROR("Out of memory");
4369 snaps
[count
].free
= lxcsnap_free
;
4370 snaps
[count
].name
= strdup(direntp
->d_name
);
4371 if (!snaps
[count
].name
)
4374 snaps
[count
].lxcpath
= strdup(snappath
);
4375 if (!snaps
[count
].lxcpath
) {
4376 free(snaps
[count
].name
);
4380 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4381 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4386 WARN("Failed to close directory");
4395 for (i
=0; i
<count
; i
++)
4396 lxcsnap_free(&snaps
[i
]);
4402 WARN("Failed to close directory");
4407 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4409 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4411 char clonelxcpath
[PATH_MAX
];
4413 struct lxc_container
*snap
, *rest
;
4414 struct lxc_storage
*bdev
;
4417 if (!c
|| !c
->name
|| !c
->config_path
)
4420 if (has_fs_snapshots(c
)) {
4421 ERROR("container rootfs has dependent snapshots");
4425 bdev
= storage_init(c
->lxc_conf
);
4427 ERROR("Failed to find original backing store type");
4431 /* For an overlay container the rootfs is considered immutable
4432 * and cannot be removed when restoring from a snapshot. We pass this
4433 * internal flag along to communicate this to various parts of the
4436 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4437 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4442 if (!get_snappath_dir(c
, clonelxcpath
)) {
4446 /* how should we lock this? */
4448 snap
= lxc_container_new(snapname
, clonelxcpath
);
4449 if (!snap
|| !lxcapi_is_defined(snap
)) {
4450 ERROR("Could not open snapshot %s", snapname
);
4453 lxc_container_put(snap
);
4459 if (!strcmp(c
->name
, newname
)) {
4460 if (!container_destroy(c
, bdev
)) {
4461 ERROR("Could not destroy existing container %s", newname
);
4462 lxc_container_put(snap
);
4468 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4469 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4471 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4472 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4474 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4477 if (rest
&& lxcapi_is_defined(rest
))
4481 lxc_container_put(rest
);
4483 lxc_container_put(snap
);
4487 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4489 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4491 struct lxc_container
*snap
= NULL
;
4494 snap
= lxc_container_new(snapname
, clonelxcpath
);
4496 ERROR("Could not find snapshot %s", snapname
);
4500 if (!do_lxcapi_destroy(snap
)) {
4501 ERROR("Could not destroy snapshot %s", snapname
);
4509 lxc_container_put(snap
);
4514 static bool remove_all_snapshots(const char *path
)
4517 struct dirent
*direntp
;
4520 dir
= opendir(path
);
4522 SYSERROR("opendir on snapshot path %s", path
);
4526 while ((direntp
= readdir(dir
))) {
4527 if (!strcmp(direntp
->d_name
, "."))
4530 if (!strcmp(direntp
->d_name
, ".."))
4533 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4542 SYSERROR("Error removing directory %s", path
);
4547 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4549 char clonelxcpath
[PATH_MAX
];
4551 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4554 if (!get_snappath_dir(c
, clonelxcpath
))
4557 return do_snapshot_destroy(snapname
, clonelxcpath
);
4560 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4562 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4564 char clonelxcpath
[PATH_MAX
];
4566 if (!c
|| !c
->name
|| !c
->config_path
)
4569 if (!get_snappath_dir(c
, clonelxcpath
))
4572 return remove_all_snapshots(clonelxcpath
);
4575 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4577 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4582 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4585 WRAP_API(bool, lxcapi_may_control
)
4587 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4593 char chrootpath
[PATH_MAX
];
4594 char *directory_path
= NULL
;
4598 SYSERROR("Failed to fork()");
4603 ret
= wait_for_pid(pid
);
4605 ERROR("Failed to create device node");
4612 /* prepare the path */
4613 ret
= snprintf(chrootpath
, PATH_MAX
, "/proc/%d/root", init_pid
);
4614 if (ret
< 0 || ret
>= PATH_MAX
)
4617 ret
= chroot(chrootpath
);
4619 _exit(EXIT_FAILURE
);
4623 _exit(EXIT_FAILURE
);
4625 /* remove path if it exists */
4626 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4630 SYSERROR("Failed to remove \"%s\"", path
);
4631 _exit(EXIT_FAILURE
);
4636 _exit(EXIT_SUCCESS
);
4638 /* create any missing directories */
4641 _exit(EXIT_FAILURE
);
4643 directory_path
= dirname(tmp
);
4644 ret
= mkdir_p(directory_path
, 0755);
4645 if (ret
< 0 && errno
!= EEXIST
) {
4646 SYSERROR("Failed to create path \"%s\"", directory_path
);
4648 _exit(EXIT_FAILURE
);
4651 /* create the device node */
4652 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4655 SYSERROR("Failed to create device node at \"%s\"", path
);
4656 _exit(EXIT_FAILURE
);
4659 _exit(EXIT_SUCCESS
);
4662 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4666 char value
[LXC_MAX_BUFFER
];
4670 /* make sure container is running */
4671 if (!do_lxcapi_is_running(c
)) {
4672 ERROR("container is not running");
4676 /* use src_path if dest_path is NULL otherwise use dest_path */
4677 p
= dest_path
? dest_path
: src_path
;
4679 /* make sure we can access p */
4680 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4683 /* continue if path is character device or block device */
4684 if (S_ISCHR(st
.st_mode
))
4685 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4686 else if (S_ISBLK(st
.st_mode
))
4687 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4691 /* check snprintf return code */
4692 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4695 init_pid
= do_lxcapi_init_pid(c
);
4697 ERROR("Failed to get init pid");
4701 if (!do_add_remove_node(init_pid
, p
, add
, &st
))
4704 /* add or remove device to/from cgroup access list */
4706 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4707 ERROR("set_cgroup_item failed while adding the device node");
4711 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4712 ERROR("set_cgroup_item failed while removing the device node");
4720 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4722 // cannot mknod if we're not privileged wrt init_user_ns
4723 if (am_host_unpriv()) {
4724 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4728 return add_remove_device_node(c
, src_path
, dest_path
, true);
4731 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4733 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4735 if (am_guest_unpriv()) {
4736 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4740 return add_remove_device_node(c
, src_path
, dest_path
, false);
4743 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4745 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4747 const char *dst_ifname
)
4752 if (am_guest_unpriv()) {
4753 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4758 ERROR("No source interface name given");
4762 ret
= lxc_netdev_isup(ifname
);
4764 /* netdev of ifname is up. */
4765 ret
= lxc_netdev_down(ifname
);
4770 init_pid
= do_lxcapi_init_pid(c
);
4772 ERROR("Failed to get init pid");
4776 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4780 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4787 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4789 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4791 const char *dst_ifname
)
4794 pid_t pid
, pid_outside
;
4797 * TODO - if this is a physical device, then we need am_host_unpriv.
4798 * But for other types guest privilege suffices.
4800 if (am_guest_unpriv()) {
4801 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4806 ERROR("No source interface name given");
4810 pid_outside
= lxc_raw_getpid();
4813 ERROR("Failed to fork");
4817 if (pid
== 0) { /* child */
4820 init_pid
= do_lxcapi_init_pid(c
);
4822 ERROR("Failed to get init pid");
4823 _exit(EXIT_FAILURE
);
4825 if (!switch_to_ns(init_pid
, "net")) {
4826 ERROR("Failed to enter network namespace");
4827 _exit(EXIT_FAILURE
);
4830 ret
= lxc_netdev_isup(ifname
);
4832 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4833 _exit(EXIT_FAILURE
);
4836 /* netdev of ifname is up. */
4838 ret
= lxc_netdev_down(ifname
);
4840 ERROR("Failed to set network device \"%s\" down", ifname
);
4841 _exit(EXIT_FAILURE
);
4845 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4846 /* -EINVAL means there is no netdev named as ifname. */
4849 ERROR("Network device \"%s\" not found", ifname
);
4851 ERROR("Failed to remove network device \"%s\"", ifname
);
4853 _exit(EXIT_FAILURE
);
4856 _exit(EXIT_SUCCESS
);
4859 ret
= wait_for_pid(pid
);
4863 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4867 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4869 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4870 struct migrate_opts
*opts
, unsigned int size
)
4873 struct migrate_opts
*valid_opts
= opts
;
4874 uint64_t features_to_check
= 0;
4876 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4877 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4878 * to do anything special.
4880 if (size
> sizeof(*opts
)) {
4881 unsigned char *addr
;
4884 addr
= (void *)opts
+ sizeof(*opts
);
4885 end
= (void *)opts
+ size
;
4887 for (; addr
< end
; addr
++)
4892 /* If the caller has a smaller struct, let's zero out the end for them
4893 * so we don't accidentally use bits of it that they didn't know about
4896 if (size
< sizeof(*opts
)) {
4897 valid_opts
= malloc(sizeof(*opts
));
4901 memset(valid_opts
, 0, sizeof(*opts
));
4902 memcpy(valid_opts
, opts
, size
);
4906 case MIGRATE_PRE_DUMP
:
4907 if (!do_lxcapi_is_running(c
)) {
4908 ERROR("container is not running");
4912 ret
= !__criu_pre_dump(c
, valid_opts
);
4915 if (!do_lxcapi_is_running(c
)) {
4916 ERROR("container is not running");
4920 ret
= !__criu_dump(c
, valid_opts
);
4922 case MIGRATE_RESTORE
:
4923 if (do_lxcapi_is_running(c
)) {
4924 ERROR("container is already running");
4928 ret
= !__criu_restore(c
, valid_opts
);
4930 case MIGRATE_FEATURE_CHECK
:
4931 features_to_check
= valid_opts
->features_to_check
;
4932 ret
= !__criu_check_feature(&features_to_check
);
4934 /* Something went wrong. Let's let the caller
4935 * know which feature checks failed. */
4936 valid_opts
->features_to_check
= features_to_check
;
4940 ERROR("invalid migrate command %u", cmd
);
4945 if (size
< sizeof(*opts
))
4951 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4953 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4955 struct migrate_opts opts
;
4957 memset(&opts
, 0, sizeof(opts
));
4959 opts
.directory
= directory
;
4961 opts
.verbose
= verbose
;
4963 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4966 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4968 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4970 struct migrate_opts opts
;
4972 memset(&opts
, 0, sizeof(opts
));
4974 opts
.directory
= directory
;
4975 opts
.verbose
= verbose
;
4977 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4980 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4982 /* @st_mode is the st_mode field of the stat(source) return struct */
4983 static int create_mount_target(const char *dest
, mode_t st_mode
)
4985 char *dirdup
, *destdirname
;
4988 dirdup
= strdup(dest
);
4990 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4993 destdirname
= dirname(dirdup
);
4995 ret
= mkdir_p(destdirname
, 0755);
4997 SYSERROR("Failed to create \"%s\"", destdirname
);
5005 if (S_ISDIR(st_mode
))
5006 ret
= mkdir(dest
, 0000);
5008 ret
= mknod(dest
, S_IFREG
| 0000, 0);
5011 TRACE("Created mount target \"%s\"", dest
);
5012 else if (ret
< 0 && errno
!= EEXIST
) {
5013 SYSERROR("Failed to create mount target \"%s\"", dest
);
5020 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
5021 const char *target
, const char *filesystemtype
,
5022 unsigned long mountflags
, const void *data
,
5023 struct lxc_mount
*mnt
)
5026 char template[PATH_MAX
], path
[PATH_MAX
];
5027 pid_t pid
, init_pid
;
5030 int ret
= -1, fd
= -EBADF
;
5032 if (!c
|| !c
->lxc_conf
) {
5033 ERROR("Container or configuration is NULL");
5037 if (!c
->lxc_conf
->shmount
.path_host
) {
5038 ERROR("Host path to shared mountpoint must be specified in the config\n");
5042 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
5043 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
5044 SYSERROR("Error writing shmounts tempdir name");
5048 /* Create a temporary file / dir under the shared mountpoint */
5049 if (!source
|| strcmp(source
, "") == 0) {
5050 /* If source is not specified, maybe we want to mount a filesystem? */
5051 sb
.st_mode
= S_IFDIR
;
5053 ret
= stat(source
, &sb
);
5055 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5060 is_dir
= (S_ISDIR(sb
.st_mode
) != 0);
5062 sret
= mkdtemp(template);
5064 SYSERROR("Could not create shmounts temporary dir");
5068 fd
= lxc_make_tmpfile(template, false);
5070 SYSERROR("Could not create shmounts temporary file");
5078 SYSERROR("Could not fork");
5084 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5086 SYSERROR("Failed to mount onto \"%s\"", template);
5087 _exit(EXIT_FAILURE
);
5089 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5091 init_pid
= do_lxcapi_init_pid(c
);
5093 ERROR("Failed to obtain container's init pid");
5094 _exit(EXIT_FAILURE
);
5097 /* Enter the container namespaces */
5098 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5099 if (!switch_to_ns(init_pid
, "user")) {
5100 ERROR("Failed to enter user namespace");
5101 _exit(EXIT_FAILURE
);
5104 if (!lxc_switch_uid_gid(0, 0))
5105 _exit(EXIT_FAILURE
);
5108 if (!switch_to_ns(init_pid
, "mnt")) {
5109 ERROR("Failed to enter mount namespace");
5110 _exit(EXIT_FAILURE
);
5113 ret
= create_mount_target(target
, sb
.st_mode
);
5115 _exit(EXIT_FAILURE
);
5117 suff
= strrchr(template, '/');
5119 _exit(EXIT_FAILURE
);
5121 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5122 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5123 SYSERROR("Error writing container mountpoint name");
5124 _exit(EXIT_FAILURE
);
5127 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5129 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5130 _exit(EXIT_FAILURE
);
5132 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5134 _exit(EXIT_SUCCESS
);
5137 ret
= wait_for_pid(pid
);
5139 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5145 (void)umount2(template, MNT_DETACH
);
5147 (void)rmdir(template);
5149 (void)unlink(template);
5158 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5159 unsigned long, const void *, struct lxc_mount
*)
5161 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5162 unsigned long flags
, struct lxc_mount
*mnt
)
5164 pid_t pid
, init_pid
;
5167 if (!c
|| !c
->lxc_conf
) {
5168 ERROR("Container or configuration is NULL");
5175 SYSERROR("Could not fork");
5180 init_pid
= do_lxcapi_init_pid(c
);
5182 ERROR("Failed to obtain container's init pid");
5183 _exit(EXIT_FAILURE
);
5186 /* Enter the container namespaces */
5187 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5188 if (!switch_to_ns(init_pid
, "user")) {
5189 ERROR("Failed to enter user namespace");
5190 _exit(EXIT_FAILURE
);
5194 if (!switch_to_ns(init_pid
, "mnt")) {
5195 ERROR("Failed to enter mount namespace");
5196 _exit(EXIT_FAILURE
);
5199 /* Do the unmount */
5200 ret
= umount2(target
, flags
);
5202 SYSERROR("Failed to umount \"%s\"", target
);
5203 _exit(EXIT_FAILURE
);
5206 _exit(EXIT_SUCCESS
);
5209 ret
= wait_for_pid(pid
);
5211 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5218 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5220 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5229 current_config
= c
->lxc_conf
;
5232 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5236 ERROR("Memory allocation error.");
5242 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5246 current_config
= NULL
;
5250 static int do_lxcapi_seccomp_notify(struct lxc_container
*c
, unsigned int cmd
, int fd
)
5252 if (!c
|| !c
->lxc_conf
)
5253 return minus_one_set_errno(-EINVAL
);
5256 case LXC_SECCOMP_NOTIFY_GET_FD
:
5258 return minus_one_set_errno(EINVAL
);
5260 return lxc_seccomp_get_notify_fd(&c
->lxc_conf
->seccomp
);
5263 return minus_one_set_errno(EINVAL
);
5266 WRAP_API_2(int, lxcapi_seccomp_notify
, unsigned int, int)
5268 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5270 struct lxc_container
*c
;
5277 c
= malloc(sizeof(*c
));
5279 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5282 memset(c
, 0, sizeof(*c
));
5285 c
->config_path
= strdup(configpath
);
5287 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5288 if (!c
->config_path
) {
5289 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5293 remove_trailing_slashes(c
->config_path
);
5296 c
->name
= malloc(len
+ 1);
5298 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5301 (void)strlcpy(c
->name
, name
, len
+ 1);
5304 c
->slock
= lxc_newlock(c
->config_path
, name
);
5306 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5310 c
->privlock
= lxc_newlock(NULL
, NULL
);
5312 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5316 if (!set_config_filename(c
)) {
5317 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5321 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5322 fprintf(stderr
, "Failed to load config for %s\n", name
);
5326 rc
= ongoing_create(c
);
5328 case LXC_CREATE_INCOMPLETE
:
5329 SYSERROR("Failed to complete container creation for %s", c
->name
);
5330 container_destroy(c
, NULL
);
5331 lxcapi_clear_config(c
);
5333 case LXC_CREATE_ONGOING
:
5334 /* container creation going on */
5336 case LXC_CREATE_FAILED
:
5337 /* container creation failed */
5338 if (errno
!= EACCES
&& errno
!= EPERM
) {
5339 /* insufficient privileges */
5340 SYSERROR("Failed checking for incomplete container %s creation", c
->name
);
5346 c
->daemonize
= true;
5349 /* Assign the member functions. */
5350 c
->is_defined
= lxcapi_is_defined
;
5351 c
->state
= lxcapi_state
;
5352 c
->is_running
= lxcapi_is_running
;
5353 c
->freeze
= lxcapi_freeze
;
5354 c
->unfreeze
= lxcapi_unfreeze
;
5355 c
->console
= lxcapi_console
;
5356 c
->console_getfd
= lxcapi_console_getfd
;
5357 c
->init_pid
= lxcapi_init_pid
;
5358 c
->load_config
= lxcapi_load_config
;
5359 c
->want_daemonize
= lxcapi_want_daemonize
;
5360 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5361 c
->start
= lxcapi_start
;
5362 c
->startl
= lxcapi_startl
;
5363 c
->stop
= lxcapi_stop
;
5364 c
->config_file_name
= lxcapi_config_file_name
;
5365 c
->wait
= lxcapi_wait
;
5366 c
->set_config_item
= lxcapi_set_config_item
;
5367 c
->destroy
= lxcapi_destroy
;
5368 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5369 c
->rename
= lxcapi_rename
;
5370 c
->save_config
= lxcapi_save_config
;
5371 c
->get_keys
= lxcapi_get_keys
;
5372 c
->create
= lxcapi_create
;
5373 c
->createl
= lxcapi_createl
;
5374 c
->shutdown
= lxcapi_shutdown
;
5375 c
->reboot
= lxcapi_reboot
;
5376 c
->reboot2
= lxcapi_reboot2
;
5377 c
->clear_config
= lxcapi_clear_config
;
5378 c
->clear_config_item
= lxcapi_clear_config_item
;
5379 c
->get_config_item
= lxcapi_get_config_item
;
5380 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5381 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5382 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5383 c
->get_config_path
= lxcapi_get_config_path
;
5384 c
->set_config_path
= lxcapi_set_config_path
;
5385 c
->clone
= lxcapi_clone
;
5386 c
->get_interfaces
= lxcapi_get_interfaces
;
5387 c
->get_ips
= lxcapi_get_ips
;
5388 c
->attach
= lxcapi_attach
;
5389 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5390 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5391 c
->snapshot
= lxcapi_snapshot
;
5392 c
->snapshot_list
= lxcapi_snapshot_list
;
5393 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5394 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5395 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5396 c
->may_control
= lxcapi_may_control
;
5397 c
->add_device_node
= lxcapi_add_device_node
;
5398 c
->remove_device_node
= lxcapi_remove_device_node
;
5399 c
->attach_interface
= lxcapi_attach_interface
;
5400 c
->detach_interface
= lxcapi_detach_interface
;
5401 c
->checkpoint
= lxcapi_checkpoint
;
5402 c
->restore
= lxcapi_restore
;
5403 c
->migrate
= lxcapi_migrate
;
5404 c
->console_log
= lxcapi_console_log
;
5405 c
->mount
= lxcapi_mount
;
5406 c
->umount
= lxcapi_umount
;
5407 c
->seccomp_notify
= lxcapi_seccomp_notify
;
5412 lxc_container_free(c
);
5416 int lxc_get_wait_states(const char **states
)
5421 for (i
=0; i
<MAX_STATE
; i
++)
5422 states
[i
] = lxc_state2str(i
);
5428 * These next two could probably be done smarter with reusing a common function
5429 * with different iterators and tests...
5431 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5434 int i
, cfound
= 0, nfound
= 0;
5435 struct dirent
*direntp
;
5436 struct lxc_container
*c
;
5439 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5441 dir
= opendir(lxcpath
);
5443 SYSERROR("opendir on lxcpath");
5453 while ((direntp
= readdir(dir
))) {
5454 /* Ignore '.', '..' and any hidden directory. */
5455 if (!strncmp(direntp
->d_name
, ".", 1))
5458 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5462 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5472 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5474 INFO("Container %s:%s has a config but could not be loaded",
5475 lxcpath
, direntp
->d_name
);
5478 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5484 if (!do_lxcapi_is_defined(c
)) {
5485 INFO("Container %s:%s has a config but is not defined",
5486 lxcpath
, direntp
->d_name
);
5489 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5492 lxc_container_put(c
);
5496 if (!add_to_clist(cret
, c
, nfound
, true)) {
5497 lxc_container_put(c
);
5508 if (names
&& *names
) {
5509 for (i
=0; i
<cfound
; i
++)
5514 if (cret
&& *cret
) {
5515 for (i
=0; i
<nfound
; i
++)
5516 lxc_container_put((*cret
)[i
]);
5524 int list_active_containers(const char *lxcpath
, char ***nret
,
5525 struct lxc_container
***cret
)
5527 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5530 char **ct_name
= NULL
;
5532 struct lxc_container
*c
= NULL
;
5536 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5537 lxcpath_len
= strlen(lxcpath
);
5545 FILE *f
= fopen("/proc/net/unix", "r");
5549 while (getline(&line
, &len
, f
) != -1) {
5550 char *p
= strrchr(line
, ' '), *p2
;
5561 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5563 } else if (strncmp(p
, "lxc/", 4) == 0) {
5573 /* Now p is the start of lxc_name. */
5574 p2
= strchr(p
, '/');
5575 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5580 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5584 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5590 p
= lxc_cmd_get_name(p
);
5595 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5601 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5604 goto free_cret_list
;
5615 c
= lxc_container_new(p
, lxcpath
);
5617 INFO("Container %s:%s is running but could not be loaded",
5620 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5631 * If this is an anonymous container, then is_defined *can*
5632 * return false. So we don't do that check. Count on the
5633 * fact that the command socket exists.
5636 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5637 lxc_container_put(c
);
5638 goto free_cret_list
;
5644 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5646 lxc_container_put(c
);
5647 goto free_cret_list
;
5659 if (cret
&& *cret
) {
5660 for (i
= 0; i
< cret_cnt
; i
++)
5661 lxc_container_put((*cret
)[i
]);
5667 for (i
= 0; i
< ct_name_cnt
; i
++)
5678 int list_all_containers(const char *lxcpath
, char ***nret
,
5679 struct lxc_container
***cret
)
5681 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5684 struct lxc_container
**ct_list
= NULL
;
5686 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5690 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5691 if (active_cnt
< 0) {
5696 for (i
= 0; i
< active_cnt
; i
++) {
5697 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5698 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5700 goto free_active_name
;
5706 free(active_name
[i
]);
5707 active_name
[i
] = NULL
;
5714 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5715 struct lxc_container
*c
;
5717 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5719 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5720 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5724 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5725 lxc_container_put(c
);
5746 for (i
= 0; i
< ct_list_cnt
; i
++) {
5747 lxc_container_put(ct_list
[i
]);
5752 for (i
= 0; i
< active_cnt
; i
++) {
5753 free(active_name
[i
]);
5758 for (i
= 0; i
< ct_cnt
; i
++) {
5765 bool lxc_config_item_is_supported(const char *key
)
5767 return !!lxc_get_config(key
);
5770 bool lxc_has_api_extension(const char *extension
)
5772 /* The NULL API extension is always present. :) */
5776 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5777 if (strcmp(api_extensions
[i
], extension
) == 0)