3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include <arpa/inet.h>
35 #include <sys/mount.h>
36 #include <sys/syscall.h>
37 #include <sys/sysmacros.h>
38 #include <sys/types.h>
46 #include "commands_utils.h"
50 #include "confile_utils.h"
53 #include "initutils.h"
56 #include "lxccontainer.h"
59 #include "namespace.h"
65 #include "storage/btrfs.h"
66 #include "storage/overlay.h"
67 #include "storage_utils.h"
75 #include <sys/mkdev.h>
81 #include <../include/ifaddrs.h>
85 #include <../include/lxcmntent.h>
91 #include "include/strlcpy.h"
94 /* Define faccessat() if missing from the C library */
95 #ifndef HAVE_FACCESSAT
96 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
99 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
107 lxc_log_define(lxc_container
, lxc
);
109 static bool do_lxcapi_destroy(struct lxc_container
*c
);
110 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
111 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
112 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
113 static bool container_destroy(struct lxc_container
*c
,
114 struct lxc_storage
*storage
);
115 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
116 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
117 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
119 static bool config_file_exists(const char *lxcpath
, const char *cname
)
125 /* $lxcpath + '/' + $cname + '/config' + \0 */
126 len
= strlen(lxcpath
) + strlen(cname
) + 9;
128 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
129 if (ret
< 0 || (size_t)ret
>= len
)
132 return file_exists(fname
);
135 /* A few functions to help detect when a container creation failed. If a
136 * container creation was killed partway through, then trying to actually start
137 * that container could harm the host. We detect this by creating a 'partial'
138 * file under the container directory, and keeping an advisory lock. When
139 * container creation completes, we remove that file. When we load or try to
140 * start a container, if we find that file, without a flock, we remove the
143 static int ongoing_create(struct lxc_container
*c
)
148 struct flock lk
= {0};
150 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
152 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
153 if (ret
< 0 || (size_t)ret
>= len
)
156 if (!file_exists(path
))
159 fd
= open(path
, O_RDWR
);
164 lk
.l_whence
= SEEK_SET
;
167 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
168 if (ret
< 0 && errno
== EINVAL
)
169 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
171 if (ret
== 0 && lk
.l_pid
!= -1) {
172 /* create is still ongoing */
176 /* Create completed but partial is still there. */
180 static int create_partial(struct lxc_container
*c
)
185 struct flock lk
= {0};
187 /* $lxcpath + '/' + $name + '/partial' + \0 */
188 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
190 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
191 if (ret
< 0 || (size_t)ret
>= len
)
194 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
199 lk
.l_whence
= SEEK_SET
;
201 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
203 if (errno
== EINVAL
) {
204 ret
= flock(fd
, LOCK_EX
);
209 SYSERROR("Failed to lock partial file %s", path
);
217 static void remove_partial(struct lxc_container
*c
, int fd
)
224 /* $lxcpath + '/' + $name + '/partial' + \0 */
225 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
227 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
228 if (ret
< 0 || (size_t)ret
>= len
)
233 SYSERROR("Failed to remove partial file %s", path
);
237 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
238 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
239 * container configuration file.
240 * The container_disk_lock also takes the container_mem_lock.
241 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
242 * NOTHING mutexes two independent programs with their own struct
243 * lxc_container for the same c->name, between API calls. For instance,
244 * c->config_read(); c->start(); Between those calls, data on disk
245 * could change (which shouldn't bother the caller unless for instance
246 * the rootfs get moved). c->config_read(); update; c->config_write();
247 * Two such updaters could race. The callers should therefore check their
248 * results. Trying to prevent that would necessarily expose us to deadlocks
249 * due to hung callers. So I prefer to keep the locks only within our own
250 * functions, not across functions.
252 * If you're going to clone while holding a lxccontainer, increment
253 * c->numthreads (under privlock) before forking. When deleting,
254 * decrement numthreads under privlock, then if it hits 0 you can delete.
255 * Do not ever use a lxccontainer whose numthreads you did not bump.
258 static void lxc_container_free(struct lxc_container
*c
)
264 c
->configfile
= NULL
;
266 free(c
->error_string
);
267 c
->error_string
= NULL
;
270 lxc_putlock(c
->slock
);
275 lxc_putlock(c
->privlock
);
283 lxc_conf_free(c
->lxc_conf
);
287 free(c
->config_path
);
288 c
->config_path
= NULL
;
293 /* Consider the following case:
295 * |====================================================================|
296 * | freer | racing get()er |
297 * |====================================================================|
298 * | lxc_container_put() | lxc_container_get() |
299 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
300 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
301 * | \ lxcunlock() | \ |
302 * | \ lxc_container_free() | \ lxclock() returns |
303 * | | \ c->numthreads < 1 -> return 0 |
304 * | \ \ (free stuff) | |
305 * | \ \ sem_destroy(privlock) | |
306 * |_______________________________|____________________________________|
308 * When the get()er checks numthreads the first time, one of the following
310 * 1. freer has set numthreads = 0. get() returns 0
311 * 2. freer is between lxclock and setting numthreads to 0. get()er will
312 * sem_wait on privlock, get lxclock after freer() drops it, then see
313 * numthreads is 0 and exit without touching lxclock again..
314 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
315 * will see --numthreads = 1 and not call lxc_container_free().
318 int lxc_container_get(struct lxc_container
*c
)
323 /* If someone else has already started freeing the container, don't try
324 * to take the lock, which may be invalid.
326 if (c
->numthreads
< 1)
329 if (container_mem_lock(c
))
332 /* Bail without trying to unlock, bc the privlock is now probably in
335 if (c
->numthreads
< 1)
339 container_mem_unlock(c
);
344 int lxc_container_put(struct lxc_container
*c
)
349 if (container_mem_lock(c
))
354 if (c
->numthreads
< 1) {
355 container_mem_unlock(c
);
356 lxc_container_free(c
);
360 container_mem_unlock(c
);
365 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
374 if (container_mem_lock(c
))
380 statret
= stat(c
->configfile
, &statbuf
);
387 container_mem_unlock(c
);
392 #define WRAP_API(rettype, fnname) \
393 static rettype fnname(struct lxc_container *c) \
396 bool reset_config = false; \
398 if (!current_config && c && c->lxc_conf) { \
399 current_config = c->lxc_conf; \
400 reset_config = true; \
403 ret = do_##fnname(c); \
405 current_config = NULL; \
410 #define WRAP_API_1(rettype, fnname, t1) \
411 static rettype fnname(struct lxc_container *c, t1 a1) \
414 bool reset_config = false; \
416 if (!current_config && c && c->lxc_conf) { \
417 current_config = c->lxc_conf; \
418 reset_config = true; \
421 ret = do_##fnname(c, a1); \
423 current_config = NULL; \
428 #define WRAP_API_2(rettype, fnname, t1, t2) \
429 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
432 bool reset_config = false; \
434 if (!current_config && c && c->lxc_conf) { \
435 current_config = c->lxc_conf; \
436 reset_config = true; \
439 ret = do_##fnname(c, a1, a2); \
441 current_config = NULL; \
446 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
447 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
450 bool reset_config = false; \
452 if (!current_config && c && c->lxc_conf) { \
453 current_config = c->lxc_conf; \
454 reset_config = true; \
457 ret = do_##fnname(c, a1, a2, a3); \
459 current_config = NULL; \
464 WRAP_API(bool, lxcapi_is_defined
)
466 static const char *do_lxcapi_state(struct lxc_container
*c
)
473 s
= lxc_getstate(c
->name
, c
->config_path
);
474 return lxc_state2str(s
);
477 WRAP_API(const char *, lxcapi_state
)
479 static bool is_stopped(struct lxc_container
*c
)
483 s
= lxc_getstate(c
->name
, c
->config_path
);
484 return (s
== STOPPED
);
487 static bool do_lxcapi_is_running(struct lxc_container
*c
)
492 return !is_stopped(c
);
495 WRAP_API(bool, lxcapi_is_running
)
497 static bool do_lxcapi_freeze(struct lxc_container
*c
)
504 ret
= lxc_freeze(c
->name
, c
->config_path
);
511 WRAP_API(bool, lxcapi_freeze
)
513 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
520 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
527 WRAP_API(bool, lxcapi_unfreeze
)
529 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
534 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
537 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
539 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
540 int stdoutfd
, int stderrfd
, int escape
)
547 current_config
= c
->lxc_conf
;
548 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
549 current_config
= NULL
;
554 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
558 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
561 NOTICE("The console log is empty");
562 else if (ret
== -EFAULT
)
563 NOTICE("The container does not keep a console log");
564 else if (ret
== -ENOENT
)
565 NOTICE("The container does not keep a console log file");
566 else if (ret
== -EIO
)
567 NOTICE("Failed to write console log to log file");
569 ERROR("Failed to retrieve console log");
575 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
577 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
582 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
585 WRAP_API(pid_t
, lxcapi_init_pid
)
587 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
590 c
->lxc_conf
= lxc_conf_init();
595 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
598 c
->lxc_conf
->name
= c
->name
;
603 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
607 bool need_disklock
= false, ret
= false;
612 fname
= c
->configfile
;
618 /* If we're reading something other than the container's config, we only
619 * need to lock the in-memory container. If loading the container's
620 * config file, take the disk lock.
622 if (strcmp(fname
, c
->configfile
) == 0)
623 need_disklock
= true;
626 lret
= container_disk_lock(c
);
628 lret
= container_mem_lock(c
);
632 ret
= load_config_locked(c
, fname
);
635 container_disk_unlock(c
);
637 container_mem_unlock(c
);
642 WRAP_API_1(bool, lxcapi_load_config
, const char *)
644 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
646 if (!c
|| !c
->lxc_conf
)
649 if (container_mem_lock(c
))
652 c
->daemonize
= state
;
654 container_mem_unlock(c
);
659 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
661 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
663 if (!c
|| !c
->lxc_conf
)
666 if (container_mem_lock(c
))
669 c
->lxc_conf
->close_all_fds
= state
;
671 container_mem_unlock(c
);
676 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
678 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
686 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
690 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
692 static bool am_single_threaded(void)
695 struct dirent
*direntp
;
698 dir
= opendir("/proc/self/task");
702 while ((direntp
= readdir(dir
))) {
703 if (strcmp(direntp
->d_name
, ".") == 0)
706 if (strcmp(direntp
->d_name
, "..") == 0)
718 static void push_arg(char ***argp
, char *arg
, int *nargs
)
723 copy
= must_copy_string(arg
);
726 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
735 static char **split_init_cmd(const char *incmd
)
741 char *saveptr
= NULL
;
746 len
= strlen(incmd
) + 1;
748 retlen
= strlcpy(copy
, incmd
, len
);
754 argv
= malloc(sizeof(char *));
758 for (; (p
= strtok_r(copy
, " ", &saveptr
)); copy
= NULL
)
759 push_arg(&argv
, p
, &nargs
);
769 static void free_init_cmd(char **argv
)
782 static int lxc_rcv_status(int state_socket
)
788 /* Receive container state. */
789 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
,
794 TRACE("Caught EINTR; retrying");
801 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
805 /* Close write end of the socket pair. */
806 close(handler
->state_socket_pair
[1]);
807 handler
->state_socket_pair
[1] = -1;
809 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
811 /* Close read end of the socket pair. */
812 close(handler
->state_socket_pair
[0]);
813 handler
->state_socket_pair
[0] = -1;
815 /* The first child is going to fork() again and then exits. So we reap
816 * the first child here.
818 ret
= wait_for_pid(pid
);
820 DEBUG("Failed waiting on first child %d", pid
);
822 DEBUG("First child %d exited", pid
);
825 SYSERROR("Failed to receive the container state");
829 /* If we receive anything else then running we know that the container
832 if (state
!= RUNNING
) {
833 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
834 lxc_state2str(state
));
838 TRACE("Container is in \"RUNNING\" state");
842 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
845 struct lxc_handler
*handler
;
846 struct lxc_conf
*conf
;
847 char *default_args
[] = {
851 char **init_cmd
= NULL
;
852 int keepfds
[3] = {-1, -1, -1};
854 /* container does exist */
858 /* If anything fails before we set error_num, we want an error in there.
862 /* Container has not been setup. */
866 ret
= ongoing_create(c
);
868 ERROR("Failed checking for incomplete container creation");
870 } else if (ret
== 1) {
871 ERROR("Ongoing container creation detected");
873 } else if (ret
== 2) {
874 ERROR("Failed to create container");
875 do_lxcapi_destroy(c
);
879 if (container_mem_lock(c
))
884 /* initialize handler */
885 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
887 container_mem_unlock(c
);
892 if (useinit
&& conf
->execute_cmd
)
893 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
895 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
898 /* ... otherwise use default_args. */
901 ERROR("No valid init detected");
902 lxc_free_handler(handler
);
908 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
909 * here to protect the on disk container? We don't want to exclude
910 * things like lxc_info while the container is running.
919 free_init_cmd(init_cmd
);
920 lxc_free_handler(handler
);
926 /* Set to NULL because we don't want father unlink
927 * the PID file, child will do the free and unlink.
931 /* Wait for container to tell us whether it started
934 started
= wait_on_daemonized_start(handler
, pid
);
936 free_init_cmd(init_cmd
);
937 lxc_free_handler(handler
);
943 /* We don't really care if this doesn't print all the
944 * characters. All that it means is that the proctitle will be
945 * ugly. Similarly, we also don't care if setproctitle() fails.
947 (void)snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
948 INFO("Attempting to set proc title to %s", title
);
949 (void)setproctitle(title
);
951 /* We fork() a second time to be reparented to init. Like
952 * POSIX's daemon() function we change to "/" and redirect
953 * std{in,out,err} to /dev/null.
957 SYSERROR("Failed to fork first child process");
963 free_init_cmd(init_cmd
);
964 lxc_free_handler(handler
);
970 /* change to / directory */
973 SYSERROR("Failed to change to \"/\" directory");
977 keepfds
[0] = handler
->conf
->maincmd_fd
;
978 keepfds
[1] = handler
->state_socket_pair
[0];
979 keepfds
[2] = handler
->state_socket_pair
[1];
980 ret
= lxc_check_inherited(conf
, true, keepfds
,
981 sizeof(keepfds
) / sizeof(keepfds
[0]));
985 /* redirect std{in,out,err} to /dev/null */
988 ERROR("Failed to redirect std{in,out,err} to /dev/null");
992 /* become session leader */
995 TRACE("Process %d is already process group leader", lxc_raw_getpid());
997 if (!am_single_threaded()) {
998 ERROR("Cannot start non-daemonized container when threaded");
999 free_init_cmd(init_cmd
);
1000 lxc_free_handler(handler
);
1005 /* We need to write PID file after daemonize, so we always
1006 * write the right PID.
1010 char pidstr
[LXC_NUMSTRLEN64
];
1012 w
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", (int)lxc_raw_getpid());
1013 if (w
< 0 || (size_t)w
>= LXC_NUMSTRLEN64
) {
1014 free_init_cmd(init_cmd
);
1015 lxc_free_handler(handler
);
1017 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1020 _exit(EXIT_FAILURE
);
1025 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1027 free_init_cmd(init_cmd
);
1028 lxc_free_handler(handler
);
1030 SYSERROR("Failed to write '%s'", c
->pidfile
);
1033 _exit(EXIT_FAILURE
);
1041 /* Unshare the mount namespace if requested */
1042 if (conf
->monitor_unshare
) {
1043 ret
= unshare(CLONE_NEWNS
);
1045 SYSERROR("failed to unshare mount namespace");
1046 lxc_free_handler(handler
);
1051 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1053 SYSERROR("Failed to make / rslave at startup");
1054 lxc_free_handler(handler
);
1061 if (conf
->reboot
== 2) {
1062 /* initialize handler */
1063 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1070 keepfds
[0] = handler
->conf
->maincmd_fd
;
1071 keepfds
[1] = handler
->state_socket_pair
[0];
1072 keepfds
[2] = handler
->state_socket_pair
[1];
1073 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1074 sizeof(keepfds
) / sizeof(keepfds
[0]));
1076 lxc_free_handler(handler
);
1082 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1083 c
->daemonize
, &c
->error_num
);
1085 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1086 c
->daemonize
, &c
->error_num
);
1088 if (conf
->reboot
== 1) {
1089 INFO("Container requested reboot");
1100 free_init_cmd(init_cmd
);
1102 if (c
->daemonize
&& ret
!= 0)
1103 _exit(EXIT_FAILURE
);
1104 else if (c
->daemonize
)
1105 _exit(EXIT_SUCCESS
);
1113 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1118 current_config
= c
? c
->lxc_conf
: NULL
;
1119 ret
= do_lxcapi_start(c
, useinit
, argv
);
1120 current_config
= NULL
;
1125 /* Note, there MUST be an ending NULL. */
1126 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1129 char **inargs
= NULL
;
1132 /* container exists */
1136 current_config
= c
->lxc_conf
;
1138 va_start(ap
, useinit
);
1139 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1144 /* pass NULL if no arguments were supplied */
1145 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1150 for (arg
= inargs
; *arg
; arg
++)
1155 current_config
= NULL
;
1160 static bool do_lxcapi_stop(struct lxc_container
*c
)
1167 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1172 WRAP_API(bool, lxcapi_stop
)
1174 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1181 mode_t mask
= umask(0002);
1182 ret
= mkdir(path
, 0770);
1187 if (errno
!= EEXIST
)
1194 p
= alloca(len
+ 1);
1196 if (!lxc_list_empty(&conf
->id_map
)) {
1197 ret
= chown_mapped_root(p
, conf
);
1205 /* Create the standard expected container dir. */
1206 static bool create_container_dir(struct lxc_container
*c
)
1212 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1217 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1218 if (ret
< 0 || (size_t)ret
>= len
) {
1223 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1229 /* do_storage_create: thin wrapper around storage_create(). Like
1230 * storage_create(), it returns a mounted bdev on success, NULL on error.
1232 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1234 struct bdev_specs
*specs
)
1239 struct lxc_storage
*bdev
;
1241 /* rootfs.path or lxcpath/lxcname/rootfs */
1242 if (c
->lxc_conf
->rootfs
.path
&&
1243 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1244 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1245 len
= strlen(rpath
) + 1;
1247 ret
= snprintf(dest
, len
, "%s", rpath
);
1249 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1250 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1252 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1254 if (ret
< 0 || (size_t)ret
>= len
)
1257 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1259 ERROR("Failed to create \"%s\" storage", type
);
1263 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1264 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1268 /* If we are not root, chown the rootfs dir to root in the target user
1272 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1273 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1275 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1276 suggest_default_idmap();
1285 static char *lxcbasename(char *path
)
1289 p
= path
+ strlen(path
) - 1;
1290 while (*p
!= '/' && p
> path
)
1296 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1297 bool need_null_stdfds
, char *const argv
[])
1307 SYSERROR("Failed to fork task for container creation template");
1311 if (pid
== 0) { /* child */
1313 char *namearg
, *patharg
, *rootfsarg
;
1316 struct lxc_storage
*bdev
= NULL
;
1317 struct lxc_conf
*conf
= c
->lxc_conf
;
1320 if (need_null_stdfds
) {
1321 ret
= null_stdfds();
1323 _exit(EXIT_FAILURE
);
1326 bdev
= storage_init(c
->lxc_conf
);
1328 ERROR("Failed to initialize storage");
1329 _exit(EXIT_FAILURE
);
1334 ret
= unshare(CLONE_NEWNS
);
1336 ERROR("Failed to unshare CLONE_NEWNS");
1337 _exit(EXIT_FAILURE
);
1340 ret
= detect_shared_rootfs();
1342 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1344 SYSERROR("Failed to make \"/\" rslave");
1345 ERROR("Continuing...");
1350 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1352 ERROR("Unprivileged users can only create "
1353 "btrfs and directory-backed containers");
1354 _exit(EXIT_FAILURE
);
1357 if (strcmp(bdev
->type
, "overlay") == 0 ||
1358 strcmp(bdev
->type
, "overlayfs") == 0) {
1359 /* If we create an overlay container we need to
1360 * rsync the contents into
1361 * <container-path>/<container-name>/rootfs.
1362 * However, the overlay mount function will
1364 * <container-path>/<container-name>/delta0
1366 * <container-path>/<container-name>/rootfs
1367 * which means we would rsync the rootfs into
1368 * the delta directory. That doesn't make sense
1369 * since the delta directory only exists to
1370 * record the differences to
1371 * <container-path>/<container-name>/rootfs. So
1372 * let's simply bind-mount here and then rsync
1374 * <container-path>/<container-name>/rootfs.
1378 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1380 ERROR("Failed to get rootfs");
1381 _exit(EXIT_FAILURE
);
1384 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1386 ERROR("Failed to mount rootfs");
1390 ret
= bdev
->ops
->mount(bdev
);
1392 ERROR("Failed to mount rootfs");
1393 _exit(EXIT_FAILURE
);
1396 } else { /* TODO come up with a better way here! */
1399 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1400 bdev
->dest
= strdup(src
);
1403 /* Create our new array, pre-pend the template name and base
1407 for (nargs
= 0; argv
[nargs
]; nargs
++) {
1410 /* template, path, rootfs and name args */
1413 newargv
= malloc(nargs
* sizeof(*newargv
));
1415 _exit(EXIT_FAILURE
);
1416 newargv
[0] = lxcbasename(tpath
);
1419 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1420 patharg
= malloc(len
);
1422 _exit(EXIT_FAILURE
);
1423 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1424 if (ret
< 0 || ret
>= len
)
1425 _exit(EXIT_FAILURE
);
1426 newargv
[1] = patharg
;
1429 len
= strlen("--name=") + strlen(c
->name
) + 1;
1430 namearg
= malloc(len
);
1432 _exit(EXIT_FAILURE
);
1433 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1434 if (ret
< 0 || ret
>= len
)
1435 _exit(EXIT_FAILURE
);
1436 newargv
[2] = namearg
;
1439 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1440 rootfsarg
= malloc(len
);
1442 _exit(EXIT_FAILURE
);
1443 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1444 if (ret
< 0 || ret
>= len
)
1445 _exit(EXIT_FAILURE
);
1446 newargv
[3] = rootfsarg
;
1448 /* add passed-in args */
1450 for (i
= 4; i
< nargs
; i
++)
1451 newargv
[i
] = argv
[i
- 4];
1453 /* add trailing NULL */
1455 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1457 _exit(EXIT_FAILURE
);
1458 newargv
[nargs
- 1] = NULL
;
1460 /* If we're running the template in a mapped userns, then we
1461 * prepend the template command with: lxc-usernsexec <-m map1>
1462 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1463 * the mapped uid for our geteuid()
1465 if (!lxc_list_empty(&conf
->id_map
)) {
1466 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1468 char txtuid
[20], txtgid
[20];
1469 struct lxc_list
*it
;
1473 n2
= malloc(n2args
* sizeof(*n2
));
1475 _exit(EXIT_FAILURE
);
1478 tpath
= "lxc-usernsexec";
1479 n2
[0] = "lxc-usernsexec";
1480 lxc_list_for_each(it
, &conf
->id_map
) {
1483 n2
= realloc(n2
, n2args
* sizeof(char *));
1485 _exit(EXIT_FAILURE
);
1487 n2
[n2args
- 2] = "-m";
1488 n2
[n2args
- 1] = malloc(200);
1489 if (!n2
[n2args
- 1])
1490 _exit(EXIT_FAILURE
);
1492 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1493 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1494 map
->nsid
, map
->hostid
, map
->range
);
1495 if (ret
< 0 || ret
>= 200)
1496 _exit(EXIT_FAILURE
);
1499 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1500 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1501 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1503 _exit(EXIT_FAILURE
);
1505 if (hostuid_mapped
< 0) {
1506 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1507 n2
[n2args
++] = "-m";
1508 if (hostuid_mapped
< 0) {
1509 ERROR("Failed to find free uid to map");
1510 _exit(EXIT_FAILURE
);
1513 n2
[n2args
++] = malloc(200);
1514 if (!n2
[n2args
- 1]) {
1515 SYSERROR("out of memory");
1516 _exit(EXIT_FAILURE
);
1518 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1519 hostuid_mapped
, geteuid());
1520 if (ret
< 0 || ret
>= 200)
1521 _exit(EXIT_FAILURE
);
1524 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1525 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1526 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1528 _exit(EXIT_FAILURE
);
1530 if (hostgid_mapped
< 0) {
1531 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1532 n2
[n2args
++] = "-m";
1533 if (hostgid_mapped
< 0) {
1534 ERROR("Failed to find free gid to map");
1535 _exit(EXIT_FAILURE
);
1538 n2
[n2args
++] = malloc(200);
1539 if (!n2
[n2args
- 1]) {
1540 SYSERROR("out of memory");
1541 _exit(EXIT_FAILURE
);
1544 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1545 hostgid_mapped
, getegid());
1546 if (ret
< 0 || ret
>= 200)
1547 _exit(EXIT_FAILURE
);
1549 n2
[n2args
++] = "--";
1550 for (i
= 0; i
< nargs
; i
++)
1551 n2
[i
+ n2args
] = newargv
[i
];
1554 /* Finally add "--mapped-uid $uid" to tell template what
1555 * to chown cached images to.
1558 n2
= realloc(n2
, n2args
* sizeof(char *));
1560 _exit(EXIT_FAILURE
);
1562 /* note n2[n2args-1] is NULL */
1563 n2
[n2args
- 5] = "--mapped-uid";
1564 snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1565 n2
[n2args
- 4] = txtuid
;
1566 n2
[n2args
- 3] = "--mapped-gid";
1567 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1568 n2
[n2args
- 2] = txtgid
;
1569 n2
[n2args
- 1] = NULL
;
1574 execvp(tpath
, newargv
);
1575 SYSERROR("Failed to execute template %s", tpath
);
1576 _exit(EXIT_FAILURE
);
1579 ret
= wait_for_pid(pid
);
1581 ERROR("Failed to create container from template");
1588 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1597 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1601 f
= fopen(path
, "r");
1605 ret
= fseek(f
, 0, SEEK_END
);
1614 ret
= fseek(f
, 0, SEEK_SET
);
1618 ret
= fseek(f
, 0, SEEK_SET
);
1623 contents
= malloc(flen
+ 1);
1627 len
= fread(contents
, 1, flen
, f
);
1629 goto out_free_contents
;
1631 contents
[flen
] = '\0';
1635 goto out_free_contents
;
1638 tpath
= get_template_path(t
);
1640 ERROR("Invalid template \"%s\" specified", t
);
1641 goto out_free_contents
;
1644 ret
= sha1sum_file(tpath
, md_value
);
1646 ERROR("Failed to get sha1sum of %s", tpath
);
1648 goto out_free_contents
;
1653 f
= fopen(path
, "w");
1655 SYSERROR("Reopening config for writing");
1660 fprintf(f
, "# Template used to create this container: %s\n", t
);
1662 fprintf(f
, "# Parameters passed to the template:");
1664 fprintf(f
, " %s", *argv
);
1670 fprintf(f
, "# Template script checksum (SHA-1): ");
1671 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1672 fprintf(f
, "%02x", md_value
[i
]);
1675 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1676 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1677 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1678 fprintf(f
, "# (Be aware this has security implications)\n\n");
1679 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1680 SYSERROR("Writing original contents");
1700 SYSERROR("Error prepending header");
1707 static void lxcapi_clear_config(struct lxc_container
*c
)
1709 if (!c
|| !c
->lxc_conf
)
1712 lxc_conf_free(c
->lxc_conf
);
1716 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1720 * create a container with the given parameters.
1721 * @c: container to be created. It has the lxcpath, name, and a starting
1722 * configuration already set
1723 * @t: the template to execute to instantiate the root filesystem and
1724 * adjust the configuration.
1725 * @bdevtype: backing store type to use. If NULL, dir will be used.
1726 * @specs: additional parameters for the backing store, i.e. LVM vg to
1729 * @argv: the arguments to pass to the template, terminated by NULL. If no
1730 * arguments, you can just pass NULL.
1732 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1733 const char *bdevtype
, struct bdev_specs
*specs
,
1734 int flags
, char *const argv
[])
1746 tpath
= get_template_path(t
);
1748 ERROR("Unknown template \"%s\"", t
);
1753 /* If a template is passed in, and the rootfs already is defined in the
1754 * container config and exists, then the caller is trying to create an
1755 * existing container. Return an error, but do NOT delete the container.
1757 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1758 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1759 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1765 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1766 ERROR("Error loading default configuration file %s",
1767 lxc_global_config_value("lxc.default_config"));
1772 if (!create_container_dir(c
))
1775 /* If both template and rootfs.path are set, template is setup as
1776 * rootfs.path. The container is already created if we have a config and
1777 * rootfs.path is accessible
1779 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1780 /* No template passed in and rootfs does not exist. */
1781 if (!c
->save_config(c
, NULL
)) {
1782 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1789 /* Rootfs passed into configuration, but does not exist. */
1790 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1793 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1794 /* Rootfs already existed, user just wanted to save the loaded
1797 if (!c
->save_config(c
, NULL
))
1798 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1803 /* Mark that this container is being created */
1804 partial_fd
= create_partial(c
);
1808 /* No need to get disk lock bc we have the partial lock. */
1812 /* Create the storage.
1813 * Note we can't do this in the same task as we use to execute the
1814 * template because of the way zfs works.
1815 * After you 'zfs create', zfs mounts the fs only in the initial
1820 SYSERROR("Failed to fork task for container creation template");
1824 if (pid
== 0) { /* child */
1825 struct lxc_storage
*bdev
= NULL
;
1827 bdev
= do_storage_create(c
, bdevtype
, specs
);
1829 ERROR("Failed to create %s storage for %s",
1830 bdevtype
? bdevtype
: "(none)", c
->name
);
1831 _exit(EXIT_FAILURE
);
1834 /* Save config file again to store the new rootfs location. */
1835 if (!do_lxcapi_save_config(c
, NULL
)) {
1836 ERROR("Failed to save initial config for %s", c
->name
);
1837 /* Parent task won't see the storage driver in the
1838 * config so we delete it.
1840 bdev
->ops
->umount(bdev
);
1841 bdev
->ops
->destroy(bdev
);
1842 _exit(EXIT_FAILURE
);
1844 _exit(EXIT_SUCCESS
);
1846 if (wait_for_pid(pid
) != 0)
1849 /* Reload config to get the rootfs. */
1850 lxc_conf_free(c
->lxc_conf
);
1852 if (!load_config_locked(c
, c
->configfile
))
1855 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1858 /* Now clear out the lxc_conf we have, reload from the created
1861 do_lxcapi_clear_config(c
);
1864 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1865 ERROR("Failed to prepend header to config file");
1869 ret
= load_config_locked(c
, c
->configfile
);
1873 if (partial_fd
>= 0)
1874 remove_partial(c
, partial_fd
);
1877 container_destroy(c
, NULL
);
1883 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1884 const char *bdevtype
, struct bdev_specs
*specs
,
1885 int flags
, char *const argv
[])
1888 current_config
= c
? c
->lxc_conf
: NULL
;
1889 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1890 current_config
= NULL
;
1894 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1897 int rebootsignal
= SIGINT
;
1901 if (!do_lxcapi_is_running(c
))
1903 pid
= do_lxcapi_init_pid(c
);
1906 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1907 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1908 if (kill(pid
, rebootsignal
) < 0) {
1909 WARN("Could not send signal %d to pid %d.", rebootsignal
, pid
);
1916 WRAP_API(bool, lxcapi_reboot
)
1918 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1922 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1923 lxc_state_t states
[MAX_STATE
] = {0};
1928 if (!do_lxcapi_is_running(c
))
1931 pid
= do_lxcapi_init_pid(c
);
1935 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1936 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1938 /* Add a new state client before sending the shutdown signal so that we
1939 * don't miss a state.
1942 states
[RUNNING
] = 2;
1943 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1948 if (state_client_fd
< 0)
1954 if (ret
< MAX_STATE
)
1958 /* Send reboot signal to container. */
1959 killret
= kill(pid
, rebootsignal
);
1961 WARN("Could not send signal %d to pid %d", rebootsignal
, pid
);
1962 if (state_client_fd
>= 0)
1963 close(state_client_fd
);
1966 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
1971 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
1972 close(state_client_fd
);
1976 TRACE("Received state \"%s\"", lxc_state2str(ret
));
1983 WRAP_API_1(bool, lxcapi_reboot2
, int)
1985 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1989 int haltsignal
= SIGPWR
, state_client_fd
= -1;
1990 lxc_state_t states
[MAX_STATE
] = {0};
1995 if (!do_lxcapi_is_running(c
))
1998 pid
= do_lxcapi_init_pid(c
);
2002 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2003 if (task_blocking_signal(pid
, (SIGRTMIN
+ 3)))
2004 haltsignal
= (SIGRTMIN
+ 3);
2006 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2007 haltsignal
= c
->lxc_conf
->haltsignal
;
2009 /* Add a new state client before sending the shutdown signal so that we
2010 * don't miss a state.
2013 states
[STOPPED
] = 1;
2014 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2019 if (state_client_fd
< 0)
2025 if (ret
< MAX_STATE
)
2029 /* Send shutdown signal to container. */
2030 killret
= kill(pid
, haltsignal
);
2032 WARN("Could not send signal %d to pid %d", haltsignal
, pid
);
2033 if (state_client_fd
>= 0)
2034 close(state_client_fd
);
2037 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2042 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2043 close(state_client_fd
);
2047 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2054 WRAP_API_1(bool, lxcapi_shutdown
, int)
2056 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2057 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2066 current_config
= c
->lxc_conf
;
2069 * since we're going to wait for create to finish, I don't think we
2070 * need to get a copy of the arguments.
2072 va_start(ap
, flags
);
2073 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2076 ERROR("Failed to allocate memory");
2080 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2084 current_config
= NULL
;
2088 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2090 if (!strcmp(key
, "lxc.cgroup"))
2091 return clear_unexp_config_line(conf
, key
, true);
2093 if (!strcmp(key
, "lxc.network"))
2094 return clear_unexp_config_line(conf
, key
, true);
2096 if (!strcmp(key
, "lxc.net"))
2097 return clear_unexp_config_line(conf
, key
, true);
2099 /* Clear a network with a specific index. */
2100 if (!strncmp(key
, "lxc.net.", 8)) {
2105 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2107 return clear_unexp_config_line(conf
, key
, true);
2110 if (!strcmp(key
, "lxc.hook"))
2111 return clear_unexp_config_line(conf
, key
, true);
2113 return clear_unexp_config_line(conf
, key
, false);
2116 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2120 struct lxc_config_t
*config
;
2122 if (!c
|| !c
->lxc_conf
)
2125 if (container_mem_lock(c
))
2128 config
= lxc_get_config(key
);
2129 /* Verify that the config key exists and that it has a callback
2132 if (config
&& config
->clr
)
2133 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2135 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2137 container_mem_unlock(c
);
2141 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2143 static inline bool enter_net_ns(struct lxc_container
*c
)
2145 pid_t pid
= do_lxcapi_init_pid(c
);
2147 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
2148 if (!switch_to_ns(pid
, "user"))
2151 return switch_to_ns(pid
, "net");
2154 /* Used by qsort and bsearch functions for comparing names. */
2155 static inline int string_cmp(char **first
, char **second
)
2157 return strcmp(*first
, *second
);
2160 /* Used by qsort and bsearch functions for comparing container names. */
2161 static inline int container_cmp(struct lxc_container
**first
,
2162 struct lxc_container
**second
)
2164 return strcmp((*first
)->name
, (*second
)->name
);
2167 static bool add_to_array(char ***names
, char *cname
, int pos
)
2169 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2171 ERROR("Out of memory");
2176 newnames
[pos
] = strdup(cname
);
2180 /* Sort the arrray as we will use binary search on it. */
2181 qsort(newnames
, pos
+ 1, sizeof(char *),
2182 (int (*)(const void *, const void *))string_cmp
);
2187 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2190 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2192 ERROR("Out of memory");
2199 /* Sort the arrray as we will use binary search on it. */
2201 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2202 (int (*)(const void *, const void *))container_cmp
);
2207 static char** get_from_array(char ***names
, char *cname
, int size
)
2209 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2213 static bool array_contains(char ***names
, char *cname
, int size
) {
2214 if(get_from_array(names
, cname
, size
) != NULL
)
2219 static bool remove_from_array(char ***names
, char *cname
, int size
)
2221 char **result
= get_from_array(names
, cname
, size
);
2222 if (result
!= NULL
) {
2229 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2232 int i
, count
= 0, pipefd
[2];
2233 char **interfaces
= NULL
;
2234 char interface
[IFNAMSIZ
];
2236 if(pipe(pipefd
) < 0) {
2237 SYSERROR("pipe failed");
2243 SYSERROR("failed to fork task to get interfaces information");
2249 if (pid
== 0) { /* child */
2250 int ret
= 1, nbytes
;
2251 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2253 /* close the read-end of the pipe */
2256 if (!enter_net_ns(c
)) {
2257 SYSERROR("failed to enter namespace");
2261 /* Grab the list of interfaces */
2262 if (getifaddrs(&interfaceArray
)) {
2263 SYSERROR("failed to get interfaces list");
2267 /* Iterate through the interfaces */
2268 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2269 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2271 ERROR("write failed");
2280 freeifaddrs(interfaceArray
);
2282 /* close the write-end of the pipe, thus sending EOF to the reader */
2287 /* close the write-end of the pipe */
2290 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2291 interface
[IFNAMSIZ
- 1] = '\0';
2293 if (array_contains(&interfaces
, interface
, count
))
2296 if(!add_to_array(&interfaces
, interface
, count
))
2297 ERROR("Failed to add \"%s\" to array", interface
);
2302 if (wait_for_pid(pid
) != 0) {
2303 for(i
=0;i
<count
;i
++)
2304 free(interfaces
[i
]);
2309 /* close the read-end of the pipe */
2312 /* Append NULL to the array */
2314 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2319 WRAP_API(char **, lxcapi_get_interfaces
)
2321 static char** do_lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
2324 int i
, count
= 0, pipefd
[2];
2325 char **addresses
= NULL
;
2326 char address
[INET6_ADDRSTRLEN
];
2328 if(pipe(pipefd
) < 0) {
2329 SYSERROR("pipe failed");
2335 SYSERROR("failed to fork task to get container ips");
2341 if (pid
== 0) { /* child */
2342 int ret
= 1, nbytes
;
2343 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2344 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2345 void *tempAddrPtr
= NULL
;
2346 char *address
= NULL
;
2348 /* close the read-end of the pipe */
2351 if (!enter_net_ns(c
)) {
2352 SYSERROR("failed to enter namespace");
2356 /* Grab the list of interfaces */
2357 if (getifaddrs(&interfaceArray
)) {
2358 SYSERROR("failed to get interfaces list");
2362 /* Iterate through the interfaces */
2363 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2364 if (tempIfAddr
->ifa_addr
== NULL
)
2367 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2368 if (family
&& strcmp(family
, "inet"))
2370 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2373 if (family
&& strcmp(family
, "inet6"))
2376 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2379 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2382 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2384 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2387 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2389 addressOutputBuffer
,
2390 sizeof(addressOutputBuffer
));
2394 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2396 ERROR("write failed");
2405 freeifaddrs(interfaceArray
);
2407 /* close the write-end of the pipe, thus sending EOF to the reader */
2412 /* close the write-end of the pipe */
2415 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2416 if(!add_to_array(&addresses
, address
, count
))
2417 ERROR("PARENT: add_to_array failed");
2421 if (wait_for_pid(pid
) != 0) {
2422 for(i
=0;i
<count
;i
++)
2428 /* close the read-end of the pipe */
2431 /* Append NULL to the array */
2433 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2438 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2440 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2443 struct lxc_config_t
*config
;
2445 if (!c
|| !c
->lxc_conf
)
2448 if (container_mem_lock(c
))
2451 config
= lxc_get_config(key
);
2452 /* Verify that the config key exists and that it has a callback
2455 if (config
&& config
->get
)
2456 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2458 container_mem_unlock(c
);
2462 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2464 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2468 if (!c
|| !c
->lxc_conf
)
2470 if (container_mem_lock(c
))
2472 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2473 container_mem_unlock(c
);
2477 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2479 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2483 /* List all config items. */
2485 return lxc_list_config_items(retv
, inlen
);
2487 if (!c
|| !c
->lxc_conf
)
2490 if (container_mem_lock(c
))
2493 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2494 * This is an intelligent result to show which keys are valid given the
2495 * type of nic it is.
2497 if (strncmp(key
, "lxc.net.", 8) == 0)
2498 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2500 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2502 container_mem_unlock(c
);
2506 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2508 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2511 bool ret
= false, need_disklock
= false;
2514 alt_file
= c
->configfile
;
2518 /* If we haven't yet loaded a config, load the stock config. */
2520 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2521 ERROR("Error loading default configuration file %s "
2523 lxc_global_config_value("lxc.default_config"),
2529 if (!create_container_dir(c
))
2532 /* If we're writing to the container's config file, take the disk lock.
2533 * Otherwise just take the memlock to protect the struct lxc_container
2534 * while we're traversing it.
2536 if (strcmp(c
->configfile
, alt_file
) == 0)
2537 need_disklock
= true;
2540 lret
= container_disk_lock(c
);
2542 lret
= container_mem_lock(c
);
2546 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2547 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2551 lret
= write_config(fd
, c
->lxc_conf
);
2560 container_disk_unlock(c
);
2562 container_mem_unlock(c
);
2567 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2570 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2576 char path
[MAXPATHLEN
];
2577 char newpath
[MAXPATHLEN
];
2578 int fd
, ret
, n
= 0, v
= 0;
2580 size_t len
= 0, bytes
= 0;
2582 if (container_disk_lock(c0
))
2585 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2586 if (ret
< 0 || ret
> MAXPATHLEN
)
2588 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2589 if (ret
< 0 || ret
> MAXPATHLEN
)
2592 /* If we find an lxc-snapshot file using the old format only listing the
2593 * number of snapshots we will keep using it. */
2594 f1
= fopen(path
, "r");
2596 n
= fscanf(f1
, "%d", &v
);
2598 if (n
== 1 && v
== 0) {
2605 f1
= fopen(path
, "w");
2608 if (fprintf(f1
, "%d\n", v
) < 0) {
2609 ERROR("Error writing new snapshots value");
2615 SYSERROR("Error writing to or closing snapshots file");
2619 /* Here we know that we have or can use an lxc-snapshot file
2620 * using the new format. */
2622 f1
= fopen(path
, "a");
2626 if (fprintf(f1
, "%s", newpath
) < 0) {
2627 ERROR("Error writing new snapshots entry");
2630 SYSERROR("Error writing to or closing snapshots file");
2636 SYSERROR("Error writing to or closing snapshots file");
2640 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2643 if (fstat(fd
, &fbuf
) < 0) {
2648 if (fbuf
.st_size
!= 0) {
2650 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2651 if (buf
== MAP_FAILED
) {
2652 SYSERROR("Failed to create mapping %s", path
);
2657 len
= strlen(newpath
);
2658 while ((del
= strstr((char *)buf
, newpath
))) {
2659 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2663 lxc_strmunmap(buf
, fbuf
.st_size
);
2664 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2665 SYSERROR("Failed to truncate file %s", path
);
2673 /* If the lxc-snapshot file is empty, remove it. */
2674 if (stat(path
, &fbuf
) < 0)
2676 if (!fbuf
.st_size
) {
2684 container_disk_unlock(c0
);
2688 static void strip_newline(char *p
)
2690 size_t len
= strlen(p
);
2693 if (p
[len
-1] == '\n')
2697 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2699 struct lxc_container
*p
;
2700 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2701 size_t pathlen
= 0, namelen
= 0;
2705 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2706 c
->config_path
, c
->name
);
2707 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2708 ERROR("Path name too long");
2711 f
= fopen(path
, "r");
2714 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2715 if (getline(&lxcname
, &namelen
, f
) == -1) {
2716 ERROR("badly formatted file %s", path
);
2719 strip_newline(lxcpath
);
2720 strip_newline(lxcname
);
2721 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2722 ERROR("Unable to find dependent container %s:%s",
2726 if (!mod_rdep(p
, c
, inc
))
2727 ERROR("Failed to update snapshots file for %s:%s",
2729 lxc_container_put(p
);
2737 static bool has_fs_snapshots(struct lxc_container
*c
)
2740 char path
[MAXPATHLEN
];
2745 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2747 if (ret
< 0 || ret
> MAXPATHLEN
)
2749 /* If the file doesn't exist there are no snapshots. */
2750 if (stat(path
, &fbuf
) < 0)
2754 f
= fopen(path
, "r");
2757 ret
= fscanf(f
, "%d", &v
);
2759 /* TODO: Figure out what to do with the return value of fscanf. */
2761 INFO("Container uses new lxc-snapshots format %s", path
);
2769 static bool has_snapshots(struct lxc_container
*c
)
2771 char path
[MAXPATHLEN
];
2772 struct dirent
*direntp
;
2776 if (!get_snappath_dir(c
, path
))
2778 dir
= opendir(path
);
2781 while ((direntp
= readdir(dir
))) {
2785 if (!strcmp(direntp
->d_name
, "."))
2788 if (!strcmp(direntp
->d_name
, ".."))
2797 static bool do_destroy_container(struct lxc_conf
*conf
) {
2800 if (am_guest_unpriv()) {
2801 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2802 "storage_destroy_wrapper");
2809 return storage_destroy(conf
);
2812 static int lxc_rmdir_onedev_wrapper(void *data
)
2814 char *arg
= (char *) data
;
2815 return lxc_rmdir_onedev(arg
, "snaps");
2818 static int lxc_unlink_exec_wrapper(void *data
)
2824 static bool container_destroy(struct lxc_container
*c
,
2825 struct lxc_storage
*storage
)
2829 struct lxc_conf
*conf
;
2834 if (!c
|| !do_lxcapi_is_defined(c
))
2838 if (container_disk_lock(c
))
2841 if (!is_stopped(c
)) {
2842 /* We should queue some sort of error - in c->error_string? */
2843 ERROR("container %s is not stopped", c
->name
);
2847 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2848 /* Start of environment variable setup for hooks */
2849 if (setenv("LXC_NAME", c
->name
, 1))
2850 SYSERROR("Failed to set environment variable for container name");
2852 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2853 SYSERROR("Failed to set environment variable for config path");
2855 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2856 SYSERROR("Failed to set environment variable for rootfs mount");
2858 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2859 SYSERROR("Failed to set environment variable for rootfs mount");
2861 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2862 SYSERROR("Failed to set environment variable for console path");
2864 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2865 SYSERROR("Failed to set environment variable for console log");
2866 /* End of environment variable setup for hooks */
2868 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2869 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2874 if (current_config
&& conf
== current_config
) {
2875 current_config
= NULL
;
2876 if (conf
->logfd
!= -1) {
2882 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2883 if (!do_destroy_container(conf
)) {
2884 ERROR("Error destroying rootfs for %s", c
->name
);
2887 INFO("Destroyed rootfs for %s", c
->name
);
2890 mod_all_rdeps(c
, false);
2892 p1
= do_lxcapi_get_config_path(c
);
2901 * strlen("config") = 6
2905 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
2908 ERROR("Failed to allocate memory");
2912 /* For an overlay container the rootfs is considered immutable and
2913 * cannot be removed when restoring from a snapshot.
2915 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
2916 !strcmp(storage
->type
, "overlayfs")) &&
2917 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
2918 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
2919 if (ret
< 0 || (size_t)ret
>= len
)
2922 if (am_guest_unpriv())
2923 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
2924 "lxc_unlink_exec_wrapper");
2928 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
2932 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
2938 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
2939 if (ret
< 0 || (size_t)ret
>= len
)
2941 if (am_guest_unpriv())
2942 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
2943 "lxc_rmdir_onedev_wrapper");
2945 ret
= lxc_rmdir_onedev(path
, "snaps");
2947 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
2951 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
2958 container_disk_unlock(c
);
2962 static bool do_lxcapi_destroy(struct lxc_container
*c
)
2964 if (!c
|| !lxcapi_is_defined(c
))
2967 if (has_snapshots(c
)) {
2968 ERROR("Container %s has snapshots; not removing", c
->name
);
2972 if (has_fs_snapshots(c
)) {
2973 ERROR("container %s has snapshots on its rootfs", c
->name
);
2977 return container_destroy(c
, NULL
);
2980 WRAP_API(bool, lxcapi_destroy
)
2982 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2984 if (!c
|| !lxcapi_is_defined(c
))
2986 if (!lxcapi_snapshot_destroy_all(c
)) {
2987 ERROR("Error deleting all snapshots");
2990 return lxcapi_destroy(c
);
2993 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
2995 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
2999 struct lxc_config_t
*config
;
3002 config
= lxc_get_config(key
);
3006 ret
= config
->set(key
, v
, conf
, NULL
);
3010 if (lxc_config_value_empty(v
))
3011 do_clear_unexp_config_line(conf
, key
);
3013 bret
= do_append_unexp_config_line(conf
, key
, v
);
3020 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3026 c
->lxc_conf
= lxc_conf_init();
3031 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3038 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3045 if (container_mem_lock(c
))
3048 b
= do_set_config_item_locked(c
, key
, v
);
3050 container_mem_unlock(c
);
3054 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3056 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3058 if (!c
|| !c
->configfile
)
3060 return strdup(c
->configfile
);
3063 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3065 if (!c
|| !c
->config_path
)
3067 return (const char *)(c
->config_path
);
3072 * Just recalculate the c->configfile based on the
3073 * c->config_path, which must be set.
3074 * The lxc_container must be locked or not yet public.
3076 static bool set_config_filename(struct lxc_container
*c
)
3081 if (!c
->config_path
)
3084 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3085 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3086 newpath
= malloc(len
);
3090 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3091 if (ret
< 0 || ret
>= len
) {
3092 fprintf(stderr
, "Error printing out config file name\n");
3097 free(c
->configfile
);
3098 c
->configfile
= newpath
;
3103 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3107 char *oldpath
= NULL
;
3112 if (container_mem_lock(c
))
3117 ERROR("Out of memory setting new lxc path");
3123 oldpath
= c
->config_path
;
3126 /* Since we've changed the config path, we have to change the
3127 * config file name too */
3128 if (!set_config_filename(c
)) {
3129 ERROR("Out of memory setting new config filename");
3131 free(c
->config_path
);
3132 c
->config_path
= oldpath
;
3137 container_mem_unlock(c
);
3141 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3143 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3153 if (container_disk_lock(c
))
3156 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
3158 container_disk_unlock(c
);
3162 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3164 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3174 if (container_disk_lock(c
))
3177 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
3179 container_disk_unlock(c
);
3183 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3185 const char *lxc_get_global_config_item(const char *key
)
3187 return lxc_global_config_value(key
);
3190 const char *lxc_get_version(void)
3195 static int copy_file(const char *old
, const char *new)
3202 if (file_exists(new)) {
3203 ERROR("copy destination %s exists", new);
3206 ret
= stat(old
, &sbuf
);
3208 INFO("Error stat'ing %s", old
);
3212 in
= open(old
, O_RDONLY
);
3214 SYSERROR("Error opening original file %s", old
);
3217 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3219 SYSERROR("Error opening new file %s", new);
3225 len
= read(in
, buf
, 8096);
3227 SYSERROR("Error reading old file %s", old
);
3232 ret
= write(out
, buf
, len
);
3233 if (ret
< len
) { /* should we retry? */
3234 SYSERROR("Error: write to new file %s was interrupted", new);
3241 /* We set mode, but not owner/group. */
3242 ret
= chmod(new, sbuf
.st_mode
);
3244 SYSERROR("Error setting mode on %s", new);
3256 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3259 struct lxc_list
*it
;
3262 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3263 cpath
= alloca(len
);
3264 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3265 if (ret
< 0 || ret
>= len
)
3268 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3269 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3270 char *hookname
= it
->elem
;
3271 char *fname
= strrchr(hookname
, '/');
3272 char tmppath
[MAXPATHLEN
];
3273 if (!fname
) /* relative path - we don't support, but maybe we should */
3275 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3276 /* this hook is public - ignore */
3279 /* copy the script, and change the entry in confile */
3280 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3281 c
->config_path
, c
->name
, fname
+1);
3282 if (ret
< 0 || ret
>= MAXPATHLEN
)
3284 ret
= copy_file(it
->elem
, tmppath
);
3288 it
->elem
= strdup(tmppath
);
3290 ERROR("out of memory copying hook path");
3296 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3297 c
->config_path
, oldc
->name
, c
->name
)) {
3298 ERROR("Error saving new hooks in clone");
3301 do_lxcapi_save_config(c
, NULL
);
3306 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3308 char newpath
[MAXPATHLEN
];
3309 char *oldpath
= oldc
->lxc_conf
->fstab
;
3315 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3317 char *p
= strrchr(oldpath
, '/');
3320 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3321 c
->config_path
, c
->name
, p
);
3322 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3323 ERROR("error printing new path for %s", oldpath
);
3326 if (file_exists(newpath
)) {
3327 ERROR("error: fstab file %s exists", newpath
);
3331 if (copy_file(oldpath
, newpath
) < 0) {
3332 ERROR("error: copying %s to %s", oldpath
, newpath
);
3335 free(c
->lxc_conf
->fstab
);
3336 c
->lxc_conf
->fstab
= strdup(newpath
);
3337 if (!c
->lxc_conf
->fstab
) {
3338 ERROR("error: allocating pathname");
3341 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3342 ERROR("error saving new lxctab");
3349 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3351 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3354 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3356 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3357 WARN("Error copying reverse dependencies");
3360 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3362 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3363 WARN("Error copying reverse dependencies");
3366 if (copy_file(path0
, path1
) < 0) {
3367 INFO("Error copying reverse dependencies");
3372 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3375 char path
[MAXPATHLEN
];
3379 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3381 if (ret
< 0 || ret
>= MAXPATHLEN
)
3383 f
= fopen(path
, "a");
3387 /* If anything goes wrong, just return an error. */
3388 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3396 * If the fs natively supports snapshot clones with no penalty,
3397 * then default to those even if not requested.
3398 * Currently we only do this for btrfs.
3400 bool should_default_to_snapshot(struct lxc_container
*c0
,
3401 struct lxc_container
*c1
)
3403 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3404 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3405 char *p0
= alloca(l0
+ 1);
3406 char *p1
= alloca(l1
+ 1);
3407 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3409 snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3410 snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3412 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3415 if (is_btrfs_subvol(rootfs
) <= 0)
3418 return btrfs_same_fs(p0
, p1
) == 0;
3421 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3422 const char *newtype
, int flags
, const char *bdevdata
,
3425 struct lxc_storage
*bdev
;
3428 if (should_default_to_snapshot(c0
, c
))
3429 flags
|= LXC_CLONE_SNAPSHOT
;
3431 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3432 bdevdata
, newsize
, &need_rdep
);
3434 ERROR("Error copying storage.");
3438 /* Set new rootfs. */
3439 free(c
->lxc_conf
->rootfs
.path
);
3440 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3443 if (!c
->lxc_conf
->rootfs
.path
) {
3444 ERROR("Out of memory while setting storage path.");
3448 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3449 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3450 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3451 c
->lxc_conf
->rootfs
.path
)) {
3452 ERROR("Error saving new rootfs to cloned config.");
3456 if (flags
& LXC_CLONE_SNAPSHOT
)
3457 copy_rdepends(c
, c0
);
3459 if (!add_rdepends(c
, c0
))
3460 WARN("Error adding reverse dependency from %s to %s",
3464 mod_all_rdeps(c
, true);
3469 struct clone_update_data
{
3470 struct lxc_container
*c0
;
3471 struct lxc_container
*c1
;
3476 static int clone_update_rootfs(struct clone_update_data
*data
)
3478 struct lxc_container
*c0
= data
->c0
;
3479 struct lxc_container
*c
= data
->c1
;
3480 int flags
= data
->flags
;
3481 char **hookargs
= data
->hookargs
;
3483 char path
[MAXPATHLEN
];
3484 struct lxc_storage
*bdev
;
3486 struct lxc_conf
*conf
= c
->lxc_conf
;
3488 /* update hostname in rootfs */
3489 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3491 if (setgid(0) < 0) {
3492 ERROR("Failed to setgid to 0");
3495 if (setuid(0) < 0) {
3496 ERROR("Failed to setuid to 0");
3499 if (setgroups(0, NULL
) < 0)
3500 WARN("Failed to clear groups");
3502 if (unshare(CLONE_NEWNS
) < 0)
3504 bdev
= storage_init(c
->lxc_conf
);
3507 if (strcmp(bdev
->type
, "dir") != 0) {
3508 if (unshare(CLONE_NEWNS
) < 0) {
3509 ERROR("error unsharing mounts");
3513 if (detect_shared_rootfs()) {
3514 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3515 SYSERROR("Failed to make / rslave");
3516 ERROR("Continuing...");
3519 if (bdev
->ops
->mount(bdev
) < 0) {
3523 } else { /* TODO come up with a better way */
3525 bdev
->dest
= strdup(bdev
->src
);
3528 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3529 /* Start of environment variable setup for hooks */
3530 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1)) {
3531 SYSERROR("failed to set environment variable for source container name");
3533 if (setenv("LXC_NAME", c
->name
, 1)) {
3534 SYSERROR("failed to set environment variable for container name");
3536 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
3537 SYSERROR("failed to set environment variable for config path");
3539 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
3540 SYSERROR("failed to set environment variable for rootfs mount");
3542 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
3543 SYSERROR("failed to set environment variable for rootfs mount");
3546 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3547 ERROR("Error executing clone hook for %s", c
->name
);
3553 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3554 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3557 if (ret
< 0 || ret
>= MAXPATHLEN
)
3559 if (!file_exists(path
))
3561 if (!(fout
= fopen(path
, "w"))) {
3562 SYSERROR("unable to open %s: ignoring", path
);
3565 if (fprintf(fout
, "%s", c
->name
) < 0) {
3569 if (fclose(fout
) < 0)
3578 static int clone_update_rootfs_wrapper(void *data
)
3580 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3581 return clone_update_rootfs(arg
);
3585 * We want to support:
3586 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3587 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3589 -s [ implies overlay]
3592 only rootfs gets converted (copied/snapshotted) on clone.
3595 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3597 char *p
= strrchr(path
, '/');
3603 ret
= do_create_container_dir(path
, conf
);
3608 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3609 const char *lxcpath
, int flags
,
3610 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3613 char newpath
[MAXPATHLEN
];
3615 struct clone_update_data data
;
3616 size_t saved_unexp_len
;
3618 int storage_copied
= 0;
3619 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3620 struct lxc_container
*c2
= NULL
;
3622 if (!c
|| !do_lxcapi_is_defined(c
))
3625 if (container_mem_lock(c
))
3628 if (!is_stopped(c
)) {
3629 ERROR("error: Original container (%s) is running", c
->name
);
3633 /* Make sure the container doesn't yet exist. */
3637 lxcpath
= do_lxcapi_get_config_path(c
);
3638 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3639 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3640 SYSERROR("clone: failed making config pathname");
3644 if (file_exists(newpath
)) {
3645 ERROR("error: clone: %s exists", newpath
);
3649 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3650 if (ret
< 0 && errno
!= EEXIST
) {
3651 ERROR("Error creating container dir for %s", newpath
);
3655 /* Copy the configuration. Tweak it as needed. */
3656 if (c
->lxc_conf
->rootfs
.path
) {
3657 origroot
= c
->lxc_conf
->rootfs
.path
;
3658 c
->lxc_conf
->rootfs
.path
= NULL
;
3661 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3662 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3664 SYSERROR("Failed to open \"%s\"", newpath
);
3668 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3669 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3670 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3671 if (!c
->lxc_conf
->unexpanded_config
) {
3676 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3677 write_config(fd
, c
->lxc_conf
);
3679 c
->lxc_conf
->rootfs
.path
= origroot
;
3680 free(c
->lxc_conf
->unexpanded_config
);
3681 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3682 saved_unexp_conf
= NULL
;
3683 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3685 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3686 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3687 SYSERROR("clone: failed making rootfs pathname");
3691 ret
= mkdir(newpath
, 0755);
3693 /* For an overlay container the rootfs is considered immutable
3694 * and will not have been removed when restoring from a
3697 if (errno
!= ENOENT
&&
3698 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3699 SYSERROR("Failed to create directory \"%s\"", newpath
);
3704 if (am_guest_unpriv()) {
3705 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3706 ERROR("Error chowning %s to container root", newpath
);
3711 c2
= lxc_container_new(newname
, lxcpath
);
3713 ERROR("clone: failed to create new container (%s %s)", newname
,
3718 /* copy/snapshot rootfs's */
3719 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3724 /* update utsname */
3725 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3726 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3727 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3729 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3730 ERROR("Error setting new hostname");
3736 ret
= copyhooks(c
, c2
);
3738 ERROR("error copying hooks");
3742 if (copy_fstab(c
, c2
) < 0) {
3743 ERROR("error copying fstab");
3747 /* update macaddrs */
3748 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3749 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3750 ERROR("Error updating mac addresses");
3755 /* Update absolute paths for overlay mount directories. */
3756 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3759 /* We've now successfully created c2's storage, so clear it out if we
3764 if (!c2
->save_config(c2
, NULL
))
3767 if ((pid
= fork()) < 0) {
3772 ret
= wait_for_pid(pid
);
3775 container_mem_unlock(c
);
3781 data
.hookargs
= hookargs
;
3782 if (am_guest_unpriv())
3783 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3784 &data
, "clone_update_rootfs_wrapper");
3786 ret
= clone_update_rootfs(&data
);
3788 _exit(EXIT_FAILURE
);
3790 container_mem_unlock(c
);
3791 _exit(EXIT_SUCCESS
);
3794 container_mem_unlock(c
);
3796 if (!storage_copied
)
3797 c2
->lxc_conf
->rootfs
.path
= NULL
;
3799 lxc_container_put(c2
);
3805 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3806 const char *lxcpath
, int flags
,
3807 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3810 struct lxc_container
* ret
;
3811 current_config
= c
? c
->lxc_conf
: NULL
;
3812 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3813 current_config
= NULL
;
3817 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3819 struct lxc_storage
*bdev
;
3820 struct lxc_container
*newc
;
3822 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3825 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3826 ERROR("Renaming a container with snapshots is not supported");
3829 bdev
= storage_init(c
->lxc_conf
);
3831 ERROR("Failed to find original backing store type");
3835 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3838 lxc_container_put(newc
);
3842 if (newc
&& lxcapi_is_defined(newc
))
3843 lxc_container_put(newc
);
3845 if (!container_destroy(c
, NULL
)) {
3846 ERROR("Could not destroy existing container %s", c
->name
);
3852 WRAP_API_1(bool, lxcapi_rename
, const char *)
3854 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
)
3861 current_config
= c
->lxc_conf
;
3863 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
3864 current_config
= NULL
;
3868 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3870 lxc_attach_command_t command
;
3877 command
.program
= (char*)program
;
3878 command
.argv
= (char**)argv
;
3879 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
3884 return lxc_wait_for_pid_status(pid
);
3887 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3890 current_config
= c
? c
->lxc_conf
: NULL
;
3891 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
3892 current_config
= NULL
;
3896 static int get_next_index(const char *lxcpath
, char *cname
)
3902 fname
= alloca(strlen(lxcpath
) + 20);
3904 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
3905 ret
= stat(fname
, &sb
);
3912 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
3916 * If the old style snapshot path exists, use it
3917 * /var/lib/lxc -> /var/lib/lxcsnaps
3919 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
3920 if (ret
< 0 || ret
>= MAXPATHLEN
)
3922 if (dir_exists(snappath
)) {
3923 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3924 if (ret
< 0 || ret
>= MAXPATHLEN
)
3930 * Use the new style path
3931 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3933 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
3934 if (ret
< 0 || ret
>= MAXPATHLEN
)
3939 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
3942 struct lxc_container
*c2
;
3943 char snappath
[MAXPATHLEN
], newname
[20];
3945 if (!c
|| !lxcapi_is_defined(c
))
3948 if (!storage_can_backup(c
->lxc_conf
)) {
3949 ERROR("%s's backing store cannot be backed up.", c
->name
);
3950 ERROR("Your container must use another backing store type.");
3954 if (!get_snappath_dir(c
, snappath
))
3957 i
= get_next_index(snappath
, c
->name
);
3959 if (mkdir_p(snappath
, 0755) < 0) {
3960 ERROR("Failed to create snapshot directory %s", snappath
);
3964 ret
= snprintf(newname
, 20, "snap%d", i
);
3965 if (ret
< 0 || ret
>= 20)
3969 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3970 * created in the original container
3972 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
3973 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
3974 if (storage_is_dir(c
->lxc_conf
)) {
3975 ERROR("Snapshot of directory-backed container requested.");
3976 ERROR("Making a copy-clone. If you do want snapshots, then");
3977 ERROR("please create overlay clone first, snapshot that");
3978 ERROR("and keep the original container pristine.");
3979 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3981 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
3983 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
3987 lxc_container_put(c2
);
3989 /* Now write down the creation time. */
3996 tm_info
= localtime(&timer
);
3998 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
4000 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4001 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4002 f
= fopen(dfnam
, "w");
4004 ERROR("Failed to open %s", dfnam
);
4007 if (fprintf(f
, "%s", buffer
) < 0) {
4008 SYSERROR("Writing timestamp");
4014 SYSERROR("Writing timestamp");
4019 /* $p / $name / comment \0 */
4020 int len
= strlen(snappath
) + strlen(newname
) + 10;
4021 char *path
= alloca(len
);
4022 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4023 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4029 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4031 static void lxcsnap_free(struct lxc_snapshot
*s
)
4034 free(s
->comment_pathname
);
4039 static char *get_snapcomment_path(char* snappath
, char *name
)
4041 /* $snappath/$name/comment */
4042 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4043 char *s
= malloc(len
);
4046 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4047 if (ret
< 0 || ret
>= len
) {
4055 static char *get_timestamp(char* snappath
, char *name
)
4057 char path
[MAXPATHLEN
], *s
= NULL
;
4061 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4062 if (ret
< 0 || ret
>= MAXPATHLEN
)
4064 fin
= fopen(path
, "r");
4067 (void) fseek(fin
, 0, SEEK_END
);
4069 (void) fseek(fin
, 0, SEEK_SET
);
4074 if (fread(s
, 1, len
, fin
) != len
) {
4075 SYSERROR("reading timestamp");
4085 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4087 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4089 struct dirent
*direntp
;
4090 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4093 if (!c
|| !lxcapi_is_defined(c
))
4096 if (!get_snappath_dir(c
, snappath
)) {
4097 ERROR("path name too long");
4100 dir
= opendir(snappath
);
4102 INFO("failed to open %s - assuming no snapshots", snappath
);
4106 while ((direntp
= readdir(dir
))) {
4110 if (!strcmp(direntp
->d_name
, "."))
4113 if (!strcmp(direntp
->d_name
, ".."))
4116 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4117 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4118 ERROR("pathname too long");
4121 if (!file_exists(path2
))
4123 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4125 SYSERROR("Out of memory");
4129 snaps
[count
].free
= lxcsnap_free
;
4130 snaps
[count
].name
= strdup(direntp
->d_name
);
4131 if (!snaps
[count
].name
)
4133 snaps
[count
].lxcpath
= strdup(snappath
);
4134 if (!snaps
[count
].lxcpath
) {
4135 free(snaps
[count
].name
);
4138 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4139 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4144 WARN("failed to close directory");
4152 for (i
=0; i
<count
; i
++)
4153 lxcsnap_free(&snaps
[i
]);
4157 WARN("failed to close directory");
4161 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4163 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4165 char clonelxcpath
[MAXPATHLEN
];
4167 struct lxc_container
*snap
, *rest
;
4168 struct lxc_storage
*bdev
;
4171 if (!c
|| !c
->name
|| !c
->config_path
)
4174 if (has_fs_snapshots(c
)) {
4175 ERROR("container rootfs has dependent snapshots");
4179 bdev
= storage_init(c
->lxc_conf
);
4181 ERROR("Failed to find original backing store type");
4185 /* For an overlay container the rootfs is considered immutable
4186 * and cannot be removed when restoring from a snapshot. We pass this
4187 * internal flag along to communicate this to various parts of the
4190 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4191 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4196 if (!get_snappath_dir(c
, clonelxcpath
)) {
4200 /* how should we lock this? */
4202 snap
= lxc_container_new(snapname
, clonelxcpath
);
4203 if (!snap
|| !lxcapi_is_defined(snap
)) {
4204 ERROR("Could not open snapshot %s", snapname
);
4206 lxc_container_put(snap
);
4211 if (!strcmp(c
->name
, newname
)) {
4212 if (!container_destroy(c
, bdev
)) {
4213 ERROR("Could not destroy existing container %s", newname
);
4214 lxc_container_put(snap
);
4220 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4221 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4223 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4224 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4225 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4228 if (rest
&& lxcapi_is_defined(rest
))
4231 lxc_container_put(rest
);
4233 lxc_container_put(snap
);
4237 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4239 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4241 struct lxc_container
*snap
= NULL
;
4244 snap
= lxc_container_new(snapname
, clonelxcpath
);
4246 ERROR("Could not find snapshot %s", snapname
);
4250 if (!do_lxcapi_destroy(snap
)) {
4251 ERROR("Could not destroy snapshot %s", snapname
);
4258 lxc_container_put(snap
);
4262 static bool remove_all_snapshots(const char *path
)
4265 struct dirent
*direntp
;
4268 dir
= opendir(path
);
4270 SYSERROR("opendir on snapshot path %s", path
);
4273 while ((direntp
= readdir(dir
))) {
4274 if (!strcmp(direntp
->d_name
, "."))
4276 if (!strcmp(direntp
->d_name
, ".."))
4278 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4287 SYSERROR("Error removing directory %s", path
);
4292 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4294 char clonelxcpath
[MAXPATHLEN
];
4296 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4299 if (!get_snappath_dir(c
, clonelxcpath
))
4302 return do_snapshot_destroy(snapname
, clonelxcpath
);
4305 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4307 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4309 char clonelxcpath
[MAXPATHLEN
];
4311 if (!c
|| !c
->name
|| !c
->config_path
)
4314 if (!get_snappath_dir(c
, clonelxcpath
))
4317 return remove_all_snapshots(clonelxcpath
);
4320 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4322 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4324 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4327 WRAP_API(bool, lxcapi_may_control
)
4329 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4335 char chrootpath
[MAXPATHLEN
];
4336 char *directory_path
= NULL
;
4340 SYSERROR("Failed to fork()");
4345 ret
= wait_for_pid(pid
);
4347 ERROR("Failed to create device node");
4354 /* prepare the path */
4355 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4356 if (ret
< 0 || ret
>= MAXPATHLEN
)
4359 ret
= chroot(chrootpath
);
4361 _exit(EXIT_FAILURE
);
4365 _exit(EXIT_FAILURE
);
4367 /* remove path if it exists */
4368 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4372 ERROR("%s - Failed to remove \"%s\"", strerror(errno
), path
);
4373 _exit(EXIT_FAILURE
);
4378 _exit(EXIT_SUCCESS
);
4380 /* create any missing directories */
4383 _exit(EXIT_FAILURE
);
4385 directory_path
= dirname(tmp
);
4386 ret
= mkdir_p(directory_path
, 0755);
4387 if (ret
< 0 && errno
!= EEXIST
) {
4388 ERROR("%s - Failed to create path \"%s\"", strerror(errno
), directory_path
);
4390 _exit(EXIT_FAILURE
);
4393 /* create the device node */
4394 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4397 ERROR("%s - Failed to create device node at \"%s\"", strerror(errno
), path
);
4398 _exit(EXIT_FAILURE
);
4401 _exit(EXIT_SUCCESS
);
4404 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4408 char value
[LXC_MAX_BUFFER
];
4411 /* make sure container is running */
4412 if (!do_lxcapi_is_running(c
)) {
4413 ERROR("container is not running");
4417 /* use src_path if dest_path is NULL otherwise use dest_path */
4418 p
= dest_path
? dest_path
: src_path
;
4420 /* make sure we can access p */
4421 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4424 /* continue if path is character device or block device */
4425 if (S_ISCHR(st
.st_mode
))
4426 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4427 else if (S_ISBLK(st
.st_mode
))
4428 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4432 /* check snprintf return code */
4433 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4436 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4439 /* add or remove device to/from cgroup access list */
4441 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4442 ERROR("set_cgroup_item failed while adding the device node");
4446 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4447 ERROR("set_cgroup_item failed while removing the device node");
4455 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4457 // cannot mknod if we're not privileged wrt init_user_ns
4458 if (am_host_unpriv()) {
4459 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4462 return add_remove_device_node(c
, src_path
, dest_path
, true);
4465 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4467 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4469 if (am_guest_unpriv()) {
4470 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4473 return add_remove_device_node(c
, src_path
, dest_path
, false);
4476 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4478 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4480 const char *dst_ifname
)
4485 if (am_guest_unpriv()) {
4486 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4491 ERROR("No source interface name given");
4495 ret
= lxc_netdev_isup(ifname
);
4497 /* netdev of ifname is up. */
4498 ret
= lxc_netdev_down(ifname
);
4503 init_pid
= do_lxcapi_init_pid(c
);
4504 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4508 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4515 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4517 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4519 const char *dst_ifname
)
4522 pid_t pid
, pid_outside
;
4525 * TODO - if this is a physical device, then we need am_host_unpriv.
4526 * But for other types guest privilege suffices.
4528 if (am_guest_unpriv()) {
4529 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4534 ERROR("No source interface name given");
4538 pid_outside
= lxc_raw_getpid();
4541 ERROR("Failed to fork");
4545 if (pid
== 0) { /* child */
4548 init_pid
= do_lxcapi_init_pid(c
);
4549 if (!switch_to_ns(init_pid
, "net")) {
4550 ERROR("Failed to enter network namespace");
4551 _exit(EXIT_FAILURE
);
4554 ret
= lxc_netdev_isup(ifname
);
4556 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4557 _exit(EXIT_FAILURE
);
4560 /* netdev of ifname is up. */
4562 ret
= lxc_netdev_down(ifname
);
4564 ERROR("Failed to set network device \"%s\" down", ifname
);
4565 _exit(EXIT_FAILURE
);
4569 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4570 /* -EINVAL means there is no netdev named as ifname. */
4573 ERROR("Network device \"%s\" not found", ifname
);
4575 ERROR("Failed to remove network device \"%s\"", ifname
);
4576 _exit(EXIT_FAILURE
);
4579 _exit(EXIT_SUCCESS
);
4582 ret
= wait_for_pid(pid
);
4586 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4590 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4592 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4593 struct migrate_opts
*opts
, unsigned int size
)
4596 struct migrate_opts
*valid_opts
= opts
;
4597 uint64_t features_to_check
= 0;
4599 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4600 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4601 * to do anything special.
4603 if (size
> sizeof(*opts
)) {
4604 unsigned char *addr
;
4607 addr
= (void *)opts
+ sizeof(*opts
);
4608 end
= (void *)opts
+ size
;
4609 for (; addr
< end
; addr
++) {
4616 /* If the caller has a smaller struct, let's zero out the end for them
4617 * so we don't accidentally use bits of it that they didn't know about
4620 if (size
< sizeof(*opts
)) {
4621 valid_opts
= malloc(sizeof(*opts
));
4625 memset(valid_opts
, 0, sizeof(*opts
));
4626 memcpy(valid_opts
, opts
, size
);
4630 case MIGRATE_PRE_DUMP
:
4631 if (!do_lxcapi_is_running(c
)) {
4632 ERROR("container is not running");
4635 ret
= !__criu_pre_dump(c
, valid_opts
);
4638 if (!do_lxcapi_is_running(c
)) {
4639 ERROR("container is not running");
4642 ret
= !__criu_dump(c
, valid_opts
);
4644 case MIGRATE_RESTORE
:
4645 if (do_lxcapi_is_running(c
)) {
4646 ERROR("container is already running");
4649 ret
= !__criu_restore(c
, valid_opts
);
4651 case MIGRATE_FEATURE_CHECK
:
4652 features_to_check
= valid_opts
->features_to_check
;
4653 ret
= !__criu_check_feature(&features_to_check
);
4655 /* Something went wrong. Let's let the caller
4656 * know which feature checks failed. */
4657 valid_opts
->features_to_check
= features_to_check
;
4661 ERROR("invalid migrate command %u", cmd
);
4666 if (size
< sizeof(*opts
))
4672 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4674 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4676 struct migrate_opts opts
;
4678 memset(&opts
, 0, sizeof(opts
));
4680 opts
.directory
= directory
;
4682 opts
.verbose
= verbose
;
4684 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4687 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4689 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4691 struct migrate_opts opts
;
4693 memset(&opts
, 0, sizeof(opts
));
4695 opts
.directory
= directory
;
4696 opts
.verbose
= verbose
;
4698 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4701 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4703 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4712 current_config
= c
->lxc_conf
;
4715 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4719 ERROR("Memory allocation error.");
4725 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4728 current_config
= NULL
;
4732 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4734 struct lxc_container
*c
;
4739 c
= malloc(sizeof(*c
));
4741 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4744 memset(c
, 0, sizeof(*c
));
4747 c
->config_path
= strdup(configpath
);
4749 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4751 if (!c
->config_path
) {
4752 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4756 remove_trailing_slashes(c
->config_path
);
4757 c
->name
= malloc(strlen(name
)+1);
4759 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4762 strcpy(c
->name
, name
);
4765 c
->slock
= lxc_newlock(c
->config_path
, name
);
4767 fprintf(stderr
, "Failed to create lock for %s\n", name
);
4771 c
->privlock
= lxc_newlock(NULL
, NULL
);
4773 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
4777 if (!set_config_filename(c
)) {
4778 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
4782 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
4783 fprintf(stderr
, "Failed to load config for %s\n", name
);
4787 if (ongoing_create(c
) == 2) {
4788 ERROR("Failed to complete container creation for %s", c
->name
);
4789 container_destroy(c
, NULL
);
4790 lxcapi_clear_config(c
);
4792 c
->daemonize
= true;
4795 /* Assign the member functions. */
4796 c
->is_defined
= lxcapi_is_defined
;
4797 c
->state
= lxcapi_state
;
4798 c
->is_running
= lxcapi_is_running
;
4799 c
->freeze
= lxcapi_freeze
;
4800 c
->unfreeze
= lxcapi_unfreeze
;
4801 c
->console
= lxcapi_console
;
4802 c
->console_getfd
= lxcapi_console_getfd
;
4803 c
->init_pid
= lxcapi_init_pid
;
4804 c
->load_config
= lxcapi_load_config
;
4805 c
->want_daemonize
= lxcapi_want_daemonize
;
4806 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4807 c
->start
= lxcapi_start
;
4808 c
->startl
= lxcapi_startl
;
4809 c
->stop
= lxcapi_stop
;
4810 c
->config_file_name
= lxcapi_config_file_name
;
4811 c
->wait
= lxcapi_wait
;
4812 c
->set_config_item
= lxcapi_set_config_item
;
4813 c
->destroy
= lxcapi_destroy
;
4814 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4815 c
->rename
= lxcapi_rename
;
4816 c
->save_config
= lxcapi_save_config
;
4817 c
->get_keys
= lxcapi_get_keys
;
4818 c
->create
= lxcapi_create
;
4819 c
->createl
= lxcapi_createl
;
4820 c
->shutdown
= lxcapi_shutdown
;
4821 c
->reboot
= lxcapi_reboot
;
4822 c
->reboot2
= lxcapi_reboot2
;
4823 c
->clear_config
= lxcapi_clear_config
;
4824 c
->clear_config_item
= lxcapi_clear_config_item
;
4825 c
->get_config_item
= lxcapi_get_config_item
;
4826 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4827 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4828 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4829 c
->get_config_path
= lxcapi_get_config_path
;
4830 c
->set_config_path
= lxcapi_set_config_path
;
4831 c
->clone
= lxcapi_clone
;
4832 c
->get_interfaces
= lxcapi_get_interfaces
;
4833 c
->get_ips
= lxcapi_get_ips
;
4834 c
->attach
= lxcapi_attach
;
4835 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4836 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4837 c
->snapshot
= lxcapi_snapshot
;
4838 c
->snapshot_list
= lxcapi_snapshot_list
;
4839 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4840 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4841 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4842 c
->may_control
= lxcapi_may_control
;
4843 c
->add_device_node
= lxcapi_add_device_node
;
4844 c
->remove_device_node
= lxcapi_remove_device_node
;
4845 c
->attach_interface
= lxcapi_attach_interface
;
4846 c
->detach_interface
= lxcapi_detach_interface
;
4847 c
->checkpoint
= lxcapi_checkpoint
;
4848 c
->restore
= lxcapi_restore
;
4849 c
->migrate
= lxcapi_migrate
;
4850 c
->console_log
= lxcapi_console_log
;
4855 lxc_container_free(c
);
4859 int lxc_get_wait_states(const char **states
)
4864 for (i
=0; i
<MAX_STATE
; i
++)
4865 states
[i
] = lxc_state2str(i
);
4870 * These next two could probably be done smarter with reusing a common function
4871 * with different iterators and tests...
4873 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4876 int i
, cfound
= 0, nfound
= 0;
4877 struct dirent
*direntp
;
4878 struct lxc_container
*c
;
4881 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4883 dir
= opendir(lxcpath
);
4885 SYSERROR("opendir on lxcpath");
4894 while ((direntp
= readdir(dir
))) {
4898 /* Ignore '.', '..' and any hidden directory. */
4899 if (!strncmp(direntp
->d_name
, ".", 1))
4902 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4906 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4916 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4918 INFO("Container %s:%s has a config but could not be loaded",
4919 lxcpath
, direntp
->d_name
);
4921 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4925 if (!do_lxcapi_is_defined(c
)) {
4926 INFO("Container %s:%s has a config but is not defined",
4927 lxcpath
, direntp
->d_name
);
4929 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4931 lxc_container_put(c
);
4935 if (!add_to_clist(cret
, c
, nfound
, true)) {
4936 lxc_container_put(c
);
4946 if (names
&& *names
) {
4947 for (i
=0; i
<cfound
; i
++)
4951 if (cret
&& *cret
) {
4952 for (i
=0; i
<nfound
; i
++)
4953 lxc_container_put((*cret
)[i
]);
4960 int list_active_containers(const char *lxcpath
, char ***nret
,
4961 struct lxc_container
***cret
)
4963 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4966 char **ct_name
= NULL
;
4968 struct lxc_container
*c
= NULL
;
4972 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4973 lxcpath_len
= strlen(lxcpath
);
4980 FILE *f
= fopen("/proc/net/unix", "r");
4984 while (getline(&line
, &len
, f
) != -1) {
4986 char *p
= strrchr(line
, ' '), *p2
;
4995 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4997 } else if (strncmp(p
, "lxc/", 4) == 0) {
5007 /* Now p is the start of lxc_name. */
5008 p2
= strchr(p
, '/');
5009 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5014 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5017 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5022 p
= lxc_cmd_get_name(p
);
5027 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5033 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5036 goto free_cret_list
;
5047 c
= lxc_container_new(p
, lxcpath
);
5049 INFO("Container %s:%s is running but could not be loaded",
5051 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5061 * If this is an anonymous container, then is_defined *can*
5062 * return false. So we don't do that check. Count on the
5063 * fact that the command socket exists.
5066 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5067 lxc_container_put(c
);
5068 goto free_cret_list
;
5073 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5075 lxc_container_put(c
);
5076 goto free_cret_list
;
5087 if (cret
&& *cret
) {
5088 for (i
= 0; i
< cret_cnt
; i
++)
5089 lxc_container_put((*cret
)[i
]);
5095 for (i
= 0; i
< ct_name_cnt
; i
++)
5107 int list_all_containers(const char *lxcpath
, char ***nret
,
5108 struct lxc_container
***cret
)
5110 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5113 struct lxc_container
**ct_list
= NULL
;
5115 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5119 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5120 if (active_cnt
< 0) {
5125 for (i
= 0; i
< active_cnt
; i
++) {
5126 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5127 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5129 goto free_active_name
;
5133 free(active_name
[i
]);
5134 active_name
[i
] = NULL
;
5140 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5141 struct lxc_container
*c
;
5143 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5145 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5146 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5150 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5151 lxc_container_put(c
);
5170 for (i
= 0; i
< ct_list_cnt
; i
++) {
5171 lxc_container_put(ct_list
[i
]);
5176 for (i
= 0; i
< active_cnt
; i
++) {
5177 free(active_name
[i
]);
5182 for (i
= 0; i
< ct_cnt
; i
++) {
5189 bool lxc_config_item_is_supported(const char *key
)
5191 return !!lxc_get_config(key
);