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>
90 /* Define faccessat() if missing from the C library */
91 #ifndef HAVE_FACCESSAT
92 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
95 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
103 lxc_log_define(lxc_container
, lxc
);
105 static bool do_lxcapi_destroy(struct lxc_container
*c
);
106 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
107 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
108 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
109 static bool container_destroy(struct lxc_container
*c
,
110 struct lxc_storage
*storage
);
111 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
112 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
113 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
115 static bool config_file_exists(const char *lxcpath
, const char *cname
)
121 /* $lxcpath + '/' + $cname + '/config' + \0 */
122 len
= strlen(lxcpath
) + strlen(cname
) + 9;
124 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
125 if (ret
< 0 || (size_t)ret
>= len
)
128 return file_exists(fname
);
131 /* A few functions to help detect when a container creation failed. If a
132 * container creation was killed partway through, then trying to actually start
133 * that container could harm the host. We detect this by creating a 'partial'
134 * file under the container directory, and keeping an advisory lock. When
135 * container creation completes, we remove that file. When we load or try to
136 * start a container, if we find that file, without a flock, we remove the
139 static int ongoing_create(struct lxc_container
*c
)
144 struct flock lk
= {0};
146 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
148 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
149 if (ret
< 0 || (size_t)ret
>= len
)
152 if (!file_exists(path
))
155 fd
= open(path
, O_RDWR
);
160 lk
.l_whence
= SEEK_SET
;
163 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
164 if (ret
< 0 && errno
== EINVAL
)
165 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
167 if (ret
== 0 && lk
.l_pid
!= -1) {
168 /* create is still ongoing */
172 /* Create completed but partial is still there. */
176 static int create_partial(struct lxc_container
*c
)
181 struct flock lk
= {0};
183 /* $lxcpath + '/' + $name + '/partial' + \0 */
184 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
186 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
187 if (ret
< 0 || (size_t)ret
>= len
)
190 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
195 lk
.l_whence
= SEEK_SET
;
197 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
199 if (errno
== EINVAL
) {
200 ret
= flock(fd
, LOCK_EX
);
205 SYSERROR("Failed to lock partial file %s", path
);
213 static void remove_partial(struct lxc_container
*c
, int fd
)
220 /* $lxcpath + '/' + $name + '/partial' + \0 */
221 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
223 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
224 if (ret
< 0 || (size_t)ret
>= len
)
229 SYSERROR("Failed to remove partial file %s", path
);
233 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
234 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
235 * container configuration file.
236 * The container_disk_lock also takes the container_mem_lock.
237 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
238 * NOTHING mutexes two independent programs with their own struct
239 * lxc_container for the same c->name, between API calls. For instance,
240 * c->config_read(); c->start(); Between those calls, data on disk
241 * could change (which shouldn't bother the caller unless for instance
242 * the rootfs get moved). c->config_read(); update; c->config_write();
243 * Two such updaters could race. The callers should therefore check their
244 * results. Trying to prevent that would necessarily expose us to deadlocks
245 * due to hung callers. So I prefer to keep the locks only within our own
246 * functions, not across functions.
248 * If you're going to clone while holding a lxccontainer, increment
249 * c->numthreads (under privlock) before forking. When deleting,
250 * decrement numthreads under privlock, then if it hits 0 you can delete.
251 * Do not ever use a lxccontainer whose numthreads you did not bump.
254 static void lxc_container_free(struct lxc_container
*c
)
260 c
->configfile
= NULL
;
262 free(c
->error_string
);
263 c
->error_string
= NULL
;
266 lxc_putlock(c
->slock
);
271 lxc_putlock(c
->privlock
);
279 lxc_conf_free(c
->lxc_conf
);
283 free(c
->config_path
);
284 c
->config_path
= NULL
;
289 /* Consider the following case:
291 * |====================================================================|
292 * | freer | racing get()er |
293 * |====================================================================|
294 * | lxc_container_put() | lxc_container_get() |
295 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
296 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
297 * | \ lxcunlock() | \ |
298 * | \ lxc_container_free() | \ lxclock() returns |
299 * | | \ c->numthreads < 1 -> return 0 |
300 * | \ \ (free stuff) | |
301 * | \ \ sem_destroy(privlock) | |
302 * |_______________________________|____________________________________|
304 * When the get()er checks numthreads the first time, one of the following
306 * 1. freer has set numthreads = 0. get() returns 0
307 * 2. freer is between lxclock and setting numthreads to 0. get()er will
308 * sem_wait on privlock, get lxclock after freer() drops it, then see
309 * numthreads is 0 and exit without touching lxclock again..
310 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
311 * will see --numthreads = 1 and not call lxc_container_free().
314 int lxc_container_get(struct lxc_container
*c
)
319 /* If someone else has already started freeing the container, don't try
320 * to take the lock, which may be invalid.
322 if (c
->numthreads
< 1)
325 if (container_mem_lock(c
))
328 /* Bail without trying to unlock, bc the privlock is now probably in
331 if (c
->numthreads
< 1)
335 container_mem_unlock(c
);
340 int lxc_container_put(struct lxc_container
*c
)
345 if (container_mem_lock(c
))
350 if (c
->numthreads
< 1) {
351 container_mem_unlock(c
);
352 lxc_container_free(c
);
356 container_mem_unlock(c
);
361 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
370 if (container_mem_lock(c
))
376 statret
= stat(c
->configfile
, &statbuf
);
383 container_mem_unlock(c
);
388 #define WRAP_API(rettype, fnname) \
389 static rettype fnname(struct lxc_container *c) \
392 bool reset_config = false; \
394 if (!current_config && c && c->lxc_conf) { \
395 current_config = c->lxc_conf; \
396 reset_config = true; \
399 ret = do_##fnname(c); \
401 current_config = NULL; \
406 #define WRAP_API_1(rettype, fnname, t1) \
407 static rettype fnname(struct lxc_container *c, t1 a1) \
410 bool reset_config = false; \
412 if (!current_config && c && c->lxc_conf) { \
413 current_config = c->lxc_conf; \
414 reset_config = true; \
417 ret = do_##fnname(c, a1); \
419 current_config = NULL; \
424 #define WRAP_API_2(rettype, fnname, t1, t2) \
425 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
428 bool reset_config = false; \
430 if (!current_config && c && c->lxc_conf) { \
431 current_config = c->lxc_conf; \
432 reset_config = true; \
435 ret = do_##fnname(c, a1, a2); \
437 current_config = NULL; \
442 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
443 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
446 bool reset_config = false; \
448 if (!current_config && c && c->lxc_conf) { \
449 current_config = c->lxc_conf; \
450 reset_config = true; \
453 ret = do_##fnname(c, a1, a2, a3); \
455 current_config = NULL; \
460 WRAP_API(bool, lxcapi_is_defined
)
462 static const char *do_lxcapi_state(struct lxc_container
*c
)
469 s
= lxc_getstate(c
->name
, c
->config_path
);
470 return lxc_state2str(s
);
473 WRAP_API(const char *, lxcapi_state
)
475 static bool is_stopped(struct lxc_container
*c
)
479 s
= lxc_getstate(c
->name
, c
->config_path
);
480 return (s
== STOPPED
);
483 static bool do_lxcapi_is_running(struct lxc_container
*c
)
488 return !is_stopped(c
);
491 WRAP_API(bool, lxcapi_is_running
)
493 static bool do_lxcapi_freeze(struct lxc_container
*c
)
500 ret
= lxc_freeze(c
->name
, c
->config_path
);
507 WRAP_API(bool, lxcapi_freeze
)
509 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
516 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
523 WRAP_API(bool, lxcapi_unfreeze
)
525 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
530 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
533 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
535 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
536 int stdoutfd
, int stderrfd
, int escape
)
543 current_config
= c
->lxc_conf
;
544 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
545 current_config
= NULL
;
550 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
554 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
557 NOTICE("The console log is empty");
558 else if (ret
== -EFAULT
)
559 NOTICE("The container does not keep a console log");
560 else if (ret
== -ENOENT
)
561 NOTICE("The container does not keep a console log file");
562 else if (ret
== -EIO
)
563 NOTICE("Failed to write console log to log file");
565 ERROR("Failed to retrieve console log");
571 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
573 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
578 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
581 WRAP_API(pid_t
, lxcapi_init_pid
)
583 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
586 c
->lxc_conf
= lxc_conf_init();
591 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
597 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
601 bool need_disklock
= false, ret
= false;
606 fname
= c
->configfile
;
612 /* If we're reading something other than the container's config, we only
613 * need to lock the in-memory container. If loading the container's
614 * config file, take the disk lock.
616 if (strcmp(fname
, c
->configfile
) == 0)
617 need_disklock
= true;
620 lret
= container_disk_lock(c
);
622 lret
= container_mem_lock(c
);
626 ret
= load_config_locked(c
, fname
);
629 container_disk_unlock(c
);
631 container_mem_unlock(c
);
636 WRAP_API_1(bool, lxcapi_load_config
, const char *)
638 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
640 if (!c
|| !c
->lxc_conf
)
643 if (container_mem_lock(c
))
646 c
->daemonize
= state
;
648 container_mem_unlock(c
);
653 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
655 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
657 if (!c
|| !c
->lxc_conf
)
660 if (container_mem_lock(c
))
663 c
->lxc_conf
->close_all_fds
= state
;
665 container_mem_unlock(c
);
670 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
672 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
680 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
684 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
686 static bool am_single_threaded(void)
689 struct dirent
*direntp
;
692 dir
= opendir("/proc/self/task");
696 while ((direntp
= readdir(dir
))) {
697 if (strcmp(direntp
->d_name
, ".") == 0)
700 if (strcmp(direntp
->d_name
, "..") == 0)
712 static void push_arg(char ***argp
, char *arg
, int *nargs
)
717 copy
= must_copy_string(arg
);
720 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
729 static char **split_init_cmd(const char *incmd
)
735 char *saveptr
= NULL
;
740 len
= strlen(incmd
) + 1;
742 strncpy(copy
, incmd
, len
);
743 copy
[len
- 1] = '\0';
746 argv
= malloc(sizeof(char *));
750 for (; (p
= strtok_r(copy
, " ", &saveptr
)); copy
= NULL
)
751 push_arg(&argv
, p
, &nargs
);
761 static void free_init_cmd(char **argv
)
774 static int lxc_rcv_status(int state_socket
)
780 /* Receive container state. */
781 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
,
786 TRACE("Caught EINTR; retrying");
793 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
797 /* Close write end of the socket pair. */
798 close(handler
->state_socket_pair
[1]);
799 handler
->state_socket_pair
[1] = -1;
801 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
803 /* Close read end of the socket pair. */
804 close(handler
->state_socket_pair
[0]);
805 handler
->state_socket_pair
[0] = -1;
807 /* The first child is going to fork() again and then exits. So we reap
808 * the first child here.
810 ret
= wait_for_pid(pid
);
812 DEBUG("Failed waiting on first child %d", pid
);
814 DEBUG("First child %d exited", pid
);
817 SYSERROR("Failed to receive the container state");
821 /* If we receive anything else then running we know that the container
824 if (state
!= RUNNING
) {
825 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
826 lxc_state2str(state
));
830 TRACE("Container is in \"RUNNING\" state");
834 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
837 struct lxc_handler
*handler
;
838 struct lxc_conf
*conf
;
839 char *default_args
[] = {
843 char **init_cmd
= NULL
;
844 int keepfds
[3] = {-1, -1, -1};
846 /* container does exist */
850 /* If anything fails before we set error_num, we want an error in there.
854 /* Container has not been setup. */
858 ret
= ongoing_create(c
);
860 ERROR("Failed checking for incomplete container creation");
862 } else if (ret
== 1) {
863 ERROR("Ongoing container creation detected");
865 } else if (ret
== 2) {
866 ERROR("Failed to create container");
867 do_lxcapi_destroy(c
);
871 if (container_mem_lock(c
))
876 /* initialize handler */
877 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
879 container_mem_unlock(c
);
884 if (useinit
&& conf
->execute_cmd
)
885 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
887 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
890 /* ... otherwise use default_args. */
893 ERROR("No valid init detected");
894 lxc_free_handler(handler
);
900 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
901 * here to protect the on disk container? We don't want to exclude
902 * things like lxc_info while the container is running.
911 free_init_cmd(init_cmd
);
912 lxc_free_handler(handler
);
918 /* Set to NULL because we don't want father unlink
919 * the PID file, child will do the free and unlink.
923 /* Wait for container to tell us whether it started
926 started
= wait_on_daemonized_start(handler
, pid
);
928 free_init_cmd(init_cmd
);
929 lxc_free_handler(handler
);
935 /* We don't really care if this doesn't print all the
936 * characters. All that it means is that the proctitle will be
937 * ugly. Similarly, we also don't care if setproctitle() fails.
939 (void)snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
940 INFO("Attempting to set proc title to %s", title
);
941 (void)setproctitle(title
);
943 /* We fork() a second time to be reparented to init. Like
944 * POSIX's daemon() function we change to "/" and redirect
945 * std{in,out,err} to /dev/null.
949 SYSERROR("Failed to fork first child process");
955 free_init_cmd(init_cmd
);
956 lxc_free_handler(handler
);
962 /* change to / directory */
965 SYSERROR("Failed to change to \"/\" directory");
969 keepfds
[0] = handler
->conf
->maincmd_fd
;
970 keepfds
[1] = handler
->state_socket_pair
[0];
971 keepfds
[2] = handler
->state_socket_pair
[1];
972 ret
= lxc_check_inherited(conf
, true, keepfds
,
973 sizeof(keepfds
) / sizeof(keepfds
[0]));
977 /* redirect std{in,out,err} to /dev/null */
980 ERROR("Failed to redirect std{in,out,err} to /dev/null");
984 /* become session leader */
987 TRACE("Process %d is already process group leader", lxc_raw_getpid());
989 if (!am_single_threaded()) {
990 ERROR("Cannot start non-daemonized container when threaded");
991 free_init_cmd(init_cmd
);
992 lxc_free_handler(handler
);
997 /* We need to write PID file after daemonize, so we always
998 * write the right PID.
1002 char pidstr
[LXC_NUMSTRLEN64
];
1004 w
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", (int)lxc_raw_getpid());
1005 if (w
< 0 || (size_t)w
>= LXC_NUMSTRLEN64
) {
1006 free_init_cmd(init_cmd
);
1007 lxc_free_handler(handler
);
1009 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1012 _exit(EXIT_FAILURE
);
1017 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1019 free_init_cmd(init_cmd
);
1020 lxc_free_handler(handler
);
1022 SYSERROR("Failed to write '%s'", c
->pidfile
);
1025 _exit(EXIT_FAILURE
);
1033 /* Unshare the mount namespace if requested */
1034 if (conf
->monitor_unshare
) {
1035 ret
= unshare(CLONE_NEWNS
);
1037 SYSERROR("failed to unshare mount namespace");
1038 lxc_free_handler(handler
);
1043 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1045 SYSERROR("Failed to make / rslave at startup");
1046 lxc_free_handler(handler
);
1053 if (conf
->reboot
== 2) {
1054 /* initialize handler */
1055 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1062 keepfds
[0] = handler
->conf
->maincmd_fd
;
1063 keepfds
[1] = handler
->state_socket_pair
[0];
1064 keepfds
[2] = handler
->state_socket_pair
[1];
1065 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1066 sizeof(keepfds
) / sizeof(keepfds
[0]));
1068 lxc_free_handler(handler
);
1074 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1075 c
->daemonize
, &c
->error_num
);
1077 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1078 c
->daemonize
, &c
->error_num
);
1080 if (conf
->reboot
== 1) {
1081 INFO("Container requested reboot");
1092 free_init_cmd(init_cmd
);
1094 if (c
->daemonize
&& ret
!= 0)
1095 _exit(EXIT_FAILURE
);
1096 else if (c
->daemonize
)
1097 _exit(EXIT_SUCCESS
);
1105 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1110 current_config
= c
? c
->lxc_conf
: NULL
;
1111 ret
= do_lxcapi_start(c
, useinit
, argv
);
1112 current_config
= NULL
;
1117 /* Note, there MUST be an ending NULL. */
1118 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1121 char **inargs
= NULL
;
1124 /* container exists */
1128 current_config
= c
->lxc_conf
;
1130 va_start(ap
, useinit
);
1131 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1136 /* pass NULL if no arguments were supplied */
1137 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1142 for (arg
= inargs
; *arg
; arg
++)
1147 current_config
= NULL
;
1152 static bool do_lxcapi_stop(struct lxc_container
*c
)
1159 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1164 WRAP_API(bool, lxcapi_stop
)
1166 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1173 mode_t mask
= umask(0002);
1174 ret
= mkdir(path
, 0770);
1179 if (errno
!= EEXIST
)
1186 p
= alloca(len
+ 1);
1188 if (!lxc_list_empty(&conf
->id_map
)) {
1189 ret
= chown_mapped_root(p
, conf
);
1197 /* Create the standard expected container dir. */
1198 static bool create_container_dir(struct lxc_container
*c
)
1204 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1209 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1210 if (ret
< 0 || (size_t)ret
>= len
) {
1215 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1221 /* do_storage_create: thin wrapper around storage_create(). Like
1222 * storage_create(), it returns a mounted bdev on success, NULL on error.
1224 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1226 struct bdev_specs
*specs
)
1231 struct lxc_storage
*bdev
;
1233 /* rootfs.path or lxcpath/lxcname/rootfs */
1234 if (c
->lxc_conf
->rootfs
.path
&&
1235 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1236 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1237 len
= strlen(rpath
) + 1;
1239 ret
= snprintf(dest
, len
, "%s", rpath
);
1241 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1242 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1244 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1246 if (ret
< 0 || (size_t)ret
>= len
)
1249 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1251 ERROR("Failed to create \"%s\" storage", type
);
1255 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1256 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1260 /* If we are not root, chown the rootfs dir to root in the target user
1264 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1265 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1267 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1268 suggest_default_idmap();
1277 static char *lxcbasename(char *path
)
1281 p
= path
+ strlen(path
) - 1;
1282 while (*p
!= '/' && p
> path
)
1288 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1289 bool need_null_stdfds
, char *const argv
[])
1299 SYSERROR("Failed to fork task for container creation template");
1303 if (pid
== 0) { /* child */
1305 char *namearg
, *patharg
, *rootfsarg
;
1308 struct lxc_storage
*bdev
= NULL
;
1309 struct lxc_conf
*conf
= c
->lxc_conf
;
1312 if (need_null_stdfds
) {
1313 ret
= null_stdfds();
1315 _exit(EXIT_FAILURE
);
1318 bdev
= storage_init(c
->lxc_conf
);
1320 ERROR("Failed to initialize storage");
1321 _exit(EXIT_FAILURE
);
1326 ret
= unshare(CLONE_NEWNS
);
1328 ERROR("Failed to unshare CLONE_NEWNS");
1329 _exit(EXIT_FAILURE
);
1332 ret
= detect_shared_rootfs();
1334 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1336 SYSERROR("Failed to make \"/\" rslave");
1337 ERROR("Continuing...");
1342 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1344 ERROR("Unprivileged users can only create "
1345 "btrfs and directory-backed containers");
1346 _exit(EXIT_FAILURE
);
1349 if (strcmp(bdev
->type
, "overlay") == 0 ||
1350 strcmp(bdev
->type
, "overlayfs") == 0) {
1351 /* If we create an overlay container we need to
1352 * rsync the contents into
1353 * <container-path>/<container-name>/rootfs.
1354 * However, the overlay mount function will
1356 * <container-path>/<container-name>/delta0
1358 * <container-path>/<container-name>/rootfs
1359 * which means we would rsync the rootfs into
1360 * the delta directory. That doesn't make sense
1361 * since the delta directory only exists to
1362 * record the differences to
1363 * <container-path>/<container-name>/rootfs. So
1364 * let's simply bind-mount here and then rsync
1366 * <container-path>/<container-name>/rootfs.
1370 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1372 ERROR("Failed to get rootfs");
1373 _exit(EXIT_FAILURE
);
1376 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1378 ERROR("Failed to mount rootfs");
1382 ret
= bdev
->ops
->mount(bdev
);
1384 ERROR("Failed to mount rootfs");
1385 _exit(EXIT_FAILURE
);
1388 } else { /* TODO come up with a better way here! */
1391 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1392 bdev
->dest
= strdup(src
);
1395 /* Create our new array, pre-pend the template name and base
1399 for (nargs
= 0; argv
[nargs
]; nargs
++) {
1402 /* template, path, rootfs and name args */
1405 newargv
= malloc(nargs
* sizeof(*newargv
));
1407 _exit(EXIT_FAILURE
);
1408 newargv
[0] = lxcbasename(tpath
);
1411 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1412 patharg
= malloc(len
);
1414 _exit(EXIT_FAILURE
);
1415 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1416 if (ret
< 0 || ret
>= len
)
1417 _exit(EXIT_FAILURE
);
1418 newargv
[1] = patharg
;
1421 len
= strlen("--name=") + strlen(c
->name
) + 1;
1422 namearg
= malloc(len
);
1424 _exit(EXIT_FAILURE
);
1425 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1426 if (ret
< 0 || ret
>= len
)
1427 _exit(EXIT_FAILURE
);
1428 newargv
[2] = namearg
;
1431 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1432 rootfsarg
= malloc(len
);
1434 _exit(EXIT_FAILURE
);
1435 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1436 if (ret
< 0 || ret
>= len
)
1437 _exit(EXIT_FAILURE
);
1438 newargv
[3] = rootfsarg
;
1440 /* add passed-in args */
1442 for (i
= 4; i
< nargs
; i
++)
1443 newargv
[i
] = argv
[i
- 4];
1445 /* add trailing NULL */
1447 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1449 _exit(EXIT_FAILURE
);
1450 newargv
[nargs
- 1] = NULL
;
1452 /* If we're running the template in a mapped userns, then we
1453 * prepend the template command with: lxc-usernsexec <-m map1>
1454 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1455 * the mapped uid for our geteuid()
1457 if (!lxc_list_empty(&conf
->id_map
)) {
1458 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1460 char txtuid
[20], txtgid
[20];
1461 struct lxc_list
*it
;
1465 n2
= malloc(n2args
* sizeof(*n2
));
1467 _exit(EXIT_FAILURE
);
1470 tpath
= "lxc-usernsexec";
1471 n2
[0] = "lxc-usernsexec";
1472 lxc_list_for_each(it
, &conf
->id_map
) {
1475 n2
= realloc(n2
, n2args
* sizeof(char *));
1477 _exit(EXIT_FAILURE
);
1479 n2
[n2args
- 2] = "-m";
1480 n2
[n2args
- 1] = malloc(200);
1481 if (!n2
[n2args
- 1])
1482 _exit(EXIT_FAILURE
);
1484 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1485 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1486 map
->nsid
, map
->hostid
, map
->range
);
1487 if (ret
< 0 || ret
>= 200)
1488 _exit(EXIT_FAILURE
);
1491 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1492 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1493 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1495 _exit(EXIT_FAILURE
);
1497 if (hostuid_mapped
< 0) {
1498 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1499 n2
[n2args
++] = "-m";
1500 if (hostuid_mapped
< 0) {
1501 ERROR("Failed to find free uid to map");
1502 _exit(EXIT_FAILURE
);
1505 n2
[n2args
++] = malloc(200);
1506 if (!n2
[n2args
- 1]) {
1507 SYSERROR("out of memory");
1508 _exit(EXIT_FAILURE
);
1510 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1511 hostuid_mapped
, geteuid());
1512 if (ret
< 0 || ret
>= 200)
1513 _exit(EXIT_FAILURE
);
1516 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1517 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1518 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1520 _exit(EXIT_FAILURE
);
1522 if (hostgid_mapped
< 0) {
1523 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1524 n2
[n2args
++] = "-m";
1525 if (hostgid_mapped
< 0) {
1526 ERROR("Failed to find free gid to map");
1527 _exit(EXIT_FAILURE
);
1530 n2
[n2args
++] = malloc(200);
1531 if (!n2
[n2args
- 1]) {
1532 SYSERROR("out of memory");
1533 _exit(EXIT_FAILURE
);
1536 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1537 hostgid_mapped
, getegid());
1538 if (ret
< 0 || ret
>= 200)
1539 _exit(EXIT_FAILURE
);
1541 n2
[n2args
++] = "--";
1542 for (i
= 0; i
< nargs
; i
++)
1543 n2
[i
+ n2args
] = newargv
[i
];
1546 /* Finally add "--mapped-uid $uid" to tell template what
1547 * to chown cached images to.
1550 n2
= realloc(n2
, n2args
* sizeof(char *));
1552 _exit(EXIT_FAILURE
);
1554 /* note n2[n2args-1] is NULL */
1555 n2
[n2args
- 5] = "--mapped-uid";
1556 snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1557 n2
[n2args
- 4] = txtuid
;
1558 n2
[n2args
- 3] = "--mapped-gid";
1559 snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1560 n2
[n2args
- 2] = txtgid
;
1561 n2
[n2args
- 1] = NULL
;
1566 execvp(tpath
, newargv
);
1567 SYSERROR("Failed to execute template %s", tpath
);
1568 _exit(EXIT_FAILURE
);
1571 ret
= wait_for_pid(pid
);
1573 ERROR("Failed to create container from template");
1580 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1589 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1593 f
= fopen(path
, "r");
1597 ret
= fseek(f
, 0, SEEK_END
);
1606 ret
= fseek(f
, 0, SEEK_SET
);
1610 ret
= fseek(f
, 0, SEEK_SET
);
1615 contents
= malloc(flen
+ 1);
1619 len
= fread(contents
, 1, flen
, f
);
1621 goto out_free_contents
;
1623 contents
[flen
] = '\0';
1627 goto out_free_contents
;
1630 tpath
= get_template_path(t
);
1632 ERROR("Invalid template \"%s\" specified", t
);
1633 goto out_free_contents
;
1636 ret
= sha1sum_file(tpath
, md_value
);
1638 ERROR("Failed to get sha1sum of %s", tpath
);
1640 goto out_free_contents
;
1645 f
= fopen(path
, "w");
1647 SYSERROR("Reopening config for writing");
1652 fprintf(f
, "# Template used to create this container: %s\n", t
);
1654 fprintf(f
, "# Parameters passed to the template:");
1656 fprintf(f
, " %s", *argv
);
1662 fprintf(f
, "# Template script checksum (SHA-1): ");
1663 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1664 fprintf(f
, "%02x", md_value
[i
]);
1667 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1668 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1669 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1670 fprintf(f
, "# (Be aware this has security implications)\n\n");
1671 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1672 SYSERROR("Writing original contents");
1692 SYSERROR("Error prepending header");
1699 static void lxcapi_clear_config(struct lxc_container
*c
)
1701 if (!c
|| !c
->lxc_conf
)
1704 lxc_conf_free(c
->lxc_conf
);
1708 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1712 * create a container with the given parameters.
1713 * @c: container to be created. It has the lxcpath, name, and a starting
1714 * configuration already set
1715 * @t: the template to execute to instantiate the root filesystem and
1716 * adjust the configuration.
1717 * @bdevtype: backing store type to use. If NULL, dir will be used.
1718 * @specs: additional parameters for the backing store, i.e. LVM vg to
1721 * @argv: the arguments to pass to the template, terminated by NULL. If no
1722 * arguments, you can just pass NULL.
1724 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1725 const char *bdevtype
, struct bdev_specs
*specs
,
1726 int flags
, char *const argv
[])
1738 tpath
= get_template_path(t
);
1740 ERROR("Unknown template \"%s\"", t
);
1745 /* If a template is passed in, and the rootfs already is defined in the
1746 * container config and exists, then the caller is trying to create an
1747 * existing container. Return an error, but do NOT delete the container.
1749 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1750 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1751 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1757 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1758 ERROR("Error loading default configuration file %s",
1759 lxc_global_config_value("lxc.default_config"));
1764 if (!create_container_dir(c
))
1767 /* If both template and rootfs.path are set, template is setup as
1768 * rootfs.path. The container is already created if we have a config and
1769 * rootfs.path is accessible
1771 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1772 /* No template passed in and rootfs does not exist. */
1773 if (!c
->save_config(c
, NULL
)) {
1774 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1781 /* Rootfs passed into configuration, but does not exist. */
1782 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1785 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1786 /* Rootfs already existed, user just wanted to save the loaded
1789 if (!c
->save_config(c
, NULL
))
1790 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1795 /* Mark that this container is being created */
1796 partial_fd
= create_partial(c
);
1800 /* No need to get disk lock bc we have the partial lock. */
1804 /* Create the storage.
1805 * Note we can't do this in the same task as we use to execute the
1806 * template because of the way zfs works.
1807 * After you 'zfs create', zfs mounts the fs only in the initial
1812 SYSERROR("Failed to fork task for container creation template");
1816 if (pid
== 0) { /* child */
1817 struct lxc_storage
*bdev
= NULL
;
1819 bdev
= do_storage_create(c
, bdevtype
, specs
);
1821 ERROR("Failed to create %s storage for %s",
1822 bdevtype
? bdevtype
: "(none)", c
->name
);
1823 _exit(EXIT_FAILURE
);
1826 /* Save config file again to store the new rootfs location. */
1827 if (!do_lxcapi_save_config(c
, NULL
)) {
1828 ERROR("Failed to save initial config for %s", c
->name
);
1829 /* Parent task won't see the storage driver in the
1830 * config so we delete it.
1832 bdev
->ops
->umount(bdev
);
1833 bdev
->ops
->destroy(bdev
);
1834 _exit(EXIT_FAILURE
);
1836 _exit(EXIT_SUCCESS
);
1838 if (wait_for_pid(pid
) != 0)
1841 /* Reload config to get the rootfs. */
1842 lxc_conf_free(c
->lxc_conf
);
1844 if (!load_config_locked(c
, c
->configfile
))
1847 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1850 /* Now clear out the lxc_conf we have, reload from the created
1853 do_lxcapi_clear_config(c
);
1856 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1857 ERROR("Failed to prepend header to config file");
1861 ret
= load_config_locked(c
, c
->configfile
);
1865 if (partial_fd
>= 0)
1866 remove_partial(c
, partial_fd
);
1869 container_destroy(c
, NULL
);
1875 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1876 const char *bdevtype
, struct bdev_specs
*specs
,
1877 int flags
, char *const argv
[])
1880 current_config
= c
? c
->lxc_conf
: NULL
;
1881 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1882 current_config
= NULL
;
1886 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1889 int rebootsignal
= SIGINT
;
1893 if (!do_lxcapi_is_running(c
))
1895 pid
= do_lxcapi_init_pid(c
);
1898 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1899 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1900 if (kill(pid
, rebootsignal
) < 0) {
1901 WARN("Could not send signal %d to pid %d.", rebootsignal
, pid
);
1908 WRAP_API(bool, lxcapi_reboot
)
1910 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1914 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1915 lxc_state_t states
[MAX_STATE
] = {0};
1920 if (!do_lxcapi_is_running(c
))
1923 pid
= do_lxcapi_init_pid(c
);
1927 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1928 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1930 /* Add a new state client before sending the shutdown signal so that we
1931 * don't miss a state.
1934 states
[RUNNING
] = 2;
1935 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
1940 if (state_client_fd
< 0)
1946 if (ret
< MAX_STATE
)
1950 /* Send reboot signal to container. */
1951 killret
= kill(pid
, rebootsignal
);
1953 WARN("Could not send signal %d to pid %d", rebootsignal
, pid
);
1954 if (state_client_fd
>= 0)
1955 close(state_client_fd
);
1958 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
1963 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
1964 close(state_client_fd
);
1968 TRACE("Received state \"%s\"", lxc_state2str(ret
));
1975 WRAP_API_1(bool, lxcapi_reboot2
, int)
1977 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1981 int haltsignal
= SIGPWR
, state_client_fd
= -1;
1982 lxc_state_t states
[MAX_STATE
] = {0};
1987 if (!do_lxcapi_is_running(c
))
1990 pid
= do_lxcapi_init_pid(c
);
1994 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
1995 if (task_blocking_signal(pid
, (SIGRTMIN
+ 3)))
1996 haltsignal
= (SIGRTMIN
+ 3);
1998 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1999 haltsignal
= c
->lxc_conf
->haltsignal
;
2001 /* Add a new state client before sending the shutdown signal so that we
2002 * don't miss a state.
2005 states
[STOPPED
] = 1;
2006 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2011 if (state_client_fd
< 0)
2017 if (ret
< MAX_STATE
)
2021 /* Send shutdown signal to container. */
2022 killret
= kill(pid
, haltsignal
);
2024 WARN("Could not send signal %d to pid %d", haltsignal
, pid
);
2025 if (state_client_fd
>= 0)
2026 close(state_client_fd
);
2029 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2034 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2035 close(state_client_fd
);
2039 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2046 WRAP_API_1(bool, lxcapi_shutdown
, int)
2048 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2049 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2058 current_config
= c
->lxc_conf
;
2061 * since we're going to wait for create to finish, I don't think we
2062 * need to get a copy of the arguments.
2064 va_start(ap
, flags
);
2065 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2068 ERROR("Failed to allocate memory");
2072 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2076 current_config
= NULL
;
2080 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2082 if (!strcmp(key
, "lxc.cgroup"))
2083 return clear_unexp_config_line(conf
, key
, true);
2085 if (!strcmp(key
, "lxc.network"))
2086 return clear_unexp_config_line(conf
, key
, true);
2088 if (!strcmp(key
, "lxc.net"))
2089 return clear_unexp_config_line(conf
, key
, true);
2091 /* Clear a network with a specific index. */
2092 if (!strncmp(key
, "lxc.net.", 8)) {
2097 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2099 return clear_unexp_config_line(conf
, key
, true);
2102 if (!strcmp(key
, "lxc.hook"))
2103 return clear_unexp_config_line(conf
, key
, true);
2105 return clear_unexp_config_line(conf
, key
, false);
2108 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2112 struct lxc_config_t
*config
;
2114 if (!c
|| !c
->lxc_conf
)
2117 if (container_mem_lock(c
))
2120 config
= lxc_get_config(key
);
2121 /* Verify that the config key exists and that it has a callback
2124 if (config
&& config
->clr
)
2125 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2127 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2129 container_mem_unlock(c
);
2133 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2135 static inline bool enter_net_ns(struct lxc_container
*c
)
2137 pid_t pid
= do_lxcapi_init_pid(c
);
2139 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) && access("/proc/self/ns/user", F_OK
) == 0) {
2140 if (!switch_to_ns(pid
, "user"))
2143 return switch_to_ns(pid
, "net");
2146 /* Used by qsort and bsearch functions for comparing names. */
2147 static inline int string_cmp(char **first
, char **second
)
2149 return strcmp(*first
, *second
);
2152 /* Used by qsort and bsearch functions for comparing container names. */
2153 static inline int container_cmp(struct lxc_container
**first
,
2154 struct lxc_container
**second
)
2156 return strcmp((*first
)->name
, (*second
)->name
);
2159 static bool add_to_array(char ***names
, char *cname
, int pos
)
2161 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2163 ERROR("Out of memory");
2168 newnames
[pos
] = strdup(cname
);
2172 /* Sort the arrray as we will use binary search on it. */
2173 qsort(newnames
, pos
+ 1, sizeof(char *),
2174 (int (*)(const void *, const void *))string_cmp
);
2179 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2182 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2184 ERROR("Out of memory");
2191 /* Sort the arrray as we will use binary search on it. */
2193 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2194 (int (*)(const void *, const void *))container_cmp
);
2199 static char** get_from_array(char ***names
, char *cname
, int size
)
2201 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2205 static bool array_contains(char ***names
, char *cname
, int size
) {
2206 if(get_from_array(names
, cname
, size
) != NULL
)
2211 static bool remove_from_array(char ***names
, char *cname
, int size
)
2213 char **result
= get_from_array(names
, cname
, size
);
2214 if (result
!= NULL
) {
2221 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2224 int i
, count
= 0, pipefd
[2];
2225 char **interfaces
= NULL
;
2226 char interface
[IFNAMSIZ
];
2228 if(pipe(pipefd
) < 0) {
2229 SYSERROR("pipe failed");
2235 SYSERROR("failed to fork task to get interfaces information");
2241 if (pid
== 0) { /* child */
2242 int ret
= 1, nbytes
;
2243 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2245 /* close the read-end of the pipe */
2248 if (!enter_net_ns(c
)) {
2249 SYSERROR("failed to enter namespace");
2253 /* Grab the list of interfaces */
2254 if (getifaddrs(&interfaceArray
)) {
2255 SYSERROR("failed to get interfaces list");
2259 /* Iterate through the interfaces */
2260 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2261 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2263 ERROR("write failed");
2272 freeifaddrs(interfaceArray
);
2274 /* close the write-end of the pipe, thus sending EOF to the reader */
2279 /* close the write-end of the pipe */
2282 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2283 interface
[IFNAMSIZ
- 1] = '\0';
2285 if (array_contains(&interfaces
, interface
, count
))
2288 if(!add_to_array(&interfaces
, interface
, count
))
2289 ERROR("Failed to add \"%s\" to array", interface
);
2294 if (wait_for_pid(pid
) != 0) {
2295 for(i
=0;i
<count
;i
++)
2296 free(interfaces
[i
]);
2301 /* close the read-end of the pipe */
2304 /* Append NULL to the array */
2306 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2311 WRAP_API(char **, lxcapi_get_interfaces
)
2313 static char** do_lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
2316 int i
, count
= 0, pipefd
[2];
2317 char **addresses
= NULL
;
2318 char address
[INET6_ADDRSTRLEN
];
2320 if(pipe(pipefd
) < 0) {
2321 SYSERROR("pipe failed");
2327 SYSERROR("failed to fork task to get container ips");
2333 if (pid
== 0) { /* child */
2334 int ret
= 1, nbytes
;
2335 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2336 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2337 void *tempAddrPtr
= NULL
;
2338 char *address
= NULL
;
2340 /* close the read-end of the pipe */
2343 if (!enter_net_ns(c
)) {
2344 SYSERROR("failed to enter namespace");
2348 /* Grab the list of interfaces */
2349 if (getifaddrs(&interfaceArray
)) {
2350 SYSERROR("failed to get interfaces list");
2354 /* Iterate through the interfaces */
2355 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2356 if (tempIfAddr
->ifa_addr
== NULL
)
2359 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2360 if (family
&& strcmp(family
, "inet"))
2362 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2365 if (family
&& strcmp(family
, "inet6"))
2368 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2371 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2374 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2376 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2379 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2381 addressOutputBuffer
,
2382 sizeof(addressOutputBuffer
));
2386 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2388 ERROR("write failed");
2397 freeifaddrs(interfaceArray
);
2399 /* close the write-end of the pipe, thus sending EOF to the reader */
2404 /* close the write-end of the pipe */
2407 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2408 if(!add_to_array(&addresses
, address
, count
))
2409 ERROR("PARENT: add_to_array failed");
2413 if (wait_for_pid(pid
) != 0) {
2414 for(i
=0;i
<count
;i
++)
2420 /* close the read-end of the pipe */
2423 /* Append NULL to the array */
2425 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2430 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2432 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2435 struct lxc_config_t
*config
;
2437 if (!c
|| !c
->lxc_conf
)
2440 if (container_mem_lock(c
))
2443 config
= lxc_get_config(key
);
2444 /* Verify that the config key exists and that it has a callback
2447 if (config
&& config
->get
)
2448 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2450 container_mem_unlock(c
);
2454 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2456 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2460 if (!c
|| !c
->lxc_conf
)
2462 if (container_mem_lock(c
))
2464 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2465 container_mem_unlock(c
);
2469 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2471 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2475 /* List all config items. */
2477 return lxc_list_config_items(retv
, inlen
);
2479 if (!c
|| !c
->lxc_conf
)
2482 if (container_mem_lock(c
))
2485 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2486 * This is an intelligent result to show which keys are valid given the
2487 * type of nic it is.
2489 if (strncmp(key
, "lxc.net.", 8) == 0)
2490 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2492 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2494 container_mem_unlock(c
);
2498 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2500 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2503 bool ret
= false, need_disklock
= false;
2506 alt_file
= c
->configfile
;
2510 /* If we haven't yet loaded a config, load the stock config. */
2512 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2513 ERROR("Error loading default configuration file %s "
2515 lxc_global_config_value("lxc.default_config"),
2521 if (!create_container_dir(c
))
2524 /* If we're writing to the container's config file, take the disk lock.
2525 * Otherwise just take the memlock to protect the struct lxc_container
2526 * while we're traversing it.
2528 if (strcmp(c
->configfile
, alt_file
) == 0)
2529 need_disklock
= true;
2532 lret
= container_disk_lock(c
);
2534 lret
= container_mem_lock(c
);
2538 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2539 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2543 lret
= write_config(fd
, c
->lxc_conf
);
2552 container_disk_unlock(c
);
2554 container_mem_unlock(c
);
2559 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2562 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2568 char path
[MAXPATHLEN
];
2569 char newpath
[MAXPATHLEN
];
2570 int fd
, ret
, n
= 0, v
= 0;
2572 size_t len
= 0, bytes
= 0;
2574 if (container_disk_lock(c0
))
2577 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2578 if (ret
< 0 || ret
> MAXPATHLEN
)
2580 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2581 if (ret
< 0 || ret
> MAXPATHLEN
)
2584 /* If we find an lxc-snapshot file using the old format only listing the
2585 * number of snapshots we will keep using it. */
2586 f1
= fopen(path
, "r");
2588 n
= fscanf(f1
, "%d", &v
);
2590 if (n
== 1 && v
== 0) {
2597 f1
= fopen(path
, "w");
2600 if (fprintf(f1
, "%d\n", v
) < 0) {
2601 ERROR("Error writing new snapshots value");
2607 SYSERROR("Error writing to or closing snapshots file");
2611 /* Here we know that we have or can use an lxc-snapshot file
2612 * using the new format. */
2614 f1
= fopen(path
, "a");
2618 if (fprintf(f1
, "%s", newpath
) < 0) {
2619 ERROR("Error writing new snapshots entry");
2622 SYSERROR("Error writing to or closing snapshots file");
2628 SYSERROR("Error writing to or closing snapshots file");
2632 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2635 if (fstat(fd
, &fbuf
) < 0) {
2640 if (fbuf
.st_size
!= 0) {
2642 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2643 if (buf
== MAP_FAILED
) {
2644 SYSERROR("Failed to create mapping %s", path
);
2649 len
= strlen(newpath
);
2650 while ((del
= strstr((char *)buf
, newpath
))) {
2651 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2655 lxc_strmunmap(buf
, fbuf
.st_size
);
2656 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2657 SYSERROR("Failed to truncate file %s", path
);
2665 /* If the lxc-snapshot file is empty, remove it. */
2666 if (stat(path
, &fbuf
) < 0)
2668 if (!fbuf
.st_size
) {
2676 container_disk_unlock(c0
);
2680 static void strip_newline(char *p
)
2682 size_t len
= strlen(p
);
2685 if (p
[len
-1] == '\n')
2689 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2691 struct lxc_container
*p
;
2692 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2693 size_t pathlen
= 0, namelen
= 0;
2697 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2698 c
->config_path
, c
->name
);
2699 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2700 ERROR("Path name too long");
2703 f
= fopen(path
, "r");
2706 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2707 if (getline(&lxcname
, &namelen
, f
) == -1) {
2708 ERROR("badly formatted file %s", path
);
2711 strip_newline(lxcpath
);
2712 strip_newline(lxcname
);
2713 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2714 ERROR("Unable to find dependent container %s:%s",
2718 if (!mod_rdep(p
, c
, inc
))
2719 ERROR("Failed to update snapshots file for %s:%s",
2721 lxc_container_put(p
);
2729 static bool has_fs_snapshots(struct lxc_container
*c
)
2732 char path
[MAXPATHLEN
];
2737 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2739 if (ret
< 0 || ret
> MAXPATHLEN
)
2741 /* If the file doesn't exist there are no snapshots. */
2742 if (stat(path
, &fbuf
) < 0)
2746 f
= fopen(path
, "r");
2749 ret
= fscanf(f
, "%d", &v
);
2751 /* TODO: Figure out what to do with the return value of fscanf. */
2753 INFO("Container uses new lxc-snapshots format %s", path
);
2761 static bool has_snapshots(struct lxc_container
*c
)
2763 char path
[MAXPATHLEN
];
2764 struct dirent
*direntp
;
2768 if (!get_snappath_dir(c
, path
))
2770 dir
= opendir(path
);
2773 while ((direntp
= readdir(dir
))) {
2777 if (!strcmp(direntp
->d_name
, "."))
2780 if (!strcmp(direntp
->d_name
, ".."))
2789 static bool do_destroy_container(struct lxc_conf
*conf
) {
2792 if (am_guest_unpriv()) {
2793 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2794 "storage_destroy_wrapper");
2801 return storage_destroy(conf
);
2804 static int lxc_rmdir_onedev_wrapper(void *data
)
2806 char *arg
= (char *) data
;
2807 return lxc_rmdir_onedev(arg
, "snaps");
2810 static int lxc_unlink_exec_wrapper(void *data
)
2816 static bool container_destroy(struct lxc_container
*c
,
2817 struct lxc_storage
*storage
)
2821 struct lxc_conf
*conf
;
2826 if (!c
|| !do_lxcapi_is_defined(c
))
2830 if (container_disk_lock(c
))
2833 if (!is_stopped(c
)) {
2834 /* We should queue some sort of error - in c->error_string? */
2835 ERROR("container %s is not stopped", c
->name
);
2839 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2840 /* Start of environment variable setup for hooks */
2841 if (setenv("LXC_NAME", c
->name
, 1))
2842 SYSERROR("Failed to set environment variable for container name");
2844 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2845 SYSERROR("Failed to set environment variable for config path");
2847 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2848 SYSERROR("Failed to set environment variable for rootfs mount");
2850 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2851 SYSERROR("Failed to set environment variable for rootfs mount");
2853 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2854 SYSERROR("Failed to set environment variable for console path");
2856 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2857 SYSERROR("Failed to set environment variable for console log");
2858 /* End of environment variable setup for hooks */
2860 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2861 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2866 if (current_config
&& conf
== current_config
) {
2867 current_config
= NULL
;
2868 if (conf
->logfd
!= -1) {
2874 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2875 if (!do_destroy_container(conf
)) {
2876 ERROR("Error destroying rootfs for %s", c
->name
);
2879 INFO("Destroyed rootfs for %s", c
->name
);
2882 mod_all_rdeps(c
, false);
2884 p1
= do_lxcapi_get_config_path(c
);
2893 * strlen("config") = 6
2897 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
2900 ERROR("Failed to allocate memory");
2904 /* For an overlay container the rootfs is considered immutable and
2905 * cannot be removed when restoring from a snapshot.
2907 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
2908 !strcmp(storage
->type
, "overlayfs")) &&
2909 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
2910 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
2911 if (ret
< 0 || (size_t)ret
>= len
)
2914 if (am_guest_unpriv())
2915 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
2916 "lxc_unlink_exec_wrapper");
2920 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
2924 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
2930 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
2931 if (ret
< 0 || (size_t)ret
>= len
)
2933 if (am_guest_unpriv())
2934 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
2935 "lxc_rmdir_onedev_wrapper");
2937 ret
= lxc_rmdir_onedev(path
, "snaps");
2939 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
2943 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
2950 container_disk_unlock(c
);
2954 static bool do_lxcapi_destroy(struct lxc_container
*c
)
2956 if (!c
|| !lxcapi_is_defined(c
))
2959 if (has_snapshots(c
)) {
2960 ERROR("Container %s has snapshots; not removing", c
->name
);
2964 if (has_fs_snapshots(c
)) {
2965 ERROR("container %s has snapshots on its rootfs", c
->name
);
2969 return container_destroy(c
, NULL
);
2972 WRAP_API(bool, lxcapi_destroy
)
2974 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
2976 if (!c
|| !lxcapi_is_defined(c
))
2978 if (!lxcapi_snapshot_destroy_all(c
)) {
2979 ERROR("Error deleting all snapshots");
2982 return lxcapi_destroy(c
);
2985 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
2987 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
2991 struct lxc_config_t
*config
;
2994 config
= lxc_get_config(key
);
2998 ret
= config
->set(key
, v
, conf
, NULL
);
3002 if (lxc_config_value_empty(v
))
3003 do_clear_unexp_config_line(conf
, key
);
3005 bret
= do_append_unexp_config_line(conf
, key
, v
);
3012 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3018 c
->lxc_conf
= lxc_conf_init();
3023 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3030 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3037 if (container_mem_lock(c
))
3040 b
= do_set_config_item_locked(c
, key
, v
);
3042 container_mem_unlock(c
);
3046 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3048 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3050 if (!c
|| !c
->configfile
)
3052 return strdup(c
->configfile
);
3055 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3057 if (!c
|| !c
->config_path
)
3059 return (const char *)(c
->config_path
);
3064 * Just recalculate the c->configfile based on the
3065 * c->config_path, which must be set.
3066 * The lxc_container must be locked or not yet public.
3068 static bool set_config_filename(struct lxc_container
*c
)
3073 if (!c
->config_path
)
3076 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3077 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3078 newpath
= malloc(len
);
3082 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3083 if (ret
< 0 || ret
>= len
) {
3084 fprintf(stderr
, "Error printing out config file name\n");
3089 free(c
->configfile
);
3090 c
->configfile
= newpath
;
3095 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3099 char *oldpath
= NULL
;
3104 if (container_mem_lock(c
))
3109 ERROR("Out of memory setting new lxc path");
3115 oldpath
= c
->config_path
;
3118 /* Since we've changed the config path, we have to change the
3119 * config file name too */
3120 if (!set_config_filename(c
)) {
3121 ERROR("Out of memory setting new config filename");
3123 free(c
->config_path
);
3124 c
->config_path
= oldpath
;
3129 container_mem_unlock(c
);
3133 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3135 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3145 if (container_disk_lock(c
))
3148 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
3150 container_disk_unlock(c
);
3154 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3156 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3166 if (container_disk_lock(c
))
3169 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
3171 container_disk_unlock(c
);
3175 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3177 const char *lxc_get_global_config_item(const char *key
)
3179 return lxc_global_config_value(key
);
3182 const char *lxc_get_version(void)
3187 static int copy_file(const char *old
, const char *new)
3194 if (file_exists(new)) {
3195 ERROR("copy destination %s exists", new);
3198 ret
= stat(old
, &sbuf
);
3200 INFO("Error stat'ing %s", old
);
3204 in
= open(old
, O_RDONLY
);
3206 SYSERROR("Error opening original file %s", old
);
3209 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3211 SYSERROR("Error opening new file %s", new);
3217 len
= read(in
, buf
, 8096);
3219 SYSERROR("Error reading old file %s", old
);
3224 ret
= write(out
, buf
, len
);
3225 if (ret
< len
) { /* should we retry? */
3226 SYSERROR("Error: write to new file %s was interrupted", new);
3233 /* We set mode, but not owner/group. */
3234 ret
= chmod(new, sbuf
.st_mode
);
3236 SYSERROR("Error setting mode on %s", new);
3248 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3251 struct lxc_list
*it
;
3254 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3255 cpath
= alloca(len
);
3256 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3257 if (ret
< 0 || ret
>= len
)
3260 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3261 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3262 char *hookname
= it
->elem
;
3263 char *fname
= strrchr(hookname
, '/');
3264 char tmppath
[MAXPATHLEN
];
3265 if (!fname
) /* relative path - we don't support, but maybe we should */
3267 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3268 /* this hook is public - ignore */
3271 /* copy the script, and change the entry in confile */
3272 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3273 c
->config_path
, c
->name
, fname
+1);
3274 if (ret
< 0 || ret
>= MAXPATHLEN
)
3276 ret
= copy_file(it
->elem
, tmppath
);
3280 it
->elem
= strdup(tmppath
);
3282 ERROR("out of memory copying hook path");
3288 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3289 c
->config_path
, oldc
->name
, c
->name
)) {
3290 ERROR("Error saving new hooks in clone");
3293 do_lxcapi_save_config(c
, NULL
);
3298 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3300 char newpath
[MAXPATHLEN
];
3301 char *oldpath
= oldc
->lxc_conf
->fstab
;
3307 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3309 char *p
= strrchr(oldpath
, '/');
3312 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3313 c
->config_path
, c
->name
, p
);
3314 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3315 ERROR("error printing new path for %s", oldpath
);
3318 if (file_exists(newpath
)) {
3319 ERROR("error: fstab file %s exists", newpath
);
3323 if (copy_file(oldpath
, newpath
) < 0) {
3324 ERROR("error: copying %s to %s", oldpath
, newpath
);
3327 free(c
->lxc_conf
->fstab
);
3328 c
->lxc_conf
->fstab
= strdup(newpath
);
3329 if (!c
->lxc_conf
->fstab
) {
3330 ERROR("error: allocating pathname");
3333 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3334 ERROR("error saving new lxctab");
3341 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3343 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3346 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3348 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3349 WARN("Error copying reverse dependencies");
3352 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3354 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3355 WARN("Error copying reverse dependencies");
3358 if (copy_file(path0
, path1
) < 0) {
3359 INFO("Error copying reverse dependencies");
3364 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3367 char path
[MAXPATHLEN
];
3371 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3373 if (ret
< 0 || ret
>= MAXPATHLEN
)
3375 f
= fopen(path
, "a");
3379 /* If anything goes wrong, just return an error. */
3380 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3388 * If the fs natively supports snapshot clones with no penalty,
3389 * then default to those even if not requested.
3390 * Currently we only do this for btrfs.
3392 bool should_default_to_snapshot(struct lxc_container
*c0
,
3393 struct lxc_container
*c1
)
3395 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3396 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3397 char *p0
= alloca(l0
+ 1);
3398 char *p1
= alloca(l1
+ 1);
3399 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3401 snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3402 snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3404 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3407 if (is_btrfs_subvol(rootfs
) <= 0)
3410 return btrfs_same_fs(p0
, p1
) == 0;
3413 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3414 const char *newtype
, int flags
, const char *bdevdata
,
3417 struct lxc_storage
*bdev
;
3420 if (should_default_to_snapshot(c0
, c
))
3421 flags
|= LXC_CLONE_SNAPSHOT
;
3423 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3424 bdevdata
, newsize
, &need_rdep
);
3426 ERROR("Error copying storage.");
3430 /* Set new rootfs. */
3431 free(c
->lxc_conf
->rootfs
.path
);
3432 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3435 if (!c
->lxc_conf
->rootfs
.path
) {
3436 ERROR("Out of memory while setting storage path.");
3440 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3441 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3442 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3443 c
->lxc_conf
->rootfs
.path
)) {
3444 ERROR("Error saving new rootfs to cloned config.");
3448 if (flags
& LXC_CLONE_SNAPSHOT
)
3449 copy_rdepends(c
, c0
);
3451 if (!add_rdepends(c
, c0
))
3452 WARN("Error adding reverse dependency from %s to %s",
3456 mod_all_rdeps(c
, true);
3461 struct clone_update_data
{
3462 struct lxc_container
*c0
;
3463 struct lxc_container
*c1
;
3468 static int clone_update_rootfs(struct clone_update_data
*data
)
3470 struct lxc_container
*c0
= data
->c0
;
3471 struct lxc_container
*c
= data
->c1
;
3472 int flags
= data
->flags
;
3473 char **hookargs
= data
->hookargs
;
3475 char path
[MAXPATHLEN
];
3476 struct lxc_storage
*bdev
;
3478 struct lxc_conf
*conf
= c
->lxc_conf
;
3480 /* update hostname in rootfs */
3481 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3483 if (setgid(0) < 0) {
3484 ERROR("Failed to setgid to 0");
3487 if (setuid(0) < 0) {
3488 ERROR("Failed to setuid to 0");
3491 if (setgroups(0, NULL
) < 0)
3492 WARN("Failed to clear groups");
3494 if (unshare(CLONE_NEWNS
) < 0)
3496 bdev
= storage_init(c
->lxc_conf
);
3499 if (strcmp(bdev
->type
, "dir") != 0) {
3500 if (unshare(CLONE_NEWNS
) < 0) {
3501 ERROR("error unsharing mounts");
3505 if (detect_shared_rootfs()) {
3506 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3507 SYSERROR("Failed to make / rslave");
3508 ERROR("Continuing...");
3511 if (bdev
->ops
->mount(bdev
) < 0) {
3515 } else { /* TODO come up with a better way */
3517 bdev
->dest
= strdup(bdev
->src
);
3520 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3521 /* Start of environment variable setup for hooks */
3522 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1)) {
3523 SYSERROR("failed to set environment variable for source container name");
3525 if (setenv("LXC_NAME", c
->name
, 1)) {
3526 SYSERROR("failed to set environment variable for container name");
3528 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
3529 SYSERROR("failed to set environment variable for config path");
3531 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
3532 SYSERROR("failed to set environment variable for rootfs mount");
3534 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
3535 SYSERROR("failed to set environment variable for rootfs mount");
3538 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3539 ERROR("Error executing clone hook for %s", c
->name
);
3545 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3546 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3549 if (ret
< 0 || ret
>= MAXPATHLEN
)
3551 if (!file_exists(path
))
3553 if (!(fout
= fopen(path
, "w"))) {
3554 SYSERROR("unable to open %s: ignoring", path
);
3557 if (fprintf(fout
, "%s", c
->name
) < 0) {
3561 if (fclose(fout
) < 0)
3570 static int clone_update_rootfs_wrapper(void *data
)
3572 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3573 return clone_update_rootfs(arg
);
3577 * We want to support:
3578 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3579 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3581 -s [ implies overlay]
3584 only rootfs gets converted (copied/snapshotted) on clone.
3587 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3589 char *p
= strrchr(path
, '/');
3595 ret
= do_create_container_dir(path
, conf
);
3600 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3601 const char *lxcpath
, int flags
,
3602 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3605 char newpath
[MAXPATHLEN
];
3607 struct clone_update_data data
;
3608 size_t saved_unexp_len
;
3610 int storage_copied
= 0;
3611 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3612 struct lxc_container
*c2
= NULL
;
3614 if (!c
|| !do_lxcapi_is_defined(c
))
3617 if (container_mem_lock(c
))
3620 if (!is_stopped(c
)) {
3621 ERROR("error: Original container (%s) is running", c
->name
);
3625 /* Make sure the container doesn't yet exist. */
3629 lxcpath
= do_lxcapi_get_config_path(c
);
3630 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3631 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3632 SYSERROR("clone: failed making config pathname");
3636 if (file_exists(newpath
)) {
3637 ERROR("error: clone: %s exists", newpath
);
3641 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3642 if (ret
< 0 && errno
!= EEXIST
) {
3643 ERROR("Error creating container dir for %s", newpath
);
3647 /* Copy the configuration. Tweak it as needed. */
3648 if (c
->lxc_conf
->rootfs
.path
) {
3649 origroot
= c
->lxc_conf
->rootfs
.path
;
3650 c
->lxc_conf
->rootfs
.path
= NULL
;
3653 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3654 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3656 SYSERROR("Failed to open \"%s\"", newpath
);
3660 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3661 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3662 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3663 if (!c
->lxc_conf
->unexpanded_config
) {
3668 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3669 write_config(fd
, c
->lxc_conf
);
3671 c
->lxc_conf
->rootfs
.path
= origroot
;
3672 free(c
->lxc_conf
->unexpanded_config
);
3673 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3674 saved_unexp_conf
= NULL
;
3675 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3677 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3678 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3679 SYSERROR("clone: failed making rootfs pathname");
3683 ret
= mkdir(newpath
, 0755);
3685 /* For an overlay container the rootfs is considered immutable
3686 * and will not have been removed when restoring from a
3689 if (errno
!= ENOENT
&&
3690 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3691 SYSERROR("Failed to create directory \"%s\"", newpath
);
3696 if (am_guest_unpriv()) {
3697 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3698 ERROR("Error chowning %s to container root", newpath
);
3703 c2
= lxc_container_new(newname
, lxcpath
);
3705 ERROR("clone: failed to create new container (%s %s)", newname
,
3710 /* copy/snapshot rootfs's */
3711 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3716 /* update utsname */
3717 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3718 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3719 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3721 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3722 ERROR("Error setting new hostname");
3728 ret
= copyhooks(c
, c2
);
3730 ERROR("error copying hooks");
3734 if (copy_fstab(c
, c2
) < 0) {
3735 ERROR("error copying fstab");
3739 /* update macaddrs */
3740 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3741 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3742 ERROR("Error updating mac addresses");
3747 /* Update absolute paths for overlay mount directories. */
3748 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3751 /* We've now successfully created c2's storage, so clear it out if we
3756 if (!c2
->save_config(c2
, NULL
))
3759 if ((pid
= fork()) < 0) {
3764 ret
= wait_for_pid(pid
);
3767 container_mem_unlock(c
);
3773 data
.hookargs
= hookargs
;
3774 if (am_guest_unpriv())
3775 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3776 &data
, "clone_update_rootfs_wrapper");
3778 ret
= clone_update_rootfs(&data
);
3780 _exit(EXIT_FAILURE
);
3782 container_mem_unlock(c
);
3783 _exit(EXIT_SUCCESS
);
3786 container_mem_unlock(c
);
3788 if (!storage_copied
)
3789 c2
->lxc_conf
->rootfs
.path
= NULL
;
3791 lxc_container_put(c2
);
3797 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3798 const char *lxcpath
, int flags
,
3799 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3802 struct lxc_container
* ret
;
3803 current_config
= c
? c
->lxc_conf
: NULL
;
3804 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3805 current_config
= NULL
;
3809 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3811 struct lxc_storage
*bdev
;
3812 struct lxc_container
*newc
;
3814 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3817 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3818 ERROR("Renaming a container with snapshots is not supported");
3821 bdev
= storage_init(c
->lxc_conf
);
3823 ERROR("Failed to find original backing store type");
3827 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
3830 lxc_container_put(newc
);
3834 if (newc
&& lxcapi_is_defined(newc
))
3835 lxc_container_put(newc
);
3837 if (!container_destroy(c
, NULL
)) {
3838 ERROR("Could not destroy existing container %s", c
->name
);
3844 WRAP_API_1(bool, lxcapi_rename
, const char *)
3846 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
)
3853 current_config
= c
->lxc_conf
;
3855 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
3856 current_config
= NULL
;
3860 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3862 lxc_attach_command_t command
;
3869 command
.program
= (char*)program
;
3870 command
.argv
= (char**)argv
;
3871 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
3876 return lxc_wait_for_pid_status(pid
);
3879 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
3882 current_config
= c
? c
->lxc_conf
: NULL
;
3883 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
3884 current_config
= NULL
;
3888 static int get_next_index(const char *lxcpath
, char *cname
)
3894 fname
= alloca(strlen(lxcpath
) + 20);
3896 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
3897 ret
= stat(fname
, &sb
);
3904 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
3908 * If the old style snapshot path exists, use it
3909 * /var/lib/lxc -> /var/lib/lxcsnaps
3911 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
3912 if (ret
< 0 || ret
>= MAXPATHLEN
)
3914 if (dir_exists(snappath
)) {
3915 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
3916 if (ret
< 0 || ret
>= MAXPATHLEN
)
3922 * Use the new style path
3923 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
3925 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
3926 if (ret
< 0 || ret
>= MAXPATHLEN
)
3931 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
3934 struct lxc_container
*c2
;
3935 char snappath
[MAXPATHLEN
], newname
[20];
3937 if (!c
|| !lxcapi_is_defined(c
))
3940 if (!storage_can_backup(c
->lxc_conf
)) {
3941 ERROR("%s's backing store cannot be backed up.", c
->name
);
3942 ERROR("Your container must use another backing store type.");
3946 if (!get_snappath_dir(c
, snappath
))
3949 i
= get_next_index(snappath
, c
->name
);
3951 if (mkdir_p(snappath
, 0755) < 0) {
3952 ERROR("Failed to create snapshot directory %s", snappath
);
3956 ret
= snprintf(newname
, 20, "snap%d", i
);
3957 if (ret
< 0 || ret
>= 20)
3961 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
3962 * created in the original container
3964 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
3965 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
3966 if (storage_is_dir(c
->lxc_conf
)) {
3967 ERROR("Snapshot of directory-backed container requested.");
3968 ERROR("Making a copy-clone. If you do want snapshots, then");
3969 ERROR("please create overlay clone first, snapshot that");
3970 ERROR("and keep the original container pristine.");
3971 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
3973 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
3975 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
3979 lxc_container_put(c2
);
3981 /* Now write down the creation time. */
3988 tm_info
= localtime(&timer
);
3990 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
3992 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
3993 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
3994 f
= fopen(dfnam
, "w");
3996 ERROR("Failed to open %s", dfnam
);
3999 if (fprintf(f
, "%s", buffer
) < 0) {
4000 SYSERROR("Writing timestamp");
4006 SYSERROR("Writing timestamp");
4011 /* $p / $name / comment \0 */
4012 int len
= strlen(snappath
) + strlen(newname
) + 10;
4013 char *path
= alloca(len
);
4014 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4015 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4021 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4023 static void lxcsnap_free(struct lxc_snapshot
*s
)
4026 free(s
->comment_pathname
);
4031 static char *get_snapcomment_path(char* snappath
, char *name
)
4033 /* $snappath/$name/comment */
4034 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4035 char *s
= malloc(len
);
4038 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4039 if (ret
< 0 || ret
>= len
) {
4047 static char *get_timestamp(char* snappath
, char *name
)
4049 char path
[MAXPATHLEN
], *s
= NULL
;
4053 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4054 if (ret
< 0 || ret
>= MAXPATHLEN
)
4056 fin
= fopen(path
, "r");
4059 (void) fseek(fin
, 0, SEEK_END
);
4061 (void) fseek(fin
, 0, SEEK_SET
);
4066 if (fread(s
, 1, len
, fin
) != len
) {
4067 SYSERROR("reading timestamp");
4077 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4079 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4081 struct dirent
*direntp
;
4082 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4085 if (!c
|| !lxcapi_is_defined(c
))
4088 if (!get_snappath_dir(c
, snappath
)) {
4089 ERROR("path name too long");
4092 dir
= opendir(snappath
);
4094 INFO("failed to open %s - assuming no snapshots", snappath
);
4098 while ((direntp
= readdir(dir
))) {
4102 if (!strcmp(direntp
->d_name
, "."))
4105 if (!strcmp(direntp
->d_name
, ".."))
4108 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4109 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4110 ERROR("pathname too long");
4113 if (!file_exists(path2
))
4115 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4117 SYSERROR("Out of memory");
4121 snaps
[count
].free
= lxcsnap_free
;
4122 snaps
[count
].name
= strdup(direntp
->d_name
);
4123 if (!snaps
[count
].name
)
4125 snaps
[count
].lxcpath
= strdup(snappath
);
4126 if (!snaps
[count
].lxcpath
) {
4127 free(snaps
[count
].name
);
4130 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4131 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4136 WARN("failed to close directory");
4144 for (i
=0; i
<count
; i
++)
4145 lxcsnap_free(&snaps
[i
]);
4149 WARN("failed to close directory");
4153 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4155 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4157 char clonelxcpath
[MAXPATHLEN
];
4159 struct lxc_container
*snap
, *rest
;
4160 struct lxc_storage
*bdev
;
4163 if (!c
|| !c
->name
|| !c
->config_path
)
4166 if (has_fs_snapshots(c
)) {
4167 ERROR("container rootfs has dependent snapshots");
4171 bdev
= storage_init(c
->lxc_conf
);
4173 ERROR("Failed to find original backing store type");
4177 /* For an overlay container the rootfs is considered immutable
4178 * and cannot be removed when restoring from a snapshot. We pass this
4179 * internal flag along to communicate this to various parts of the
4182 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4183 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4188 if (!get_snappath_dir(c
, clonelxcpath
)) {
4192 /* how should we lock this? */
4194 snap
= lxc_container_new(snapname
, clonelxcpath
);
4195 if (!snap
|| !lxcapi_is_defined(snap
)) {
4196 ERROR("Could not open snapshot %s", snapname
);
4198 lxc_container_put(snap
);
4203 if (!strcmp(c
->name
, newname
)) {
4204 if (!container_destroy(c
, bdev
)) {
4205 ERROR("Could not destroy existing container %s", newname
);
4206 lxc_container_put(snap
);
4212 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4213 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4215 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4216 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4217 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4220 if (rest
&& lxcapi_is_defined(rest
))
4223 lxc_container_put(rest
);
4225 lxc_container_put(snap
);
4229 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4231 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4233 struct lxc_container
*snap
= NULL
;
4236 snap
= lxc_container_new(snapname
, clonelxcpath
);
4238 ERROR("Could not find snapshot %s", snapname
);
4242 if (!do_lxcapi_destroy(snap
)) {
4243 ERROR("Could not destroy snapshot %s", snapname
);
4250 lxc_container_put(snap
);
4254 static bool remove_all_snapshots(const char *path
)
4257 struct dirent
*direntp
;
4260 dir
= opendir(path
);
4262 SYSERROR("opendir on snapshot path %s", path
);
4265 while ((direntp
= readdir(dir
))) {
4266 if (!strcmp(direntp
->d_name
, "."))
4268 if (!strcmp(direntp
->d_name
, ".."))
4270 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4279 SYSERROR("Error removing directory %s", path
);
4284 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4286 char clonelxcpath
[MAXPATHLEN
];
4288 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4291 if (!get_snappath_dir(c
, clonelxcpath
))
4294 return do_snapshot_destroy(snapname
, clonelxcpath
);
4297 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4299 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4301 char clonelxcpath
[MAXPATHLEN
];
4303 if (!c
|| !c
->name
|| !c
->config_path
)
4306 if (!get_snappath_dir(c
, clonelxcpath
))
4309 return remove_all_snapshots(clonelxcpath
);
4312 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4314 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4316 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4319 WRAP_API(bool, lxcapi_may_control
)
4321 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4327 char chrootpath
[MAXPATHLEN
];
4328 char *directory_path
= NULL
;
4332 SYSERROR("Failed to fork()");
4337 ret
= wait_for_pid(pid
);
4339 ERROR("Failed to create device node");
4346 /* prepare the path */
4347 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4348 if (ret
< 0 || ret
>= MAXPATHLEN
)
4351 ret
= chroot(chrootpath
);
4353 _exit(EXIT_FAILURE
);
4357 _exit(EXIT_FAILURE
);
4359 /* remove path if it exists */
4360 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4364 ERROR("%s - Failed to remove \"%s\"", strerror(errno
), path
);
4365 _exit(EXIT_FAILURE
);
4370 _exit(EXIT_SUCCESS
);
4372 /* create any missing directories */
4375 _exit(EXIT_FAILURE
);
4377 directory_path
= dirname(tmp
);
4378 ret
= mkdir_p(directory_path
, 0755);
4379 if (ret
< 0 && errno
!= EEXIST
) {
4380 ERROR("%s - Failed to create path \"%s\"", strerror(errno
), directory_path
);
4382 _exit(EXIT_FAILURE
);
4385 /* create the device node */
4386 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4389 ERROR("%s - Failed to create device node at \"%s\"", strerror(errno
), path
);
4390 _exit(EXIT_FAILURE
);
4393 _exit(EXIT_SUCCESS
);
4396 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4400 char value
[LXC_MAX_BUFFER
];
4403 /* make sure container is running */
4404 if (!do_lxcapi_is_running(c
)) {
4405 ERROR("container is not running");
4409 /* use src_path if dest_path is NULL otherwise use dest_path */
4410 p
= dest_path
? dest_path
: src_path
;
4412 /* make sure we can access p */
4413 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4416 /* continue if path is character device or block device */
4417 if (S_ISCHR(st
.st_mode
))
4418 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4419 else if (S_ISBLK(st
.st_mode
))
4420 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4424 /* check snprintf return code */
4425 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4428 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4431 /* add or remove device to/from cgroup access list */
4433 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4434 ERROR("set_cgroup_item failed while adding the device node");
4438 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4439 ERROR("set_cgroup_item failed while removing the device node");
4447 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4449 // cannot mknod if we're not privileged wrt init_user_ns
4450 if (am_host_unpriv()) {
4451 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4454 return add_remove_device_node(c
, src_path
, dest_path
, true);
4457 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4459 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4461 if (am_guest_unpriv()) {
4462 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4465 return add_remove_device_node(c
, src_path
, dest_path
, false);
4468 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4470 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4472 const char *dst_ifname
)
4477 if (am_guest_unpriv()) {
4478 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4483 ERROR("No source interface name given");
4487 ret
= lxc_netdev_isup(ifname
);
4489 /* netdev of ifname is up. */
4490 ret
= lxc_netdev_down(ifname
);
4495 init_pid
= do_lxcapi_init_pid(c
);
4496 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4500 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4507 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4509 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4511 const char *dst_ifname
)
4514 pid_t pid
, pid_outside
;
4517 * TODO - if this is a physical device, then we need am_host_unpriv.
4518 * But for other types guest privilege suffices.
4520 if (am_guest_unpriv()) {
4521 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4526 ERROR("No source interface name given");
4530 pid_outside
= lxc_raw_getpid();
4533 ERROR("Failed to fork");
4537 if (pid
== 0) { /* child */
4540 init_pid
= do_lxcapi_init_pid(c
);
4541 if (!switch_to_ns(init_pid
, "net")) {
4542 ERROR("Failed to enter network namespace");
4543 _exit(EXIT_FAILURE
);
4546 ret
= lxc_netdev_isup(ifname
);
4548 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4549 _exit(EXIT_FAILURE
);
4552 /* netdev of ifname is up. */
4554 ret
= lxc_netdev_down(ifname
);
4556 ERROR("Failed to set network device \"%s\" down", ifname
);
4557 _exit(EXIT_FAILURE
);
4561 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4562 /* -EINVAL means there is no netdev named as ifname. */
4565 ERROR("Network device \"%s\" not found", ifname
);
4567 ERROR("Failed to remove network device \"%s\"", ifname
);
4568 _exit(EXIT_FAILURE
);
4571 _exit(EXIT_SUCCESS
);
4574 ret
= wait_for_pid(pid
);
4578 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4582 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4584 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4585 struct migrate_opts
*opts
, unsigned int size
)
4588 struct migrate_opts
*valid_opts
= opts
;
4589 uint64_t features_to_check
= 0;
4591 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4592 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4593 * to do anything special.
4595 if (size
> sizeof(*opts
)) {
4596 unsigned char *addr
;
4599 addr
= (void *)opts
+ sizeof(*opts
);
4600 end
= (void *)opts
+ size
;
4601 for (; addr
< end
; addr
++) {
4608 /* If the caller has a smaller struct, let's zero out the end for them
4609 * so we don't accidentally use bits of it that they didn't know about
4612 if (size
< sizeof(*opts
)) {
4613 valid_opts
= malloc(sizeof(*opts
));
4617 memset(valid_opts
, 0, sizeof(*opts
));
4618 memcpy(valid_opts
, opts
, size
);
4622 case MIGRATE_PRE_DUMP
:
4623 if (!do_lxcapi_is_running(c
)) {
4624 ERROR("container is not running");
4627 ret
= !__criu_pre_dump(c
, valid_opts
);
4630 if (!do_lxcapi_is_running(c
)) {
4631 ERROR("container is not running");
4634 ret
= !__criu_dump(c
, valid_opts
);
4636 case MIGRATE_RESTORE
:
4637 if (do_lxcapi_is_running(c
)) {
4638 ERROR("container is already running");
4641 ret
= !__criu_restore(c
, valid_opts
);
4643 case MIGRATE_FEATURE_CHECK
:
4644 features_to_check
= valid_opts
->features_to_check
;
4645 ret
= !__criu_check_feature(&features_to_check
);
4647 /* Something went wrong. Let's let the caller
4648 * know which feature checks failed. */
4649 valid_opts
->features_to_check
= features_to_check
;
4653 ERROR("invalid migrate command %u", cmd
);
4658 if (size
< sizeof(*opts
))
4664 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4666 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4668 struct migrate_opts opts
;
4670 memset(&opts
, 0, sizeof(opts
));
4672 opts
.directory
= directory
;
4674 opts
.verbose
= verbose
;
4676 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4679 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4681 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4683 struct migrate_opts opts
;
4685 memset(&opts
, 0, sizeof(opts
));
4687 opts
.directory
= directory
;
4688 opts
.verbose
= verbose
;
4690 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4693 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4695 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
4704 current_config
= c
->lxc_conf
;
4707 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
4711 ERROR("Memory allocation error.");
4717 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
4720 current_config
= NULL
;
4724 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
4726 struct lxc_container
*c
;
4731 c
= malloc(sizeof(*c
));
4733 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4736 memset(c
, 0, sizeof(*c
));
4739 c
->config_path
= strdup(configpath
);
4741 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
4743 if (!c
->config_path
) {
4744 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4748 remove_trailing_slashes(c
->config_path
);
4749 c
->name
= malloc(strlen(name
)+1);
4751 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
4754 strcpy(c
->name
, name
);
4757 c
->slock
= lxc_newlock(c
->config_path
, name
);
4759 fprintf(stderr
, "Failed to create lock for %s\n", name
);
4763 c
->privlock
= lxc_newlock(NULL
, NULL
);
4765 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
4769 if (!set_config_filename(c
)) {
4770 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
4774 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
4775 fprintf(stderr
, "Failed to load config for %s\n", name
);
4779 if (ongoing_create(c
) == 2) {
4780 ERROR("Failed to complete container creation for %s", c
->name
);
4781 container_destroy(c
, NULL
);
4782 lxcapi_clear_config(c
);
4784 c
->daemonize
= true;
4787 /* Assign the member functions. */
4788 c
->is_defined
= lxcapi_is_defined
;
4789 c
->state
= lxcapi_state
;
4790 c
->is_running
= lxcapi_is_running
;
4791 c
->freeze
= lxcapi_freeze
;
4792 c
->unfreeze
= lxcapi_unfreeze
;
4793 c
->console
= lxcapi_console
;
4794 c
->console_getfd
= lxcapi_console_getfd
;
4795 c
->init_pid
= lxcapi_init_pid
;
4796 c
->load_config
= lxcapi_load_config
;
4797 c
->want_daemonize
= lxcapi_want_daemonize
;
4798 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
4799 c
->start
= lxcapi_start
;
4800 c
->startl
= lxcapi_startl
;
4801 c
->stop
= lxcapi_stop
;
4802 c
->config_file_name
= lxcapi_config_file_name
;
4803 c
->wait
= lxcapi_wait
;
4804 c
->set_config_item
= lxcapi_set_config_item
;
4805 c
->destroy
= lxcapi_destroy
;
4806 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
4807 c
->rename
= lxcapi_rename
;
4808 c
->save_config
= lxcapi_save_config
;
4809 c
->get_keys
= lxcapi_get_keys
;
4810 c
->create
= lxcapi_create
;
4811 c
->createl
= lxcapi_createl
;
4812 c
->shutdown
= lxcapi_shutdown
;
4813 c
->reboot
= lxcapi_reboot
;
4814 c
->reboot2
= lxcapi_reboot2
;
4815 c
->clear_config
= lxcapi_clear_config
;
4816 c
->clear_config_item
= lxcapi_clear_config_item
;
4817 c
->get_config_item
= lxcapi_get_config_item
;
4818 c
->get_running_config_item
= lxcapi_get_running_config_item
;
4819 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
4820 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
4821 c
->get_config_path
= lxcapi_get_config_path
;
4822 c
->set_config_path
= lxcapi_set_config_path
;
4823 c
->clone
= lxcapi_clone
;
4824 c
->get_interfaces
= lxcapi_get_interfaces
;
4825 c
->get_ips
= lxcapi_get_ips
;
4826 c
->attach
= lxcapi_attach
;
4827 c
->attach_run_wait
= lxcapi_attach_run_wait
;
4828 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
4829 c
->snapshot
= lxcapi_snapshot
;
4830 c
->snapshot_list
= lxcapi_snapshot_list
;
4831 c
->snapshot_restore
= lxcapi_snapshot_restore
;
4832 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
4833 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
4834 c
->may_control
= lxcapi_may_control
;
4835 c
->add_device_node
= lxcapi_add_device_node
;
4836 c
->remove_device_node
= lxcapi_remove_device_node
;
4837 c
->attach_interface
= lxcapi_attach_interface
;
4838 c
->detach_interface
= lxcapi_detach_interface
;
4839 c
->checkpoint
= lxcapi_checkpoint
;
4840 c
->restore
= lxcapi_restore
;
4841 c
->migrate
= lxcapi_migrate
;
4842 c
->console_log
= lxcapi_console_log
;
4847 lxc_container_free(c
);
4851 int lxc_get_wait_states(const char **states
)
4856 for (i
=0; i
<MAX_STATE
; i
++)
4857 states
[i
] = lxc_state2str(i
);
4862 * These next two could probably be done smarter with reusing a common function
4863 * with different iterators and tests...
4865 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
4868 int i
, cfound
= 0, nfound
= 0;
4869 struct dirent
*direntp
;
4870 struct lxc_container
*c
;
4873 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4875 dir
= opendir(lxcpath
);
4877 SYSERROR("opendir on lxcpath");
4886 while ((direntp
= readdir(dir
))) {
4890 /* Ignore '.', '..' and any hidden directory. */
4891 if (!strncmp(direntp
->d_name
, ".", 1))
4894 if (!config_file_exists(lxcpath
, direntp
->d_name
))
4898 if (!add_to_array(names
, direntp
->d_name
, cfound
))
4908 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
4910 INFO("Container %s:%s has a config but could not be loaded",
4911 lxcpath
, direntp
->d_name
);
4913 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4917 if (!do_lxcapi_is_defined(c
)) {
4918 INFO("Container %s:%s has a config but is not defined",
4919 lxcpath
, direntp
->d_name
);
4921 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
4923 lxc_container_put(c
);
4927 if (!add_to_clist(cret
, c
, nfound
, true)) {
4928 lxc_container_put(c
);
4938 if (names
&& *names
) {
4939 for (i
=0; i
<cfound
; i
++)
4943 if (cret
&& *cret
) {
4944 for (i
=0; i
<nfound
; i
++)
4945 lxc_container_put((*cret
)[i
]);
4952 int list_active_containers(const char *lxcpath
, char ***nret
,
4953 struct lxc_container
***cret
)
4955 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
4958 char **ct_name
= NULL
;
4960 struct lxc_container
*c
= NULL
;
4964 lxcpath
= lxc_global_config_value("lxc.lxcpath");
4965 lxcpath_len
= strlen(lxcpath
);
4972 FILE *f
= fopen("/proc/net/unix", "r");
4976 while (getline(&line
, &len
, f
) != -1) {
4978 char *p
= strrchr(line
, ' '), *p2
;
4987 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
4989 } else if (strncmp(p
, "lxc/", 4) == 0) {
4999 /* Now p is the start of lxc_name. */
5000 p2
= strchr(p
, '/');
5001 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5006 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5009 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5014 p
= lxc_cmd_get_name(p
);
5019 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5025 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5028 goto free_cret_list
;
5039 c
= lxc_container_new(p
, lxcpath
);
5041 INFO("Container %s:%s is running but could not be loaded",
5043 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5053 * If this is an anonymous container, then is_defined *can*
5054 * return false. So we don't do that check. Count on the
5055 * fact that the command socket exists.
5058 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5059 lxc_container_put(c
);
5060 goto free_cret_list
;
5065 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5067 lxc_container_put(c
);
5068 goto free_cret_list
;
5079 if (cret
&& *cret
) {
5080 for (i
= 0; i
< cret_cnt
; i
++)
5081 lxc_container_put((*cret
)[i
]);
5087 for (i
= 0; i
< ct_name_cnt
; i
++)
5099 int list_all_containers(const char *lxcpath
, char ***nret
,
5100 struct lxc_container
***cret
)
5102 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5105 struct lxc_container
**ct_list
= NULL
;
5107 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5111 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5112 if (active_cnt
< 0) {
5117 for (i
= 0; i
< active_cnt
; i
++) {
5118 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5119 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5121 goto free_active_name
;
5125 free(active_name
[i
]);
5126 active_name
[i
] = NULL
;
5132 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5133 struct lxc_container
*c
;
5135 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5137 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5138 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5142 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5143 lxc_container_put(c
);
5162 for (i
= 0; i
< ct_list_cnt
; i
++) {
5163 lxc_container_put(ct_list
[i
]);
5168 for (i
= 0; i
< active_cnt
; i
++) {
5169 free(active_name
[i
]);
5174 for (i
= 0; i
< ct_cnt
; i
++) {
5181 bool lxc_config_item_is_supported(const char *key
)
5183 return !!lxc_get_config(key
);