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
22 #include <arpa/inet.h>
36 #include <sys/mount.h>
38 #include <sys/syscall.h>
39 #include <sys/sysmacros.h>
40 #include <sys/types.h>
45 #include "api_extensions.h"
49 #include "commands_utils.h"
53 #include "confile_utils.h"
56 #include "initutils.h"
59 #include "lxccontainer.h"
62 #include "namespace.h"
68 #include "storage/btrfs.h"
69 #include "storage/overlay.h"
70 #include "storage_utils.h"
78 #include <sys/mkdev.h>
84 #include <../include/ifaddrs.h>
88 #include <../include/lxcmntent.h>
94 #include "include/strlcpy.h"
97 /* Define faccessat() if missing from the C library */
98 #ifndef HAVE_FACCESSAT
99 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
101 #ifdef __NR_faccessat
102 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
110 lxc_log_define(lxccontainer
, lxc
);
112 static bool do_lxcapi_destroy(struct lxc_container
*c
);
113 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
114 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
115 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
116 static bool container_destroy(struct lxc_container
*c
,
117 struct lxc_storage
*storage
);
118 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
119 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
120 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
122 static bool config_file_exists(const char *lxcpath
, const char *cname
)
128 /* $lxcpath + '/' + $cname + '/config' + \0 */
129 len
= strlen(lxcpath
) + strlen(cname
) + 9;
131 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
132 if (ret
< 0 || (size_t)ret
>= len
)
135 return file_exists(fname
);
138 /* A few functions to help detect when a container creation failed. If a
139 * container creation was killed partway through, then trying to actually start
140 * that container could harm the host. We detect this by creating a 'partial'
141 * file under the container directory, and keeping an advisory lock. When
142 * container creation completes, we remove that file. When we load or try to
143 * start a container, if we find that file, without a flock, we remove the
146 static int ongoing_create(struct lxc_container
*c
)
151 struct flock lk
= {0};
153 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
155 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
156 if (ret
< 0 || (size_t)ret
>= len
)
159 fd
= open(path
, O_RDWR
| O_CLOEXEC
);
168 lk
.l_whence
= SEEK_SET
;
169 /* F_OFD_GETLK requires that l_pid be set to 0 otherwise the kernel
174 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
175 if (ret
< 0 && errno
== EINVAL
) {
176 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
177 if (ret
< 0 && errno
== EWOULDBLOCK
)
183 /* F_OFD_GETLK will not send us back a pid so don't check it. */
185 /* Create is still ongoing. */
188 /* Create completed but partial is still there. */
192 static int create_partial(struct lxc_container
*c
)
197 struct flock lk
= {0};
199 /* $lxcpath + '/' + $name + '/partial' + \0 */
200 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
202 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
203 if (ret
< 0 || (size_t)ret
>= len
)
206 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
| O_CLOEXEC
, 0000);
211 lk
.l_whence
= SEEK_SET
;
213 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
215 if (errno
== EINVAL
) {
216 ret
= flock(fd
, LOCK_EX
);
221 SYSERROR("Failed to lock partial file %s", path
);
229 static void remove_partial(struct lxc_container
*c
, int fd
)
237 /* $lxcpath + '/' + $name + '/partial' + \0 */
238 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
240 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
241 if (ret
< 0 || (size_t)ret
>= len
)
246 SYSERROR("Failed to remove partial file %s", path
);
250 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
251 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
252 * container configuration file.
253 * The container_disk_lock also takes the container_mem_lock.
254 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
255 * NOTHING mutexes two independent programs with their own struct
256 * lxc_container for the same c->name, between API calls. For instance,
257 * c->config_read(); c->start(); Between those calls, data on disk
258 * could change (which shouldn't bother the caller unless for instance
259 * the rootfs get moved). c->config_read(); update; c->config_write();
260 * Two such updaters could race. The callers should therefore check their
261 * results. Trying to prevent that would necessarily expose us to deadlocks
262 * due to hung callers. So I prefer to keep the locks only within our own
263 * functions, not across functions.
265 * If you're going to clone while holding a lxccontainer, increment
266 * c->numthreads (under privlock) before forking. When deleting,
267 * decrement numthreads under privlock, then if it hits 0 you can delete.
268 * Do not ever use a lxccontainer whose numthreads you did not bump.
270 static void lxc_container_free(struct lxc_container
*c
)
276 c
->configfile
= NULL
;
278 free(c
->error_string
);
279 c
->error_string
= NULL
;
282 lxc_putlock(c
->slock
);
287 lxc_putlock(c
->privlock
);
295 lxc_conf_free(c
->lxc_conf
);
299 free(c
->config_path
);
300 c
->config_path
= NULL
;
305 /* Consider the following case:
307 * |====================================================================|
308 * | freer | racing get()er |
309 * |====================================================================|
310 * | lxc_container_put() | lxc_container_get() |
311 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
312 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
313 * | \ lxcunlock() | \ |
314 * | \ lxc_container_free() | \ lxclock() returns |
315 * | | \ c->numthreads < 1 -> return 0 |
316 * | \ \ (free stuff) | |
317 * | \ \ sem_destroy(privlock) | |
318 * |_______________________________|____________________________________|
320 * When the get()er checks numthreads the first time, one of the following
322 * 1. freer has set numthreads = 0. get() returns 0
323 * 2. freer is between lxclock and setting numthreads to 0. get()er will
324 * sem_wait on privlock, get lxclock after freer() drops it, then see
325 * numthreads is 0 and exit without touching lxclock again..
326 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
327 * will see --numthreads = 1 and not call lxc_container_free().
330 int lxc_container_get(struct lxc_container
*c
)
335 /* If someone else has already started freeing the container, don't try
336 * to take the lock, which may be invalid.
338 if (c
->numthreads
< 1)
341 if (container_mem_lock(c
))
344 /* Bail without trying to unlock, bc the privlock is now probably in
347 if (c
->numthreads
< 1)
351 container_mem_unlock(c
);
356 int lxc_container_put(struct lxc_container
*c
)
361 if (container_mem_lock(c
))
366 if (c
->numthreads
< 1) {
367 container_mem_unlock(c
);
368 lxc_container_free(c
);
372 container_mem_unlock(c
);
376 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
385 if (container_mem_lock(c
))
391 statret
= stat(c
->configfile
, &statbuf
);
398 container_mem_unlock(c
);
402 #define WRAP_API(rettype, fnname) \
403 static rettype fnname(struct lxc_container *c) \
406 bool reset_config = false; \
408 if (!current_config && c && c->lxc_conf) { \
409 current_config = c->lxc_conf; \
410 reset_config = true; \
413 ret = do_##fnname(c); \
415 current_config = NULL; \
420 #define WRAP_API_1(rettype, fnname, t1) \
421 static rettype fnname(struct lxc_container *c, t1 a1) \
424 bool reset_config = false; \
426 if (!current_config && c && c->lxc_conf) { \
427 current_config = c->lxc_conf; \
428 reset_config = true; \
431 ret = do_##fnname(c, a1); \
433 current_config = NULL; \
438 #define WRAP_API_2(rettype, fnname, t1, t2) \
439 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
442 bool reset_config = false; \
444 if (!current_config && c && c->lxc_conf) { \
445 current_config = c->lxc_conf; \
446 reset_config = true; \
449 ret = do_##fnname(c, a1, a2); \
451 current_config = NULL; \
456 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
457 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
460 bool reset_config = false; \
462 if (!current_config && c && c->lxc_conf) { \
463 current_config = c->lxc_conf; \
464 reset_config = true; \
467 ret = do_##fnname(c, a1, a2, a3); \
469 current_config = NULL; \
474 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
475 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
476 t4 a4, t5 a5, t6 a6) \
479 bool reset_config = false; \
481 if (!current_config && c && c->lxc_conf) { \
482 current_config = c->lxc_conf; \
483 reset_config = true; \
486 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
488 current_config = NULL; \
493 WRAP_API(bool, lxcapi_is_defined
)
495 static const char *do_lxcapi_state(struct lxc_container
*c
)
502 s
= lxc_getstate(c
->name
, c
->config_path
);
503 return lxc_state2str(s
);
506 WRAP_API(const char *, lxcapi_state
)
508 static bool is_stopped(struct lxc_container
*c
)
512 s
= lxc_getstate(c
->name
, c
->config_path
);
513 return (s
== STOPPED
);
516 static bool do_lxcapi_is_running(struct lxc_container
*c
)
521 return !is_stopped(c
);
524 WRAP_API(bool, lxcapi_is_running
)
526 static bool do_lxcapi_freeze(struct lxc_container
*c
)
533 ret
= lxc_freeze(c
->lxc_conf
, c
->name
, c
->config_path
);
540 WRAP_API(bool, lxcapi_freeze
)
542 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
549 ret
= lxc_unfreeze(c
->lxc_conf
, c
->name
, c
->config_path
);
556 WRAP_API(bool, lxcapi_unfreeze
)
558 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
563 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
566 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
568 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
569 int stdoutfd
, int stderrfd
, int escape
)
576 current_config
= c
->lxc_conf
;
577 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
578 current_config
= NULL
;
583 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
590 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
593 NOTICE("The console log is empty");
594 else if (ret
== -EFAULT
)
595 NOTICE("The container does not keep a console log");
596 else if (ret
== -ENOENT
)
597 NOTICE("The container does not keep a console log file");
598 else if (ret
== -EIO
)
599 NOTICE("Failed to write console log to log file");
601 ERROR("Failed to retrieve console log");
607 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
609 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
614 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
617 WRAP_API(pid_t
, lxcapi_init_pid
)
619 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
622 c
->lxc_conf
= lxc_conf_init();
627 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
630 c
->lxc_conf
->name
= c
->name
;
634 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
638 bool need_disklock
= false, ret
= false;
643 fname
= c
->configfile
;
651 /* If we're reading something other than the container's config, we only
652 * need to lock the in-memory container. If loading the container's
653 * config file, take the disk lock.
655 if (strcmp(fname
, c
->configfile
) == 0)
656 need_disklock
= true;
659 lret
= container_disk_lock(c
);
661 lret
= container_mem_lock(c
);
665 ret
= load_config_locked(c
, fname
);
668 container_disk_unlock(c
);
670 container_mem_unlock(c
);
675 WRAP_API_1(bool, lxcapi_load_config
, const char *)
677 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
679 if (!c
|| !c
->lxc_conf
)
682 if (container_mem_lock(c
))
685 c
->daemonize
= state
;
687 container_mem_unlock(c
);
692 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
694 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
696 if (!c
|| !c
->lxc_conf
)
699 if (container_mem_lock(c
))
702 c
->lxc_conf
->close_all_fds
= state
;
704 container_mem_unlock(c
);
709 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
711 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
719 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
723 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
725 static bool am_single_threaded(void)
728 struct dirent
*direntp
;
731 dir
= opendir("/proc/self/task");
735 while ((direntp
= readdir(dir
))) {
736 if (strcmp(direntp
->d_name
, ".") == 0)
739 if (strcmp(direntp
->d_name
, "..") == 0)
751 static void push_arg(char ***argp
, char *arg
, int *nargs
)
756 copy
= must_copy_string(arg
);
759 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
768 static char **split_init_cmd(const char *incmd
)
778 len
= strlen(incmd
) + 1;
780 retlen
= strlcpy(copy
, incmd
, len
);
785 argv
= malloc(sizeof(char *));
789 lxc_iterate_parts(p
, copy
, " ")
790 push_arg(&argv
, p
, &nargs
);
800 static void free_init_cmd(char **argv
)
813 static int lxc_rcv_status(int state_socket
)
819 /* Receive container state. */
820 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
825 TRACE("Caught EINTR; retrying");
832 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
836 /* Close write end of the socket pair. */
837 close(handler
->state_socket_pair
[1]);
838 handler
->state_socket_pair
[1] = -1;
840 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
842 /* Close read end of the socket pair. */
843 close(handler
->state_socket_pair
[0]);
844 handler
->state_socket_pair
[0] = -1;
846 /* The first child is going to fork() again and then exits. So we reap
847 * the first child here.
849 ret
= wait_for_pid(pid
);
851 DEBUG("Failed waiting on first child %d", pid
);
853 DEBUG("First child %d exited", pid
);
856 SYSERROR("Failed to receive the container state");
860 /* If we receive anything else then running we know that the container
863 if (state
!= RUNNING
) {
864 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
865 lxc_state2str(state
));
869 TRACE("Container is in \"RUNNING\" state");
873 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
876 struct lxc_handler
*handler
;
877 struct lxc_conf
*conf
;
878 char *default_args
[] = {
882 char **init_cmd
= NULL
;
883 int keepfds
[3] = {-1, -1, -1};
885 /* container does exist */
889 /* If anything fails before we set error_num, we want an error in there.
893 /* Container has not been setup. */
897 ret
= ongoing_create(c
);
899 ERROR("Failed checking for incomplete container creation");
901 } else if (ret
== 1) {
902 ERROR("Ongoing container creation detected");
904 } else if (ret
== 2) {
905 ERROR("Failed to create container");
906 do_lxcapi_destroy(c
);
910 if (container_mem_lock(c
))
915 /* initialize handler */
916 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
918 container_mem_unlock(c
);
923 if (useinit
&& conf
->execute_cmd
)
924 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
926 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
929 /* ... otherwise use default_args. */
932 ERROR("No valid init detected");
933 lxc_free_handler(handler
);
939 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
940 * here to protect the on disk container? We don't want to exclude
941 * things like lxc_info while the container is running.
950 free_init_cmd(init_cmd
);
951 lxc_free_handler(handler
);
957 /* Set to NULL because we don't want father unlink
958 * the PID file, child will do the free and unlink.
962 /* Wait for container to tell us whether it started
965 started
= wait_on_daemonized_start(handler
, pid
);
967 free_init_cmd(init_cmd
);
968 lxc_free_handler(handler
);
974 /* We don't really care if this doesn't print all the
975 * characters. All that it means is that the proctitle will be
976 * ugly. Similarly, we also don't care if setproctitle() fails.
978 ret
= snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
980 ret
= setproctitle(title
);
982 INFO("Failed to set process title to %s", title
);
984 INFO("Set process title to %s", title
);
987 /* We fork() a second time to be reparented to init. Like
988 * POSIX's daemon() function we change to "/" and redirect
989 * std{in,out,err} to /dev/null.
993 SYSERROR("Failed to fork first child process");
999 free_init_cmd(init_cmd
);
1000 lxc_free_handler(handler
);
1001 _exit(EXIT_SUCCESS
);
1006 /* change to / directory */
1009 SYSERROR("Failed to change to \"/\" directory");
1010 _exit(EXIT_FAILURE
);
1013 keepfds
[0] = handler
->conf
->maincmd_fd
;
1014 keepfds
[1] = handler
->state_socket_pair
[0];
1015 keepfds
[2] = handler
->state_socket_pair
[1];
1016 ret
= lxc_check_inherited(conf
, true, keepfds
,
1017 sizeof(keepfds
) / sizeof(keepfds
[0]));
1019 _exit(EXIT_FAILURE
);
1021 /* redirect std{in,out,err} to /dev/null */
1022 ret
= null_stdfds();
1024 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1025 _exit(EXIT_FAILURE
);
1028 /* become session leader */
1031 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1032 } else if (!am_single_threaded()) {
1033 ERROR("Cannot start non-daemonized container when threaded");
1034 free_init_cmd(init_cmd
);
1035 lxc_free_handler(handler
);
1039 /* We need to write PID file after daemonize, so we always write the
1044 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1046 w
= snprintf(pidstr
, sizeof(pidstr
), "%d", lxc_raw_getpid());
1047 if (w
< 0 || (size_t)w
>= sizeof(pidstr
)) {
1048 free_init_cmd(init_cmd
);
1049 lxc_free_handler(handler
);
1051 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1054 _exit(EXIT_FAILURE
);
1059 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1061 free_init_cmd(init_cmd
);
1062 lxc_free_handler(handler
);
1064 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1067 _exit(EXIT_FAILURE
);
1073 conf
->reboot
= REBOOT_NONE
;
1075 /* Unshare the mount namespace if requested */
1076 if (conf
->monitor_unshare
) {
1077 ret
= unshare(CLONE_NEWNS
);
1079 SYSERROR("Failed to unshare mount namespace");
1080 lxc_free_handler(handler
);
1085 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1087 SYSERROR("Failed to make / rslave at startup");
1088 lxc_free_handler(handler
);
1095 if (conf
->reboot
== REBOOT_INIT
) {
1096 /* initialize handler */
1097 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1104 keepfds
[0] = handler
->conf
->maincmd_fd
;
1105 keepfds
[1] = handler
->state_socket_pair
[0];
1106 keepfds
[2] = handler
->state_socket_pair
[1];
1107 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1108 sizeof(keepfds
) / sizeof(keepfds
[0]));
1110 lxc_free_handler(handler
);
1116 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1117 c
->daemonize
, &c
->error_num
);
1119 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1120 c
->daemonize
, &c
->error_num
);
1122 if (conf
->reboot
== REBOOT_REQ
) {
1123 INFO("Container requested reboot");
1124 conf
->reboot
= REBOOT_INIT
;
1134 free_init_cmd(init_cmd
);
1136 if (c
->daemonize
&& ret
!= 0)
1137 _exit(EXIT_FAILURE
);
1138 else if (c
->daemonize
)
1139 _exit(EXIT_SUCCESS
);
1147 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1152 current_config
= c
? c
->lxc_conf
: NULL
;
1153 ret
= do_lxcapi_start(c
, useinit
, argv
);
1154 current_config
= NULL
;
1159 /* Note, there MUST be an ending NULL. */
1160 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1163 char **inargs
= NULL
;
1166 /* container exists */
1170 current_config
= c
->lxc_conf
;
1172 va_start(ap
, useinit
);
1173 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1178 /* pass NULL if no arguments were supplied */
1179 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1185 for (arg
= inargs
; *arg
; arg
++)
1190 current_config
= NULL
;
1195 static bool do_lxcapi_stop(struct lxc_container
*c
)
1202 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1207 WRAP_API(bool, lxcapi_stop
)
1209 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1216 mode_t mask
= umask(0002);
1217 ret
= mkdir(path
, 0770);
1222 if (errno
!= EEXIST
)
1229 p
= alloca(len
+ 1);
1230 (void)strlcpy(p
, path
, len
+ 1);
1232 if (!lxc_list_empty(&conf
->id_map
)) {
1233 ret
= chown_mapped_root(p
, conf
);
1241 /* Create the standard expected container dir. */
1242 static bool create_container_dir(struct lxc_container
*c
)
1248 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1253 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1254 if (ret
< 0 || (size_t)ret
>= len
) {
1259 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1265 /* do_storage_create: thin wrapper around storage_create(). Like
1266 * storage_create(), it returns a mounted bdev on success, NULL on error.
1268 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1270 struct bdev_specs
*specs
)
1275 struct lxc_storage
*bdev
;
1277 /* rootfs.path or lxcpath/lxcname/rootfs */
1278 if (c
->lxc_conf
->rootfs
.path
&&
1279 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1280 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1281 len
= strlen(rpath
) + 1;
1283 ret
= snprintf(dest
, len
, "%s", rpath
);
1285 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1286 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1288 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1290 if (ret
< 0 || (size_t)ret
>= len
)
1293 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1295 ERROR("Failed to create \"%s\" storage", type
);
1299 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1300 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1304 /* If we are not root, chown the rootfs dir to root in the target user
1308 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1309 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1311 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1312 suggest_default_idmap();
1321 static char *lxcbasename(char *path
)
1325 p
= path
+ strlen(path
) - 1;
1326 while (*p
!= '/' && p
> path
)
1332 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1333 bool need_null_stdfds
, char *const argv
[])
1343 SYSERROR("Failed to fork task for container creation template");
1347 if (pid
== 0) { /* child */
1349 char *namearg
, *patharg
, *rootfsarg
;
1352 struct lxc_storage
*bdev
= NULL
;
1353 struct lxc_conf
*conf
= c
->lxc_conf
;
1356 if (need_null_stdfds
) {
1357 ret
= null_stdfds();
1359 _exit(EXIT_FAILURE
);
1362 bdev
= storage_init(c
->lxc_conf
);
1364 ERROR("Failed to initialize storage");
1365 _exit(EXIT_FAILURE
);
1370 ret
= unshare(CLONE_NEWNS
);
1372 ERROR("Failed to unshare CLONE_NEWNS");
1373 _exit(EXIT_FAILURE
);
1376 ret
= detect_shared_rootfs();
1378 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1380 SYSERROR("Failed to make \"/\" rslave");
1381 ERROR("Continuing...");
1386 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1388 ERROR("Unprivileged users can only create "
1389 "btrfs and directory-backed containers");
1390 _exit(EXIT_FAILURE
);
1393 if (strcmp(bdev
->type
, "overlay") == 0 ||
1394 strcmp(bdev
->type
, "overlayfs") == 0) {
1395 /* If we create an overlay container we need to
1396 * rsync the contents into
1397 * <container-path>/<container-name>/rootfs.
1398 * However, the overlay mount function will
1400 * <container-path>/<container-name>/delta0
1402 * <container-path>/<container-name>/rootfs
1403 * which means we would rsync the rootfs into
1404 * the delta directory. That doesn't make sense
1405 * since the delta directory only exists to
1406 * record the differences to
1407 * <container-path>/<container-name>/rootfs. So
1408 * let's simply bind-mount here and then rsync
1410 * <container-path>/<container-name>/rootfs.
1414 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1416 ERROR("Failed to get rootfs");
1417 _exit(EXIT_FAILURE
);
1420 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1422 ERROR("Failed to mount rootfs");
1423 _exit(EXIT_FAILURE
);
1426 ret
= bdev
->ops
->mount(bdev
);
1428 ERROR("Failed to mount rootfs");
1429 _exit(EXIT_FAILURE
);
1432 } else { /* TODO come up with a better way here! */
1435 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1436 bdev
->dest
= strdup(src
);
1439 /* Create our new array, pre-pend the template name and base
1443 for (nargs
= 0; argv
[nargs
]; nargs
++)
1446 /* template, path, rootfs and name args */
1449 newargv
= malloc(nargs
* sizeof(*newargv
));
1451 _exit(EXIT_FAILURE
);
1452 newargv
[0] = lxcbasename(tpath
);
1455 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1456 patharg
= malloc(len
);
1458 _exit(EXIT_FAILURE
);
1460 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1461 if (ret
< 0 || ret
>= len
)
1462 _exit(EXIT_FAILURE
);
1463 newargv
[1] = patharg
;
1466 len
= strlen("--name=") + strlen(c
->name
) + 1;
1467 namearg
= malloc(len
);
1469 _exit(EXIT_FAILURE
);
1471 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1472 if (ret
< 0 || ret
>= len
)
1473 _exit(EXIT_FAILURE
);
1474 newargv
[2] = namearg
;
1477 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1478 rootfsarg
= malloc(len
);
1480 _exit(EXIT_FAILURE
);
1482 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1483 if (ret
< 0 || ret
>= len
)
1484 _exit(EXIT_FAILURE
);
1485 newargv
[3] = rootfsarg
;
1487 /* add passed-in args */
1489 for (i
= 4; i
< nargs
; i
++)
1490 newargv
[i
] = argv
[i
- 4];
1492 /* add trailing NULL */
1494 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1496 _exit(EXIT_FAILURE
);
1497 newargv
[nargs
- 1] = NULL
;
1499 /* If we're running the template in a mapped userns, then we
1500 * prepend the template command with: lxc-usernsexec <-m map1>
1501 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1502 * the mapped uid for our geteuid()
1504 if (!lxc_list_empty(&conf
->id_map
)) {
1505 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1507 char txtuid
[20], txtgid
[20];
1508 struct lxc_list
*it
;
1512 n2
= malloc(n2args
* sizeof(*n2
));
1514 _exit(EXIT_FAILURE
);
1517 tpath
= "lxc-usernsexec";
1518 n2
[0] = "lxc-usernsexec";
1520 lxc_list_for_each(it
, &conf
->id_map
) {
1523 n2
= realloc(n2
, n2args
* sizeof(char *));
1525 _exit(EXIT_FAILURE
);
1527 n2
[n2args
- 2] = "-m";
1528 n2
[n2args
- 1] = malloc(200);
1529 if (!n2
[n2args
- 1])
1530 _exit(EXIT_FAILURE
);
1532 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1533 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1534 map
->nsid
, map
->hostid
, map
->range
);
1535 if (ret
< 0 || ret
>= 200)
1536 _exit(EXIT_FAILURE
);
1539 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1540 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1542 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1544 _exit(EXIT_FAILURE
);
1546 if (hostuid_mapped
< 0) {
1547 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1548 n2
[n2args
++] = "-m";
1549 if (hostuid_mapped
< 0) {
1550 ERROR("Failed to find free uid to map");
1551 _exit(EXIT_FAILURE
);
1554 n2
[n2args
++] = malloc(200);
1555 if (!n2
[n2args
- 1]) {
1556 SYSERROR("out of memory");
1557 _exit(EXIT_FAILURE
);
1560 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1561 hostuid_mapped
, geteuid());
1562 if (ret
< 0 || ret
>= 200)
1563 _exit(EXIT_FAILURE
);
1566 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1567 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1569 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1571 _exit(EXIT_FAILURE
);
1573 if (hostgid_mapped
< 0) {
1574 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1575 n2
[n2args
++] = "-m";
1576 if (hostgid_mapped
< 0) {
1577 ERROR("Failed to find free gid to map");
1578 _exit(EXIT_FAILURE
);
1581 n2
[n2args
++] = malloc(200);
1582 if (!n2
[n2args
- 1]) {
1583 SYSERROR("out of memory");
1584 _exit(EXIT_FAILURE
);
1587 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1588 hostgid_mapped
, getegid());
1589 if (ret
< 0 || ret
>= 200)
1590 _exit(EXIT_FAILURE
);
1593 n2
[n2args
++] = "--";
1595 for (i
= 0; i
< nargs
; i
++)
1596 n2
[i
+ n2args
] = newargv
[i
];
1599 /* Finally add "--mapped-uid $uid" to tell template what
1600 * to chown cached images to.
1603 n2
= realloc(n2
, n2args
* sizeof(char *));
1605 _exit(EXIT_FAILURE
);
1607 /* note n2[n2args-1] is NULL */
1608 n2
[n2args
- 5] = "--mapped-uid";
1610 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1611 if (ret
< 0 || ret
>= 20) {
1614 _exit(EXIT_FAILURE
);
1617 n2
[n2args
- 4] = txtuid
;
1618 n2
[n2args
- 3] = "--mapped-gid";
1620 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1621 if (ret
< 0 || ret
>= 20) {
1624 _exit(EXIT_FAILURE
);
1627 n2
[n2args
- 2] = txtgid
;
1628 n2
[n2args
- 1] = NULL
;
1633 execvp(tpath
, newargv
);
1634 SYSERROR("Failed to execute template %s", tpath
);
1635 _exit(EXIT_FAILURE
);
1638 ret
= wait_for_pid(pid
);
1640 ERROR("Failed to create container from template");
1647 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1656 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1660 f
= fopen(path
, "r");
1664 ret
= fseek(f
, 0, SEEK_END
);
1673 ret
= fseek(f
, 0, SEEK_SET
);
1677 ret
= fseek(f
, 0, SEEK_SET
);
1682 contents
= malloc(flen
+ 1);
1686 len
= fread(contents
, 1, flen
, f
);
1688 goto out_free_contents
;
1690 contents
[flen
] = '\0';
1695 goto out_free_contents
;
1698 tpath
= get_template_path(t
);
1700 ERROR("Invalid template \"%s\" specified", t
);
1701 goto out_free_contents
;
1704 ret
= sha1sum_file(tpath
, md_value
);
1706 ERROR("Failed to get sha1sum of %s", tpath
);
1708 goto out_free_contents
;
1713 f
= fopen(path
, "w");
1715 SYSERROR("Reopening config for writing");
1720 fprintf(f
, "# Template used to create this container: %s\n", t
);
1722 fprintf(f
, "# Parameters passed to the template:");
1724 fprintf(f
, " %s", *argv
);
1731 fprintf(f
, "# Template script checksum (SHA-1): ");
1732 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1733 fprintf(f
, "%02x", md_value
[i
]);
1736 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1737 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1738 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1739 fprintf(f
, "# (Be aware this has security implications)\n\n");
1740 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1741 SYSERROR("Writing original contents");
1761 SYSERROR("Error prepending header");
1768 static void lxcapi_clear_config(struct lxc_container
*c
)
1770 if (!c
|| !c
->lxc_conf
)
1773 lxc_conf_free(c
->lxc_conf
);
1777 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1781 * create a container with the given parameters.
1782 * @c: container to be created. It has the lxcpath, name, and a starting
1783 * configuration already set
1784 * @t: the template to execute to instantiate the root filesystem and
1785 * adjust the configuration.
1786 * @bdevtype: backing store type to use. If NULL, dir will be used.
1787 * @specs: additional parameters for the backing store, i.e. LVM vg to
1790 * @argv: the arguments to pass to the template, terminated by NULL. If no
1791 * arguments, you can just pass NULL.
1793 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1794 const char *bdevtype
, struct bdev_specs
*specs
,
1795 int flags
, char *const argv
[])
1807 tpath
= get_template_path(t
);
1809 ERROR("Unknown template \"%s\"", t
);
1814 /* If a template is passed in, and the rootfs already is defined in the
1815 * container config and exists, then the caller is trying to create an
1816 * existing container. Return an error, but do NOT delete the container.
1818 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1819 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1820 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1826 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1827 ERROR("Error loading default configuration file %s",
1828 lxc_global_config_value("lxc.default_config"));
1833 if (!create_container_dir(c
))
1836 /* If both template and rootfs.path are set, template is setup as
1837 * rootfs.path. The container is already created if we have a config and
1838 * rootfs.path is accessible
1840 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1841 /* No template passed in and rootfs does not exist. */
1842 if (!c
->save_config(c
, NULL
)) {
1843 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1850 /* Rootfs passed into configuration, but does not exist. */
1851 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1854 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1855 /* Rootfs already existed, user just wanted to save the loaded
1858 if (!c
->save_config(c
, NULL
))
1859 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1865 /* Mark that this container is being created */
1866 partial_fd
= create_partial(c
);
1870 /* No need to get disk lock bc we have the partial lock. */
1874 /* Create the storage.
1875 * Note we can't do this in the same task as we use to execute the
1876 * template because of the way zfs works.
1877 * After you 'zfs create', zfs mounts the fs only in the initial
1882 SYSERROR("Failed to fork task for container creation template");
1886 if (pid
== 0) { /* child */
1887 struct lxc_storage
*bdev
= NULL
;
1889 bdev
= do_storage_create(c
, bdevtype
, specs
);
1891 ERROR("Failed to create %s storage for %s",
1892 bdevtype
? bdevtype
: "(none)", c
->name
);
1893 _exit(EXIT_FAILURE
);
1896 /* Save config file again to store the new rootfs location. */
1897 if (!do_lxcapi_save_config(c
, NULL
)) {
1898 ERROR("Failed to save initial config for %s", c
->name
);
1899 /* Parent task won't see the storage driver in the
1900 * config so we delete it.
1902 bdev
->ops
->umount(bdev
);
1903 bdev
->ops
->destroy(bdev
);
1904 _exit(EXIT_FAILURE
);
1907 _exit(EXIT_SUCCESS
);
1910 if (wait_for_pid(pid
) != 0)
1913 /* Reload config to get the rootfs. */
1914 lxc_conf_free(c
->lxc_conf
);
1917 if (!load_config_locked(c
, c
->configfile
))
1920 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1923 /* Now clear out the lxc_conf we have, reload from the created
1926 do_lxcapi_clear_config(c
);
1929 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1930 ERROR("Failed to prepend header to config file");
1935 ret
= load_config_locked(c
, c
->configfile
);
1939 if (partial_fd
>= 0)
1940 remove_partial(c
, partial_fd
);
1944 container_destroy(c
, NULL
);
1951 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1952 const char *bdevtype
, struct bdev_specs
*specs
,
1953 int flags
, char *const argv
[])
1957 current_config
= c
? c
->lxc_conf
: NULL
;
1959 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1960 current_config
= NULL
;
1964 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1968 int rebootsignal
= SIGINT
;
1973 if (!do_lxcapi_is_running(c
))
1976 pid
= do_lxcapi_init_pid(c
);
1980 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1981 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1983 ret
= kill(pid
, rebootsignal
);
1985 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
1992 WRAP_API(bool, lxcapi_reboot
)
1994 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1998 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1999 lxc_state_t states
[MAX_STATE
] = {0};
2004 if (!do_lxcapi_is_running(c
))
2007 pid
= do_lxcapi_init_pid(c
);
2011 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
2012 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2014 /* Add a new state client before sending the shutdown signal so that we
2015 * don't miss a state.
2018 states
[RUNNING
] = 2;
2019 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2024 if (state_client_fd
< 0)
2030 if (ret
< MAX_STATE
)
2034 /* Send reboot signal to container. */
2035 killret
= kill(pid
, rebootsignal
);
2037 if (state_client_fd
>= 0)
2038 close(state_client_fd
);
2040 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2043 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2048 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2049 close(state_client_fd
);
2053 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2060 WRAP_API_1(bool, lxcapi_reboot2
, int)
2062 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2066 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2067 lxc_state_t states
[MAX_STATE
] = {0};
2072 if (!do_lxcapi_is_running(c
))
2075 pid
= do_lxcapi_init_pid(c
);
2079 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2080 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2081 haltsignal
= c
->lxc_conf
->haltsignal
;
2082 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2083 haltsignal
= (SIGRTMIN
+ 3);
2085 /* Add a new state client before sending the shutdown signal so that we
2086 * don't miss a state.
2089 states
[STOPPED
] = 1;
2090 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2095 if (state_client_fd
< 0)
2101 if (ret
< MAX_STATE
)
2105 /* Send shutdown signal to container. */
2106 killret
= kill(pid
, haltsignal
);
2108 if (state_client_fd
>= 0)
2109 close(state_client_fd
);
2111 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2114 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2119 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2120 close(state_client_fd
);
2124 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2131 WRAP_API_1(bool, lxcapi_shutdown
, int)
2133 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2134 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2143 current_config
= c
->lxc_conf
;
2146 * since we're going to wait for create to finish, I don't think we
2147 * need to get a copy of the arguments.
2149 va_start(ap
, flags
);
2150 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2153 ERROR("Failed to allocate memory");
2157 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2161 current_config
= NULL
;
2165 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2167 if (!strcmp(key
, "lxc.cgroup"))
2168 return clear_unexp_config_line(conf
, key
, true);
2170 if (!strcmp(key
, "lxc.network"))
2171 return clear_unexp_config_line(conf
, key
, true);
2173 if (!strcmp(key
, "lxc.net"))
2174 return clear_unexp_config_line(conf
, key
, true);
2176 /* Clear a network with a specific index. */
2177 if (!strncmp(key
, "lxc.net.", 8)) {
2182 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2184 return clear_unexp_config_line(conf
, key
, true);
2187 if (!strcmp(key
, "lxc.hook"))
2188 return clear_unexp_config_line(conf
, key
, true);
2190 return clear_unexp_config_line(conf
, key
, false);
2193 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2197 struct lxc_config_t
*config
;
2199 if (!c
|| !c
->lxc_conf
)
2202 if (container_mem_lock(c
))
2205 config
= lxc_get_config(key
);
2206 /* Verify that the config key exists and that it has a callback
2209 if (config
&& config
->clr
)
2210 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2213 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2215 container_mem_unlock(c
);
2219 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2221 static inline bool enter_net_ns(struct lxc_container
*c
)
2223 pid_t pid
= do_lxcapi_init_pid(c
);
2225 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2226 (access("/proc/self/ns/user", F_OK
) == 0))
2227 if (!switch_to_ns(pid
, "user"))
2230 return switch_to_ns(pid
, "net");
2233 /* Used by qsort and bsearch functions for comparing names. */
2234 static inline int string_cmp(char **first
, char **second
)
2236 return strcmp(*first
, *second
);
2239 /* Used by qsort and bsearch functions for comparing container names. */
2240 static inline int container_cmp(struct lxc_container
**first
,
2241 struct lxc_container
**second
)
2243 return strcmp((*first
)->name
, (*second
)->name
);
2246 static bool add_to_array(char ***names
, char *cname
, int pos
)
2248 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2250 ERROR("Out of memory");
2255 newnames
[pos
] = strdup(cname
);
2259 /* Sort the arrray as we will use binary search on it. */
2260 qsort(newnames
, pos
+ 1, sizeof(char *),
2261 (int (*)(const void *, const void *))string_cmp
);
2266 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2269 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2271 ERROR("Out of memory");
2278 /* Sort the arrray as we will use binary search on it. */
2280 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2281 (int (*)(const void *, const void *))container_cmp
);
2286 static char** get_from_array(char ***names
, char *cname
, int size
)
2288 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2291 static bool array_contains(char ***names
, char *cname
, int size
)
2293 if(get_from_array(names
, cname
, size
) != NULL
)
2299 static bool remove_from_array(char ***names
, char *cname
, int size
)
2301 char **result
= get_from_array(names
, cname
, size
);
2302 if (result
!= NULL
) {
2310 static char **do_lxcapi_get_interfaces(struct lxc_container
*c
)
2313 int i
, count
= 0, pipefd
[2];
2314 char **interfaces
= NULL
;
2315 char interface
[IFNAMSIZ
];
2317 if (pipe2(pipefd
, O_CLOEXEC
) < 0)
2322 SYSERROR("Failed to fork task to get interfaces information");
2328 if (pid
== 0) { /* child */
2329 int ret
= 1, nbytes
;
2330 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2332 /* close the read-end of the pipe */
2335 if (!enter_net_ns(c
)) {
2336 SYSERROR("Failed to enter network namespace");
2340 /* Grab the list of interfaces */
2341 if (getifaddrs(&interfaceArray
)) {
2342 SYSERROR("Failed to get interfaces list");
2346 /* Iterate through the interfaces */
2347 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
;
2348 tempIfAddr
= tempIfAddr
->ifa_next
) {
2349 nbytes
= lxc_write_nointr(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2360 freeifaddrs(interfaceArray
);
2362 /* close the write-end of the pipe, thus sending EOF to the reader */
2367 /* close the write-end of the pipe */
2370 while (lxc_read_nointr(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2371 interface
[IFNAMSIZ
- 1] = '\0';
2373 if (array_contains(&interfaces
, interface
, count
))
2376 if (!add_to_array(&interfaces
, interface
, count
))
2377 ERROR("Failed to add \"%s\" to array", interface
);
2382 if (wait_for_pid(pid
) != 0) {
2383 for (i
= 0; i
< count
; i
++)
2384 free(interfaces
[i
]);
2390 /* close the read-end of the pipe */
2393 /* Append NULL to the array */
2395 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2400 WRAP_API(char **, lxcapi_get_interfaces
)
2402 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2403 const char *family
, int scope
)
2408 char address
[INET6_ADDRSTRLEN
];
2410 char **addresses
= NULL
;
2412 ret
= pipe2(pipefd
, O_CLOEXEC
);
2414 SYSERROR("Failed to create pipe");
2420 SYSERROR("Failed to create new process");
2428 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2430 char *address
= NULL
;
2431 void *tempAddrPtr
= NULL
;
2432 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2434 /* close the read-end of the pipe */
2437 if (!enter_net_ns(c
)) {
2438 SYSERROR("Failed to attach to network namespace");
2442 /* Grab the list of interfaces */
2443 if (getifaddrs(&interfaceArray
)) {
2444 SYSERROR("Failed to get interfaces list");
2448 /* Iterate through the interfaces */
2449 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2450 tempIfAddr
= tempIfAddr
->ifa_next
) {
2451 if (tempIfAddr
->ifa_addr
== NULL
)
2454 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2455 if (family
&& strcmp(family
, "inet"))
2458 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2460 if (family
&& strcmp(family
, "inet6"))
2463 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2466 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2469 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2471 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2474 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2475 tempAddrPtr
, addressOutputBuffer
,
2476 sizeof(addressOutputBuffer
));
2480 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2481 if (nbytes
!= INET6_ADDRSTRLEN
) {
2482 SYSERROR("Failed to send ipv6 address \"%s\"",
2494 freeifaddrs(interfaceArray
);
2496 /* close the write-end of the pipe, thus sending EOF to the reader */
2501 /* close the write-end of the pipe */
2504 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2505 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2507 if (!add_to_array(&addresses
, address
, count
))
2508 ERROR("PARENT: add_to_array failed");
2513 if (wait_for_pid(pid
) != 0) {
2514 for (i
= 0; i
< count
; i
++)
2521 /* close the read-end of the pipe */
2524 /* Append NULL to the array */
2526 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2531 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2533 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2536 struct lxc_config_t
*config
;
2538 if (!c
|| !c
->lxc_conf
)
2541 if (container_mem_lock(c
))
2544 config
= lxc_get_config(key
);
2545 /* Verify that the config key exists and that it has a callback
2548 if (config
&& config
->get
)
2549 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2551 container_mem_unlock(c
);
2555 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2557 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2561 if (!c
|| !c
->lxc_conf
)
2564 if (container_mem_lock(c
))
2567 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2568 container_mem_unlock(c
);
2572 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2574 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2578 /* List all config items. */
2580 return lxc_list_config_items(retv
, inlen
);
2582 if (!c
|| !c
->lxc_conf
)
2585 if (container_mem_lock(c
))
2588 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2589 * This is an intelligent result to show which keys are valid given the
2590 * type of nic it is.
2592 if (strncmp(key
, "lxc.net.", 8) == 0)
2593 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2595 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2597 container_mem_unlock(c
);
2601 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2603 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2606 bool ret
= false, need_disklock
= false;
2609 alt_file
= c
->configfile
;
2614 /* If we haven't yet loaded a config, load the stock config. */
2616 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2617 ERROR("Error loading default configuration file %s "
2619 lxc_global_config_value("lxc.default_config"),
2625 if (!create_container_dir(c
))
2628 /* If we're writing to the container's config file, take the disk lock.
2629 * Otherwise just take the memlock to protect the struct lxc_container
2630 * while we're traversing it.
2632 if (strcmp(c
->configfile
, alt_file
) == 0)
2633 need_disklock
= true;
2636 lret
= container_disk_lock(c
);
2638 lret
= container_mem_lock(c
);
2642 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2643 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
2647 lret
= write_config(fd
, c
->lxc_conf
);
2656 container_disk_unlock(c
);
2658 container_mem_unlock(c
);
2663 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2666 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2672 char path
[MAXPATHLEN
];
2673 char newpath
[MAXPATHLEN
];
2674 int fd
, ret
, n
= 0, v
= 0;
2676 size_t len
= 0, bytes
= 0;
2678 if (container_disk_lock(c0
))
2681 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2682 if (ret
< 0 || ret
> MAXPATHLEN
)
2685 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2686 if (ret
< 0 || ret
> MAXPATHLEN
)
2689 /* If we find an lxc-snapshot file using the old format only listing the
2690 * number of snapshots we will keep using it. */
2691 f1
= fopen(path
, "r");
2693 n
= fscanf(f1
, "%d", &v
);
2695 if (n
== 1 && v
== 0) {
2698 SYSERROR("Failed to remove \"%s\"", path
);
2706 f1
= fopen(path
, "w");
2710 if (fprintf(f1
, "%d\n", v
) < 0) {
2711 ERROR("Error writing new snapshots value");
2718 SYSERROR("Error writing to or closing snapshots file");
2722 /* Here we know that we have or can use an lxc-snapshot file
2723 * using the new format. */
2725 f1
= fopen(path
, "a");
2729 if (fprintf(f1
, "%s", newpath
) < 0) {
2730 ERROR("Error writing new snapshots entry");
2733 SYSERROR("Error writing to or closing snapshots file");
2739 SYSERROR("Error writing to or closing snapshots file");
2743 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2746 if (fstat(fd
, &fbuf
) < 0) {
2751 if (fbuf
.st_size
!= 0) {
2752 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2753 if (buf
== MAP_FAILED
) {
2754 SYSERROR("Failed to create mapping %s", path
);
2759 len
= strlen(newpath
);
2760 while ((del
= strstr((char *)buf
, newpath
))) {
2761 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2765 lxc_strmunmap(buf
, fbuf
.st_size
);
2766 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2767 SYSERROR("Failed to truncate file %s", path
);
2776 /* If the lxc-snapshot file is empty, remove it. */
2777 if (stat(path
, &fbuf
) < 0)
2780 if (!fbuf
.st_size
) {
2783 SYSERROR("Failed to remove \"%s\"", path
);
2790 container_disk_unlock(c0
);
2794 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2796 struct lxc_container
*p
;
2797 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2798 size_t pathlen
= 0, namelen
= 0;
2802 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2803 c
->config_path
, c
->name
);
2804 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2805 ERROR("Path name too long");
2809 f
= fopen(path
, "r");
2813 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2814 if (getline(&lxcname
, &namelen
, f
) == -1) {
2815 ERROR("badly formatted file %s", path
);
2819 remove_trailing_newlines(lxcpath
);
2820 remove_trailing_newlines(lxcname
);
2822 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2823 ERROR("Unable to find dependent container %s:%s",
2828 if (!mod_rdep(p
, c
, inc
))
2829 ERROR("Failed to update snapshots file for %s:%s",
2832 lxc_container_put(p
);
2841 static bool has_fs_snapshots(struct lxc_container
*c
)
2844 char path
[MAXPATHLEN
];
2849 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2851 if (ret
< 0 || ret
> MAXPATHLEN
)
2854 /* If the file doesn't exist there are no snapshots. */
2855 if (stat(path
, &fbuf
) < 0)
2860 f
= fopen(path
, "r");
2864 ret
= fscanf(f
, "%d", &v
);
2866 /* TODO: Figure out what to do with the return value of fscanf. */
2868 INFO("Container uses new lxc-snapshots format %s", path
);
2877 static bool has_snapshots(struct lxc_container
*c
)
2879 char path
[MAXPATHLEN
];
2880 struct dirent
*direntp
;
2884 if (!get_snappath_dir(c
, path
))
2887 dir
= opendir(path
);
2891 while ((direntp
= readdir(dir
))) {
2892 if (!strcmp(direntp
->d_name
, "."))
2895 if (!strcmp(direntp
->d_name
, ".."))
2905 static bool do_destroy_container(struct lxc_conf
*conf
) {
2908 if (am_guest_unpriv()) {
2909 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2910 "storage_destroy_wrapper");
2917 return storage_destroy(conf
);
2920 static int lxc_rmdir_onedev_wrapper(void *data
)
2922 char *arg
= (char *) data
;
2923 return lxc_rmdir_onedev(arg
, "snaps");
2926 static int lxc_unlink_exec_wrapper(void *data
)
2932 static bool container_destroy(struct lxc_container
*c
,
2933 struct lxc_storage
*storage
)
2937 struct lxc_conf
*conf
;
2942 if (!c
|| !do_lxcapi_is_defined(c
))
2946 if (container_disk_lock(c
))
2949 if (!is_stopped(c
)) {
2950 /* We should queue some sort of error - in c->error_string? */
2951 ERROR("container %s is not stopped", c
->name
);
2955 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2956 /* Start of environment variable setup for hooks */
2957 if (setenv("LXC_NAME", c
->name
, 1))
2958 SYSERROR("Failed to set environment variable for container name");
2960 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2961 SYSERROR("Failed to set environment variable for config path");
2963 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2964 SYSERROR("Failed to set environment variable for rootfs mount");
2966 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2967 SYSERROR("Failed to set environment variable for rootfs mount");
2969 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2970 SYSERROR("Failed to set environment variable for console path");
2972 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2973 SYSERROR("Failed to set environment variable for console log");
2974 /* End of environment variable setup for hooks */
2976 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2977 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2982 if (current_config
&& conf
== current_config
) {
2983 current_config
= NULL
;
2985 if (conf
->logfd
!= -1) {
2991 /* LXC is not managing the storage of the container. */
2992 if (conf
&& !conf
->rootfs
.managed
)
2995 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2996 if (!do_destroy_container(conf
)) {
2997 ERROR("Error destroying rootfs for %s", c
->name
);
3000 INFO("Destroyed rootfs for %s", c
->name
);
3003 mod_all_rdeps(c
, false);
3005 p1
= do_lxcapi_get_config_path(c
);
3014 * strlen("config") = 6
3018 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3021 ERROR("Failed to allocate memory");
3025 /* For an overlay container the rootfs is considered immutable and
3026 * cannot be removed when restoring from a snapshot.
3028 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3029 !strcmp(storage
->type
, "overlayfs")) &&
3030 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3031 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3032 if (ret
< 0 || (size_t)ret
>= len
)
3035 if (am_guest_unpriv())
3036 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3037 "lxc_unlink_exec_wrapper");
3041 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3045 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3051 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3052 if (ret
< 0 || (size_t)ret
>= len
)
3055 if (am_guest_unpriv())
3056 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3057 "lxc_rmdir_onedev_wrapper");
3059 ret
= lxc_rmdir_onedev(path
, "snaps");
3061 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3065 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3074 container_disk_unlock(c
);
3078 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3080 if (!c
|| !lxcapi_is_defined(c
))
3083 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.managed
) {
3084 if (has_snapshots(c
)) {
3085 ERROR("Container %s has snapshots; not removing", c
->name
);
3089 if (has_fs_snapshots(c
)) {
3090 ERROR("container %s has snapshots on its rootfs", c
->name
);
3095 return container_destroy(c
, NULL
);
3098 WRAP_API(bool, lxcapi_destroy
)
3100 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3102 if (!c
|| !lxcapi_is_defined(c
))
3105 if (!lxcapi_snapshot_destroy_all(c
)) {
3106 ERROR("Error deleting all snapshots");
3110 return lxcapi_destroy(c
);
3113 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3115 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3119 struct lxc_config_t
*config
;
3122 config
= lxc_get_config(key
);
3126 ret
= config
->set(key
, v
, conf
, NULL
);
3130 if (lxc_config_value_empty(v
))
3131 do_clear_unexp_config_line(conf
, key
);
3133 bret
= do_append_unexp_config_line(conf
, key
, v
);
3140 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3146 c
->lxc_conf
= lxc_conf_init();
3151 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3158 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3165 if (container_mem_lock(c
))
3168 b
= do_set_config_item_locked(c
, key
, v
);
3170 container_mem_unlock(c
);
3174 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3176 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3178 if (!c
|| !c
->configfile
)
3181 return strdup(c
->configfile
);
3184 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3186 if (!c
|| !c
->config_path
)
3189 return (const char *)(c
->config_path
);
3194 * Just recalculate the c->configfile based on the
3195 * c->config_path, which must be set.
3196 * The lxc_container must be locked or not yet public.
3198 static bool set_config_filename(struct lxc_container
*c
)
3203 if (!c
->config_path
)
3206 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3207 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3208 newpath
= malloc(len
);
3212 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3213 if (ret
< 0 || ret
>= len
) {
3214 fprintf(stderr
, "Error printing out config file name\n");
3219 free(c
->configfile
);
3220 c
->configfile
= newpath
;
3225 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3229 char *oldpath
= NULL
;
3234 if (container_mem_lock(c
))
3239 ERROR("Out of memory setting new lxc path");
3245 oldpath
= c
->config_path
;
3248 /* Since we've changed the config path, we have to change the
3249 * config file name too */
3250 if (!set_config_filename(c
)) {
3251 ERROR("Out of memory setting new config filename");
3253 free(c
->config_path
);
3254 c
->config_path
= oldpath
;
3260 container_mem_unlock(c
);
3264 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3266 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3269 struct cgroup_ops
*cgroup_ops
;
3277 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3281 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3283 cgroup_exit(cgroup_ops
);
3288 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3290 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3293 struct cgroup_ops
*cgroup_ops
;
3301 cgroup_ops
= cgroup_init(c
->lxc_conf
);
3305 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3308 cgroup_exit(cgroup_ops
);
3313 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3315 const char *lxc_get_global_config_item(const char *key
)
3317 return lxc_global_config_value(key
);
3320 const char *lxc_get_version(void)
3325 static int copy_file(const char *old
, const char *new)
3332 if (file_exists(new)) {
3333 ERROR("copy destination %s exists", new);
3337 ret
= stat(old
, &sbuf
);
3339 INFO("Error stat'ing %s", old
);
3343 in
= open(old
, O_RDONLY
);
3345 SYSERROR("Error opening original file %s", old
);
3349 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3351 SYSERROR("Error opening new file %s", new);
3357 len
= lxc_read_nointr(in
, buf
, 8096);
3359 SYSERROR("Error reading old file %s", old
);
3366 ret
= lxc_write_nointr(out
, buf
, len
);
3367 if (ret
< len
) { /* should we retry? */
3368 SYSERROR("Error: write to new file %s was interrupted", new);
3376 /* We set mode, but not owner/group. */
3377 ret
= chmod(new, sbuf
.st_mode
);
3379 SYSERROR("Error setting mode on %s", new);
3391 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3394 struct lxc_list
*it
;
3397 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3398 cpath
= alloca(len
);
3399 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3400 if (ret
< 0 || ret
>= len
)
3403 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3404 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3405 char *hookname
= it
->elem
;
3406 char *fname
= strrchr(hookname
, '/');
3407 char tmppath
[MAXPATHLEN
];
3408 if (!fname
) /* relative path - we don't support, but maybe we should */
3411 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3412 /* this hook is public - ignore */
3416 /* copy the script, and change the entry in confile */
3417 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3418 c
->config_path
, c
->name
, fname
+1);
3419 if (ret
< 0 || ret
>= MAXPATHLEN
)
3422 ret
= copy_file(it
->elem
, tmppath
);
3428 it
->elem
= strdup(tmppath
);
3430 ERROR("out of memory copying hook path");
3436 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3437 c
->config_path
, oldc
->name
, c
->name
)) {
3438 ERROR("Error saving new hooks in clone");
3442 do_lxcapi_save_config(c
, NULL
);
3447 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3449 char newpath
[MAXPATHLEN
];
3450 char *oldpath
= oldc
->lxc_conf
->fstab
;
3456 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3458 char *p
= strrchr(oldpath
, '/');
3462 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3463 c
->config_path
, c
->name
, p
);
3464 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3465 ERROR("error printing new path for %s", oldpath
);
3469 if (file_exists(newpath
)) {
3470 ERROR("error: fstab file %s exists", newpath
);
3474 if (copy_file(oldpath
, newpath
) < 0) {
3475 ERROR("error: copying %s to %s", oldpath
, newpath
);
3479 free(c
->lxc_conf
->fstab
);
3481 c
->lxc_conf
->fstab
= strdup(newpath
);
3482 if (!c
->lxc_conf
->fstab
) {
3483 ERROR("error: allocating pathname");
3487 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3488 ERROR("error saving new lxctab");
3495 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3497 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3500 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3502 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3503 WARN("Error copying reverse dependencies");
3507 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3509 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3510 WARN("Error copying reverse dependencies");
3514 if (copy_file(path0
, path1
) < 0) {
3515 INFO("Error copying reverse dependencies");
3520 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3523 char path
[MAXPATHLEN
];
3527 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3529 if (ret
< 0 || ret
>= MAXPATHLEN
)
3532 f
= fopen(path
, "a");
3538 /* If anything goes wrong, just return an error. */
3539 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3549 * If the fs natively supports snapshot clones with no penalty,
3550 * then default to those even if not requested.
3551 * Currently we only do this for btrfs.
3553 bool should_default_to_snapshot(struct lxc_container
*c0
,
3554 struct lxc_container
*c1
)
3557 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3558 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3559 char *p0
= alloca(l0
+ 1);
3560 char *p1
= alloca(l1
+ 1);
3561 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3563 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3564 if (ret
< 0 || ret
>= l0
)
3567 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3568 if (ret
< 0 || ret
>= l1
)
3571 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3574 if (is_btrfs_subvol(rootfs
) <= 0)
3577 return btrfs_same_fs(p0
, p1
) == 0;
3580 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3581 const char *newtype
, int flags
, const char *bdevdata
,
3584 struct lxc_storage
*bdev
;
3587 if (should_default_to_snapshot(c0
, c
))
3588 flags
|= LXC_CLONE_SNAPSHOT
;
3590 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3591 bdevdata
, newsize
, &need_rdep
);
3593 ERROR("Error copying storage.");
3597 /* Set new rootfs. */
3598 free(c
->lxc_conf
->rootfs
.path
);
3599 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3602 if (!c
->lxc_conf
->rootfs
.path
) {
3603 ERROR("Out of memory while setting storage path.");
3607 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3608 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3609 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3610 c
->lxc_conf
->rootfs
.path
)) {
3611 ERROR("Error saving new rootfs to cloned config.");
3615 if (flags
& LXC_CLONE_SNAPSHOT
)
3616 copy_rdepends(c
, c0
);
3619 if (!add_rdepends(c
, c0
))
3620 WARN("Error adding reverse dependency from %s to %s",
3624 mod_all_rdeps(c
, true);
3629 struct clone_update_data
{
3630 struct lxc_container
*c0
;
3631 struct lxc_container
*c1
;
3636 static int clone_update_rootfs(struct clone_update_data
*data
)
3638 struct lxc_container
*c0
= data
->c0
;
3639 struct lxc_container
*c
= data
->c1
;
3640 int flags
= data
->flags
;
3641 char **hookargs
= data
->hookargs
;
3643 char path
[MAXPATHLEN
];
3644 struct lxc_storage
*bdev
;
3646 struct lxc_conf
*conf
= c
->lxc_conf
;
3648 /* update hostname in rootfs */
3649 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3651 if (setgid(0) < 0) {
3652 ERROR("Failed to setgid to 0");
3656 if (setuid(0) < 0) {
3657 ERROR("Failed to setuid to 0");
3661 if (setgroups(0, NULL
) < 0)
3662 WARN("Failed to clear groups");
3664 if (unshare(CLONE_NEWNS
) < 0)
3667 bdev
= storage_init(c
->lxc_conf
);
3671 if (strcmp(bdev
->type
, "dir") != 0) {
3672 if (unshare(CLONE_NEWNS
) < 0) {
3673 ERROR("error unsharing mounts");
3678 if (detect_shared_rootfs()) {
3679 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3680 SYSERROR("Failed to make / rslave");
3681 ERROR("Continuing...");
3685 if (bdev
->ops
->mount(bdev
) < 0) {
3689 } else { /* TODO come up with a better way */
3691 bdev
->dest
= strdup(bdev
->src
);
3694 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3695 /* Start of environment variable setup for hooks */
3696 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3697 SYSERROR("failed to set environment variable for source container name");
3699 if (setenv("LXC_NAME", c
->name
, 1))
3700 SYSERROR("failed to set environment variable for container name");
3702 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3703 SYSERROR("failed to set environment variable for config path");
3705 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3706 SYSERROR("failed to set environment variable for rootfs mount");
3708 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3709 SYSERROR("failed to set environment variable for rootfs mount");
3711 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3712 ERROR("Error executing clone hook for %s", c
->name
);
3718 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3719 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3722 if (ret
< 0 || ret
>= MAXPATHLEN
)
3725 if (!file_exists(path
))
3728 if (!(fout
= fopen(path
, "w"))) {
3729 SYSERROR("unable to open %s: ignoring", path
);
3733 if (fprintf(fout
, "%s", c
->name
) < 0) {
3738 if (fclose(fout
) < 0)
3747 static int clone_update_rootfs_wrapper(void *data
)
3749 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3750 return clone_update_rootfs(arg
);
3754 * We want to support:
3755 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3756 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3758 -s [ implies overlay]
3761 only rootfs gets converted (copied/snapshotted) on clone.
3764 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3766 char *p
= strrchr(path
, '/');
3773 ret
= do_create_container_dir(path
, conf
);
3779 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3780 const char *lxcpath
, int flags
,
3781 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3784 char newpath
[MAXPATHLEN
];
3786 struct clone_update_data data
;
3787 size_t saved_unexp_len
;
3789 int storage_copied
= 0;
3790 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3791 struct lxc_container
*c2
= NULL
;
3793 if (!c
|| !do_lxcapi_is_defined(c
))
3796 if (container_mem_lock(c
))
3799 if (!is_stopped(c
)) {
3800 ERROR("error: Original container (%s) is running", c
->name
);
3804 /* Make sure the container doesn't yet exist. */
3809 lxcpath
= do_lxcapi_get_config_path(c
);
3811 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3812 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3813 SYSERROR("clone: failed making config pathname");
3817 if (file_exists(newpath
)) {
3818 ERROR("error: clone: %s exists", newpath
);
3822 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3823 if (ret
< 0 && errno
!= EEXIST
) {
3824 ERROR("Error creating container dir for %s", newpath
);
3828 /* Copy the configuration. Tweak it as needed. */
3829 if (c
->lxc_conf
->rootfs
.path
) {
3830 origroot
= c
->lxc_conf
->rootfs
.path
;
3831 c
->lxc_conf
->rootfs
.path
= NULL
;
3834 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3835 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
3837 SYSERROR("Failed to open \"%s\"", newpath
);
3841 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3842 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3843 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3844 if (!c
->lxc_conf
->unexpanded_config
) {
3849 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3850 write_config(fd
, c
->lxc_conf
);
3853 c
->lxc_conf
->rootfs
.path
= origroot
;
3855 free(c
->lxc_conf
->unexpanded_config
);
3856 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3857 saved_unexp_conf
= NULL
;
3858 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3860 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3861 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3862 SYSERROR("clone: failed making rootfs pathname");
3866 ret
= mkdir(newpath
, 0755);
3868 /* For an overlay container the rootfs is considered immutable
3869 * and will not have been removed when restoring from a
3872 if (errno
!= ENOENT
&&
3873 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3874 SYSERROR("Failed to create directory \"%s\"", newpath
);
3879 if (am_guest_unpriv()) {
3880 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3881 ERROR("Error chowning %s to container root", newpath
);
3886 c2
= lxc_container_new(newname
, lxcpath
);
3888 ERROR("clone: failed to create new container (%s %s)", newname
,
3893 /* copy/snapshot rootfs's */
3894 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3898 /* update utsname */
3899 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3900 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3901 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3903 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3904 ERROR("Error setting new hostname");
3910 ret
= copyhooks(c
, c2
);
3912 ERROR("error copying hooks");
3916 if (copy_fstab(c
, c2
) < 0) {
3917 ERROR("error copying fstab");
3921 /* update macaddrs */
3922 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3923 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3924 ERROR("Error updating mac addresses");
3929 /* Update absolute paths for overlay mount directories. */
3930 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3933 /* We've now successfully created c2's storage, so clear it out if we
3938 if (!c2
->save_config(c2
, NULL
))
3941 if ((pid
= fork()) < 0) {
3947 ret
= wait_for_pid(pid
);
3951 container_mem_unlock(c
);
3958 data
.hookargs
= hookargs
;
3960 if (am_guest_unpriv())
3961 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3962 &data
, "clone_update_rootfs_wrapper");
3964 ret
= clone_update_rootfs(&data
);
3966 _exit(EXIT_FAILURE
);
3968 container_mem_unlock(c
);
3969 _exit(EXIT_SUCCESS
);
3972 container_mem_unlock(c
);
3974 if (!storage_copied
)
3975 c2
->lxc_conf
->rootfs
.path
= NULL
;
3978 lxc_container_put(c2
);
3984 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3985 const char *lxcpath
, int flags
,
3986 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3989 struct lxc_container
* ret
;
3991 current_config
= c
? c
->lxc_conf
: NULL
;
3992 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3993 current_config
= NULL
;
3998 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
4000 struct lxc_storage
*bdev
;
4001 struct lxc_container
*newc
;
4003 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
4006 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
4007 ERROR("Renaming a container with snapshots is not supported");
4011 bdev
= storage_init(c
->lxc_conf
);
4013 ERROR("Failed to find original backing store type");
4017 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4020 lxc_container_put(newc
);
4024 if (newc
&& lxcapi_is_defined(newc
))
4025 lxc_container_put(newc
);
4027 if (!container_destroy(c
, NULL
)) {
4028 ERROR("Could not destroy existing container %s", c
->name
);
4035 WRAP_API_1(bool, lxcapi_rename
, const char *)
4037 static int lxcapi_attach(struct lxc_container
*c
, lxc_attach_exec_t exec_function
, void *exec_payload
, lxc_attach_options_t
*options
, pid_t
*attached_process
)
4044 current_config
= c
->lxc_conf
;
4046 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4047 current_config
= NULL
;
4051 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4053 lxc_attach_command_t command
;
4060 command
.program
= (char*)program
;
4061 command
.argv
= (char**)argv
;
4063 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4069 return lxc_wait_for_pid_status(pid
);
4072 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4076 current_config
= c
? c
->lxc_conf
: NULL
;
4077 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4078 current_config
= NULL
;
4083 static int get_next_index(const char *lxcpath
, char *cname
)
4089 fname
= alloca(strlen(lxcpath
) + 20);
4092 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4094 ret
= stat(fname
, &sb
);
4102 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4107 * If the old style snapshot path exists, use it
4108 * /var/lib/lxc -> /var/lib/lxcsnaps
4110 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
4111 if (ret
< 0 || ret
>= MAXPATHLEN
)
4114 if (dir_exists(snappath
)) {
4115 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
4116 if (ret
< 0 || ret
>= MAXPATHLEN
)
4123 * Use the new style path
4124 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4126 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
4127 if (ret
< 0 || ret
>= MAXPATHLEN
)
4133 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4138 struct lxc_container
*c2
;
4139 char snappath
[MAXPATHLEN
], newname
[20];
4143 if (!c
|| !lxcapi_is_defined(c
))
4146 if (!storage_can_backup(c
->lxc_conf
)) {
4147 ERROR("%s's backing store cannot be backed up", c
->name
);
4148 ERROR("Your container must use another backing store type");
4152 if (!get_snappath_dir(c
, snappath
))
4155 i
= get_next_index(snappath
, c
->name
);
4157 if (mkdir_p(snappath
, 0755) < 0) {
4158 ERROR("Failed to create snapshot directory %s", snappath
);
4162 ret
= snprintf(newname
, 20, "snap%d", i
);
4163 if (ret
< 0 || ret
>= 20)
4167 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4168 * created in the original container
4170 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4171 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4172 if (storage_is_dir(c
->lxc_conf
)) {
4173 ERROR("Snapshot of directory-backed container requested");
4174 ERROR("Making a copy-clone. If you do want snapshots, then");
4175 ERROR("please create overlay clone first, snapshot that");
4176 ERROR("and keep the original container pristine");
4177 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4180 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4182 ERROR("Failed to clone of %s:%s", c
->config_path
, c
->name
);
4186 lxc_container_put(c2
);
4188 /* Now write down the creation time. */
4191 if (!localtime_r(&timer
, &tm_info
)) {
4192 ERROR("Failed to get localtime");
4196 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", &tm_info
);
4198 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4199 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4200 f
= fopen(dfnam
, "w");
4202 ERROR("Failed to open %s", dfnam
);
4206 if (fprintf(f
, "%s", buffer
) < 0) {
4207 SYSERROR("Writing timestamp");
4214 SYSERROR("Writing timestamp");
4219 /* $p / $name / comment \0 */
4220 int len
= strlen(snappath
) + strlen(newname
) + 10;
4221 char *path
= alloca(len
);
4223 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4224 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4230 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4232 static void lxcsnap_free(struct lxc_snapshot
*s
)
4235 free(s
->comment_pathname
);
4240 static char *get_snapcomment_path(char* snappath
, char *name
)
4242 /* $snappath/$name/comment */
4243 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4244 char *s
= malloc(len
);
4247 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4248 if (ret
< 0 || ret
>= len
) {
4257 static char *get_timestamp(char* snappath
, char *name
)
4259 char path
[MAXPATHLEN
], *s
= NULL
;
4263 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4264 if (ret
< 0 || ret
>= MAXPATHLEN
)
4267 fin
= fopen(path
, "r");
4271 (void) fseek(fin
, 0, SEEK_END
);
4273 (void) fseek(fin
, 0, SEEK_SET
);
4278 if (fread(s
, 1, len
, fin
) != len
) {
4279 SYSERROR("reading timestamp");
4290 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4292 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4294 struct dirent
*direntp
;
4295 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4298 if (!c
|| !lxcapi_is_defined(c
))
4301 if (!get_snappath_dir(c
, snappath
)) {
4302 ERROR("path name too long");
4306 dir
= opendir(snappath
);
4308 INFO("Failed to open %s - assuming no snapshots", snappath
);
4312 while ((direntp
= readdir(dir
))) {
4313 if (!strcmp(direntp
->d_name
, "."))
4316 if (!strcmp(direntp
->d_name
, ".."))
4319 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4320 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4321 ERROR("pathname too long");
4325 if (!file_exists(path2
))
4328 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4330 SYSERROR("Out of memory");
4335 snaps
[count
].free
= lxcsnap_free
;
4336 snaps
[count
].name
= strdup(direntp
->d_name
);
4337 if (!snaps
[count
].name
)
4340 snaps
[count
].lxcpath
= strdup(snappath
);
4341 if (!snaps
[count
].lxcpath
) {
4342 free(snaps
[count
].name
);
4346 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4347 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4352 WARN("Failed to close directory");
4361 for (i
=0; i
<count
; i
++)
4362 lxcsnap_free(&snaps
[i
]);
4368 WARN("Failed to close directory");
4373 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4375 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4377 char clonelxcpath
[MAXPATHLEN
];
4379 struct lxc_container
*snap
, *rest
;
4380 struct lxc_storage
*bdev
;
4383 if (!c
|| !c
->name
|| !c
->config_path
)
4386 if (has_fs_snapshots(c
)) {
4387 ERROR("container rootfs has dependent snapshots");
4391 bdev
= storage_init(c
->lxc_conf
);
4393 ERROR("Failed to find original backing store type");
4397 /* For an overlay container the rootfs is considered immutable
4398 * and cannot be removed when restoring from a snapshot. We pass this
4399 * internal flag along to communicate this to various parts of the
4402 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4403 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4408 if (!get_snappath_dir(c
, clonelxcpath
)) {
4412 /* how should we lock this? */
4414 snap
= lxc_container_new(snapname
, clonelxcpath
);
4415 if (!snap
|| !lxcapi_is_defined(snap
)) {
4416 ERROR("Could not open snapshot %s", snapname
);
4419 lxc_container_put(snap
);
4425 if (!strcmp(c
->name
, newname
)) {
4426 if (!container_destroy(c
, bdev
)) {
4427 ERROR("Could not destroy existing container %s", newname
);
4428 lxc_container_put(snap
);
4434 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4435 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4437 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4438 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4440 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4443 if (rest
&& lxcapi_is_defined(rest
))
4447 lxc_container_put(rest
);
4449 lxc_container_put(snap
);
4453 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4455 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4457 struct lxc_container
*snap
= NULL
;
4460 snap
= lxc_container_new(snapname
, clonelxcpath
);
4462 ERROR("Could not find snapshot %s", snapname
);
4466 if (!do_lxcapi_destroy(snap
)) {
4467 ERROR("Could not destroy snapshot %s", snapname
);
4475 lxc_container_put(snap
);
4480 static bool remove_all_snapshots(const char *path
)
4483 struct dirent
*direntp
;
4486 dir
= opendir(path
);
4488 SYSERROR("opendir on snapshot path %s", path
);
4492 while ((direntp
= readdir(dir
))) {
4493 if (!strcmp(direntp
->d_name
, "."))
4496 if (!strcmp(direntp
->d_name
, ".."))
4499 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4508 SYSERROR("Error removing directory %s", path
);
4513 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4515 char clonelxcpath
[MAXPATHLEN
];
4517 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4520 if (!get_snappath_dir(c
, clonelxcpath
))
4523 return do_snapshot_destroy(snapname
, clonelxcpath
);
4526 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4528 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4530 char clonelxcpath
[MAXPATHLEN
];
4532 if (!c
|| !c
->name
|| !c
->config_path
)
4535 if (!get_snappath_dir(c
, clonelxcpath
))
4538 return remove_all_snapshots(clonelxcpath
);
4541 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4543 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4548 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4551 WRAP_API(bool, lxcapi_may_control
)
4553 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4559 char chrootpath
[MAXPATHLEN
];
4560 char *directory_path
= NULL
;
4564 SYSERROR("Failed to fork()");
4569 ret
= wait_for_pid(pid
);
4571 ERROR("Failed to create device node");
4578 /* prepare the path */
4579 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4580 if (ret
< 0 || ret
>= MAXPATHLEN
)
4583 ret
= chroot(chrootpath
);
4585 _exit(EXIT_FAILURE
);
4589 _exit(EXIT_FAILURE
);
4591 /* remove path if it exists */
4592 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4596 SYSERROR("Failed to remove \"%s\"", path
);
4597 _exit(EXIT_FAILURE
);
4602 _exit(EXIT_SUCCESS
);
4604 /* create any missing directories */
4607 _exit(EXIT_FAILURE
);
4609 directory_path
= dirname(tmp
);
4610 ret
= mkdir_p(directory_path
, 0755);
4611 if (ret
< 0 && errno
!= EEXIST
) {
4612 SYSERROR("Failed to create path \"%s\"", directory_path
);
4614 _exit(EXIT_FAILURE
);
4617 /* create the device node */
4618 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4621 SYSERROR("Failed to create device node at \"%s\"", path
);
4622 _exit(EXIT_FAILURE
);
4625 _exit(EXIT_SUCCESS
);
4628 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4632 char value
[LXC_MAX_BUFFER
];
4635 /* make sure container is running */
4636 if (!do_lxcapi_is_running(c
)) {
4637 ERROR("container is not running");
4641 /* use src_path if dest_path is NULL otherwise use dest_path */
4642 p
= dest_path
? dest_path
: src_path
;
4644 /* make sure we can access p */
4645 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4648 /* continue if path is character device or block device */
4649 if (S_ISCHR(st
.st_mode
))
4650 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4651 else if (S_ISBLK(st
.st_mode
))
4652 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4656 /* check snprintf return code */
4657 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4660 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4663 /* add or remove device to/from cgroup access list */
4665 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4666 ERROR("set_cgroup_item failed while adding the device node");
4670 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4671 ERROR("set_cgroup_item failed while removing the device node");
4679 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4681 // cannot mknod if we're not privileged wrt init_user_ns
4682 if (am_host_unpriv()) {
4683 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4687 return add_remove_device_node(c
, src_path
, dest_path
, true);
4690 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4692 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4694 if (am_guest_unpriv()) {
4695 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4699 return add_remove_device_node(c
, src_path
, dest_path
, false);
4702 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4704 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4706 const char *dst_ifname
)
4711 if (am_guest_unpriv()) {
4712 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4717 ERROR("No source interface name given");
4721 ret
= lxc_netdev_isup(ifname
);
4723 /* netdev of ifname is up. */
4724 ret
= lxc_netdev_down(ifname
);
4729 init_pid
= do_lxcapi_init_pid(c
);
4730 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4734 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4741 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4743 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4745 const char *dst_ifname
)
4748 pid_t pid
, pid_outside
;
4751 * TODO - if this is a physical device, then we need am_host_unpriv.
4752 * But for other types guest privilege suffices.
4754 if (am_guest_unpriv()) {
4755 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4760 ERROR("No source interface name given");
4764 pid_outside
= lxc_raw_getpid();
4767 ERROR("Failed to fork");
4771 if (pid
== 0) { /* child */
4774 init_pid
= do_lxcapi_init_pid(c
);
4775 if (!switch_to_ns(init_pid
, "net")) {
4776 ERROR("Failed to enter network namespace");
4777 _exit(EXIT_FAILURE
);
4780 ret
= lxc_netdev_isup(ifname
);
4782 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4783 _exit(EXIT_FAILURE
);
4786 /* netdev of ifname is up. */
4788 ret
= lxc_netdev_down(ifname
);
4790 ERROR("Failed to set network device \"%s\" down", ifname
);
4791 _exit(EXIT_FAILURE
);
4795 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4796 /* -EINVAL means there is no netdev named as ifname. */
4799 ERROR("Network device \"%s\" not found", ifname
);
4801 ERROR("Failed to remove network device \"%s\"", ifname
);
4803 _exit(EXIT_FAILURE
);
4806 _exit(EXIT_SUCCESS
);
4809 ret
= wait_for_pid(pid
);
4813 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4817 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4819 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4820 struct migrate_opts
*opts
, unsigned int size
)
4823 struct migrate_opts
*valid_opts
= opts
;
4824 uint64_t features_to_check
= 0;
4826 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4827 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4828 * to do anything special.
4830 if (size
> sizeof(*opts
)) {
4831 unsigned char *addr
;
4834 addr
= (void *)opts
+ sizeof(*opts
);
4835 end
= (void *)opts
+ size
;
4837 for (; addr
< end
; addr
++)
4842 /* If the caller has a smaller struct, let's zero out the end for them
4843 * so we don't accidentally use bits of it that they didn't know about
4846 if (size
< sizeof(*opts
)) {
4847 valid_opts
= malloc(sizeof(*opts
));
4851 memset(valid_opts
, 0, sizeof(*opts
));
4852 memcpy(valid_opts
, opts
, size
);
4856 case MIGRATE_PRE_DUMP
:
4857 if (!do_lxcapi_is_running(c
)) {
4858 ERROR("container is not running");
4862 ret
= !__criu_pre_dump(c
, valid_opts
);
4865 if (!do_lxcapi_is_running(c
)) {
4866 ERROR("container is not running");
4870 ret
= !__criu_dump(c
, valid_opts
);
4872 case MIGRATE_RESTORE
:
4873 if (do_lxcapi_is_running(c
)) {
4874 ERROR("container is already running");
4878 ret
= !__criu_restore(c
, valid_opts
);
4880 case MIGRATE_FEATURE_CHECK
:
4881 features_to_check
= valid_opts
->features_to_check
;
4882 ret
= !__criu_check_feature(&features_to_check
);
4884 /* Something went wrong. Let's let the caller
4885 * know which feature checks failed. */
4886 valid_opts
->features_to_check
= features_to_check
;
4890 ERROR("invalid migrate command %u", cmd
);
4895 if (size
< sizeof(*opts
))
4901 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4903 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4905 struct migrate_opts opts
;
4907 memset(&opts
, 0, sizeof(opts
));
4909 opts
.directory
= directory
;
4911 opts
.verbose
= verbose
;
4913 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4916 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4918 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4920 struct migrate_opts opts
;
4922 memset(&opts
, 0, sizeof(opts
));
4924 opts
.directory
= directory
;
4925 opts
.verbose
= verbose
;
4927 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4930 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4932 /* @st_mode is the st_mode field of the stat(source) return struct */
4933 static int create_mount_target(const char *dest
, mode_t st_mode
)
4935 char *dirdup
, *destdirname
;
4938 dirdup
= strdup(dest
);
4940 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4943 destdirname
= dirname(dirdup
);
4945 ret
= mkdir_p(destdirname
, 0755);
4947 SYSERROR("Failed to create \"%s\"", destdirname
);
4955 if (S_ISDIR(st_mode
))
4956 ret
= mkdir(dest
, 0000);
4958 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4960 SYSERROR("Failed to create mount target \"%s\"", dest
);
4967 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4968 const char *target
, const char *filesystemtype
,
4969 unsigned long mountflags
, const void *data
,
4970 struct lxc_mount
*mnt
)
4973 char template[MAXPATHLEN
], path
[MAXPATHLEN
];
4974 pid_t pid
, init_pid
;
4976 int ret
= -1, fd
= -EBADF
;
4978 if (!c
|| !c
->lxc_conf
) {
4979 ERROR("Container or configuration is NULL");
4983 if (!c
->lxc_conf
->shmount
.path_host
) {
4984 ERROR("Host path to shared mountpoint must be specified in the config\n");
4988 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
4989 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
4990 SYSERROR("Error writing shmounts tempdir name");
4994 /* Create a temporary file / dir under the shared mountpoint */
4995 if (!source
|| strcmp(source
, "") == 0) {
4996 /* If source is not specified, maybe we want to mount a filesystem? */
4997 sb
.st_mode
= S_IFDIR
;
4999 ret
= stat(source
, &sb
);
5001 SYSERROR("Error getting stat info about the source \"%s\"", source
);
5006 if (S_ISDIR(sb
.st_mode
)) {
5007 sret
= mkdtemp(template);
5009 SYSERROR("Could not create shmounts temporary dir");
5013 fd
= lxc_make_tmpfile(template, false);
5015 SYSERROR("Could not create shmounts temporary file");
5023 SYSERROR("Could not fork");
5029 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5031 SYSERROR("Failed to mount onto \"%s\"", template);
5032 _exit(EXIT_FAILURE
);
5034 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5036 init_pid
= do_lxcapi_init_pid(c
);
5038 ERROR("Failed to obtain container's init pid");
5039 _exit(EXIT_FAILURE
);
5042 /* Enter the container namespaces */
5043 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5044 if (!switch_to_ns(init_pid
, "user")){
5045 ERROR("Failed to enter user namespace");
5046 _exit(EXIT_FAILURE
);
5050 if (!switch_to_ns(init_pid
, "mnt")) {
5051 ERROR("Failed to enter mount namespace");
5052 _exit(EXIT_FAILURE
);
5055 ret
= create_mount_target(target
, sb
.st_mode
);
5057 _exit(EXIT_FAILURE
);
5058 TRACE("Created mount target \"%s\"", target
);
5060 suff
= strrchr(template, '/');
5062 _exit(EXIT_FAILURE
);
5064 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5065 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5066 SYSERROR("Error writing container mountpoint name");
5067 _exit(EXIT_FAILURE
);
5070 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5072 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5073 _exit(EXIT_FAILURE
);
5075 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5077 _exit(EXIT_SUCCESS
);
5080 ret
= wait_for_pid(pid
);
5082 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5088 (void)umount2(template, MNT_DETACH
);
5089 (void)unlink(template);
5098 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5099 unsigned long, const void *, struct lxc_mount
*)
5101 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5102 unsigned long flags
, struct lxc_mount
*mnt
)
5104 pid_t pid
, init_pid
;
5107 if (!c
|| !c
->lxc_conf
) {
5108 ERROR("Container or configuration is NULL");
5115 SYSERROR("Could not fork");
5120 init_pid
= do_lxcapi_init_pid(c
);
5122 ERROR("Failed to obtain container's init pid");
5123 _exit(EXIT_FAILURE
);
5126 /* Enter the container namespaces */
5127 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5128 if (!switch_to_ns(init_pid
, "user")) {
5129 ERROR("Failed to enter user namespace");
5130 _exit(EXIT_FAILURE
);
5134 if (!switch_to_ns(init_pid
, "mnt")) {
5135 ERROR("Failed to enter mount namespace");
5136 _exit(EXIT_FAILURE
);
5139 /* Do the unmount */
5140 ret
= umount2(target
, flags
);
5142 SYSERROR("Failed to umount \"%s\"", target
);
5143 _exit(EXIT_FAILURE
);
5146 _exit(EXIT_SUCCESS
);
5149 ret
= wait_for_pid(pid
);
5151 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5158 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5160 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5169 current_config
= c
->lxc_conf
;
5172 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5176 ERROR("Memory allocation error.");
5182 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5186 current_config
= NULL
;
5190 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5192 struct lxc_container
*c
;
5198 c
= malloc(sizeof(*c
));
5200 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5203 memset(c
, 0, sizeof(*c
));
5206 c
->config_path
= strdup(configpath
);
5208 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5209 if (!c
->config_path
) {
5210 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5214 remove_trailing_slashes(c
->config_path
);
5217 c
->name
= malloc(len
+ 1);
5219 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5222 (void)strlcpy(c
->name
, name
, len
+ 1);
5225 c
->slock
= lxc_newlock(c
->config_path
, name
);
5227 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5231 c
->privlock
= lxc_newlock(NULL
, NULL
);
5233 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5237 if (!set_config_filename(c
)) {
5238 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5242 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5243 fprintf(stderr
, "Failed to load config for %s\n", name
);
5247 if (ongoing_create(c
) == 2) {
5248 ERROR("Failed to complete container creation for %s", c
->name
);
5249 container_destroy(c
, NULL
);
5250 lxcapi_clear_config(c
);
5253 c
->daemonize
= true;
5256 /* Assign the member functions. */
5257 c
->is_defined
= lxcapi_is_defined
;
5258 c
->state
= lxcapi_state
;
5259 c
->is_running
= lxcapi_is_running
;
5260 c
->freeze
= lxcapi_freeze
;
5261 c
->unfreeze
= lxcapi_unfreeze
;
5262 c
->console
= lxcapi_console
;
5263 c
->console_getfd
= lxcapi_console_getfd
;
5264 c
->init_pid
= lxcapi_init_pid
;
5265 c
->load_config
= lxcapi_load_config
;
5266 c
->want_daemonize
= lxcapi_want_daemonize
;
5267 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5268 c
->start
= lxcapi_start
;
5269 c
->startl
= lxcapi_startl
;
5270 c
->stop
= lxcapi_stop
;
5271 c
->config_file_name
= lxcapi_config_file_name
;
5272 c
->wait
= lxcapi_wait
;
5273 c
->set_config_item
= lxcapi_set_config_item
;
5274 c
->destroy
= lxcapi_destroy
;
5275 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5276 c
->rename
= lxcapi_rename
;
5277 c
->save_config
= lxcapi_save_config
;
5278 c
->get_keys
= lxcapi_get_keys
;
5279 c
->create
= lxcapi_create
;
5280 c
->createl
= lxcapi_createl
;
5281 c
->shutdown
= lxcapi_shutdown
;
5282 c
->reboot
= lxcapi_reboot
;
5283 c
->reboot2
= lxcapi_reboot2
;
5284 c
->clear_config
= lxcapi_clear_config
;
5285 c
->clear_config_item
= lxcapi_clear_config_item
;
5286 c
->get_config_item
= lxcapi_get_config_item
;
5287 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5288 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5289 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5290 c
->get_config_path
= lxcapi_get_config_path
;
5291 c
->set_config_path
= lxcapi_set_config_path
;
5292 c
->clone
= lxcapi_clone
;
5293 c
->get_interfaces
= lxcapi_get_interfaces
;
5294 c
->get_ips
= lxcapi_get_ips
;
5295 c
->attach
= lxcapi_attach
;
5296 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5297 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5298 c
->snapshot
= lxcapi_snapshot
;
5299 c
->snapshot_list
= lxcapi_snapshot_list
;
5300 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5301 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5302 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5303 c
->may_control
= lxcapi_may_control
;
5304 c
->add_device_node
= lxcapi_add_device_node
;
5305 c
->remove_device_node
= lxcapi_remove_device_node
;
5306 c
->attach_interface
= lxcapi_attach_interface
;
5307 c
->detach_interface
= lxcapi_detach_interface
;
5308 c
->checkpoint
= lxcapi_checkpoint
;
5309 c
->restore
= lxcapi_restore
;
5310 c
->migrate
= lxcapi_migrate
;
5311 c
->console_log
= lxcapi_console_log
;
5312 c
->mount
= lxcapi_mount
;
5313 c
->umount
= lxcapi_umount
;
5318 lxc_container_free(c
);
5322 int lxc_get_wait_states(const char **states
)
5327 for (i
=0; i
<MAX_STATE
; i
++)
5328 states
[i
] = lxc_state2str(i
);
5334 * These next two could probably be done smarter with reusing a common function
5335 * with different iterators and tests...
5337 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5340 int i
, cfound
= 0, nfound
= 0;
5341 struct dirent
*direntp
;
5342 struct lxc_container
*c
;
5345 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5347 dir
= opendir(lxcpath
);
5349 SYSERROR("opendir on lxcpath");
5359 while ((direntp
= readdir(dir
))) {
5360 /* Ignore '.', '..' and any hidden directory. */
5361 if (!strncmp(direntp
->d_name
, ".", 1))
5364 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5368 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5378 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5380 INFO("Container %s:%s has a config but could not be loaded",
5381 lxcpath
, direntp
->d_name
);
5384 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5390 if (!do_lxcapi_is_defined(c
)) {
5391 INFO("Container %s:%s has a config but is not defined",
5392 lxcpath
, direntp
->d_name
);
5395 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5398 lxc_container_put(c
);
5402 if (!add_to_clist(cret
, c
, nfound
, true)) {
5403 lxc_container_put(c
);
5414 if (names
&& *names
) {
5415 for (i
=0; i
<cfound
; i
++)
5420 if (cret
&& *cret
) {
5421 for (i
=0; i
<nfound
; i
++)
5422 lxc_container_put((*cret
)[i
]);
5430 int list_active_containers(const char *lxcpath
, char ***nret
,
5431 struct lxc_container
***cret
)
5433 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5436 char **ct_name
= NULL
;
5438 struct lxc_container
*c
= NULL
;
5442 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5443 lxcpath_len
= strlen(lxcpath
);
5451 FILE *f
= fopen("/proc/net/unix", "r");
5455 while (getline(&line
, &len
, f
) != -1) {
5456 char *p
= strrchr(line
, ' '), *p2
;
5467 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5469 } else if (strncmp(p
, "lxc/", 4) == 0) {
5479 /* Now p is the start of lxc_name. */
5480 p2
= strchr(p
, '/');
5481 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5486 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5490 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5496 p
= lxc_cmd_get_name(p
);
5501 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5507 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5510 goto free_cret_list
;
5521 c
= lxc_container_new(p
, lxcpath
);
5523 INFO("Container %s:%s is running but could not be loaded",
5526 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5537 * If this is an anonymous container, then is_defined *can*
5538 * return false. So we don't do that check. Count on the
5539 * fact that the command socket exists.
5542 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5543 lxc_container_put(c
);
5544 goto free_cret_list
;
5550 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5552 lxc_container_put(c
);
5553 goto free_cret_list
;
5565 if (cret
&& *cret
) {
5566 for (i
= 0; i
< cret_cnt
; i
++)
5567 lxc_container_put((*cret
)[i
]);
5573 for (i
= 0; i
< ct_name_cnt
; i
++)
5584 int list_all_containers(const char *lxcpath
, char ***nret
,
5585 struct lxc_container
***cret
)
5587 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5590 struct lxc_container
**ct_list
= NULL
;
5592 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5596 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5597 if (active_cnt
< 0) {
5602 for (i
= 0; i
< active_cnt
; i
++) {
5603 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5604 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5606 goto free_active_name
;
5612 free(active_name
[i
]);
5613 active_name
[i
] = NULL
;
5620 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5621 struct lxc_container
*c
;
5623 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5625 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5626 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5630 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5631 lxc_container_put(c
);
5652 for (i
= 0; i
< ct_list_cnt
; i
++) {
5653 lxc_container_put(ct_list
[i
]);
5658 for (i
= 0; i
< active_cnt
; i
++) {
5659 free(active_name
[i
]);
5664 for (i
= 0; i
< ct_cnt
; i
++) {
5671 bool lxc_config_item_is_supported(const char *key
)
5673 return !!lxc_get_config(key
);
5676 bool lxc_has_api_extension(const char *extension
)
5678 /* The NULL API extension is always present. :) */
5682 for (size_t i
= 0; i
< nr_api_extensions
; i
++)
5683 if (strcmp(api_extensions
[i
], extension
) == 0)