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
33 #include <arpa/inet.h>
34 #include <sys/sysmacros.h>
36 #include <sys/mount.h>
37 #include <sys/syscall.h>
38 #include <sys/types.h>
47 #include "commands_utils.h"
49 #include "confile_utils.h"
52 #include "initutils.h"
55 #include "lxccontainer.h"
58 #include "namespace.h"
64 #include "storage_utils.h"
65 #include "storage/btrfs.h"
66 #include "storage/overlay.h"
73 # include <sys/mkdev.h>
79 #include <../include/ifaddrs.h>
83 #include <../include/lxcmntent.h>
88 #define MAX_BUFFER 4096
90 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
92 /* Define faccessat() if missing from the C library */
93 #ifndef HAVE_FACCESSAT
94 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
97 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
105 lxc_log_define(lxc_container
, lxc
);
107 static bool do_lxcapi_destroy(struct lxc_container
*c
);
108 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
109 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
110 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
111 static bool container_destroy(struct lxc_container
*c
,
112 struct lxc_storage
*storage
);
113 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
114 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
115 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
117 static bool config_file_exists(const char *lxcpath
, const char *cname
)
119 /* $lxcpath + '/' + $cname + '/config' + \0 */
120 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
121 char *fname
= alloca(len
);
123 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
124 if (ret
< 0 || ret
>= len
)
127 return file_exists(fname
);
131 * A few functions to help detect when a container creation failed.
132 * If a container creation was killed partway through, then trying
133 * to actually start that container could harm the host. We detect
134 * this by creating a 'partial' file under the container directory,
135 * and keeping an advisory lock. When container creation completes,
136 * we remove that file. When we load or try to start a container, if
137 * we find that file, without a flock, we remove the container.
139 static int ongoing_create(struct lxc_container
*c
)
141 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
142 char *path
= alloca(len
);
146 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
147 if (ret
< 0 || ret
>= len
) {
148 ERROR("Error writing partial pathname");
152 if (!file_exists(path
))
154 fd
= open(path
, O_RDWR
);
156 /* give benefit of the doubt */
157 SYSERROR("Error opening partial file");
161 lk
.l_whence
= SEEK_SET
;
165 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
166 /* create is still ongoing */
170 /* create completed but partial is still there. */
175 static int create_partial(struct lxc_container
*c
)
177 /* $lxcpath + '/' + $name + '/partial' + \0 */
178 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
179 char *path
= alloca(len
);
183 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
184 if (ret
< 0 || ret
>= len
) {
185 ERROR("Error writing partial pathname");
188 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
189 SYSERROR("Error creating partial file");
193 lk
.l_whence
= SEEK_SET
;
196 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
197 SYSERROR("Error locking partial file %s", path
);
205 static void remove_partial(struct lxc_container
*c
, int fd
)
207 /* $lxcpath + '/' + $name + '/partial' + \0 */
208 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
209 char *path
= alloca(len
);
213 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
214 if (ret
< 0 || ret
>= len
) {
215 ERROR("Error writing partial pathname");
218 if (unlink(path
) < 0)
219 SYSERROR("Error unlink partial file %s", path
);
223 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
224 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
225 * container configuration file.
226 * The container_disk_lock also takes the container_mem_lock.
227 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
228 * NOTHING mutexes two independent programs with their own struct
229 * lxc_container for the same c->name, between API calls. For instance,
230 * c->config_read(); c->start(); Between those calls, data on disk
231 * could change (which shouldn't bother the caller unless for instance
232 * the rootfs get moved). c->config_read(); update; c->config_write();
233 * Two such updaters could race. The callers should therefore check their
234 * results. Trying to prevent that would necessarily expose us to deadlocks
235 * due to hung callers. So I prefer to keep the locks only within our own
236 * functions, not across functions.
238 * If you're going to clone while holding a lxccontainer, increment
239 * c->numthreads (under privlock) before forking. When deleting,
240 * decrement numthreads under privlock, then if it hits 0 you can delete.
241 * Do not ever use a lxccontainer whose numthreads you did not bump.
244 static void lxc_container_free(struct lxc_container
*c
)
250 c
->configfile
= NULL
;
251 free(c
->error_string
);
252 c
->error_string
= NULL
;
254 lxc_putlock(c
->slock
);
258 lxc_putlock(c
->privlock
);
264 lxc_conf_free(c
->lxc_conf
);
267 free(c
->config_path
);
268 c
->config_path
= NULL
;
274 * Consider the following case:
275 freer | racing get()er
276 ==================================================================
277 lxc_container_put() | lxc_container_get()
278 \ lxclock(c->privlock) | c->numthreads < 1? (no)
279 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
281 \ lxc_container_free() | \ lxclock() returns
282 | \ c->numthreads < 1 -> return 0
284 \ \ sem_destroy(privlock) |
286 * When the get()er checks numthreads the first time, one of the following
288 * 1. freer has set numthreads = 0. get() returns 0
289 * 2. freer is between lxclock and setting numthreads to 0. get()er will
290 * sem_wait on privlock, get lxclock after freer() drops it, then see
291 * numthreads is 0 and exit without touching lxclock again..
292 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
293 * will see --numthreads = 1 and not call lxc_container_free().
296 int lxc_container_get(struct lxc_container
*c
)
301 /* If someone else has already started freeing the container, don't try
302 * to take the lock, which may be invalid.
304 if (c
->numthreads
< 1)
307 if (container_mem_lock(c
))
310 /* Bail without trying to unlock, bc the privlock is now probably in
313 if (c
->numthreads
< 1)
317 container_mem_unlock(c
);
321 int lxc_container_put(struct lxc_container
*c
)
325 if (container_mem_lock(c
))
327 if (--c
->numthreads
< 1) {
328 container_mem_unlock(c
);
329 lxc_container_free(c
);
332 container_mem_unlock(c
);
336 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
345 if (container_mem_lock(c
))
349 statret
= stat(c
->configfile
, &statbuf
);
355 container_mem_unlock(c
);
359 #define WRAP_API(rettype, fnname) \
360 static rettype fnname(struct lxc_container *c) \
363 bool reset_config = false; \
365 if (!current_config && c && c->lxc_conf) { \
366 current_config = c->lxc_conf; \
367 reset_config = true; \
370 ret = do_##fnname(c); \
372 current_config = NULL; \
377 #define WRAP_API_1(rettype, fnname, t1) \
378 static rettype fnname(struct lxc_container *c, t1 a1) \
381 bool reset_config = false; \
383 if (!current_config && c && c->lxc_conf) { \
384 current_config = c->lxc_conf; \
385 reset_config = true; \
388 ret = do_##fnname(c, a1); \
390 current_config = NULL; \
395 #define WRAP_API_2(rettype, fnname, t1, t2) \
396 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
399 bool reset_config = false; \
401 if (!current_config && c && c->lxc_conf) { \
402 current_config = c->lxc_conf; \
403 reset_config = true; \
406 ret = do_##fnname(c, a1, a2); \
408 current_config = NULL; \
413 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
414 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
417 bool reset_config = false; \
419 if (!current_config && c && c->lxc_conf) { \
420 current_config = c->lxc_conf; \
421 reset_config = true; \
424 ret = do_##fnname(c, a1, a2, a3); \
426 current_config = NULL; \
431 WRAP_API(bool, lxcapi_is_defined
)
433 static const char *do_lxcapi_state(struct lxc_container
*c
)
439 s
= lxc_getstate(c
->name
, c
->config_path
);
440 return lxc_state2str(s
);
443 WRAP_API(const char *, lxcapi_state
)
445 static bool is_stopped(struct lxc_container
*c
)
448 s
= lxc_getstate(c
->name
, c
->config_path
);
449 return (s
== STOPPED
);
452 static bool do_lxcapi_is_running(struct lxc_container
*c
)
458 s
= do_lxcapi_state(c
);
459 if (!s
|| strcmp(s
, "STOPPED") == 0)
464 WRAP_API(bool, lxcapi_is_running
)
466 static bool do_lxcapi_freeze(struct lxc_container
*c
)
472 ret
= lxc_freeze(c
->name
, c
->config_path
);
478 WRAP_API(bool, lxcapi_freeze
)
480 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
486 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
492 WRAP_API(bool, lxcapi_unfreeze
)
494 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
500 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
504 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
506 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
507 int stdoutfd
, int stderrfd
, int escape
)
514 current_config
= c
->lxc_conf
;
515 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
516 current_config
= NULL
;
520 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
524 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
527 NOTICE("The console log is empty");
528 else if (ret
== -EFAULT
)
529 NOTICE("The container does not keep a console log");
530 else if (ret
== -ENOENT
)
531 NOTICE("The container does not keep a console log file");
532 else if (ret
== -EIO
)
533 NOTICE("Failed to write console log to log file");
535 ERROR("Failed to retrieve console log");
541 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
543 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
548 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
551 WRAP_API(pid_t
, lxcapi_init_pid
)
553 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
556 c
->lxc_conf
= lxc_conf_init();
559 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
564 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
566 bool ret
= false, need_disklock
= false;
572 fname
= c
->configfile
;
578 * If we're reading something other than the container's config,
579 * we only need to lock the in-memory container. If loading the
580 * container's config file, take the disk lock.
582 if (strcmp(fname
, c
->configfile
) == 0)
583 need_disklock
= true;
586 lret
= container_disk_lock(c
);
588 lret
= container_mem_lock(c
);
592 ret
= load_config_locked(c
, fname
);
595 container_disk_unlock(c
);
597 container_mem_unlock(c
);
601 WRAP_API_1(bool, lxcapi_load_config
, const char *)
603 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
605 if (!c
|| !c
->lxc_conf
)
607 if (container_mem_lock(c
)) {
608 ERROR("Error getting mem lock");
611 c
->daemonize
= state
;
612 container_mem_unlock(c
);
616 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
618 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
620 if (!c
|| !c
->lxc_conf
)
622 if (container_mem_lock(c
)) {
623 ERROR("Error getting mem lock");
626 c
->lxc_conf
->close_all_fds
= state
;
627 container_mem_unlock(c
);
631 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
633 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
640 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
644 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
646 static bool am_single_threaded(void)
648 struct dirent
*direntp
;
652 dir
= opendir("/proc/self/task");
654 INFO("failed to open /proc/self/task");
658 while ((direntp
= readdir(dir
))) {
659 if (!strcmp(direntp
->d_name
, "."))
662 if (!strcmp(direntp
->d_name
, ".."))
671 static void push_arg(char ***argp
, char *arg
, int *nargs
)
680 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
688 static char **split_init_cmd(const char *incmd
)
692 char *copy
, *p
, *saveptr
= NULL
;
698 len
= strlen(incmd
) + 1;
700 strncpy(copy
, incmd
, len
);
704 argv
= malloc(sizeof(char *));
707 for (p
= strtok_r(copy
, " ", &saveptr
); p
!= NULL
;
708 p
= strtok_r(NULL
, " ", &saveptr
))
709 push_arg(&argv
, p
, &nargs
);
718 static void free_init_cmd(char **argv
)
729 static int lxc_rcv_status(int state_socket
)
735 /* Receive container state. */
736 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
,
741 TRACE("Caught EINTR; retrying");
748 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
752 /* Close write end of the socket pair. */
753 close(handler
->state_socket_pair
[1]);
754 handler
->state_socket_pair
[1] = -1;
756 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
758 /* Close read end of the socket pair. */
759 close(handler
->state_socket_pair
[0]);
760 handler
->state_socket_pair
[0] = -1;
762 /* The first child is going to fork() again and then exits. So we reap
763 * the first child here.
765 ret
= wait_for_pid(pid
);
767 DEBUG("Failed waiting on first child %d", pid
);
769 DEBUG("First child %d exited", pid
);
772 SYSERROR("Failed to receive the container state");
776 /* If we receive anything else then running we know that the container
779 if (state
!= RUNNING
) {
780 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
781 lxc_state2str(state
));
785 TRACE("Container is in \"RUNNING\" state");
789 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
792 struct lxc_handler
*handler
;
793 struct lxc_conf
*conf
;
794 bool daemonize
= false;
796 char *default_args
[] = {
800 char **init_cmd
= NULL
;
801 int keepfds
[3] = {-1, -1, -1};
803 /* container does exist */
807 /* If anything fails before we set error_num, we want an error in there.
811 /* Container has not been setup. */
815 ret
= ongoing_create(c
);
817 ERROR("Failed checking for incomplete container creation");
819 } else if (ret
== 1) {
820 ERROR("Ongoing container creation detected");
822 } else if (ret
== 2) {
823 ERROR("Failed to create container");
824 do_lxcapi_destroy(c
);
828 if (container_mem_lock(c
))
831 daemonize
= c
->daemonize
;
833 /* initialize handler */
834 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, daemonize
);
835 container_mem_unlock(c
);
840 if (useinit
&& conf
->execute_cmd
)
841 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
843 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
846 /* ... otherwise use default_args. */
849 ERROR("No valid init detected");
850 lxc_free_handler(handler
);
856 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
857 * here to protect the on disk container? We don't want to exclude
858 * things like lxc_info while the container is running.
867 free_init_cmd(init_cmd
);
868 lxc_free_handler(handler
);
874 /* Set to NULL because we don't want father unlink
875 * the PID file, child will do the free and unlink.
879 /* Wait for container to tell us whether it started
882 started
= wait_on_daemonized_start(handler
, pid
);
884 free_init_cmd(init_cmd
);
885 lxc_free_handler(handler
);
891 /* We don't really care if this doesn't print all the
892 * characters. All that it means is that the proctitle will be
893 * ugly. Similarly, we also don't care if setproctitle() fails.
895 snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
896 INFO("Attempting to set proc title to %s", title
);
899 /* We fork() a second time to be reparented to init. Like
900 * POSIX's daemon() function we change to "/" and redirect
901 * std{in,out,err} to /dev/null.
905 SYSERROR("Failed to fork first child process");
911 free_init_cmd(init_cmd
);
912 lxc_free_handler(handler
);
918 /* change to / directory */
921 SYSERROR("Failed to change to \"/\" directory");
925 keepfds
[0] = handler
->conf
->maincmd_fd
;
926 keepfds
[1] = handler
->state_socket_pair
[0];
927 keepfds
[2] = handler
->state_socket_pair
[1];
928 ret
= lxc_check_inherited(conf
, true, keepfds
,
929 sizeof(keepfds
) / sizeof(keepfds
[0]));
933 /* redirect std{in,out,err} to /dev/null */
936 ERROR("Failed to redirect std{in,out,err} to /dev/null");
940 /* become session leader */
943 TRACE("Process %d is already process group leader", lxc_raw_getpid());
945 if (!am_single_threaded()) {
946 ERROR("Cannot start non-daemonized container when threaded");
947 free_init_cmd(init_cmd
);
948 lxc_free_handler(handler
);
953 /* We need to write PID file after daemonize, so we always
954 * write the right PID.
957 pid_fp
= fopen(c
->pidfile
, "w");
958 if (pid_fp
== NULL
) {
959 SYSERROR("Failed to create pidfile '%s' for '%s'",
960 c
->pidfile
, c
->name
);
961 free_init_cmd(init_cmd
);
962 lxc_free_handler(handler
);
968 if (fprintf(pid_fp
, "%d\n", lxc_raw_getpid()) < 0) {
969 SYSERROR("Failed to write '%s'", c
->pidfile
);
972 free_init_cmd(init_cmd
);
973 lxc_free_handler(handler
);
985 /* Unshare the mount namespace if requested */
986 if (conf
->monitor_unshare
) {
987 ret
= unshare(CLONE_NEWNS
);
989 SYSERROR("failed to unshare mount namespace");
990 lxc_free_handler(handler
);
995 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
997 SYSERROR("Failed to make / rslave at startup");
998 lxc_free_handler(handler
);
1005 if (conf
->reboot
== 2) {
1006 /* initialize handler */
1007 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, daemonize
);
1014 keepfds
[0] = handler
->conf
->maincmd_fd
;
1015 keepfds
[1] = handler
->state_socket_pair
[0];
1016 keepfds
[2] = handler
->state_socket_pair
[1];
1017 ret
= lxc_check_inherited(conf
, daemonize
, keepfds
,
1018 sizeof(keepfds
) / sizeof(keepfds
[0]));
1020 lxc_free_handler(handler
);
1026 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
, daemonize
);
1028 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
, daemonize
);
1029 c
->error_num
= handler
->exit_status
;
1031 if (conf
->reboot
== 1) {
1032 INFO("Container requested reboot");
1043 free_init_cmd(init_cmd
);
1045 if (daemonize
&& ret
!= 0)
1046 _exit(EXIT_FAILURE
);
1048 _exit(EXIT_SUCCESS
);
1056 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
1059 current_config
= c
? c
->lxc_conf
: NULL
;
1060 ret
= do_lxcapi_start(c
, useinit
, argv
);
1061 current_config
= NULL
;
1066 * note there MUST be an ending NULL
1068 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1071 char **inargs
= NULL
;
1074 /* container exists */
1078 current_config
= c
->lxc_conf
;
1080 va_start(ap
, useinit
);
1081 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1085 ERROR("Memory allocation error.");
1089 /* pass NULL if no arguments were supplied */
1090 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1095 for (arg
= inargs
; *arg
; arg
++)
1100 current_config
= NULL
;
1104 static bool do_lxcapi_stop(struct lxc_container
*c
)
1111 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1116 WRAP_API(bool, lxcapi_stop
)
1118 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1120 int ret
= -1, lasterr
;
1121 char *p
= alloca(strlen(path
)+1);
1122 mode_t mask
= umask(0002);
1123 ret
= mkdir(path
, 0770);
1128 if (errno
== EEXIST
)
1131 SYSERROR("failed to create container path %s", path
);
1136 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
1137 ERROR("Failed to chown container dir");
1144 * create the standard expected container dir
1146 static bool create_container_dir(struct lxc_container
*c
)
1151 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1155 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1156 if (ret
< 0 || ret
>= len
) {
1160 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1165 /* do_storage_create: thin wrapper around storage_create(). Like
1166 * storage_create(), it returns a mounted bdev on success, NULL on error.
1168 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1170 struct bdev_specs
*specs
)
1175 struct lxc_storage
*bdev
;
1177 /* rootfs.path or lxcpath/lxcname/rootfs */
1178 if (c
->lxc_conf
->rootfs
.path
&&
1179 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1180 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1181 len
= strlen(rpath
) + 1;
1183 ret
= snprintf(dest
, len
, "%s", rpath
);
1185 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1186 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1188 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1190 if (ret
< 0 || (size_t)ret
>= len
)
1193 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1195 ERROR("Failed to create \"%s\" storage", type
);
1199 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1200 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1204 /* If we are not root, chown the rootfs dir to root in the target user
1208 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1209 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1211 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1212 suggest_default_idmap();
1221 static char *lxcbasename(char *path
)
1225 p
= path
+ strlen(path
) - 1;
1226 while (*p
!= '/' && p
> path
)
1232 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1233 bool need_null_stdfds
, char *const argv
[])
1243 SYSERROR("Failed to fork task for container creation template");
1247 if (pid
== 0) { /* child */
1249 char *namearg
, *patharg
, *rootfsarg
;
1252 struct lxc_storage
*bdev
= NULL
;
1253 struct lxc_conf
*conf
= c
->lxc_conf
;
1256 if (need_null_stdfds
) {
1257 ret
= null_stdfds();
1259 _exit(EXIT_FAILURE
);
1262 bdev
= storage_init(c
->lxc_conf
);
1264 ERROR("Failed to initialize storage");
1265 _exit(EXIT_FAILURE
);
1270 ret
= unshare(CLONE_NEWNS
);
1272 ERROR("Failed to unshare CLONE_NEWNS");
1273 _exit(EXIT_FAILURE
);
1276 ret
= detect_shared_rootfs();
1278 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1280 SYSERROR("Failed to make \"/\" rslave");
1281 ERROR("Continuing...");
1286 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1288 ERROR("Unprivileged users can only create "
1289 "btrfs and directory-backed containers");
1290 _exit(EXIT_FAILURE
);
1293 if (strcmp(bdev
->type
, "overlay") == 0 ||
1294 strcmp(bdev
->type
, "overlayfs") == 0) {
1295 /* If we create an overlay container we need to
1296 * rsync the contents into
1297 * <container-path>/<container-name>/rootfs.
1298 * However, the overlay mount function will
1300 * <container-path>/<container-name>/delta0
1302 * <container-path>/<container-name>/rootfs
1303 * which means we would rsync the rootfs into
1304 * the delta directory. That doesn't make sense
1305 * since the delta directory only exists to
1306 * record the differences to
1307 * <container-path>/<container-name>/rootfs. So
1308 * let's simply bind-mount here and then rsync
1310 * <container-path>/<container-name>/rootfs.
1314 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1316 ERROR("Failed to get rootfs");
1317 _exit(EXIT_FAILURE
);
1320 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1322 ERROR("Failed to mount rootfs");
1326 ret
= bdev
->ops
->mount(bdev
);
1328 ERROR("Failed to mount rootfs");
1329 _exit(EXIT_FAILURE
);
1332 } else { /* TODO come up with a better way here! */
1335 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1336 bdev
->dest
= strdup(src
);
1339 /* Create our new array, pre-pend the template name and base
1343 for (nargs
= 0; argv
[nargs
]; nargs
++) {
1346 /* template, path, rootfs and name args */
1349 newargv
= malloc(nargs
* sizeof(*newargv
));
1351 _exit(EXIT_FAILURE
);
1352 newargv
[0] = lxcbasename(tpath
);
1355 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1356 patharg
= malloc(len
);
1358 _exit(EXIT_FAILURE
);
1359 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1360 if (ret
< 0 || ret
>= len
)
1361 _exit(EXIT_FAILURE
);
1362 newargv
[1] = patharg
;
1365 len
= strlen("--name=") + strlen(c
->name
) + 1;
1366 namearg
= malloc(len
);
1368 _exit(EXIT_FAILURE
);
1369 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1370 if (ret
< 0 || ret
>= len
)
1371 _exit(EXIT_FAILURE
);
1372 newargv
[2] = namearg
;
1375 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1376 rootfsarg
= malloc(len
);
1378 _exit(EXIT_FAILURE
);
1379 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1380 if (ret
< 0 || ret
>= len
)
1381 _exit(EXIT_FAILURE
);
1382 newargv
[3] = rootfsarg
;
1384 /* add passed-in args */
1386 for (i
= 4; i
< nargs
; i
++)
1387 newargv
[i
] = argv
[i
- 4];
1389 /* add trailing NULL */
1391 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1393 _exit(EXIT_FAILURE
);
1394 newargv
[nargs
- 1] = NULL
;
1396 /* If we're running the template in a mapped userns, then we
1397 * prepend the template command with: lxc-usernsexec <-m map1>
1398 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1399 * the mapped uid for our geteuid()
1401 if (!lxc_list_empty(&conf
->id_map
)) {
1402 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1404 char txtuid
[20], txtgid
[20];
1405 struct lxc_list
*it
;
1409 n2
= malloc(n2args
* sizeof(*n2
));
1411 _exit(EXIT_FAILURE
);
1414 tpath
= "lxc-usernsexec";
1415 n2
[0] = "lxc-usernsexec";
1416 lxc_list_for_each(it
, &conf
->id_map
) {
1419 n2
= realloc(n2
, n2args
* sizeof(char *));
1421 _exit(EXIT_FAILURE
);
1423 n2
[n2args
- 2] = "-m";
1424 n2
[n2args
- 1] = malloc(200);
1425 if (!n2
[n2args
- 1])
1426 _exit(EXIT_FAILURE
);
1428 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1429 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1430 map
->nsid
, map
->hostid
, map
->range
);
1431 if (ret
< 0 || ret
>= 200)
1432 _exit(EXIT_FAILURE
);
1435 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1436 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1437 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1439 _exit(EXIT_FAILURE
);
1441 if (hostuid_mapped
< 0) {
1442 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1443 n2
[n2args
++] = "-m";
1444 if (hostuid_mapped
< 0) {
1445 ERROR("Failed to find free uid to map");
1446 _exit(EXIT_FAILURE
);
1449 n2
[n2args
++] = malloc(200);
1450 if (!n2
[n2args
- 1]) {
1451 SYSERROR("out of memory");
1452 _exit(EXIT_FAILURE
);
1454 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1455 hostuid_mapped
, geteuid());
1456 if (ret
< 0 || ret
>= 200)
1457 _exit(EXIT_FAILURE
);
1460 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1461 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1462 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1464 _exit(EXIT_FAILURE
);
1466 if (hostgid_mapped
< 0) {
1467 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1468 n2
[n2args
++] = "-m";
1469 if (hostgid_mapped
< 0) {
1470 ERROR("Failed to find free gid to map");
1471 _exit(EXIT_FAILURE
);
1474 n2
[n2args
++] = malloc(200);
1475 if (!n2
[n2args
- 1]) {
1476 SYSERROR("out of memory");
1477 _exit(EXIT_FAILURE
);
1480 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1481 hostgid_mapped
, getegid());
1482 if (ret
< 0 || ret
>= 200)
1483 _exit(EXIT_FAILURE
);
1485 n2
[n2args
++] = "--";
1486 for (i
= 0; i
< nargs
; i
++)
1487 n2
[i
+ n2args
] = newargv
[i
];
1490 /* Finally add "--mapped-uid $uid" to tell template what
1491 * to chown cached images to.
1494 n2
= realloc(n2
, n2args
* sizeof(char *));
1496 _exit(EXIT_FAILURE
);
1498 /* note n2[n2args-1] is NULL */
1499 n2
[n2args
- 5] = "--mapped-uid";
1500 snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1501 n2
[n2args
- 4] = txtuid
;
1502 n2
[n2args
- 3] = "--mapped-gid";
1503 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1504 n2
[n2args
- 2] = txtgid
;
1505 n2
[n2args
- 1] = NULL
;
1510 execvp(tpath
, newargv
);
1511 SYSERROR("Failed to execute template %s", tpath
);
1512 _exit(EXIT_FAILURE
);
1515 ret
= wait_for_pid(pid
);
1517 ERROR("Failed to create container from template");
1524 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1532 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1536 f
= fopen(path
, "r");
1540 if (fseek(f
, 0, SEEK_END
) < 0)
1542 if ((flen
= ftell(f
)) < 0)
1544 if (fseek(f
, 0, SEEK_SET
) < 0)
1546 if ((contents
= malloc(flen
+ 1)) == NULL
)
1548 if (fread(contents
, 1, flen
, f
) != flen
)
1549 goto out_free_contents
;
1551 contents
[flen
] = '\0';
1555 goto out_free_contents
;
1558 tpath
= get_template_path(t
);
1560 ERROR("bad template: %s", t
);
1561 goto out_free_contents
;
1564 ret
= sha1sum_file(tpath
, md_value
);
1566 ERROR("Error getting sha1sum of %s", tpath
);
1568 goto out_free_contents
;
1573 f
= fopen(path
, "w");
1575 SYSERROR("reopening config for writing");
1579 fprintf(f
, "# Template used to create this container: %s\n", t
);
1581 fprintf(f
, "# Parameters passed to the template:");
1583 fprintf(f
, " %s", *argv
);
1589 fprintf(f
, "# Template script checksum (SHA-1): ");
1590 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1591 fprintf(f
, "%02x", md_value
[i
]);
1594 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1595 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1596 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1597 fprintf(f
, "# (Be aware this has security implications)\n\n");
1598 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1599 SYSERROR("Writing original contents");
1615 SYSERROR("Error prepending header");
1621 static void lxcapi_clear_config(struct lxc_container
*c
)
1625 lxc_conf_free(c
->lxc_conf
);
1631 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1635 * create a container with the given parameters.
1636 * @c: container to be created. It has the lxcpath, name, and a starting
1637 * configuration already set
1638 * @t: the template to execute to instantiate the root filesystem and
1639 * adjust the configuration.
1640 * @bdevtype: backing store type to use. If NULL, dir will be used.
1641 * @specs: additional parameters for the backing store, i.e. LVM vg to
1644 * @argv: the arguments to pass to the template, terminated by NULL. If no
1645 * arguments, you can just pass NULL.
1647 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1648 const char *bdevtype
, struct bdev_specs
*specs
,
1649 int flags
, char *const argv
[])
1660 tpath
= get_template_path(t
);
1662 ERROR("Unknown template \"%s\"", t
);
1667 /* If a template is passed in, and the rootfs already is defined in the
1668 * container config and exists, then the caller is trying to create an
1669 * existing container. Return an error, but do NOT delete the container.
1671 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1672 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1673 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1679 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1680 ERROR("Error loading default configuration file %s",
1681 lxc_global_config_value("lxc.default_config"));
1686 if (!create_container_dir(c
))
1689 /* If both template and rootfs.path are set, template is setup as
1690 * rootfs.path. The container is already created if we have a config and
1691 * rootfs.path is accessible
1693 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1694 /* No template passed in and rootfs does not exist. */
1695 if (!c
->save_config(c
, NULL
)) {
1696 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1703 /* Rootfs passed into configuration, but does not exist. */
1704 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1707 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1708 /* Rootfs already existed, user just wanted to save the loaded
1711 if (!c
->save_config(c
, NULL
))
1712 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1717 /* Mark that this container is being created */
1718 partial_fd
= create_partial(c
);
1722 /* No need to get disk lock bc we have the partial lock. */
1724 /* Create the storage.
1725 * Note we can't do this in the same task as we use to execute the
1726 * template because of the way zfs works.
1727 * After you 'zfs create', zfs mounts the fs only in the initial
1732 SYSERROR("Failed to fork task for container creation template");
1736 if (pid
== 0) { /* child */
1737 struct lxc_storage
*bdev
= NULL
;
1739 bdev
= do_storage_create(c
, bdevtype
, specs
);
1741 ERROR("Failed to create %s storage for %s",
1742 bdevtype
? bdevtype
: "(none)", c
->name
);
1743 _exit(EXIT_FAILURE
);
1746 /* Save config file again to store the new rootfs location. */
1747 if (!do_lxcapi_save_config(c
, NULL
)) {
1748 ERROR("Failed to save initial config for %s", c
->name
);
1749 /* Parent task won't see the storage driver in the
1750 * config so we delete it.
1752 bdev
->ops
->umount(bdev
);
1753 bdev
->ops
->destroy(bdev
);
1754 _exit(EXIT_FAILURE
);
1756 _exit(EXIT_SUCCESS
);
1758 if (wait_for_pid(pid
) != 0)
1761 /* Reload config to get the rootfs. */
1762 lxc_conf_free(c
->lxc_conf
);
1764 if (!load_config_locked(c
, c
->configfile
))
1767 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1770 /* Now clear out the lxc_conf we have, reload from the created
1773 do_lxcapi_clear_config(c
);
1776 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1777 ERROR("Failed to prepend header to config file");
1781 ret
= load_config_locked(c
, c
->configfile
);
1784 if (partial_fd
>= 0)
1785 remove_partial(c
, partial_fd
);
1788 container_destroy(c
, NULL
);
1794 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1795 const char *bdevtype
, struct bdev_specs
*specs
,
1796 int flags
, char *const argv
[])
1799 current_config
= c
? c
->lxc_conf
: NULL
;
1800 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1801 current_config
= NULL
;
1805 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1808 int rebootsignal
= SIGINT
;
1812 if (!do_lxcapi_is_running(c
))
1814 pid
= do_lxcapi_init_pid(c
);
1817 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1818 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1819 if (kill(pid
, rebootsignal
) < 0) {
1820 WARN("Could not send signal %d to pid %d.", rebootsignal
, pid
);
1827 WRAP_API(bool, lxcapi_reboot
)
1829 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1833 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1834 lxc_state_t states
[MAX_STATE
] = {0};
1839 if (!do_lxcapi_is_running(c
))
1842 pid
= do_lxcapi_init_pid(c
);
1846 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1847 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1849 /* Add a new state client before sending the shutdown signal so that we
1850 * don't miss a state.
1853 states
[RUNNING
] = 2;
1854 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1859 if (state_client_fd
< 0)
1865 if (ret
< MAX_STATE
)
1869 /* Send reboot signal to container. */
1870 killret
= kill(pid
, rebootsignal
);
1872 WARN("Could not send signal %d to pid %d", rebootsignal
, pid
);
1873 if (state_client_fd
>= 0)
1874 close(state_client_fd
);
1877 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
1882 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
1883 close(state_client_fd
);
1887 TRACE("Received state \"%s\"", lxc_state2str(ret
));
1894 WRAP_API_1(bool, lxcapi_reboot2
, int)
1896 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1900 int haltsignal
= SIGPWR
, state_client_fd
= -1;
1901 lxc_state_t states
[MAX_STATE
] = {0};
1906 if (!do_lxcapi_is_running(c
))
1909 pid
= do_lxcapi_init_pid(c
);
1913 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
1914 if (task_blocking_signal(pid
, (SIGRTMIN
+ 3)))
1915 haltsignal
= (SIGRTMIN
+ 3);
1917 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1918 haltsignal
= c
->lxc_conf
->haltsignal
;
1920 /* Add a new state client before sending the shutdown signal so that we
1921 * don't miss a state.
1924 states
[STOPPED
] = 1;
1925 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1930 if (state_client_fd
< 0)
1936 if (ret
< MAX_STATE
)
1940 /* Send shutdown signal to container. */
1941 killret
= kill(pid
, haltsignal
);
1943 WARN("Could not send signal %d to pid %d", haltsignal
, pid
);
1944 if (state_client_fd
>= 0)
1945 close(state_client_fd
);
1948 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
1953 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
1954 close(state_client_fd
);
1958 TRACE("Received state \"%s\"", lxc_state2str(ret
));
1965 WRAP_API_1(bool, lxcapi_shutdown
, int)
1967 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1968 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1977 current_config
= c
->lxc_conf
;
1980 * since we're going to wait for create to finish, I don't think we
1981 * need to get a copy of the arguments.
1983 va_start(ap
, flags
);
1984 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1987 ERROR("Failed to allocate memory");
1991 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
1995 current_config
= NULL
;
1999 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2001 if (!strcmp(key
, "lxc.cgroup"))
2002 return clear_unexp_config_line(conf
, key
, true);
2004 if (!strcmp(key
, "lxc.network"))
2005 return clear_unexp_config_line(conf
, key
, true);
2007 if (!strcmp(key
, "lxc.net"))
2008 return clear_unexp_config_line(conf
, key
, true);
2010 /* Clear a network with a specific index. */
2011 if (!strncmp(key
, "lxc.net.", 8)) {
2016 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2018 return clear_unexp_config_line(conf
, key
, true);
2021 if (!strcmp(key
, "lxc.hook"))
2022 return clear_unexp_config_line(conf
, key
, true);
2024 return clear_unexp_config_line(conf
, key
, false);
2027 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2031 struct lxc_config_t
*config
;
2033 if (!c
|| !c
->lxc_conf
)
2036 if (container_mem_lock(c
))
2039 config
= lxc_get_config(key
);
2040 /* Verify that the config key exists and that it has a callback
2043 if (config
&& config
->clr
)
2044 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2046 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2048 container_mem_unlock(c
);
2052 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2054 static inline bool enter_net_ns(struct lxc_container
*c
)
2056 pid_t pid
= do_lxcapi_init_pid(c
);
2058 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
2059 if (!switch_to_ns(pid
, "user"))
2062 return switch_to_ns(pid
, "net");
2065 /* Used by qsort and bsearch functions for comparing names. */
2066 static inline int string_cmp(char **first
, char **second
)
2068 return strcmp(*first
, *second
);
2071 /* Used by qsort and bsearch functions for comparing container names. */
2072 static inline int container_cmp(struct lxc_container
**first
,
2073 struct lxc_container
**second
)
2075 return strcmp((*first
)->name
, (*second
)->name
);
2078 static bool add_to_array(char ***names
, char *cname
, int pos
)
2080 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2082 ERROR("Out of memory");
2087 newnames
[pos
] = strdup(cname
);
2091 /* Sort the arrray as we will use binary search on it. */
2092 qsort(newnames
, pos
+ 1, sizeof(char *),
2093 (int (*)(const void *, const void *))string_cmp
);
2098 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2101 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2103 ERROR("Out of memory");
2110 /* Sort the arrray as we will use binary search on it. */
2112 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2113 (int (*)(const void *, const void *))container_cmp
);
2118 static char** get_from_array(char ***names
, char *cname
, int size
)
2120 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2124 static bool array_contains(char ***names
, char *cname
, int size
) {
2125 if(get_from_array(names
, cname
, size
) != NULL
)
2130 static bool remove_from_array(char ***names
, char *cname
, int size
)
2132 char **result
= get_from_array(names
, cname
, size
);
2133 if (result
!= NULL
) {
2140 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2143 int i
, count
= 0, pipefd
[2];
2144 char **interfaces
= NULL
;
2145 char interface
[IFNAMSIZ
];
2147 if(pipe(pipefd
) < 0) {
2148 SYSERROR("pipe failed");
2154 SYSERROR("failed to fork task to get interfaces information");
2160 if (pid
== 0) { /* child */
2161 int ret
= 1, nbytes
;
2162 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2164 /* close the read-end of the pipe */
2167 if (!enter_net_ns(c
)) {
2168 SYSERROR("failed to enter namespace");
2172 /* Grab the list of interfaces */
2173 if (getifaddrs(&interfaceArray
)) {
2174 SYSERROR("failed to get interfaces list");
2178 /* Iterate through the interfaces */
2179 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2180 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2182 ERROR("write failed");
2191 freeifaddrs(interfaceArray
);
2193 /* close the write-end of the pipe, thus sending EOF to the reader */
2198 /* close the write-end of the pipe */
2201 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2202 interface
[IFNAMSIZ
- 1] = '\0';
2204 if (array_contains(&interfaces
, interface
, count
))
2207 if(!add_to_array(&interfaces
, interface
, count
))
2208 ERROR("Failed to add \"%s\" to array", interface
);
2213 if (wait_for_pid(pid
) != 0) {
2214 for(i
=0;i
<count
;i
++)
2215 free(interfaces
[i
]);
2220 /* close the read-end of the pipe */
2223 /* Append NULL to the array */
2225 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2230 WRAP_API(char **, lxcapi_get_interfaces
)
2232 static char** do_lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
2235 int i
, count
= 0, pipefd
[2];
2236 char **addresses
= NULL
;
2237 char address
[INET6_ADDRSTRLEN
];
2239 if(pipe(pipefd
) < 0) {
2240 SYSERROR("pipe failed");
2246 SYSERROR("failed to fork task to get container ips");
2252 if (pid
== 0) { /* child */
2253 int ret
= 1, nbytes
;
2254 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2255 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2256 void *tempAddrPtr
= NULL
;
2257 char *address
= NULL
;
2259 /* close the read-end of the pipe */
2262 if (!enter_net_ns(c
)) {
2263 SYSERROR("failed to enter namespace");
2267 /* Grab the list of interfaces */
2268 if (getifaddrs(&interfaceArray
)) {
2269 SYSERROR("failed to get interfaces list");
2273 /* Iterate through the interfaces */
2274 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2275 if (tempIfAddr
->ifa_addr
== NULL
)
2278 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2279 if (family
&& strcmp(family
, "inet"))
2281 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2284 if (family
&& strcmp(family
, "inet6"))
2287 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2290 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2293 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2295 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2298 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2300 addressOutputBuffer
,
2301 sizeof(addressOutputBuffer
));
2305 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2307 ERROR("write failed");
2316 freeifaddrs(interfaceArray
);
2318 /* close the write-end of the pipe, thus sending EOF to the reader */
2323 /* close the write-end of the pipe */
2326 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2327 if(!add_to_array(&addresses
, address
, count
))
2328 ERROR("PARENT: add_to_array failed");
2332 if (wait_for_pid(pid
) != 0) {
2333 for(i
=0;i
<count
;i
++)
2339 /* close the read-end of the pipe */
2342 /* Append NULL to the array */
2344 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2349 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2351 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2354 struct lxc_config_t
*config
;
2356 if (!c
|| !c
->lxc_conf
)
2359 if (container_mem_lock(c
))
2362 config
= lxc_get_config(key
);
2363 /* Verify that the config key exists and that it has a callback
2366 if (config
&& config
->get
)
2367 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2369 container_mem_unlock(c
);
2373 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2375 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2379 if (!c
|| !c
->lxc_conf
)
2381 if (container_mem_lock(c
))
2383 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2384 container_mem_unlock(c
);
2388 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2390 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2394 /* List all config items. */
2396 return lxc_list_config_items(retv
, inlen
);
2398 if (!c
|| !c
->lxc_conf
)
2401 if (container_mem_lock(c
))
2404 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2405 * This is an intelligent result to show which keys are valid given the
2406 * type of nic it is.
2408 if (strncmp(key
, "lxc.net.", 8) == 0)
2409 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2411 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2413 container_mem_unlock(c
);
2417 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2419 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2422 bool ret
= false, need_disklock
= false;
2426 alt_file
= c
->configfile
;
2430 /* If we haven't yet loaded a config, load the stock config. */
2432 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2433 ERROR("Error loading default configuration file %s while saving %s", lxc_global_config_value("lxc.default_config"), c
->name
);
2438 if (!create_container_dir(c
))
2441 /* If we're writing to the container's config file, take the disk lock.
2442 * Otherwise just take the memlock to protect the struct lxc_container
2443 * while we're traversing it.
2445 if (strcmp(c
->configfile
, alt_file
) == 0)
2446 need_disklock
= true;
2449 lret
= container_disk_lock(c
);
2451 lret
= container_mem_lock(c
);
2456 fout
= fopen(alt_file
, "w");
2459 write_config(fout
, c
->lxc_conf
);
2465 container_disk_unlock(c
);
2467 container_mem_unlock(c
);
2471 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2474 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2480 char path
[MAXPATHLEN
];
2481 char newpath
[MAXPATHLEN
];
2482 int fd
, ret
, n
= 0, v
= 0;
2484 size_t len
= 0, bytes
= 0;
2486 if (container_disk_lock(c0
))
2489 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2490 if (ret
< 0 || ret
> MAXPATHLEN
)
2492 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2493 if (ret
< 0 || ret
> MAXPATHLEN
)
2496 /* If we find an lxc-snapshot file using the old format only listing the
2497 * number of snapshots we will keep using it. */
2498 f1
= fopen(path
, "r");
2500 n
= fscanf(f1
, "%d", &v
);
2502 if (n
== 1 && v
== 0) {
2509 f1
= fopen(path
, "w");
2512 if (fprintf(f1
, "%d\n", v
) < 0) {
2513 ERROR("Error writing new snapshots value");
2519 SYSERROR("Error writing to or closing snapshots file");
2523 /* Here we know that we have or can use an lxc-snapshot file
2524 * using the new format. */
2526 f1
= fopen(path
, "a");
2530 if (fprintf(f1
, "%s", newpath
) < 0) {
2531 ERROR("Error writing new snapshots entry");
2534 SYSERROR("Error writing to or closing snapshots file");
2540 SYSERROR("Error writing to or closing snapshots file");
2544 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2547 if (fstat(fd
, &fbuf
) < 0) {
2552 if (fbuf
.st_size
!= 0) {
2554 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2555 if (buf
== MAP_FAILED
) {
2556 SYSERROR("Failed to create mapping %s", path
);
2561 len
= strlen(newpath
);
2562 while ((del
= strstr((char *)buf
, newpath
))) {
2563 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2567 lxc_strmunmap(buf
, fbuf
.st_size
);
2568 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2569 SYSERROR("Failed to truncate file %s", path
);
2577 /* If the lxc-snapshot file is empty, remove it. */
2578 if (stat(path
, &fbuf
) < 0)
2580 if (!fbuf
.st_size
) {
2588 container_disk_unlock(c0
);
2592 static void strip_newline(char *p
)
2594 size_t len
= strlen(p
);
2597 if (p
[len
-1] == '\n')
2601 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2603 struct lxc_container
*p
;
2604 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2605 size_t pathlen
= 0, namelen
= 0;
2609 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2610 c
->config_path
, c
->name
);
2611 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2612 ERROR("Path name too long");
2615 f
= fopen(path
, "r");
2618 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2619 if (getline(&lxcname
, &namelen
, f
) == -1) {
2620 ERROR("badly formatted file %s", path
);
2623 strip_newline(lxcpath
);
2624 strip_newline(lxcname
);
2625 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2626 ERROR("Unable to find dependent container %s:%s",
2630 if (!mod_rdep(p
, c
, inc
))
2631 ERROR("Failed to update snapshots file for %s:%s",
2633 lxc_container_put(p
);
2641 static bool has_fs_snapshots(struct lxc_container
*c
)
2644 char path
[MAXPATHLEN
];
2649 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2651 if (ret
< 0 || ret
> MAXPATHLEN
)
2653 /* If the file doesn't exist there are no snapshots. */
2654 if (stat(path
, &fbuf
) < 0)
2658 f
= fopen(path
, "r");
2661 ret
= fscanf(f
, "%d", &v
);
2663 /* TODO: Figure out what to do with the return value of fscanf. */
2665 INFO("Container uses new lxc-snapshots format %s", path
);
2673 static bool has_snapshots(struct lxc_container
*c
)
2675 char path
[MAXPATHLEN
];
2676 struct dirent
*direntp
;
2680 if (!get_snappath_dir(c
, path
))
2682 dir
= opendir(path
);
2685 while ((direntp
= readdir(dir
))) {
2689 if (!strcmp(direntp
->d_name
, "."))
2692 if (!strcmp(direntp
->d_name
, ".."))
2701 static bool do_destroy_container(struct lxc_conf
*conf
) {
2704 if (am_guest_unpriv()) {
2705 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2706 "storage_destroy_wrapper");
2713 return storage_destroy(conf
);
2716 static int lxc_rmdir_onedev_wrapper(void *data
)
2718 char *arg
= (char *) data
;
2719 return lxc_rmdir_onedev(arg
, "snaps");
2722 static int lxc_unlink_exec_wrapper(void *data
)
2728 static bool container_destroy(struct lxc_container
*c
,
2729 struct lxc_storage
*storage
)
2733 struct lxc_conf
*conf
;
2738 if (!c
|| !do_lxcapi_is_defined(c
))
2742 if (container_disk_lock(c
))
2745 if (!is_stopped(c
)) {
2746 /* We should queue some sort of error - in c->error_string? */
2747 ERROR("container %s is not stopped", c
->name
);
2751 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2752 /* Start of environment variable setup for hooks */
2753 if (setenv("LXC_NAME", c
->name
, 1))
2754 SYSERROR("Failed to set environment variable for container name");
2756 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2757 SYSERROR("Failed to set environment variable for config path");
2759 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2760 SYSERROR("Failed to set environment variable for rootfs mount");
2762 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2763 SYSERROR("Failed to set environment variable for rootfs mount");
2765 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2766 SYSERROR("Failed to set environment variable for console path");
2768 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2769 SYSERROR("Failed to set environment variable for console log");
2770 /* End of environment variable setup for hooks */
2772 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2773 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2778 if (current_config
&& conf
== current_config
) {
2779 current_config
= NULL
;
2780 if (conf
->logfd
!= -1) {
2786 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2787 if (!do_destroy_container(conf
)) {
2788 ERROR("Error destroying rootfs for %s", c
->name
);
2791 INFO("Destroyed rootfs for %s", c
->name
);
2794 mod_all_rdeps(c
, false);
2796 p1
= do_lxcapi_get_config_path(c
);
2805 * strlen("config") = 6
2809 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
2812 ERROR("Failed to allocate memory");
2816 /* For an overlay container the rootfs is considered immutable and
2817 * cannot be removed when restoring from a snapshot.
2819 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
2820 !strcmp(storage
->type
, "overlayfs")) &&
2821 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
2822 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
2823 if (ret
< 0 || (size_t)ret
>= len
)
2826 if (am_guest_unpriv())
2827 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
2828 "lxc_unlink_exec_wrapper");
2832 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
2836 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
2842 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
2843 if (ret
< 0 || (size_t)ret
>= len
)
2845 if (am_guest_unpriv())
2846 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
2847 "lxc_rmdir_onedev_wrapper");
2849 ret
= lxc_rmdir_onedev(path
, "snaps");
2851 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
2855 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
2862 container_disk_unlock(c
);
2866 static bool do_lxcapi_destroy(struct lxc_container
*c
)
2868 if (!c
|| !lxcapi_is_defined(c
))
2870 if (has_snapshots(c
)) {
2871 ERROR("Container %s has snapshots; not removing", c
->name
);
2875 if (has_fs_snapshots(c
)) {
2876 ERROR("container %s has snapshots on its rootfs", c
->name
);
2880 return container_destroy(c
, NULL
);
2883 WRAP_API(bool, lxcapi_destroy
)
2885 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2887 if (!c
|| !lxcapi_is_defined(c
))
2889 if (!lxcapi_snapshot_destroy_all(c
)) {
2890 ERROR("Error deleting all snapshots");
2893 return lxcapi_destroy(c
);
2896 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
2898 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
2902 struct lxc_config_t
*config
;
2905 config
= lxc_get_config(key
);
2909 ret
= config
->set(key
, v
, conf
, NULL
);
2913 if (lxc_config_value_empty(v
))
2914 do_clear_unexp_config_line(conf
, key
);
2916 bret
= do_append_unexp_config_line(conf
, key
, v
);
2923 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
2929 c
->lxc_conf
= lxc_conf_init();
2934 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
2941 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2948 if (container_mem_lock(c
))
2951 b
= do_set_config_item_locked(c
, key
, v
);
2953 container_mem_unlock(c
);
2957 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
2959 static char *lxcapi_config_file_name(struct lxc_container
*c
)
2961 if (!c
|| !c
->configfile
)
2963 return strdup(c
->configfile
);
2966 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2968 if (!c
|| !c
->config_path
)
2970 return (const char *)(c
->config_path
);
2975 * Just recalculate the c->configfile based on the
2976 * c->config_path, which must be set.
2977 * The lxc_container must be locked or not yet public.
2979 static bool set_config_filename(struct lxc_container
*c
)
2984 if (!c
->config_path
)
2987 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2988 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2989 newpath
= malloc(len
);
2993 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2994 if (ret
< 0 || ret
>= len
) {
2995 fprintf(stderr
, "Error printing out config file name\n");
3000 free(c
->configfile
);
3001 c
->configfile
= newpath
;
3006 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3010 char *oldpath
= NULL
;
3015 if (container_mem_lock(c
))
3020 ERROR("Out of memory setting new lxc path");
3026 oldpath
= c
->config_path
;
3029 /* Since we've changed the config path, we have to change the
3030 * config file name too */
3031 if (!set_config_filename(c
)) {
3032 ERROR("Out of memory setting new config filename");
3034 free(c
->config_path
);
3035 c
->config_path
= oldpath
;
3040 container_mem_unlock(c
);
3044 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3046 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3056 if (container_disk_lock(c
))
3059 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
3061 container_disk_unlock(c
);
3065 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3067 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3077 if (container_disk_lock(c
))
3080 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
3082 container_disk_unlock(c
);
3086 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3088 const char *lxc_get_global_config_item(const char *key
)
3090 return lxc_global_config_value(key
);
3093 const char *lxc_get_version(void)
3098 static int copy_file(const char *old
, const char *new)
3105 if (file_exists(new)) {
3106 ERROR("copy destination %s exists", new);
3109 ret
= stat(old
, &sbuf
);
3111 INFO("Error stat'ing %s", old
);
3115 in
= open(old
, O_RDONLY
);
3117 SYSERROR("Error opening original file %s", old
);
3120 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3122 SYSERROR("Error opening new file %s", new);
3128 len
= read(in
, buf
, 8096);
3130 SYSERROR("Error reading old file %s", old
);
3135 ret
= write(out
, buf
, len
);
3136 if (ret
< len
) { /* should we retry? */
3137 SYSERROR("Error: write to new file %s was interrupted", new);
3144 /* We set mode, but not owner/group. */
3145 ret
= chmod(new, sbuf
.st_mode
);
3147 SYSERROR("Error setting mode on %s", new);
3159 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3162 struct lxc_list
*it
;
3165 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3166 cpath
= alloca(len
);
3167 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3168 if (ret
< 0 || ret
>= len
)
3171 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3172 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3173 char *hookname
= it
->elem
;
3174 char *fname
= strrchr(hookname
, '/');
3175 char tmppath
[MAXPATHLEN
];
3176 if (!fname
) /* relative path - we don't support, but maybe we should */
3178 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3179 /* this hook is public - ignore */
3182 /* copy the script, and change the entry in confile */
3183 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3184 c
->config_path
, c
->name
, fname
+1);
3185 if (ret
< 0 || ret
>= MAXPATHLEN
)
3187 ret
= copy_file(it
->elem
, tmppath
);
3191 it
->elem
= strdup(tmppath
);
3193 ERROR("out of memory copying hook path");
3199 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3200 c
->config_path
, oldc
->name
, c
->name
)) {
3201 ERROR("Error saving new hooks in clone");
3204 do_lxcapi_save_config(c
, NULL
);
3209 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3211 char newpath
[MAXPATHLEN
];
3212 char *oldpath
= oldc
->lxc_conf
->fstab
;
3218 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3220 char *p
= strrchr(oldpath
, '/');
3223 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3224 c
->config_path
, c
->name
, p
);
3225 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3226 ERROR("error printing new path for %s", oldpath
);
3229 if (file_exists(newpath
)) {
3230 ERROR("error: fstab file %s exists", newpath
);
3234 if (copy_file(oldpath
, newpath
) < 0) {
3235 ERROR("error: copying %s to %s", oldpath
, newpath
);
3238 free(c
->lxc_conf
->fstab
);
3239 c
->lxc_conf
->fstab
= strdup(newpath
);
3240 if (!c
->lxc_conf
->fstab
) {
3241 ERROR("error: allocating pathname");
3244 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3245 ERROR("error saving new lxctab");
3252 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3254 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3257 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3259 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3260 WARN("Error copying reverse dependencies");
3263 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3265 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3266 WARN("Error copying reverse dependencies");
3269 if (copy_file(path0
, path1
) < 0) {
3270 INFO("Error copying reverse dependencies");
3275 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3278 char path
[MAXPATHLEN
];
3282 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3284 if (ret
< 0 || ret
>= MAXPATHLEN
)
3286 f
= fopen(path
, "a");
3290 /* If anything goes wrong, just return an error. */
3291 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3299 * If the fs natively supports snapshot clones with no penalty,
3300 * then default to those even if not requested.
3301 * Currently we only do this for btrfs.
3303 bool should_default_to_snapshot(struct lxc_container
*c0
,
3304 struct lxc_container
*c1
)
3306 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3307 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3308 char *p0
= alloca(l0
+ 1);
3309 char *p1
= alloca(l1
+ 1);
3310 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3312 snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3313 snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3315 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3318 if (is_btrfs_subvol(rootfs
) <= 0)
3321 return btrfs_same_fs(p0
, p1
) == 0;
3324 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3325 const char *newtype
, int flags
, const char *bdevdata
,
3328 struct lxc_storage
*bdev
;
3331 if (should_default_to_snapshot(c0
, c
))
3332 flags
|= LXC_CLONE_SNAPSHOT
;
3334 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3335 bdevdata
, newsize
, &need_rdep
);
3337 ERROR("Error copying storage.");
3341 /* Set new rootfs. */
3342 free(c
->lxc_conf
->rootfs
.path
);
3343 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3346 if (!c
->lxc_conf
->rootfs
.path
) {
3347 ERROR("Out of memory while setting storage path.");
3351 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3352 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3353 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3354 c
->lxc_conf
->rootfs
.path
)) {
3355 ERROR("Error saving new rootfs to cloned config.");
3359 if (flags
& LXC_CLONE_SNAPSHOT
)
3360 copy_rdepends(c
, c0
);
3362 if (!add_rdepends(c
, c0
))
3363 WARN("Error adding reverse dependency from %s to %s",
3367 mod_all_rdeps(c
, true);
3372 struct clone_update_data
{
3373 struct lxc_container
*c0
;
3374 struct lxc_container
*c1
;
3379 static int clone_update_rootfs(struct clone_update_data
*data
)
3381 struct lxc_container
*c0
= data
->c0
;
3382 struct lxc_container
*c
= data
->c1
;
3383 int flags
= data
->flags
;
3384 char **hookargs
= data
->hookargs
;
3386 char path
[MAXPATHLEN
];
3387 struct lxc_storage
*bdev
;
3389 struct lxc_conf
*conf
= c
->lxc_conf
;
3391 /* update hostname in rootfs */
3392 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3394 if (setgid(0) < 0) {
3395 ERROR("Failed to setgid to 0");
3398 if (setuid(0) < 0) {
3399 ERROR("Failed to setuid to 0");
3402 if (setgroups(0, NULL
) < 0)
3403 WARN("Failed to clear groups");
3405 if (unshare(CLONE_NEWNS
) < 0)
3407 bdev
= storage_init(c
->lxc_conf
);
3410 if (strcmp(bdev
->type
, "dir") != 0) {
3411 if (unshare(CLONE_NEWNS
) < 0) {
3412 ERROR("error unsharing mounts");
3416 if (detect_shared_rootfs()) {
3417 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3418 SYSERROR("Failed to make / rslave");
3419 ERROR("Continuing...");
3422 if (bdev
->ops
->mount(bdev
) < 0) {
3426 } else { /* TODO come up with a better way */
3428 bdev
->dest
= strdup(bdev
->src
);
3431 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3432 /* Start of environment variable setup for hooks */
3433 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1)) {
3434 SYSERROR("failed to set environment variable for source container name");
3436 if (setenv("LXC_NAME", c
->name
, 1)) {
3437 SYSERROR("failed to set environment variable for container name");
3439 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
3440 SYSERROR("failed to set environment variable for config path");
3442 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
3443 SYSERROR("failed to set environment variable for rootfs mount");
3445 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
3446 SYSERROR("failed to set environment variable for rootfs mount");
3449 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3450 ERROR("Error executing clone hook for %s", c
->name
);
3456 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3457 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3460 if (ret
< 0 || ret
>= MAXPATHLEN
)
3462 if (!file_exists(path
))
3464 if (!(fout
= fopen(path
, "w"))) {
3465 SYSERROR("unable to open %s: ignoring", path
);
3468 if (fprintf(fout
, "%s", c
->name
) < 0) {
3472 if (fclose(fout
) < 0)
3481 static int clone_update_rootfs_wrapper(void *data
)
3483 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3484 return clone_update_rootfs(arg
);
3488 * We want to support:
3489 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3490 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3492 -s [ implies overlay]
3496 only rootfs gets converted (copied/snapshotted) on clone.
3499 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3501 char *p
= strrchr(path
, '/');
3507 ret
= do_create_container_dir(path
, conf
);
3512 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3513 const char *lxcpath
, int flags
,
3514 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3517 char newpath
[MAXPATHLEN
];
3519 struct clone_update_data data
;
3520 size_t saved_unexp_len
;
3523 int storage_copied
= 0;
3524 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3525 struct lxc_container
*c2
= NULL
;
3527 if (!c
|| !do_lxcapi_is_defined(c
))
3530 if (container_mem_lock(c
))
3533 if (!is_stopped(c
)) {
3534 ERROR("error: Original container (%s) is running", c
->name
);
3538 /* Make sure the container doesn't yet exist. */
3542 lxcpath
= do_lxcapi_get_config_path(c
);
3543 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3544 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3545 SYSERROR("clone: failed making config pathname");
3549 if (file_exists(newpath
)) {
3550 ERROR("error: clone: %s exists", newpath
);
3554 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3555 if (ret
< 0 && errno
!= EEXIST
) {
3556 ERROR("Error creating container dir for %s", newpath
);
3560 /* Copy the configuration. Tweak it as needed. */
3561 if (c
->lxc_conf
->rootfs
.path
) {
3562 origroot
= c
->lxc_conf
->rootfs
.path
;
3563 c
->lxc_conf
->rootfs
.path
= NULL
;
3565 fout
= fopen(newpath
, "w");
3567 SYSERROR("open %s", newpath
);
3571 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3572 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3573 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3574 if (!c
->lxc_conf
->unexpanded_config
) {
3575 ERROR("Out of memory");
3580 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3581 write_config(fout
, c
->lxc_conf
);
3583 c
->lxc_conf
->rootfs
.path
= origroot
;
3584 free(c
->lxc_conf
->unexpanded_config
);
3585 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3586 saved_unexp_conf
= NULL
;
3587 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3589 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3590 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3591 SYSERROR("clone: failed making rootfs pathname");
3595 ret
= mkdir(newpath
, 0755);
3597 /* For an overlay container the rootfs is considered immutable
3598 * and will not have been removed when restoring from a
3601 if (errno
!= ENOENT
&&
3602 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3603 SYSERROR("Failed to create directory \"%s\"", newpath
);
3608 if (am_guest_unpriv()) {
3609 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3610 ERROR("Error chowning %s to container root", newpath
);
3615 c2
= lxc_container_new(newname
, lxcpath
);
3617 ERROR("clone: failed to create new container (%s %s)", newname
,
3622 /* copy/snapshot rootfs's */
3623 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3628 /* update utsname */
3629 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3630 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3631 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3633 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3634 ERROR("Error setting new hostname");
3640 ret
= copyhooks(c
, c2
);
3642 ERROR("error copying hooks");
3646 if (copy_fstab(c
, c2
) < 0) {
3647 ERROR("error copying fstab");
3651 /* update macaddrs */
3652 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3653 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3654 ERROR("Error updating mac addresses");
3659 /* Update absolute paths for overlay mount directories. */
3660 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3663 /* We've now successfully created c2's storage, so clear it out if we
3668 if (!c2
->save_config(c2
, NULL
))
3671 if ((pid
= fork()) < 0) {
3676 ret
= wait_for_pid(pid
);
3679 container_mem_unlock(c
);
3685 data
.hookargs
= hookargs
;
3686 if (am_guest_unpriv())
3687 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3688 &data
, "clone_update_rootfs_wrapper");
3690 ret
= clone_update_rootfs(&data
);
3694 container_mem_unlock(c
);
3698 container_mem_unlock(c
);
3700 if (!storage_copied
)
3701 c2
->lxc_conf
->rootfs
.path
= NULL
;
3703 lxc_container_put(c2
);
3709 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3710 const char *lxcpath
, int flags
,
3711 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3714 struct lxc_container
* ret
;
3715 current_config
= c
? c
->lxc_conf
: NULL
;
3716 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3717 current_config
= NULL
;
3721 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3723 struct lxc_storage
*bdev
;
3724 struct lxc_container
*newc
;
3726 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3729 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3730 ERROR("Renaming a container with snapshots is not supported");
3733 bdev
= storage_init(c
->lxc_conf
);
3735 ERROR("Failed to find original backing store type");
3739 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3742 lxc_container_put(newc
);
3746 if (newc
&& lxcapi_is_defined(newc
))
3747 lxc_container_put(newc
);
3749 if (!container_destroy(c
, NULL
)) {
3750 ERROR("Could not destroy existing container %s", c
->name
);
3756 WRAP_API_1(bool, lxcapi_rename
, const char *)
3758 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
)
3765 current_config
= c
->lxc_conf
;
3767 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
3768 current_config
= NULL
;
3772 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3774 lxc_attach_command_t command
;
3781 command
.program
= (char*)program
;
3782 command
.argv
= (char**)argv
;
3783 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
3788 return lxc_wait_for_pid_status(pid
);
3791 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3794 current_config
= c
? c
->lxc_conf
: NULL
;
3795 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
3796 current_config
= NULL
;
3800 static int get_next_index(const char *lxcpath
, char *cname
)
3806 fname
= alloca(strlen(lxcpath
) + 20);
3808 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
3809 ret
= stat(fname
, &sb
);
3816 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
3820 * If the old style snapshot path exists, use it
3821 * /var/lib/lxc -> /var/lib/lxcsnaps
3823 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
3824 if (ret
< 0 || ret
>= MAXPATHLEN
)
3826 if (dir_exists(snappath
)) {
3827 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3828 if (ret
< 0 || ret
>= MAXPATHLEN
)
3834 * Use the new style path
3835 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3837 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
3838 if (ret
< 0 || ret
>= MAXPATHLEN
)
3843 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
3846 struct lxc_container
*c2
;
3847 char snappath
[MAXPATHLEN
], newname
[20];
3849 if (!c
|| !lxcapi_is_defined(c
))
3852 if (!storage_can_backup(c
->lxc_conf
)) {
3853 ERROR("%s's backing store cannot be backed up.", c
->name
);
3854 ERROR("Your container must use another backing store type.");
3858 if (!get_snappath_dir(c
, snappath
))
3861 i
= get_next_index(snappath
, c
->name
);
3863 if (mkdir_p(snappath
, 0755) < 0) {
3864 ERROR("Failed to create snapshot directory %s", snappath
);
3868 ret
= snprintf(newname
, 20, "snap%d", i
);
3869 if (ret
< 0 || ret
>= 20)
3873 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3874 * created in the original container
3876 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
3877 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
3878 if (storage_is_dir(c
->lxc_conf
)) {
3879 ERROR("Snapshot of directory-backed container requested.");
3880 ERROR("Making a copy-clone. If you do want snapshots, then");
3881 ERROR("please create an aufs or overlay clone first, snapshot that");
3882 ERROR("and keep the original container pristine.");
3883 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3885 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
3887 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
3891 lxc_container_put(c2
);
3893 /* Now write down the creation time. */
3900 tm_info
= localtime(&timer
);
3902 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
3904 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
3905 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
3906 f
= fopen(dfnam
, "w");
3908 ERROR("Failed to open %s", dfnam
);
3911 if (fprintf(f
, "%s", buffer
) < 0) {
3912 SYSERROR("Writing timestamp");
3918 SYSERROR("Writing timestamp");
3923 /* $p / $name / comment \0 */
3924 int len
= strlen(snappath
) + strlen(newname
) + 10;
3925 char *path
= alloca(len
);
3926 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3927 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3933 WRAP_API_1(int, lxcapi_snapshot
, const char *)
3935 static void lxcsnap_free(struct lxc_snapshot
*s
)
3938 free(s
->comment_pathname
);
3943 static char *get_snapcomment_path(char* snappath
, char *name
)
3945 /* $snappath/$name/comment */
3946 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3947 char *s
= malloc(len
);
3950 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
3951 if (ret
< 0 || ret
>= len
) {
3959 static char *get_timestamp(char* snappath
, char *name
)
3961 char path
[MAXPATHLEN
], *s
= NULL
;
3965 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
3966 if (ret
< 0 || ret
>= MAXPATHLEN
)
3968 fin
= fopen(path
, "r");
3971 (void) fseek(fin
, 0, SEEK_END
);
3973 (void) fseek(fin
, 0, SEEK_SET
);
3978 if (fread(s
, 1, len
, fin
) != len
) {
3979 SYSERROR("reading timestamp");
3989 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
3991 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
3993 struct dirent
*direntp
;
3994 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
3997 if (!c
|| !lxcapi_is_defined(c
))
4000 if (!get_snappath_dir(c
, snappath
)) {
4001 ERROR("path name too long");
4004 dir
= opendir(snappath
);
4006 INFO("failed to open %s - assuming no snapshots", snappath
);
4010 while ((direntp
= readdir(dir
))) {
4014 if (!strcmp(direntp
->d_name
, "."))
4017 if (!strcmp(direntp
->d_name
, ".."))
4020 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4021 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4022 ERROR("pathname too long");
4025 if (!file_exists(path2
))
4027 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4029 SYSERROR("Out of memory");
4033 snaps
[count
].free
= lxcsnap_free
;
4034 snaps
[count
].name
= strdup(direntp
->d_name
);
4035 if (!snaps
[count
].name
)
4037 snaps
[count
].lxcpath
= strdup(snappath
);
4038 if (!snaps
[count
].lxcpath
) {
4039 free(snaps
[count
].name
);
4042 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4043 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4048 WARN("failed to close directory");
4056 for (i
=0; i
<count
; i
++)
4057 lxcsnap_free(&snaps
[i
]);
4061 WARN("failed to close directory");
4065 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4067 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4069 char clonelxcpath
[MAXPATHLEN
];
4071 struct lxc_container
*snap
, *rest
;
4072 struct lxc_storage
*bdev
;
4075 if (!c
|| !c
->name
|| !c
->config_path
)
4078 if (has_fs_snapshots(c
)) {
4079 ERROR("container rootfs has dependent snapshots");
4083 bdev
= storage_init(c
->lxc_conf
);
4085 ERROR("Failed to find original backing store type");
4089 /* For an overlay container the rootfs is considered immutable
4090 * and cannot be removed when restoring from a snapshot. We pass this
4091 * internal flag along to communicate this to various parts of the
4094 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4095 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4100 if (!get_snappath_dir(c
, clonelxcpath
)) {
4104 /* how should we lock this? */
4106 snap
= lxc_container_new(snapname
, clonelxcpath
);
4107 if (!snap
|| !lxcapi_is_defined(snap
)) {
4108 ERROR("Could not open snapshot %s", snapname
);
4110 lxc_container_put(snap
);
4115 if (!strcmp(c
->name
, newname
)) {
4116 if (!container_destroy(c
, bdev
)) {
4117 ERROR("Could not destroy existing container %s", newname
);
4118 lxc_container_put(snap
);
4124 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4125 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4127 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4128 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4129 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4132 if (rest
&& lxcapi_is_defined(rest
))
4135 lxc_container_put(rest
);
4137 lxc_container_put(snap
);
4141 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4143 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4145 struct lxc_container
*snap
= NULL
;
4148 snap
= lxc_container_new(snapname
, clonelxcpath
);
4150 ERROR("Could not find snapshot %s", snapname
);
4154 if (!do_lxcapi_destroy(snap
)) {
4155 ERROR("Could not destroy snapshot %s", snapname
);
4162 lxc_container_put(snap
);
4166 static bool remove_all_snapshots(const char *path
)
4169 struct dirent
*direntp
;
4172 dir
= opendir(path
);
4174 SYSERROR("opendir on snapshot path %s", path
);
4177 while ((direntp
= readdir(dir
))) {
4178 if (!strcmp(direntp
->d_name
, "."))
4180 if (!strcmp(direntp
->d_name
, ".."))
4182 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4191 SYSERROR("Error removing directory %s", path
);
4196 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4198 char clonelxcpath
[MAXPATHLEN
];
4200 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4203 if (!get_snappath_dir(c
, clonelxcpath
))
4206 return do_snapshot_destroy(snapname
, clonelxcpath
);
4209 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4211 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4213 char clonelxcpath
[MAXPATHLEN
];
4215 if (!c
|| !c
->name
|| !c
->config_path
)
4218 if (!get_snappath_dir(c
, clonelxcpath
))
4221 return remove_all_snapshots(clonelxcpath
);
4224 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4226 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4228 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4231 WRAP_API(bool, lxcapi_may_control
)
4233 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4239 char chrootpath
[MAXPATHLEN
];
4240 char *directory_path
= NULL
;
4244 SYSERROR("Failed to fork()");
4249 ret
= wait_for_pid(pid
);
4251 ERROR("Failed to create device node");
4258 /* prepare the path */
4259 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4260 if (ret
< 0 || ret
>= MAXPATHLEN
)
4263 ret
= chroot(chrootpath
);
4271 /* remove path if it exists */
4272 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4276 ERROR("%s - Failed to remove \"%s\"", strerror(errno
), path
);
4284 /* create any missing directories */
4289 directory_path
= dirname(tmp
);
4290 ret
= mkdir_p(directory_path
, 0755);
4291 if (ret
< 0 && errno
!= EEXIST
) {
4292 ERROR("%s - Failed to create path \"%s\"", strerror(errno
), directory_path
);
4297 /* create the device node */
4298 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4301 ERROR("%s - Failed to create device node at \"%s\"", strerror(errno
), path
);
4308 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4312 char value
[MAX_BUFFER
];
4315 /* make sure container is running */
4316 if (!do_lxcapi_is_running(c
)) {
4317 ERROR("container is not running");
4321 /* use src_path if dest_path is NULL otherwise use dest_path */
4322 p
= dest_path
? dest_path
: src_path
;
4324 /* make sure we can access p */
4325 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4328 /* continue if path is character device or block device */
4329 if (S_ISCHR(st
.st_mode
))
4330 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4331 else if (S_ISBLK(st
.st_mode
))
4332 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4336 /* check snprintf return code */
4337 if (ret
< 0 || ret
>= MAX_BUFFER
)
4340 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4343 /* add or remove device to/from cgroup access list */
4345 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4346 ERROR("set_cgroup_item failed while adding the device node");
4350 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4351 ERROR("set_cgroup_item failed while removing the device node");
4359 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4361 // cannot mknod if we're not privileged wrt init_user_ns
4362 if (am_host_unpriv()) {
4363 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
4366 return add_remove_device_node(c
, src_path
, dest_path
, true);
4369 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4371 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4373 if (am_guest_unpriv()) {
4374 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
4377 return add_remove_device_node(c
, src_path
, dest_path
, false);
4380 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4382 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4384 const char *dst_ifname
)
4389 if (am_guest_unpriv()) {
4390 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
4395 ERROR("No source interface name given");
4399 ret
= lxc_netdev_isup(ifname
);
4401 /* netdev of ifname is up. */
4402 ret
= lxc_netdev_down(ifname
);
4407 init_pid
= do_lxcapi_init_pid(c
);
4408 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4412 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4419 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4421 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4423 const char *dst_ifname
)
4426 pid_t pid
, pid_outside
;
4429 * TODO - if this is a physical device, then we need am_host_unpriv.
4430 * But for other types guest privilege suffices.
4432 if (am_guest_unpriv()) {
4433 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
4438 ERROR("No source interface name given");
4442 pid_outside
= lxc_raw_getpid();
4445 ERROR("Failed to fork");
4449 if (pid
== 0) { /* child */
4452 init_pid
= do_lxcapi_init_pid(c
);
4453 if (!switch_to_ns(init_pid
, "net")) {
4454 ERROR("Failed to enter network namespace");
4458 ret
= lxc_netdev_isup(ifname
);
4460 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4464 /* netdev of ifname is up. */
4466 ret
= lxc_netdev_down(ifname
);
4468 ERROR("Failed to set network device \"%s\" down", ifname
);
4473 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4474 /* -EINVAL means there is no netdev named as ifname. */
4477 ERROR("Network device \"%s\" not found", ifname
);
4479 ERROR("Failed to remove network device \"%s\"", ifname
);
4486 ret
= wait_for_pid(pid
);
4490 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4494 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4496 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4497 struct migrate_opts
*opts
, unsigned int size
)
4500 struct migrate_opts
*valid_opts
= opts
;
4501 uint64_t features_to_check
= 0;
4503 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4504 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4505 * to do anything special.
4507 if (size
> sizeof(*opts
)) {
4508 unsigned char *addr
;
4511 addr
= (void *)opts
+ sizeof(*opts
);
4512 end
= (void *)opts
+ size
;
4513 for (; addr
< end
; addr
++) {
4520 /* If the caller has a smaller struct, let's zero out the end for them
4521 * so we don't accidentally use bits of it that they didn't know about
4524 if (size
< sizeof(*opts
)) {
4525 valid_opts
= malloc(sizeof(*opts
));
4529 memset(valid_opts
, 0, sizeof(*opts
));
4530 memcpy(valid_opts
, opts
, size
);
4534 case MIGRATE_PRE_DUMP
:
4535 if (!do_lxcapi_is_running(c
)) {
4536 ERROR("container is not running");
4539 ret
= !__criu_pre_dump(c
, valid_opts
);
4542 if (!do_lxcapi_is_running(c
)) {
4543 ERROR("container is not running");
4546 ret
= !__criu_dump(c
, valid_opts
);
4548 case MIGRATE_RESTORE
:
4549 if (do_lxcapi_is_running(c
)) {
4550 ERROR("container is already running");
4553 ret
= !__criu_restore(c
, valid_opts
);
4555 case MIGRATE_FEATURE_CHECK
:
4556 features_to_check
= valid_opts
->features_to_check
;
4557 ret
= !__criu_check_feature(&features_to_check
);
4559 /* Something went wrong. Let's let the caller
4560 * know which feature checks failed. */
4561 valid_opts
->features_to_check
= features_to_check
;
4565 ERROR("invalid migrate command %u", cmd
);
4570 if (size
< sizeof(*opts
))
4576 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4578 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4580 struct migrate_opts opts
;
4582 memset(&opts
, 0, sizeof(opts
));
4584 opts
.directory
= directory
;
4586 opts
.verbose
= verbose
;
4588 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4591 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4593 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4595 struct migrate_opts opts
;
4597 memset(&opts
, 0, sizeof(opts
));
4599 opts
.directory
= directory
;
4600 opts
.verbose
= verbose
;
4602 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4605 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4607 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4616 current_config
= c
->lxc_conf
;
4619 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4623 ERROR("Memory allocation error.");
4629 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4632 current_config
= NULL
;
4636 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4638 struct lxc_container
*c
;
4643 c
= malloc(sizeof(*c
));
4645 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4648 memset(c
, 0, sizeof(*c
));
4651 c
->config_path
= strdup(configpath
);
4653 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4655 if (!c
->config_path
) {
4656 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4660 remove_trailing_slashes(c
->config_path
);
4661 c
->name
= malloc(strlen(name
)+1);
4663 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4666 strcpy(c
->name
, name
);
4669 c
->slock
= lxc_newlock(c
->config_path
, name
);
4671 fprintf(stderr
, "Failed to create lock for %s\n", name
);
4675 c
->privlock
= lxc_newlock(NULL
, NULL
);
4677 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
4681 if (!set_config_filename(c
)) {
4682 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
4686 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
4687 fprintf(stderr
, "Failed to load config for %s\n", name
);
4691 if (ongoing_create(c
) == 2) {
4692 ERROR("Failed to complete container creation for %s", c
->name
);
4693 container_destroy(c
, NULL
);
4694 lxcapi_clear_config(c
);
4696 c
->daemonize
= true;
4699 /* Assign the member functions. */
4700 c
->is_defined
= lxcapi_is_defined
;
4701 c
->state
= lxcapi_state
;
4702 c
->is_running
= lxcapi_is_running
;
4703 c
->freeze
= lxcapi_freeze
;
4704 c
->unfreeze
= lxcapi_unfreeze
;
4705 c
->console
= lxcapi_console
;
4706 c
->console_getfd
= lxcapi_console_getfd
;
4707 c
->init_pid
= lxcapi_init_pid
;
4708 c
->load_config
= lxcapi_load_config
;
4709 c
->want_daemonize
= lxcapi_want_daemonize
;
4710 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4711 c
->start
= lxcapi_start
;
4712 c
->startl
= lxcapi_startl
;
4713 c
->stop
= lxcapi_stop
;
4714 c
->config_file_name
= lxcapi_config_file_name
;
4715 c
->wait
= lxcapi_wait
;
4716 c
->set_config_item
= lxcapi_set_config_item
;
4717 c
->destroy
= lxcapi_destroy
;
4718 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4719 c
->rename
= lxcapi_rename
;
4720 c
->save_config
= lxcapi_save_config
;
4721 c
->get_keys
= lxcapi_get_keys
;
4722 c
->create
= lxcapi_create
;
4723 c
->createl
= lxcapi_createl
;
4724 c
->shutdown
= lxcapi_shutdown
;
4725 c
->reboot
= lxcapi_reboot
;
4726 c
->reboot2
= lxcapi_reboot2
;
4727 c
->clear_config
= lxcapi_clear_config
;
4728 c
->clear_config_item
= lxcapi_clear_config_item
;
4729 c
->get_config_item
= lxcapi_get_config_item
;
4730 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4731 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4732 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4733 c
->get_config_path
= lxcapi_get_config_path
;
4734 c
->set_config_path
= lxcapi_set_config_path
;
4735 c
->clone
= lxcapi_clone
;
4736 c
->get_interfaces
= lxcapi_get_interfaces
;
4737 c
->get_ips
= lxcapi_get_ips
;
4738 c
->attach
= lxcapi_attach
;
4739 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4740 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4741 c
->snapshot
= lxcapi_snapshot
;
4742 c
->snapshot_list
= lxcapi_snapshot_list
;
4743 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4744 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4745 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4746 c
->may_control
= lxcapi_may_control
;
4747 c
->add_device_node
= lxcapi_add_device_node
;
4748 c
->remove_device_node
= lxcapi_remove_device_node
;
4749 c
->attach_interface
= lxcapi_attach_interface
;
4750 c
->detach_interface
= lxcapi_detach_interface
;
4751 c
->checkpoint
= lxcapi_checkpoint
;
4752 c
->restore
= lxcapi_restore
;
4753 c
->migrate
= lxcapi_migrate
;
4754 c
->console_log
= lxcapi_console_log
;
4759 lxc_container_free(c
);
4763 int lxc_get_wait_states(const char **states
)
4768 for (i
=0; i
<MAX_STATE
; i
++)
4769 states
[i
] = lxc_state2str(i
);
4774 * These next two could probably be done smarter with reusing a common function
4775 * with different iterators and tests...
4777 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4780 int i
, cfound
= 0, nfound
= 0;
4781 struct dirent
*direntp
;
4782 struct lxc_container
*c
;
4785 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4787 dir
= opendir(lxcpath
);
4789 SYSERROR("opendir on lxcpath");
4798 while ((direntp
= readdir(dir
))) {
4802 /* Ignore '.', '..' and any hidden directory. */
4803 if (!strncmp(direntp
->d_name
, ".", 1))
4806 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4810 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4820 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4822 INFO("Container %s:%s has a config but could not be loaded",
4823 lxcpath
, direntp
->d_name
);
4825 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4829 if (!do_lxcapi_is_defined(c
)) {
4830 INFO("Container %s:%s has a config but is not defined",
4831 lxcpath
, direntp
->d_name
);
4833 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4835 lxc_container_put(c
);
4839 if (!add_to_clist(cret
, c
, nfound
, true)) {
4840 lxc_container_put(c
);
4850 if (names
&& *names
) {
4851 for (i
=0; i
<cfound
; i
++)
4855 if (cret
&& *cret
) {
4856 for (i
=0; i
<nfound
; i
++)
4857 lxc_container_put((*cret
)[i
]);
4864 int list_active_containers(const char *lxcpath
, char ***nret
,
4865 struct lxc_container
***cret
)
4867 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4870 char **ct_name
= NULL
;
4872 struct lxc_container
*c
= NULL
;
4876 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4877 lxcpath_len
= strlen(lxcpath
);
4884 FILE *f
= fopen("/proc/net/unix", "r");
4888 while (getline(&line
, &len
, f
) != -1) {
4890 char *p
= strrchr(line
, ' '), *p2
;
4899 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4901 } else if (strncmp(p
, "lxc/", 4) == 0) {
4911 /* Now p is the start of lxc_name. */
4912 p2
= strchr(p
, '/');
4913 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4918 char *recvpath
= lxc_cmd_get_lxcpath(p
);
4921 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0)
4923 p
= lxc_cmd_get_name(p
);
4928 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4931 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4932 goto free_cret_list
;
4939 c
= lxc_container_new(p
, lxcpath
);
4941 INFO("Container %s:%s is running but could not be loaded",
4943 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4948 * If this is an anonymous container, then is_defined *can*
4949 * return false. So we don't do that check. Count on the
4950 * fact that the command socket exists.
4953 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
4954 lxc_container_put(c
);
4955 goto free_cret_list
;
4960 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
4962 lxc_container_put(c
);
4963 goto free_cret_list
;
4974 if (cret
&& *cret
) {
4975 for (i
= 0; i
< cret_cnt
; i
++)
4976 lxc_container_put((*cret
)[i
]);
4982 for (i
= 0; i
< ct_name_cnt
; i
++)
4994 int list_all_containers(const char *lxcpath
, char ***nret
,
4995 struct lxc_container
***cret
)
4997 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5000 struct lxc_container
**ct_list
= NULL
;
5002 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5006 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5007 if (active_cnt
< 0) {
5012 for (i
= 0; i
< active_cnt
; i
++) {
5013 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5014 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5016 goto free_active_name
;
5020 free(active_name
[i
]);
5021 active_name
[i
] = NULL
;
5027 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5028 struct lxc_container
*c
;
5030 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5032 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5033 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5037 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5038 lxc_container_put(c
);
5057 for (i
= 0; i
< ct_list_cnt
; i
++) {
5058 lxc_container_put(ct_list
[i
]);
5063 for (i
= 0; i
< active_cnt
; i
++) {
5064 free(active_name
[i
]);
5069 for (i
= 0; i
< ct_cnt
; i
++) {
5076 bool lxc_config_item_is_supported(const char *key
)
5078 return !!lxc_get_config(key
);