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>
48 #include "commands_utils.h"
52 #include "confile_utils.h"
55 #include "initutils.h"
58 #include "lxccontainer.h"
61 #include "namespace.h"
67 #include "storage/btrfs.h"
68 #include "storage/overlay.h"
69 #include "storage_utils.h"
77 #include <sys/mkdev.h>
83 #include <../include/ifaddrs.h>
87 #include <../include/lxcmntent.h>
93 #include "include/strlcpy.h"
96 /* Define faccessat() if missing from the C library */
97 #ifndef HAVE_FACCESSAT
98 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
100 #ifdef __NR_faccessat
101 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
109 lxc_log_define(lxccontainer
, lxc
);
111 static bool do_lxcapi_destroy(struct lxc_container
*c
);
112 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
113 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
114 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
115 static bool container_destroy(struct lxc_container
*c
,
116 struct lxc_storage
*storage
);
117 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
118 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
119 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
121 static bool config_file_exists(const char *lxcpath
, const char *cname
)
127 /* $lxcpath + '/' + $cname + '/config' + \0 */
128 len
= strlen(lxcpath
) + strlen(cname
) + 9;
130 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
131 if (ret
< 0 || (size_t)ret
>= len
)
134 return file_exists(fname
);
137 /* A few functions to help detect when a container creation failed. If a
138 * container creation was killed partway through, then trying to actually start
139 * that container could harm the host. We detect this by creating a 'partial'
140 * file under the container directory, and keeping an advisory lock. When
141 * container creation completes, we remove that file. When we load or try to
142 * start a container, if we find that file, without a flock, we remove the
145 static int ongoing_create(struct lxc_container
*c
)
150 struct flock lk
= {0};
152 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
154 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
155 if (ret
< 0 || (size_t)ret
>= len
)
158 if (!file_exists(path
))
161 fd
= open(path
, O_RDWR
);
166 lk
.l_whence
= SEEK_SET
;
169 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
170 if (ret
< 0 && errno
== EINVAL
)
171 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
175 if (ret
== 0 && lk
.l_pid
!= -1)
176 /* create is still ongoing */
179 /* Create completed but partial is still there. */
183 static int create_partial(struct lxc_container
*c
)
188 struct flock lk
= {0};
190 /* $lxcpath + '/' + $name + '/partial' + \0 */
191 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
193 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
194 if (ret
< 0 || (size_t)ret
>= len
)
197 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
202 lk
.l_whence
= SEEK_SET
;
204 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
206 if (errno
== EINVAL
) {
207 ret
= flock(fd
, LOCK_EX
);
212 SYSERROR("Failed to lock partial file %s", path
);
220 static void remove_partial(struct lxc_container
*c
, int fd
)
228 /* $lxcpath + '/' + $name + '/partial' + \0 */
229 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
231 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
232 if (ret
< 0 || (size_t)ret
>= len
)
237 SYSERROR("Failed to remove partial file %s", path
);
241 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
242 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
243 * container configuration file.
244 * The container_disk_lock also takes the container_mem_lock.
245 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
246 * NOTHING mutexes two independent programs with their own struct
247 * lxc_container for the same c->name, between API calls. For instance,
248 * c->config_read(); c->start(); Between those calls, data on disk
249 * could change (which shouldn't bother the caller unless for instance
250 * the rootfs get moved). c->config_read(); update; c->config_write();
251 * Two such updaters could race. The callers should therefore check their
252 * results. Trying to prevent that would necessarily expose us to deadlocks
253 * due to hung callers. So I prefer to keep the locks only within our own
254 * functions, not across functions.
256 * If you're going to clone while holding a lxccontainer, increment
257 * c->numthreads (under privlock) before forking. When deleting,
258 * decrement numthreads under privlock, then if it hits 0 you can delete.
259 * Do not ever use a lxccontainer whose numthreads you did not bump.
261 static void lxc_container_free(struct lxc_container
*c
)
267 c
->configfile
= NULL
;
269 free(c
->error_string
);
270 c
->error_string
= NULL
;
273 lxc_putlock(c
->slock
);
278 lxc_putlock(c
->privlock
);
286 lxc_conf_free(c
->lxc_conf
);
290 free(c
->config_path
);
291 c
->config_path
= NULL
;
296 /* Consider the following case:
298 * |====================================================================|
299 * | freer | racing get()er |
300 * |====================================================================|
301 * | lxc_container_put() | lxc_container_get() |
302 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
303 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
304 * | \ lxcunlock() | \ |
305 * | \ lxc_container_free() | \ lxclock() returns |
306 * | | \ c->numthreads < 1 -> return 0 |
307 * | \ \ (free stuff) | |
308 * | \ \ sem_destroy(privlock) | |
309 * |_______________________________|____________________________________|
311 * When the get()er checks numthreads the first time, one of the following
313 * 1. freer has set numthreads = 0. get() returns 0
314 * 2. freer is between lxclock and setting numthreads to 0. get()er will
315 * sem_wait on privlock, get lxclock after freer() drops it, then see
316 * numthreads is 0 and exit without touching lxclock again..
317 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
318 * will see --numthreads = 1 and not call lxc_container_free().
321 int lxc_container_get(struct lxc_container
*c
)
326 /* If someone else has already started freeing the container, don't try
327 * to take the lock, which may be invalid.
329 if (c
->numthreads
< 1)
332 if (container_mem_lock(c
))
335 /* Bail without trying to unlock, bc the privlock is now probably in
338 if (c
->numthreads
< 1)
342 container_mem_unlock(c
);
347 int lxc_container_put(struct lxc_container
*c
)
352 if (container_mem_lock(c
))
357 if (c
->numthreads
< 1) {
358 container_mem_unlock(c
);
359 lxc_container_free(c
);
363 container_mem_unlock(c
);
367 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
376 if (container_mem_lock(c
))
382 statret
= stat(c
->configfile
, &statbuf
);
389 container_mem_unlock(c
);
393 #define WRAP_API(rettype, fnname) \
394 static rettype fnname(struct lxc_container *c) \
397 bool reset_config = false; \
399 if (!current_config && c && c->lxc_conf) { \
400 current_config = c->lxc_conf; \
401 reset_config = true; \
404 ret = do_##fnname(c); \
406 current_config = NULL; \
411 #define WRAP_API_1(rettype, fnname, t1) \
412 static rettype fnname(struct lxc_container *c, t1 a1) \
415 bool reset_config = false; \
417 if (!current_config && c && c->lxc_conf) { \
418 current_config = c->lxc_conf; \
419 reset_config = true; \
422 ret = do_##fnname(c, a1); \
424 current_config = NULL; \
429 #define WRAP_API_2(rettype, fnname, t1, t2) \
430 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
433 bool reset_config = false; \
435 if (!current_config && c && c->lxc_conf) { \
436 current_config = c->lxc_conf; \
437 reset_config = true; \
440 ret = do_##fnname(c, a1, a2); \
442 current_config = NULL; \
447 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
448 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
451 bool reset_config = false; \
453 if (!current_config && c && c->lxc_conf) { \
454 current_config = c->lxc_conf; \
455 reset_config = true; \
458 ret = do_##fnname(c, a1, a2, a3); \
460 current_config = NULL; \
465 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
466 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
467 t4 a4, t5 a5, t6 a6) \
470 bool reset_config = false; \
472 if (!current_config && c && c->lxc_conf) { \
473 current_config = c->lxc_conf; \
474 reset_config = true; \
477 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
479 current_config = NULL; \
484 WRAP_API(bool, lxcapi_is_defined
)
486 static const char *do_lxcapi_state(struct lxc_container
*c
)
493 s
= lxc_getstate(c
->name
, c
->config_path
);
494 return lxc_state2str(s
);
497 WRAP_API(const char *, lxcapi_state
)
499 static bool is_stopped(struct lxc_container
*c
)
503 s
= lxc_getstate(c
->name
, c
->config_path
);
504 return (s
== STOPPED
);
507 static bool do_lxcapi_is_running(struct lxc_container
*c
)
512 return !is_stopped(c
);
515 WRAP_API(bool, lxcapi_is_running
)
517 static bool do_lxcapi_freeze(struct lxc_container
*c
)
524 ret
= lxc_freeze(c
->name
, c
->config_path
);
531 WRAP_API(bool, lxcapi_freeze
)
533 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
540 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
547 WRAP_API(bool, lxcapi_unfreeze
)
549 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
554 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
557 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
559 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
560 int stdoutfd
, int stderrfd
, int escape
)
567 current_config
= c
->lxc_conf
;
568 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
569 current_config
= NULL
;
574 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
578 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
581 NOTICE("The console log is empty");
582 else if (ret
== -EFAULT
)
583 NOTICE("The container does not keep a console log");
584 else if (ret
== -ENOENT
)
585 NOTICE("The container does not keep a console log file");
586 else if (ret
== -EIO
)
587 NOTICE("Failed to write console log to log file");
589 ERROR("Failed to retrieve console log");
595 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
597 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
602 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
605 WRAP_API(pid_t
, lxcapi_init_pid
)
607 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
610 c
->lxc_conf
= lxc_conf_init();
615 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
618 c
->lxc_conf
->name
= c
->name
;
622 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
626 bool need_disklock
= false, ret
= false;
631 fname
= c
->configfile
;
639 /* If we're reading something other than the container's config, we only
640 * need to lock the in-memory container. If loading the container's
641 * config file, take the disk lock.
643 if (strcmp(fname
, c
->configfile
) == 0)
644 need_disklock
= true;
647 lret
= container_disk_lock(c
);
649 lret
= container_mem_lock(c
);
653 ret
= load_config_locked(c
, fname
);
656 container_disk_unlock(c
);
658 container_mem_unlock(c
);
663 WRAP_API_1(bool, lxcapi_load_config
, const char *)
665 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
667 if (!c
|| !c
->lxc_conf
)
670 if (container_mem_lock(c
))
673 c
->daemonize
= state
;
675 container_mem_unlock(c
);
680 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
682 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
684 if (!c
|| !c
->lxc_conf
)
687 if (container_mem_lock(c
))
690 c
->lxc_conf
->close_all_fds
= state
;
692 container_mem_unlock(c
);
697 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
699 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
707 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
711 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
713 static bool am_single_threaded(void)
716 struct dirent
*direntp
;
719 dir
= opendir("/proc/self/task");
723 while ((direntp
= readdir(dir
))) {
724 if (strcmp(direntp
->d_name
, ".") == 0)
727 if (strcmp(direntp
->d_name
, "..") == 0)
739 static void push_arg(char ***argp
, char *arg
, int *nargs
)
744 copy
= must_copy_string(arg
);
747 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
756 static char **split_init_cmd(const char *incmd
)
762 char *saveptr
= NULL
;
767 len
= strlen(incmd
) + 1;
769 retlen
= strlcpy(copy
, incmd
, len
);
774 argv
= malloc(sizeof(char *));
778 for (; (p
= strtok_r(copy
, " ", &saveptr
)); copy
= NULL
)
779 push_arg(&argv
, p
, &nargs
);
789 static void free_init_cmd(char **argv
)
802 static int lxc_rcv_status(int state_socket
)
808 /* Receive container state. */
809 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
814 TRACE("Caught EINTR; retrying");
821 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
825 /* Close write end of the socket pair. */
826 close(handler
->state_socket_pair
[1]);
827 handler
->state_socket_pair
[1] = -1;
829 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
831 /* Close read end of the socket pair. */
832 close(handler
->state_socket_pair
[0]);
833 handler
->state_socket_pair
[0] = -1;
835 /* The first child is going to fork() again and then exits. So we reap
836 * the first child here.
838 ret
= wait_for_pid(pid
);
840 DEBUG("Failed waiting on first child %d", pid
);
842 DEBUG("First child %d exited", pid
);
845 SYSERROR("Failed to receive the container state");
849 /* If we receive anything else then running we know that the container
852 if (state
!= RUNNING
) {
853 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
854 lxc_state2str(state
));
858 TRACE("Container is in \"RUNNING\" state");
862 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
865 struct lxc_handler
*handler
;
866 struct lxc_conf
*conf
;
867 char *default_args
[] = {
871 char **init_cmd
= NULL
;
872 int keepfds
[3] = {-1, -1, -1};
874 /* container does exist */
878 /* If anything fails before we set error_num, we want an error in there.
882 /* Container has not been setup. */
886 ret
= ongoing_create(c
);
888 ERROR("Failed checking for incomplete container creation");
890 } else if (ret
== 1) {
891 ERROR("Ongoing container creation detected");
893 } else if (ret
== 2) {
894 ERROR("Failed to create container");
895 do_lxcapi_destroy(c
);
899 if (container_mem_lock(c
))
904 /* initialize handler */
905 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
907 container_mem_unlock(c
);
912 if (useinit
&& conf
->execute_cmd
)
913 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
915 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
918 /* ... otherwise use default_args. */
921 ERROR("No valid init detected");
922 lxc_free_handler(handler
);
928 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
929 * here to protect the on disk container? We don't want to exclude
930 * things like lxc_info while the container is running.
939 free_init_cmd(init_cmd
);
940 lxc_free_handler(handler
);
946 /* Set to NULL because we don't want father unlink
947 * the PID file, child will do the free and unlink.
951 /* Wait for container to tell us whether it started
954 started
= wait_on_daemonized_start(handler
, pid
);
956 free_init_cmd(init_cmd
);
957 lxc_free_handler(handler
);
963 /* We don't really care if this doesn't print all the
964 * characters. All that it means is that the proctitle will be
965 * ugly. Similarly, we also don't care if setproctitle() fails.
967 (void)snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
968 INFO("Attempting to set proc title to %s", title
);
969 (void)setproctitle(title
);
971 /* We fork() a second time to be reparented to init. Like
972 * POSIX's daemon() function we change to "/" and redirect
973 * std{in,out,err} to /dev/null.
977 SYSERROR("Failed to fork first child process");
983 free_init_cmd(init_cmd
);
984 lxc_free_handler(handler
);
990 /* change to / directory */
993 SYSERROR("Failed to change to \"/\" directory");
997 keepfds
[0] = handler
->conf
->maincmd_fd
;
998 keepfds
[1] = handler
->state_socket_pair
[0];
999 keepfds
[2] = handler
->state_socket_pair
[1];
1000 ret
= lxc_check_inherited(conf
, true, keepfds
,
1001 sizeof(keepfds
) / sizeof(keepfds
[0]));
1003 _exit(EXIT_FAILURE
);
1005 /* redirect std{in,out,err} to /dev/null */
1006 ret
= null_stdfds();
1008 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1009 _exit(EXIT_FAILURE
);
1012 /* become session leader */
1015 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1017 if (!am_single_threaded()) {
1018 ERROR("Cannot start non-daemonized container when threaded");
1019 free_init_cmd(init_cmd
);
1020 lxc_free_handler(handler
);
1025 /* We need to write PID file after daemonize, so we always
1026 * write the right PID.
1030 char pidstr
[LXC_NUMSTRLEN64
];
1032 w
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", (int)lxc_raw_getpid());
1033 if (w
< 0 || (size_t)w
>= LXC_NUMSTRLEN64
) {
1034 free_init_cmd(init_cmd
);
1035 lxc_free_handler(handler
);
1037 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1040 _exit(EXIT_FAILURE
);
1045 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1047 free_init_cmd(init_cmd
);
1048 lxc_free_handler(handler
);
1050 SYSERROR("Failed to write '%s'", c
->pidfile
);
1053 _exit(EXIT_FAILURE
);
1059 conf
->reboot
= REBOOT_NONE
;
1061 /* Unshare the mount namespace if requested */
1062 if (conf
->monitor_unshare
) {
1063 ret
= unshare(CLONE_NEWNS
);
1065 SYSERROR("failed to unshare mount namespace");
1066 lxc_free_handler(handler
);
1071 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1073 SYSERROR("Failed to make / rslave at startup");
1074 lxc_free_handler(handler
);
1081 if (conf
->reboot
== REBOOT_INIT
) {
1082 /* initialize handler */
1083 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1090 keepfds
[0] = handler
->conf
->maincmd_fd
;
1091 keepfds
[1] = handler
->state_socket_pair
[0];
1092 keepfds
[2] = handler
->state_socket_pair
[1];
1093 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1094 sizeof(keepfds
) / sizeof(keepfds
[0]));
1096 lxc_free_handler(handler
);
1102 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1103 c
->daemonize
, &c
->error_num
);
1105 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1106 c
->daemonize
, &c
->error_num
);
1108 if (conf
->reboot
== REBOOT_REQ
) {
1109 INFO("Container requested reboot");
1110 conf
->reboot
= REBOOT_INIT
;
1120 free_init_cmd(init_cmd
);
1122 if (c
->daemonize
&& ret
!= 0)
1123 _exit(EXIT_FAILURE
);
1124 else if (c
->daemonize
)
1125 _exit(EXIT_SUCCESS
);
1133 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1138 current_config
= c
? c
->lxc_conf
: NULL
;
1139 ret
= do_lxcapi_start(c
, useinit
, argv
);
1140 current_config
= NULL
;
1145 /* Note, there MUST be an ending NULL. */
1146 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1149 char **inargs
= NULL
;
1152 /* container exists */
1156 current_config
= c
->lxc_conf
;
1158 va_start(ap
, useinit
);
1159 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1164 /* pass NULL if no arguments were supplied */
1165 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1171 for (arg
= inargs
; *arg
; arg
++)
1176 current_config
= NULL
;
1181 static bool do_lxcapi_stop(struct lxc_container
*c
)
1188 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1193 WRAP_API(bool, lxcapi_stop
)
1195 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1202 mode_t mask
= umask(0002);
1203 ret
= mkdir(path
, 0770);
1208 if (errno
!= EEXIST
)
1215 p
= alloca(len
+ 1);
1216 (void)strlcpy(p
, path
, len
+ 1);
1218 if (!lxc_list_empty(&conf
->id_map
)) {
1219 ret
= chown_mapped_root(p
, conf
);
1227 /* Create the standard expected container dir. */
1228 static bool create_container_dir(struct lxc_container
*c
)
1234 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1239 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1240 if (ret
< 0 || (size_t)ret
>= len
) {
1245 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1251 /* do_storage_create: thin wrapper around storage_create(). Like
1252 * storage_create(), it returns a mounted bdev on success, NULL on error.
1254 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1256 struct bdev_specs
*specs
)
1261 struct lxc_storage
*bdev
;
1263 /* rootfs.path or lxcpath/lxcname/rootfs */
1264 if (c
->lxc_conf
->rootfs
.path
&&
1265 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1266 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1267 len
= strlen(rpath
) + 1;
1269 ret
= snprintf(dest
, len
, "%s", rpath
);
1271 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1272 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1274 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1276 if (ret
< 0 || (size_t)ret
>= len
)
1279 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1281 ERROR("Failed to create \"%s\" storage", type
);
1285 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1286 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1290 /* If we are not root, chown the rootfs dir to root in the target user
1294 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1295 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1297 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1298 suggest_default_idmap();
1307 static char *lxcbasename(char *path
)
1311 p
= path
+ strlen(path
) - 1;
1312 while (*p
!= '/' && p
> path
)
1318 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1319 bool need_null_stdfds
, char *const argv
[])
1329 SYSERROR("Failed to fork task for container creation template");
1333 if (pid
== 0) { /* child */
1335 char *namearg
, *patharg
, *rootfsarg
;
1338 struct lxc_storage
*bdev
= NULL
;
1339 struct lxc_conf
*conf
= c
->lxc_conf
;
1342 if (need_null_stdfds
) {
1343 ret
= null_stdfds();
1345 _exit(EXIT_FAILURE
);
1348 bdev
= storage_init(c
->lxc_conf
);
1350 ERROR("Failed to initialize storage");
1351 _exit(EXIT_FAILURE
);
1356 ret
= unshare(CLONE_NEWNS
);
1358 ERROR("Failed to unshare CLONE_NEWNS");
1359 _exit(EXIT_FAILURE
);
1362 ret
= detect_shared_rootfs();
1364 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1366 SYSERROR("Failed to make \"/\" rslave");
1367 ERROR("Continuing...");
1372 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1374 ERROR("Unprivileged users can only create "
1375 "btrfs and directory-backed containers");
1376 _exit(EXIT_FAILURE
);
1379 if (strcmp(bdev
->type
, "overlay") == 0 ||
1380 strcmp(bdev
->type
, "overlayfs") == 0) {
1381 /* If we create an overlay container we need to
1382 * rsync the contents into
1383 * <container-path>/<container-name>/rootfs.
1384 * However, the overlay mount function will
1386 * <container-path>/<container-name>/delta0
1388 * <container-path>/<container-name>/rootfs
1389 * which means we would rsync the rootfs into
1390 * the delta directory. That doesn't make sense
1391 * since the delta directory only exists to
1392 * record the differences to
1393 * <container-path>/<container-name>/rootfs. So
1394 * let's simply bind-mount here and then rsync
1396 * <container-path>/<container-name>/rootfs.
1400 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1402 ERROR("Failed to get rootfs");
1403 _exit(EXIT_FAILURE
);
1406 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1408 ERROR("Failed to mount rootfs");
1409 _exit(EXIT_FAILURE
);
1412 ret
= bdev
->ops
->mount(bdev
);
1414 ERROR("Failed to mount rootfs");
1415 _exit(EXIT_FAILURE
);
1418 } else { /* TODO come up with a better way here! */
1421 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1422 bdev
->dest
= strdup(src
);
1425 /* Create our new array, pre-pend the template name and base
1429 for (nargs
= 0; argv
[nargs
]; nargs
++)
1432 /* template, path, rootfs and name args */
1435 newargv
= malloc(nargs
* sizeof(*newargv
));
1437 _exit(EXIT_FAILURE
);
1438 newargv
[0] = lxcbasename(tpath
);
1441 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1442 patharg
= malloc(len
);
1444 _exit(EXIT_FAILURE
);
1446 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1447 if (ret
< 0 || ret
>= len
)
1448 _exit(EXIT_FAILURE
);
1449 newargv
[1] = patharg
;
1452 len
= strlen("--name=") + strlen(c
->name
) + 1;
1453 namearg
= malloc(len
);
1455 _exit(EXIT_FAILURE
);
1457 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1458 if (ret
< 0 || ret
>= len
)
1459 _exit(EXIT_FAILURE
);
1460 newargv
[2] = namearg
;
1463 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1464 rootfsarg
= malloc(len
);
1466 _exit(EXIT_FAILURE
);
1468 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1469 if (ret
< 0 || ret
>= len
)
1470 _exit(EXIT_FAILURE
);
1471 newargv
[3] = rootfsarg
;
1473 /* add passed-in args */
1475 for (i
= 4; i
< nargs
; i
++)
1476 newargv
[i
] = argv
[i
- 4];
1478 /* add trailing NULL */
1480 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1482 _exit(EXIT_FAILURE
);
1483 newargv
[nargs
- 1] = NULL
;
1485 /* If we're running the template in a mapped userns, then we
1486 * prepend the template command with: lxc-usernsexec <-m map1>
1487 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1488 * the mapped uid for our geteuid()
1490 if (!lxc_list_empty(&conf
->id_map
)) {
1491 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1493 char txtuid
[20], txtgid
[20];
1494 struct lxc_list
*it
;
1498 n2
= malloc(n2args
* sizeof(*n2
));
1500 _exit(EXIT_FAILURE
);
1503 tpath
= "lxc-usernsexec";
1504 n2
[0] = "lxc-usernsexec";
1506 lxc_list_for_each(it
, &conf
->id_map
) {
1509 n2
= realloc(n2
, n2args
* sizeof(char *));
1511 _exit(EXIT_FAILURE
);
1513 n2
[n2args
- 2] = "-m";
1514 n2
[n2args
- 1] = malloc(200);
1515 if (!n2
[n2args
- 1])
1516 _exit(EXIT_FAILURE
);
1518 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1519 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1520 map
->nsid
, map
->hostid
, map
->range
);
1521 if (ret
< 0 || ret
>= 200)
1522 _exit(EXIT_FAILURE
);
1525 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1526 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1528 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1530 _exit(EXIT_FAILURE
);
1532 if (hostuid_mapped
< 0) {
1533 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1534 n2
[n2args
++] = "-m";
1535 if (hostuid_mapped
< 0) {
1536 ERROR("Failed to find free uid to map");
1537 _exit(EXIT_FAILURE
);
1540 n2
[n2args
++] = malloc(200);
1541 if (!n2
[n2args
- 1]) {
1542 SYSERROR("out of memory");
1543 _exit(EXIT_FAILURE
);
1546 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1547 hostuid_mapped
, geteuid());
1548 if (ret
< 0 || ret
>= 200)
1549 _exit(EXIT_FAILURE
);
1552 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1553 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1555 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1557 _exit(EXIT_FAILURE
);
1559 if (hostgid_mapped
< 0) {
1560 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1561 n2
[n2args
++] = "-m";
1562 if (hostgid_mapped
< 0) {
1563 ERROR("Failed to find free gid to map");
1564 _exit(EXIT_FAILURE
);
1567 n2
[n2args
++] = malloc(200);
1568 if (!n2
[n2args
- 1]) {
1569 SYSERROR("out of memory");
1570 _exit(EXIT_FAILURE
);
1573 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1574 hostgid_mapped
, getegid());
1575 if (ret
< 0 || ret
>= 200)
1576 _exit(EXIT_FAILURE
);
1579 n2
[n2args
++] = "--";
1581 for (i
= 0; i
< nargs
; i
++)
1582 n2
[i
+ n2args
] = newargv
[i
];
1585 /* Finally add "--mapped-uid $uid" to tell template what
1586 * to chown cached images to.
1589 n2
= realloc(n2
, n2args
* sizeof(char *));
1591 _exit(EXIT_FAILURE
);
1593 /* note n2[n2args-1] is NULL */
1594 n2
[n2args
- 5] = "--mapped-uid";
1596 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1597 if (ret
< 0 || ret
>= 20) {
1600 _exit(EXIT_FAILURE
);
1603 n2
[n2args
- 4] = txtuid
;
1604 n2
[n2args
- 3] = "--mapped-gid";
1606 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1607 if (ret
< 0 || ret
>= 20) {
1610 _exit(EXIT_FAILURE
);
1613 n2
[n2args
- 2] = txtgid
;
1614 n2
[n2args
- 1] = NULL
;
1619 execvp(tpath
, newargv
);
1620 SYSERROR("Failed to execute template %s", tpath
);
1621 _exit(EXIT_FAILURE
);
1624 ret
= wait_for_pid(pid
);
1626 ERROR("Failed to create container from template");
1633 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1642 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1646 f
= fopen(path
, "r");
1650 ret
= fseek(f
, 0, SEEK_END
);
1659 ret
= fseek(f
, 0, SEEK_SET
);
1663 ret
= fseek(f
, 0, SEEK_SET
);
1668 contents
= malloc(flen
+ 1);
1672 len
= fread(contents
, 1, flen
, f
);
1674 goto out_free_contents
;
1676 contents
[flen
] = '\0';
1681 goto out_free_contents
;
1684 tpath
= get_template_path(t
);
1686 ERROR("Invalid template \"%s\" specified", t
);
1687 goto out_free_contents
;
1690 ret
= sha1sum_file(tpath
, md_value
);
1692 ERROR("Failed to get sha1sum of %s", tpath
);
1694 goto out_free_contents
;
1699 f
= fopen(path
, "w");
1701 SYSERROR("Reopening config for writing");
1706 fprintf(f
, "# Template used to create this container: %s\n", t
);
1708 fprintf(f
, "# Parameters passed to the template:");
1710 fprintf(f
, " %s", *argv
);
1717 fprintf(f
, "# Template script checksum (SHA-1): ");
1718 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1719 fprintf(f
, "%02x", md_value
[i
]);
1722 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1723 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1724 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1725 fprintf(f
, "# (Be aware this has security implications)\n\n");
1726 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1727 SYSERROR("Writing original contents");
1747 SYSERROR("Error prepending header");
1754 static void lxcapi_clear_config(struct lxc_container
*c
)
1756 if (!c
|| !c
->lxc_conf
)
1759 lxc_conf_free(c
->lxc_conf
);
1763 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1767 * create a container with the given parameters.
1768 * @c: container to be created. It has the lxcpath, name, and a starting
1769 * configuration already set
1770 * @t: the template to execute to instantiate the root filesystem and
1771 * adjust the configuration.
1772 * @bdevtype: backing store type to use. If NULL, dir will be used.
1773 * @specs: additional parameters for the backing store, i.e. LVM vg to
1776 * @argv: the arguments to pass to the template, terminated by NULL. If no
1777 * arguments, you can just pass NULL.
1779 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1780 const char *bdevtype
, struct bdev_specs
*specs
,
1781 int flags
, char *const argv
[])
1793 tpath
= get_template_path(t
);
1795 ERROR("Unknown template \"%s\"", t
);
1800 /* If a template is passed in, and the rootfs already is defined in the
1801 * container config and exists, then the caller is trying to create an
1802 * existing container. Return an error, but do NOT delete the container.
1804 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1805 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1806 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1812 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1813 ERROR("Error loading default configuration file %s",
1814 lxc_global_config_value("lxc.default_config"));
1819 if (!create_container_dir(c
))
1822 /* If both template and rootfs.path are set, template is setup as
1823 * rootfs.path. The container is already created if we have a config and
1824 * rootfs.path is accessible
1826 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1827 /* No template passed in and rootfs does not exist. */
1828 if (!c
->save_config(c
, NULL
)) {
1829 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1836 /* Rootfs passed into configuration, but does not exist. */
1837 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1840 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1841 /* Rootfs already existed, user just wanted to save the loaded
1844 if (!c
->save_config(c
, NULL
))
1845 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1851 /* Mark that this container is being created */
1852 partial_fd
= create_partial(c
);
1856 /* No need to get disk lock bc we have the partial lock. */
1860 /* Create the storage.
1861 * Note we can't do this in the same task as we use to execute the
1862 * template because of the way zfs works.
1863 * After you 'zfs create', zfs mounts the fs only in the initial
1868 SYSERROR("Failed to fork task for container creation template");
1872 if (pid
== 0) { /* child */
1873 struct lxc_storage
*bdev
= NULL
;
1875 bdev
= do_storage_create(c
, bdevtype
, specs
);
1877 ERROR("Failed to create %s storage for %s",
1878 bdevtype
? bdevtype
: "(none)", c
->name
);
1879 _exit(EXIT_FAILURE
);
1882 /* Save config file again to store the new rootfs location. */
1883 if (!do_lxcapi_save_config(c
, NULL
)) {
1884 ERROR("Failed to save initial config for %s", c
->name
);
1885 /* Parent task won't see the storage driver in the
1886 * config so we delete it.
1888 bdev
->ops
->umount(bdev
);
1889 bdev
->ops
->destroy(bdev
);
1890 _exit(EXIT_FAILURE
);
1893 _exit(EXIT_SUCCESS
);
1896 if (wait_for_pid(pid
) != 0)
1899 /* Reload config to get the rootfs. */
1900 lxc_conf_free(c
->lxc_conf
);
1903 if (!load_config_locked(c
, c
->configfile
))
1906 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1909 /* Now clear out the lxc_conf we have, reload from the created
1912 do_lxcapi_clear_config(c
);
1915 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1916 ERROR("Failed to prepend header to config file");
1921 ret
= load_config_locked(c
, c
->configfile
);
1925 if (partial_fd
>= 0)
1926 remove_partial(c
, partial_fd
);
1930 container_destroy(c
, NULL
);
1937 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1938 const char *bdevtype
, struct bdev_specs
*specs
,
1939 int flags
, char *const argv
[])
1943 current_config
= c
? c
->lxc_conf
: NULL
;
1945 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1946 current_config
= NULL
;
1950 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1954 int rebootsignal
= SIGINT
;
1959 if (!do_lxcapi_is_running(c
))
1962 pid
= do_lxcapi_init_pid(c
);
1966 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1967 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1969 ret
= kill(pid
, rebootsignal
);
1971 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
1978 WRAP_API(bool, lxcapi_reboot
)
1980 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1984 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1985 lxc_state_t states
[MAX_STATE
] = {0};
1990 if (!do_lxcapi_is_running(c
))
1993 pid
= do_lxcapi_init_pid(c
);
1997 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1998 rebootsignal
= c
->lxc_conf
->rebootsignal
;
2000 /* Add a new state client before sending the shutdown signal so that we
2001 * don't miss a state.
2004 states
[RUNNING
] = 2;
2005 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2010 if (state_client_fd
< 0)
2016 if (ret
< MAX_STATE
)
2020 /* Send reboot signal to container. */
2021 killret
= kill(pid
, rebootsignal
);
2023 if (state_client_fd
>= 0)
2024 close(state_client_fd
);
2026 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2029 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2034 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2035 close(state_client_fd
);
2039 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2046 WRAP_API_1(bool, lxcapi_reboot2
, int)
2048 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2052 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2053 lxc_state_t states
[MAX_STATE
] = {0};
2058 if (!do_lxcapi_is_running(c
))
2061 pid
= do_lxcapi_init_pid(c
);
2065 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2066 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2067 haltsignal
= c
->lxc_conf
->haltsignal
;
2068 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2069 haltsignal
= (SIGRTMIN
+ 3);
2071 /* Add a new state client before sending the shutdown signal so that we
2072 * don't miss a state.
2075 states
[STOPPED
] = 1;
2076 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2081 if (state_client_fd
< 0)
2087 if (ret
< MAX_STATE
)
2091 /* Send shutdown signal to container. */
2092 killret
= kill(pid
, haltsignal
);
2094 if (state_client_fd
>= 0)
2095 close(state_client_fd
);
2097 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2100 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2105 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2106 close(state_client_fd
);
2110 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2117 WRAP_API_1(bool, lxcapi_shutdown
, int)
2119 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2120 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2129 current_config
= c
->lxc_conf
;
2132 * since we're going to wait for create to finish, I don't think we
2133 * need to get a copy of the arguments.
2135 va_start(ap
, flags
);
2136 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2139 ERROR("Failed to allocate memory");
2143 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2147 current_config
= NULL
;
2151 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2153 if (!strcmp(key
, "lxc.cgroup"))
2154 return clear_unexp_config_line(conf
, key
, true);
2156 if (!strcmp(key
, "lxc.network"))
2157 return clear_unexp_config_line(conf
, key
, true);
2159 if (!strcmp(key
, "lxc.net"))
2160 return clear_unexp_config_line(conf
, key
, true);
2162 /* Clear a network with a specific index. */
2163 if (!strncmp(key
, "lxc.net.", 8)) {
2168 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2170 return clear_unexp_config_line(conf
, key
, true);
2173 if (!strcmp(key
, "lxc.hook"))
2174 return clear_unexp_config_line(conf
, key
, true);
2176 return clear_unexp_config_line(conf
, key
, false);
2179 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2183 struct lxc_config_t
*config
;
2185 if (!c
|| !c
->lxc_conf
)
2188 if (container_mem_lock(c
))
2191 config
= lxc_get_config(key
);
2192 /* Verify that the config key exists and that it has a callback
2195 if (config
&& config
->clr
)
2196 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2199 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2201 container_mem_unlock(c
);
2205 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2207 static inline bool enter_net_ns(struct lxc_container
*c
)
2209 pid_t pid
= do_lxcapi_init_pid(c
);
2211 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2212 (access("/proc/self/ns/user", F_OK
) == 0))
2213 if (!switch_to_ns(pid
, "user"))
2216 return switch_to_ns(pid
, "net");
2219 /* Used by qsort and bsearch functions for comparing names. */
2220 static inline int string_cmp(char **first
, char **second
)
2222 return strcmp(*first
, *second
);
2225 /* Used by qsort and bsearch functions for comparing container names. */
2226 static inline int container_cmp(struct lxc_container
**first
,
2227 struct lxc_container
**second
)
2229 return strcmp((*first
)->name
, (*second
)->name
);
2232 static bool add_to_array(char ***names
, char *cname
, int pos
)
2234 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2236 ERROR("Out of memory");
2241 newnames
[pos
] = strdup(cname
);
2245 /* Sort the arrray as we will use binary search on it. */
2246 qsort(newnames
, pos
+ 1, sizeof(char *),
2247 (int (*)(const void *, const void *))string_cmp
);
2252 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2255 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2257 ERROR("Out of memory");
2264 /* Sort the arrray as we will use binary search on it. */
2266 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2267 (int (*)(const void *, const void *))container_cmp
);
2272 static char** get_from_array(char ***names
, char *cname
, int size
)
2274 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2277 static bool array_contains(char ***names
, char *cname
, int size
)
2279 if(get_from_array(names
, cname
, size
) != NULL
)
2285 static bool remove_from_array(char ***names
, char *cname
, int size
)
2287 char **result
= get_from_array(names
, cname
, size
);
2288 if (result
!= NULL
) {
2296 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2299 int i
, count
= 0, pipefd
[2];
2300 char **interfaces
= NULL
;
2301 char interface
[IFNAMSIZ
];
2303 if(pipe(pipefd
) < 0) {
2304 SYSERROR("pipe failed");
2310 SYSERROR("failed to fork task to get interfaces information");
2316 if (pid
== 0) { /* child */
2317 int ret
= 1, nbytes
;
2318 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2320 /* close the read-end of the pipe */
2323 if (!enter_net_ns(c
)) {
2324 SYSERROR("failed to enter namespace");
2328 /* Grab the list of interfaces */
2329 if (getifaddrs(&interfaceArray
)) {
2330 SYSERROR("failed to get interfaces list");
2334 /* Iterate through the interfaces */
2335 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2336 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2338 ERROR("write failed");
2348 freeifaddrs(interfaceArray
);
2350 /* close the write-end of the pipe, thus sending EOF to the reader */
2355 /* close the write-end of the pipe */
2358 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2359 interface
[IFNAMSIZ
- 1] = '\0';
2361 if (array_contains(&interfaces
, interface
, count
))
2364 if(!add_to_array(&interfaces
, interface
, count
))
2365 ERROR("Failed to add \"%s\" to array", interface
);
2370 if (wait_for_pid(pid
) != 0) {
2371 for(i
=0;i
<count
;i
++)
2372 free(interfaces
[i
]);
2378 /* close the read-end of the pipe */
2381 /* Append NULL to the array */
2383 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2388 WRAP_API(char **, lxcapi_get_interfaces
)
2390 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2391 const char *family
, int scope
)
2396 char address
[INET6_ADDRSTRLEN
];
2398 char **addresses
= NULL
;
2402 SYSERROR("Failed to create pipe");
2408 SYSERROR("Failed to create new process");
2416 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2418 char *address
= NULL
;
2419 void *tempAddrPtr
= NULL
;
2420 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2422 /* close the read-end of the pipe */
2425 if (!enter_net_ns(c
)) {
2426 SYSERROR("Failed to attach to network namespace");
2430 /* Grab the list of interfaces */
2431 if (getifaddrs(&interfaceArray
)) {
2432 SYSERROR("Failed to get interfaces list");
2436 /* Iterate through the interfaces */
2437 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2438 tempIfAddr
= tempIfAddr
->ifa_next
) {
2439 if (tempIfAddr
->ifa_addr
== NULL
)
2442 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2443 if (family
&& strcmp(family
, "inet"))
2446 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2448 if (family
&& strcmp(family
, "inet6"))
2451 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2454 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2457 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2459 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2462 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2463 tempAddrPtr
, addressOutputBuffer
,
2464 sizeof(addressOutputBuffer
));
2468 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2469 if (nbytes
!= INET6_ADDRSTRLEN
) {
2470 SYSERROR("Failed to send ipv6 address \"%s\"",
2482 freeifaddrs(interfaceArray
);
2484 /* close the write-end of the pipe, thus sending EOF to the reader */
2489 /* close the write-end of the pipe */
2492 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2493 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2495 if (!add_to_array(&addresses
, address
, count
))
2496 ERROR("PARENT: add_to_array failed");
2501 if (wait_for_pid(pid
) != 0) {
2502 for (i
= 0; i
< count
; i
++)
2509 /* close the read-end of the pipe */
2512 /* Append NULL to the array */
2514 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2519 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2521 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2524 struct lxc_config_t
*config
;
2526 if (!c
|| !c
->lxc_conf
)
2529 if (container_mem_lock(c
))
2532 config
= lxc_get_config(key
);
2533 /* Verify that the config key exists and that it has a callback
2536 if (config
&& config
->get
)
2537 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2539 container_mem_unlock(c
);
2543 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2545 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2549 if (!c
|| !c
->lxc_conf
)
2552 if (container_mem_lock(c
))
2555 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2556 container_mem_unlock(c
);
2560 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2562 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2566 /* List all config items. */
2568 return lxc_list_config_items(retv
, inlen
);
2570 if (!c
|| !c
->lxc_conf
)
2573 if (container_mem_lock(c
))
2576 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2577 * This is an intelligent result to show which keys are valid given the
2578 * type of nic it is.
2580 if (strncmp(key
, "lxc.net.", 8) == 0)
2581 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2583 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2585 container_mem_unlock(c
);
2589 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2591 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2594 bool ret
= false, need_disklock
= false;
2597 alt_file
= c
->configfile
;
2602 /* If we haven't yet loaded a config, load the stock config. */
2604 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2605 ERROR("Error loading default configuration file %s "
2607 lxc_global_config_value("lxc.default_config"),
2613 if (!create_container_dir(c
))
2616 /* If we're writing to the container's config file, take the disk lock.
2617 * Otherwise just take the memlock to protect the struct lxc_container
2618 * while we're traversing it.
2620 if (strcmp(c
->configfile
, alt_file
) == 0)
2621 need_disklock
= true;
2624 lret
= container_disk_lock(c
);
2626 lret
= container_mem_lock(c
);
2630 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2631 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2635 lret
= write_config(fd
, c
->lxc_conf
);
2644 container_disk_unlock(c
);
2646 container_mem_unlock(c
);
2651 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2654 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2660 char path
[MAXPATHLEN
];
2661 char newpath
[MAXPATHLEN
];
2662 int fd
, ret
, n
= 0, v
= 0;
2664 size_t len
= 0, bytes
= 0;
2666 if (container_disk_lock(c0
))
2669 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2670 if (ret
< 0 || ret
> MAXPATHLEN
)
2673 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2674 if (ret
< 0 || ret
> MAXPATHLEN
)
2677 /* If we find an lxc-snapshot file using the old format only listing the
2678 * number of snapshots we will keep using it. */
2679 f1
= fopen(path
, "r");
2681 n
= fscanf(f1
, "%d", &v
);
2683 if (n
== 1 && v
== 0) {
2686 SYSERROR("Failed to remove \"%s\"", path
);
2694 f1
= fopen(path
, "w");
2698 if (fprintf(f1
, "%d\n", v
) < 0) {
2699 ERROR("Error writing new snapshots value");
2706 SYSERROR("Error writing to or closing snapshots file");
2710 /* Here we know that we have or can use an lxc-snapshot file
2711 * using the new format. */
2713 f1
= fopen(path
, "a");
2717 if (fprintf(f1
, "%s", newpath
) < 0) {
2718 ERROR("Error writing new snapshots entry");
2721 SYSERROR("Error writing to or closing snapshots file");
2727 SYSERROR("Error writing to or closing snapshots file");
2731 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2734 if (fstat(fd
, &fbuf
) < 0) {
2739 if (fbuf
.st_size
!= 0) {
2740 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2741 if (buf
== MAP_FAILED
) {
2742 SYSERROR("Failed to create mapping %s", path
);
2747 len
= strlen(newpath
);
2748 while ((del
= strstr((char *)buf
, newpath
))) {
2749 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2753 lxc_strmunmap(buf
, fbuf
.st_size
);
2754 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2755 SYSERROR("Failed to truncate file %s", path
);
2764 /* If the lxc-snapshot file is empty, remove it. */
2765 if (stat(path
, &fbuf
) < 0)
2768 if (!fbuf
.st_size
) {
2771 SYSERROR("Failed to remove \"%s\"", path
);
2778 container_disk_unlock(c0
);
2782 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2784 struct lxc_container
*p
;
2785 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2786 size_t pathlen
= 0, namelen
= 0;
2790 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2791 c
->config_path
, c
->name
);
2792 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2793 ERROR("Path name too long");
2797 f
= fopen(path
, "r");
2801 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2802 if (getline(&lxcname
, &namelen
, f
) == -1) {
2803 ERROR("badly formatted file %s", path
);
2807 remove_trailing_newlines(lxcpath
);
2808 remove_trailing_newlines(lxcname
);
2810 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2811 ERROR("Unable to find dependent container %s:%s",
2816 if (!mod_rdep(p
, c
, inc
))
2817 ERROR("Failed to update snapshots file for %s:%s",
2820 lxc_container_put(p
);
2829 static bool has_fs_snapshots(struct lxc_container
*c
)
2832 char path
[MAXPATHLEN
];
2837 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2839 if (ret
< 0 || ret
> MAXPATHLEN
)
2842 /* If the file doesn't exist there are no snapshots. */
2843 if (stat(path
, &fbuf
) < 0)
2848 f
= fopen(path
, "r");
2852 ret
= fscanf(f
, "%d", &v
);
2854 /* TODO: Figure out what to do with the return value of fscanf. */
2856 INFO("Container uses new lxc-snapshots format %s", path
);
2865 static bool has_snapshots(struct lxc_container
*c
)
2867 char path
[MAXPATHLEN
];
2868 struct dirent
*direntp
;
2872 if (!get_snappath_dir(c
, path
))
2875 dir
= opendir(path
);
2879 while ((direntp
= readdir(dir
))) {
2880 if (!strcmp(direntp
->d_name
, "."))
2883 if (!strcmp(direntp
->d_name
, ".."))
2893 static bool do_destroy_container(struct lxc_conf
*conf
) {
2896 if (am_guest_unpriv()) {
2897 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2898 "storage_destroy_wrapper");
2905 return storage_destroy(conf
);
2908 static int lxc_rmdir_onedev_wrapper(void *data
)
2910 char *arg
= (char *) data
;
2911 return lxc_rmdir_onedev(arg
, "snaps");
2914 static int lxc_unlink_exec_wrapper(void *data
)
2920 static bool container_destroy(struct lxc_container
*c
,
2921 struct lxc_storage
*storage
)
2925 struct lxc_conf
*conf
;
2930 if (!c
|| !do_lxcapi_is_defined(c
))
2934 if (container_disk_lock(c
))
2937 if (!is_stopped(c
)) {
2938 /* We should queue some sort of error - in c->error_string? */
2939 ERROR("container %s is not stopped", c
->name
);
2943 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2944 /* Start of environment variable setup for hooks */
2945 if (setenv("LXC_NAME", c
->name
, 1))
2946 SYSERROR("Failed to set environment variable for container name");
2948 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2949 SYSERROR("Failed to set environment variable for config path");
2951 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2952 SYSERROR("Failed to set environment variable for rootfs mount");
2954 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2955 SYSERROR("Failed to set environment variable for rootfs mount");
2957 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2958 SYSERROR("Failed to set environment variable for console path");
2960 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2961 SYSERROR("Failed to set environment variable for console log");
2962 /* End of environment variable setup for hooks */
2964 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2965 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2970 if (current_config
&& conf
== current_config
) {
2971 current_config
= NULL
;
2973 if (conf
->logfd
!= -1) {
2979 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2980 if (!do_destroy_container(conf
)) {
2981 ERROR("Error destroying rootfs for %s", c
->name
);
2984 INFO("Destroyed rootfs for %s", c
->name
);
2987 mod_all_rdeps(c
, false);
2989 p1
= do_lxcapi_get_config_path(c
);
2998 * strlen("config") = 6
3002 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3005 ERROR("Failed to allocate memory");
3009 /* For an overlay container the rootfs is considered immutable and
3010 * cannot be removed when restoring from a snapshot.
3012 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3013 !strcmp(storage
->type
, "overlayfs")) &&
3014 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3015 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3016 if (ret
< 0 || (size_t)ret
>= len
)
3019 if (am_guest_unpriv())
3020 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3021 "lxc_unlink_exec_wrapper");
3025 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3029 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3035 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3036 if (ret
< 0 || (size_t)ret
>= len
)
3039 if (am_guest_unpriv())
3040 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3041 "lxc_rmdir_onedev_wrapper");
3043 ret
= lxc_rmdir_onedev(path
, "snaps");
3045 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3049 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3057 container_disk_unlock(c
);
3061 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3063 if (!c
|| !lxcapi_is_defined(c
))
3066 if (has_snapshots(c
)) {
3067 ERROR("Container %s has snapshots; not removing", c
->name
);
3071 if (has_fs_snapshots(c
)) {
3072 ERROR("container %s has snapshots on its rootfs", c
->name
);
3076 return container_destroy(c
, NULL
);
3079 WRAP_API(bool, lxcapi_destroy
)
3081 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3083 if (!c
|| !lxcapi_is_defined(c
))
3086 if (!lxcapi_snapshot_destroy_all(c
)) {
3087 ERROR("Error deleting all snapshots");
3091 return lxcapi_destroy(c
);
3094 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3096 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3100 struct lxc_config_t
*config
;
3103 config
= lxc_get_config(key
);
3107 ret
= config
->set(key
, v
, conf
, NULL
);
3111 if (lxc_config_value_empty(v
))
3112 do_clear_unexp_config_line(conf
, key
);
3114 bret
= do_append_unexp_config_line(conf
, key
, v
);
3121 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3127 c
->lxc_conf
= lxc_conf_init();
3132 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3139 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3146 if (container_mem_lock(c
))
3149 b
= do_set_config_item_locked(c
, key
, v
);
3151 container_mem_unlock(c
);
3155 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3157 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3159 if (!c
|| !c
->configfile
)
3162 return strdup(c
->configfile
);
3165 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3167 if (!c
|| !c
->config_path
)
3170 return (const char *)(c
->config_path
);
3175 * Just recalculate the c->configfile based on the
3176 * c->config_path, which must be set.
3177 * The lxc_container must be locked or not yet public.
3179 static bool set_config_filename(struct lxc_container
*c
)
3184 if (!c
->config_path
)
3187 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3188 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3189 newpath
= malloc(len
);
3193 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3194 if (ret
< 0 || ret
>= len
) {
3195 fprintf(stderr
, "Error printing out config file name\n");
3200 free(c
->configfile
);
3201 c
->configfile
= newpath
;
3206 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3210 char *oldpath
= NULL
;
3215 if (container_mem_lock(c
))
3220 ERROR("Out of memory setting new lxc path");
3226 oldpath
= c
->config_path
;
3229 /* Since we've changed the config path, we have to change the
3230 * config file name too */
3231 if (!set_config_filename(c
)) {
3232 ERROR("Out of memory setting new config filename");
3234 free(c
->config_path
);
3235 c
->config_path
= oldpath
;
3241 container_mem_unlock(c
);
3245 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3247 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3250 struct cgroup_ops
*cgroup_ops
;
3258 cgroup_ops
= cgroup_init(NULL
);
3262 if (container_disk_lock(c
))
3265 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3267 container_disk_unlock(c
);
3269 cgroup_exit(cgroup_ops
);
3274 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3276 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3279 struct cgroup_ops
*cgroup_ops
;
3287 cgroup_ops
= cgroup_init(NULL
);
3291 if (container_disk_lock(c
))
3294 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3297 container_disk_unlock(c
);
3299 cgroup_exit(cgroup_ops
);
3304 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3306 const char *lxc_get_global_config_item(const char *key
)
3308 return lxc_global_config_value(key
);
3311 const char *lxc_get_version(void)
3316 static int copy_file(const char *old
, const char *new)
3323 if (file_exists(new)) {
3324 ERROR("copy destination %s exists", new);
3328 ret
= stat(old
, &sbuf
);
3330 INFO("Error stat'ing %s", old
);
3334 in
= open(old
, O_RDONLY
);
3336 SYSERROR("Error opening original file %s", old
);
3340 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3342 SYSERROR("Error opening new file %s", new);
3348 len
= read(in
, buf
, 8096);
3350 SYSERROR("Error reading old file %s", old
);
3357 ret
= write(out
, buf
, len
);
3358 if (ret
< len
) { /* should we retry? */
3359 SYSERROR("Error: write to new file %s was interrupted", new);
3367 /* We set mode, but not owner/group. */
3368 ret
= chmod(new, sbuf
.st_mode
);
3370 SYSERROR("Error setting mode on %s", new);
3382 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3385 struct lxc_list
*it
;
3388 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3389 cpath
= alloca(len
);
3390 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3391 if (ret
< 0 || ret
>= len
)
3394 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3395 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3396 char *hookname
= it
->elem
;
3397 char *fname
= strrchr(hookname
, '/');
3398 char tmppath
[MAXPATHLEN
];
3399 if (!fname
) /* relative path - we don't support, but maybe we should */
3402 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3403 /* this hook is public - ignore */
3407 /* copy the script, and change the entry in confile */
3408 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3409 c
->config_path
, c
->name
, fname
+1);
3410 if (ret
< 0 || ret
>= MAXPATHLEN
)
3413 ret
= copy_file(it
->elem
, tmppath
);
3419 it
->elem
= strdup(tmppath
);
3421 ERROR("out of memory copying hook path");
3427 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3428 c
->config_path
, oldc
->name
, c
->name
)) {
3429 ERROR("Error saving new hooks in clone");
3433 do_lxcapi_save_config(c
, NULL
);
3438 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3440 char newpath
[MAXPATHLEN
];
3441 char *oldpath
= oldc
->lxc_conf
->fstab
;
3447 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3449 char *p
= strrchr(oldpath
, '/');
3453 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3454 c
->config_path
, c
->name
, p
);
3455 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3456 ERROR("error printing new path for %s", oldpath
);
3460 if (file_exists(newpath
)) {
3461 ERROR("error: fstab file %s exists", newpath
);
3465 if (copy_file(oldpath
, newpath
) < 0) {
3466 ERROR("error: copying %s to %s", oldpath
, newpath
);
3470 free(c
->lxc_conf
->fstab
);
3472 c
->lxc_conf
->fstab
= strdup(newpath
);
3473 if (!c
->lxc_conf
->fstab
) {
3474 ERROR("error: allocating pathname");
3478 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3479 ERROR("error saving new lxctab");
3486 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3488 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3491 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3493 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3494 WARN("Error copying reverse dependencies");
3498 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3500 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3501 WARN("Error copying reverse dependencies");
3505 if (copy_file(path0
, path1
) < 0) {
3506 INFO("Error copying reverse dependencies");
3511 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3514 char path
[MAXPATHLEN
];
3518 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3520 if (ret
< 0 || ret
>= MAXPATHLEN
)
3523 f
= fopen(path
, "a");
3529 /* If anything goes wrong, just return an error. */
3530 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3540 * If the fs natively supports snapshot clones with no penalty,
3541 * then default to those even if not requested.
3542 * Currently we only do this for btrfs.
3544 bool should_default_to_snapshot(struct lxc_container
*c0
,
3545 struct lxc_container
*c1
)
3548 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3549 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3550 char *p0
= alloca(l0
+ 1);
3551 char *p1
= alloca(l1
+ 1);
3552 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3554 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3555 if (ret
< 0 || ret
>= l0
)
3558 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3559 if (ret
< 0 || ret
>= l1
)
3562 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3565 if (is_btrfs_subvol(rootfs
) <= 0)
3568 return btrfs_same_fs(p0
, p1
) == 0;
3571 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3572 const char *newtype
, int flags
, const char *bdevdata
,
3575 struct lxc_storage
*bdev
;
3578 if (should_default_to_snapshot(c0
, c
))
3579 flags
|= LXC_CLONE_SNAPSHOT
;
3581 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3582 bdevdata
, newsize
, &need_rdep
);
3584 ERROR("Error copying storage.");
3588 /* Set new rootfs. */
3589 free(c
->lxc_conf
->rootfs
.path
);
3590 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3593 if (!c
->lxc_conf
->rootfs
.path
) {
3594 ERROR("Out of memory while setting storage path.");
3598 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3599 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3600 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3601 c
->lxc_conf
->rootfs
.path
)) {
3602 ERROR("Error saving new rootfs to cloned config.");
3606 if (flags
& LXC_CLONE_SNAPSHOT
)
3607 copy_rdepends(c
, c0
);
3610 if (!add_rdepends(c
, c0
))
3611 WARN("Error adding reverse dependency from %s to %s",
3615 mod_all_rdeps(c
, true);
3620 struct clone_update_data
{
3621 struct lxc_container
*c0
;
3622 struct lxc_container
*c1
;
3627 static int clone_update_rootfs(struct clone_update_data
*data
)
3629 struct lxc_container
*c0
= data
->c0
;
3630 struct lxc_container
*c
= data
->c1
;
3631 int flags
= data
->flags
;
3632 char **hookargs
= data
->hookargs
;
3634 char path
[MAXPATHLEN
];
3635 struct lxc_storage
*bdev
;
3637 struct lxc_conf
*conf
= c
->lxc_conf
;
3639 /* update hostname in rootfs */
3640 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3642 if (setgid(0) < 0) {
3643 ERROR("Failed to setgid to 0");
3647 if (setuid(0) < 0) {
3648 ERROR("Failed to setuid to 0");
3652 if (setgroups(0, NULL
) < 0)
3653 WARN("Failed to clear groups");
3655 if (unshare(CLONE_NEWNS
) < 0)
3658 bdev
= storage_init(c
->lxc_conf
);
3662 if (strcmp(bdev
->type
, "dir") != 0) {
3663 if (unshare(CLONE_NEWNS
) < 0) {
3664 ERROR("error unsharing mounts");
3669 if (detect_shared_rootfs()) {
3670 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3671 SYSERROR("Failed to make / rslave");
3672 ERROR("Continuing...");
3676 if (bdev
->ops
->mount(bdev
) < 0) {
3680 } else { /* TODO come up with a better way */
3682 bdev
->dest
= strdup(bdev
->src
);
3685 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3686 /* Start of environment variable setup for hooks */
3687 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3688 SYSERROR("failed to set environment variable for source container name");
3690 if (setenv("LXC_NAME", c
->name
, 1))
3691 SYSERROR("failed to set environment variable for container name");
3693 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3694 SYSERROR("failed to set environment variable for config path");
3696 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3697 SYSERROR("failed to set environment variable for rootfs mount");
3699 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3700 SYSERROR("failed to set environment variable for rootfs mount");
3702 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3703 ERROR("Error executing clone hook for %s", c
->name
);
3709 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3710 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3713 if (ret
< 0 || ret
>= MAXPATHLEN
)
3716 if (!file_exists(path
))
3719 if (!(fout
= fopen(path
, "w"))) {
3720 SYSERROR("unable to open %s: ignoring", path
);
3724 if (fprintf(fout
, "%s", c
->name
) < 0) {
3729 if (fclose(fout
) < 0)
3738 static int clone_update_rootfs_wrapper(void *data
)
3740 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3741 return clone_update_rootfs(arg
);
3745 * We want to support:
3746 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3747 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3749 -s [ implies overlay]
3752 only rootfs gets converted (copied/snapshotted) on clone.
3755 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3757 char *p
= strrchr(path
, '/');
3764 ret
= do_create_container_dir(path
, conf
);
3770 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3771 const char *lxcpath
, int flags
,
3772 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3775 char newpath
[MAXPATHLEN
];
3777 struct clone_update_data data
;
3778 size_t saved_unexp_len
;
3780 int storage_copied
= 0;
3781 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3782 struct lxc_container
*c2
= NULL
;
3784 if (!c
|| !do_lxcapi_is_defined(c
))
3787 if (container_mem_lock(c
))
3790 if (!is_stopped(c
)) {
3791 ERROR("error: Original container (%s) is running", c
->name
);
3795 /* Make sure the container doesn't yet exist. */
3800 lxcpath
= do_lxcapi_get_config_path(c
);
3802 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3803 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3804 SYSERROR("clone: failed making config pathname");
3808 if (file_exists(newpath
)) {
3809 ERROR("error: clone: %s exists", newpath
);
3813 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3814 if (ret
< 0 && errno
!= EEXIST
) {
3815 ERROR("Error creating container dir for %s", newpath
);
3819 /* Copy the configuration. Tweak it as needed. */
3820 if (c
->lxc_conf
->rootfs
.path
) {
3821 origroot
= c
->lxc_conf
->rootfs
.path
;
3822 c
->lxc_conf
->rootfs
.path
= NULL
;
3825 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3826 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3828 SYSERROR("Failed to open \"%s\"", newpath
);
3832 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3833 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3834 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3835 if (!c
->lxc_conf
->unexpanded_config
) {
3840 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3841 write_config(fd
, c
->lxc_conf
);
3844 c
->lxc_conf
->rootfs
.path
= origroot
;
3846 free(c
->lxc_conf
->unexpanded_config
);
3847 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3848 saved_unexp_conf
= NULL
;
3849 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3851 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3852 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3853 SYSERROR("clone: failed making rootfs pathname");
3857 ret
= mkdir(newpath
, 0755);
3859 /* For an overlay container the rootfs is considered immutable
3860 * and will not have been removed when restoring from a
3863 if (errno
!= ENOENT
&&
3864 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3865 SYSERROR("Failed to create directory \"%s\"", newpath
);
3870 if (am_guest_unpriv()) {
3871 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3872 ERROR("Error chowning %s to container root", newpath
);
3877 c2
= lxc_container_new(newname
, lxcpath
);
3879 ERROR("clone: failed to create new container (%s %s)", newname
,
3884 /* copy/snapshot rootfs's */
3885 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3889 /* update utsname */
3890 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3891 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3892 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3894 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3895 ERROR("Error setting new hostname");
3901 ret
= copyhooks(c
, c2
);
3903 ERROR("error copying hooks");
3907 if (copy_fstab(c
, c2
) < 0) {
3908 ERROR("error copying fstab");
3912 /* update macaddrs */
3913 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3914 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3915 ERROR("Error updating mac addresses");
3920 /* Update absolute paths for overlay mount directories. */
3921 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3924 /* We've now successfully created c2's storage, so clear it out if we
3929 if (!c2
->save_config(c2
, NULL
))
3932 if ((pid
= fork()) < 0) {
3938 ret
= wait_for_pid(pid
);
3942 container_mem_unlock(c
);
3949 data
.hookargs
= hookargs
;
3951 if (am_guest_unpriv())
3952 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3953 &data
, "clone_update_rootfs_wrapper");
3955 ret
= clone_update_rootfs(&data
);
3957 _exit(EXIT_FAILURE
);
3959 container_mem_unlock(c
);
3960 _exit(EXIT_SUCCESS
);
3963 container_mem_unlock(c
);
3965 if (!storage_copied
)
3966 c2
->lxc_conf
->rootfs
.path
= NULL
;
3969 lxc_container_put(c2
);
3975 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3976 const char *lxcpath
, int flags
,
3977 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3980 struct lxc_container
* ret
;
3982 current_config
= c
? c
->lxc_conf
: NULL
;
3983 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3984 current_config
= NULL
;
3989 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3991 struct lxc_storage
*bdev
;
3992 struct lxc_container
*newc
;
3994 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3997 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3998 ERROR("Renaming a container with snapshots is not supported");
4002 bdev
= storage_init(c
->lxc_conf
);
4004 ERROR("Failed to find original backing store type");
4008 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4011 lxc_container_put(newc
);
4015 if (newc
&& lxcapi_is_defined(newc
))
4016 lxc_container_put(newc
);
4018 if (!container_destroy(c
, NULL
)) {
4019 ERROR("Could not destroy existing container %s", c
->name
);
4026 WRAP_API_1(bool, lxcapi_rename
, const char *)
4028 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
)
4035 current_config
= c
->lxc_conf
;
4037 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4038 current_config
= NULL
;
4042 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4044 lxc_attach_command_t command
;
4051 command
.program
= (char*)program
;
4052 command
.argv
= (char**)argv
;
4054 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4060 return lxc_wait_for_pid_status(pid
);
4063 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4067 current_config
= c
? c
->lxc_conf
: NULL
;
4068 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4069 current_config
= NULL
;
4074 static int get_next_index(const char *lxcpath
, char *cname
)
4080 fname
= alloca(strlen(lxcpath
) + 20);
4083 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4085 ret
= stat(fname
, &sb
);
4093 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4098 * If the old style snapshot path exists, use it
4099 * /var/lib/lxc -> /var/lib/lxcsnaps
4101 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
4102 if (ret
< 0 || ret
>= MAXPATHLEN
)
4105 if (dir_exists(snappath
)) {
4106 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
4107 if (ret
< 0 || ret
>= MAXPATHLEN
)
4114 * Use the new style path
4115 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4117 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
4118 if (ret
< 0 || ret
>= MAXPATHLEN
)
4124 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4127 struct lxc_container
*c2
;
4128 char snappath
[MAXPATHLEN
], newname
[20];
4130 if (!c
|| !lxcapi_is_defined(c
))
4133 if (!storage_can_backup(c
->lxc_conf
)) {
4134 ERROR("%s's backing store cannot be backed up.", c
->name
);
4135 ERROR("Your container must use another backing store type.");
4139 if (!get_snappath_dir(c
, snappath
))
4142 i
= get_next_index(snappath
, c
->name
);
4144 if (mkdir_p(snappath
, 0755) < 0) {
4145 ERROR("Failed to create snapshot directory %s", snappath
);
4149 ret
= snprintf(newname
, 20, "snap%d", i
);
4150 if (ret
< 0 || ret
>= 20)
4154 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4155 * created in the original container
4157 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4158 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4159 if (storage_is_dir(c
->lxc_conf
)) {
4160 ERROR("Snapshot of directory-backed container requested.");
4161 ERROR("Making a copy-clone. If you do want snapshots, then");
4162 ERROR("please create overlay clone first, snapshot that");
4163 ERROR("and keep the original container pristine.");
4164 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4167 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4169 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
4173 lxc_container_put(c2
);
4175 /* Now write down the creation time. */
4182 tm_info
= localtime(&timer
);
4184 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
4186 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4187 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4188 f
= fopen(dfnam
, "w");
4190 ERROR("Failed to open %s", dfnam
);
4194 if (fprintf(f
, "%s", buffer
) < 0) {
4195 SYSERROR("Writing timestamp");
4202 SYSERROR("Writing timestamp");
4207 /* $p / $name / comment \0 */
4208 int len
= strlen(snappath
) + strlen(newname
) + 10;
4209 char *path
= alloca(len
);
4211 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4212 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4218 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4220 static void lxcsnap_free(struct lxc_snapshot
*s
)
4223 free(s
->comment_pathname
);
4228 static char *get_snapcomment_path(char* snappath
, char *name
)
4230 /* $snappath/$name/comment */
4231 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4232 char *s
= malloc(len
);
4235 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4236 if (ret
< 0 || ret
>= len
) {
4245 static char *get_timestamp(char* snappath
, char *name
)
4247 char path
[MAXPATHLEN
], *s
= NULL
;
4251 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4252 if (ret
< 0 || ret
>= MAXPATHLEN
)
4255 fin
= fopen(path
, "r");
4259 (void) fseek(fin
, 0, SEEK_END
);
4261 (void) fseek(fin
, 0, SEEK_SET
);
4266 if (fread(s
, 1, len
, fin
) != len
) {
4267 SYSERROR("reading timestamp");
4278 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4280 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4282 struct dirent
*direntp
;
4283 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4286 if (!c
|| !lxcapi_is_defined(c
))
4289 if (!get_snappath_dir(c
, snappath
)) {
4290 ERROR("path name too long");
4294 dir
= opendir(snappath
);
4296 INFO("Failed to open %s - assuming no snapshots", snappath
);
4300 while ((direntp
= readdir(dir
))) {
4301 if (!strcmp(direntp
->d_name
, "."))
4304 if (!strcmp(direntp
->d_name
, ".."))
4307 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4308 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4309 ERROR("pathname too long");
4313 if (!file_exists(path2
))
4316 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4318 SYSERROR("Out of memory");
4323 snaps
[count
].free
= lxcsnap_free
;
4324 snaps
[count
].name
= strdup(direntp
->d_name
);
4325 if (!snaps
[count
].name
)
4328 snaps
[count
].lxcpath
= strdup(snappath
);
4329 if (!snaps
[count
].lxcpath
) {
4330 free(snaps
[count
].name
);
4334 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4335 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4340 WARN("Failed to close directory");
4349 for (i
=0; i
<count
; i
++)
4350 lxcsnap_free(&snaps
[i
]);
4356 WARN("Failed to close directory");
4361 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4363 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4365 char clonelxcpath
[MAXPATHLEN
];
4367 struct lxc_container
*snap
, *rest
;
4368 struct lxc_storage
*bdev
;
4371 if (!c
|| !c
->name
|| !c
->config_path
)
4374 if (has_fs_snapshots(c
)) {
4375 ERROR("container rootfs has dependent snapshots");
4379 bdev
= storage_init(c
->lxc_conf
);
4381 ERROR("Failed to find original backing store type");
4385 /* For an overlay container the rootfs is considered immutable
4386 * and cannot be removed when restoring from a snapshot. We pass this
4387 * internal flag along to communicate this to various parts of the
4390 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4391 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4396 if (!get_snappath_dir(c
, clonelxcpath
)) {
4400 /* how should we lock this? */
4402 snap
= lxc_container_new(snapname
, clonelxcpath
);
4403 if (!snap
|| !lxcapi_is_defined(snap
)) {
4404 ERROR("Could not open snapshot %s", snapname
);
4407 lxc_container_put(snap
);
4413 if (!strcmp(c
->name
, newname
)) {
4414 if (!container_destroy(c
, bdev
)) {
4415 ERROR("Could not destroy existing container %s", newname
);
4416 lxc_container_put(snap
);
4422 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4423 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4425 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4426 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4428 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4431 if (rest
&& lxcapi_is_defined(rest
))
4435 lxc_container_put(rest
);
4437 lxc_container_put(snap
);
4441 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4443 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4445 struct lxc_container
*snap
= NULL
;
4448 snap
= lxc_container_new(snapname
, clonelxcpath
);
4450 ERROR("Could not find snapshot %s", snapname
);
4454 if (!do_lxcapi_destroy(snap
)) {
4455 ERROR("Could not destroy snapshot %s", snapname
);
4463 lxc_container_put(snap
);
4468 static bool remove_all_snapshots(const char *path
)
4471 struct dirent
*direntp
;
4474 dir
= opendir(path
);
4476 SYSERROR("opendir on snapshot path %s", path
);
4480 while ((direntp
= readdir(dir
))) {
4481 if (!strcmp(direntp
->d_name
, "."))
4484 if (!strcmp(direntp
->d_name
, ".."))
4487 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4496 SYSERROR("Error removing directory %s", path
);
4501 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4503 char clonelxcpath
[MAXPATHLEN
];
4505 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4508 if (!get_snappath_dir(c
, clonelxcpath
))
4511 return do_snapshot_destroy(snapname
, clonelxcpath
);
4514 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4516 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4518 char clonelxcpath
[MAXPATHLEN
];
4520 if (!c
|| !c
->name
|| !c
->config_path
)
4523 if (!get_snappath_dir(c
, clonelxcpath
))
4526 return remove_all_snapshots(clonelxcpath
);
4529 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4531 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4533 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4536 WRAP_API(bool, lxcapi_may_control
)
4538 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4544 char chrootpath
[MAXPATHLEN
];
4545 char *directory_path
= NULL
;
4549 SYSERROR("Failed to fork()");
4554 ret
= wait_for_pid(pid
);
4556 ERROR("Failed to create device node");
4563 /* prepare the path */
4564 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4565 if (ret
< 0 || ret
>= MAXPATHLEN
)
4568 ret
= chroot(chrootpath
);
4570 _exit(EXIT_FAILURE
);
4574 _exit(EXIT_FAILURE
);
4576 /* remove path if it exists */
4577 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4581 SYSERROR("Failed to remove \"%s\"", path
);
4582 _exit(EXIT_FAILURE
);
4587 _exit(EXIT_SUCCESS
);
4589 /* create any missing directories */
4592 _exit(EXIT_FAILURE
);
4594 directory_path
= dirname(tmp
);
4595 ret
= mkdir_p(directory_path
, 0755);
4596 if (ret
< 0 && errno
!= EEXIST
) {
4597 SYSERROR("Failed to create path \"%s\"", directory_path
);
4599 _exit(EXIT_FAILURE
);
4602 /* create the device node */
4603 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4606 SYSERROR("Failed to create device node at \"%s\"", path
);
4607 _exit(EXIT_FAILURE
);
4610 _exit(EXIT_SUCCESS
);
4613 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4617 char value
[LXC_MAX_BUFFER
];
4620 /* make sure container is running */
4621 if (!do_lxcapi_is_running(c
)) {
4622 ERROR("container is not running");
4626 /* use src_path if dest_path is NULL otherwise use dest_path */
4627 p
= dest_path
? dest_path
: src_path
;
4629 /* make sure we can access p */
4630 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4633 /* continue if path is character device or block device */
4634 if (S_ISCHR(st
.st_mode
))
4635 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4636 else if (S_ISBLK(st
.st_mode
))
4637 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4641 /* check snprintf return code */
4642 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4645 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4648 /* add or remove device to/from cgroup access list */
4650 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4651 ERROR("set_cgroup_item failed while adding the device node");
4655 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4656 ERROR("set_cgroup_item failed while removing the device node");
4664 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4666 // cannot mknod if we're not privileged wrt init_user_ns
4667 if (am_host_unpriv()) {
4668 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4672 return add_remove_device_node(c
, src_path
, dest_path
, true);
4675 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4677 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4679 if (am_guest_unpriv()) {
4680 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4684 return add_remove_device_node(c
, src_path
, dest_path
, false);
4687 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4689 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4691 const char *dst_ifname
)
4696 if (am_guest_unpriv()) {
4697 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4702 ERROR("No source interface name given");
4706 ret
= lxc_netdev_isup(ifname
);
4708 /* netdev of ifname is up. */
4709 ret
= lxc_netdev_down(ifname
);
4714 init_pid
= do_lxcapi_init_pid(c
);
4715 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4719 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4726 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4728 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4730 const char *dst_ifname
)
4733 pid_t pid
, pid_outside
;
4736 * TODO - if this is a physical device, then we need am_host_unpriv.
4737 * But for other types guest privilege suffices.
4739 if (am_guest_unpriv()) {
4740 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4745 ERROR("No source interface name given");
4749 pid_outside
= lxc_raw_getpid();
4752 ERROR("Failed to fork");
4756 if (pid
== 0) { /* child */
4759 init_pid
= do_lxcapi_init_pid(c
);
4760 if (!switch_to_ns(init_pid
, "net")) {
4761 ERROR("Failed to enter network namespace");
4762 _exit(EXIT_FAILURE
);
4765 ret
= lxc_netdev_isup(ifname
);
4767 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4768 _exit(EXIT_FAILURE
);
4771 /* netdev of ifname is up. */
4773 ret
= lxc_netdev_down(ifname
);
4775 ERROR("Failed to set network device \"%s\" down", ifname
);
4776 _exit(EXIT_FAILURE
);
4780 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4781 /* -EINVAL means there is no netdev named as ifname. */
4784 ERROR("Network device \"%s\" not found", ifname
);
4786 ERROR("Failed to remove network device \"%s\"", ifname
);
4788 _exit(EXIT_FAILURE
);
4791 _exit(EXIT_SUCCESS
);
4794 ret
= wait_for_pid(pid
);
4798 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4802 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4804 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4805 struct migrate_opts
*opts
, unsigned int size
)
4808 struct migrate_opts
*valid_opts
= opts
;
4809 uint64_t features_to_check
= 0;
4811 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4812 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4813 * to do anything special.
4815 if (size
> sizeof(*opts
)) {
4816 unsigned char *addr
;
4819 addr
= (void *)opts
+ sizeof(*opts
);
4820 end
= (void *)opts
+ size
;
4822 for (; addr
< end
; addr
++)
4827 /* If the caller has a smaller struct, let's zero out the end for them
4828 * so we don't accidentally use bits of it that they didn't know about
4831 if (size
< sizeof(*opts
)) {
4832 valid_opts
= malloc(sizeof(*opts
));
4836 memset(valid_opts
, 0, sizeof(*opts
));
4837 memcpy(valid_opts
, opts
, size
);
4841 case MIGRATE_PRE_DUMP
:
4842 if (!do_lxcapi_is_running(c
)) {
4843 ERROR("container is not running");
4847 ret
= !__criu_pre_dump(c
, valid_opts
);
4850 if (!do_lxcapi_is_running(c
)) {
4851 ERROR("container is not running");
4855 ret
= !__criu_dump(c
, valid_opts
);
4857 case MIGRATE_RESTORE
:
4858 if (do_lxcapi_is_running(c
)) {
4859 ERROR("container is already running");
4863 ret
= !__criu_restore(c
, valid_opts
);
4865 case MIGRATE_FEATURE_CHECK
:
4866 features_to_check
= valid_opts
->features_to_check
;
4867 ret
= !__criu_check_feature(&features_to_check
);
4869 /* Something went wrong. Let's let the caller
4870 * know which feature checks failed. */
4871 valid_opts
->features_to_check
= features_to_check
;
4875 ERROR("invalid migrate command %u", cmd
);
4880 if (size
< sizeof(*opts
))
4886 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4888 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4890 struct migrate_opts opts
;
4892 memset(&opts
, 0, sizeof(opts
));
4894 opts
.directory
= directory
;
4896 opts
.verbose
= verbose
;
4898 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4901 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4903 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4905 struct migrate_opts opts
;
4907 memset(&opts
, 0, sizeof(opts
));
4909 opts
.directory
= directory
;
4910 opts
.verbose
= verbose
;
4912 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4915 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4917 static int do_lxcapi_mount(struct lxc_container
*c
,
4918 const char *source
, const char *target
,
4919 const char *filesystemtype
, unsigned long mountflags
,
4920 const void *data
, struct lxc_mount
*mnt
) {
4922 char template[MAXPATHLEN
], path
[MAXPATHLEN
];
4923 pid_t pid
, init_pid
;
4925 int ret
= -1, fd
= -EBADF
;
4927 if (!c
|| !c
->lxc_conf
) {
4928 ERROR("Container or configuration is NULL");
4932 if (!c
->lxc_conf
->lxc_shmount
.path_host
) {
4933 ERROR("Host path to shared mountpoint must be specified in the config\n");
4936 len
= strlen(c
->lxc_conf
->lxc_shmount
.path_host
) + sizeof("/.lxcmount_XXXXXX") - 1;
4938 ret
= snprintf(template, len
+ 1, "%s/.lxcmount_XXXXXX", c
->lxc_conf
->lxc_shmount
.path_host
);
4939 if (ret
< 0 || (size_t)ret
>= len
+ 1) {
4940 SYSERROR("Error writing shmounts tempdir name");
4944 /* Create a temporary dir under the shared mountpoint */
4945 sret
= mkdtemp(template);
4947 SYSERROR("Could not create shmounts temporary dir");
4954 SYSERROR("Could not fork");
4960 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
4962 SYSERROR("Failed to mount \"%s\" onto \"%s\"", source
, template);
4963 _exit(EXIT_FAILURE
);
4966 init_pid
= do_lxcapi_init_pid(c
);
4968 ERROR("Failed to obtain container's init pid");
4969 _exit(EXIT_FAILURE
);
4972 /* Enter the container namespaces */
4973 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
4974 if (!switch_to_ns(init_pid
, "user")){
4975 ERROR("Failed to enter user namespace");
4976 _exit(EXIT_FAILURE
);
4979 if (!switch_to_ns(init_pid
, "mnt")) {
4980 ERROR("Failed to enter mount namespace");
4981 _exit(EXIT_FAILURE
);
4984 suff
= strrchr(template, '/');
4986 _exit(EXIT_FAILURE
);
4988 len
= strlen(c
->lxc_conf
->lxc_shmount
.path_cont
) + sizeof("/.lxcmount_XXXXXX") - 1;
4989 ret
= snprintf(path
, len
+ 1, "%s%s", c
->lxc_conf
->lxc_shmount
.path_cont
, suff
);
4990 if (ret
< 0 || (size_t)ret
>= len
+ 1) {
4991 SYSERROR("Error writing container mountpoint name");
4992 _exit(EXIT_FAILURE
);
4995 ret
= mkdir_p(target
, 0700);
4997 ERROR("Failed to create container temp mountpoint");
4998 _exit(EXIT_FAILURE
);
5001 ret
= mount(path
, target
, NULL
, MS_REC
| MS_MOVE
, NULL
);
5003 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5004 _exit(EXIT_FAILURE
);
5007 _exit(EXIT_SUCCESS
);
5010 ret
= wait_for_pid(pid
);
5012 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5018 (void)umount2(template, MNT_DETACH
);
5019 (void)unlink(template);
5027 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5028 unsigned long, const void *, struct lxc_mount
*)
5030 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5039 current_config
= c
->lxc_conf
;
5042 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5046 ERROR("Memory allocation error.");
5052 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5056 current_config
= NULL
;
5060 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5062 struct lxc_container
*c
;
5068 c
= malloc(sizeof(*c
));
5070 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5073 memset(c
, 0, sizeof(*c
));
5076 c
->config_path
= strdup(configpath
);
5078 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5079 if (!c
->config_path
) {
5080 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5084 remove_trailing_slashes(c
->config_path
);
5087 c
->name
= malloc(len
+ 1);
5089 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5092 (void)strlcpy(c
->name
, name
, len
+ 1);
5095 c
->slock
= lxc_newlock(c
->config_path
, name
);
5097 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5101 c
->privlock
= lxc_newlock(NULL
, NULL
);
5103 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5107 if (!set_config_filename(c
)) {
5108 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5112 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5113 fprintf(stderr
, "Failed to load config for %s\n", name
);
5117 if (ongoing_create(c
) == 2) {
5118 ERROR("Failed to complete container creation for %s", c
->name
);
5119 container_destroy(c
, NULL
);
5120 lxcapi_clear_config(c
);
5123 c
->daemonize
= true;
5126 /* Assign the member functions. */
5127 c
->is_defined
= lxcapi_is_defined
;
5128 c
->state
= lxcapi_state
;
5129 c
->is_running
= lxcapi_is_running
;
5130 c
->freeze
= lxcapi_freeze
;
5131 c
->unfreeze
= lxcapi_unfreeze
;
5132 c
->console
= lxcapi_console
;
5133 c
->console_getfd
= lxcapi_console_getfd
;
5134 c
->init_pid
= lxcapi_init_pid
;
5135 c
->load_config
= lxcapi_load_config
;
5136 c
->want_daemonize
= lxcapi_want_daemonize
;
5137 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5138 c
->start
= lxcapi_start
;
5139 c
->startl
= lxcapi_startl
;
5140 c
->stop
= lxcapi_stop
;
5141 c
->config_file_name
= lxcapi_config_file_name
;
5142 c
->wait
= lxcapi_wait
;
5143 c
->set_config_item
= lxcapi_set_config_item
;
5144 c
->destroy
= lxcapi_destroy
;
5145 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5146 c
->rename
= lxcapi_rename
;
5147 c
->save_config
= lxcapi_save_config
;
5148 c
->get_keys
= lxcapi_get_keys
;
5149 c
->create
= lxcapi_create
;
5150 c
->createl
= lxcapi_createl
;
5151 c
->shutdown
= lxcapi_shutdown
;
5152 c
->reboot
= lxcapi_reboot
;
5153 c
->reboot2
= lxcapi_reboot2
;
5154 c
->clear_config
= lxcapi_clear_config
;
5155 c
->clear_config_item
= lxcapi_clear_config_item
;
5156 c
->get_config_item
= lxcapi_get_config_item
;
5157 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5158 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5159 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5160 c
->get_config_path
= lxcapi_get_config_path
;
5161 c
->set_config_path
= lxcapi_set_config_path
;
5162 c
->clone
= lxcapi_clone
;
5163 c
->get_interfaces
= lxcapi_get_interfaces
;
5164 c
->get_ips
= lxcapi_get_ips
;
5165 c
->attach
= lxcapi_attach
;
5166 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5167 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5168 c
->snapshot
= lxcapi_snapshot
;
5169 c
->snapshot_list
= lxcapi_snapshot_list
;
5170 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5171 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5172 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5173 c
->may_control
= lxcapi_may_control
;
5174 c
->add_device_node
= lxcapi_add_device_node
;
5175 c
->remove_device_node
= lxcapi_remove_device_node
;
5176 c
->attach_interface
= lxcapi_attach_interface
;
5177 c
->detach_interface
= lxcapi_detach_interface
;
5178 c
->checkpoint
= lxcapi_checkpoint
;
5179 c
->restore
= lxcapi_restore
;
5180 c
->migrate
= lxcapi_migrate
;
5181 c
->console_log
= lxcapi_console_log
;
5182 c
->mount
= lxcapi_mount
;
5187 lxc_container_free(c
);
5191 int lxc_get_wait_states(const char **states
)
5196 for (i
=0; i
<MAX_STATE
; i
++)
5197 states
[i
] = lxc_state2str(i
);
5203 * These next two could probably be done smarter with reusing a common function
5204 * with different iterators and tests...
5206 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5209 int i
, cfound
= 0, nfound
= 0;
5210 struct dirent
*direntp
;
5211 struct lxc_container
*c
;
5214 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5216 dir
= opendir(lxcpath
);
5218 SYSERROR("opendir on lxcpath");
5228 while ((direntp
= readdir(dir
))) {
5229 /* Ignore '.', '..' and any hidden directory. */
5230 if (!strncmp(direntp
->d_name
, ".", 1))
5233 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5237 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5247 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5249 INFO("Container %s:%s has a config but could not be loaded",
5250 lxcpath
, direntp
->d_name
);
5253 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5259 if (!do_lxcapi_is_defined(c
)) {
5260 INFO("Container %s:%s has a config but is not defined",
5261 lxcpath
, direntp
->d_name
);
5264 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5267 lxc_container_put(c
);
5271 if (!add_to_clist(cret
, c
, nfound
, true)) {
5272 lxc_container_put(c
);
5283 if (names
&& *names
) {
5284 for (i
=0; i
<cfound
; i
++)
5289 if (cret
&& *cret
) {
5290 for (i
=0; i
<nfound
; i
++)
5291 lxc_container_put((*cret
)[i
]);
5299 int list_active_containers(const char *lxcpath
, char ***nret
,
5300 struct lxc_container
***cret
)
5302 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5305 char **ct_name
= NULL
;
5307 struct lxc_container
*c
= NULL
;
5311 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5312 lxcpath_len
= strlen(lxcpath
);
5320 FILE *f
= fopen("/proc/net/unix", "r");
5324 while (getline(&line
, &len
, f
) != -1) {
5325 char *p
= strrchr(line
, ' '), *p2
;
5336 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5338 } else if (strncmp(p
, "lxc/", 4) == 0) {
5348 /* Now p is the start of lxc_name. */
5349 p2
= strchr(p
, '/');
5350 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5355 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5359 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5365 p
= lxc_cmd_get_name(p
);
5370 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5376 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5379 goto free_cret_list
;
5390 c
= lxc_container_new(p
, lxcpath
);
5392 INFO("Container %s:%s is running but could not be loaded",
5395 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5406 * If this is an anonymous container, then is_defined *can*
5407 * return false. So we don't do that check. Count on the
5408 * fact that the command socket exists.
5411 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5412 lxc_container_put(c
);
5413 goto free_cret_list
;
5419 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5421 lxc_container_put(c
);
5422 goto free_cret_list
;
5434 if (cret
&& *cret
) {
5435 for (i
= 0; i
< cret_cnt
; i
++)
5436 lxc_container_put((*cret
)[i
]);
5442 for (i
= 0; i
< ct_name_cnt
; i
++)
5453 int list_all_containers(const char *lxcpath
, char ***nret
,
5454 struct lxc_container
***cret
)
5456 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5459 struct lxc_container
**ct_list
= NULL
;
5461 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5465 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5466 if (active_cnt
< 0) {
5471 for (i
= 0; i
< active_cnt
; i
++) {
5472 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5473 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5475 goto free_active_name
;
5481 free(active_name
[i
]);
5482 active_name
[i
] = NULL
;
5489 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5490 struct lxc_container
*c
;
5492 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5494 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5495 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5499 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5500 lxc_container_put(c
);
5521 for (i
= 0; i
< ct_list_cnt
; i
++) {
5522 lxc_container_put(ct_list
[i
]);
5527 for (i
= 0; i
< active_cnt
; i
++) {
5528 free(active_name
[i
]);
5533 for (i
= 0; i
< ct_cnt
; i
++) {
5540 bool lxc_config_item_is_supported(const char *key
)
5542 return !!lxc_get_config(key
);