3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
33 #include <arpa/inet.h>
34 #include <sys/sysmacros.h>
36 #include <sys/mount.h>
37 #include <sys/syscall.h>
38 #include <sys/types.h>
47 #include "commands_utils.h"
49 #include "confile_utils.h"
53 #include "initutils.h"
56 #include "lxccontainer.h"
59 #include "namespace.h"
65 #include "storage_utils.h"
66 #include "storage/btrfs.h"
67 #include "storage/overlay.h"
74 #include <sys/mkdev.h>
80 #include <../include/ifaddrs.h>
84 #include <../include/lxcmntent.h>
89 /* Define faccessat() if missing from the C library */
90 #ifndef HAVE_FACCESSAT
91 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
94 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
102 lxc_log_define(lxc_container
, lxc
);
104 static bool do_lxcapi_destroy(struct lxc_container
*c
);
105 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
106 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
107 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
108 static bool container_destroy(struct lxc_container
*c
,
109 struct lxc_storage
*storage
);
110 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
111 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
112 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
114 static bool config_file_exists(const char *lxcpath
, const char *cname
)
120 /* $lxcpath + '/' + $cname + '/config' + \0 */
121 len
= strlen(lxcpath
) + strlen(cname
) + 9;
123 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
124 if (ret
< 0 || (size_t)ret
>= len
)
127 return file_exists(fname
);
130 /* A few functions to help detect when a container creation failed. If a
131 * container creation was killed partway through, then trying to actually start
132 * that container could harm the host. We detect this by creating a 'partial'
133 * file under the container directory, and keeping an advisory lock. When
134 * container creation completes, we remove that file. When we load or try to
135 * start a container, if we find that file, without a flock, we remove the
138 static int ongoing_create(struct lxc_container
*c
)
145 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
147 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
148 if (ret
< 0 || (size_t)ret
>= len
)
151 if (!file_exists(path
))
154 fd
= open(path
, O_RDWR
);
159 lk
.l_whence
= SEEK_SET
;
164 ret
= fcntl(fd
, F_GETLK
, &lk
);
166 if (ret
== 0 && lk
.l_pid
!= -1) {
167 /* create is still ongoing */
171 /* Create completed but partial is still there. */
175 static int create_partial(struct lxc_container
*c
)
182 /* $lxcpath + '/' + $name + '/partial' + \0 */
183 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
185 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
186 if (ret
< 0 || (size_t)ret
>= len
)
189 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
194 lk
.l_whence
= SEEK_SET
;
198 ret
= fcntl(fd
, F_SETLKW
, &lk
);
200 SYSERROR("Failed to lock partial file %s", path
);
208 static void remove_partial(struct lxc_container
*c
, int fd
)
215 /* $lxcpath + '/' + $name + '/partial' + \0 */
216 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
218 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
219 if (ret
< 0 || (size_t)ret
>= len
)
224 SYSERROR("Failed to remove partial file %s", path
);
228 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
229 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
230 * container configuration file.
231 * The container_disk_lock also takes the container_mem_lock.
232 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
233 * NOTHING mutexes two independent programs with their own struct
234 * lxc_container for the same c->name, between API calls. For instance,
235 * c->config_read(); c->start(); Between those calls, data on disk
236 * could change (which shouldn't bother the caller unless for instance
237 * the rootfs get moved). c->config_read(); update; c->config_write();
238 * Two such updaters could race. The callers should therefore check their
239 * results. Trying to prevent that would necessarily expose us to deadlocks
240 * due to hung callers. So I prefer to keep the locks only within our own
241 * functions, not across functions.
243 * If you're going to clone while holding a lxccontainer, increment
244 * c->numthreads (under privlock) before forking. When deleting,
245 * decrement numthreads under privlock, then if it hits 0 you can delete.
246 * Do not ever use a lxccontainer whose numthreads you did not bump.
249 static void lxc_container_free(struct lxc_container
*c
)
255 c
->configfile
= NULL
;
257 free(c
->error_string
);
258 c
->error_string
= NULL
;
261 lxc_putlock(c
->slock
);
266 lxc_putlock(c
->privlock
);
274 lxc_conf_free(c
->lxc_conf
);
278 free(c
->config_path
);
279 c
->config_path
= NULL
;
284 /* Consider the following case:
286 * |====================================================================|
287 * | freer | racing get()er |
288 * |====================================================================|
289 * | lxc_container_put() | lxc_container_get() |
290 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
291 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
292 * | \ lxcunlock() | \ |
293 * | \ lxc_container_free() | \ lxclock() returns |
294 * | | \ c->numthreads < 1 -> return 0 |
295 * | \ \ (free stuff) | |
296 * | \ \ sem_destroy(privlock) | |
297 * |_______________________________|____________________________________|
299 * When the get()er checks numthreads the first time, one of the following
301 * 1. freer has set numthreads = 0. get() returns 0
302 * 2. freer is between lxclock and setting numthreads to 0. get()er will
303 * sem_wait on privlock, get lxclock after freer() drops it, then see
304 * numthreads is 0 and exit without touching lxclock again..
305 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
306 * will see --numthreads = 1 and not call lxc_container_free().
309 int lxc_container_get(struct lxc_container
*c
)
314 /* If someone else has already started freeing the container, don't try
315 * to take the lock, which may be invalid.
317 if (c
->numthreads
< 1)
320 if (container_mem_lock(c
))
323 /* Bail without trying to unlock, bc the privlock is now probably in
326 if (c
->numthreads
< 1)
330 container_mem_unlock(c
);
335 int lxc_container_put(struct lxc_container
*c
)
340 if (container_mem_lock(c
))
343 if (--c
->numthreads
< 1) {
344 container_mem_unlock(c
);
345 lxc_container_free(c
);
349 container_mem_unlock(c
);
354 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
363 if (container_mem_lock(c
))
369 statret
= stat(c
->configfile
, &statbuf
);
376 container_mem_unlock(c
);
381 #define WRAP_API(rettype, fnname) \
382 static rettype fnname(struct lxc_container *c) \
385 bool reset_config = false; \
387 if (!current_config && c && c->lxc_conf) { \
388 current_config = c->lxc_conf; \
389 reset_config = true; \
392 ret = do_##fnname(c); \
394 current_config = NULL; \
399 #define WRAP_API_1(rettype, fnname, t1) \
400 static rettype fnname(struct lxc_container *c, t1 a1) \
403 bool reset_config = false; \
405 if (!current_config && c && c->lxc_conf) { \
406 current_config = c->lxc_conf; \
407 reset_config = true; \
410 ret = do_##fnname(c, a1); \
412 current_config = NULL; \
417 #define WRAP_API_2(rettype, fnname, t1, t2) \
418 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
421 bool reset_config = false; \
423 if (!current_config && c && c->lxc_conf) { \
424 current_config = c->lxc_conf; \
425 reset_config = true; \
428 ret = do_##fnname(c, a1, a2); \
430 current_config = NULL; \
435 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
436 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
439 bool reset_config = false; \
441 if (!current_config && c && c->lxc_conf) { \
442 current_config = c->lxc_conf; \
443 reset_config = true; \
446 ret = do_##fnname(c, a1, a2, a3); \
448 current_config = NULL; \
453 WRAP_API(bool, lxcapi_is_defined
)
455 static const char *do_lxcapi_state(struct lxc_container
*c
)
462 s
= lxc_getstate(c
->name
, c
->config_path
);
463 return lxc_state2str(s
);
466 WRAP_API(const char *, lxcapi_state
)
468 static bool is_stopped(struct lxc_container
*c
)
472 s
= lxc_getstate(c
->name
, c
->config_path
);
473 return (s
== STOPPED
);
476 static bool do_lxcapi_is_running(struct lxc_container
*c
)
483 s
= do_lxcapi_state(c
);
484 if (!s
|| strcmp(s
, "STOPPED") == 0)
490 WRAP_API(bool, lxcapi_is_running
)
492 static bool do_lxcapi_freeze(struct lxc_container
*c
)
499 ret
= lxc_freeze(c
->name
, c
->config_path
);
506 WRAP_API(bool, lxcapi_freeze
)
508 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
515 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
522 WRAP_API(bool, lxcapi_unfreeze
)
524 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
529 return lxc_console_getfd(c
, ttynum
, masterfd
);
532 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
534 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
535 int stdoutfd
, int stderrfd
, int escape
)
542 current_config
= c
->lxc_conf
;
543 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
544 current_config
= NULL
;
549 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
553 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
556 NOTICE("The console log is empty");
557 else if (ret
== -EFAULT
)
558 NOTICE("The container does not keep a console log");
559 else if (ret
== -ENOENT
)
560 NOTICE("The container does not keep a console log file");
561 else if (ret
== -EIO
)
562 NOTICE("Failed to write console log to log file");
564 ERROR("Failed to retrieve console log");
570 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
572 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
577 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
580 WRAP_API(pid_t
, lxcapi_init_pid
)
582 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
585 c
->lxc_conf
= lxc_conf_init();
590 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
596 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
600 bool need_disklock
= false, ret
= false;
605 fname
= c
->configfile
;
611 /* If we're reading something other than the container's config, we only
612 * need to lock the in-memory container. If loading the container's
613 * config file, take the disk lock.
615 if (strcmp(fname
, c
->configfile
) == 0)
616 need_disklock
= true;
619 lret
= container_disk_lock(c
);
621 lret
= container_mem_lock(c
);
625 ret
= load_config_locked(c
, fname
);
628 container_disk_unlock(c
);
630 container_mem_unlock(c
);
635 WRAP_API_1(bool, lxcapi_load_config
, const char *)
637 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
639 if (!c
|| !c
->lxc_conf
)
642 if (container_mem_lock(c
))
645 c
->daemonize
= state
;
646 container_mem_unlock(c
);
651 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
653 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
655 if (!c
|| !c
->lxc_conf
)
658 if (container_mem_lock(c
))
661 c
->lxc_conf
->close_all_fds
= state
;
662 container_mem_unlock(c
);
667 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
669 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
677 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
681 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
683 static bool am_single_threaded(void)
685 struct dirent
*direntp
;
689 dir
= opendir("/proc/self/task");
693 while ((direntp
= readdir(dir
))) {
694 if (!strcmp(direntp
->d_name
, "."))
697 if (!strcmp(direntp
->d_name
, ".."))
708 static void push_arg(char ***argp
, char *arg
, int *nargs
)
718 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
727 static char **split_init_cmd(const char *incmd
)
733 char *saveptr
= NULL
;
738 len
= strlen(incmd
) + 1;
740 strncpy(copy
, incmd
, len
);
741 copy
[len
- 1] = '\0';
744 argv
= malloc(sizeof(char *));
748 for (; (p
= strtok_r(copy
, " ", &saveptr
)); copy
= NULL
)
749 push_arg(&argv
, p
, &nargs
);
759 static void free_init_cmd(char **argv
)
772 static int lxc_rcv_status(int state_socket
)
778 /* Receive container state. */
779 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
,
784 TRACE("Caught EINTR; retrying");
791 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
795 /* Close write end of the socket pair. */
796 close(handler
->state_socket_pair
[1]);
797 handler
->state_socket_pair
[1] = -1;
799 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
801 /* Close read end of the socket pair. */
802 close(handler
->state_socket_pair
[0]);
803 handler
->state_socket_pair
[0] = -1;
805 /* The first child is going to fork() again and then exits. So we reap
806 * the first child here.
808 ret
= wait_for_pid(pid
);
810 DEBUG("Failed waiting on first child %d", pid
);
812 DEBUG("First child %d exited", pid
);
815 SYSERROR("Failed to receive the container state");
819 /* If we receive anything else then running we know that the container
822 if (state
!= RUNNING
) {
823 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
824 lxc_state2str(state
));
828 TRACE("Container is in \"RUNNING\" state");
832 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
835 struct lxc_handler
*handler
;
836 struct lxc_conf
*conf
;
837 bool daemonize
= false;
839 char *default_args
[] = {
843 char **init_cmd
= NULL
;
844 int keepfds
[3] = {-1, -1, -1};
846 /* container does exist */
850 /* If anything fails before we set error_num, we want an error in there.
854 /* Container has not been setup. */
858 ret
= ongoing_create(c
);
860 ERROR("Failed checking for incomplete container creation");
862 } else if (ret
== 1) {
863 ERROR("Ongoing container creation detected");
865 } else if (ret
== 2) {
866 ERROR("Failed to create container");
867 do_lxcapi_destroy(c
);
871 if (container_mem_lock(c
))
874 daemonize
= c
->daemonize
;
876 /* initialize handler */
877 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, daemonize
);
878 container_mem_unlock(c
);
883 if (useinit
&& conf
->execute_cmd
)
884 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
886 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
889 /* ... otherwise use default_args. */
892 ERROR("No valid init detected");
893 lxc_free_handler(handler
);
899 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
900 * here to protect the on disk container? We don't want to exclude
901 * things like lxc_info while the container is running.
910 free_init_cmd(init_cmd
);
911 lxc_free_handler(handler
);
917 /* Set to NULL because we don't want father unlink
918 * the PID file, child will do the free and unlink.
922 /* Wait for container to tell us whether it started
925 started
= wait_on_daemonized_start(handler
, pid
);
927 free_init_cmd(init_cmd
);
928 lxc_free_handler(handler
);
934 /* We don't really care if this doesn't print all the
935 * characters. All that it means is that the proctitle will be
936 * ugly. Similarly, we also don't care if setproctitle() fails.
938 snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
939 INFO("Attempting to set proc title to %s", title
);
942 /* We fork() a second time to be reparented to init. Like
943 * POSIX's daemon() function we change to "/" and redirect
944 * std{in,out,err} to /dev/null.
948 SYSERROR("Failed to fork first child process");
954 free_init_cmd(init_cmd
);
955 lxc_free_handler(handler
);
961 /* change to / directory */
964 SYSERROR("Failed to change to \"/\" directory");
968 keepfds
[0] = handler
->conf
->maincmd_fd
;
969 keepfds
[1] = handler
->state_socket_pair
[0];
970 keepfds
[2] = handler
->state_socket_pair
[1];
971 ret
= lxc_check_inherited(conf
, true, keepfds
,
972 sizeof(keepfds
) / sizeof(keepfds
[0]));
976 /* redirect std{in,out,err} to /dev/null */
979 ERROR("Failed to redirect std{in,out,err} to /dev/null");
983 /* become session leader */
986 TRACE("Process %d is already process group leader", lxc_raw_getpid());
988 if (!am_single_threaded()) {
989 ERROR("Cannot start non-daemonized container when threaded");
990 free_init_cmd(init_cmd
);
991 lxc_free_handler(handler
);
996 /* We need to write PID file after daemonize, so we always
997 * write the right PID.
1000 pid_fp
= fopen(c
->pidfile
, "w");
1001 if (pid_fp
== NULL
) {
1002 SYSERROR("Failed to create pidfile '%s' for '%s'",
1003 c
->pidfile
, c
->name
);
1004 free_init_cmd(init_cmd
);
1005 lxc_free_handler(handler
);
1007 _exit(EXIT_FAILURE
);
1011 if (fprintf(pid_fp
, "%d\n", lxc_raw_getpid()) < 0) {
1012 SYSERROR("Failed to write '%s'", c
->pidfile
);
1015 free_init_cmd(init_cmd
);
1016 lxc_free_handler(handler
);
1018 _exit(EXIT_FAILURE
);
1028 /* Unshare the mount namespace if requested */
1029 if (conf
->monitor_unshare
) {
1030 ret
= unshare(CLONE_NEWNS
);
1032 SYSERROR("failed to unshare mount namespace");
1033 lxc_free_handler(handler
);
1038 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1040 SYSERROR("Failed to make / rslave at startup");
1041 lxc_free_handler(handler
);
1048 if (conf
->reboot
== 2) {
1049 /* initialize handler */
1050 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, daemonize
);
1057 keepfds
[0] = handler
->conf
->maincmd_fd
;
1058 keepfds
[1] = handler
->state_socket_pair
[0];
1059 keepfds
[2] = handler
->state_socket_pair
[1];
1060 ret
= lxc_check_inherited(conf
, daemonize
, keepfds
,
1061 sizeof(keepfds
) / sizeof(keepfds
[0]));
1063 lxc_free_handler(handler
);
1069 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
, daemonize
);
1071 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
, daemonize
);
1072 c
->error_num
= handler
->exit_status
;
1074 if (conf
->reboot
== 1) {
1075 INFO("Container requested reboot");
1086 free_init_cmd(init_cmd
);
1088 if (daemonize
&& ret
!= 0)
1089 _exit(EXIT_FAILURE
);
1091 _exit(EXIT_SUCCESS
);
1099 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1104 current_config
= c
? c
->lxc_conf
: NULL
;
1105 ret
= do_lxcapi_start(c
, useinit
, argv
);
1106 current_config
= NULL
;
1111 /* Note, there MUST be an ending NULL. */
1112 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1115 char **inargs
= NULL
;
1118 /* container exists */
1122 current_config
= c
->lxc_conf
;
1124 va_start(ap
, useinit
);
1125 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1130 /* pass NULL if no arguments were supplied */
1131 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1136 for (arg
= inargs
; *arg
; arg
++)
1141 current_config
= NULL
;
1146 static bool do_lxcapi_stop(struct lxc_container
*c
)
1153 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1158 WRAP_API(bool, lxcapi_stop
)
1160 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1162 int ret
= -1, lasterr
;
1163 char *p
= alloca(strlen(path
)+1);
1164 mode_t mask
= umask(0002);
1165 ret
= mkdir(path
, 0770);
1170 if (errno
== EEXIST
)
1173 SYSERROR("failed to create container path %s", path
);
1178 if (!lxc_list_empty(&conf
->id_map
) && chown_mapped_root(p
, conf
) != 0) {
1179 ERROR("Failed to chown container dir");
1186 * create the standard expected container dir
1188 static bool create_container_dir(struct lxc_container
*c
)
1193 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1197 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1198 if (ret
< 0 || ret
>= len
) {
1202 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1207 /* do_storage_create: thin wrapper around storage_create(). Like
1208 * storage_create(), it returns a mounted bdev on success, NULL on error.
1210 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1212 struct bdev_specs
*specs
)
1217 struct lxc_storage
*bdev
;
1219 /* rootfs.path or lxcpath/lxcname/rootfs */
1220 if (c
->lxc_conf
->rootfs
.path
&&
1221 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1222 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1223 len
= strlen(rpath
) + 1;
1225 ret
= snprintf(dest
, len
, "%s", rpath
);
1227 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1228 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1230 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1232 if (ret
< 0 || (size_t)ret
>= len
)
1235 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1237 ERROR("Failed to create \"%s\" storage", type
);
1241 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1242 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1246 /* If we are not root, chown the rootfs dir to root in the target user
1250 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1251 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1253 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1254 suggest_default_idmap();
1263 static char *lxcbasename(char *path
)
1267 p
= path
+ strlen(path
) - 1;
1268 while (*p
!= '/' && p
> path
)
1274 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1275 bool need_null_stdfds
, char *const argv
[])
1285 SYSERROR("Failed to fork task for container creation template");
1289 if (pid
== 0) { /* child */
1291 char *namearg
, *patharg
, *rootfsarg
;
1294 struct lxc_storage
*bdev
= NULL
;
1295 struct lxc_conf
*conf
= c
->lxc_conf
;
1298 if (need_null_stdfds
) {
1299 ret
= null_stdfds();
1301 _exit(EXIT_FAILURE
);
1304 bdev
= storage_init(c
->lxc_conf
);
1306 ERROR("Failed to initialize storage");
1307 _exit(EXIT_FAILURE
);
1312 ret
= unshare(CLONE_NEWNS
);
1314 ERROR("Failed to unshare CLONE_NEWNS");
1315 _exit(EXIT_FAILURE
);
1318 ret
= detect_shared_rootfs();
1320 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1322 SYSERROR("Failed to make \"/\" rslave");
1323 ERROR("Continuing...");
1328 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1330 ERROR("Unprivileged users can only create "
1331 "btrfs and directory-backed containers");
1332 _exit(EXIT_FAILURE
);
1335 if (strcmp(bdev
->type
, "overlay") == 0 ||
1336 strcmp(bdev
->type
, "overlayfs") == 0) {
1337 /* If we create an overlay container we need to
1338 * rsync the contents into
1339 * <container-path>/<container-name>/rootfs.
1340 * However, the overlay mount function will
1342 * <container-path>/<container-name>/delta0
1344 * <container-path>/<container-name>/rootfs
1345 * which means we would rsync the rootfs into
1346 * the delta directory. That doesn't make sense
1347 * since the delta directory only exists to
1348 * record the differences to
1349 * <container-path>/<container-name>/rootfs. So
1350 * let's simply bind-mount here and then rsync
1352 * <container-path>/<container-name>/rootfs.
1356 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1358 ERROR("Failed to get rootfs");
1359 _exit(EXIT_FAILURE
);
1362 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1364 ERROR("Failed to mount rootfs");
1368 ret
= bdev
->ops
->mount(bdev
);
1370 ERROR("Failed to mount rootfs");
1371 _exit(EXIT_FAILURE
);
1374 } else { /* TODO come up with a better way here! */
1377 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1378 bdev
->dest
= strdup(src
);
1381 /* Create our new array, pre-pend the template name and base
1385 for (nargs
= 0; argv
[nargs
]; nargs
++) {
1388 /* template, path, rootfs and name args */
1391 newargv
= malloc(nargs
* sizeof(*newargv
));
1393 _exit(EXIT_FAILURE
);
1394 newargv
[0] = lxcbasename(tpath
);
1397 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1398 patharg
= malloc(len
);
1400 _exit(EXIT_FAILURE
);
1401 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1402 if (ret
< 0 || ret
>= len
)
1403 _exit(EXIT_FAILURE
);
1404 newargv
[1] = patharg
;
1407 len
= strlen("--name=") + strlen(c
->name
) + 1;
1408 namearg
= malloc(len
);
1410 _exit(EXIT_FAILURE
);
1411 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1412 if (ret
< 0 || ret
>= len
)
1413 _exit(EXIT_FAILURE
);
1414 newargv
[2] = namearg
;
1417 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1418 rootfsarg
= malloc(len
);
1420 _exit(EXIT_FAILURE
);
1421 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1422 if (ret
< 0 || ret
>= len
)
1423 _exit(EXIT_FAILURE
);
1424 newargv
[3] = rootfsarg
;
1426 /* add passed-in args */
1428 for (i
= 4; i
< nargs
; i
++)
1429 newargv
[i
] = argv
[i
- 4];
1431 /* add trailing NULL */
1433 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1435 _exit(EXIT_FAILURE
);
1436 newargv
[nargs
- 1] = NULL
;
1438 /* If we're running the template in a mapped userns, then we
1439 * prepend the template command with: lxc-usernsexec <-m map1>
1440 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1441 * the mapped uid for our geteuid()
1443 if (!lxc_list_empty(&conf
->id_map
)) {
1444 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1446 char txtuid
[20], txtgid
[20];
1447 struct lxc_list
*it
;
1451 n2
= malloc(n2args
* sizeof(*n2
));
1453 _exit(EXIT_FAILURE
);
1456 tpath
= "lxc-usernsexec";
1457 n2
[0] = "lxc-usernsexec";
1458 lxc_list_for_each(it
, &conf
->id_map
) {
1461 n2
= realloc(n2
, n2args
* sizeof(char *));
1463 _exit(EXIT_FAILURE
);
1465 n2
[n2args
- 2] = "-m";
1466 n2
[n2args
- 1] = malloc(200);
1467 if (!n2
[n2args
- 1])
1468 _exit(EXIT_FAILURE
);
1470 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1471 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1472 map
->nsid
, map
->hostid
, map
->range
);
1473 if (ret
< 0 || ret
>= 200)
1474 _exit(EXIT_FAILURE
);
1477 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1478 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1479 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1481 _exit(EXIT_FAILURE
);
1483 if (hostuid_mapped
< 0) {
1484 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1485 n2
[n2args
++] = "-m";
1486 if (hostuid_mapped
< 0) {
1487 ERROR("Failed to find free uid to map");
1488 _exit(EXIT_FAILURE
);
1491 n2
[n2args
++] = malloc(200);
1492 if (!n2
[n2args
- 1]) {
1493 SYSERROR("out of memory");
1494 _exit(EXIT_FAILURE
);
1496 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1497 hostuid_mapped
, geteuid());
1498 if (ret
< 0 || ret
>= 200)
1499 _exit(EXIT_FAILURE
);
1502 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1503 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1504 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1506 _exit(EXIT_FAILURE
);
1508 if (hostgid_mapped
< 0) {
1509 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1510 n2
[n2args
++] = "-m";
1511 if (hostgid_mapped
< 0) {
1512 ERROR("Failed to find free gid to map");
1513 _exit(EXIT_FAILURE
);
1516 n2
[n2args
++] = malloc(200);
1517 if (!n2
[n2args
- 1]) {
1518 SYSERROR("out of memory");
1519 _exit(EXIT_FAILURE
);
1522 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1523 hostgid_mapped
, getegid());
1524 if (ret
< 0 || ret
>= 200)
1525 _exit(EXIT_FAILURE
);
1527 n2
[n2args
++] = "--";
1528 for (i
= 0; i
< nargs
; i
++)
1529 n2
[i
+ n2args
] = newargv
[i
];
1532 /* Finally add "--mapped-uid $uid" to tell template what
1533 * to chown cached images to.
1536 n2
= realloc(n2
, n2args
* sizeof(char *));
1538 _exit(EXIT_FAILURE
);
1540 /* note n2[n2args-1] is NULL */
1541 n2
[n2args
- 5] = "--mapped-uid";
1542 snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1543 n2
[n2args
- 4] = txtuid
;
1544 n2
[n2args
- 3] = "--mapped-gid";
1545 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1546 n2
[n2args
- 2] = txtgid
;
1547 n2
[n2args
- 1] = NULL
;
1552 execvp(tpath
, newargv
);
1553 SYSERROR("Failed to execute template %s", tpath
);
1554 _exit(EXIT_FAILURE
);
1557 ret
= wait_for_pid(pid
);
1559 ERROR("Failed to create container from template");
1566 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1574 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1578 f
= fopen(path
, "r");
1582 if (fseek(f
, 0, SEEK_END
) < 0)
1584 if ((flen
= ftell(f
)) < 0)
1586 if (fseek(f
, 0, SEEK_SET
) < 0)
1588 if ((contents
= malloc(flen
+ 1)) == NULL
)
1590 if (fread(contents
, 1, flen
, f
) != flen
)
1591 goto out_free_contents
;
1593 contents
[flen
] = '\0';
1597 goto out_free_contents
;
1600 tpath
= get_template_path(t
);
1602 ERROR("bad template: %s", t
);
1603 goto out_free_contents
;
1606 ret
= sha1sum_file(tpath
, md_value
);
1608 ERROR("Error getting sha1sum of %s", tpath
);
1610 goto out_free_contents
;
1615 f
= fopen(path
, "w");
1617 SYSERROR("reopening config for writing");
1621 fprintf(f
, "# Template used to create this container: %s\n", t
);
1623 fprintf(f
, "# Parameters passed to the template:");
1625 fprintf(f
, " %s", *argv
);
1631 fprintf(f
, "# Template script checksum (SHA-1): ");
1632 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1633 fprintf(f
, "%02x", md_value
[i
]);
1636 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1637 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1638 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1639 fprintf(f
, "# (Be aware this has security implications)\n\n");
1640 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1641 SYSERROR("Writing original contents");
1657 SYSERROR("Error prepending header");
1663 static void lxcapi_clear_config(struct lxc_container
*c
)
1667 lxc_conf_free(c
->lxc_conf
);
1673 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1677 * create a container with the given parameters.
1678 * @c: container to be created. It has the lxcpath, name, and a starting
1679 * configuration already set
1680 * @t: the template to execute to instantiate the root filesystem and
1681 * adjust the configuration.
1682 * @bdevtype: backing store type to use. If NULL, dir will be used.
1683 * @specs: additional parameters for the backing store, i.e. LVM vg to
1686 * @argv: the arguments to pass to the template, terminated by NULL. If no
1687 * arguments, you can just pass NULL.
1689 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1690 const char *bdevtype
, struct bdev_specs
*specs
,
1691 int flags
, char *const argv
[])
1702 tpath
= get_template_path(t
);
1704 ERROR("Unknown template \"%s\"", t
);
1709 /* If a template is passed in, and the rootfs already is defined in the
1710 * container config and exists, then the caller is trying to create an
1711 * existing container. Return an error, but do NOT delete the container.
1713 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1714 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1715 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1721 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1722 ERROR("Error loading default configuration file %s",
1723 lxc_global_config_value("lxc.default_config"));
1728 if (!create_container_dir(c
))
1731 /* If both template and rootfs.path are set, template is setup as
1732 * rootfs.path. The container is already created if we have a config and
1733 * rootfs.path is accessible
1735 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1736 /* No template passed in and rootfs does not exist. */
1737 if (!c
->save_config(c
, NULL
)) {
1738 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1745 /* Rootfs passed into configuration, but does not exist. */
1746 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1749 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1750 /* Rootfs already existed, user just wanted to save the loaded
1753 if (!c
->save_config(c
, NULL
))
1754 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1759 /* Mark that this container is being created */
1760 partial_fd
= create_partial(c
);
1764 /* No need to get disk lock bc we have the partial lock. */
1766 /* Create the storage.
1767 * Note we can't do this in the same task as we use to execute the
1768 * template because of the way zfs works.
1769 * After you 'zfs create', zfs mounts the fs only in the initial
1774 SYSERROR("Failed to fork task for container creation template");
1778 if (pid
== 0) { /* child */
1779 struct lxc_storage
*bdev
= NULL
;
1781 bdev
= do_storage_create(c
, bdevtype
, specs
);
1783 ERROR("Failed to create %s storage for %s",
1784 bdevtype
? bdevtype
: "(none)", c
->name
);
1785 _exit(EXIT_FAILURE
);
1788 /* Save config file again to store the new rootfs location. */
1789 if (!do_lxcapi_save_config(c
, NULL
)) {
1790 ERROR("Failed to save initial config for %s", c
->name
);
1791 /* Parent task won't see the storage driver in the
1792 * config so we delete it.
1794 bdev
->ops
->umount(bdev
);
1795 bdev
->ops
->destroy(bdev
);
1796 _exit(EXIT_FAILURE
);
1798 _exit(EXIT_SUCCESS
);
1800 if (wait_for_pid(pid
) != 0)
1803 /* Reload config to get the rootfs. */
1804 lxc_conf_free(c
->lxc_conf
);
1806 if (!load_config_locked(c
, c
->configfile
))
1809 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1812 /* Now clear out the lxc_conf we have, reload from the created
1815 do_lxcapi_clear_config(c
);
1818 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1819 ERROR("Failed to prepend header to config file");
1823 ret
= load_config_locked(c
, c
->configfile
);
1826 if (partial_fd
>= 0)
1827 remove_partial(c
, partial_fd
);
1830 container_destroy(c
, NULL
);
1836 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1837 const char *bdevtype
, struct bdev_specs
*specs
,
1838 int flags
, char *const argv
[])
1841 current_config
= c
? c
->lxc_conf
: NULL
;
1842 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1843 current_config
= NULL
;
1847 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1850 int rebootsignal
= SIGINT
;
1854 if (!do_lxcapi_is_running(c
))
1856 pid
= do_lxcapi_init_pid(c
);
1859 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1860 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1861 if (kill(pid
, rebootsignal
) < 0) {
1862 WARN("Could not send signal %d to pid %d.", rebootsignal
, pid
);
1869 WRAP_API(bool, lxcapi_reboot
)
1871 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1875 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1876 lxc_state_t states
[MAX_STATE
] = {0};
1881 if (!do_lxcapi_is_running(c
))
1884 pid
= do_lxcapi_init_pid(c
);
1888 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1889 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1891 /* Add a new state client before sending the shutdown signal so that we
1892 * don't miss a state.
1895 states
[RUNNING
] = 2;
1896 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1901 if (state_client_fd
< 0)
1907 if (ret
< MAX_STATE
)
1911 /* Send reboot signal to container. */
1912 killret
= kill(pid
, rebootsignal
);
1914 WARN("Could not send signal %d to pid %d", rebootsignal
, pid
);
1915 if (state_client_fd
>= 0)
1916 close(state_client_fd
);
1919 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
1924 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
1925 close(state_client_fd
);
1929 TRACE("Received state \"%s\"", lxc_state2str(ret
));
1936 WRAP_API_1(bool, lxcapi_reboot2
, int)
1938 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1942 int haltsignal
= SIGPWR
, state_client_fd
= -1;
1943 lxc_state_t states
[MAX_STATE
] = {0};
1948 if (!do_lxcapi_is_running(c
))
1951 pid
= do_lxcapi_init_pid(c
);
1955 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
1956 if (task_blocking_signal(pid
, (SIGRTMIN
+ 3)))
1957 haltsignal
= (SIGRTMIN
+ 3);
1959 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1960 haltsignal
= c
->lxc_conf
->haltsignal
;
1962 /* Add a new state client before sending the shutdown signal so that we
1963 * don't miss a state.
1966 states
[STOPPED
] = 1;
1967 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1972 if (state_client_fd
< 0)
1978 if (ret
< MAX_STATE
)
1982 /* Send shutdown signal to container. */
1983 killret
= kill(pid
, haltsignal
);
1985 WARN("Could not send signal %d to pid %d", haltsignal
, pid
);
1986 if (state_client_fd
>= 0)
1987 close(state_client_fd
);
1990 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
1995 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
1996 close(state_client_fd
);
2000 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2007 WRAP_API_1(bool, lxcapi_shutdown
, int)
2009 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2010 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2019 current_config
= c
->lxc_conf
;
2022 * since we're going to wait for create to finish, I don't think we
2023 * need to get a copy of the arguments.
2025 va_start(ap
, flags
);
2026 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2029 ERROR("Failed to allocate memory");
2033 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2037 current_config
= NULL
;
2041 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2043 if (!strcmp(key
, "lxc.cgroup"))
2044 return clear_unexp_config_line(conf
, key
, true);
2046 if (!strcmp(key
, "lxc.network"))
2047 return clear_unexp_config_line(conf
, key
, true);
2049 if (!strcmp(key
, "lxc.net"))
2050 return clear_unexp_config_line(conf
, key
, true);
2052 /* Clear a network with a specific index. */
2053 if (!strncmp(key
, "lxc.net.", 8)) {
2058 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2060 return clear_unexp_config_line(conf
, key
, true);
2063 if (!strcmp(key
, "lxc.hook"))
2064 return clear_unexp_config_line(conf
, key
, true);
2066 return clear_unexp_config_line(conf
, key
, false);
2069 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2073 struct lxc_config_t
*config
;
2075 if (!c
|| !c
->lxc_conf
)
2078 if (container_mem_lock(c
))
2081 config
= lxc_get_config(key
);
2082 /* Verify that the config key exists and that it has a callback
2085 if (config
&& config
->clr
)
2086 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2088 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2090 container_mem_unlock(c
);
2094 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2096 static inline bool enter_net_ns(struct lxc_container
*c
)
2098 pid_t pid
= do_lxcapi_init_pid(c
);
2100 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
2101 if (!switch_to_ns(pid
, "user"))
2104 return switch_to_ns(pid
, "net");
2107 /* Used by qsort and bsearch functions for comparing names. */
2108 static inline int string_cmp(char **first
, char **second
)
2110 return strcmp(*first
, *second
);
2113 /* Used by qsort and bsearch functions for comparing container names. */
2114 static inline int container_cmp(struct lxc_container
**first
,
2115 struct lxc_container
**second
)
2117 return strcmp((*first
)->name
, (*second
)->name
);
2120 static bool add_to_array(char ***names
, char *cname
, int pos
)
2122 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2124 ERROR("Out of memory");
2129 newnames
[pos
] = strdup(cname
);
2133 /* Sort the arrray as we will use binary search on it. */
2134 qsort(newnames
, pos
+ 1, sizeof(char *),
2135 (int (*)(const void *, const void *))string_cmp
);
2140 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2143 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2145 ERROR("Out of memory");
2152 /* Sort the arrray as we will use binary search on it. */
2154 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2155 (int (*)(const void *, const void *))container_cmp
);
2160 static char** get_from_array(char ***names
, char *cname
, int size
)
2162 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2166 static bool array_contains(char ***names
, char *cname
, int size
) {
2167 if(get_from_array(names
, cname
, size
) != NULL
)
2172 static bool remove_from_array(char ***names
, char *cname
, int size
)
2174 char **result
= get_from_array(names
, cname
, size
);
2175 if (result
!= NULL
) {
2182 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2185 int i
, count
= 0, pipefd
[2];
2186 char **interfaces
= NULL
;
2187 char interface
[IFNAMSIZ
];
2189 if(pipe(pipefd
) < 0) {
2190 SYSERROR("pipe failed");
2196 SYSERROR("failed to fork task to get interfaces information");
2202 if (pid
== 0) { /* child */
2203 int ret
= 1, nbytes
;
2204 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2206 /* close the read-end of the pipe */
2209 if (!enter_net_ns(c
)) {
2210 SYSERROR("failed to enter namespace");
2214 /* Grab the list of interfaces */
2215 if (getifaddrs(&interfaceArray
)) {
2216 SYSERROR("failed to get interfaces list");
2220 /* Iterate through the interfaces */
2221 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2222 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2224 ERROR("write failed");
2233 freeifaddrs(interfaceArray
);
2235 /* close the write-end of the pipe, thus sending EOF to the reader */
2240 /* close the write-end of the pipe */
2243 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2244 interface
[IFNAMSIZ
- 1] = '\0';
2246 if (array_contains(&interfaces
, interface
, count
))
2249 if(!add_to_array(&interfaces
, interface
, count
))
2250 ERROR("Failed to add \"%s\" to array", interface
);
2255 if (wait_for_pid(pid
) != 0) {
2256 for(i
=0;i
<count
;i
++)
2257 free(interfaces
[i
]);
2262 /* close the read-end of the pipe */
2265 /* Append NULL to the array */
2267 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2272 WRAP_API(char **, lxcapi_get_interfaces
)
2274 static char** do_lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
2277 int i
, count
= 0, pipefd
[2];
2278 char **addresses
= NULL
;
2279 char address
[INET6_ADDRSTRLEN
];
2281 if(pipe(pipefd
) < 0) {
2282 SYSERROR("pipe failed");
2288 SYSERROR("failed to fork task to get container ips");
2294 if (pid
== 0) { /* child */
2295 int ret
= 1, nbytes
;
2296 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2297 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2298 void *tempAddrPtr
= NULL
;
2299 char *address
= NULL
;
2301 /* close the read-end of the pipe */
2304 if (!enter_net_ns(c
)) {
2305 SYSERROR("failed to enter namespace");
2309 /* Grab the list of interfaces */
2310 if (getifaddrs(&interfaceArray
)) {
2311 SYSERROR("failed to get interfaces list");
2315 /* Iterate through the interfaces */
2316 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2317 if (tempIfAddr
->ifa_addr
== NULL
)
2320 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2321 if (family
&& strcmp(family
, "inet"))
2323 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2326 if (family
&& strcmp(family
, "inet6"))
2329 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2332 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2335 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2337 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2340 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2342 addressOutputBuffer
,
2343 sizeof(addressOutputBuffer
));
2347 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2349 ERROR("write failed");
2358 freeifaddrs(interfaceArray
);
2360 /* close the write-end of the pipe, thus sending EOF to the reader */
2365 /* close the write-end of the pipe */
2368 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2369 if(!add_to_array(&addresses
, address
, count
))
2370 ERROR("PARENT: add_to_array failed");
2374 if (wait_for_pid(pid
) != 0) {
2375 for(i
=0;i
<count
;i
++)
2381 /* close the read-end of the pipe */
2384 /* Append NULL to the array */
2386 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2391 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2393 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2396 struct lxc_config_t
*config
;
2398 if (!c
|| !c
->lxc_conf
)
2401 if (container_mem_lock(c
))
2404 config
= lxc_get_config(key
);
2405 /* Verify that the config key exists and that it has a callback
2408 if (config
&& config
->get
)
2409 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2411 container_mem_unlock(c
);
2415 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2417 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2421 if (!c
|| !c
->lxc_conf
)
2423 if (container_mem_lock(c
))
2425 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2426 container_mem_unlock(c
);
2430 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2432 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2436 /* List all config items. */
2438 return lxc_list_config_items(retv
, inlen
);
2440 if (!c
|| !c
->lxc_conf
)
2443 if (container_mem_lock(c
))
2446 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2447 * This is an intelligent result to show which keys are valid given the
2448 * type of nic it is.
2450 if (strncmp(key
, "lxc.net.", 8) == 0)
2451 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2453 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2455 container_mem_unlock(c
);
2459 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2461 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2464 bool ret
= false, need_disklock
= false;
2467 alt_file
= c
->configfile
;
2471 /* If we haven't yet loaded a config, load the stock config. */
2473 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2474 ERROR("Error loading default configuration file %s "
2476 lxc_global_config_value("lxc.default_config"),
2482 if (!create_container_dir(c
))
2485 /* If we're writing to the container's config file, take the disk lock.
2486 * Otherwise just take the memlock to protect the struct lxc_container
2487 * while we're traversing it.
2489 if (strcmp(c
->configfile
, alt_file
) == 0)
2490 need_disklock
= true;
2493 lret
= container_disk_lock(c
);
2495 lret
= container_mem_lock(c
);
2500 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
2501 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2505 lret
= write_config(fd
, c
->lxc_conf
);
2514 container_disk_unlock(c
);
2516 container_mem_unlock(c
);
2521 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2524 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2530 char path
[MAXPATHLEN
];
2531 char newpath
[MAXPATHLEN
];
2532 int fd
, ret
, n
= 0, v
= 0;
2534 size_t len
= 0, bytes
= 0;
2536 if (container_disk_lock(c0
))
2539 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2540 if (ret
< 0 || ret
> MAXPATHLEN
)
2542 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2543 if (ret
< 0 || ret
> MAXPATHLEN
)
2546 /* If we find an lxc-snapshot file using the old format only listing the
2547 * number of snapshots we will keep using it. */
2548 f1
= fopen(path
, "r");
2550 n
= fscanf(f1
, "%d", &v
);
2552 if (n
== 1 && v
== 0) {
2559 f1
= fopen(path
, "w");
2562 if (fprintf(f1
, "%d\n", v
) < 0) {
2563 ERROR("Error writing new snapshots value");
2569 SYSERROR("Error writing to or closing snapshots file");
2573 /* Here we know that we have or can use an lxc-snapshot file
2574 * using the new format. */
2576 f1
= fopen(path
, "a");
2580 if (fprintf(f1
, "%s", newpath
) < 0) {
2581 ERROR("Error writing new snapshots entry");
2584 SYSERROR("Error writing to or closing snapshots file");
2590 SYSERROR("Error writing to or closing snapshots file");
2594 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2597 if (fstat(fd
, &fbuf
) < 0) {
2602 if (fbuf
.st_size
!= 0) {
2604 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2605 if (buf
== MAP_FAILED
) {
2606 SYSERROR("Failed to create mapping %s", path
);
2611 len
= strlen(newpath
);
2612 while ((del
= strstr((char *)buf
, newpath
))) {
2613 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2617 lxc_strmunmap(buf
, fbuf
.st_size
);
2618 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2619 SYSERROR("Failed to truncate file %s", path
);
2627 /* If the lxc-snapshot file is empty, remove it. */
2628 if (stat(path
, &fbuf
) < 0)
2630 if (!fbuf
.st_size
) {
2638 container_disk_unlock(c0
);
2642 static void strip_newline(char *p
)
2644 size_t len
= strlen(p
);
2647 if (p
[len
-1] == '\n')
2651 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2653 struct lxc_container
*p
;
2654 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2655 size_t pathlen
= 0, namelen
= 0;
2659 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2660 c
->config_path
, c
->name
);
2661 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2662 ERROR("Path name too long");
2665 f
= fopen(path
, "r");
2668 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2669 if (getline(&lxcname
, &namelen
, f
) == -1) {
2670 ERROR("badly formatted file %s", path
);
2673 strip_newline(lxcpath
);
2674 strip_newline(lxcname
);
2675 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2676 ERROR("Unable to find dependent container %s:%s",
2680 if (!mod_rdep(p
, c
, inc
))
2681 ERROR("Failed to update snapshots file for %s:%s",
2683 lxc_container_put(p
);
2691 static bool has_fs_snapshots(struct lxc_container
*c
)
2694 char path
[MAXPATHLEN
];
2699 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2701 if (ret
< 0 || ret
> MAXPATHLEN
)
2703 /* If the file doesn't exist there are no snapshots. */
2704 if (stat(path
, &fbuf
) < 0)
2708 f
= fopen(path
, "r");
2711 ret
= fscanf(f
, "%d", &v
);
2713 /* TODO: Figure out what to do with the return value of fscanf. */
2715 INFO("Container uses new lxc-snapshots format %s", path
);
2723 static bool has_snapshots(struct lxc_container
*c
)
2725 char path
[MAXPATHLEN
];
2726 struct dirent
*direntp
;
2730 if (!get_snappath_dir(c
, path
))
2732 dir
= opendir(path
);
2735 while ((direntp
= readdir(dir
))) {
2739 if (!strcmp(direntp
->d_name
, "."))
2742 if (!strcmp(direntp
->d_name
, ".."))
2751 static bool do_destroy_container(struct lxc_conf
*conf
) {
2754 if (am_guest_unpriv()) {
2755 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2756 "storage_destroy_wrapper");
2763 return storage_destroy(conf
);
2766 static int lxc_rmdir_onedev_wrapper(void *data
)
2768 char *arg
= (char *) data
;
2769 return lxc_rmdir_onedev(arg
, "snaps");
2772 static int lxc_unlink_exec_wrapper(void *data
)
2778 static bool container_destroy(struct lxc_container
*c
,
2779 struct lxc_storage
*storage
)
2783 struct lxc_conf
*conf
;
2788 if (!c
|| !do_lxcapi_is_defined(c
))
2792 if (container_disk_lock(c
))
2795 if (!is_stopped(c
)) {
2796 /* We should queue some sort of error - in c->error_string? */
2797 ERROR("container %s is not stopped", c
->name
);
2801 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2802 /* Start of environment variable setup for hooks */
2803 if (setenv("LXC_NAME", c
->name
, 1))
2804 SYSERROR("Failed to set environment variable for container name");
2806 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2807 SYSERROR("Failed to set environment variable for config path");
2809 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2810 SYSERROR("Failed to set environment variable for rootfs mount");
2812 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2813 SYSERROR("Failed to set environment variable for rootfs mount");
2815 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2816 SYSERROR("Failed to set environment variable for console path");
2818 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2819 SYSERROR("Failed to set environment variable for console log");
2820 /* End of environment variable setup for hooks */
2822 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2823 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2828 if (current_config
&& conf
== current_config
) {
2829 current_config
= NULL
;
2830 if (conf
->logfd
!= -1) {
2836 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2837 if (!do_destroy_container(conf
)) {
2838 ERROR("Error destroying rootfs for %s", c
->name
);
2841 INFO("Destroyed rootfs for %s", c
->name
);
2844 mod_all_rdeps(c
, false);
2846 p1
= do_lxcapi_get_config_path(c
);
2855 * strlen("config") = 6
2859 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
2862 ERROR("Failed to allocate memory");
2866 /* For an overlay container the rootfs is considered immutable and
2867 * cannot be removed when restoring from a snapshot.
2869 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
2870 !strcmp(storage
->type
, "overlayfs")) &&
2871 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
2872 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
2873 if (ret
< 0 || (size_t)ret
>= len
)
2876 if (am_guest_unpriv())
2877 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
2878 "lxc_unlink_exec_wrapper");
2882 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
2886 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
2892 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
2893 if (ret
< 0 || (size_t)ret
>= len
)
2895 if (am_guest_unpriv())
2896 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
2897 "lxc_rmdir_onedev_wrapper");
2899 ret
= lxc_rmdir_onedev(path
, "snaps");
2901 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
2905 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
2912 container_disk_unlock(c
);
2916 static bool do_lxcapi_destroy(struct lxc_container
*c
)
2918 if (!c
|| !lxcapi_is_defined(c
))
2920 if (has_snapshots(c
)) {
2921 ERROR("Container %s has snapshots; not removing", c
->name
);
2925 if (has_fs_snapshots(c
)) {
2926 ERROR("container %s has snapshots on its rootfs", c
->name
);
2930 return container_destroy(c
, NULL
);
2933 WRAP_API(bool, lxcapi_destroy
)
2935 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2937 if (!c
|| !lxcapi_is_defined(c
))
2939 if (!lxcapi_snapshot_destroy_all(c
)) {
2940 ERROR("Error deleting all snapshots");
2943 return lxcapi_destroy(c
);
2946 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
2948 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
2952 struct lxc_config_t
*config
;
2955 config
= lxc_get_config(key
);
2959 ret
= config
->set(key
, v
, conf
, NULL
);
2963 if (lxc_config_value_empty(v
))
2964 do_clear_unexp_config_line(conf
, key
);
2966 bret
= do_append_unexp_config_line(conf
, key
, v
);
2973 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
2979 c
->lxc_conf
= lxc_conf_init();
2984 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
2991 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
2998 if (container_mem_lock(c
))
3001 b
= do_set_config_item_locked(c
, key
, v
);
3003 container_mem_unlock(c
);
3007 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3009 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3011 if (!c
|| !c
->configfile
)
3013 return strdup(c
->configfile
);
3016 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3018 if (!c
|| !c
->config_path
)
3020 return (const char *)(c
->config_path
);
3025 * Just recalculate the c->configfile based on the
3026 * c->config_path, which must be set.
3027 * The lxc_container must be locked or not yet public.
3029 static bool set_config_filename(struct lxc_container
*c
)
3034 if (!c
->config_path
)
3037 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3038 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3039 newpath
= malloc(len
);
3043 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3044 if (ret
< 0 || ret
>= len
) {
3045 fprintf(stderr
, "Error printing out config file name\n");
3050 free(c
->configfile
);
3051 c
->configfile
= newpath
;
3056 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3060 char *oldpath
= NULL
;
3065 if (container_mem_lock(c
))
3070 ERROR("Out of memory setting new lxc path");
3076 oldpath
= c
->config_path
;
3079 /* Since we've changed the config path, we have to change the
3080 * config file name too */
3081 if (!set_config_filename(c
)) {
3082 ERROR("Out of memory setting new config filename");
3084 free(c
->config_path
);
3085 c
->config_path
= oldpath
;
3090 container_mem_unlock(c
);
3094 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3096 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3106 if (container_disk_lock(c
))
3109 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
3111 container_disk_unlock(c
);
3115 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3117 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3127 if (container_disk_lock(c
))
3130 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
3132 container_disk_unlock(c
);
3136 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3138 const char *lxc_get_global_config_item(const char *key
)
3140 return lxc_global_config_value(key
);
3143 const char *lxc_get_version(void)
3148 static int copy_file(const char *old
, const char *new)
3155 if (file_exists(new)) {
3156 ERROR("copy destination %s exists", new);
3159 ret
= stat(old
, &sbuf
);
3161 INFO("Error stat'ing %s", old
);
3165 in
= open(old
, O_RDONLY
);
3167 SYSERROR("Error opening original file %s", old
);
3170 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3172 SYSERROR("Error opening new file %s", new);
3178 len
= read(in
, buf
, 8096);
3180 SYSERROR("Error reading old file %s", old
);
3185 ret
= write(out
, buf
, len
);
3186 if (ret
< len
) { /* should we retry? */
3187 SYSERROR("Error: write to new file %s was interrupted", new);
3194 /* We set mode, but not owner/group. */
3195 ret
= chmod(new, sbuf
.st_mode
);
3197 SYSERROR("Error setting mode on %s", new);
3209 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3212 struct lxc_list
*it
;
3215 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3216 cpath
= alloca(len
);
3217 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3218 if (ret
< 0 || ret
>= len
)
3221 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3222 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3223 char *hookname
= it
->elem
;
3224 char *fname
= strrchr(hookname
, '/');
3225 char tmppath
[MAXPATHLEN
];
3226 if (!fname
) /* relative path - we don't support, but maybe we should */
3228 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3229 /* this hook is public - ignore */
3232 /* copy the script, and change the entry in confile */
3233 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3234 c
->config_path
, c
->name
, fname
+1);
3235 if (ret
< 0 || ret
>= MAXPATHLEN
)
3237 ret
= copy_file(it
->elem
, tmppath
);
3241 it
->elem
= strdup(tmppath
);
3243 ERROR("out of memory copying hook path");
3249 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3250 c
->config_path
, oldc
->name
, c
->name
)) {
3251 ERROR("Error saving new hooks in clone");
3254 do_lxcapi_save_config(c
, NULL
);
3259 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3261 char newpath
[MAXPATHLEN
];
3262 char *oldpath
= oldc
->lxc_conf
->fstab
;
3268 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3270 char *p
= strrchr(oldpath
, '/');
3273 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3274 c
->config_path
, c
->name
, p
);
3275 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3276 ERROR("error printing new path for %s", oldpath
);
3279 if (file_exists(newpath
)) {
3280 ERROR("error: fstab file %s exists", newpath
);
3284 if (copy_file(oldpath
, newpath
) < 0) {
3285 ERROR("error: copying %s to %s", oldpath
, newpath
);
3288 free(c
->lxc_conf
->fstab
);
3289 c
->lxc_conf
->fstab
= strdup(newpath
);
3290 if (!c
->lxc_conf
->fstab
) {
3291 ERROR("error: allocating pathname");
3294 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3295 ERROR("error saving new lxctab");
3302 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3304 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3307 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3309 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3310 WARN("Error copying reverse dependencies");
3313 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3315 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3316 WARN("Error copying reverse dependencies");
3319 if (copy_file(path0
, path1
) < 0) {
3320 INFO("Error copying reverse dependencies");
3325 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3328 char path
[MAXPATHLEN
];
3332 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3334 if (ret
< 0 || ret
>= MAXPATHLEN
)
3336 f
= fopen(path
, "a");
3340 /* If anything goes wrong, just return an error. */
3341 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3349 * If the fs natively supports snapshot clones with no penalty,
3350 * then default to those even if not requested.
3351 * Currently we only do this for btrfs.
3353 bool should_default_to_snapshot(struct lxc_container
*c0
,
3354 struct lxc_container
*c1
)
3356 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3357 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3358 char *p0
= alloca(l0
+ 1);
3359 char *p1
= alloca(l1
+ 1);
3360 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3362 snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3363 snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3365 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3368 if (is_btrfs_subvol(rootfs
) <= 0)
3371 return btrfs_same_fs(p0
, p1
) == 0;
3374 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3375 const char *newtype
, int flags
, const char *bdevdata
,
3378 struct lxc_storage
*bdev
;
3381 if (should_default_to_snapshot(c0
, c
))
3382 flags
|= LXC_CLONE_SNAPSHOT
;
3384 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3385 bdevdata
, newsize
, &need_rdep
);
3387 ERROR("Error copying storage.");
3391 /* Set new rootfs. */
3392 free(c
->lxc_conf
->rootfs
.path
);
3393 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3396 if (!c
->lxc_conf
->rootfs
.path
) {
3397 ERROR("Out of memory while setting storage path.");
3401 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3402 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3403 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3404 c
->lxc_conf
->rootfs
.path
)) {
3405 ERROR("Error saving new rootfs to cloned config.");
3409 if (flags
& LXC_CLONE_SNAPSHOT
)
3410 copy_rdepends(c
, c0
);
3412 if (!add_rdepends(c
, c0
))
3413 WARN("Error adding reverse dependency from %s to %s",
3417 mod_all_rdeps(c
, true);
3422 struct clone_update_data
{
3423 struct lxc_container
*c0
;
3424 struct lxc_container
*c1
;
3429 static int clone_update_rootfs(struct clone_update_data
*data
)
3431 struct lxc_container
*c0
= data
->c0
;
3432 struct lxc_container
*c
= data
->c1
;
3433 int flags
= data
->flags
;
3434 char **hookargs
= data
->hookargs
;
3436 char path
[MAXPATHLEN
];
3437 struct lxc_storage
*bdev
;
3439 struct lxc_conf
*conf
= c
->lxc_conf
;
3441 /* update hostname in rootfs */
3442 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3444 if (setgid(0) < 0) {
3445 ERROR("Failed to setgid to 0");
3448 if (setuid(0) < 0) {
3449 ERROR("Failed to setuid to 0");
3452 if (setgroups(0, NULL
) < 0)
3453 WARN("Failed to clear groups");
3455 if (unshare(CLONE_NEWNS
) < 0)
3457 bdev
= storage_init(c
->lxc_conf
);
3460 if (strcmp(bdev
->type
, "dir") != 0) {
3461 if (unshare(CLONE_NEWNS
) < 0) {
3462 ERROR("error unsharing mounts");
3466 if (detect_shared_rootfs()) {
3467 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3468 SYSERROR("Failed to make / rslave");
3469 ERROR("Continuing...");
3472 if (bdev
->ops
->mount(bdev
) < 0) {
3476 } else { /* TODO come up with a better way */
3478 bdev
->dest
= strdup(bdev
->src
);
3481 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3482 /* Start of environment variable setup for hooks */
3483 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1)) {
3484 SYSERROR("failed to set environment variable for source container name");
3486 if (setenv("LXC_NAME", c
->name
, 1)) {
3487 SYSERROR("failed to set environment variable for container name");
3489 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
3490 SYSERROR("failed to set environment variable for config path");
3492 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
3493 SYSERROR("failed to set environment variable for rootfs mount");
3495 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
3496 SYSERROR("failed to set environment variable for rootfs mount");
3499 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3500 ERROR("Error executing clone hook for %s", c
->name
);
3506 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3507 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3510 if (ret
< 0 || ret
>= MAXPATHLEN
)
3512 if (!file_exists(path
))
3514 if (!(fout
= fopen(path
, "w"))) {
3515 SYSERROR("unable to open %s: ignoring", path
);
3518 if (fprintf(fout
, "%s", c
->name
) < 0) {
3522 if (fclose(fout
) < 0)
3531 static int clone_update_rootfs_wrapper(void *data
)
3533 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3534 return clone_update_rootfs(arg
);
3538 * We want to support:
3539 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3540 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3542 -s [ implies overlay]
3546 only rootfs gets converted (copied/snapshotted) on clone.
3549 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3551 char *p
= strrchr(path
, '/');
3557 ret
= do_create_container_dir(path
, conf
);
3562 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3563 const char *lxcpath
, int flags
,
3564 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3567 char newpath
[MAXPATHLEN
];
3569 struct clone_update_data data
;
3570 size_t saved_unexp_len
;
3572 int storage_copied
= 0;
3573 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3574 struct lxc_container
*c2
= NULL
;
3576 if (!c
|| !do_lxcapi_is_defined(c
))
3579 if (container_mem_lock(c
))
3582 if (!is_stopped(c
)) {
3583 ERROR("error: Original container (%s) is running", c
->name
);
3587 /* Make sure the container doesn't yet exist. */
3591 lxcpath
= do_lxcapi_get_config_path(c
);
3592 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3593 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3594 SYSERROR("clone: failed making config pathname");
3598 if (file_exists(newpath
)) {
3599 ERROR("error: clone: %s exists", newpath
);
3603 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3604 if (ret
< 0 && errno
!= EEXIST
) {
3605 ERROR("Error creating container dir for %s", newpath
);
3609 /* Copy the configuration. Tweak it as needed. */
3610 if (c
->lxc_conf
->rootfs
.path
) {
3611 origroot
= c
->lxc_conf
->rootfs
.path
;
3612 c
->lxc_conf
->rootfs
.path
= NULL
;
3615 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3616 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3618 SYSERROR("Failed to open \"%s\"", newpath
);
3622 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3623 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3624 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3625 if (!c
->lxc_conf
->unexpanded_config
) {
3630 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3631 write_config(fd
, c
->lxc_conf
);
3633 c
->lxc_conf
->rootfs
.path
= origroot
;
3634 free(c
->lxc_conf
->unexpanded_config
);
3635 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3636 saved_unexp_conf
= NULL
;
3637 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3639 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3640 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3641 SYSERROR("clone: failed making rootfs pathname");
3645 ret
= mkdir(newpath
, 0755);
3647 /* For an overlay container the rootfs is considered immutable
3648 * and will not have been removed when restoring from a
3651 if (errno
!= ENOENT
&&
3652 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3653 SYSERROR("Failed to create directory \"%s\"", newpath
);
3658 if (am_guest_unpriv()) {
3659 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3660 ERROR("Error chowning %s to container root", newpath
);
3665 c2
= lxc_container_new(newname
, lxcpath
);
3667 ERROR("clone: failed to create new container (%s %s)", newname
,
3672 /* copy/snapshot rootfs's */
3673 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3678 /* update utsname */
3679 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3680 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3681 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3683 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3684 ERROR("Error setting new hostname");
3690 ret
= copyhooks(c
, c2
);
3692 ERROR("error copying hooks");
3696 if (copy_fstab(c
, c2
) < 0) {
3697 ERROR("error copying fstab");
3701 /* update macaddrs */
3702 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3703 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3704 ERROR("Error updating mac addresses");
3709 /* Update absolute paths for overlay mount directories. */
3710 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3713 /* We've now successfully created c2's storage, so clear it out if we
3718 if (!c2
->save_config(c2
, NULL
))
3721 if ((pid
= fork()) < 0) {
3726 ret
= wait_for_pid(pid
);
3729 container_mem_unlock(c
);
3735 data
.hookargs
= hookargs
;
3736 if (am_guest_unpriv())
3737 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3738 &data
, "clone_update_rootfs_wrapper");
3740 ret
= clone_update_rootfs(&data
);
3742 _exit(EXIT_FAILURE
);
3744 container_mem_unlock(c
);
3745 _exit(EXIT_SUCCESS
);
3748 container_mem_unlock(c
);
3750 if (!storage_copied
)
3751 c2
->lxc_conf
->rootfs
.path
= NULL
;
3753 lxc_container_put(c2
);
3759 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3760 const char *lxcpath
, int flags
,
3761 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3764 struct lxc_container
* ret
;
3765 current_config
= c
? c
->lxc_conf
: NULL
;
3766 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3767 current_config
= NULL
;
3771 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3773 struct lxc_storage
*bdev
;
3774 struct lxc_container
*newc
;
3776 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3779 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3780 ERROR("Renaming a container with snapshots is not supported");
3783 bdev
= storage_init(c
->lxc_conf
);
3785 ERROR("Failed to find original backing store type");
3789 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3792 lxc_container_put(newc
);
3796 if (newc
&& lxcapi_is_defined(newc
))
3797 lxc_container_put(newc
);
3799 if (!container_destroy(c
, NULL
)) {
3800 ERROR("Could not destroy existing container %s", c
->name
);
3806 WRAP_API_1(bool, lxcapi_rename
, const char *)
3808 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
)
3815 current_config
= c
->lxc_conf
;
3817 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
3818 current_config
= NULL
;
3822 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3824 lxc_attach_command_t command
;
3831 command
.program
= (char*)program
;
3832 command
.argv
= (char**)argv
;
3833 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
3838 return lxc_wait_for_pid_status(pid
);
3841 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3844 current_config
= c
? c
->lxc_conf
: NULL
;
3845 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
3846 current_config
= NULL
;
3850 static int get_next_index(const char *lxcpath
, char *cname
)
3856 fname
= alloca(strlen(lxcpath
) + 20);
3858 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
3859 ret
= stat(fname
, &sb
);
3866 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
3870 * If the old style snapshot path exists, use it
3871 * /var/lib/lxc -> /var/lib/lxcsnaps
3873 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
3874 if (ret
< 0 || ret
>= MAXPATHLEN
)
3876 if (dir_exists(snappath
)) {
3877 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3878 if (ret
< 0 || ret
>= MAXPATHLEN
)
3884 * Use the new style path
3885 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3887 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
3888 if (ret
< 0 || ret
>= MAXPATHLEN
)
3893 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
3896 struct lxc_container
*c2
;
3897 char snappath
[MAXPATHLEN
], newname
[20];
3899 if (!c
|| !lxcapi_is_defined(c
))
3902 if (!storage_can_backup(c
->lxc_conf
)) {
3903 ERROR("%s's backing store cannot be backed up.", c
->name
);
3904 ERROR("Your container must use another backing store type.");
3908 if (!get_snappath_dir(c
, snappath
))
3911 i
= get_next_index(snappath
, c
->name
);
3913 if (mkdir_p(snappath
, 0755) < 0) {
3914 ERROR("Failed to create snapshot directory %s", snappath
);
3918 ret
= snprintf(newname
, 20, "snap%d", i
);
3919 if (ret
< 0 || ret
>= 20)
3923 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3924 * created in the original container
3926 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
3927 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
3928 if (storage_is_dir(c
->lxc_conf
)) {
3929 ERROR("Snapshot of directory-backed container requested.");
3930 ERROR("Making a copy-clone. If you do want snapshots, then");
3931 ERROR("please create an aufs or overlay clone first, snapshot that");
3932 ERROR("and keep the original container pristine.");
3933 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3935 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
3937 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
3941 lxc_container_put(c2
);
3943 /* Now write down the creation time. */
3950 tm_info
= localtime(&timer
);
3952 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
3954 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
3955 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
3956 f
= fopen(dfnam
, "w");
3958 ERROR("Failed to open %s", dfnam
);
3961 if (fprintf(f
, "%s", buffer
) < 0) {
3962 SYSERROR("Writing timestamp");
3968 SYSERROR("Writing timestamp");
3973 /* $p / $name / comment \0 */
3974 int len
= strlen(snappath
) + strlen(newname
) + 10;
3975 char *path
= alloca(len
);
3976 sprintf(path
, "%s/%s/comment", snappath
, newname
);
3977 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
3983 WRAP_API_1(int, lxcapi_snapshot
, const char *)
3985 static void lxcsnap_free(struct lxc_snapshot
*s
)
3988 free(s
->comment_pathname
);
3993 static char *get_snapcomment_path(char* snappath
, char *name
)
3995 /* $snappath/$name/comment */
3996 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
3997 char *s
= malloc(len
);
4000 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4001 if (ret
< 0 || ret
>= len
) {
4009 static char *get_timestamp(char* snappath
, char *name
)
4011 char path
[MAXPATHLEN
], *s
= NULL
;
4015 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4016 if (ret
< 0 || ret
>= MAXPATHLEN
)
4018 fin
= fopen(path
, "r");
4021 (void) fseek(fin
, 0, SEEK_END
);
4023 (void) fseek(fin
, 0, SEEK_SET
);
4028 if (fread(s
, 1, len
, fin
) != len
) {
4029 SYSERROR("reading timestamp");
4039 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4041 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4043 struct dirent
*direntp
;
4044 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4047 if (!c
|| !lxcapi_is_defined(c
))
4050 if (!get_snappath_dir(c
, snappath
)) {
4051 ERROR("path name too long");
4054 dir
= opendir(snappath
);
4056 INFO("failed to open %s - assuming no snapshots", snappath
);
4060 while ((direntp
= readdir(dir
))) {
4064 if (!strcmp(direntp
->d_name
, "."))
4067 if (!strcmp(direntp
->d_name
, ".."))
4070 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4071 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4072 ERROR("pathname too long");
4075 if (!file_exists(path2
))
4077 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4079 SYSERROR("Out of memory");
4083 snaps
[count
].free
= lxcsnap_free
;
4084 snaps
[count
].name
= strdup(direntp
->d_name
);
4085 if (!snaps
[count
].name
)
4087 snaps
[count
].lxcpath
= strdup(snappath
);
4088 if (!snaps
[count
].lxcpath
) {
4089 free(snaps
[count
].name
);
4092 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4093 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4098 WARN("failed to close directory");
4106 for (i
=0; i
<count
; i
++)
4107 lxcsnap_free(&snaps
[i
]);
4111 WARN("failed to close directory");
4115 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4117 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4119 char clonelxcpath
[MAXPATHLEN
];
4121 struct lxc_container
*snap
, *rest
;
4122 struct lxc_storage
*bdev
;
4125 if (!c
|| !c
->name
|| !c
->config_path
)
4128 if (has_fs_snapshots(c
)) {
4129 ERROR("container rootfs has dependent snapshots");
4133 bdev
= storage_init(c
->lxc_conf
);
4135 ERROR("Failed to find original backing store type");
4139 /* For an overlay container the rootfs is considered immutable
4140 * and cannot be removed when restoring from a snapshot. We pass this
4141 * internal flag along to communicate this to various parts of the
4144 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4145 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4150 if (!get_snappath_dir(c
, clonelxcpath
)) {
4154 /* how should we lock this? */
4156 snap
= lxc_container_new(snapname
, clonelxcpath
);
4157 if (!snap
|| !lxcapi_is_defined(snap
)) {
4158 ERROR("Could not open snapshot %s", snapname
);
4160 lxc_container_put(snap
);
4165 if (!strcmp(c
->name
, newname
)) {
4166 if (!container_destroy(c
, bdev
)) {
4167 ERROR("Could not destroy existing container %s", newname
);
4168 lxc_container_put(snap
);
4174 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4175 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4177 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4178 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4179 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4182 if (rest
&& lxcapi_is_defined(rest
))
4185 lxc_container_put(rest
);
4187 lxc_container_put(snap
);
4191 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4193 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4195 struct lxc_container
*snap
= NULL
;
4198 snap
= lxc_container_new(snapname
, clonelxcpath
);
4200 ERROR("Could not find snapshot %s", snapname
);
4204 if (!do_lxcapi_destroy(snap
)) {
4205 ERROR("Could not destroy snapshot %s", snapname
);
4212 lxc_container_put(snap
);
4216 static bool remove_all_snapshots(const char *path
)
4219 struct dirent
*direntp
;
4222 dir
= opendir(path
);
4224 SYSERROR("opendir on snapshot path %s", path
);
4227 while ((direntp
= readdir(dir
))) {
4228 if (!strcmp(direntp
->d_name
, "."))
4230 if (!strcmp(direntp
->d_name
, ".."))
4232 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4241 SYSERROR("Error removing directory %s", path
);
4246 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4248 char clonelxcpath
[MAXPATHLEN
];
4250 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4253 if (!get_snappath_dir(c
, clonelxcpath
))
4256 return do_snapshot_destroy(snapname
, clonelxcpath
);
4259 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4261 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4263 char clonelxcpath
[MAXPATHLEN
];
4265 if (!c
|| !c
->name
|| !c
->config_path
)
4268 if (!get_snappath_dir(c
, clonelxcpath
))
4271 return remove_all_snapshots(clonelxcpath
);
4274 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4276 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4278 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4281 WRAP_API(bool, lxcapi_may_control
)
4283 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4289 char chrootpath
[MAXPATHLEN
];
4290 char *directory_path
= NULL
;
4294 SYSERROR("Failed to fork()");
4299 ret
= wait_for_pid(pid
);
4301 ERROR("Failed to create device node");
4308 /* prepare the path */
4309 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4310 if (ret
< 0 || ret
>= MAXPATHLEN
)
4313 ret
= chroot(chrootpath
);
4315 _exit(EXIT_FAILURE
);
4319 _exit(EXIT_FAILURE
);
4321 /* remove path if it exists */
4322 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4326 ERROR("%s - Failed to remove \"%s\"", strerror(errno
), path
);
4327 _exit(EXIT_FAILURE
);
4332 _exit(EXIT_SUCCESS
);
4334 /* create any missing directories */
4337 _exit(EXIT_FAILURE
);
4339 directory_path
= dirname(tmp
);
4340 ret
= mkdir_p(directory_path
, 0755);
4341 if (ret
< 0 && errno
!= EEXIST
) {
4342 ERROR("%s - Failed to create path \"%s\"", strerror(errno
), directory_path
);
4344 _exit(EXIT_FAILURE
);
4347 /* create the device node */
4348 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4351 ERROR("%s - Failed to create device node at \"%s\"", strerror(errno
), path
);
4352 _exit(EXIT_FAILURE
);
4355 _exit(EXIT_SUCCESS
);
4358 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4362 char value
[LXC_MAX_BUFFER
];
4365 /* make sure container is running */
4366 if (!do_lxcapi_is_running(c
)) {
4367 ERROR("container is not running");
4371 /* use src_path if dest_path is NULL otherwise use dest_path */
4372 p
= dest_path
? dest_path
: src_path
;
4374 /* make sure we can access p */
4375 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4378 /* continue if path is character device or block device */
4379 if (S_ISCHR(st
.st_mode
))
4380 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4381 else if (S_ISBLK(st
.st_mode
))
4382 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4386 /* check snprintf return code */
4387 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4390 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4393 /* add or remove device to/from cgroup access list */
4395 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4396 ERROR("set_cgroup_item failed while adding the device node");
4400 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4401 ERROR("set_cgroup_item failed while removing the device node");
4409 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4411 // cannot mknod if we're not privileged wrt init_user_ns
4412 if (am_host_unpriv()) {
4413 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4416 return add_remove_device_node(c
, src_path
, dest_path
, true);
4419 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4421 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4423 if (am_guest_unpriv()) {
4424 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4427 return add_remove_device_node(c
, src_path
, dest_path
, false);
4430 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4432 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4434 const char *dst_ifname
)
4439 if (am_guest_unpriv()) {
4440 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4445 ERROR("No source interface name given");
4449 ret
= lxc_netdev_isup(ifname
);
4451 /* netdev of ifname is up. */
4452 ret
= lxc_netdev_down(ifname
);
4457 init_pid
= do_lxcapi_init_pid(c
);
4458 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4462 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4469 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4471 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4473 const char *dst_ifname
)
4476 pid_t pid
, pid_outside
;
4479 * TODO - if this is a physical device, then we need am_host_unpriv.
4480 * But for other types guest privilege suffices.
4482 if (am_guest_unpriv()) {
4483 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4488 ERROR("No source interface name given");
4492 pid_outside
= lxc_raw_getpid();
4495 ERROR("Failed to fork");
4499 if (pid
== 0) { /* child */
4502 init_pid
= do_lxcapi_init_pid(c
);
4503 if (!switch_to_ns(init_pid
, "net")) {
4504 ERROR("Failed to enter network namespace");
4505 _exit(EXIT_FAILURE
);
4508 ret
= lxc_netdev_isup(ifname
);
4510 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4511 _exit(EXIT_FAILURE
);
4514 /* netdev of ifname is up. */
4516 ret
= lxc_netdev_down(ifname
);
4518 ERROR("Failed to set network device \"%s\" down", ifname
);
4519 _exit(EXIT_FAILURE
);
4523 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4524 /* -EINVAL means there is no netdev named as ifname. */
4527 ERROR("Network device \"%s\" not found", ifname
);
4529 ERROR("Failed to remove network device \"%s\"", ifname
);
4530 _exit(EXIT_FAILURE
);
4533 _exit(EXIT_SUCCESS
);
4536 ret
= wait_for_pid(pid
);
4540 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4544 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4546 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4547 struct migrate_opts
*opts
, unsigned int size
)
4550 struct migrate_opts
*valid_opts
= opts
;
4551 uint64_t features_to_check
= 0;
4553 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4554 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4555 * to do anything special.
4557 if (size
> sizeof(*opts
)) {
4558 unsigned char *addr
;
4561 addr
= (void *)opts
+ sizeof(*opts
);
4562 end
= (void *)opts
+ size
;
4563 for (; addr
< end
; addr
++) {
4570 /* If the caller has a smaller struct, let's zero out the end for them
4571 * so we don't accidentally use bits of it that they didn't know about
4574 if (size
< sizeof(*opts
)) {
4575 valid_opts
= malloc(sizeof(*opts
));
4579 memset(valid_opts
, 0, sizeof(*opts
));
4580 memcpy(valid_opts
, opts
, size
);
4584 case MIGRATE_PRE_DUMP
:
4585 if (!do_lxcapi_is_running(c
)) {
4586 ERROR("container is not running");
4589 ret
= !__criu_pre_dump(c
, valid_opts
);
4592 if (!do_lxcapi_is_running(c
)) {
4593 ERROR("container is not running");
4596 ret
= !__criu_dump(c
, valid_opts
);
4598 case MIGRATE_RESTORE
:
4599 if (do_lxcapi_is_running(c
)) {
4600 ERROR("container is already running");
4603 ret
= !__criu_restore(c
, valid_opts
);
4605 case MIGRATE_FEATURE_CHECK
:
4606 features_to_check
= valid_opts
->features_to_check
;
4607 ret
= !__criu_check_feature(&features_to_check
);
4609 /* Something went wrong. Let's let the caller
4610 * know which feature checks failed. */
4611 valid_opts
->features_to_check
= features_to_check
;
4615 ERROR("invalid migrate command %u", cmd
);
4620 if (size
< sizeof(*opts
))
4626 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4628 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4630 struct migrate_opts opts
;
4632 memset(&opts
, 0, sizeof(opts
));
4634 opts
.directory
= directory
;
4636 opts
.verbose
= verbose
;
4638 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4641 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4643 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4645 struct migrate_opts opts
;
4647 memset(&opts
, 0, sizeof(opts
));
4649 opts
.directory
= directory
;
4650 opts
.verbose
= verbose
;
4652 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4655 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4657 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4666 current_config
= c
->lxc_conf
;
4669 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4673 ERROR("Memory allocation error.");
4679 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4682 current_config
= NULL
;
4686 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4688 struct lxc_container
*c
;
4693 c
= malloc(sizeof(*c
));
4695 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4698 memset(c
, 0, sizeof(*c
));
4701 c
->config_path
= strdup(configpath
);
4703 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4705 if (!c
->config_path
) {
4706 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4710 remove_trailing_slashes(c
->config_path
);
4711 c
->name
= malloc(strlen(name
)+1);
4713 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4716 strcpy(c
->name
, name
);
4719 c
->slock
= lxc_newlock(c
->config_path
, name
);
4721 fprintf(stderr
, "Failed to create lock for %s\n", name
);
4725 c
->privlock
= lxc_newlock(NULL
, NULL
);
4727 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
4731 if (!set_config_filename(c
)) {
4732 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
4736 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
4737 fprintf(stderr
, "Failed to load config for %s\n", name
);
4741 if (ongoing_create(c
) == 2) {
4742 ERROR("Failed to complete container creation for %s", c
->name
);
4743 container_destroy(c
, NULL
);
4744 lxcapi_clear_config(c
);
4746 c
->daemonize
= true;
4749 /* Assign the member functions. */
4750 c
->is_defined
= lxcapi_is_defined
;
4751 c
->state
= lxcapi_state
;
4752 c
->is_running
= lxcapi_is_running
;
4753 c
->freeze
= lxcapi_freeze
;
4754 c
->unfreeze
= lxcapi_unfreeze
;
4755 c
->console
= lxcapi_console
;
4756 c
->console_getfd
= lxcapi_console_getfd
;
4757 c
->init_pid
= lxcapi_init_pid
;
4758 c
->load_config
= lxcapi_load_config
;
4759 c
->want_daemonize
= lxcapi_want_daemonize
;
4760 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4761 c
->start
= lxcapi_start
;
4762 c
->startl
= lxcapi_startl
;
4763 c
->stop
= lxcapi_stop
;
4764 c
->config_file_name
= lxcapi_config_file_name
;
4765 c
->wait
= lxcapi_wait
;
4766 c
->set_config_item
= lxcapi_set_config_item
;
4767 c
->destroy
= lxcapi_destroy
;
4768 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4769 c
->rename
= lxcapi_rename
;
4770 c
->save_config
= lxcapi_save_config
;
4771 c
->get_keys
= lxcapi_get_keys
;
4772 c
->create
= lxcapi_create
;
4773 c
->createl
= lxcapi_createl
;
4774 c
->shutdown
= lxcapi_shutdown
;
4775 c
->reboot
= lxcapi_reboot
;
4776 c
->reboot2
= lxcapi_reboot2
;
4777 c
->clear_config
= lxcapi_clear_config
;
4778 c
->clear_config_item
= lxcapi_clear_config_item
;
4779 c
->get_config_item
= lxcapi_get_config_item
;
4780 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4781 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4782 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4783 c
->get_config_path
= lxcapi_get_config_path
;
4784 c
->set_config_path
= lxcapi_set_config_path
;
4785 c
->clone
= lxcapi_clone
;
4786 c
->get_interfaces
= lxcapi_get_interfaces
;
4787 c
->get_ips
= lxcapi_get_ips
;
4788 c
->attach
= lxcapi_attach
;
4789 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4790 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4791 c
->snapshot
= lxcapi_snapshot
;
4792 c
->snapshot_list
= lxcapi_snapshot_list
;
4793 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4794 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4795 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4796 c
->may_control
= lxcapi_may_control
;
4797 c
->add_device_node
= lxcapi_add_device_node
;
4798 c
->remove_device_node
= lxcapi_remove_device_node
;
4799 c
->attach_interface
= lxcapi_attach_interface
;
4800 c
->detach_interface
= lxcapi_detach_interface
;
4801 c
->checkpoint
= lxcapi_checkpoint
;
4802 c
->restore
= lxcapi_restore
;
4803 c
->migrate
= lxcapi_migrate
;
4804 c
->console_log
= lxcapi_console_log
;
4809 lxc_container_free(c
);
4813 int lxc_get_wait_states(const char **states
)
4818 for (i
=0; i
<MAX_STATE
; i
++)
4819 states
[i
] = lxc_state2str(i
);
4824 * These next two could probably be done smarter with reusing a common function
4825 * with different iterators and tests...
4827 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4830 int i
, cfound
= 0, nfound
= 0;
4831 struct dirent
*direntp
;
4832 struct lxc_container
*c
;
4835 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4837 dir
= opendir(lxcpath
);
4839 SYSERROR("opendir on lxcpath");
4848 while ((direntp
= readdir(dir
))) {
4852 /* Ignore '.', '..' and any hidden directory. */
4853 if (!strncmp(direntp
->d_name
, ".", 1))
4856 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4860 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4870 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4872 INFO("Container %s:%s has a config but could not be loaded",
4873 lxcpath
, direntp
->d_name
);
4875 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4879 if (!do_lxcapi_is_defined(c
)) {
4880 INFO("Container %s:%s has a config but is not defined",
4881 lxcpath
, direntp
->d_name
);
4883 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4885 lxc_container_put(c
);
4889 if (!add_to_clist(cret
, c
, nfound
, true)) {
4890 lxc_container_put(c
);
4900 if (names
&& *names
) {
4901 for (i
=0; i
<cfound
; i
++)
4905 if (cret
&& *cret
) {
4906 for (i
=0; i
<nfound
; i
++)
4907 lxc_container_put((*cret
)[i
]);
4914 int list_active_containers(const char *lxcpath
, char ***nret
,
4915 struct lxc_container
***cret
)
4917 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4920 char **ct_name
= NULL
;
4922 struct lxc_container
*c
= NULL
;
4926 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4927 lxcpath_len
= strlen(lxcpath
);
4934 FILE *f
= fopen("/proc/net/unix", "r");
4938 while (getline(&line
, &len
, f
) != -1) {
4940 char *p
= strrchr(line
, ' '), *p2
;
4949 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4951 } else if (strncmp(p
, "lxc/", 4) == 0) {
4961 /* Now p is the start of lxc_name. */
4962 p2
= strchr(p
, '/');
4963 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
4968 char *recvpath
= lxc_cmd_get_lxcpath(p
);
4971 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0)
4973 p
= lxc_cmd_get_name(p
);
4978 if (array_contains(&ct_name
, p
, ct_name_cnt
))
4981 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
4982 goto free_cret_list
;
4989 c
= lxc_container_new(p
, lxcpath
);
4991 INFO("Container %s:%s is running but could not be loaded",
4993 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
4998 * If this is an anonymous container, then is_defined *can*
4999 * return false. So we don't do that check. Count on the
5000 * fact that the command socket exists.
5003 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5004 lxc_container_put(c
);
5005 goto free_cret_list
;
5010 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5012 lxc_container_put(c
);
5013 goto free_cret_list
;
5024 if (cret
&& *cret
) {
5025 for (i
= 0; i
< cret_cnt
; i
++)
5026 lxc_container_put((*cret
)[i
]);
5032 for (i
= 0; i
< ct_name_cnt
; i
++)
5044 int list_all_containers(const char *lxcpath
, char ***nret
,
5045 struct lxc_container
***cret
)
5047 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5050 struct lxc_container
**ct_list
= NULL
;
5052 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5056 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5057 if (active_cnt
< 0) {
5062 for (i
= 0; i
< active_cnt
; i
++) {
5063 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5064 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5066 goto free_active_name
;
5070 free(active_name
[i
]);
5071 active_name
[i
] = NULL
;
5077 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5078 struct lxc_container
*c
;
5080 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5082 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5083 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5087 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5088 lxc_container_put(c
);
5107 for (i
= 0; i
< ct_list_cnt
; i
++) {
5108 lxc_container_put(ct_list
[i
]);
5113 for (i
= 0; i
< active_cnt
; i
++) {
5114 free(active_name
[i
]);
5119 for (i
= 0; i
< ct_cnt
; i
++) {
5126 bool lxc_config_item_is_supported(const char *key
)
5128 return !!lxc_get_config(key
);