3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include <arpa/inet.h>
35 #include <sys/mount.h>
36 #include <sys/syscall.h>
37 #include <sys/sysmacros.h>
38 #include <sys/types.h>
46 #include "commands_utils.h"
50 #include "confile_utils.h"
53 #include "initutils.h"
56 #include "lxccontainer.h"
59 #include "namespace.h"
65 #include "storage/btrfs.h"
66 #include "storage/overlay.h"
67 #include "storage_utils.h"
75 #include <sys/mkdev.h>
81 #include <../include/ifaddrs.h>
85 #include <../include/lxcmntent.h>
91 #include "include/strlcpy.h"
94 /* Define faccessat() if missing from the C library */
95 #ifndef HAVE_FACCESSAT
96 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
99 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
107 lxc_log_define(lxccontainer
, lxc
);
109 static bool do_lxcapi_destroy(struct lxc_container
*c
);
110 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
111 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
112 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
113 static bool container_destroy(struct lxc_container
*c
,
114 struct lxc_storage
*storage
);
115 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
116 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
117 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
119 static bool config_file_exists(const char *lxcpath
, const char *cname
)
125 /* $lxcpath + '/' + $cname + '/config' + \0 */
126 len
= strlen(lxcpath
) + strlen(cname
) + 9;
128 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
129 if (ret
< 0 || (size_t)ret
>= len
)
132 return file_exists(fname
);
135 /* A few functions to help detect when a container creation failed. If a
136 * container creation was killed partway through, then trying to actually start
137 * that container could harm the host. We detect this by creating a 'partial'
138 * file under the container directory, and keeping an advisory lock. When
139 * container creation completes, we remove that file. When we load or try to
140 * start a container, if we find that file, without a flock, we remove the
143 static int ongoing_create(struct lxc_container
*c
)
148 struct flock lk
= {0};
150 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
152 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
153 if (ret
< 0 || (size_t)ret
>= len
)
156 if (!file_exists(path
))
159 fd
= open(path
, O_RDWR
);
164 lk
.l_whence
= SEEK_SET
;
167 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
168 if (ret
< 0 && errno
== EINVAL
)
169 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
173 if (ret
== 0 && lk
.l_pid
!= -1)
174 /* create is still ongoing */
177 /* Create completed but partial is still there. */
181 static int create_partial(struct lxc_container
*c
)
186 struct flock lk
= {0};
188 /* $lxcpath + '/' + $name + '/partial' + \0 */
189 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
191 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
192 if (ret
< 0 || (size_t)ret
>= len
)
195 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
200 lk
.l_whence
= SEEK_SET
;
202 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
204 if (errno
== EINVAL
) {
205 ret
= flock(fd
, LOCK_EX
);
210 SYSERROR("Failed to lock partial file %s", path
);
218 static void remove_partial(struct lxc_container
*c
, int fd
)
226 /* $lxcpath + '/' + $name + '/partial' + \0 */
227 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
229 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
230 if (ret
< 0 || (size_t)ret
>= len
)
235 SYSERROR("Failed to remove partial file %s", path
);
239 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
240 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
241 * container configuration file.
242 * The container_disk_lock also takes the container_mem_lock.
243 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
244 * NOTHING mutexes two independent programs with their own struct
245 * lxc_container for the same c->name, between API calls. For instance,
246 * c->config_read(); c->start(); Between those calls, data on disk
247 * could change (which shouldn't bother the caller unless for instance
248 * the rootfs get moved). c->config_read(); update; c->config_write();
249 * Two such updaters could race. The callers should therefore check their
250 * results. Trying to prevent that would necessarily expose us to deadlocks
251 * due to hung callers. So I prefer to keep the locks only within our own
252 * functions, not across functions.
254 * If you're going to clone while holding a lxccontainer, increment
255 * c->numthreads (under privlock) before forking. When deleting,
256 * decrement numthreads under privlock, then if it hits 0 you can delete.
257 * Do not ever use a lxccontainer whose numthreads you did not bump.
259 static void lxc_container_free(struct lxc_container
*c
)
265 c
->configfile
= NULL
;
267 free(c
->error_string
);
268 c
->error_string
= NULL
;
271 lxc_putlock(c
->slock
);
276 lxc_putlock(c
->privlock
);
284 lxc_conf_free(c
->lxc_conf
);
288 free(c
->config_path
);
289 c
->config_path
= NULL
;
294 /* Consider the following case:
296 * |====================================================================|
297 * | freer | racing get()er |
298 * |====================================================================|
299 * | lxc_container_put() | lxc_container_get() |
300 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
301 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
302 * | \ lxcunlock() | \ |
303 * | \ lxc_container_free() | \ lxclock() returns |
304 * | | \ c->numthreads < 1 -> return 0 |
305 * | \ \ (free stuff) | |
306 * | \ \ sem_destroy(privlock) | |
307 * |_______________________________|____________________________________|
309 * When the get()er checks numthreads the first time, one of the following
311 * 1. freer has set numthreads = 0. get() returns 0
312 * 2. freer is between lxclock and setting numthreads to 0. get()er will
313 * sem_wait on privlock, get lxclock after freer() drops it, then see
314 * numthreads is 0 and exit without touching lxclock again..
315 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
316 * will see --numthreads = 1 and not call lxc_container_free().
319 int lxc_container_get(struct lxc_container
*c
)
324 /* If someone else has already started freeing the container, don't try
325 * to take the lock, which may be invalid.
327 if (c
->numthreads
< 1)
330 if (container_mem_lock(c
))
333 /* Bail without trying to unlock, bc the privlock is now probably in
336 if (c
->numthreads
< 1)
340 container_mem_unlock(c
);
345 int lxc_container_put(struct lxc_container
*c
)
350 if (container_mem_lock(c
))
355 if (c
->numthreads
< 1) {
356 container_mem_unlock(c
);
357 lxc_container_free(c
);
361 container_mem_unlock(c
);
365 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
374 if (container_mem_lock(c
))
380 statret
= stat(c
->configfile
, &statbuf
);
387 container_mem_unlock(c
);
391 #define WRAP_API(rettype, fnname) \
392 static rettype fnname(struct lxc_container *c) \
395 bool reset_config = false; \
397 if (!current_config && c && c->lxc_conf) { \
398 current_config = c->lxc_conf; \
399 reset_config = true; \
402 ret = do_##fnname(c); \
404 current_config = NULL; \
409 #define WRAP_API_1(rettype, fnname, t1) \
410 static rettype fnname(struct lxc_container *c, t1 a1) \
413 bool reset_config = false; \
415 if (!current_config && c && c->lxc_conf) { \
416 current_config = c->lxc_conf; \
417 reset_config = true; \
420 ret = do_##fnname(c, a1); \
422 current_config = NULL; \
427 #define WRAP_API_2(rettype, fnname, t1, t2) \
428 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
431 bool reset_config = false; \
433 if (!current_config && c && c->lxc_conf) { \
434 current_config = c->lxc_conf; \
435 reset_config = true; \
438 ret = do_##fnname(c, a1, a2); \
440 current_config = NULL; \
445 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
446 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
449 bool reset_config = false; \
451 if (!current_config && c && c->lxc_conf) { \
452 current_config = c->lxc_conf; \
453 reset_config = true; \
456 ret = do_##fnname(c, a1, a2, a3); \
458 current_config = NULL; \
463 WRAP_API(bool, lxcapi_is_defined
)
465 static const char *do_lxcapi_state(struct lxc_container
*c
)
472 s
= lxc_getstate(c
->name
, c
->config_path
);
473 return lxc_state2str(s
);
476 WRAP_API(const char *, lxcapi_state
)
478 static bool is_stopped(struct lxc_container
*c
)
482 s
= lxc_getstate(c
->name
, c
->config_path
);
483 return (s
== STOPPED
);
486 static bool do_lxcapi_is_running(struct lxc_container
*c
)
491 return !is_stopped(c
);
494 WRAP_API(bool, lxcapi_is_running
)
496 static bool do_lxcapi_freeze(struct lxc_container
*c
)
503 ret
= lxc_freeze(c
->name
, c
->config_path
);
510 WRAP_API(bool, lxcapi_freeze
)
512 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
519 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
526 WRAP_API(bool, lxcapi_unfreeze
)
528 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
533 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
536 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
538 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
539 int stdoutfd
, int stderrfd
, int escape
)
546 current_config
= c
->lxc_conf
;
547 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
548 current_config
= NULL
;
553 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
557 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
560 NOTICE("The console log is empty");
561 else if (ret
== -EFAULT
)
562 NOTICE("The container does not keep a console log");
563 else if (ret
== -ENOENT
)
564 NOTICE("The container does not keep a console log file");
565 else if (ret
== -EIO
)
566 NOTICE("Failed to write console log to log file");
568 ERROR("Failed to retrieve console log");
574 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
576 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
581 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
584 WRAP_API(pid_t
, lxcapi_init_pid
)
586 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
589 c
->lxc_conf
= lxc_conf_init();
594 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
597 c
->lxc_conf
->name
= c
->name
;
601 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
605 bool need_disklock
= false, ret
= false;
610 fname
= c
->configfile
;
618 /* If we're reading something other than the container's config, we only
619 * need to lock the in-memory container. If loading the container's
620 * config file, take the disk lock.
622 if (strcmp(fname
, c
->configfile
) == 0)
623 need_disklock
= true;
626 lret
= container_disk_lock(c
);
628 lret
= container_mem_lock(c
);
632 ret
= load_config_locked(c
, fname
);
635 container_disk_unlock(c
);
637 container_mem_unlock(c
);
642 WRAP_API_1(bool, lxcapi_load_config
, const char *)
644 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
646 if (!c
|| !c
->lxc_conf
)
649 if (container_mem_lock(c
))
652 c
->daemonize
= state
;
654 container_mem_unlock(c
);
659 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
661 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
663 if (!c
|| !c
->lxc_conf
)
666 if (container_mem_lock(c
))
669 c
->lxc_conf
->close_all_fds
= state
;
671 container_mem_unlock(c
);
676 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
678 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
686 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
690 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
692 static bool am_single_threaded(void)
695 struct dirent
*direntp
;
698 dir
= opendir("/proc/self/task");
702 while ((direntp
= readdir(dir
))) {
703 if (strcmp(direntp
->d_name
, ".") == 0)
706 if (strcmp(direntp
->d_name
, "..") == 0)
718 static void push_arg(char ***argp
, char *arg
, int *nargs
)
723 copy
= must_copy_string(arg
);
726 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
735 static char **split_init_cmd(const char *incmd
)
741 char *saveptr
= NULL
;
746 len
= strlen(incmd
) + 1;
748 retlen
= strlcpy(copy
, incmd
, len
);
753 argv
= malloc(sizeof(char *));
757 for (; (p
= strtok_r(copy
, " ", &saveptr
)); copy
= NULL
)
758 push_arg(&argv
, p
, &nargs
);
768 static void free_init_cmd(char **argv
)
781 static int lxc_rcv_status(int state_socket
)
787 /* Receive container state. */
788 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
793 TRACE("Caught EINTR; retrying");
800 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
804 /* Close write end of the socket pair. */
805 close(handler
->state_socket_pair
[1]);
806 handler
->state_socket_pair
[1] = -1;
808 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
810 /* Close read end of the socket pair. */
811 close(handler
->state_socket_pair
[0]);
812 handler
->state_socket_pair
[0] = -1;
814 /* The first child is going to fork() again and then exits. So we reap
815 * the first child here.
817 ret
= wait_for_pid(pid
);
819 DEBUG("Failed waiting on first child %d", pid
);
821 DEBUG("First child %d exited", pid
);
824 SYSERROR("Failed to receive the container state");
828 /* If we receive anything else then running we know that the container
831 if (state
!= RUNNING
) {
832 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
833 lxc_state2str(state
));
837 TRACE("Container is in \"RUNNING\" state");
841 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
844 struct lxc_handler
*handler
;
845 struct lxc_conf
*conf
;
846 char *default_args
[] = {
850 char **init_cmd
= NULL
;
851 int keepfds
[3] = {-1, -1, -1};
853 /* container does exist */
857 /* If anything fails before we set error_num, we want an error in there.
861 /* Container has not been setup. */
865 ret
= ongoing_create(c
);
867 ERROR("Failed checking for incomplete container creation");
869 } else if (ret
== 1) {
870 ERROR("Ongoing container creation detected");
872 } else if (ret
== 2) {
873 ERROR("Failed to create container");
874 do_lxcapi_destroy(c
);
878 if (container_mem_lock(c
))
883 /* initialize handler */
884 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
886 container_mem_unlock(c
);
891 if (useinit
&& conf
->execute_cmd
)
892 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
894 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
897 /* ... otherwise use default_args. */
900 ERROR("No valid init detected");
901 lxc_free_handler(handler
);
907 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
908 * here to protect the on disk container? We don't want to exclude
909 * things like lxc_info while the container is running.
918 free_init_cmd(init_cmd
);
919 lxc_free_handler(handler
);
925 /* Set to NULL because we don't want father unlink
926 * the PID file, child will do the free and unlink.
930 /* Wait for container to tell us whether it started
933 started
= wait_on_daemonized_start(handler
, pid
);
935 free_init_cmd(init_cmd
);
936 lxc_free_handler(handler
);
942 /* We don't really care if this doesn't print all the
943 * characters. All that it means is that the proctitle will be
944 * ugly. Similarly, we also don't care if setproctitle() fails.
946 (void)snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
947 INFO("Attempting to set proc title to %s", title
);
948 (void)setproctitle(title
);
950 /* We fork() a second time to be reparented to init. Like
951 * POSIX's daemon() function we change to "/" and redirect
952 * std{in,out,err} to /dev/null.
956 SYSERROR("Failed to fork first child process");
962 free_init_cmd(init_cmd
);
963 lxc_free_handler(handler
);
969 /* change to / directory */
972 SYSERROR("Failed to change to \"/\" directory");
976 keepfds
[0] = handler
->conf
->maincmd_fd
;
977 keepfds
[1] = handler
->state_socket_pair
[0];
978 keepfds
[2] = handler
->state_socket_pair
[1];
979 ret
= lxc_check_inherited(conf
, true, keepfds
,
980 sizeof(keepfds
) / sizeof(keepfds
[0]));
984 /* redirect std{in,out,err} to /dev/null */
987 ERROR("Failed to redirect std{in,out,err} to /dev/null");
991 /* become session leader */
994 TRACE("Process %d is already process group leader", lxc_raw_getpid());
996 if (!am_single_threaded()) {
997 ERROR("Cannot start non-daemonized container when threaded");
998 free_init_cmd(init_cmd
);
999 lxc_free_handler(handler
);
1004 /* We need to write PID file after daemonize, so we always
1005 * write the right PID.
1009 char pidstr
[LXC_NUMSTRLEN64
];
1011 w
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", (int)lxc_raw_getpid());
1012 if (w
< 0 || (size_t)w
>= LXC_NUMSTRLEN64
) {
1013 free_init_cmd(init_cmd
);
1014 lxc_free_handler(handler
);
1016 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1019 _exit(EXIT_FAILURE
);
1024 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1026 free_init_cmd(init_cmd
);
1027 lxc_free_handler(handler
);
1029 SYSERROR("Failed to write '%s'", c
->pidfile
);
1032 _exit(EXIT_FAILURE
);
1038 conf
->reboot
= REBOOT_NONE
;
1040 /* Unshare the mount namespace if requested */
1041 if (conf
->monitor_unshare
) {
1042 ret
= unshare(CLONE_NEWNS
);
1044 SYSERROR("failed to unshare mount namespace");
1045 lxc_free_handler(handler
);
1050 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1052 SYSERROR("Failed to make / rslave at startup");
1053 lxc_free_handler(handler
);
1060 if (conf
->reboot
== REBOOT_INIT
) {
1061 /* initialize handler */
1062 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1069 keepfds
[0] = handler
->conf
->maincmd_fd
;
1070 keepfds
[1] = handler
->state_socket_pair
[0];
1071 keepfds
[2] = handler
->state_socket_pair
[1];
1072 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1073 sizeof(keepfds
) / sizeof(keepfds
[0]));
1075 lxc_free_handler(handler
);
1081 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1082 c
->daemonize
, &c
->error_num
);
1084 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1085 c
->daemonize
, &c
->error_num
);
1087 if (conf
->reboot
== REBOOT_REQ
) {
1088 INFO("Container requested reboot");
1089 conf
->reboot
= REBOOT_INIT
;
1099 free_init_cmd(init_cmd
);
1101 if (c
->daemonize
&& ret
!= 0)
1102 _exit(EXIT_FAILURE
);
1103 else if (c
->daemonize
)
1104 _exit(EXIT_SUCCESS
);
1112 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1117 current_config
= c
? c
->lxc_conf
: NULL
;
1118 ret
= do_lxcapi_start(c
, useinit
, argv
);
1119 current_config
= NULL
;
1124 /* Note, there MUST be an ending NULL. */
1125 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1128 char **inargs
= NULL
;
1131 /* container exists */
1135 current_config
= c
->lxc_conf
;
1137 va_start(ap
, useinit
);
1138 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1143 /* pass NULL if no arguments were supplied */
1144 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1150 for (arg
= inargs
; *arg
; arg
++)
1155 current_config
= NULL
;
1160 static bool do_lxcapi_stop(struct lxc_container
*c
)
1167 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1172 WRAP_API(bool, lxcapi_stop
)
1174 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1181 mode_t mask
= umask(0002);
1182 ret
= mkdir(path
, 0770);
1187 if (errno
!= EEXIST
)
1194 p
= alloca(len
+ 1);
1195 (void)strlcpy(p
, path
, len
+ 1);
1197 if (!lxc_list_empty(&conf
->id_map
)) {
1198 ret
= chown_mapped_root(p
, conf
);
1206 /* Create the standard expected container dir. */
1207 static bool create_container_dir(struct lxc_container
*c
)
1213 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1218 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1219 if (ret
< 0 || (size_t)ret
>= len
) {
1224 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1230 /* do_storage_create: thin wrapper around storage_create(). Like
1231 * storage_create(), it returns a mounted bdev on success, NULL on error.
1233 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1235 struct bdev_specs
*specs
)
1240 struct lxc_storage
*bdev
;
1242 /* rootfs.path or lxcpath/lxcname/rootfs */
1243 if (c
->lxc_conf
->rootfs
.path
&&
1244 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1245 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1246 len
= strlen(rpath
) + 1;
1248 ret
= snprintf(dest
, len
, "%s", rpath
);
1250 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1251 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1253 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1255 if (ret
< 0 || (size_t)ret
>= len
)
1258 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1260 ERROR("Failed to create \"%s\" storage", type
);
1264 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1265 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1269 /* If we are not root, chown the rootfs dir to root in the target user
1273 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1274 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1276 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1277 suggest_default_idmap();
1286 static char *lxcbasename(char *path
)
1290 p
= path
+ strlen(path
) - 1;
1291 while (*p
!= '/' && p
> path
)
1297 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1298 bool need_null_stdfds
, char *const argv
[])
1308 SYSERROR("Failed to fork task for container creation template");
1312 if (pid
== 0) { /* child */
1314 char *namearg
, *patharg
, *rootfsarg
;
1317 struct lxc_storage
*bdev
= NULL
;
1318 struct lxc_conf
*conf
= c
->lxc_conf
;
1321 if (need_null_stdfds
) {
1322 ret
= null_stdfds();
1324 _exit(EXIT_FAILURE
);
1327 bdev
= storage_init(c
->lxc_conf
);
1329 ERROR("Failed to initialize storage");
1330 _exit(EXIT_FAILURE
);
1335 ret
= unshare(CLONE_NEWNS
);
1337 ERROR("Failed to unshare CLONE_NEWNS");
1338 _exit(EXIT_FAILURE
);
1341 ret
= detect_shared_rootfs();
1343 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1345 SYSERROR("Failed to make \"/\" rslave");
1346 ERROR("Continuing...");
1351 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1353 ERROR("Unprivileged users can only create "
1354 "btrfs and directory-backed containers");
1355 _exit(EXIT_FAILURE
);
1358 if (strcmp(bdev
->type
, "overlay") == 0 ||
1359 strcmp(bdev
->type
, "overlayfs") == 0) {
1360 /* If we create an overlay container we need to
1361 * rsync the contents into
1362 * <container-path>/<container-name>/rootfs.
1363 * However, the overlay mount function will
1365 * <container-path>/<container-name>/delta0
1367 * <container-path>/<container-name>/rootfs
1368 * which means we would rsync the rootfs into
1369 * the delta directory. That doesn't make sense
1370 * since the delta directory only exists to
1371 * record the differences to
1372 * <container-path>/<container-name>/rootfs. So
1373 * let's simply bind-mount here and then rsync
1375 * <container-path>/<container-name>/rootfs.
1379 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1381 ERROR("Failed to get rootfs");
1382 _exit(EXIT_FAILURE
);
1385 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1387 ERROR("Failed to mount rootfs");
1388 _exit(EXIT_FAILURE
);
1391 ret
= bdev
->ops
->mount(bdev
);
1393 ERROR("Failed to mount rootfs");
1394 _exit(EXIT_FAILURE
);
1397 } else { /* TODO come up with a better way here! */
1400 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1401 bdev
->dest
= strdup(src
);
1404 /* Create our new array, pre-pend the template name and base
1408 for (nargs
= 0; argv
[nargs
]; nargs
++)
1411 /* template, path, rootfs and name args */
1414 newargv
= malloc(nargs
* sizeof(*newargv
));
1416 _exit(EXIT_FAILURE
);
1417 newargv
[0] = lxcbasename(tpath
);
1420 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1421 patharg
= malloc(len
);
1423 _exit(EXIT_FAILURE
);
1425 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1426 if (ret
< 0 || ret
>= len
)
1427 _exit(EXIT_FAILURE
);
1428 newargv
[1] = patharg
;
1431 len
= strlen("--name=") + strlen(c
->name
) + 1;
1432 namearg
= malloc(len
);
1434 _exit(EXIT_FAILURE
);
1436 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1437 if (ret
< 0 || ret
>= len
)
1438 _exit(EXIT_FAILURE
);
1439 newargv
[2] = namearg
;
1442 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1443 rootfsarg
= malloc(len
);
1445 _exit(EXIT_FAILURE
);
1447 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1448 if (ret
< 0 || ret
>= len
)
1449 _exit(EXIT_FAILURE
);
1450 newargv
[3] = rootfsarg
;
1452 /* add passed-in args */
1454 for (i
= 4; i
< nargs
; i
++)
1455 newargv
[i
] = argv
[i
- 4];
1457 /* add trailing NULL */
1459 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1461 _exit(EXIT_FAILURE
);
1462 newargv
[nargs
- 1] = NULL
;
1464 /* If we're running the template in a mapped userns, then we
1465 * prepend the template command with: lxc-usernsexec <-m map1>
1466 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1467 * the mapped uid for our geteuid()
1469 if (!lxc_list_empty(&conf
->id_map
)) {
1470 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1472 char txtuid
[20], txtgid
[20];
1473 struct lxc_list
*it
;
1477 n2
= malloc(n2args
* sizeof(*n2
));
1479 _exit(EXIT_FAILURE
);
1482 tpath
= "lxc-usernsexec";
1483 n2
[0] = "lxc-usernsexec";
1485 lxc_list_for_each(it
, &conf
->id_map
) {
1488 n2
= realloc(n2
, n2args
* sizeof(char *));
1490 _exit(EXIT_FAILURE
);
1492 n2
[n2args
- 2] = "-m";
1493 n2
[n2args
- 1] = malloc(200);
1494 if (!n2
[n2args
- 1])
1495 _exit(EXIT_FAILURE
);
1497 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1498 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1499 map
->nsid
, map
->hostid
, map
->range
);
1500 if (ret
< 0 || ret
>= 200)
1501 _exit(EXIT_FAILURE
);
1504 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1505 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1507 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1509 _exit(EXIT_FAILURE
);
1511 if (hostuid_mapped
< 0) {
1512 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1513 n2
[n2args
++] = "-m";
1514 if (hostuid_mapped
< 0) {
1515 ERROR("Failed to find free uid to map");
1516 _exit(EXIT_FAILURE
);
1519 n2
[n2args
++] = malloc(200);
1520 if (!n2
[n2args
- 1]) {
1521 SYSERROR("out of memory");
1522 _exit(EXIT_FAILURE
);
1525 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1526 hostuid_mapped
, geteuid());
1527 if (ret
< 0 || ret
>= 200)
1528 _exit(EXIT_FAILURE
);
1531 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1532 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1534 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1536 _exit(EXIT_FAILURE
);
1538 if (hostgid_mapped
< 0) {
1539 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1540 n2
[n2args
++] = "-m";
1541 if (hostgid_mapped
< 0) {
1542 ERROR("Failed to find free gid to map");
1543 _exit(EXIT_FAILURE
);
1546 n2
[n2args
++] = malloc(200);
1547 if (!n2
[n2args
- 1]) {
1548 SYSERROR("out of memory");
1549 _exit(EXIT_FAILURE
);
1552 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1553 hostgid_mapped
, getegid());
1554 if (ret
< 0 || ret
>= 200)
1555 _exit(EXIT_FAILURE
);
1558 n2
[n2args
++] = "--";
1560 for (i
= 0; i
< nargs
; i
++)
1561 n2
[i
+ n2args
] = newargv
[i
];
1564 /* Finally add "--mapped-uid $uid" to tell template what
1565 * to chown cached images to.
1568 n2
= realloc(n2
, n2args
* sizeof(char *));
1570 _exit(EXIT_FAILURE
);
1572 /* note n2[n2args-1] is NULL */
1573 n2
[n2args
- 5] = "--mapped-uid";
1575 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1576 if (ret
< 0 || ret
>= 20) {
1579 _exit(EXIT_FAILURE
);
1582 n2
[n2args
- 4] = txtuid
;
1583 n2
[n2args
- 3] = "--mapped-gid";
1585 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1586 if (ret
< 0 || ret
>= 20) {
1589 _exit(EXIT_FAILURE
);
1592 n2
[n2args
- 2] = txtgid
;
1593 n2
[n2args
- 1] = NULL
;
1598 execvp(tpath
, newargv
);
1599 SYSERROR("Failed to execute template %s", tpath
);
1600 _exit(EXIT_FAILURE
);
1603 ret
= wait_for_pid(pid
);
1605 ERROR("Failed to create container from template");
1612 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1621 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1625 f
= fopen(path
, "r");
1629 ret
= fseek(f
, 0, SEEK_END
);
1638 ret
= fseek(f
, 0, SEEK_SET
);
1642 ret
= fseek(f
, 0, SEEK_SET
);
1647 contents
= malloc(flen
+ 1);
1651 len
= fread(contents
, 1, flen
, f
);
1653 goto out_free_contents
;
1655 contents
[flen
] = '\0';
1660 goto out_free_contents
;
1663 tpath
= get_template_path(t
);
1665 ERROR("Invalid template \"%s\" specified", t
);
1666 goto out_free_contents
;
1669 ret
= sha1sum_file(tpath
, md_value
);
1671 ERROR("Failed to get sha1sum of %s", tpath
);
1673 goto out_free_contents
;
1678 f
= fopen(path
, "w");
1680 SYSERROR("Reopening config for writing");
1685 fprintf(f
, "# Template used to create this container: %s\n", t
);
1687 fprintf(f
, "# Parameters passed to the template:");
1689 fprintf(f
, " %s", *argv
);
1696 fprintf(f
, "# Template script checksum (SHA-1): ");
1697 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1698 fprintf(f
, "%02x", md_value
[i
]);
1701 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1702 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1703 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1704 fprintf(f
, "# (Be aware this has security implications)\n\n");
1705 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1706 SYSERROR("Writing original contents");
1726 SYSERROR("Error prepending header");
1733 static void lxcapi_clear_config(struct lxc_container
*c
)
1735 if (!c
|| !c
->lxc_conf
)
1738 lxc_conf_free(c
->lxc_conf
);
1742 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1746 * create a container with the given parameters.
1747 * @c: container to be created. It has the lxcpath, name, and a starting
1748 * configuration already set
1749 * @t: the template to execute to instantiate the root filesystem and
1750 * adjust the configuration.
1751 * @bdevtype: backing store type to use. If NULL, dir will be used.
1752 * @specs: additional parameters for the backing store, i.e. LVM vg to
1755 * @argv: the arguments to pass to the template, terminated by NULL. If no
1756 * arguments, you can just pass NULL.
1758 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1759 const char *bdevtype
, struct bdev_specs
*specs
,
1760 int flags
, char *const argv
[])
1772 tpath
= get_template_path(t
);
1774 ERROR("Unknown template \"%s\"", t
);
1779 /* If a template is passed in, and the rootfs already is defined in the
1780 * container config and exists, then the caller is trying to create an
1781 * existing container. Return an error, but do NOT delete the container.
1783 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1784 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1785 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1791 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1792 ERROR("Error loading default configuration file %s",
1793 lxc_global_config_value("lxc.default_config"));
1798 if (!create_container_dir(c
))
1801 /* If both template and rootfs.path are set, template is setup as
1802 * rootfs.path. The container is already created if we have a config and
1803 * rootfs.path is accessible
1805 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1806 /* No template passed in and rootfs does not exist. */
1807 if (!c
->save_config(c
, NULL
)) {
1808 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1815 /* Rootfs passed into configuration, but does not exist. */
1816 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1819 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1820 /* Rootfs already existed, user just wanted to save the loaded
1823 if (!c
->save_config(c
, NULL
))
1824 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1830 /* Mark that this container is being created */
1831 partial_fd
= create_partial(c
);
1835 /* No need to get disk lock bc we have the partial lock. */
1839 /* Create the storage.
1840 * Note we can't do this in the same task as we use to execute the
1841 * template because of the way zfs works.
1842 * After you 'zfs create', zfs mounts the fs only in the initial
1847 SYSERROR("Failed to fork task for container creation template");
1851 if (pid
== 0) { /* child */
1852 struct lxc_storage
*bdev
= NULL
;
1854 bdev
= do_storage_create(c
, bdevtype
, specs
);
1856 ERROR("Failed to create %s storage for %s",
1857 bdevtype
? bdevtype
: "(none)", c
->name
);
1858 _exit(EXIT_FAILURE
);
1861 /* Save config file again to store the new rootfs location. */
1862 if (!do_lxcapi_save_config(c
, NULL
)) {
1863 ERROR("Failed to save initial config for %s", c
->name
);
1864 /* Parent task won't see the storage driver in the
1865 * config so we delete it.
1867 bdev
->ops
->umount(bdev
);
1868 bdev
->ops
->destroy(bdev
);
1869 _exit(EXIT_FAILURE
);
1872 _exit(EXIT_SUCCESS
);
1875 if (wait_for_pid(pid
) != 0)
1878 /* Reload config to get the rootfs. */
1879 lxc_conf_free(c
->lxc_conf
);
1882 if (!load_config_locked(c
, c
->configfile
))
1885 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1888 /* Now clear out the lxc_conf we have, reload from the created
1891 do_lxcapi_clear_config(c
);
1894 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1895 ERROR("Failed to prepend header to config file");
1900 ret
= load_config_locked(c
, c
->configfile
);
1904 if (partial_fd
>= 0)
1905 remove_partial(c
, partial_fd
);
1909 container_destroy(c
, NULL
);
1916 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1917 const char *bdevtype
, struct bdev_specs
*specs
,
1918 int flags
, char *const argv
[])
1922 current_config
= c
? c
->lxc_conf
: NULL
;
1924 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1925 current_config
= NULL
;
1929 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1933 int rebootsignal
= SIGINT
;
1938 if (!do_lxcapi_is_running(c
))
1941 pid
= do_lxcapi_init_pid(c
);
1945 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1946 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1948 ret
= kill(pid
, rebootsignal
);
1950 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
1957 WRAP_API(bool, lxcapi_reboot
)
1959 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1963 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1964 lxc_state_t states
[MAX_STATE
] = {0};
1969 if (!do_lxcapi_is_running(c
))
1972 pid
= do_lxcapi_init_pid(c
);
1976 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1977 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1979 /* Add a new state client before sending the shutdown signal so that we
1980 * don't miss a state.
1983 states
[RUNNING
] = 2;
1984 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1989 if (state_client_fd
< 0)
1995 if (ret
< MAX_STATE
)
1999 /* Send reboot signal to container. */
2000 killret
= kill(pid
, rebootsignal
);
2002 if (state_client_fd
>= 0)
2003 close(state_client_fd
);
2005 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2008 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2013 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2014 close(state_client_fd
);
2018 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2025 WRAP_API_1(bool, lxcapi_reboot2
, int)
2027 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2031 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2032 lxc_state_t states
[MAX_STATE
] = {0};
2037 if (!do_lxcapi_is_running(c
))
2040 pid
= do_lxcapi_init_pid(c
);
2044 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2045 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2046 haltsignal
= c
->lxc_conf
->haltsignal
;
2047 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2048 haltsignal
= (SIGRTMIN
+ 3);
2050 /* Add a new state client before sending the shutdown signal so that we
2051 * don't miss a state.
2054 states
[STOPPED
] = 1;
2055 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2060 if (state_client_fd
< 0)
2066 if (ret
< MAX_STATE
)
2070 /* Send shutdown signal to container. */
2071 killret
= kill(pid
, haltsignal
);
2073 if (state_client_fd
>= 0)
2074 close(state_client_fd
);
2076 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2079 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2084 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2085 close(state_client_fd
);
2089 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2096 WRAP_API_1(bool, lxcapi_shutdown
, int)
2098 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2099 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2108 current_config
= c
->lxc_conf
;
2111 * since we're going to wait for create to finish, I don't think we
2112 * need to get a copy of the arguments.
2114 va_start(ap
, flags
);
2115 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2118 ERROR("Failed to allocate memory");
2122 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2126 current_config
= NULL
;
2130 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2132 if (!strcmp(key
, "lxc.cgroup"))
2133 return clear_unexp_config_line(conf
, key
, true);
2135 if (!strcmp(key
, "lxc.network"))
2136 return clear_unexp_config_line(conf
, key
, true);
2138 if (!strcmp(key
, "lxc.net"))
2139 return clear_unexp_config_line(conf
, key
, true);
2141 /* Clear a network with a specific index. */
2142 if (!strncmp(key
, "lxc.net.", 8)) {
2147 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2149 return clear_unexp_config_line(conf
, key
, true);
2152 if (!strcmp(key
, "lxc.hook"))
2153 return clear_unexp_config_line(conf
, key
, true);
2155 return clear_unexp_config_line(conf
, key
, false);
2158 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2162 struct lxc_config_t
*config
;
2164 if (!c
|| !c
->lxc_conf
)
2167 if (container_mem_lock(c
))
2170 config
= lxc_get_config(key
);
2171 /* Verify that the config key exists and that it has a callback
2174 if (config
&& config
->clr
)
2175 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2178 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2180 container_mem_unlock(c
);
2184 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2186 static inline bool enter_net_ns(struct lxc_container
*c
)
2188 pid_t pid
= do_lxcapi_init_pid(c
);
2190 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2191 (access("/proc/self/ns/user", F_OK
) == 0))
2192 if (!switch_to_ns(pid
, "user"))
2195 return switch_to_ns(pid
, "net");
2198 /* Used by qsort and bsearch functions for comparing names. */
2199 static inline int string_cmp(char **first
, char **second
)
2201 return strcmp(*first
, *second
);
2204 /* Used by qsort and bsearch functions for comparing container names. */
2205 static inline int container_cmp(struct lxc_container
**first
,
2206 struct lxc_container
**second
)
2208 return strcmp((*first
)->name
, (*second
)->name
);
2211 static bool add_to_array(char ***names
, char *cname
, int pos
)
2213 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2215 ERROR("Out of memory");
2220 newnames
[pos
] = strdup(cname
);
2224 /* Sort the arrray as we will use binary search on it. */
2225 qsort(newnames
, pos
+ 1, sizeof(char *),
2226 (int (*)(const void *, const void *))string_cmp
);
2231 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2234 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2236 ERROR("Out of memory");
2243 /* Sort the arrray as we will use binary search on it. */
2245 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2246 (int (*)(const void *, const void *))container_cmp
);
2251 static char** get_from_array(char ***names
, char *cname
, int size
)
2253 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2256 static bool array_contains(char ***names
, char *cname
, int size
)
2258 if(get_from_array(names
, cname
, size
) != NULL
)
2264 static bool remove_from_array(char ***names
, char *cname
, int size
)
2266 char **result
= get_from_array(names
, cname
, size
);
2267 if (result
!= NULL
) {
2275 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2278 int i
, count
= 0, pipefd
[2];
2279 char **interfaces
= NULL
;
2280 char interface
[IFNAMSIZ
];
2282 if(pipe(pipefd
) < 0) {
2283 SYSERROR("pipe failed");
2289 SYSERROR("failed to fork task to get interfaces information");
2295 if (pid
== 0) { /* child */
2296 int ret
= 1, nbytes
;
2297 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2299 /* close the read-end of the pipe */
2302 if (!enter_net_ns(c
)) {
2303 SYSERROR("failed to enter namespace");
2307 /* Grab the list of interfaces */
2308 if (getifaddrs(&interfaceArray
)) {
2309 SYSERROR("failed to get interfaces list");
2313 /* Iterate through the interfaces */
2314 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2315 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2317 ERROR("write failed");
2327 freeifaddrs(interfaceArray
);
2329 /* close the write-end of the pipe, thus sending EOF to the reader */
2334 /* close the write-end of the pipe */
2337 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2338 interface
[IFNAMSIZ
- 1] = '\0';
2340 if (array_contains(&interfaces
, interface
, count
))
2343 if(!add_to_array(&interfaces
, interface
, count
))
2344 ERROR("Failed to add \"%s\" to array", interface
);
2349 if (wait_for_pid(pid
) != 0) {
2350 for(i
=0;i
<count
;i
++)
2351 free(interfaces
[i
]);
2357 /* close the read-end of the pipe */
2360 /* Append NULL to the array */
2362 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2367 WRAP_API(char **, lxcapi_get_interfaces
)
2369 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2370 const char *family
, int scope
)
2375 char address
[INET6_ADDRSTRLEN
];
2377 char **addresses
= NULL
;
2381 SYSERROR("Failed to create pipe");
2387 SYSERROR("Failed to create new process");
2395 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2397 char *address
= NULL
;
2398 void *tempAddrPtr
= NULL
;
2399 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2401 /* close the read-end of the pipe */
2404 if (!enter_net_ns(c
)) {
2405 SYSERROR("Failed to attach to network namespace");
2409 /* Grab the list of interfaces */
2410 if (getifaddrs(&interfaceArray
)) {
2411 SYSERROR("Failed to get interfaces list");
2415 /* Iterate through the interfaces */
2416 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2417 tempIfAddr
= tempIfAddr
->ifa_next
) {
2418 if (tempIfAddr
->ifa_addr
== NULL
)
2421 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2422 if (family
&& strcmp(family
, "inet"))
2425 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2427 if (family
&& strcmp(family
, "inet6"))
2430 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2433 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2436 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2438 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2441 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2442 tempAddrPtr
, addressOutputBuffer
,
2443 sizeof(addressOutputBuffer
));
2447 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2448 if (nbytes
!= INET6_ADDRSTRLEN
) {
2449 SYSERROR("Failed to send ipv6 address \"%s\"",
2461 freeifaddrs(interfaceArray
);
2463 /* close the write-end of the pipe, thus sending EOF to the reader */
2468 /* close the write-end of the pipe */
2471 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2472 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2474 if (!add_to_array(&addresses
, address
, count
))
2475 ERROR("PARENT: add_to_array failed");
2480 if (wait_for_pid(pid
) != 0) {
2481 for (i
= 0; i
< count
; i
++)
2488 /* close the read-end of the pipe */
2491 /* Append NULL to the array */
2493 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2498 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2500 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2503 struct lxc_config_t
*config
;
2505 if (!c
|| !c
->lxc_conf
)
2508 if (container_mem_lock(c
))
2511 config
= lxc_get_config(key
);
2512 /* Verify that the config key exists and that it has a callback
2515 if (config
&& config
->get
)
2516 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2518 container_mem_unlock(c
);
2522 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2524 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2528 if (!c
|| !c
->lxc_conf
)
2531 if (container_mem_lock(c
))
2534 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2535 container_mem_unlock(c
);
2539 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2541 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2545 /* List all config items. */
2547 return lxc_list_config_items(retv
, inlen
);
2549 if (!c
|| !c
->lxc_conf
)
2552 if (container_mem_lock(c
))
2555 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2556 * This is an intelligent result to show which keys are valid given the
2557 * type of nic it is.
2559 if (strncmp(key
, "lxc.net.", 8) == 0)
2560 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2562 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2564 container_mem_unlock(c
);
2568 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2570 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2573 bool ret
= false, need_disklock
= false;
2576 alt_file
= c
->configfile
;
2581 /* If we haven't yet loaded a config, load the stock config. */
2583 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2584 ERROR("Error loading default configuration file %s "
2586 lxc_global_config_value("lxc.default_config"),
2592 if (!create_container_dir(c
))
2595 /* If we're writing to the container's config file, take the disk lock.
2596 * Otherwise just take the memlock to protect the struct lxc_container
2597 * while we're traversing it.
2599 if (strcmp(c
->configfile
, alt_file
) == 0)
2600 need_disklock
= true;
2603 lret
= container_disk_lock(c
);
2605 lret
= container_mem_lock(c
);
2609 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2610 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2614 lret
= write_config(fd
, c
->lxc_conf
);
2623 container_disk_unlock(c
);
2625 container_mem_unlock(c
);
2630 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2633 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2639 char path
[MAXPATHLEN
];
2640 char newpath
[MAXPATHLEN
];
2641 int fd
, ret
, n
= 0, v
= 0;
2643 size_t len
= 0, bytes
= 0;
2645 if (container_disk_lock(c0
))
2648 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2649 if (ret
< 0 || ret
> MAXPATHLEN
)
2652 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2653 if (ret
< 0 || ret
> MAXPATHLEN
)
2656 /* If we find an lxc-snapshot file using the old format only listing the
2657 * number of snapshots we will keep using it. */
2658 f1
= fopen(path
, "r");
2660 n
= fscanf(f1
, "%d", &v
);
2662 if (n
== 1 && v
== 0) {
2665 SYSERROR("Failed to remove \"%s\"", path
);
2673 f1
= fopen(path
, "w");
2677 if (fprintf(f1
, "%d\n", v
) < 0) {
2678 ERROR("Error writing new snapshots value");
2685 SYSERROR("Error writing to or closing snapshots file");
2689 /* Here we know that we have or can use an lxc-snapshot file
2690 * using the new format. */
2692 f1
= fopen(path
, "a");
2696 if (fprintf(f1
, "%s", newpath
) < 0) {
2697 ERROR("Error writing new snapshots entry");
2700 SYSERROR("Error writing to or closing snapshots file");
2706 SYSERROR("Error writing to or closing snapshots file");
2710 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2713 if (fstat(fd
, &fbuf
) < 0) {
2718 if (fbuf
.st_size
!= 0) {
2719 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2720 if (buf
== MAP_FAILED
) {
2721 SYSERROR("Failed to create mapping %s", path
);
2726 len
= strlen(newpath
);
2727 while ((del
= strstr((char *)buf
, newpath
))) {
2728 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2732 lxc_strmunmap(buf
, fbuf
.st_size
);
2733 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2734 SYSERROR("Failed to truncate file %s", path
);
2743 /* If the lxc-snapshot file is empty, remove it. */
2744 if (stat(path
, &fbuf
) < 0)
2747 if (!fbuf
.st_size
) {
2750 SYSERROR("Failed to remove \"%s\"", path
);
2757 container_disk_unlock(c0
);
2761 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2763 struct lxc_container
*p
;
2764 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2765 size_t pathlen
= 0, namelen
= 0;
2769 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2770 c
->config_path
, c
->name
);
2771 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2772 ERROR("Path name too long");
2776 f
= fopen(path
, "r");
2780 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2781 if (getline(&lxcname
, &namelen
, f
) == -1) {
2782 ERROR("badly formatted file %s", path
);
2786 remove_trailing_newlines(lxcpath
);
2787 remove_trailing_newlines(lxcname
);
2789 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2790 ERROR("Unable to find dependent container %s:%s",
2795 if (!mod_rdep(p
, c
, inc
))
2796 ERROR("Failed to update snapshots file for %s:%s",
2799 lxc_container_put(p
);
2808 static bool has_fs_snapshots(struct lxc_container
*c
)
2811 char path
[MAXPATHLEN
];
2816 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2818 if (ret
< 0 || ret
> MAXPATHLEN
)
2821 /* If the file doesn't exist there are no snapshots. */
2822 if (stat(path
, &fbuf
) < 0)
2827 f
= fopen(path
, "r");
2831 ret
= fscanf(f
, "%d", &v
);
2833 /* TODO: Figure out what to do with the return value of fscanf. */
2835 INFO("Container uses new lxc-snapshots format %s", path
);
2844 static bool has_snapshots(struct lxc_container
*c
)
2846 char path
[MAXPATHLEN
];
2847 struct dirent
*direntp
;
2851 if (!get_snappath_dir(c
, path
))
2854 dir
= opendir(path
);
2858 while ((direntp
= readdir(dir
))) {
2859 if (!strcmp(direntp
->d_name
, "."))
2862 if (!strcmp(direntp
->d_name
, ".."))
2872 static bool do_destroy_container(struct lxc_conf
*conf
) {
2875 if (am_guest_unpriv()) {
2876 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2877 "storage_destroy_wrapper");
2884 return storage_destroy(conf
);
2887 static int lxc_rmdir_onedev_wrapper(void *data
)
2889 char *arg
= (char *) data
;
2890 return lxc_rmdir_onedev(arg
, "snaps");
2893 static int lxc_unlink_exec_wrapper(void *data
)
2899 static bool container_destroy(struct lxc_container
*c
,
2900 struct lxc_storage
*storage
)
2904 struct lxc_conf
*conf
;
2909 if (!c
|| !do_lxcapi_is_defined(c
))
2913 if (container_disk_lock(c
))
2916 if (!is_stopped(c
)) {
2917 /* We should queue some sort of error - in c->error_string? */
2918 ERROR("container %s is not stopped", c
->name
);
2922 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2923 /* Start of environment variable setup for hooks */
2924 if (setenv("LXC_NAME", c
->name
, 1))
2925 SYSERROR("Failed to set environment variable for container name");
2927 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2928 SYSERROR("Failed to set environment variable for config path");
2930 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2931 SYSERROR("Failed to set environment variable for rootfs mount");
2933 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2934 SYSERROR("Failed to set environment variable for rootfs mount");
2936 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2937 SYSERROR("Failed to set environment variable for console path");
2939 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2940 SYSERROR("Failed to set environment variable for console log");
2941 /* End of environment variable setup for hooks */
2943 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2944 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2949 if (current_config
&& conf
== current_config
) {
2950 current_config
= NULL
;
2952 if (conf
->logfd
!= -1) {
2958 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2959 if (!do_destroy_container(conf
)) {
2960 ERROR("Error destroying rootfs for %s", c
->name
);
2963 INFO("Destroyed rootfs for %s", c
->name
);
2966 mod_all_rdeps(c
, false);
2968 p1
= do_lxcapi_get_config_path(c
);
2977 * strlen("config") = 6
2981 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
2984 ERROR("Failed to allocate memory");
2988 /* For an overlay container the rootfs is considered immutable and
2989 * cannot be removed when restoring from a snapshot.
2991 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
2992 !strcmp(storage
->type
, "overlayfs")) &&
2993 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
2994 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
2995 if (ret
< 0 || (size_t)ret
>= len
)
2998 if (am_guest_unpriv())
2999 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3000 "lxc_unlink_exec_wrapper");
3004 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3008 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3014 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3015 if (ret
< 0 || (size_t)ret
>= len
)
3018 if (am_guest_unpriv())
3019 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3020 "lxc_rmdir_onedev_wrapper");
3022 ret
= lxc_rmdir_onedev(path
, "snaps");
3024 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3028 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3036 container_disk_unlock(c
);
3040 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3042 if (!c
|| !lxcapi_is_defined(c
))
3045 if (has_snapshots(c
)) {
3046 ERROR("Container %s has snapshots; not removing", c
->name
);
3050 if (has_fs_snapshots(c
)) {
3051 ERROR("container %s has snapshots on its rootfs", c
->name
);
3055 return container_destroy(c
, NULL
);
3058 WRAP_API(bool, lxcapi_destroy
)
3060 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3062 if (!c
|| !lxcapi_is_defined(c
))
3065 if (!lxcapi_snapshot_destroy_all(c
)) {
3066 ERROR("Error deleting all snapshots");
3070 return lxcapi_destroy(c
);
3073 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3075 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3079 struct lxc_config_t
*config
;
3082 config
= lxc_get_config(key
);
3086 ret
= config
->set(key
, v
, conf
, NULL
);
3090 if (lxc_config_value_empty(v
))
3091 do_clear_unexp_config_line(conf
, key
);
3093 bret
= do_append_unexp_config_line(conf
, key
, v
);
3100 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3106 c
->lxc_conf
= lxc_conf_init();
3111 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3118 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3125 if (container_mem_lock(c
))
3128 b
= do_set_config_item_locked(c
, key
, v
);
3130 container_mem_unlock(c
);
3134 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3136 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3138 if (!c
|| !c
->configfile
)
3141 return strdup(c
->configfile
);
3144 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3146 if (!c
|| !c
->config_path
)
3149 return (const char *)(c
->config_path
);
3154 * Just recalculate the c->configfile based on the
3155 * c->config_path, which must be set.
3156 * The lxc_container must be locked or not yet public.
3158 static bool set_config_filename(struct lxc_container
*c
)
3163 if (!c
->config_path
)
3166 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3167 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3168 newpath
= malloc(len
);
3172 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3173 if (ret
< 0 || ret
>= len
) {
3174 fprintf(stderr
, "Error printing out config file name\n");
3179 free(c
->configfile
);
3180 c
->configfile
= newpath
;
3185 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3189 char *oldpath
= NULL
;
3194 if (container_mem_lock(c
))
3199 ERROR("Out of memory setting new lxc path");
3205 oldpath
= c
->config_path
;
3208 /* Since we've changed the config path, we have to change the
3209 * config file name too */
3210 if (!set_config_filename(c
)) {
3211 ERROR("Out of memory setting new config filename");
3213 free(c
->config_path
);
3214 c
->config_path
= oldpath
;
3220 container_mem_unlock(c
);
3224 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3226 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3229 struct cgroup_ops
*cgroup_ops
;
3237 cgroup_ops
= cgroup_init(NULL
);
3241 if (container_disk_lock(c
))
3244 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3246 container_disk_unlock(c
);
3248 cgroup_exit(cgroup_ops
);
3253 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3255 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3258 struct cgroup_ops
*cgroup_ops
;
3266 cgroup_ops
= cgroup_init(NULL
);
3270 if (container_disk_lock(c
))
3273 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3276 container_disk_unlock(c
);
3278 cgroup_exit(cgroup_ops
);
3283 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3285 const char *lxc_get_global_config_item(const char *key
)
3287 return lxc_global_config_value(key
);
3290 const char *lxc_get_version(void)
3295 static int copy_file(const char *old
, const char *new)
3302 if (file_exists(new)) {
3303 ERROR("copy destination %s exists", new);
3307 ret
= stat(old
, &sbuf
);
3309 INFO("Error stat'ing %s", old
);
3313 in
= open(old
, O_RDONLY
);
3315 SYSERROR("Error opening original file %s", old
);
3319 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3321 SYSERROR("Error opening new file %s", new);
3327 len
= read(in
, buf
, 8096);
3329 SYSERROR("Error reading old file %s", old
);
3336 ret
= write(out
, buf
, len
);
3337 if (ret
< len
) { /* should we retry? */
3338 SYSERROR("Error: write to new file %s was interrupted", new);
3346 /* We set mode, but not owner/group. */
3347 ret
= chmod(new, sbuf
.st_mode
);
3349 SYSERROR("Error setting mode on %s", new);
3361 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3364 struct lxc_list
*it
;
3367 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3368 cpath
= alloca(len
);
3369 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3370 if (ret
< 0 || ret
>= len
)
3373 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3374 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3375 char *hookname
= it
->elem
;
3376 char *fname
= strrchr(hookname
, '/');
3377 char tmppath
[MAXPATHLEN
];
3378 if (!fname
) /* relative path - we don't support, but maybe we should */
3381 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3382 /* this hook is public - ignore */
3386 /* copy the script, and change the entry in confile */
3387 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3388 c
->config_path
, c
->name
, fname
+1);
3389 if (ret
< 0 || ret
>= MAXPATHLEN
)
3392 ret
= copy_file(it
->elem
, tmppath
);
3398 it
->elem
= strdup(tmppath
);
3400 ERROR("out of memory copying hook path");
3406 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3407 c
->config_path
, oldc
->name
, c
->name
)) {
3408 ERROR("Error saving new hooks in clone");
3412 do_lxcapi_save_config(c
, NULL
);
3417 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3419 char newpath
[MAXPATHLEN
];
3420 char *oldpath
= oldc
->lxc_conf
->fstab
;
3426 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3428 char *p
= strrchr(oldpath
, '/');
3432 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3433 c
->config_path
, c
->name
, p
);
3434 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3435 ERROR("error printing new path for %s", oldpath
);
3439 if (file_exists(newpath
)) {
3440 ERROR("error: fstab file %s exists", newpath
);
3444 if (copy_file(oldpath
, newpath
) < 0) {
3445 ERROR("error: copying %s to %s", oldpath
, newpath
);
3449 free(c
->lxc_conf
->fstab
);
3451 c
->lxc_conf
->fstab
= strdup(newpath
);
3452 if (!c
->lxc_conf
->fstab
) {
3453 ERROR("error: allocating pathname");
3457 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3458 ERROR("error saving new lxctab");
3465 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3467 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3470 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3472 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3473 WARN("Error copying reverse dependencies");
3477 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3479 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3480 WARN("Error copying reverse dependencies");
3484 if (copy_file(path0
, path1
) < 0) {
3485 INFO("Error copying reverse dependencies");
3490 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3493 char path
[MAXPATHLEN
];
3497 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3499 if (ret
< 0 || ret
>= MAXPATHLEN
)
3502 f
= fopen(path
, "a");
3508 /* If anything goes wrong, just return an error. */
3509 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3519 * If the fs natively supports snapshot clones with no penalty,
3520 * then default to those even if not requested.
3521 * Currently we only do this for btrfs.
3523 bool should_default_to_snapshot(struct lxc_container
*c0
,
3524 struct lxc_container
*c1
)
3527 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3528 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3529 char *p0
= alloca(l0
+ 1);
3530 char *p1
= alloca(l1
+ 1);
3531 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3533 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3534 if (ret
< 0 || ret
>= l0
)
3537 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3538 if (ret
< 0 || ret
>= l1
)
3541 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3544 if (is_btrfs_subvol(rootfs
) <= 0)
3547 return btrfs_same_fs(p0
, p1
) == 0;
3550 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3551 const char *newtype
, int flags
, const char *bdevdata
,
3554 struct lxc_storage
*bdev
;
3557 if (should_default_to_snapshot(c0
, c
))
3558 flags
|= LXC_CLONE_SNAPSHOT
;
3560 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3561 bdevdata
, newsize
, &need_rdep
);
3563 ERROR("Error copying storage.");
3567 /* Set new rootfs. */
3568 free(c
->lxc_conf
->rootfs
.path
);
3569 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3572 if (!c
->lxc_conf
->rootfs
.path
) {
3573 ERROR("Out of memory while setting storage path.");
3577 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3578 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3579 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3580 c
->lxc_conf
->rootfs
.path
)) {
3581 ERROR("Error saving new rootfs to cloned config.");
3585 if (flags
& LXC_CLONE_SNAPSHOT
)
3586 copy_rdepends(c
, c0
);
3589 if (!add_rdepends(c
, c0
))
3590 WARN("Error adding reverse dependency from %s to %s",
3594 mod_all_rdeps(c
, true);
3599 struct clone_update_data
{
3600 struct lxc_container
*c0
;
3601 struct lxc_container
*c1
;
3606 static int clone_update_rootfs(struct clone_update_data
*data
)
3608 struct lxc_container
*c0
= data
->c0
;
3609 struct lxc_container
*c
= data
->c1
;
3610 int flags
= data
->flags
;
3611 char **hookargs
= data
->hookargs
;
3613 char path
[MAXPATHLEN
];
3614 struct lxc_storage
*bdev
;
3616 struct lxc_conf
*conf
= c
->lxc_conf
;
3618 /* update hostname in rootfs */
3619 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3621 if (setgid(0) < 0) {
3622 ERROR("Failed to setgid to 0");
3626 if (setuid(0) < 0) {
3627 ERROR("Failed to setuid to 0");
3631 if (setgroups(0, NULL
) < 0)
3632 WARN("Failed to clear groups");
3634 if (unshare(CLONE_NEWNS
) < 0)
3637 bdev
= storage_init(c
->lxc_conf
);
3641 if (strcmp(bdev
->type
, "dir") != 0) {
3642 if (unshare(CLONE_NEWNS
) < 0) {
3643 ERROR("error unsharing mounts");
3648 if (detect_shared_rootfs()) {
3649 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3650 SYSERROR("Failed to make / rslave");
3651 ERROR("Continuing...");
3655 if (bdev
->ops
->mount(bdev
) < 0) {
3659 } else { /* TODO come up with a better way */
3661 bdev
->dest
= strdup(bdev
->src
);
3664 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3665 /* Start of environment variable setup for hooks */
3666 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3667 SYSERROR("failed to set environment variable for source container name");
3669 if (setenv("LXC_NAME", c
->name
, 1))
3670 SYSERROR("failed to set environment variable for container name");
3672 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3673 SYSERROR("failed to set environment variable for config path");
3675 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3676 SYSERROR("failed to set environment variable for rootfs mount");
3678 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3679 SYSERROR("failed to set environment variable for rootfs mount");
3681 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3682 ERROR("Error executing clone hook for %s", c
->name
);
3688 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3689 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3692 if (ret
< 0 || ret
>= MAXPATHLEN
)
3695 if (!file_exists(path
))
3698 if (!(fout
= fopen(path
, "w"))) {
3699 SYSERROR("unable to open %s: ignoring", path
);
3703 if (fprintf(fout
, "%s", c
->name
) < 0) {
3708 if (fclose(fout
) < 0)
3717 static int clone_update_rootfs_wrapper(void *data
)
3719 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3720 return clone_update_rootfs(arg
);
3724 * We want to support:
3725 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3726 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3728 -s [ implies overlay]
3731 only rootfs gets converted (copied/snapshotted) on clone.
3734 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3736 char *p
= strrchr(path
, '/');
3743 ret
= do_create_container_dir(path
, conf
);
3749 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3750 const char *lxcpath
, int flags
,
3751 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3754 char newpath
[MAXPATHLEN
];
3756 struct clone_update_data data
;
3757 size_t saved_unexp_len
;
3759 int storage_copied
= 0;
3760 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3761 struct lxc_container
*c2
= NULL
;
3763 if (!c
|| !do_lxcapi_is_defined(c
))
3766 if (container_mem_lock(c
))
3769 if (!is_stopped(c
)) {
3770 ERROR("error: Original container (%s) is running", c
->name
);
3774 /* Make sure the container doesn't yet exist. */
3779 lxcpath
= do_lxcapi_get_config_path(c
);
3781 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3782 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3783 SYSERROR("clone: failed making config pathname");
3787 if (file_exists(newpath
)) {
3788 ERROR("error: clone: %s exists", newpath
);
3792 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3793 if (ret
< 0 && errno
!= EEXIST
) {
3794 ERROR("Error creating container dir for %s", newpath
);
3798 /* Copy the configuration. Tweak it as needed. */
3799 if (c
->lxc_conf
->rootfs
.path
) {
3800 origroot
= c
->lxc_conf
->rootfs
.path
;
3801 c
->lxc_conf
->rootfs
.path
= NULL
;
3804 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3805 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3807 SYSERROR("Failed to open \"%s\"", newpath
);
3811 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3812 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3813 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3814 if (!c
->lxc_conf
->unexpanded_config
) {
3819 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3820 write_config(fd
, c
->lxc_conf
);
3823 c
->lxc_conf
->rootfs
.path
= origroot
;
3825 free(c
->lxc_conf
->unexpanded_config
);
3826 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3827 saved_unexp_conf
= NULL
;
3828 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3830 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3831 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3832 SYSERROR("clone: failed making rootfs pathname");
3836 ret
= mkdir(newpath
, 0755);
3838 /* For an overlay container the rootfs is considered immutable
3839 * and will not have been removed when restoring from a
3842 if (errno
!= ENOENT
&&
3843 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3844 SYSERROR("Failed to create directory \"%s\"", newpath
);
3849 if (am_guest_unpriv()) {
3850 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3851 ERROR("Error chowning %s to container root", newpath
);
3856 c2
= lxc_container_new(newname
, lxcpath
);
3858 ERROR("clone: failed to create new container (%s %s)", newname
,
3863 /* copy/snapshot rootfs's */
3864 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3868 /* update utsname */
3869 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3870 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3871 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3873 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3874 ERROR("Error setting new hostname");
3880 ret
= copyhooks(c
, c2
);
3882 ERROR("error copying hooks");
3886 if (copy_fstab(c
, c2
) < 0) {
3887 ERROR("error copying fstab");
3891 /* update macaddrs */
3892 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3893 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3894 ERROR("Error updating mac addresses");
3899 /* Update absolute paths for overlay mount directories. */
3900 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3903 /* We've now successfully created c2's storage, so clear it out if we
3908 if (!c2
->save_config(c2
, NULL
))
3911 if ((pid
= fork()) < 0) {
3917 ret
= wait_for_pid(pid
);
3921 container_mem_unlock(c
);
3928 data
.hookargs
= hookargs
;
3930 if (am_guest_unpriv())
3931 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3932 &data
, "clone_update_rootfs_wrapper");
3934 ret
= clone_update_rootfs(&data
);
3936 _exit(EXIT_FAILURE
);
3938 container_mem_unlock(c
);
3939 _exit(EXIT_SUCCESS
);
3942 container_mem_unlock(c
);
3944 if (!storage_copied
)
3945 c2
->lxc_conf
->rootfs
.path
= NULL
;
3948 lxc_container_put(c2
);
3954 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3955 const char *lxcpath
, int flags
,
3956 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3959 struct lxc_container
* ret
;
3961 current_config
= c
? c
->lxc_conf
: NULL
;
3962 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3963 current_config
= NULL
;
3968 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3970 struct lxc_storage
*bdev
;
3971 struct lxc_container
*newc
;
3973 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3976 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3977 ERROR("Renaming a container with snapshots is not supported");
3981 bdev
= storage_init(c
->lxc_conf
);
3983 ERROR("Failed to find original backing store type");
3987 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3990 lxc_container_put(newc
);
3994 if (newc
&& lxcapi_is_defined(newc
))
3995 lxc_container_put(newc
);
3997 if (!container_destroy(c
, NULL
)) {
3998 ERROR("Could not destroy existing container %s", c
->name
);
4005 WRAP_API_1(bool, lxcapi_rename
, const char *)
4007 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
)
4014 current_config
= c
->lxc_conf
;
4016 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4017 current_config
= NULL
;
4021 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4023 lxc_attach_command_t command
;
4030 command
.program
= (char*)program
;
4031 command
.argv
= (char**)argv
;
4033 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4039 return lxc_wait_for_pid_status(pid
);
4042 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4046 current_config
= c
? c
->lxc_conf
: NULL
;
4047 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4048 current_config
= NULL
;
4053 static int get_next_index(const char *lxcpath
, char *cname
)
4059 fname
= alloca(strlen(lxcpath
) + 20);
4062 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4064 ret
= stat(fname
, &sb
);
4072 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4077 * If the old style snapshot path exists, use it
4078 * /var/lib/lxc -> /var/lib/lxcsnaps
4080 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
4081 if (ret
< 0 || ret
>= MAXPATHLEN
)
4084 if (dir_exists(snappath
)) {
4085 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
4086 if (ret
< 0 || ret
>= MAXPATHLEN
)
4093 * Use the new style path
4094 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4096 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
4097 if (ret
< 0 || ret
>= MAXPATHLEN
)
4103 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4106 struct lxc_container
*c2
;
4107 char snappath
[MAXPATHLEN
], newname
[20];
4109 if (!c
|| !lxcapi_is_defined(c
))
4112 if (!storage_can_backup(c
->lxc_conf
)) {
4113 ERROR("%s's backing store cannot be backed up.", c
->name
);
4114 ERROR("Your container must use another backing store type.");
4118 if (!get_snappath_dir(c
, snappath
))
4121 i
= get_next_index(snappath
, c
->name
);
4123 if (mkdir_p(snappath
, 0755) < 0) {
4124 ERROR("Failed to create snapshot directory %s", snappath
);
4128 ret
= snprintf(newname
, 20, "snap%d", i
);
4129 if (ret
< 0 || ret
>= 20)
4133 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4134 * created in the original container
4136 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4137 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4138 if (storage_is_dir(c
->lxc_conf
)) {
4139 ERROR("Snapshot of directory-backed container requested.");
4140 ERROR("Making a copy-clone. If you do want snapshots, then");
4141 ERROR("please create overlay clone first, snapshot that");
4142 ERROR("and keep the original container pristine.");
4143 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4146 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4148 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
4152 lxc_container_put(c2
);
4154 /* Now write down the creation time. */
4161 tm_info
= localtime(&timer
);
4163 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
4165 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4166 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4167 f
= fopen(dfnam
, "w");
4169 ERROR("Failed to open %s", dfnam
);
4173 if (fprintf(f
, "%s", buffer
) < 0) {
4174 SYSERROR("Writing timestamp");
4181 SYSERROR("Writing timestamp");
4186 /* $p / $name / comment \0 */
4187 int len
= strlen(snappath
) + strlen(newname
) + 10;
4188 char *path
= alloca(len
);
4190 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4191 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4197 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4199 static void lxcsnap_free(struct lxc_snapshot
*s
)
4202 free(s
->comment_pathname
);
4207 static char *get_snapcomment_path(char* snappath
, char *name
)
4209 /* $snappath/$name/comment */
4210 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4211 char *s
= malloc(len
);
4214 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4215 if (ret
< 0 || ret
>= len
) {
4224 static char *get_timestamp(char* snappath
, char *name
)
4226 char path
[MAXPATHLEN
], *s
= NULL
;
4230 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4231 if (ret
< 0 || ret
>= MAXPATHLEN
)
4234 fin
= fopen(path
, "r");
4238 (void) fseek(fin
, 0, SEEK_END
);
4240 (void) fseek(fin
, 0, SEEK_SET
);
4245 if (fread(s
, 1, len
, fin
) != len
) {
4246 SYSERROR("reading timestamp");
4257 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4259 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4261 struct dirent
*direntp
;
4262 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4265 if (!c
|| !lxcapi_is_defined(c
))
4268 if (!get_snappath_dir(c
, snappath
)) {
4269 ERROR("path name too long");
4273 dir
= opendir(snappath
);
4275 INFO("Failed to open %s - assuming no snapshots", snappath
);
4279 while ((direntp
= readdir(dir
))) {
4280 if (!strcmp(direntp
->d_name
, "."))
4283 if (!strcmp(direntp
->d_name
, ".."))
4286 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4287 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4288 ERROR("pathname too long");
4292 if (!file_exists(path2
))
4295 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4297 SYSERROR("Out of memory");
4302 snaps
[count
].free
= lxcsnap_free
;
4303 snaps
[count
].name
= strdup(direntp
->d_name
);
4304 if (!snaps
[count
].name
)
4307 snaps
[count
].lxcpath
= strdup(snappath
);
4308 if (!snaps
[count
].lxcpath
) {
4309 free(snaps
[count
].name
);
4313 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4314 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4319 WARN("Failed to close directory");
4328 for (i
=0; i
<count
; i
++)
4329 lxcsnap_free(&snaps
[i
]);
4335 WARN("Failed to close directory");
4340 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4342 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4344 char clonelxcpath
[MAXPATHLEN
];
4346 struct lxc_container
*snap
, *rest
;
4347 struct lxc_storage
*bdev
;
4350 if (!c
|| !c
->name
|| !c
->config_path
)
4353 if (has_fs_snapshots(c
)) {
4354 ERROR("container rootfs has dependent snapshots");
4358 bdev
= storage_init(c
->lxc_conf
);
4360 ERROR("Failed to find original backing store type");
4364 /* For an overlay container the rootfs is considered immutable
4365 * and cannot be removed when restoring from a snapshot. We pass this
4366 * internal flag along to communicate this to various parts of the
4369 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4370 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4375 if (!get_snappath_dir(c
, clonelxcpath
)) {
4379 /* how should we lock this? */
4381 snap
= lxc_container_new(snapname
, clonelxcpath
);
4382 if (!snap
|| !lxcapi_is_defined(snap
)) {
4383 ERROR("Could not open snapshot %s", snapname
);
4386 lxc_container_put(snap
);
4392 if (!strcmp(c
->name
, newname
)) {
4393 if (!container_destroy(c
, bdev
)) {
4394 ERROR("Could not destroy existing container %s", newname
);
4395 lxc_container_put(snap
);
4401 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4402 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4404 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4405 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4407 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4410 if (rest
&& lxcapi_is_defined(rest
))
4414 lxc_container_put(rest
);
4416 lxc_container_put(snap
);
4420 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4422 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4424 struct lxc_container
*snap
= NULL
;
4427 snap
= lxc_container_new(snapname
, clonelxcpath
);
4429 ERROR("Could not find snapshot %s", snapname
);
4433 if (!do_lxcapi_destroy(snap
)) {
4434 ERROR("Could not destroy snapshot %s", snapname
);
4442 lxc_container_put(snap
);
4447 static bool remove_all_snapshots(const char *path
)
4450 struct dirent
*direntp
;
4453 dir
= opendir(path
);
4455 SYSERROR("opendir on snapshot path %s", path
);
4459 while ((direntp
= readdir(dir
))) {
4460 if (!strcmp(direntp
->d_name
, "."))
4463 if (!strcmp(direntp
->d_name
, ".."))
4466 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4475 SYSERROR("Error removing directory %s", path
);
4480 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4482 char clonelxcpath
[MAXPATHLEN
];
4484 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4487 if (!get_snappath_dir(c
, clonelxcpath
))
4490 return do_snapshot_destroy(snapname
, clonelxcpath
);
4493 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4495 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4497 char clonelxcpath
[MAXPATHLEN
];
4499 if (!c
|| !c
->name
|| !c
->config_path
)
4502 if (!get_snappath_dir(c
, clonelxcpath
))
4505 return remove_all_snapshots(clonelxcpath
);
4508 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4510 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4512 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4515 WRAP_API(bool, lxcapi_may_control
)
4517 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4523 char chrootpath
[MAXPATHLEN
];
4524 char *directory_path
= NULL
;
4528 SYSERROR("Failed to fork()");
4533 ret
= wait_for_pid(pid
);
4535 ERROR("Failed to create device node");
4542 /* prepare the path */
4543 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4544 if (ret
< 0 || ret
>= MAXPATHLEN
)
4547 ret
= chroot(chrootpath
);
4549 _exit(EXIT_FAILURE
);
4553 _exit(EXIT_FAILURE
);
4555 /* remove path if it exists */
4556 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4560 SYSERROR("Failed to remove \"%s\"", path
);
4561 _exit(EXIT_FAILURE
);
4566 _exit(EXIT_SUCCESS
);
4568 /* create any missing directories */
4571 _exit(EXIT_FAILURE
);
4573 directory_path
= dirname(tmp
);
4574 ret
= mkdir_p(directory_path
, 0755);
4575 if (ret
< 0 && errno
!= EEXIST
) {
4576 SYSERROR("Failed to create path \"%s\"", directory_path
);
4578 _exit(EXIT_FAILURE
);
4581 /* create the device node */
4582 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4585 SYSERROR("Failed to create device node at \"%s\"", path
);
4586 _exit(EXIT_FAILURE
);
4589 _exit(EXIT_SUCCESS
);
4592 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4596 char value
[LXC_MAX_BUFFER
];
4599 /* make sure container is running */
4600 if (!do_lxcapi_is_running(c
)) {
4601 ERROR("container is not running");
4605 /* use src_path if dest_path is NULL otherwise use dest_path */
4606 p
= dest_path
? dest_path
: src_path
;
4608 /* make sure we can access p */
4609 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4612 /* continue if path is character device or block device */
4613 if (S_ISCHR(st
.st_mode
))
4614 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4615 else if (S_ISBLK(st
.st_mode
))
4616 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4620 /* check snprintf return code */
4621 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4624 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4627 /* add or remove device to/from cgroup access list */
4629 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4630 ERROR("set_cgroup_item failed while adding the device node");
4634 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4635 ERROR("set_cgroup_item failed while removing the device node");
4643 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4645 // cannot mknod if we're not privileged wrt init_user_ns
4646 if (am_host_unpriv()) {
4647 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4651 return add_remove_device_node(c
, src_path
, dest_path
, true);
4654 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4656 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4658 if (am_guest_unpriv()) {
4659 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4663 return add_remove_device_node(c
, src_path
, dest_path
, false);
4666 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4668 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4670 const char *dst_ifname
)
4675 if (am_guest_unpriv()) {
4676 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4681 ERROR("No source interface name given");
4685 ret
= lxc_netdev_isup(ifname
);
4687 /* netdev of ifname is up. */
4688 ret
= lxc_netdev_down(ifname
);
4693 init_pid
= do_lxcapi_init_pid(c
);
4694 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4698 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4705 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4707 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4709 const char *dst_ifname
)
4712 pid_t pid
, pid_outside
;
4715 * TODO - if this is a physical device, then we need am_host_unpriv.
4716 * But for other types guest privilege suffices.
4718 if (am_guest_unpriv()) {
4719 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4724 ERROR("No source interface name given");
4728 pid_outside
= lxc_raw_getpid();
4731 ERROR("Failed to fork");
4735 if (pid
== 0) { /* child */
4738 init_pid
= do_lxcapi_init_pid(c
);
4739 if (!switch_to_ns(init_pid
, "net")) {
4740 ERROR("Failed to enter network namespace");
4741 _exit(EXIT_FAILURE
);
4744 ret
= lxc_netdev_isup(ifname
);
4746 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4747 _exit(EXIT_FAILURE
);
4750 /* netdev of ifname is up. */
4752 ret
= lxc_netdev_down(ifname
);
4754 ERROR("Failed to set network device \"%s\" down", ifname
);
4755 _exit(EXIT_FAILURE
);
4759 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4760 /* -EINVAL means there is no netdev named as ifname. */
4763 ERROR("Network device \"%s\" not found", ifname
);
4765 ERROR("Failed to remove network device \"%s\"", ifname
);
4767 _exit(EXIT_FAILURE
);
4770 _exit(EXIT_SUCCESS
);
4773 ret
= wait_for_pid(pid
);
4777 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4781 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4783 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4784 struct migrate_opts
*opts
, unsigned int size
)
4787 struct migrate_opts
*valid_opts
= opts
;
4788 uint64_t features_to_check
= 0;
4790 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4791 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4792 * to do anything special.
4794 if (size
> sizeof(*opts
)) {
4795 unsigned char *addr
;
4798 addr
= (void *)opts
+ sizeof(*opts
);
4799 end
= (void *)opts
+ size
;
4801 for (; addr
< end
; addr
++)
4806 /* If the caller has a smaller struct, let's zero out the end for them
4807 * so we don't accidentally use bits of it that they didn't know about
4810 if (size
< sizeof(*opts
)) {
4811 valid_opts
= malloc(sizeof(*opts
));
4815 memset(valid_opts
, 0, sizeof(*opts
));
4816 memcpy(valid_opts
, opts
, size
);
4820 case MIGRATE_PRE_DUMP
:
4821 if (!do_lxcapi_is_running(c
)) {
4822 ERROR("container is not running");
4826 ret
= !__criu_pre_dump(c
, valid_opts
);
4829 if (!do_lxcapi_is_running(c
)) {
4830 ERROR("container is not running");
4834 ret
= !__criu_dump(c
, valid_opts
);
4836 case MIGRATE_RESTORE
:
4837 if (do_lxcapi_is_running(c
)) {
4838 ERROR("container is already running");
4842 ret
= !__criu_restore(c
, valid_opts
);
4844 case MIGRATE_FEATURE_CHECK
:
4845 features_to_check
= valid_opts
->features_to_check
;
4846 ret
= !__criu_check_feature(&features_to_check
);
4848 /* Something went wrong. Let's let the caller
4849 * know which feature checks failed. */
4850 valid_opts
->features_to_check
= features_to_check
;
4854 ERROR("invalid migrate command %u", cmd
);
4859 if (size
< sizeof(*opts
))
4865 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4867 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4869 struct migrate_opts opts
;
4871 memset(&opts
, 0, sizeof(opts
));
4873 opts
.directory
= directory
;
4875 opts
.verbose
= verbose
;
4877 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4880 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4882 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4884 struct migrate_opts opts
;
4886 memset(&opts
, 0, sizeof(opts
));
4888 opts
.directory
= directory
;
4889 opts
.verbose
= verbose
;
4891 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4894 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4896 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4905 current_config
= c
->lxc_conf
;
4908 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4912 ERROR("Memory allocation error.");
4918 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4922 current_config
= NULL
;
4926 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4928 struct lxc_container
*c
;
4934 c
= malloc(sizeof(*c
));
4936 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4939 memset(c
, 0, sizeof(*c
));
4942 c
->config_path
= strdup(configpath
);
4944 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4945 if (!c
->config_path
) {
4946 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4950 remove_trailing_slashes(c
->config_path
);
4953 c
->name
= malloc(len
+ 1);
4955 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4958 (void)strlcpy(c
->name
, name
, len
+ 1);
4961 c
->slock
= lxc_newlock(c
->config_path
, name
);
4963 fprintf(stderr
, "Failed to create lock for %s\n", name
);
4967 c
->privlock
= lxc_newlock(NULL
, NULL
);
4969 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
4973 if (!set_config_filename(c
)) {
4974 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
4978 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
4979 fprintf(stderr
, "Failed to load config for %s\n", name
);
4983 if (ongoing_create(c
) == 2) {
4984 ERROR("Failed to complete container creation for %s", c
->name
);
4985 container_destroy(c
, NULL
);
4986 lxcapi_clear_config(c
);
4989 c
->daemonize
= true;
4992 /* Assign the member functions. */
4993 c
->is_defined
= lxcapi_is_defined
;
4994 c
->state
= lxcapi_state
;
4995 c
->is_running
= lxcapi_is_running
;
4996 c
->freeze
= lxcapi_freeze
;
4997 c
->unfreeze
= lxcapi_unfreeze
;
4998 c
->console
= lxcapi_console
;
4999 c
->console_getfd
= lxcapi_console_getfd
;
5000 c
->init_pid
= lxcapi_init_pid
;
5001 c
->load_config
= lxcapi_load_config
;
5002 c
->want_daemonize
= lxcapi_want_daemonize
;
5003 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5004 c
->start
= lxcapi_start
;
5005 c
->startl
= lxcapi_startl
;
5006 c
->stop
= lxcapi_stop
;
5007 c
->config_file_name
= lxcapi_config_file_name
;
5008 c
->wait
= lxcapi_wait
;
5009 c
->set_config_item
= lxcapi_set_config_item
;
5010 c
->destroy
= lxcapi_destroy
;
5011 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5012 c
->rename
= lxcapi_rename
;
5013 c
->save_config
= lxcapi_save_config
;
5014 c
->get_keys
= lxcapi_get_keys
;
5015 c
->create
= lxcapi_create
;
5016 c
->createl
= lxcapi_createl
;
5017 c
->shutdown
= lxcapi_shutdown
;
5018 c
->reboot
= lxcapi_reboot
;
5019 c
->reboot2
= lxcapi_reboot2
;
5020 c
->clear_config
= lxcapi_clear_config
;
5021 c
->clear_config_item
= lxcapi_clear_config_item
;
5022 c
->get_config_item
= lxcapi_get_config_item
;
5023 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5024 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5025 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5026 c
->get_config_path
= lxcapi_get_config_path
;
5027 c
->set_config_path
= lxcapi_set_config_path
;
5028 c
->clone
= lxcapi_clone
;
5029 c
->get_interfaces
= lxcapi_get_interfaces
;
5030 c
->get_ips
= lxcapi_get_ips
;
5031 c
->attach
= lxcapi_attach
;
5032 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5033 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5034 c
->snapshot
= lxcapi_snapshot
;
5035 c
->snapshot_list
= lxcapi_snapshot_list
;
5036 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5037 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5038 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5039 c
->may_control
= lxcapi_may_control
;
5040 c
->add_device_node
= lxcapi_add_device_node
;
5041 c
->remove_device_node
= lxcapi_remove_device_node
;
5042 c
->attach_interface
= lxcapi_attach_interface
;
5043 c
->detach_interface
= lxcapi_detach_interface
;
5044 c
->checkpoint
= lxcapi_checkpoint
;
5045 c
->restore
= lxcapi_restore
;
5046 c
->migrate
= lxcapi_migrate
;
5047 c
->console_log
= lxcapi_console_log
;
5052 lxc_container_free(c
);
5056 int lxc_get_wait_states(const char **states
)
5061 for (i
=0; i
<MAX_STATE
; i
++)
5062 states
[i
] = lxc_state2str(i
);
5068 * These next two could probably be done smarter with reusing a common function
5069 * with different iterators and tests...
5071 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5074 int i
, cfound
= 0, nfound
= 0;
5075 struct dirent
*direntp
;
5076 struct lxc_container
*c
;
5079 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5081 dir
= opendir(lxcpath
);
5083 SYSERROR("opendir on lxcpath");
5093 while ((direntp
= readdir(dir
))) {
5094 /* Ignore '.', '..' and any hidden directory. */
5095 if (!strncmp(direntp
->d_name
, ".", 1))
5098 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5102 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5112 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5114 INFO("Container %s:%s has a config but could not be loaded",
5115 lxcpath
, direntp
->d_name
);
5118 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5124 if (!do_lxcapi_is_defined(c
)) {
5125 INFO("Container %s:%s has a config but is not defined",
5126 lxcpath
, direntp
->d_name
);
5129 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5132 lxc_container_put(c
);
5136 if (!add_to_clist(cret
, c
, nfound
, true)) {
5137 lxc_container_put(c
);
5148 if (names
&& *names
) {
5149 for (i
=0; i
<cfound
; i
++)
5154 if (cret
&& *cret
) {
5155 for (i
=0; i
<nfound
; i
++)
5156 lxc_container_put((*cret
)[i
]);
5164 int list_active_containers(const char *lxcpath
, char ***nret
,
5165 struct lxc_container
***cret
)
5167 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5170 char **ct_name
= NULL
;
5172 struct lxc_container
*c
= NULL
;
5176 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5177 lxcpath_len
= strlen(lxcpath
);
5185 FILE *f
= fopen("/proc/net/unix", "r");
5189 while (getline(&line
, &len
, f
) != -1) {
5190 char *p
= strrchr(line
, ' '), *p2
;
5201 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5203 } else if (strncmp(p
, "lxc/", 4) == 0) {
5213 /* Now p is the start of lxc_name. */
5214 p2
= strchr(p
, '/');
5215 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5220 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5224 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5230 p
= lxc_cmd_get_name(p
);
5235 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5241 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5244 goto free_cret_list
;
5255 c
= lxc_container_new(p
, lxcpath
);
5257 INFO("Container %s:%s is running but could not be loaded",
5260 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5271 * If this is an anonymous container, then is_defined *can*
5272 * return false. So we don't do that check. Count on the
5273 * fact that the command socket exists.
5276 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5277 lxc_container_put(c
);
5278 goto free_cret_list
;
5284 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5286 lxc_container_put(c
);
5287 goto free_cret_list
;
5299 if (cret
&& *cret
) {
5300 for (i
= 0; i
< cret_cnt
; i
++)
5301 lxc_container_put((*cret
)[i
]);
5307 for (i
= 0; i
< ct_name_cnt
; i
++)
5318 int list_all_containers(const char *lxcpath
, char ***nret
,
5319 struct lxc_container
***cret
)
5321 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5324 struct lxc_container
**ct_list
= NULL
;
5326 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5330 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5331 if (active_cnt
< 0) {
5336 for (i
= 0; i
< active_cnt
; i
++) {
5337 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5338 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5340 goto free_active_name
;
5346 free(active_name
[i
]);
5347 active_name
[i
] = NULL
;
5354 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5355 struct lxc_container
*c
;
5357 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5359 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5360 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5364 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5365 lxc_container_put(c
);
5386 for (i
= 0; i
< ct_list_cnt
; i
++) {
5387 lxc_container_put(ct_list
[i
]);
5392 for (i
= 0; i
< active_cnt
; i
++) {
5393 free(active_name
[i
]);
5398 for (i
= 0; i
< ct_cnt
; i
++) {
5405 bool lxc_config_item_is_supported(const char *key
)
5407 return !!lxc_get_config(key
);