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>
36 #include <sys/mount.h>
38 #include <sys/syscall.h>
39 #include <sys/sysmacros.h>
40 #include <sys/types.h>
48 #include "commands_utils.h"
52 #include "confile_utils.h"
55 #include "initutils.h"
58 #include "lxccontainer.h"
61 #include "namespace.h"
67 #include "storage/btrfs.h"
68 #include "storage/overlay.h"
69 #include "storage_utils.h"
77 #include <sys/mkdev.h>
83 #include <../include/ifaddrs.h>
87 #include <../include/lxcmntent.h>
93 #include "include/strlcpy.h"
96 /* Define faccessat() if missing from the C library */
97 #ifndef HAVE_FACCESSAT
98 static int faccessat(int __fd
, const char *__file
, int __type
, int __flag
)
100 #ifdef __NR_faccessat
101 return syscall(__NR_faccessat
, __fd
, __file
, __type
, __flag
);
109 lxc_log_define(lxccontainer
, lxc
);
111 static bool do_lxcapi_destroy(struct lxc_container
*c
);
112 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
113 #define do_lxcapi_get_config_path(c) lxcapi_get_config_path(c)
114 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
115 static bool container_destroy(struct lxc_container
*c
,
116 struct lxc_storage
*storage
);
117 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
);
118 static bool lxcapi_snapshot_destroy_all(struct lxc_container
*c
);
119 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
);
121 static bool config_file_exists(const char *lxcpath
, const char *cname
)
127 /* $lxcpath + '/' + $cname + '/config' + \0 */
128 len
= strlen(lxcpath
) + strlen(cname
) + 9;
130 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
131 if (ret
< 0 || (size_t)ret
>= len
)
134 return file_exists(fname
);
137 /* A few functions to help detect when a container creation failed. If a
138 * container creation was killed partway through, then trying to actually start
139 * that container could harm the host. We detect this by creating a 'partial'
140 * file under the container directory, and keeping an advisory lock. When
141 * container creation completes, we remove that file. When we load or try to
142 * start a container, if we find that file, without a flock, we remove the
145 static int ongoing_create(struct lxc_container
*c
)
150 struct flock lk
= {0};
152 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
154 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
155 if (ret
< 0 || (size_t)ret
>= len
)
158 if (!file_exists(path
))
161 fd
= open(path
, O_RDWR
);
166 lk
.l_whence
= SEEK_SET
;
169 ret
= fcntl(fd
, F_OFD_GETLK
, &lk
);
170 if (ret
< 0 && errno
== EINVAL
)
171 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
175 if (ret
== 0 && lk
.l_pid
!= -1)
176 /* create is still ongoing */
179 /* Create completed but partial is still there. */
183 static int create_partial(struct lxc_container
*c
)
188 struct flock lk
= {0};
190 /* $lxcpath + '/' + $name + '/partial' + \0 */
191 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
193 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
194 if (ret
< 0 || (size_t)ret
>= len
)
197 fd
= open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755);
202 lk
.l_whence
= SEEK_SET
;
204 ret
= fcntl(fd
, F_OFD_SETLKW
, &lk
);
206 if (errno
== EINVAL
) {
207 ret
= flock(fd
, LOCK_EX
);
212 SYSERROR("Failed to lock partial file %s", path
);
220 static void remove_partial(struct lxc_container
*c
, int fd
)
228 /* $lxcpath + '/' + $name + '/partial' + \0 */
229 len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
231 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
232 if (ret
< 0 || (size_t)ret
>= len
)
237 SYSERROR("Failed to remove partial file %s", path
);
241 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
242 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
243 * container configuration file.
244 * The container_disk_lock also takes the container_mem_lock.
245 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
246 * NOTHING mutexes two independent programs with their own struct
247 * lxc_container for the same c->name, between API calls. For instance,
248 * c->config_read(); c->start(); Between those calls, data on disk
249 * could change (which shouldn't bother the caller unless for instance
250 * the rootfs get moved). c->config_read(); update; c->config_write();
251 * Two such updaters could race. The callers should therefore check their
252 * results. Trying to prevent that would necessarily expose us to deadlocks
253 * due to hung callers. So I prefer to keep the locks only within our own
254 * functions, not across functions.
256 * If you're going to clone while holding a lxccontainer, increment
257 * c->numthreads (under privlock) before forking. When deleting,
258 * decrement numthreads under privlock, then if it hits 0 you can delete.
259 * Do not ever use a lxccontainer whose numthreads you did not bump.
261 static void lxc_container_free(struct lxc_container
*c
)
267 c
->configfile
= NULL
;
269 free(c
->error_string
);
270 c
->error_string
= NULL
;
273 lxc_putlock(c
->slock
);
278 lxc_putlock(c
->privlock
);
286 lxc_conf_free(c
->lxc_conf
);
290 free(c
->config_path
);
291 c
->config_path
= NULL
;
296 /* Consider the following case:
298 * |====================================================================|
299 * | freer | racing get()er |
300 * |====================================================================|
301 * | lxc_container_put() | lxc_container_get() |
302 * | \ lxclock(c->privlock) | c->numthreads < 1? (no) |
303 * | \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits |
304 * | \ lxcunlock() | \ |
305 * | \ lxc_container_free() | \ lxclock() returns |
306 * | | \ c->numthreads < 1 -> return 0 |
307 * | \ \ (free stuff) | |
308 * | \ \ sem_destroy(privlock) | |
309 * |_______________________________|____________________________________|
311 * When the get()er checks numthreads the first time, one of the following
313 * 1. freer has set numthreads = 0. get() returns 0
314 * 2. freer is between lxclock and setting numthreads to 0. get()er will
315 * sem_wait on privlock, get lxclock after freer() drops it, then see
316 * numthreads is 0 and exit without touching lxclock again..
317 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
318 * will see --numthreads = 1 and not call lxc_container_free().
321 int lxc_container_get(struct lxc_container
*c
)
326 /* If someone else has already started freeing the container, don't try
327 * to take the lock, which may be invalid.
329 if (c
->numthreads
< 1)
332 if (container_mem_lock(c
))
335 /* Bail without trying to unlock, bc the privlock is now probably in
338 if (c
->numthreads
< 1)
342 container_mem_unlock(c
);
347 int lxc_container_put(struct lxc_container
*c
)
352 if (container_mem_lock(c
))
357 if (c
->numthreads
< 1) {
358 container_mem_unlock(c
);
359 lxc_container_free(c
);
363 container_mem_unlock(c
);
367 static bool do_lxcapi_is_defined(struct lxc_container
*c
)
376 if (container_mem_lock(c
))
382 statret
= stat(c
->configfile
, &statbuf
);
389 container_mem_unlock(c
);
393 #define WRAP_API(rettype, fnname) \
394 static rettype fnname(struct lxc_container *c) \
397 bool reset_config = false; \
399 if (!current_config && c && c->lxc_conf) { \
400 current_config = c->lxc_conf; \
401 reset_config = true; \
404 ret = do_##fnname(c); \
406 current_config = NULL; \
411 #define WRAP_API_1(rettype, fnname, t1) \
412 static rettype fnname(struct lxc_container *c, t1 a1) \
415 bool reset_config = false; \
417 if (!current_config && c && c->lxc_conf) { \
418 current_config = c->lxc_conf; \
419 reset_config = true; \
422 ret = do_##fnname(c, a1); \
424 current_config = NULL; \
429 #define WRAP_API_2(rettype, fnname, t1, t2) \
430 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2) \
433 bool reset_config = false; \
435 if (!current_config && c && c->lxc_conf) { \
436 current_config = c->lxc_conf; \
437 reset_config = true; \
440 ret = do_##fnname(c, a1, a2); \
442 current_config = NULL; \
447 #define WRAP_API_3(rettype, fnname, t1, t2, t3) \
448 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3) \
451 bool reset_config = false; \
453 if (!current_config && c && c->lxc_conf) { \
454 current_config = c->lxc_conf; \
455 reset_config = true; \
458 ret = do_##fnname(c, a1, a2, a3); \
460 current_config = NULL; \
465 #define WRAP_API_6(rettype, fnname, t1, t2, t3, t4, t5, t6) \
466 static rettype fnname(struct lxc_container *c, t1 a1, t2 a2, t3 a3, \
467 t4 a4, t5 a5, t6 a6) \
470 bool reset_config = false; \
472 if (!current_config && c && c->lxc_conf) { \
473 current_config = c->lxc_conf; \
474 reset_config = true; \
477 ret = do_##fnname(c, a1, a2, a3, a4, a5, a6); \
479 current_config = NULL; \
484 WRAP_API(bool, lxcapi_is_defined
)
486 static const char *do_lxcapi_state(struct lxc_container
*c
)
493 s
= lxc_getstate(c
->name
, c
->config_path
);
494 return lxc_state2str(s
);
497 WRAP_API(const char *, lxcapi_state
)
499 static bool is_stopped(struct lxc_container
*c
)
503 s
= lxc_getstate(c
->name
, c
->config_path
);
504 return (s
== STOPPED
);
507 static bool do_lxcapi_is_running(struct lxc_container
*c
)
512 return !is_stopped(c
);
515 WRAP_API(bool, lxcapi_is_running
)
517 static bool do_lxcapi_freeze(struct lxc_container
*c
)
524 ret
= lxc_freeze(c
->name
, c
->config_path
);
531 WRAP_API(bool, lxcapi_freeze
)
533 static bool do_lxcapi_unfreeze(struct lxc_container
*c
)
540 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
547 WRAP_API(bool, lxcapi_unfreeze
)
549 static int do_lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
554 return lxc_terminal_getfd(c
, ttynum
, masterfd
);
557 WRAP_API_2(int, lxcapi_console_getfd
, int *, int *)
559 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
560 int stdoutfd
, int stderrfd
, int escape
)
567 current_config
= c
->lxc_conf
;
568 ret
= lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
569 current_config
= NULL
;
574 static int do_lxcapi_console_log(struct lxc_container
*c
, struct lxc_console_log
*log
)
578 ret
= lxc_cmd_console_log(c
->name
, do_lxcapi_get_config_path(c
), log
);
581 NOTICE("The console log is empty");
582 else if (ret
== -EFAULT
)
583 NOTICE("The container does not keep a console log");
584 else if (ret
== -ENOENT
)
585 NOTICE("The container does not keep a console log file");
586 else if (ret
== -EIO
)
587 NOTICE("Failed to write console log to log file");
589 ERROR("Failed to retrieve console log");
595 WRAP_API_1(int, lxcapi_console_log
, struct lxc_console_log
*)
597 static pid_t
do_lxcapi_init_pid(struct lxc_container
*c
)
602 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
605 WRAP_API(pid_t
, lxcapi_init_pid
)
607 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
610 c
->lxc_conf
= lxc_conf_init();
615 if (lxc_config_read(fname
, c
->lxc_conf
, false) != 0)
618 c
->lxc_conf
->name
= c
->name
;
622 static bool do_lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
626 bool need_disklock
= false, ret
= false;
631 fname
= c
->configfile
;
639 /* If we're reading something other than the container's config, we only
640 * need to lock the in-memory container. If loading the container's
641 * config file, take the disk lock.
643 if (strcmp(fname
, c
->configfile
) == 0)
644 need_disklock
= true;
647 lret
= container_disk_lock(c
);
649 lret
= container_mem_lock(c
);
653 ret
= load_config_locked(c
, fname
);
656 container_disk_unlock(c
);
658 container_mem_unlock(c
);
663 WRAP_API_1(bool, lxcapi_load_config
, const char *)
665 static bool do_lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
667 if (!c
|| !c
->lxc_conf
)
670 if (container_mem_lock(c
))
673 c
->daemonize
= state
;
675 container_mem_unlock(c
);
680 WRAP_API_1(bool, lxcapi_want_daemonize
, bool)
682 static bool do_lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
684 if (!c
|| !c
->lxc_conf
)
687 if (container_mem_lock(c
))
690 c
->lxc_conf
->close_all_fds
= state
;
692 container_mem_unlock(c
);
697 WRAP_API_1(bool, lxcapi_want_close_all_fds
, bool)
699 static bool do_lxcapi_wait(struct lxc_container
*c
, const char *state
,
707 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
711 WRAP_API_2(bool, lxcapi_wait
, const char *, int)
713 static bool am_single_threaded(void)
716 struct dirent
*direntp
;
719 dir
= opendir("/proc/self/task");
723 while ((direntp
= readdir(dir
))) {
724 if (strcmp(direntp
->d_name
, ".") == 0)
727 if (strcmp(direntp
->d_name
, "..") == 0)
739 static void push_arg(char ***argp
, char *arg
, int *nargs
)
744 copy
= must_copy_string(arg
);
747 argv
= realloc(*argp
, (*nargs
+ 2) * sizeof(char *));
756 static char **split_init_cmd(const char *incmd
)
766 len
= strlen(incmd
) + 1;
768 retlen
= strlcpy(copy
, incmd
, len
);
773 argv
= malloc(sizeof(char *));
777 lxc_iterate_parts(p
, copy
, " ")
778 push_arg(&argv
, p
, &nargs
);
788 static void free_init_cmd(char **argv
)
801 static int lxc_rcv_status(int state_socket
)
807 /* Receive container state. */
808 ret
= lxc_abstract_unix_rcv_credential(state_socket
, &state
, sizeof(int));
813 TRACE("Caught EINTR; retrying");
820 static bool wait_on_daemonized_start(struct lxc_handler
*handler
, int pid
)
824 /* Close write end of the socket pair. */
825 close(handler
->state_socket_pair
[1]);
826 handler
->state_socket_pair
[1] = -1;
828 state
= lxc_rcv_status(handler
->state_socket_pair
[0]);
830 /* Close read end of the socket pair. */
831 close(handler
->state_socket_pair
[0]);
832 handler
->state_socket_pair
[0] = -1;
834 /* The first child is going to fork() again and then exits. So we reap
835 * the first child here.
837 ret
= wait_for_pid(pid
);
839 DEBUG("Failed waiting on first child %d", pid
);
841 DEBUG("First child %d exited", pid
);
844 SYSERROR("Failed to receive the container state");
848 /* If we receive anything else then running we know that the container
851 if (state
!= RUNNING
) {
852 ERROR("Received container state \"%s\" instead of \"RUNNING\"",
853 lxc_state2str(state
));
857 TRACE("Container is in \"RUNNING\" state");
861 static bool do_lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
864 struct lxc_handler
*handler
;
865 struct lxc_conf
*conf
;
866 char *default_args
[] = {
870 char **init_cmd
= NULL
;
871 int keepfds
[3] = {-1, -1, -1};
873 /* container does exist */
877 /* If anything fails before we set error_num, we want an error in there.
881 /* Container has not been setup. */
885 ret
= ongoing_create(c
);
887 ERROR("Failed checking for incomplete container creation");
889 } else if (ret
== 1) {
890 ERROR("Ongoing container creation detected");
892 } else if (ret
== 2) {
893 ERROR("Failed to create container");
894 do_lxcapi_destroy(c
);
898 if (container_mem_lock(c
))
903 /* initialize handler */
904 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
906 container_mem_unlock(c
);
911 if (useinit
&& conf
->execute_cmd
)
912 argv
= init_cmd
= split_init_cmd(conf
->execute_cmd
);
914 argv
= init_cmd
= split_init_cmd(conf
->init_cmd
);
917 /* ... otherwise use default_args. */
920 ERROR("No valid init detected");
921 lxc_free_handler(handler
);
927 /* I'm not sure what locks we want here.Any? Is liblxc's locking enough
928 * here to protect the on disk container? We don't want to exclude
929 * things like lxc_info while the container is running.
938 free_init_cmd(init_cmd
);
939 lxc_free_handler(handler
);
945 /* Set to NULL because we don't want father unlink
946 * the PID file, child will do the free and unlink.
950 /* Wait for container to tell us whether it started
953 started
= wait_on_daemonized_start(handler
, pid
);
955 free_init_cmd(init_cmd
);
956 lxc_free_handler(handler
);
962 /* We don't really care if this doesn't print all the
963 * characters. All that it means is that the proctitle will be
964 * ugly. Similarly, we also don't care if setproctitle() fails.
966 (void)snprintf(title
, sizeof(title
), "[lxc monitor] %s %s", c
->config_path
, c
->name
);
967 INFO("Attempting to set proc title to %s", title
);
968 (void)setproctitle(title
);
970 /* We fork() a second time to be reparented to init. Like
971 * POSIX's daemon() function we change to "/" and redirect
972 * std{in,out,err} to /dev/null.
976 SYSERROR("Failed to fork first child process");
982 free_init_cmd(init_cmd
);
983 lxc_free_handler(handler
);
989 /* change to / directory */
992 SYSERROR("Failed to change to \"/\" directory");
996 keepfds
[0] = handler
->conf
->maincmd_fd
;
997 keepfds
[1] = handler
->state_socket_pair
[0];
998 keepfds
[2] = handler
->state_socket_pair
[1];
999 ret
= lxc_check_inherited(conf
, true, keepfds
,
1000 sizeof(keepfds
) / sizeof(keepfds
[0]));
1002 _exit(EXIT_FAILURE
);
1004 /* redirect std{in,out,err} to /dev/null */
1005 ret
= null_stdfds();
1007 ERROR("Failed to redirect std{in,out,err} to /dev/null");
1008 _exit(EXIT_FAILURE
);
1011 /* become session leader */
1014 TRACE("Process %d is already process group leader", lxc_raw_getpid());
1016 if (!am_single_threaded()) {
1017 ERROR("Cannot start non-daemonized container when threaded");
1018 free_init_cmd(init_cmd
);
1019 lxc_free_handler(handler
);
1024 /* We need to write PID file after daemonize, so we always
1025 * write the right PID.
1029 char pidstr
[LXC_NUMSTRLEN64
];
1031 w
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", (int)lxc_raw_getpid());
1032 if (w
< 0 || (size_t)w
>= LXC_NUMSTRLEN64
) {
1033 free_init_cmd(init_cmd
);
1034 lxc_free_handler(handler
);
1036 SYSERROR("Failed to write monitor pid to \"%s\"", c
->pidfile
);
1039 _exit(EXIT_FAILURE
);
1044 ret
= lxc_write_to_file(c
->pidfile
, pidstr
, w
, false, 0600);
1046 free_init_cmd(init_cmd
);
1047 lxc_free_handler(handler
);
1049 SYSERROR("Failed to write '%s'", c
->pidfile
);
1052 _exit(EXIT_FAILURE
);
1058 conf
->reboot
= REBOOT_NONE
;
1060 /* Unshare the mount namespace if requested */
1061 if (conf
->monitor_unshare
) {
1062 ret
= unshare(CLONE_NEWNS
);
1064 SYSERROR("failed to unshare mount namespace");
1065 lxc_free_handler(handler
);
1070 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
);
1072 SYSERROR("Failed to make / rslave at startup");
1073 lxc_free_handler(handler
);
1080 if (conf
->reboot
== REBOOT_INIT
) {
1081 /* initialize handler */
1082 handler
= lxc_init_handler(c
->name
, conf
, c
->config_path
, c
->daemonize
);
1089 keepfds
[0] = handler
->conf
->maincmd_fd
;
1090 keepfds
[1] = handler
->state_socket_pair
[0];
1091 keepfds
[2] = handler
->state_socket_pair
[1];
1092 ret
= lxc_check_inherited(conf
, c
->daemonize
, keepfds
,
1093 sizeof(keepfds
) / sizeof(keepfds
[0]));
1095 lxc_free_handler(handler
);
1101 ret
= lxc_execute(c
->name
, argv
, 1, handler
, c
->config_path
,
1102 c
->daemonize
, &c
->error_num
);
1104 ret
= lxc_start(c
->name
, argv
, handler
, c
->config_path
,
1105 c
->daemonize
, &c
->error_num
);
1107 if (conf
->reboot
== REBOOT_REQ
) {
1108 INFO("Container requested reboot");
1109 conf
->reboot
= REBOOT_INIT
;
1119 free_init_cmd(init_cmd
);
1121 if (c
->daemonize
&& ret
!= 0)
1122 _exit(EXIT_FAILURE
);
1123 else if (c
->daemonize
)
1124 _exit(EXIT_SUCCESS
);
1132 static bool lxcapi_start(struct lxc_container
*c
, int useinit
,
1137 current_config
= c
? c
->lxc_conf
: NULL
;
1138 ret
= do_lxcapi_start(c
, useinit
, argv
);
1139 current_config
= NULL
;
1144 /* Note, there MUST be an ending NULL. */
1145 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
1148 char **inargs
= NULL
;
1151 /* container exists */
1155 current_config
= c
->lxc_conf
;
1157 va_start(ap
, useinit
);
1158 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
1163 /* pass NULL if no arguments were supplied */
1164 bret
= do_lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
1170 for (arg
= inargs
; *arg
; arg
++)
1175 current_config
= NULL
;
1180 static bool do_lxcapi_stop(struct lxc_container
*c
)
1187 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
1192 WRAP_API(bool, lxcapi_stop
)
1194 static int do_create_container_dir(const char *path
, struct lxc_conf
*conf
)
1201 mode_t mask
= umask(0002);
1202 ret
= mkdir(path
, 0770);
1207 if (errno
!= EEXIST
)
1214 p
= alloca(len
+ 1);
1215 (void)strlcpy(p
, path
, len
+ 1);
1217 if (!lxc_list_empty(&conf
->id_map
)) {
1218 ret
= chown_mapped_root(p
, conf
);
1226 /* Create the standard expected container dir. */
1227 static bool create_container_dir(struct lxc_container
*c
)
1233 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
1238 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
1239 if (ret
< 0 || (size_t)ret
>= len
) {
1244 ret
= do_create_container_dir(s
, c
->lxc_conf
);
1250 /* do_storage_create: thin wrapper around storage_create(). Like
1251 * storage_create(), it returns a mounted bdev on success, NULL on error.
1253 static struct lxc_storage
*do_storage_create(struct lxc_container
*c
,
1255 struct bdev_specs
*specs
)
1260 struct lxc_storage
*bdev
;
1262 /* rootfs.path or lxcpath/lxcname/rootfs */
1263 if (c
->lxc_conf
->rootfs
.path
&&
1264 (access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0)) {
1265 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
1266 len
= strlen(rpath
) + 1;
1268 ret
= snprintf(dest
, len
, "%s", rpath
);
1270 const char *lxcpath
= do_lxcapi_get_config_path(c
);
1271 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
1273 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
1275 if (ret
< 0 || (size_t)ret
>= len
)
1278 bdev
= storage_create(dest
, type
, c
->name
, specs
);
1280 ERROR("Failed to create \"%s\" storage", type
);
1284 if (!c
->set_config_item(c
, "lxc.rootfs.path", bdev
->src
)) {
1285 ERROR("Failed to set \"lxc.rootfs.path = %s\"", bdev
->src
);
1289 /* If we are not root, chown the rootfs dir to root in the target user
1293 if (ret
!= 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) {
1294 ret
= chown_mapped_root(bdev
->dest
, c
->lxc_conf
);
1296 ERROR("Error chowning \"%s\" to container root", bdev
->dest
);
1297 suggest_default_idmap();
1306 static char *lxcbasename(char *path
)
1310 p
= path
+ strlen(path
) - 1;
1311 while (*p
!= '/' && p
> path
)
1317 static bool create_run_template(struct lxc_container
*c
, char *tpath
,
1318 bool need_null_stdfds
, char *const argv
[])
1328 SYSERROR("Failed to fork task for container creation template");
1332 if (pid
== 0) { /* child */
1334 char *namearg
, *patharg
, *rootfsarg
;
1337 struct lxc_storage
*bdev
= NULL
;
1338 struct lxc_conf
*conf
= c
->lxc_conf
;
1341 if (need_null_stdfds
) {
1342 ret
= null_stdfds();
1344 _exit(EXIT_FAILURE
);
1347 bdev
= storage_init(c
->lxc_conf
);
1349 ERROR("Failed to initialize storage");
1350 _exit(EXIT_FAILURE
);
1355 ret
= unshare(CLONE_NEWNS
);
1357 ERROR("Failed to unshare CLONE_NEWNS");
1358 _exit(EXIT_FAILURE
);
1361 ret
= detect_shared_rootfs();
1363 ret
= mount(NULL
, "/", NULL
, MS_SLAVE
| MS_REC
, NULL
);
1365 SYSERROR("Failed to make \"/\" rslave");
1366 ERROR("Continuing...");
1371 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "btrfs") != 0) {
1373 ERROR("Unprivileged users can only create "
1374 "btrfs and directory-backed containers");
1375 _exit(EXIT_FAILURE
);
1378 if (strcmp(bdev
->type
, "overlay") == 0 ||
1379 strcmp(bdev
->type
, "overlayfs") == 0) {
1380 /* If we create an overlay container we need to
1381 * rsync the contents into
1382 * <container-path>/<container-name>/rootfs.
1383 * However, the overlay mount function will
1385 * <container-path>/<container-name>/delta0
1387 * <container-path>/<container-name>/rootfs
1388 * which means we would rsync the rootfs into
1389 * the delta directory. That doesn't make sense
1390 * since the delta directory only exists to
1391 * record the differences to
1392 * <container-path>/<container-name>/rootfs. So
1393 * let's simply bind-mount here and then rsync
1395 * <container-path>/<container-name>/rootfs.
1399 src
= ovl_get_rootfs(bdev
->src
, &(size_t){0});
1401 ERROR("Failed to get rootfs");
1402 _exit(EXIT_FAILURE
);
1405 ret
= mount(src
, bdev
->dest
, "bind", MS_BIND
| MS_REC
, NULL
);
1407 ERROR("Failed to mount rootfs");
1408 _exit(EXIT_FAILURE
);
1411 ret
= bdev
->ops
->mount(bdev
);
1413 ERROR("Failed to mount rootfs");
1414 _exit(EXIT_FAILURE
);
1417 } else { /* TODO come up with a better way here! */
1420 src
= lxc_storage_get_path(bdev
->src
, bdev
->type
);
1421 bdev
->dest
= strdup(src
);
1424 /* Create our new array, pre-pend the template name and base
1428 for (nargs
= 0; argv
[nargs
]; nargs
++)
1431 /* template, path, rootfs and name args */
1434 newargv
= malloc(nargs
* sizeof(*newargv
));
1436 _exit(EXIT_FAILURE
);
1437 newargv
[0] = lxcbasename(tpath
);
1440 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
1441 patharg
= malloc(len
);
1443 _exit(EXIT_FAILURE
);
1445 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
1446 if (ret
< 0 || ret
>= len
)
1447 _exit(EXIT_FAILURE
);
1448 newargv
[1] = patharg
;
1451 len
= strlen("--name=") + strlen(c
->name
) + 1;
1452 namearg
= malloc(len
);
1454 _exit(EXIT_FAILURE
);
1456 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
1457 if (ret
< 0 || ret
>= len
)
1458 _exit(EXIT_FAILURE
);
1459 newargv
[2] = namearg
;
1462 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
1463 rootfsarg
= malloc(len
);
1465 _exit(EXIT_FAILURE
);
1467 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
1468 if (ret
< 0 || ret
>= len
)
1469 _exit(EXIT_FAILURE
);
1470 newargv
[3] = rootfsarg
;
1472 /* add passed-in args */
1474 for (i
= 4; i
< nargs
; i
++)
1475 newargv
[i
] = argv
[i
- 4];
1477 /* add trailing NULL */
1479 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
1481 _exit(EXIT_FAILURE
);
1482 newargv
[nargs
- 1] = NULL
;
1484 /* If we're running the template in a mapped userns, then we
1485 * prepend the template command with: lxc-usernsexec <-m map1>
1486 * ... <-m mapn> -- and we append "--mapped-uid x", where x is
1487 * the mapped uid for our geteuid()
1489 if (!lxc_list_empty(&conf
->id_map
)) {
1490 int extraargs
, hostuid_mapped
, hostgid_mapped
;
1492 char txtuid
[20], txtgid
[20];
1493 struct lxc_list
*it
;
1497 n2
= malloc(n2args
* sizeof(*n2
));
1499 _exit(EXIT_FAILURE
);
1502 tpath
= "lxc-usernsexec";
1503 n2
[0] = "lxc-usernsexec";
1505 lxc_list_for_each(it
, &conf
->id_map
) {
1508 n2
= realloc(n2
, n2args
* sizeof(char *));
1510 _exit(EXIT_FAILURE
);
1512 n2
[n2args
- 2] = "-m";
1513 n2
[n2args
- 1] = malloc(200);
1514 if (!n2
[n2args
- 1])
1515 _exit(EXIT_FAILURE
);
1517 ret
= snprintf(n2
[n2args
- 1], 200, "%c:%lu:%lu:%lu",
1518 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
1519 map
->nsid
, map
->hostid
, map
->range
);
1520 if (ret
< 0 || ret
>= 200)
1521 _exit(EXIT_FAILURE
);
1524 hostuid_mapped
= mapped_hostid(geteuid(), conf
, ID_TYPE_UID
);
1525 extraargs
= hostuid_mapped
>= 0 ? 1 : 3;
1527 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1529 _exit(EXIT_FAILURE
);
1531 if (hostuid_mapped
< 0) {
1532 hostuid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_UID
);
1533 n2
[n2args
++] = "-m";
1534 if (hostuid_mapped
< 0) {
1535 ERROR("Failed to find free uid to map");
1536 _exit(EXIT_FAILURE
);
1539 n2
[n2args
++] = malloc(200);
1540 if (!n2
[n2args
- 1]) {
1541 SYSERROR("out of memory");
1542 _exit(EXIT_FAILURE
);
1545 ret
= snprintf(n2
[n2args
- 1], 200, "u:%d:%d:1",
1546 hostuid_mapped
, geteuid());
1547 if (ret
< 0 || ret
>= 200)
1548 _exit(EXIT_FAILURE
);
1551 hostgid_mapped
= mapped_hostid(getegid(), conf
, ID_TYPE_GID
);
1552 extraargs
= hostgid_mapped
>= 0 ? 1 : 3;
1554 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
1556 _exit(EXIT_FAILURE
);
1558 if (hostgid_mapped
< 0) {
1559 hostgid_mapped
= find_unmapped_nsid(conf
, ID_TYPE_GID
);
1560 n2
[n2args
++] = "-m";
1561 if (hostgid_mapped
< 0) {
1562 ERROR("Failed to find free gid to map");
1563 _exit(EXIT_FAILURE
);
1566 n2
[n2args
++] = malloc(200);
1567 if (!n2
[n2args
- 1]) {
1568 SYSERROR("out of memory");
1569 _exit(EXIT_FAILURE
);
1572 ret
= snprintf(n2
[n2args
- 1], 200, "g:%d:%d:1",
1573 hostgid_mapped
, getegid());
1574 if (ret
< 0 || ret
>= 200)
1575 _exit(EXIT_FAILURE
);
1578 n2
[n2args
++] = "--";
1580 for (i
= 0; i
< nargs
; i
++)
1581 n2
[i
+ n2args
] = newargv
[i
];
1584 /* Finally add "--mapped-uid $uid" to tell template what
1585 * to chown cached images to.
1588 n2
= realloc(n2
, n2args
* sizeof(char *));
1590 _exit(EXIT_FAILURE
);
1592 /* note n2[n2args-1] is NULL */
1593 n2
[n2args
- 5] = "--mapped-uid";
1595 ret
= snprintf(txtuid
, 20, "%d", hostuid_mapped
);
1596 if (ret
< 0 || ret
>= 20) {
1599 _exit(EXIT_FAILURE
);
1602 n2
[n2args
- 4] = txtuid
;
1603 n2
[n2args
- 3] = "--mapped-gid";
1605 ret
= snprintf(txtgid
, 20, "%d", hostgid_mapped
);
1606 if (ret
< 0 || ret
>= 20) {
1609 _exit(EXIT_FAILURE
);
1612 n2
[n2args
- 2] = txtgid
;
1613 n2
[n2args
- 1] = NULL
;
1618 execvp(tpath
, newargv
);
1619 SYSERROR("Failed to execute template %s", tpath
);
1620 _exit(EXIT_FAILURE
);
1623 ret
= wait_for_pid(pid
);
1625 ERROR("Failed to create container from template");
1632 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1641 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1645 f
= fopen(path
, "r");
1649 ret
= fseek(f
, 0, SEEK_END
);
1658 ret
= fseek(f
, 0, SEEK_SET
);
1662 ret
= fseek(f
, 0, SEEK_SET
);
1667 contents
= malloc(flen
+ 1);
1671 len
= fread(contents
, 1, flen
, f
);
1673 goto out_free_contents
;
1675 contents
[flen
] = '\0';
1680 goto out_free_contents
;
1683 tpath
= get_template_path(t
);
1685 ERROR("Invalid template \"%s\" specified", t
);
1686 goto out_free_contents
;
1689 ret
= sha1sum_file(tpath
, md_value
);
1691 ERROR("Failed to get sha1sum of %s", tpath
);
1693 goto out_free_contents
;
1698 f
= fopen(path
, "w");
1700 SYSERROR("Reopening config for writing");
1705 fprintf(f
, "# Template used to create this container: %s\n", t
);
1707 fprintf(f
, "# Parameters passed to the template:");
1709 fprintf(f
, " %s", *argv
);
1716 fprintf(f
, "# Template script checksum (SHA-1): ");
1717 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1718 fprintf(f
, "%02x", md_value
[i
]);
1721 fprintf(f
, "# For additional config options, please look at lxc.container.conf(5)\n");
1722 fprintf(f
, "\n# Uncomment the following line to support nesting containers:\n");
1723 fprintf(f
, "#lxc.include = " LXCTEMPLATECONFIG
"/nesting.conf\n");
1724 fprintf(f
, "# (Be aware this has security implications)\n\n");
1725 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1726 SYSERROR("Writing original contents");
1746 SYSERROR("Error prepending header");
1753 static void lxcapi_clear_config(struct lxc_container
*c
)
1755 if (!c
|| !c
->lxc_conf
)
1758 lxc_conf_free(c
->lxc_conf
);
1762 #define do_lxcapi_clear_config(c) lxcapi_clear_config(c)
1766 * create a container with the given parameters.
1767 * @c: container to be created. It has the lxcpath, name, and a starting
1768 * configuration already set
1769 * @t: the template to execute to instantiate the root filesystem and
1770 * adjust the configuration.
1771 * @bdevtype: backing store type to use. If NULL, dir will be used.
1772 * @specs: additional parameters for the backing store, i.e. LVM vg to
1775 * @argv: the arguments to pass to the template, terminated by NULL. If no
1776 * arguments, you can just pass NULL.
1778 static bool do_lxcapi_create(struct lxc_container
*c
, const char *t
,
1779 const char *bdevtype
, struct bdev_specs
*specs
,
1780 int flags
, char *const argv
[])
1792 tpath
= get_template_path(t
);
1794 ERROR("Unknown template \"%s\"", t
);
1799 /* If a template is passed in, and the rootfs already is defined in the
1800 * container config and exists, then the caller is trying to create an
1801 * existing container. Return an error, but do NOT delete the container.
1803 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1804 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1805 ERROR("Container \"%s\" already exists in \"%s\"", c
->name
,
1811 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1812 ERROR("Error loading default configuration file %s",
1813 lxc_global_config_value("lxc.default_config"));
1818 if (!create_container_dir(c
))
1821 /* If both template and rootfs.path are set, template is setup as
1822 * rootfs.path. The container is already created if we have a config and
1823 * rootfs.path is accessible
1825 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1826 /* No template passed in and rootfs does not exist. */
1827 if (!c
->save_config(c
, NULL
)) {
1828 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1835 /* Rootfs passed into configuration, but does not exist. */
1836 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1839 if (do_lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1840 /* Rootfs already existed, user just wanted to save the loaded
1843 if (!c
->save_config(c
, NULL
))
1844 ERROR("Failed to save initial config for \"%s\"", c
->name
);
1850 /* Mark that this container is being created */
1851 partial_fd
= create_partial(c
);
1855 /* No need to get disk lock bc we have the partial lock. */
1859 /* Create the storage.
1860 * Note we can't do this in the same task as we use to execute the
1861 * template because of the way zfs works.
1862 * After you 'zfs create', zfs mounts the fs only in the initial
1867 SYSERROR("Failed to fork task for container creation template");
1871 if (pid
== 0) { /* child */
1872 struct lxc_storage
*bdev
= NULL
;
1874 bdev
= do_storage_create(c
, bdevtype
, specs
);
1876 ERROR("Failed to create %s storage for %s",
1877 bdevtype
? bdevtype
: "(none)", c
->name
);
1878 _exit(EXIT_FAILURE
);
1881 /* Save config file again to store the new rootfs location. */
1882 if (!do_lxcapi_save_config(c
, NULL
)) {
1883 ERROR("Failed to save initial config for %s", c
->name
);
1884 /* Parent task won't see the storage driver in the
1885 * config so we delete it.
1887 bdev
->ops
->umount(bdev
);
1888 bdev
->ops
->destroy(bdev
);
1889 _exit(EXIT_FAILURE
);
1892 _exit(EXIT_SUCCESS
);
1895 if (wait_for_pid(pid
) != 0)
1898 /* Reload config to get the rootfs. */
1899 lxc_conf_free(c
->lxc_conf
);
1902 if (!load_config_locked(c
, c
->configfile
))
1905 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1908 /* Now clear out the lxc_conf we have, reload from the created
1911 do_lxcapi_clear_config(c
);
1914 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1915 ERROR("Failed to prepend header to config file");
1920 ret
= load_config_locked(c
, c
->configfile
);
1924 if (partial_fd
>= 0)
1925 remove_partial(c
, partial_fd
);
1929 container_destroy(c
, NULL
);
1936 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1937 const char *bdevtype
, struct bdev_specs
*specs
,
1938 int flags
, char *const argv
[])
1942 current_config
= c
? c
->lxc_conf
: NULL
;
1944 ret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, argv
);
1945 current_config
= NULL
;
1949 static bool do_lxcapi_reboot(struct lxc_container
*c
)
1953 int rebootsignal
= SIGINT
;
1958 if (!do_lxcapi_is_running(c
))
1961 pid
= do_lxcapi_init_pid(c
);
1965 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1966 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1968 ret
= kill(pid
, rebootsignal
);
1970 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
1977 WRAP_API(bool, lxcapi_reboot
)
1979 static bool do_lxcapi_reboot2(struct lxc_container
*c
, int timeout
)
1983 int rebootsignal
= SIGINT
, state_client_fd
= -1;
1984 lxc_state_t states
[MAX_STATE
] = {0};
1989 if (!do_lxcapi_is_running(c
))
1992 pid
= do_lxcapi_init_pid(c
);
1996 if (c
->lxc_conf
&& c
->lxc_conf
->rebootsignal
)
1997 rebootsignal
= c
->lxc_conf
->rebootsignal
;
1999 /* Add a new state client before sending the shutdown signal so that we
2000 * don't miss a state.
2003 states
[RUNNING
] = 2;
2004 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2009 if (state_client_fd
< 0)
2015 if (ret
< MAX_STATE
)
2019 /* Send reboot signal to container. */
2020 killret
= kill(pid
, rebootsignal
);
2022 if (state_client_fd
>= 0)
2023 close(state_client_fd
);
2025 WARN("Failed to send signal %d to pid %d", rebootsignal
, pid
);
2028 TRACE("Sent signal %d to pid %d", rebootsignal
, pid
);
2033 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2034 close(state_client_fd
);
2038 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2045 WRAP_API_1(bool, lxcapi_reboot2
, int)
2047 static bool do_lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
2051 int haltsignal
= SIGPWR
, state_client_fd
= -EBADF
;
2052 lxc_state_t states
[MAX_STATE
] = {0};
2057 if (!do_lxcapi_is_running(c
))
2060 pid
= do_lxcapi_init_pid(c
);
2064 /* Detect whether we should send SIGRTMIN + 3 (e.g. systemd). */
2065 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
2066 haltsignal
= c
->lxc_conf
->haltsignal
;
2067 else if (task_blocks_signal(pid
, (SIGRTMIN
+ 3)))
2068 haltsignal
= (SIGRTMIN
+ 3);
2070 /* Add a new state client before sending the shutdown signal so that we
2071 * don't miss a state.
2074 states
[STOPPED
] = 1;
2075 ret
= lxc_cmd_add_state_client(c
->name
, c
->config_path
, states
,
2080 if (state_client_fd
< 0)
2086 if (ret
< MAX_STATE
)
2090 /* Send shutdown signal to container. */
2091 killret
= kill(pid
, haltsignal
);
2093 if (state_client_fd
>= 0)
2094 close(state_client_fd
);
2096 WARN("Failed to send signal %d to pid %d", haltsignal
, pid
);
2099 TRACE("Sent signal %d to pid %d", haltsignal
, pid
);
2104 ret
= lxc_cmd_sock_rcv_state(state_client_fd
, timeout
);
2105 close(state_client_fd
);
2109 TRACE("Received state \"%s\"", lxc_state2str(ret
));
2116 WRAP_API_1(bool, lxcapi_shutdown
, int)
2118 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
2119 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
2128 current_config
= c
->lxc_conf
;
2131 * since we're going to wait for create to finish, I don't think we
2132 * need to get a copy of the arguments.
2134 va_start(ap
, flags
);
2135 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
2138 ERROR("Failed to allocate memory");
2142 bret
= do_lxcapi_create(c
, t
, bdevtype
, specs
, flags
, args
);
2146 current_config
= NULL
;
2150 static void do_clear_unexp_config_line(struct lxc_conf
*conf
, const char *key
)
2152 if (!strcmp(key
, "lxc.cgroup"))
2153 return clear_unexp_config_line(conf
, key
, true);
2155 if (!strcmp(key
, "lxc.network"))
2156 return clear_unexp_config_line(conf
, key
, true);
2158 if (!strcmp(key
, "lxc.net"))
2159 return clear_unexp_config_line(conf
, key
, true);
2161 /* Clear a network with a specific index. */
2162 if (!strncmp(key
, "lxc.net.", 8)) {
2167 ret
= lxc_safe_uint(idx
, &(unsigned int){0});
2169 return clear_unexp_config_line(conf
, key
, true);
2172 if (!strcmp(key
, "lxc.hook"))
2173 return clear_unexp_config_line(conf
, key
, true);
2175 return clear_unexp_config_line(conf
, key
, false);
2178 static bool do_lxcapi_clear_config_item(struct lxc_container
*c
,
2182 struct lxc_config_t
*config
;
2184 if (!c
|| !c
->lxc_conf
)
2187 if (container_mem_lock(c
))
2190 config
= lxc_get_config(key
);
2191 /* Verify that the config key exists and that it has a callback
2194 if (config
&& config
->clr
)
2195 ret
= config
->clr(key
, c
->lxc_conf
, NULL
);
2198 do_clear_unexp_config_line(c
->lxc_conf
, key
);
2200 container_mem_unlock(c
);
2204 WRAP_API_1(bool, lxcapi_clear_config_item
, const char *)
2206 static inline bool enter_net_ns(struct lxc_container
*c
)
2208 pid_t pid
= do_lxcapi_init_pid(c
);
2210 if ((geteuid() != 0 || (c
->lxc_conf
&& !lxc_list_empty(&c
->lxc_conf
->id_map
))) &&
2211 (access("/proc/self/ns/user", F_OK
) == 0))
2212 if (!switch_to_ns(pid
, "user"))
2215 return switch_to_ns(pid
, "net");
2218 /* Used by qsort and bsearch functions for comparing names. */
2219 static inline int string_cmp(char **first
, char **second
)
2221 return strcmp(*first
, *second
);
2224 /* Used by qsort and bsearch functions for comparing container names. */
2225 static inline int container_cmp(struct lxc_container
**first
,
2226 struct lxc_container
**second
)
2228 return strcmp((*first
)->name
, (*second
)->name
);
2231 static bool add_to_array(char ***names
, char *cname
, int pos
)
2233 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
2235 ERROR("Out of memory");
2240 newnames
[pos
] = strdup(cname
);
2244 /* Sort the arrray as we will use binary search on it. */
2245 qsort(newnames
, pos
+ 1, sizeof(char *),
2246 (int (*)(const void *, const void *))string_cmp
);
2251 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
,
2254 struct lxc_container
**newlist
= realloc(*list
, (pos
+ 1) * sizeof(struct lxc_container
*));
2256 ERROR("Out of memory");
2263 /* Sort the arrray as we will use binary search on it. */
2265 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*),
2266 (int (*)(const void *, const void *))container_cmp
);
2271 static char** get_from_array(char ***names
, char *cname
, int size
)
2273 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
2276 static bool array_contains(char ***names
, char *cname
, int size
)
2278 if(get_from_array(names
, cname
, size
) != NULL
)
2284 static bool remove_from_array(char ***names
, char *cname
, int size
)
2286 char **result
= get_from_array(names
, cname
, size
);
2287 if (result
!= NULL
) {
2295 static char ** do_lxcapi_get_interfaces(struct lxc_container
*c
)
2298 int i
, count
= 0, pipefd
[2];
2299 char **interfaces
= NULL
;
2300 char interface
[IFNAMSIZ
];
2302 if(pipe(pipefd
) < 0) {
2303 SYSERROR("pipe failed");
2309 SYSERROR("failed to fork task to get interfaces information");
2315 if (pid
== 0) { /* child */
2316 int ret
= 1, nbytes
;
2317 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2319 /* close the read-end of the pipe */
2322 if (!enter_net_ns(c
)) {
2323 SYSERROR("failed to enter namespace");
2327 /* Grab the list of interfaces */
2328 if (getifaddrs(&interfaceArray
)) {
2329 SYSERROR("failed to get interfaces list");
2333 /* Iterate through the interfaces */
2334 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
2335 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
2337 ERROR("write failed");
2347 freeifaddrs(interfaceArray
);
2349 /* close the write-end of the pipe, thus sending EOF to the reader */
2354 /* close the write-end of the pipe */
2357 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
2358 interface
[IFNAMSIZ
- 1] = '\0';
2360 if (array_contains(&interfaces
, interface
, count
))
2363 if(!add_to_array(&interfaces
, interface
, count
))
2364 ERROR("Failed to add \"%s\" to array", interface
);
2369 if (wait_for_pid(pid
) != 0) {
2370 for(i
=0;i
<count
;i
++)
2371 free(interfaces
[i
]);
2377 /* close the read-end of the pipe */
2380 /* Append NULL to the array */
2382 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
2387 WRAP_API(char **, lxcapi_get_interfaces
)
2389 static char **do_lxcapi_get_ips(struct lxc_container
*c
, const char *interface
,
2390 const char *family
, int scope
)
2395 char address
[INET6_ADDRSTRLEN
];
2397 char **addresses
= NULL
;
2401 SYSERROR("Failed to create pipe");
2407 SYSERROR("Failed to create new process");
2415 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
2417 char *address
= NULL
;
2418 void *tempAddrPtr
= NULL
;
2419 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
2421 /* close the read-end of the pipe */
2424 if (!enter_net_ns(c
)) {
2425 SYSERROR("Failed to attach to network namespace");
2429 /* Grab the list of interfaces */
2430 if (getifaddrs(&interfaceArray
)) {
2431 SYSERROR("Failed to get interfaces list");
2435 /* Iterate through the interfaces */
2436 for (tempIfAddr
= interfaceArray
; tempIfAddr
;
2437 tempIfAddr
= tempIfAddr
->ifa_next
) {
2438 if (tempIfAddr
->ifa_addr
== NULL
)
2441 if (tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
2442 if (family
&& strcmp(family
, "inet"))
2445 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
2447 if (family
&& strcmp(family
, "inet6"))
2450 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
2453 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
2456 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
2458 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
2461 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
2462 tempAddrPtr
, addressOutputBuffer
,
2463 sizeof(addressOutputBuffer
));
2467 nbytes
= lxc_write_nointr(pipefd
[1], address
, INET6_ADDRSTRLEN
);
2468 if (nbytes
!= INET6_ADDRSTRLEN
) {
2469 SYSERROR("Failed to send ipv6 address \"%s\"",
2481 freeifaddrs(interfaceArray
);
2483 /* close the write-end of the pipe, thus sending EOF to the reader */
2488 /* close the write-end of the pipe */
2491 while (lxc_read_nointr(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
2492 address
[INET6_ADDRSTRLEN
- 1] = '\0';
2494 if (!add_to_array(&addresses
, address
, count
))
2495 ERROR("PARENT: add_to_array failed");
2500 if (wait_for_pid(pid
) != 0) {
2501 for (i
= 0; i
< count
; i
++)
2508 /* close the read-end of the pipe */
2511 /* Append NULL to the array */
2513 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
2518 WRAP_API_3(char **, lxcapi_get_ips
, const char *, const char *, int)
2520 static int do_lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2523 struct lxc_config_t
*config
;
2525 if (!c
|| !c
->lxc_conf
)
2528 if (container_mem_lock(c
))
2531 config
= lxc_get_config(key
);
2532 /* Verify that the config key exists and that it has a callback
2535 if (config
&& config
->get
)
2536 ret
= config
->get(key
, retv
, inlen
, c
->lxc_conf
, NULL
);
2538 container_mem_unlock(c
);
2542 WRAP_API_3(int, lxcapi_get_config_item
, const char *, char *, int)
2544 static char* do_lxcapi_get_running_config_item(struct lxc_container
*c
, const char *key
)
2548 if (!c
|| !c
->lxc_conf
)
2551 if (container_mem_lock(c
))
2554 ret
= lxc_cmd_get_config_item(c
->name
, key
, do_lxcapi_get_config_path(c
));
2555 container_mem_unlock(c
);
2559 WRAP_API_1(char *, lxcapi_get_running_config_item
, const char *)
2561 static int do_lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
2565 /* List all config items. */
2567 return lxc_list_config_items(retv
, inlen
);
2569 if (!c
|| !c
->lxc_conf
)
2572 if (container_mem_lock(c
))
2575 /* Support 'lxc.net.<idx>', i.e. 'lxc.net.0'
2576 * This is an intelligent result to show which keys are valid given the
2577 * type of nic it is.
2579 if (strncmp(key
, "lxc.net.", 8) == 0)
2580 ret
= lxc_list_net(c
->lxc_conf
, key
, retv
, inlen
);
2582 ret
= lxc_list_subkeys(c
->lxc_conf
, key
, retv
, inlen
);
2584 container_mem_unlock(c
);
2588 WRAP_API_3(int, lxcapi_get_keys
, const char *, char *, int)
2590 static bool do_lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
2593 bool ret
= false, need_disklock
= false;
2596 alt_file
= c
->configfile
;
2601 /* If we haven't yet loaded a config, load the stock config. */
2603 if (!do_lxcapi_load_config(c
, lxc_global_config_value("lxc.default_config"))) {
2604 ERROR("Error loading default configuration file %s "
2606 lxc_global_config_value("lxc.default_config"),
2612 if (!create_container_dir(c
))
2615 /* If we're writing to the container's config file, take the disk lock.
2616 * Otherwise just take the memlock to protect the struct lxc_container
2617 * while we're traversing it.
2619 if (strcmp(c
->configfile
, alt_file
) == 0)
2620 need_disklock
= true;
2623 lret
= container_disk_lock(c
);
2625 lret
= container_mem_lock(c
);
2629 fd
= open(alt_file
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_CLOEXEC
,
2630 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
2634 lret
= write_config(fd
, c
->lxc_conf
);
2643 container_disk_unlock(c
);
2645 container_mem_unlock(c
);
2650 WRAP_API_1(bool, lxcapi_save_config
, const char *)
2653 static bool mod_rdep(struct lxc_container
*c0
, struct lxc_container
*c
, bool inc
)
2659 char path
[MAXPATHLEN
];
2660 char newpath
[MAXPATHLEN
];
2661 int fd
, ret
, n
= 0, v
= 0;
2663 size_t len
= 0, bytes
= 0;
2665 if (container_disk_lock(c0
))
2668 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c0
->config_path
, c0
->name
);
2669 if (ret
< 0 || ret
> MAXPATHLEN
)
2672 ret
= snprintf(newpath
, MAXPATHLEN
, "%s\n%s\n", c
->config_path
, c
->name
);
2673 if (ret
< 0 || ret
> MAXPATHLEN
)
2676 /* If we find an lxc-snapshot file using the old format only listing the
2677 * number of snapshots we will keep using it. */
2678 f1
= fopen(path
, "r");
2680 n
= fscanf(f1
, "%d", &v
);
2682 if (n
== 1 && v
== 0) {
2685 SYSERROR("Failed to remove \"%s\"", path
);
2693 f1
= fopen(path
, "w");
2697 if (fprintf(f1
, "%d\n", v
) < 0) {
2698 ERROR("Error writing new snapshots value");
2705 SYSERROR("Error writing to or closing snapshots file");
2709 /* Here we know that we have or can use an lxc-snapshot file
2710 * using the new format. */
2712 f1
= fopen(path
, "a");
2716 if (fprintf(f1
, "%s", newpath
) < 0) {
2717 ERROR("Error writing new snapshots entry");
2720 SYSERROR("Error writing to or closing snapshots file");
2726 SYSERROR("Error writing to or closing snapshots file");
2730 if ((fd
= open(path
, O_RDWR
| O_CLOEXEC
)) < 0)
2733 if (fstat(fd
, &fbuf
) < 0) {
2738 if (fbuf
.st_size
!= 0) {
2739 buf
= lxc_strmmap(NULL
, fbuf
.st_size
, PROT_READ
| PROT_WRITE
, MAP_SHARED
, fd
, 0);
2740 if (buf
== MAP_FAILED
) {
2741 SYSERROR("Failed to create mapping %s", path
);
2746 len
= strlen(newpath
);
2747 while ((del
= strstr((char *)buf
, newpath
))) {
2748 memmove(del
, del
+ len
, strlen(del
) - len
+ 1);
2752 lxc_strmunmap(buf
, fbuf
.st_size
);
2753 if (ftruncate(fd
, fbuf
.st_size
- bytes
) < 0) {
2754 SYSERROR("Failed to truncate file %s", path
);
2763 /* If the lxc-snapshot file is empty, remove it. */
2764 if (stat(path
, &fbuf
) < 0)
2767 if (!fbuf
.st_size
) {
2770 SYSERROR("Failed to remove \"%s\"", path
);
2777 container_disk_unlock(c0
);
2781 void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
2783 struct lxc_container
*p
;
2784 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
2785 size_t pathlen
= 0, namelen
= 0;
2789 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
2790 c
->config_path
, c
->name
);
2791 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2792 ERROR("Path name too long");
2796 f
= fopen(path
, "r");
2800 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
2801 if (getline(&lxcname
, &namelen
, f
) == -1) {
2802 ERROR("badly formatted file %s", path
);
2806 remove_trailing_newlines(lxcpath
);
2807 remove_trailing_newlines(lxcname
);
2809 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
2810 ERROR("Unable to find dependent container %s:%s",
2815 if (!mod_rdep(p
, c
, inc
))
2816 ERROR("Failed to update snapshots file for %s:%s",
2819 lxc_container_put(p
);
2828 static bool has_fs_snapshots(struct lxc_container
*c
)
2831 char path
[MAXPATHLEN
];
2836 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
2838 if (ret
< 0 || ret
> MAXPATHLEN
)
2841 /* If the file doesn't exist there are no snapshots. */
2842 if (stat(path
, &fbuf
) < 0)
2847 f
= fopen(path
, "r");
2851 ret
= fscanf(f
, "%d", &v
);
2853 /* TODO: Figure out what to do with the return value of fscanf. */
2855 INFO("Container uses new lxc-snapshots format %s", path
);
2864 static bool has_snapshots(struct lxc_container
*c
)
2866 char path
[MAXPATHLEN
];
2867 struct dirent
*direntp
;
2871 if (!get_snappath_dir(c
, path
))
2874 dir
= opendir(path
);
2878 while ((direntp
= readdir(dir
))) {
2879 if (!strcmp(direntp
->d_name
, "."))
2882 if (!strcmp(direntp
->d_name
, ".."))
2892 static bool do_destroy_container(struct lxc_conf
*conf
) {
2895 if (am_guest_unpriv()) {
2896 ret
= userns_exec_full(conf
, storage_destroy_wrapper
, conf
,
2897 "storage_destroy_wrapper");
2904 return storage_destroy(conf
);
2907 static int lxc_rmdir_onedev_wrapper(void *data
)
2909 char *arg
= (char *) data
;
2910 return lxc_rmdir_onedev(arg
, "snaps");
2913 static int lxc_unlink_exec_wrapper(void *data
)
2919 static bool container_destroy(struct lxc_container
*c
,
2920 struct lxc_storage
*storage
)
2924 struct lxc_conf
*conf
;
2929 if (!c
|| !do_lxcapi_is_defined(c
))
2933 if (container_disk_lock(c
))
2936 if (!is_stopped(c
)) {
2937 /* We should queue some sort of error - in c->error_string? */
2938 ERROR("container %s is not stopped", c
->name
);
2942 if (conf
&& !lxc_list_empty(&conf
->hooks
[LXCHOOK_DESTROY
])) {
2943 /* Start of environment variable setup for hooks */
2944 if (setenv("LXC_NAME", c
->name
, 1))
2945 SYSERROR("Failed to set environment variable for container name");
2947 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
2948 SYSERROR("Failed to set environment variable for config path");
2950 if (conf
->rootfs
.mount
&& setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1))
2951 SYSERROR("Failed to set environment variable for rootfs mount");
2953 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
2954 SYSERROR("Failed to set environment variable for rootfs mount");
2956 if (conf
->console
.path
&& setenv("LXC_CONSOLE", conf
->console
.path
, 1))
2957 SYSERROR("Failed to set environment variable for console path");
2959 if (conf
->console
.log_path
&& setenv("LXC_CONSOLE_LOGPATH", conf
->console
.log_path
, 1))
2960 SYSERROR("Failed to set environment variable for console log");
2961 /* End of environment variable setup for hooks */
2963 if (run_lxc_hooks(c
->name
, "destroy", conf
, NULL
)) {
2964 ERROR("Failed to execute clone hook for \"%s\"", c
->name
);
2969 if (current_config
&& conf
== current_config
) {
2970 current_config
= NULL
;
2972 if (conf
->logfd
!= -1) {
2978 if (conf
&& conf
->rootfs
.path
&& conf
->rootfs
.mount
) {
2979 if (!do_destroy_container(conf
)) {
2980 ERROR("Error destroying rootfs for %s", c
->name
);
2983 INFO("Destroyed rootfs for %s", c
->name
);
2986 mod_all_rdeps(c
, false);
2988 p1
= do_lxcapi_get_config_path(c
);
2997 * strlen("config") = 6
3001 len
= strlen(p1
) + 1 + strlen(c
->name
) + 1 + 6 + 1;
3004 ERROR("Failed to allocate memory");
3008 /* For an overlay container the rootfs is considered immutable and
3009 * cannot be removed when restoring from a snapshot.
3011 if (storage
&& (!strcmp(storage
->type
, "overlay") ||
3012 !strcmp(storage
->type
, "overlayfs")) &&
3013 (storage
->flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3014 ret
= snprintf(path
, len
, "%s/%s/config", p1
, c
->name
);
3015 if (ret
< 0 || (size_t)ret
>= len
)
3018 if (am_guest_unpriv())
3019 ret
= userns_exec_1(conf
, lxc_unlink_exec_wrapper
, path
,
3020 "lxc_unlink_exec_wrapper");
3024 SYSERROR("Failed to destroy config file \"%s\" for \"%s\"",
3028 INFO("Destroyed config file \"%s\" for \"%s\"", path
, c
->name
);
3034 ret
= snprintf(path
, len
, "%s/%s", p1
, c
->name
);
3035 if (ret
< 0 || (size_t)ret
>= len
)
3038 if (am_guest_unpriv())
3039 ret
= userns_exec_full(conf
, lxc_rmdir_onedev_wrapper
, path
,
3040 "lxc_rmdir_onedev_wrapper");
3042 ret
= lxc_rmdir_onedev(path
, "snaps");
3044 ERROR("Failed to destroy directory \"%s\" for \"%s\"", path
,
3048 INFO("Destroyed directory \"%s\" for \"%s\"", path
, c
->name
);
3056 container_disk_unlock(c
);
3060 static bool do_lxcapi_destroy(struct lxc_container
*c
)
3062 if (!c
|| !lxcapi_is_defined(c
))
3065 if (has_snapshots(c
)) {
3066 ERROR("Container %s has snapshots; not removing", c
->name
);
3070 if (has_fs_snapshots(c
)) {
3071 ERROR("container %s has snapshots on its rootfs", c
->name
);
3075 return container_destroy(c
, NULL
);
3078 WRAP_API(bool, lxcapi_destroy
)
3080 static bool do_lxcapi_destroy_with_snapshots(struct lxc_container
*c
)
3082 if (!c
|| !lxcapi_is_defined(c
))
3085 if (!lxcapi_snapshot_destroy_all(c
)) {
3086 ERROR("Error deleting all snapshots");
3090 return lxcapi_destroy(c
);
3093 WRAP_API(bool, lxcapi_destroy_with_snapshots
)
3095 int lxc_set_config_item_locked(struct lxc_conf
*conf
, const char *key
,
3099 struct lxc_config_t
*config
;
3102 config
= lxc_get_config(key
);
3106 ret
= config
->set(key
, v
, conf
, NULL
);
3110 if (lxc_config_value_empty(v
))
3111 do_clear_unexp_config_line(conf
, key
);
3113 bret
= do_append_unexp_config_line(conf
, key
, v
);
3120 static bool do_set_config_item_locked(struct lxc_container
*c
, const char *key
,
3126 c
->lxc_conf
= lxc_conf_init();
3131 ret
= lxc_set_config_item_locked(c
->lxc_conf
, key
, v
);
3138 static bool do_lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
3145 if (container_mem_lock(c
))
3148 b
= do_set_config_item_locked(c
, key
, v
);
3150 container_mem_unlock(c
);
3154 WRAP_API_2(bool, lxcapi_set_config_item
, const char *, const char *)
3156 static char *lxcapi_config_file_name(struct lxc_container
*c
)
3158 if (!c
|| !c
->configfile
)
3161 return strdup(c
->configfile
);
3164 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
3166 if (!c
|| !c
->config_path
)
3169 return (const char *)(c
->config_path
);
3174 * Just recalculate the c->configfile based on the
3175 * c->config_path, which must be set.
3176 * The lxc_container must be locked or not yet public.
3178 static bool set_config_filename(struct lxc_container
*c
)
3183 if (!c
->config_path
)
3186 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
3187 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
3188 newpath
= malloc(len
);
3192 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
3193 if (ret
< 0 || ret
>= len
) {
3194 fprintf(stderr
, "Error printing out config file name\n");
3199 free(c
->configfile
);
3200 c
->configfile
= newpath
;
3205 static bool do_lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
3209 char *oldpath
= NULL
;
3214 if (container_mem_lock(c
))
3219 ERROR("Out of memory setting new lxc path");
3225 oldpath
= c
->config_path
;
3228 /* Since we've changed the config path, we have to change the
3229 * config file name too */
3230 if (!set_config_filename(c
)) {
3231 ERROR("Out of memory setting new config filename");
3233 free(c
->config_path
);
3234 c
->config_path
= oldpath
;
3240 container_mem_unlock(c
);
3244 WRAP_API_1(bool, lxcapi_set_config_path
, const char *)
3246 static bool do_lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
3249 struct cgroup_ops
*cgroup_ops
;
3257 cgroup_ops
= cgroup_init(NULL
);
3261 if (container_disk_lock(c
))
3264 ret
= cgroup_ops
->set(cgroup_ops
, subsys
, value
, c
->name
, c
->config_path
);
3266 container_disk_unlock(c
);
3268 cgroup_exit(cgroup_ops
);
3273 WRAP_API_2(bool, lxcapi_set_cgroup_item
, const char *, const char *)
3275 static int do_lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
3278 struct cgroup_ops
*cgroup_ops
;
3286 cgroup_ops
= cgroup_init(NULL
);
3290 if (container_disk_lock(c
))
3293 ret
= cgroup_ops
->get(cgroup_ops
, subsys
, retv
, inlen
, c
->name
,
3296 container_disk_unlock(c
);
3298 cgroup_exit(cgroup_ops
);
3303 WRAP_API_3(int, lxcapi_get_cgroup_item
, const char *, char *, int)
3305 const char *lxc_get_global_config_item(const char *key
)
3307 return lxc_global_config_value(key
);
3310 const char *lxc_get_version(void)
3315 static int copy_file(const char *old
, const char *new)
3322 if (file_exists(new)) {
3323 ERROR("copy destination %s exists", new);
3327 ret
= stat(old
, &sbuf
);
3329 INFO("Error stat'ing %s", old
);
3333 in
= open(old
, O_RDONLY
);
3335 SYSERROR("Error opening original file %s", old
);
3339 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
3341 SYSERROR("Error opening new file %s", new);
3347 len
= read(in
, buf
, 8096);
3349 SYSERROR("Error reading old file %s", old
);
3356 ret
= write(out
, buf
, len
);
3357 if (ret
< len
) { /* should we retry? */
3358 SYSERROR("Error: write to new file %s was interrupted", new);
3366 /* We set mode, but not owner/group. */
3367 ret
= chmod(new, sbuf
.st_mode
);
3369 SYSERROR("Error setting mode on %s", new);
3381 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
3384 struct lxc_list
*it
;
3387 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
3388 cpath
= alloca(len
);
3389 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
3390 if (ret
< 0 || ret
>= len
)
3393 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
3394 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
3395 char *hookname
= it
->elem
;
3396 char *fname
= strrchr(hookname
, '/');
3397 char tmppath
[MAXPATHLEN
];
3398 if (!fname
) /* relative path - we don't support, but maybe we should */
3401 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
3402 /* this hook is public - ignore */
3406 /* copy the script, and change the entry in confile */
3407 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
3408 c
->config_path
, c
->name
, fname
+1);
3409 if (ret
< 0 || ret
>= MAXPATHLEN
)
3412 ret
= copy_file(it
->elem
, tmppath
);
3418 it
->elem
= strdup(tmppath
);
3420 ERROR("out of memory copying hook path");
3426 if (!clone_update_unexp_hooks(c
->lxc_conf
, oldc
->config_path
,
3427 c
->config_path
, oldc
->name
, c
->name
)) {
3428 ERROR("Error saving new hooks in clone");
3432 do_lxcapi_save_config(c
, NULL
);
3437 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
3439 char newpath
[MAXPATHLEN
];
3440 char *oldpath
= oldc
->lxc_conf
->fstab
;
3446 clear_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", false);
3448 char *p
= strrchr(oldpath
, '/');
3452 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
3453 c
->config_path
, c
->name
, p
);
3454 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3455 ERROR("error printing new path for %s", oldpath
);
3459 if (file_exists(newpath
)) {
3460 ERROR("error: fstab file %s exists", newpath
);
3464 if (copy_file(oldpath
, newpath
) < 0) {
3465 ERROR("error: copying %s to %s", oldpath
, newpath
);
3469 free(c
->lxc_conf
->fstab
);
3471 c
->lxc_conf
->fstab
= strdup(newpath
);
3472 if (!c
->lxc_conf
->fstab
) {
3473 ERROR("error: allocating pathname");
3477 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.mount.fstab", newpath
)) {
3478 ERROR("error saving new lxctab");
3485 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3487 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
3490 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
3492 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3493 WARN("Error copying reverse dependencies");
3497 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3499 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3500 WARN("Error copying reverse dependencies");
3504 if (copy_file(path0
, path1
) < 0) {
3505 INFO("Error copying reverse dependencies");
3510 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
3513 char path
[MAXPATHLEN
];
3517 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
3519 if (ret
< 0 || ret
>= MAXPATHLEN
)
3522 f
= fopen(path
, "a");
3528 /* If anything goes wrong, just return an error. */
3529 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
3539 * If the fs natively supports snapshot clones with no penalty,
3540 * then default to those even if not requested.
3541 * Currently we only do this for btrfs.
3543 bool should_default_to_snapshot(struct lxc_container
*c0
,
3544 struct lxc_container
*c1
)
3547 size_t l0
= strlen(c0
->config_path
) + strlen(c0
->name
) + 2;
3548 size_t l1
= strlen(c1
->config_path
) + strlen(c1
->name
) + 2;
3549 char *p0
= alloca(l0
+ 1);
3550 char *p1
= alloca(l1
+ 1);
3551 char *rootfs
= c0
->lxc_conf
->rootfs
.path
;
3553 ret
= snprintf(p0
, l0
, "%s/%s", c0
->config_path
, c0
->name
);
3554 if (ret
< 0 || ret
>= l0
)
3557 ret
= snprintf(p1
, l1
, "%s/%s", c1
->config_path
, c1
->name
);
3558 if (ret
< 0 || ret
>= l1
)
3561 if (!is_btrfs_fs(p0
) || !is_btrfs_fs(p1
))
3564 if (is_btrfs_subvol(rootfs
) <= 0)
3567 return btrfs_same_fs(p0
, p1
) == 0;
3570 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
3571 const char *newtype
, int flags
, const char *bdevdata
,
3574 struct lxc_storage
*bdev
;
3577 if (should_default_to_snapshot(c0
, c
))
3578 flags
|= LXC_CLONE_SNAPSHOT
;
3580 bdev
= storage_copy(c0
, c
->name
, c
->config_path
, newtype
, flags
,
3581 bdevdata
, newsize
, &need_rdep
);
3583 ERROR("Error copying storage.");
3587 /* Set new rootfs. */
3588 free(c
->lxc_conf
->rootfs
.path
);
3589 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
3592 if (!c
->lxc_conf
->rootfs
.path
) {
3593 ERROR("Out of memory while setting storage path.");
3597 /* Append a new lxc.rootfs.path entry to the unexpanded config. */
3598 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3599 if (!do_append_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path",
3600 c
->lxc_conf
->rootfs
.path
)) {
3601 ERROR("Error saving new rootfs to cloned config.");
3605 if (flags
& LXC_CLONE_SNAPSHOT
)
3606 copy_rdepends(c
, c0
);
3609 if (!add_rdepends(c
, c0
))
3610 WARN("Error adding reverse dependency from %s to %s",
3614 mod_all_rdeps(c
, true);
3619 struct clone_update_data
{
3620 struct lxc_container
*c0
;
3621 struct lxc_container
*c1
;
3626 static int clone_update_rootfs(struct clone_update_data
*data
)
3628 struct lxc_container
*c0
= data
->c0
;
3629 struct lxc_container
*c
= data
->c1
;
3630 int flags
= data
->flags
;
3631 char **hookargs
= data
->hookargs
;
3633 char path
[MAXPATHLEN
];
3634 struct lxc_storage
*bdev
;
3636 struct lxc_conf
*conf
= c
->lxc_conf
;
3638 /* update hostname in rootfs */
3639 /* we're going to mount, so run in a clean namespace to simplify cleanup */
3641 if (setgid(0) < 0) {
3642 ERROR("Failed to setgid to 0");
3646 if (setuid(0) < 0) {
3647 ERROR("Failed to setuid to 0");
3651 if (setgroups(0, NULL
) < 0)
3652 WARN("Failed to clear groups");
3654 if (unshare(CLONE_NEWNS
) < 0)
3657 bdev
= storage_init(c
->lxc_conf
);
3661 if (strcmp(bdev
->type
, "dir") != 0) {
3662 if (unshare(CLONE_NEWNS
) < 0) {
3663 ERROR("error unsharing mounts");
3668 if (detect_shared_rootfs()) {
3669 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
)) {
3670 SYSERROR("Failed to make / rslave");
3671 ERROR("Continuing...");
3675 if (bdev
->ops
->mount(bdev
) < 0) {
3679 } else { /* TODO come up with a better way */
3681 bdev
->dest
= strdup(bdev
->src
);
3684 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
3685 /* Start of environment variable setup for hooks */
3686 if (c0
->name
&& setenv("LXC_SRC_NAME", c0
->name
, 1))
3687 SYSERROR("failed to set environment variable for source container name");
3689 if (setenv("LXC_NAME", c
->name
, 1))
3690 SYSERROR("failed to set environment variable for container name");
3692 if (conf
->rcfile
&& setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1))
3693 SYSERROR("failed to set environment variable for config path");
3695 if (bdev
->dest
&& setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1))
3696 SYSERROR("failed to set environment variable for rootfs mount");
3698 if (conf
->rootfs
.path
&& setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1))
3699 SYSERROR("failed to set environment variable for rootfs mount");
3701 if (run_lxc_hooks(c
->name
, "clone", conf
, hookargs
)) {
3702 ERROR("Error executing clone hook for %s", c
->name
);
3708 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3709 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
3712 if (ret
< 0 || ret
>= MAXPATHLEN
)
3715 if (!file_exists(path
))
3718 if (!(fout
= fopen(path
, "w"))) {
3719 SYSERROR("unable to open %s: ignoring", path
);
3723 if (fprintf(fout
, "%s", c
->name
) < 0) {
3728 if (fclose(fout
) < 0)
3737 static int clone_update_rootfs_wrapper(void *data
)
3739 struct clone_update_data
*arg
= (struct clone_update_data
*) data
;
3740 return clone_update_rootfs(arg
);
3744 * We want to support:
3745 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
3746 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
3748 -s [ implies overlay]
3751 only rootfs gets converted (copied/snapshotted) on clone.
3754 static int create_file_dirname(char *path
, struct lxc_conf
*conf
)
3756 char *p
= strrchr(path
, '/');
3763 ret
= do_create_container_dir(path
, conf
);
3769 static struct lxc_container
*do_lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3770 const char *lxcpath
, int flags
,
3771 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3774 char newpath
[MAXPATHLEN
];
3776 struct clone_update_data data
;
3777 size_t saved_unexp_len
;
3779 int storage_copied
= 0;
3780 char *origroot
= NULL
, *saved_unexp_conf
= NULL
;
3781 struct lxc_container
*c2
= NULL
;
3783 if (!c
|| !do_lxcapi_is_defined(c
))
3786 if (container_mem_lock(c
))
3789 if (!is_stopped(c
)) {
3790 ERROR("error: Original container (%s) is running", c
->name
);
3794 /* Make sure the container doesn't yet exist. */
3799 lxcpath
= do_lxcapi_get_config_path(c
);
3801 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", lxcpath
, newname
);
3802 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3803 SYSERROR("clone: failed making config pathname");
3807 if (file_exists(newpath
)) {
3808 ERROR("error: clone: %s exists", newpath
);
3812 ret
= create_file_dirname(newpath
, c
->lxc_conf
);
3813 if (ret
< 0 && errno
!= EEXIST
) {
3814 ERROR("Error creating container dir for %s", newpath
);
3818 /* Copy the configuration. Tweak it as needed. */
3819 if (c
->lxc_conf
->rootfs
.path
) {
3820 origroot
= c
->lxc_conf
->rootfs
.path
;
3821 c
->lxc_conf
->rootfs
.path
= NULL
;
3824 fd
= open(newpath
, O_WRONLY
| O_CREAT
| O_CLOEXEC
,
3825 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IROTH
| S_IWOTH
);
3827 SYSERROR("Failed to open \"%s\"", newpath
);
3831 saved_unexp_conf
= c
->lxc_conf
->unexpanded_config
;
3832 saved_unexp_len
= c
->lxc_conf
->unexpanded_len
;
3833 c
->lxc_conf
->unexpanded_config
= strdup(saved_unexp_conf
);
3834 if (!c
->lxc_conf
->unexpanded_config
) {
3839 clear_unexp_config_line(c
->lxc_conf
, "lxc.rootfs.path", false);
3840 write_config(fd
, c
->lxc_conf
);
3843 c
->lxc_conf
->rootfs
.path
= origroot
;
3845 free(c
->lxc_conf
->unexpanded_config
);
3846 c
->lxc_conf
->unexpanded_config
= saved_unexp_conf
;
3847 saved_unexp_conf
= NULL
;
3848 c
->lxc_conf
->unexpanded_len
= saved_unexp_len
;
3850 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, newname
);
3851 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3852 SYSERROR("clone: failed making rootfs pathname");
3856 ret
= mkdir(newpath
, 0755);
3858 /* For an overlay container the rootfs is considered immutable
3859 * and will not have been removed when restoring from a
3862 if (errno
!= ENOENT
&&
3863 !(flags
& LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
)) {
3864 SYSERROR("Failed to create directory \"%s\"", newpath
);
3869 if (am_guest_unpriv()) {
3870 if (chown_mapped_root(newpath
, c
->lxc_conf
) < 0) {
3871 ERROR("Error chowning %s to container root", newpath
);
3876 c2
= lxc_container_new(newname
, lxcpath
);
3878 ERROR("clone: failed to create new container (%s %s)", newname
,
3883 /* copy/snapshot rootfs's */
3884 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
3888 /* update utsname */
3889 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
3890 clear_unexp_config_line(c2
->lxc_conf
, "lxc.utsname", false);
3891 clear_unexp_config_line(c2
->lxc_conf
, "lxc.uts.name", false);
3893 if (!do_set_config_item_locked(c2
, "lxc.uts.name", newname
)) {
3894 ERROR("Error setting new hostname");
3900 ret
= copyhooks(c
, c2
);
3902 ERROR("error copying hooks");
3906 if (copy_fstab(c
, c2
) < 0) {
3907 ERROR("error copying fstab");
3911 /* update macaddrs */
3912 if (!(flags
& LXC_CLONE_KEEPMACADDR
)) {
3913 if (!network_new_hwaddrs(c2
->lxc_conf
)) {
3914 ERROR("Error updating mac addresses");
3919 /* Update absolute paths for overlay mount directories. */
3920 if (ovl_update_abs_paths(c2
->lxc_conf
, c
->config_path
, c
->name
, lxcpath
, newname
) < 0)
3923 /* We've now successfully created c2's storage, so clear it out if we
3928 if (!c2
->save_config(c2
, NULL
))
3931 if ((pid
= fork()) < 0) {
3937 ret
= wait_for_pid(pid
);
3941 container_mem_unlock(c
);
3948 data
.hookargs
= hookargs
;
3950 if (am_guest_unpriv())
3951 ret
= userns_exec_full(c
->lxc_conf
, clone_update_rootfs_wrapper
,
3952 &data
, "clone_update_rootfs_wrapper");
3954 ret
= clone_update_rootfs(&data
);
3956 _exit(EXIT_FAILURE
);
3958 container_mem_unlock(c
);
3959 _exit(EXIT_SUCCESS
);
3962 container_mem_unlock(c
);
3964 if (!storage_copied
)
3965 c2
->lxc_conf
->rootfs
.path
= NULL
;
3968 lxc_container_put(c2
);
3974 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
3975 const char *lxcpath
, int flags
,
3976 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
3979 struct lxc_container
* ret
;
3981 current_config
= c
? c
->lxc_conf
: NULL
;
3982 ret
= do_lxcapi_clone(c
, newname
, lxcpath
, flags
, bdevtype
, bdevdata
, newsize
, hookargs
);
3983 current_config
= NULL
;
3988 static bool do_lxcapi_rename(struct lxc_container
*c
, const char *newname
)
3990 struct lxc_storage
*bdev
;
3991 struct lxc_container
*newc
;
3993 if (!c
|| !c
->name
|| !c
->config_path
|| !c
->lxc_conf
)
3996 if (has_fs_snapshots(c
) || has_snapshots(c
)) {
3997 ERROR("Renaming a container with snapshots is not supported");
4001 bdev
= storage_init(c
->lxc_conf
);
4003 ERROR("Failed to find original backing store type");
4007 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
4010 lxc_container_put(newc
);
4014 if (newc
&& lxcapi_is_defined(newc
))
4015 lxc_container_put(newc
);
4017 if (!container_destroy(c
, NULL
)) {
4018 ERROR("Could not destroy existing container %s", c
->name
);
4025 WRAP_API_1(bool, lxcapi_rename
, const char *)
4027 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
)
4034 current_config
= c
->lxc_conf
;
4036 ret
= lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
4037 current_config
= NULL
;
4041 static int do_lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4043 lxc_attach_command_t command
;
4050 command
.program
= (char*)program
;
4051 command
.argv
= (char**)argv
;
4053 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
4059 return lxc_wait_for_pid_status(pid
);
4062 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
4066 current_config
= c
? c
->lxc_conf
: NULL
;
4067 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, argv
);
4068 current_config
= NULL
;
4073 static int get_next_index(const char *lxcpath
, char *cname
)
4079 fname
= alloca(strlen(lxcpath
) + 20);
4082 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
4084 ret
= stat(fname
, &sb
);
4092 static bool get_snappath_dir(struct lxc_container
*c
, char *snappath
)
4097 * If the old style snapshot path exists, use it
4098 * /var/lib/lxc -> /var/lib/lxcsnaps
4100 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps", c
->config_path
);
4101 if (ret
< 0 || ret
>= MAXPATHLEN
)
4104 if (dir_exists(snappath
)) {
4105 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
4106 if (ret
< 0 || ret
>= MAXPATHLEN
)
4113 * Use the new style path
4114 * /var/lib/lxc -> /var/lib/lxc + c->name + /snaps + \0
4116 ret
= snprintf(snappath
, MAXPATHLEN
, "%s/%s/snaps", c
->config_path
, c
->name
);
4117 if (ret
< 0 || ret
>= MAXPATHLEN
)
4123 static int do_lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
4126 struct lxc_container
*c2
;
4127 char snappath
[MAXPATHLEN
], newname
[20];
4129 if (!c
|| !lxcapi_is_defined(c
))
4132 if (!storage_can_backup(c
->lxc_conf
)) {
4133 ERROR("%s's backing store cannot be backed up.", c
->name
);
4134 ERROR("Your container must use another backing store type.");
4138 if (!get_snappath_dir(c
, snappath
))
4141 i
= get_next_index(snappath
, c
->name
);
4143 if (mkdir_p(snappath
, 0755) < 0) {
4144 ERROR("Failed to create snapshot directory %s", snappath
);
4148 ret
= snprintf(newname
, 20, "snap%d", i
);
4149 if (ret
< 0 || ret
>= 20)
4153 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
4154 * created in the original container
4156 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
4157 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
4158 if (storage_is_dir(c
->lxc_conf
)) {
4159 ERROR("Snapshot of directory-backed container requested.");
4160 ERROR("Making a copy-clone. If you do want snapshots, then");
4161 ERROR("please create overlay clone first, snapshot that");
4162 ERROR("and keep the original container pristine.");
4163 flags
&= ~LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4166 c2
= do_lxcapi_clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
4168 ERROR("clone of %s:%s failed", c
->config_path
, c
->name
);
4172 lxc_container_put(c2
);
4174 /* Now write down the creation time. */
4181 tm_info
= localtime(&timer
);
4183 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
4185 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
4186 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
4187 f
= fopen(dfnam
, "w");
4189 ERROR("Failed to open %s", dfnam
);
4193 if (fprintf(f
, "%s", buffer
) < 0) {
4194 SYSERROR("Writing timestamp");
4201 SYSERROR("Writing timestamp");
4206 /* $p / $name / comment \0 */
4207 int len
= strlen(snappath
) + strlen(newname
) + 10;
4208 char *path
= alloca(len
);
4210 sprintf(path
, "%s/%s/comment", snappath
, newname
);
4211 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
4217 WRAP_API_1(int, lxcapi_snapshot
, const char *)
4219 static void lxcsnap_free(struct lxc_snapshot
*s
)
4222 free(s
->comment_pathname
);
4227 static char *get_snapcomment_path(char* snappath
, char *name
)
4229 /* $snappath/$name/comment */
4230 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
4231 char *s
= malloc(len
);
4234 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
4235 if (ret
< 0 || ret
>= len
) {
4244 static char *get_timestamp(char* snappath
, char *name
)
4246 char path
[MAXPATHLEN
], *s
= NULL
;
4250 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
4251 if (ret
< 0 || ret
>= MAXPATHLEN
)
4254 fin
= fopen(path
, "r");
4258 (void) fseek(fin
, 0, SEEK_END
);
4260 (void) fseek(fin
, 0, SEEK_SET
);
4265 if (fread(s
, 1, len
, fin
) != len
) {
4266 SYSERROR("reading timestamp");
4277 static int do_lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
4279 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
4281 struct dirent
*direntp
;
4282 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
4285 if (!c
|| !lxcapi_is_defined(c
))
4288 if (!get_snappath_dir(c
, snappath
)) {
4289 ERROR("path name too long");
4293 dir
= opendir(snappath
);
4295 INFO("Failed to open %s - assuming no snapshots", snappath
);
4299 while ((direntp
= readdir(dir
))) {
4300 if (!strcmp(direntp
->d_name
, "."))
4303 if (!strcmp(direntp
->d_name
, ".."))
4306 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
4307 if (ret
< 0 || ret
>= MAXPATHLEN
) {
4308 ERROR("pathname too long");
4312 if (!file_exists(path2
))
4315 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
4317 SYSERROR("Out of memory");
4322 snaps
[count
].free
= lxcsnap_free
;
4323 snaps
[count
].name
= strdup(direntp
->d_name
);
4324 if (!snaps
[count
].name
)
4327 snaps
[count
].lxcpath
= strdup(snappath
);
4328 if (!snaps
[count
].lxcpath
) {
4329 free(snaps
[count
].name
);
4333 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
4334 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
4339 WARN("Failed to close directory");
4348 for (i
=0; i
<count
; i
++)
4349 lxcsnap_free(&snaps
[i
]);
4355 WARN("Failed to close directory");
4360 WRAP_API_1(int, lxcapi_snapshot_list
, struct lxc_snapshot
**)
4362 static bool do_lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
4364 char clonelxcpath
[MAXPATHLEN
];
4366 struct lxc_container
*snap
, *rest
;
4367 struct lxc_storage
*bdev
;
4370 if (!c
|| !c
->name
|| !c
->config_path
)
4373 if (has_fs_snapshots(c
)) {
4374 ERROR("container rootfs has dependent snapshots");
4378 bdev
= storage_init(c
->lxc_conf
);
4380 ERROR("Failed to find original backing store type");
4384 /* For an overlay container the rootfs is considered immutable
4385 * and cannot be removed when restoring from a snapshot. We pass this
4386 * internal flag along to communicate this to various parts of the
4389 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4390 bdev
->flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4395 if (!get_snappath_dir(c
, clonelxcpath
)) {
4399 /* how should we lock this? */
4401 snap
= lxc_container_new(snapname
, clonelxcpath
);
4402 if (!snap
|| !lxcapi_is_defined(snap
)) {
4403 ERROR("Could not open snapshot %s", snapname
);
4406 lxc_container_put(snap
);
4412 if (!strcmp(c
->name
, newname
)) {
4413 if (!container_destroy(c
, bdev
)) {
4414 ERROR("Could not destroy existing container %s", newname
);
4415 lxc_container_put(snap
);
4421 if (strcmp(bdev
->type
, "dir") != 0 && strcmp(bdev
->type
, "loop") != 0)
4422 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_MAYBE_SNAPSHOT
;
4424 if (!strcmp(bdev
->type
, "overlay") || !strcmp(bdev
->type
, "overlayfs"))
4425 flags
|= LXC_STORAGE_INTERNAL_OVERLAY_RESTORE
;
4427 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, flags
, bdev
->type
,
4430 if (rest
&& lxcapi_is_defined(rest
))
4434 lxc_container_put(rest
);
4436 lxc_container_put(snap
);
4440 WRAP_API_2(bool, lxcapi_snapshot_restore
, const char *, const char *)
4442 static bool do_snapshot_destroy(const char *snapname
, const char *clonelxcpath
)
4444 struct lxc_container
*snap
= NULL
;
4447 snap
= lxc_container_new(snapname
, clonelxcpath
);
4449 ERROR("Could not find snapshot %s", snapname
);
4453 if (!do_lxcapi_destroy(snap
)) {
4454 ERROR("Could not destroy snapshot %s", snapname
);
4462 lxc_container_put(snap
);
4467 static bool remove_all_snapshots(const char *path
)
4470 struct dirent
*direntp
;
4473 dir
= opendir(path
);
4475 SYSERROR("opendir on snapshot path %s", path
);
4479 while ((direntp
= readdir(dir
))) {
4480 if (!strcmp(direntp
->d_name
, "."))
4483 if (!strcmp(direntp
->d_name
, ".."))
4486 if (!do_snapshot_destroy(direntp
->d_name
, path
)) {
4495 SYSERROR("Error removing directory %s", path
);
4500 static bool do_lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
4502 char clonelxcpath
[MAXPATHLEN
];
4504 if (!c
|| !c
->name
|| !c
->config_path
|| !snapname
)
4507 if (!get_snappath_dir(c
, clonelxcpath
))
4510 return do_snapshot_destroy(snapname
, clonelxcpath
);
4513 WRAP_API_1(bool, lxcapi_snapshot_destroy
, const char *)
4515 static bool do_lxcapi_snapshot_destroy_all(struct lxc_container
*c
)
4517 char clonelxcpath
[MAXPATHLEN
];
4519 if (!c
|| !c
->name
|| !c
->config_path
)
4522 if (!get_snappath_dir(c
, clonelxcpath
))
4525 return remove_all_snapshots(clonelxcpath
);
4528 WRAP_API(bool, lxcapi_snapshot_destroy_all
)
4530 static bool do_lxcapi_may_control(struct lxc_container
*c
)
4532 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
4535 WRAP_API(bool, lxcapi_may_control
)
4537 static bool do_add_remove_node(pid_t init_pid
, const char *path
, bool add
,
4543 char chrootpath
[MAXPATHLEN
];
4544 char *directory_path
= NULL
;
4548 SYSERROR("Failed to fork()");
4553 ret
= wait_for_pid(pid
);
4555 ERROR("Failed to create device node");
4562 /* prepare the path */
4563 ret
= snprintf(chrootpath
, MAXPATHLEN
, "/proc/%d/root", init_pid
);
4564 if (ret
< 0 || ret
>= MAXPATHLEN
)
4567 ret
= chroot(chrootpath
);
4569 _exit(EXIT_FAILURE
);
4573 _exit(EXIT_FAILURE
);
4575 /* remove path if it exists */
4576 ret
= faccessat(AT_FDCWD
, path
, F_OK
, AT_SYMLINK_NOFOLLOW
);
4580 SYSERROR("Failed to remove \"%s\"", path
);
4581 _exit(EXIT_FAILURE
);
4586 _exit(EXIT_SUCCESS
);
4588 /* create any missing directories */
4591 _exit(EXIT_FAILURE
);
4593 directory_path
= dirname(tmp
);
4594 ret
= mkdir_p(directory_path
, 0755);
4595 if (ret
< 0 && errno
!= EEXIST
) {
4596 SYSERROR("Failed to create path \"%s\"", directory_path
);
4598 _exit(EXIT_FAILURE
);
4601 /* create the device node */
4602 ret
= mknod(path
, st
->st_mode
, st
->st_rdev
);
4605 SYSERROR("Failed to create device node at \"%s\"", path
);
4606 _exit(EXIT_FAILURE
);
4609 _exit(EXIT_SUCCESS
);
4612 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
4616 char value
[LXC_MAX_BUFFER
];
4619 /* make sure container is running */
4620 if (!do_lxcapi_is_running(c
)) {
4621 ERROR("container is not running");
4625 /* use src_path if dest_path is NULL otherwise use dest_path */
4626 p
= dest_path
? dest_path
: src_path
;
4628 /* make sure we can access p */
4629 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
4632 /* continue if path is character device or block device */
4633 if (S_ISCHR(st
.st_mode
))
4634 ret
= snprintf(value
, LXC_MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4635 else if (S_ISBLK(st
.st_mode
))
4636 ret
= snprintf(value
, LXC_MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
4640 /* check snprintf return code */
4641 if (ret
< 0 || ret
>= LXC_MAX_BUFFER
)
4644 if (!do_add_remove_node(do_lxcapi_init_pid(c
), p
, add
, &st
))
4647 /* add or remove device to/from cgroup access list */
4649 if (!do_lxcapi_set_cgroup_item(c
, "devices.allow", value
)) {
4650 ERROR("set_cgroup_item failed while adding the device node");
4654 if (!do_lxcapi_set_cgroup_item(c
, "devices.deny", value
)) {
4655 ERROR("set_cgroup_item failed while removing the device node");
4663 static bool do_lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4665 // cannot mknod if we're not privileged wrt init_user_ns
4666 if (am_host_unpriv()) {
4667 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4671 return add_remove_device_node(c
, src_path
, dest_path
, true);
4674 WRAP_API_2(bool, lxcapi_add_device_node
, const char *, const char *)
4676 static bool do_lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
4678 if (am_guest_unpriv()) {
4679 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4683 return add_remove_device_node(c
, src_path
, dest_path
, false);
4686 WRAP_API_2(bool, lxcapi_remove_device_node
, const char *, const char *)
4688 static bool do_lxcapi_attach_interface(struct lxc_container
*c
,
4690 const char *dst_ifname
)
4695 if (am_guest_unpriv()) {
4696 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4701 ERROR("No source interface name given");
4705 ret
= lxc_netdev_isup(ifname
);
4707 /* netdev of ifname is up. */
4708 ret
= lxc_netdev_down(ifname
);
4713 init_pid
= do_lxcapi_init_pid(c
);
4714 ret
= lxc_netdev_move_by_name(ifname
, init_pid
, dst_ifname
);
4718 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, init_pid
);
4725 WRAP_API_2(bool, lxcapi_attach_interface
, const char *, const char *)
4727 static bool do_lxcapi_detach_interface(struct lxc_container
*c
,
4729 const char *dst_ifname
)
4732 pid_t pid
, pid_outside
;
4735 * TODO - if this is a physical device, then we need am_host_unpriv.
4736 * But for other types guest privilege suffices.
4738 if (am_guest_unpriv()) {
4739 ERROR(LXC_UNPRIV_EOPNOTSUPP
, __FUNCTION__
);
4744 ERROR("No source interface name given");
4748 pid_outside
= lxc_raw_getpid();
4751 ERROR("Failed to fork");
4755 if (pid
== 0) { /* child */
4758 init_pid
= do_lxcapi_init_pid(c
);
4759 if (!switch_to_ns(init_pid
, "net")) {
4760 ERROR("Failed to enter network namespace");
4761 _exit(EXIT_FAILURE
);
4764 ret
= lxc_netdev_isup(ifname
);
4766 ERROR("Failed to determine whether network device \"%s\" is up", ifname
);
4767 _exit(EXIT_FAILURE
);
4770 /* netdev of ifname is up. */
4772 ret
= lxc_netdev_down(ifname
);
4774 ERROR("Failed to set network device \"%s\" down", ifname
);
4775 _exit(EXIT_FAILURE
);
4779 ret
= lxc_netdev_move_by_name(ifname
, pid_outside
, dst_ifname
);
4780 /* -EINVAL means there is no netdev named as ifname. */
4783 ERROR("Network device \"%s\" not found", ifname
);
4785 ERROR("Failed to remove network device \"%s\"", ifname
);
4787 _exit(EXIT_FAILURE
);
4790 _exit(EXIT_SUCCESS
);
4793 ret
= wait_for_pid(pid
);
4797 INFO("Moved network device \"%s\" to network namespace of %d", ifname
, pid_outside
);
4801 WRAP_API_2(bool, lxcapi_detach_interface
, const char *, const char *)
4803 static int do_lxcapi_migrate(struct lxc_container
*c
, unsigned int cmd
,
4804 struct migrate_opts
*opts
, unsigned int size
)
4807 struct migrate_opts
*valid_opts
= opts
;
4808 uint64_t features_to_check
= 0;
4810 /* If the caller has a bigger (newer) struct migrate_opts, let's make
4811 * sure that the stuff on the end is zero, i.e. that they didn't ask us
4812 * to do anything special.
4814 if (size
> sizeof(*opts
)) {
4815 unsigned char *addr
;
4818 addr
= (void *)opts
+ sizeof(*opts
);
4819 end
= (void *)opts
+ size
;
4821 for (; addr
< end
; addr
++)
4826 /* If the caller has a smaller struct, let's zero out the end for them
4827 * so we don't accidentally use bits of it that they didn't know about
4830 if (size
< sizeof(*opts
)) {
4831 valid_opts
= malloc(sizeof(*opts
));
4835 memset(valid_opts
, 0, sizeof(*opts
));
4836 memcpy(valid_opts
, opts
, size
);
4840 case MIGRATE_PRE_DUMP
:
4841 if (!do_lxcapi_is_running(c
)) {
4842 ERROR("container is not running");
4846 ret
= !__criu_pre_dump(c
, valid_opts
);
4849 if (!do_lxcapi_is_running(c
)) {
4850 ERROR("container is not running");
4854 ret
= !__criu_dump(c
, valid_opts
);
4856 case MIGRATE_RESTORE
:
4857 if (do_lxcapi_is_running(c
)) {
4858 ERROR("container is already running");
4862 ret
= !__criu_restore(c
, valid_opts
);
4864 case MIGRATE_FEATURE_CHECK
:
4865 features_to_check
= valid_opts
->features_to_check
;
4866 ret
= !__criu_check_feature(&features_to_check
);
4868 /* Something went wrong. Let's let the caller
4869 * know which feature checks failed. */
4870 valid_opts
->features_to_check
= features_to_check
;
4874 ERROR("invalid migrate command %u", cmd
);
4879 if (size
< sizeof(*opts
))
4885 WRAP_API_3(int, lxcapi_migrate
, unsigned int, struct migrate_opts
*, unsigned int)
4887 static bool do_lxcapi_checkpoint(struct lxc_container
*c
, char *directory
, bool stop
, bool verbose
)
4889 struct migrate_opts opts
;
4891 memset(&opts
, 0, sizeof(opts
));
4893 opts
.directory
= directory
;
4895 opts
.verbose
= verbose
;
4897 return !do_lxcapi_migrate(c
, MIGRATE_DUMP
, &opts
, sizeof(opts
));
4900 WRAP_API_3(bool, lxcapi_checkpoint
, char *, bool, bool)
4902 static bool do_lxcapi_restore(struct lxc_container
*c
, char *directory
, bool verbose
)
4904 struct migrate_opts opts
;
4906 memset(&opts
, 0, sizeof(opts
));
4908 opts
.directory
= directory
;
4909 opts
.verbose
= verbose
;
4911 return !do_lxcapi_migrate(c
, MIGRATE_RESTORE
, &opts
, sizeof(opts
));
4914 WRAP_API_2(bool, lxcapi_restore
, char *, bool)
4916 /* @st_mode is the st_mode field of the stat(source) return struct */
4917 static int create_mount_target(const char *dest
, mode_t st_mode
)
4919 char *dirdup
, *destdirname
;
4922 dirdup
= strdup(dest
);
4924 SYSERROR("Failed to duplicate target name \"%s\"", dest
);
4927 destdirname
= dirname(dirdup
);
4929 ret
= mkdir_p(destdirname
, 0755);
4931 SYSERROR("Failed to create \"%s\"", destdirname
);
4939 if (S_ISDIR(st_mode
))
4940 ret
= mkdir(dest
, 0000);
4942 ret
= mknod(dest
, S_IFREG
| 0000, 0);
4944 SYSERROR("Failed to create mount target \"%s\"", dest
);
4951 static int do_lxcapi_mount(struct lxc_container
*c
, const char *source
,
4952 const char *target
, const char *filesystemtype
,
4953 unsigned long mountflags
, const void *data
,
4954 struct lxc_mount
*mnt
)
4957 char template[MAXPATHLEN
], path
[MAXPATHLEN
];
4958 pid_t pid
, init_pid
;
4960 int ret
= -1, fd
= -EBADF
;
4962 if (!c
|| !c
->lxc_conf
) {
4963 ERROR("Container or configuration is NULL");
4967 if (!c
->lxc_conf
->shmount
.path_host
) {
4968 ERROR("Host path to shared mountpoint must be specified in the config\n");
4972 ret
= snprintf(template, sizeof(template), "%s/.lxcmount_XXXXXX", c
->lxc_conf
->shmount
.path_host
);
4973 if (ret
< 0 || (size_t)ret
>= sizeof(template)) {
4974 SYSERROR("Error writing shmounts tempdir name");
4978 /* Create a temporary file / dir under the shared mountpoint */
4979 if (!source
|| strcmp(source
, "") == 0) {
4980 /* If source is not specified, maybe we want to mount a filesystem? */
4981 sb
.st_mode
= S_IFDIR
;
4983 ret
= stat(source
, &sb
);
4985 SYSERROR("Error getting stat info about the source \"%s\"", source
);
4990 if (S_ISDIR(sb
.st_mode
)) {
4991 sret
= mkdtemp(template);
4993 SYSERROR("Could not create shmounts temporary dir");
4997 fd
= lxc_make_tmpfile(template, false);
4999 SYSERROR("Could not create shmounts temporary file");
5007 SYSERROR("Could not fork");
5013 ret
= mount(source
, template, filesystemtype
, mountflags
, data
);
5015 SYSERROR("Failed to mount onto \"%s\"", template);
5016 _exit(EXIT_FAILURE
);
5018 TRACE("Mounted \"%s\" onto \"%s\"", source
, template);
5020 init_pid
= do_lxcapi_init_pid(c
);
5022 ERROR("Failed to obtain container's init pid");
5023 _exit(EXIT_FAILURE
);
5026 /* Enter the container namespaces */
5027 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5028 if (!switch_to_ns(init_pid
, "user")){
5029 ERROR("Failed to enter user namespace");
5030 _exit(EXIT_FAILURE
);
5034 if (!switch_to_ns(init_pid
, "mnt")) {
5035 ERROR("Failed to enter mount namespace");
5036 _exit(EXIT_FAILURE
);
5039 ret
= create_mount_target(target
, sb
.st_mode
);
5041 _exit(EXIT_FAILURE
);
5042 TRACE("Created mount target \"%s\"", target
);
5044 suff
= strrchr(template, '/');
5046 _exit(EXIT_FAILURE
);
5048 ret
= snprintf(path
, sizeof(path
), "%s%s", c
->lxc_conf
->shmount
.path_cont
, suff
);
5049 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
5050 SYSERROR("Error writing container mountpoint name");
5051 _exit(EXIT_FAILURE
);
5054 ret
= mount(path
, target
, NULL
, MS_MOVE
| MS_REC
, NULL
);
5056 SYSERROR("Failed to move the mount from \"%s\" to \"%s\"", path
, target
);
5057 _exit(EXIT_FAILURE
);
5059 TRACE("Moved mount from \"%s\" to \"%s\"", path
, target
);
5061 _exit(EXIT_SUCCESS
);
5064 ret
= wait_for_pid(pid
);
5066 SYSERROR("Wait for the child with pid %ld failed", (long) pid
);
5072 (void)umount2(template, MNT_DETACH
);
5073 (void)unlink(template);
5082 WRAP_API_6(int, lxcapi_mount
, const char *, const char *, const char *,
5083 unsigned long, const void *, struct lxc_mount
*)
5085 static int do_lxcapi_umount(struct lxc_container
*c
, const char *target
,
5086 unsigned long flags
, struct lxc_mount
*mnt
)
5088 pid_t pid
, init_pid
;
5091 if (!c
|| !c
->lxc_conf
) {
5092 ERROR("Container or configuration is NULL");
5099 SYSERROR("Could not fork");
5104 init_pid
= do_lxcapi_init_pid(c
);
5106 ERROR("Failed to obtain container's init pid");
5107 _exit(EXIT_FAILURE
);
5110 /* Enter the container namespaces */
5111 if (!lxc_list_empty(&c
->lxc_conf
->id_map
)) {
5112 if (!switch_to_ns(init_pid
, "user")) {
5113 ERROR("Failed to enter user namespace");
5114 _exit(EXIT_FAILURE
);
5118 if (!switch_to_ns(init_pid
, "mnt")) {
5119 ERROR("Failed to enter mount namespace");
5120 _exit(EXIT_FAILURE
);
5123 /* Do the unmount */
5124 ret
= umount2(target
, flags
);
5126 SYSERROR("Failed to umount \"%s\"", target
);
5127 _exit(EXIT_FAILURE
);
5130 _exit(EXIT_SUCCESS
);
5133 ret
= wait_for_pid(pid
);
5135 SYSERROR("Wait for the child with pid %ld failed", (long)pid
);
5142 WRAP_API_3(int, lxcapi_umount
, const char *, unsigned long, struct lxc_mount
*)
5144 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
5153 current_config
= c
->lxc_conf
;
5156 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
5160 ERROR("Memory allocation error.");
5166 ret
= do_lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
5170 current_config
= NULL
;
5174 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
5176 struct lxc_container
*c
;
5182 c
= malloc(sizeof(*c
));
5184 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5187 memset(c
, 0, sizeof(*c
));
5190 c
->config_path
= strdup(configpath
);
5192 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
5193 if (!c
->config_path
) {
5194 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5198 remove_trailing_slashes(c
->config_path
);
5201 c
->name
= malloc(len
+ 1);
5203 fprintf(stderr
, "Failed to allocate memory for %s\n", name
);
5206 (void)strlcpy(c
->name
, name
, len
+ 1);
5209 c
->slock
= lxc_newlock(c
->config_path
, name
);
5211 fprintf(stderr
, "Failed to create lock for %s\n", name
);
5215 c
->privlock
= lxc_newlock(NULL
, NULL
);
5217 fprintf(stderr
, "Failed to create private lock for %s\n", name
);
5221 if (!set_config_filename(c
)) {
5222 fprintf(stderr
, "Failed to create config file name for %s\n", name
);
5226 if (file_exists(c
->configfile
) && !lxcapi_load_config(c
, NULL
)) {
5227 fprintf(stderr
, "Failed to load config for %s\n", name
);
5231 if (ongoing_create(c
) == 2) {
5232 ERROR("Failed to complete container creation for %s", c
->name
);
5233 container_destroy(c
, NULL
);
5234 lxcapi_clear_config(c
);
5237 c
->daemonize
= true;
5240 /* Assign the member functions. */
5241 c
->is_defined
= lxcapi_is_defined
;
5242 c
->state
= lxcapi_state
;
5243 c
->is_running
= lxcapi_is_running
;
5244 c
->freeze
= lxcapi_freeze
;
5245 c
->unfreeze
= lxcapi_unfreeze
;
5246 c
->console
= lxcapi_console
;
5247 c
->console_getfd
= lxcapi_console_getfd
;
5248 c
->init_pid
= lxcapi_init_pid
;
5249 c
->load_config
= lxcapi_load_config
;
5250 c
->want_daemonize
= lxcapi_want_daemonize
;
5251 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
5252 c
->start
= lxcapi_start
;
5253 c
->startl
= lxcapi_startl
;
5254 c
->stop
= lxcapi_stop
;
5255 c
->config_file_name
= lxcapi_config_file_name
;
5256 c
->wait
= lxcapi_wait
;
5257 c
->set_config_item
= lxcapi_set_config_item
;
5258 c
->destroy
= lxcapi_destroy
;
5259 c
->destroy_with_snapshots
= lxcapi_destroy_with_snapshots
;
5260 c
->rename
= lxcapi_rename
;
5261 c
->save_config
= lxcapi_save_config
;
5262 c
->get_keys
= lxcapi_get_keys
;
5263 c
->create
= lxcapi_create
;
5264 c
->createl
= lxcapi_createl
;
5265 c
->shutdown
= lxcapi_shutdown
;
5266 c
->reboot
= lxcapi_reboot
;
5267 c
->reboot2
= lxcapi_reboot2
;
5268 c
->clear_config
= lxcapi_clear_config
;
5269 c
->clear_config_item
= lxcapi_clear_config_item
;
5270 c
->get_config_item
= lxcapi_get_config_item
;
5271 c
->get_running_config_item
= lxcapi_get_running_config_item
;
5272 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
5273 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
5274 c
->get_config_path
= lxcapi_get_config_path
;
5275 c
->set_config_path
= lxcapi_set_config_path
;
5276 c
->clone
= lxcapi_clone
;
5277 c
->get_interfaces
= lxcapi_get_interfaces
;
5278 c
->get_ips
= lxcapi_get_ips
;
5279 c
->attach
= lxcapi_attach
;
5280 c
->attach_run_wait
= lxcapi_attach_run_wait
;
5281 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
5282 c
->snapshot
= lxcapi_snapshot
;
5283 c
->snapshot_list
= lxcapi_snapshot_list
;
5284 c
->snapshot_restore
= lxcapi_snapshot_restore
;
5285 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
5286 c
->snapshot_destroy_all
= lxcapi_snapshot_destroy_all
;
5287 c
->may_control
= lxcapi_may_control
;
5288 c
->add_device_node
= lxcapi_add_device_node
;
5289 c
->remove_device_node
= lxcapi_remove_device_node
;
5290 c
->attach_interface
= lxcapi_attach_interface
;
5291 c
->detach_interface
= lxcapi_detach_interface
;
5292 c
->checkpoint
= lxcapi_checkpoint
;
5293 c
->restore
= lxcapi_restore
;
5294 c
->migrate
= lxcapi_migrate
;
5295 c
->console_log
= lxcapi_console_log
;
5296 c
->mount
= lxcapi_mount
;
5297 c
->umount
= lxcapi_umount
;
5302 lxc_container_free(c
);
5306 int lxc_get_wait_states(const char **states
)
5311 for (i
=0; i
<MAX_STATE
; i
++)
5312 states
[i
] = lxc_state2str(i
);
5318 * These next two could probably be done smarter with reusing a common function
5319 * with different iterators and tests...
5321 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
5324 int i
, cfound
= 0, nfound
= 0;
5325 struct dirent
*direntp
;
5326 struct lxc_container
*c
;
5329 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5331 dir
= opendir(lxcpath
);
5333 SYSERROR("opendir on lxcpath");
5343 while ((direntp
= readdir(dir
))) {
5344 /* Ignore '.', '..' and any hidden directory. */
5345 if (!strncmp(direntp
->d_name
, ".", 1))
5348 if (!config_file_exists(lxcpath
, direntp
->d_name
))
5352 if (!add_to_array(names
, direntp
->d_name
, cfound
))
5362 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
5364 INFO("Container %s:%s has a config but could not be loaded",
5365 lxcpath
, direntp
->d_name
);
5368 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5374 if (!do_lxcapi_is_defined(c
)) {
5375 INFO("Container %s:%s has a config but is not defined",
5376 lxcpath
, direntp
->d_name
);
5379 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
5382 lxc_container_put(c
);
5386 if (!add_to_clist(cret
, c
, nfound
, true)) {
5387 lxc_container_put(c
);
5398 if (names
&& *names
) {
5399 for (i
=0; i
<cfound
; i
++)
5404 if (cret
&& *cret
) {
5405 for (i
=0; i
<nfound
; i
++)
5406 lxc_container_put((*cret
)[i
]);
5414 int list_active_containers(const char *lxcpath
, char ***nret
,
5415 struct lxc_container
***cret
)
5417 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
5420 char **ct_name
= NULL
;
5422 struct lxc_container
*c
= NULL
;
5426 lxcpath
= lxc_global_config_value("lxc.lxcpath");
5427 lxcpath_len
= strlen(lxcpath
);
5435 FILE *f
= fopen("/proc/net/unix", "r");
5439 while (getline(&line
, &len
, f
) != -1) {
5440 char *p
= strrchr(line
, ' '), *p2
;
5451 if (strncmp(p
, lxcpath
, lxcpath_len
) == 0) {
5453 } else if (strncmp(p
, "lxc/", 4) == 0) {
5463 /* Now p is the start of lxc_name. */
5464 p2
= strchr(p
, '/');
5465 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
5470 char *recvpath
= lxc_cmd_get_lxcpath(p
);
5474 if (strncmp(lxcpath
, recvpath
, lxcpath_len
) != 0) {
5480 p
= lxc_cmd_get_name(p
);
5485 if (array_contains(&ct_name
, p
, ct_name_cnt
)) {
5491 if (!add_to_array(&ct_name
, p
, ct_name_cnt
)) {
5494 goto free_cret_list
;
5505 c
= lxc_container_new(p
, lxcpath
);
5507 INFO("Container %s:%s is running but could not be loaded",
5510 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
5521 * If this is an anonymous container, then is_defined *can*
5522 * return false. So we don't do that check. Count on the
5523 * fact that the command socket exists.
5526 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
5527 lxc_container_put(c
);
5528 goto free_cret_list
;
5534 if (nret
&& cret
&& cret_cnt
!= ct_name_cnt
) {
5536 lxc_container_put(c
);
5537 goto free_cret_list
;
5549 if (cret
&& *cret
) {
5550 for (i
= 0; i
< cret_cnt
; i
++)
5551 lxc_container_put((*cret
)[i
]);
5557 for (i
= 0; i
< ct_name_cnt
; i
++)
5568 int list_all_containers(const char *lxcpath
, char ***nret
,
5569 struct lxc_container
***cret
)
5571 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
5574 struct lxc_container
**ct_list
= NULL
;
5576 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
5580 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
5581 if (active_cnt
< 0) {
5586 for (i
= 0; i
< active_cnt
; i
++) {
5587 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
5588 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
5590 goto free_active_name
;
5596 free(active_name
[i
]);
5597 active_name
[i
] = NULL
;
5604 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
5605 struct lxc_container
*c
;
5607 c
= lxc_container_new(ct_name
[i
], lxcpath
);
5609 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
5610 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
5614 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
5615 lxc_container_put(c
);
5636 for (i
= 0; i
< ct_list_cnt
; i
++) {
5637 lxc_container_put(ct_list
[i
]);
5642 for (i
= 0; i
< active_cnt
; i
++) {
5643 free(active_name
[i
]);
5648 for (i
= 0; i
< ct_cnt
; i
++) {
5655 bool lxc_config_item_is_supported(const char *key
)
5657 return !!lxc_get_config(key
);