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
26 #include <sys/types.h>
28 #include <sys/mount.h>
34 #include <arpa/inet.h>
38 #include <lxc/lxccontainer.h>
39 #include <lxc/version.h>
55 #include "namespace.h"
61 #include <../include/ifaddrs.h>
66 #include <../include/getline.h>
70 #define MAX_BUFFER 4096
72 lxc_log_define(lxc_container
, lxc
);
74 static bool file_exists(const char *f
)
78 return stat(f
, &statbuf
) == 0;
81 static bool config_file_exists(const char *lxcpath
, const char *cname
)
83 /* $lxcpath + '/' + $cname + '/config' + \0 */
84 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
85 char *fname
= alloca(len
);
87 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
88 if (ret
< 0 || ret
>= len
)
91 return file_exists(fname
);
95 * A few functions to help detect when a container creation failed.
96 * If a container creation was killed partway through, then trying
97 * to actually start that container could harm the host. We detect
98 * this by creating a 'partial' file under the container directory,
99 * and keeping an advisory lock. When container creation completes,
100 * we remove that file. When we load or try to start a container, if
101 * we find that file, without a flock, we remove the container.
103 static int ongoing_create(struct lxc_container
*c
)
105 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
106 char *path
= alloca(len
);
110 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
111 if (ret
< 0 || ret
>= len
) {
112 ERROR("Error writing partial pathname");
116 if (!file_exists(path
))
118 fd
= open(path
, O_RDWR
);
120 // give benefit of the doubt
121 SYSERROR("Error opening partial file");
125 lk
.l_whence
= SEEK_SET
;
129 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
130 // create is still ongoing
134 // create completed but partial is still there.
139 static int create_partial(struct lxc_container
*c
)
141 // $lxcpath + '/' + $name + '/partial' + \0
142 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
143 char *path
= alloca(len
);
147 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
148 if (ret
< 0 || ret
>= len
) {
149 ERROR("Error writing partial pathname");
152 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
153 SYSERROR("Erorr creating partial file");
157 lk
.l_whence
= SEEK_SET
;
160 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
161 SYSERROR("Error locking partial file %s", path
);
169 static void remove_partial(struct lxc_container
*c
, int fd
)
171 // $lxcpath + '/' + $name + '/partial' + \0
172 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
173 char *path
= alloca(len
);
177 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
178 if (ret
< 0 || ret
>= len
) {
179 ERROR("Error writing partial pathname");
182 if (unlink(path
) < 0)
183 SYSERROR("Error unlink partial file %s", path
);
187 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
188 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
189 * container configuration file.
190 * The container_disk_lock also takes the container_mem_lock.
191 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
192 * NOTHING mutexes two independent programs with their own struct
193 * lxc_container for the same c->name, between API calls. For instance,
194 * c->config_read(); c->start(); Between those calls, data on disk
195 * could change (which shouldn't bother the caller unless for instance
196 * the rootfs get moved). c->config_read(); update; c->config_write();
197 * Two such updaters could race. The callers should therefore check their
198 * results. Trying to prevent that would necessarily expose us to deadlocks
199 * due to hung callers. So I prefer to keep the locks only within our own
200 * functions, not across functions.
202 * If you're going to clone while holding a lxccontainer, increment
203 * c->numthreads (under privlock) before forking. When deleting,
204 * decrement numthreads under privlock, then if it hits 0 you can delete.
205 * Do not ever use a lxccontainer whose numthreads you did not bump.
208 static void lxc_container_free(struct lxc_container
*c
)
215 c
->configfile
= NULL
;
217 if (c
->error_string
) {
218 free(c
->error_string
);
219 c
->error_string
= NULL
;
222 lxc_putlock(c
->slock
);
226 lxc_putlock(c
->privlock
);
234 lxc_conf_free(c
->lxc_conf
);
237 if (c
->config_path
) {
238 free(c
->config_path
);
239 c
->config_path
= NULL
;
245 * Consider the following case:
246 freer | racing get()er
247 ==================================================================
248 lxc_container_put() | lxc_container_get()
249 \ lxclock(c->privlock) | c->numthreads < 1? (no)
250 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
252 \ lxc_container_free() | \ lxclock() returns
253 | \ c->numthreads < 1 -> return 0
255 \ \ sem_destroy(privlock) |
257 * When the get()er checks numthreads the first time, one of the following
259 * 1. freer has set numthreads = 0. get() returns 0
260 * 2. freer is between lxclock and setting numthreads to 0. get()er will
261 * sem_wait on privlock, get lxclock after freer() drops it, then see
262 * numthreads is 0 and exit without touching lxclock again..
263 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
264 * will see --numthreads = 1 and not call lxc_container_free().
267 int lxc_container_get(struct lxc_container
*c
)
272 // if someone else has already started freeing the container, don't
273 // try to take the lock, which may be invalid
274 if (c
->numthreads
< 1)
277 if (container_mem_lock(c
))
279 if (c
->numthreads
< 1) {
280 // bail without trying to unlock, bc the privlock is now probably
285 container_mem_unlock(c
);
289 int lxc_container_put(struct lxc_container
*c
)
293 if (container_mem_lock(c
))
295 if (--c
->numthreads
< 1) {
296 container_mem_unlock(c
);
297 lxc_container_free(c
);
300 container_mem_unlock(c
);
304 static bool lxcapi_is_defined(struct lxc_container
*c
)
313 if (container_mem_lock(c
))
317 statret
= stat(c
->configfile
, &statbuf
);
323 container_mem_unlock(c
);
327 static const char *lxcapi_state(struct lxc_container
*c
)
333 s
= lxc_getstate(c
->name
, c
->config_path
);
334 return lxc_state2str(s
);
337 static bool is_stopped(struct lxc_container
*c
)
340 s
= lxc_getstate(c
->name
, c
->config_path
);
341 return (s
== STOPPED
);
344 static bool lxcapi_is_running(struct lxc_container
*c
)
351 if (!s
|| strcmp(s
, "STOPPED") == 0)
356 static bool lxcapi_freeze(struct lxc_container
*c
)
362 ret
= lxc_freeze(c
->name
, c
->config_path
);
368 static bool lxcapi_unfreeze(struct lxc_container
*c
)
374 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
380 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
386 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
390 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
391 int stdoutfd
, int stderrfd
, int escape
)
393 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
396 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
401 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
404 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
407 c
->lxc_conf
= lxc_conf_init();
408 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
413 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
415 bool ret
= false, need_disklock
= false;
421 fname
= c
->configfile
;
427 * If we're reading something other than the container's config,
428 * we only need to lock the in-memory container. If loading the
429 * container's config file, take the disk lock.
431 if (strcmp(fname
, c
->configfile
) == 0)
432 need_disklock
= true;
435 lret
= container_disk_lock(c
);
437 lret
= container_mem_lock(c
);
441 ret
= load_config_locked(c
, fname
);
444 container_disk_unlock(c
);
446 container_mem_unlock(c
);
450 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
452 if (!c
|| !c
->lxc_conf
)
454 if (container_mem_lock(c
)) {
455 ERROR("Error getting mem lock");
458 c
->daemonize
= state
;
459 /* daemonize implies close_all_fds so set it */
461 c
->lxc_conf
->close_all_fds
= 1;
462 container_mem_unlock(c
);
466 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
468 if (!c
|| !c
->lxc_conf
)
470 if (container_mem_lock(c
)) {
471 ERROR("Error getting mem lock");
474 c
->lxc_conf
->close_all_fds
= state
;
475 container_mem_unlock(c
);
479 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
486 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
491 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
493 /* we'll probably want to make this timeout configurable? */
494 int timeout
= 5, ret
, status
;
497 * our child is going to fork again, then exit. reap the
500 ret
= waitpid(pid
, &status
, 0);
501 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
502 DEBUG("failed waiting for first dual-fork child");
503 return lxcapi_wait(c
, "RUNNING", timeout
);
506 static bool am_single_threaded(void)
508 struct dirent dirent
, *direntp
;
512 dir
= opendir("/proc/self/task");
514 INFO("failed to open /proc/self/task");
518 while (!readdir_r(dir
, &dirent
, &direntp
)) {
522 if (!strcmp(direntp
->d_name
, "."))
525 if (!strcmp(direntp
->d_name
, ".."))
535 * I can't decide if it'd be more convenient for callers if we accept '...',
536 * or a null-terminated array (i.e. execl vs execv)
538 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
541 struct lxc_conf
*conf
;
542 bool daemonize
= false;
543 char *default_args
[] = {
548 /* container exists */
551 /* container has been setup */
555 if ((ret
= ongoing_create(c
)) < 0) {
556 ERROR("Error checking for incomplete creation");
560 ERROR("Error: %s creation was not completed", c
->name
);
563 } else if (ret
== 1) {
564 ERROR("Error: creation of %s is ongoing", c
->name
);
568 /* is this app meant to be run through lxcinit, as in lxc-execute? */
569 if (useinit
&& !argv
)
572 if (container_mem_lock(c
))
575 daemonize
= c
->daemonize
;
576 container_mem_unlock(c
);
579 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
580 return ret
== 0 ? true : false;
587 * say, I'm not sure - what locks do we want here? Any?
588 * Is liblxc's locking enough here to protect the on disk
589 * container? We don't want to exclude things like lxc_info
590 * while container is running...
593 if (!lxc_container_get(c
))
595 lxc_monitord_spawn(c
->config_path
);
599 lxc_container_put(c
);
603 return wait_on_daemonized_start(c
, pid
);
605 /* second fork to be reparented by init */
608 SYSERROR("Error doing dual-fork");
613 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
615 SYSERROR("Error chdir()ing to /.");
621 open("/dev/zero", O_RDONLY
);
622 open("/dev/null", O_RDWR
);
623 open("/dev/null", O_RDWR
);
626 if (!am_single_threaded()) {
627 ERROR("Cannot start non-daemonized container when threaded");
634 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
637 INFO("container requested reboot");
643 lxc_container_put(c
);
644 exit (ret
== 0 ? true : false);
646 return (ret
== 0 ? true : false);
651 * note there MUST be an ending NULL
653 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
656 char **inargs
= NULL
;
659 /* container exists */
663 va_start(ap
, useinit
);
664 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
668 ERROR("Memory allocation error.");
672 /* pass NULL if no arguments were supplied */
673 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
678 for (arg
= inargs
; *arg
; arg
++)
686 static bool lxcapi_stop(struct lxc_container
*c
)
693 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
699 * create the standard expected container dir
701 static bool create_container_dir(struct lxc_container
*c
)
706 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
710 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
711 if (ret
< 0 || ret
>= len
) {
715 ret
= mkdir(s
, 0755);
720 SYSERROR("failed to create container path for %s\n", c
->name
);
726 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
727 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
730 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
731 * it returns a mounted bdev on success, NULL on error.
733 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
734 struct bdev_specs
*specs
)
741 /* rootfs.path or lxcpath/lxcname/rootfs */
742 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
743 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
744 len
= strlen(rpath
) + 1;
746 ret
= snprintf(dest
, len
, "%s", rpath
);
748 const char *lxcpath
= lxcapi_get_config_path(c
);
749 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
751 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
753 if (ret
< 0 || ret
>= len
)
756 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
758 ERROR("Failed to create backing store type %s\n", type
);
762 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
764 /* if we are not root, chown the rootfs dir to root in the
767 if (geteuid() != 0) {
768 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
769 ERROR("Error chowning %s to container root\n", bdev
->dest
);
779 * Given the '-t' template option to lxc-create, figure out what to
780 * do. If the template is a full executable path, use that. If it
781 * is something like 'sshd', then return $templatepath/lxc-sshd.
782 * On success return the template, on error return NULL.
784 static char *get_template_path(const char *t
)
789 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
794 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
798 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
799 if (ret
< 0 || ret
>= len
) {
803 if (access(tpath
, X_OK
) < 0) {
804 SYSERROR("bad template: %s\n", t
);
812 static char *lxcbasename(char *path
)
814 char *p
= path
+ strlen(path
) - 1;
815 while (*p
!= '/' && p
> path
)
820 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
830 SYSERROR("failed to fork task for container creation template\n");
834 if (pid
== 0) { // child
835 char *patharg
, *namearg
, *rootfsarg
, *src
;
836 struct bdev
*bdev
= NULL
;
838 int ret
, len
, nargs
= 0;
840 struct lxc_conf
*conf
= c
->lxc_conf
;
846 open("/dev/zero", O_RDONLY
);
847 open("/dev/null", O_RDWR
);
848 open("/dev/null", O_RDWR
);
851 src
= c
->lxc_conf
->rootfs
.path
;
853 * for an overlayfs create, what the user wants is the template to fill
854 * in what will become the readonly lower layer. So don't mount for
857 if (strncmp(src
, "overlayfs:", 10) == 0) {
858 src
= overlayfs_getlower(src
+10);
860 bdev
= bdev_init(src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
862 ERROR("Error opening rootfs");
866 if (geteuid() == 0) {
867 if (unshare(CLONE_NEWNS
) < 0) {
868 ERROR("error unsharing mounts");
871 if (detect_shared_rootfs()) {
872 if (mount("", "", NULL
, MS_SLAVE
|MS_REC
, 0)) {
873 SYSERROR("Failed to make / rslave to run template");
874 ERROR("Continuing...");
878 if (strcmp(bdev
->type
, "dir") != 0) {
879 if (geteuid() != 0) {
880 ERROR("non-root users can only create directory-backed containers");
883 if (bdev
->ops
->mount(bdev
) < 0) {
884 ERROR("Error mounting rootfs");
887 } else { // TODO come up with a better way here!
890 bdev
->dest
= strdup(bdev
->src
);
894 * create our new array, pre-pend the template name and
898 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
899 nargs
+= 4; // template, path, rootfs and name args
901 newargv
= malloc(nargs
* sizeof(*newargv
));
904 newargv
[0] = lxcbasename(tpath
);
906 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
907 patharg
= malloc(len
);
910 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
911 if (ret
< 0 || ret
>= len
)
913 newargv
[1] = patharg
;
914 len
= strlen("--name=") + strlen(c
->name
) + 1;
915 namearg
= malloc(len
);
918 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
919 if (ret
< 0 || ret
>= len
)
921 newargv
[2] = namearg
;
923 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
924 rootfsarg
= malloc(len
);
927 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
928 if (ret
< 0 || ret
>= len
)
930 newargv
[3] = rootfsarg
;
932 /* add passed-in args */
934 for (i
= 4; i
< nargs
; i
++)
935 newargv
[i
] = argv
[i
-4];
937 /* add trailing NULL */
939 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
942 newargv
[nargs
- 1] = NULL
;
945 * If we're running the template in a mapped userns, then
946 * we prepend the template command with:
947 * lxc-usernsexec <-m map1> ... <-m mapn> --
948 * and we append "--mapped-uid x", where x is the mapped uid
951 if (geteuid() != 0 && !lxc_list_empty(&conf
->id_map
)) {
954 char **n2
= malloc(n2args
* sizeof(*n2
));
959 SYSERROR("out of memory");
963 tpath
= "lxc-usernsexec";
964 n2
[0] = "lxc-usernsexec";
965 lxc_list_for_each(it
, &conf
->id_map
) {
968 n2
= realloc(n2
, n2args
* sizeof(char *));
972 n2
[n2args
-1] = malloc(200);
975 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
976 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
977 map
->nsid
, map
->hostid
, map
->range
);
978 if (ret
< 0 || ret
>= 200)
981 int hostid_mapped
= mapped_hostid(geteuid(), conf
);
982 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
983 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
986 if (hostid_mapped
< 0) {
987 hostid_mapped
= find_unmapped_nsuid(conf
);
989 if (hostid_mapped
< 0) {
990 ERROR("Could not find free uid to map");
993 n2
[n2args
++] = malloc(200);
995 SYSERROR("out of memory");
998 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
999 hostid_mapped
, geteuid());
1000 if (ret
< 0 || ret
>= 200) {
1001 ERROR("string too long");
1005 n2
[n2args
++] = "--";
1006 for (i
= 0; i
< nargs
; i
++)
1007 n2
[i
+ n2args
] = newargv
[i
];
1009 // Finally add "--mapped-uid $uid" to tell template what to chown
1012 n2
= realloc(n2
, n2args
* sizeof(char *));
1014 SYSERROR("out of memory");
1017 // note n2[n2args-1] is NULL
1018 n2
[n2args
-3] = "--mapped-uid";
1019 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1020 n2
[n2args
-2] = txtuid
;
1021 n2
[n2args
-1] = NULL
;
1026 execvp(tpath
, newargv
);
1027 SYSERROR("failed to execute template %s", tpath
);
1031 if (wait_for_pid(pid
) != 0) {
1032 ERROR("container creation template for %s failed\n", c
->name
);
1039 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1047 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1051 f
= fopen(path
, "r");
1055 if (fseek(f
, 0, SEEK_END
) < 0)
1057 if ((flen
= ftell(f
)) < 0)
1059 if (fseek(f
, 0, SEEK_SET
) < 0)
1061 if ((contents
= malloc(flen
+ 1)) == NULL
)
1063 if (fread(contents
, 1, flen
, f
) != flen
)
1064 goto out_free_contents
;
1066 contents
[flen
] = '\0';
1070 goto out_free_contents
;
1073 tpath
= get_template_path(t
);
1075 ERROR("bad template: %s\n", t
);
1076 goto out_free_contents
;
1079 ret
= sha1sum_file(tpath
, md_value
);
1081 ERROR("Error getting sha1sum of %s", tpath
);
1083 goto out_free_contents
;
1088 f
= fopen(path
, "w");
1090 SYSERROR("reopening config for writing");
1094 fprintf(f
, "# Template used to create this container: %s\n", t
);
1096 fprintf(f
, "# Parameters passed to the template:");
1098 fprintf(f
, " %s", *argv
);
1104 fprintf(f
, "# Template script checksum (SHA-1): ");
1105 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1106 fprintf(f
, "%02x", md_value
[i
]);
1109 fprintf(f
, "# For additional config options, please look at lxc.conf(5)\n");
1110 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1111 SYSERROR("Writing original contents");
1127 SYSERROR("Error prepending header");
1133 static void lxcapi_clear_config(struct lxc_container
*c
)
1135 if (c
&& c
->lxc_conf
) {
1136 lxc_conf_free(c
->lxc_conf
);
1141 static bool lxcapi_destroy(struct lxc_container
*c
);
1144 * create a container with the given parameters.
1145 * @c: container to be created. It has the lxcpath, name, and a starting
1146 * configuration already set
1147 * @t: the template to execute to instantiate the root filesystem and
1148 * adjust the configuration.
1149 * @bdevtype: backing store type to use. If NULL, dir will be used.
1150 * @specs: additional parameters for the backing store, i.e. LVM vg to
1153 * @argv: the arguments to pass to the template, terminated by NULL. If no
1154 * arguments, you can just pass NULL.
1156 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1157 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1169 tpath
= get_template_path(t
);
1171 ERROR("bad template: %s\n", t
);
1177 * If a template is passed in, and the rootfs already is defined in
1178 * the container config and exists, then * caller is trying to create
1179 * an existing container. Return an error, but do NOT delete the
1182 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1183 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1184 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1189 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1190 ERROR("Error loading default configuration file %s\n", lxc_global_config_value("lxc.default_config"));
1195 if (!create_container_dir(c
))
1199 * either template or rootfs.path should be set.
1200 * if both template and rootfs.path are set, template is setup as rootfs.path.
1201 * container is already created if we have a config and rootfs.path is accessible
1203 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1204 /* no template passed in and rootfs does not exist: error */
1206 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1207 /* rootfs passed into configuration, but does not exist: error */
1209 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1210 /* Rootfs already existed, user just wanted to save the
1211 * loaded configuration */
1216 /* Mark that this container is being created */
1217 if ((partial_fd
= create_partial(c
)) < 0)
1220 /* no need to get disk lock bc we have the partial locked */
1223 * Create the backing store
1224 * Note we can't do this in the same task as we use to execute the
1225 * template because of the way zfs works.
1226 * After you 'zfs create', zfs mounts the fs only in the initial
1231 SYSERROR("failed to fork task for container creation template\n");
1235 if (pid
== 0) { // child
1236 struct bdev
*bdev
= NULL
;
1238 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1239 ERROR("Error creating backing store type %s for %s",
1240 bdevtype
? bdevtype
: "(none)", c
->name
);
1244 /* save config file again to store the new rootfs location */
1245 if (!c
->save_config(c
, NULL
)) {
1246 ERROR("failed to save starting configuration for %s\n", c
->name
);
1247 // parent task won't see bdev in config so we delete it
1248 bdev
->ops
->umount(bdev
);
1249 bdev
->ops
->destroy(bdev
);
1254 if (wait_for_pid(pid
) != 0)
1257 /* reload config to get the rootfs */
1258 lxc_conf_free(c
->lxc_conf
);
1260 if (!load_config_locked(c
, c
->configfile
))
1263 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1266 // now clear out the lxc_conf we have, reload from the created
1268 lxcapi_clear_config(c
);
1271 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1272 ERROR("Error prepending header to configuration file");
1276 ret
= load_config_locked(c
, c
->configfile
);
1279 if (partial_fd
>= 0)
1280 remove_partial(c
, partial_fd
);
1290 static bool lxcapi_reboot(struct lxc_container
*c
)
1296 if (!c
->is_running(c
))
1298 pid
= c
->init_pid(c
);
1301 if (kill(pid
, SIGINT
) < 0)
1307 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1311 int haltsignal
= SIGPWR
;
1318 if (!c
->is_running(c
))
1320 pid
= c
->init_pid(c
);
1323 if (c
->lxc_conf
->haltsignal
)
1324 haltsignal
= c
->lxc_conf
->haltsignal
;
1325 kill(pid
, haltsignal
);
1326 retv
= c
->wait(c
, "STOPPED", timeout
);
1327 if (!retv
&& timeout
> 0) {
1329 retv
= c
->wait(c
, "STOPPED", 0); // 0 means don't wait
1334 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1335 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1345 * since we're going to wait for create to finish, I don't think we
1346 * need to get a copy of the arguments.
1348 va_start(ap
, flags
);
1349 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1352 ERROR("Memory allocation error.");
1356 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1363 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1367 if (!c
|| !c
->lxc_conf
)
1369 if (container_mem_lock(c
))
1371 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1372 container_mem_unlock(c
);
1376 static inline void exit_from_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1377 /* Switch back to original netns */
1378 if (*old_netns
>= 0 && setns(*old_netns
, CLONE_NEWNET
))
1379 SYSERROR("failed to setns");
1380 if (*new_netns
>= 0)
1382 if (*old_netns
>= 0)
1386 static inline bool enter_to_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1388 char new_netns_path
[MAXPATHLEN
];
1390 if (!c
->is_running(c
))
1393 /* Save reference to old netns */
1394 *old_netns
= open("/proc/self/ns/net", O_RDONLY
);
1395 if (*old_netns
< 0) {
1396 SYSERROR("failed to open /proc/self/ns/net");
1400 /* Switch to new netns */
1401 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", c
->init_pid(c
));
1402 if (ret
< 0 || ret
>= MAXPATHLEN
)
1405 *new_netns
= open(new_netns_path
, O_RDONLY
);
1406 if (*new_netns
< 0) {
1407 SYSERROR("failed to open %s", new_netns_path
);
1411 if (setns(*new_netns
, CLONE_NEWNET
)) {
1412 SYSERROR("failed to setns");
1417 exit_from_ns(c
, old_netns
, new_netns
);
1421 // used by qsort and bsearch functions for comparing names
1422 static inline int string_cmp(char **first
, char **second
)
1424 return strcmp(*first
, *second
);
1427 // used by qsort and bsearch functions for comparing container names
1428 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1430 return strcmp((*first
)->name
, (*second
)->name
);
1433 static bool add_to_array(char ***names
, char *cname
, int pos
)
1435 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1437 ERROR("Out of memory");
1442 newnames
[pos
] = strdup(cname
);
1446 // sort the arrray as we will use binary search on it
1447 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1452 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1454 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1456 ERROR("Out of memory");
1463 // sort the arrray as we will use binary search on it
1465 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1470 static char** get_from_array(char ***names
, char *cname
, int size
)
1472 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1476 static bool array_contains(char ***names
, char *cname
, int size
) {
1477 if(get_from_array(names
, cname
, size
) != NULL
)
1482 static bool remove_from_array(char ***names
, char *cname
, int size
)
1484 char **result
= get_from_array(names
, cname
, size
);
1485 if (result
!= NULL
) {
1492 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1495 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1496 char **interfaces
= NULL
;
1497 int old_netns
= -1, new_netns
= -1;
1499 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1502 /* Grab the list of interfaces */
1503 if (getifaddrs(&interfaceArray
)) {
1504 SYSERROR("failed to get interfaces list");
1508 /* Iterate through the interfaces */
1509 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1510 if (array_contains(&interfaces
, tempIfAddr
->ifa_name
, count
))
1513 if(!add_to_array(&interfaces
, tempIfAddr
->ifa_name
, count
))
1520 freeifaddrs(interfaceArray
);
1522 exit_from_ns(c
, &old_netns
, &new_netns
);
1524 /* Append NULL to the array */
1526 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1531 for(i
=0;i
<count
;i
++)
1532 free(interfaces
[i
]);
1538 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1541 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1542 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1543 void *tempAddrPtr
= NULL
;
1544 char **addresses
= NULL
;
1545 char *address
= NULL
;
1546 int old_netns
= -1, new_netns
= -1;
1548 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1551 /* Grab the list of interfaces */
1552 if (getifaddrs(&interfaceArray
)) {
1553 SYSERROR("failed to get interfaces list");
1557 /* Iterate through the interfaces */
1558 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1559 if (tempIfAddr
->ifa_addr
== NULL
)
1562 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1563 if (family
&& strcmp(family
, "inet"))
1565 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1568 if (family
&& strcmp(family
, "inet6"))
1571 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1574 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1577 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1579 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1582 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1584 addressOutputBuffer
,
1585 sizeof(addressOutputBuffer
));
1589 if(!add_to_array(&addresses
, address
, count
))
1596 freeifaddrs(interfaceArray
);
1598 exit_from_ns(c
, &old_netns
, &new_netns
);
1600 /* Append NULL to the array */
1602 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1607 for(i
=0;i
<count
;i
++)
1615 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1619 if (!c
|| !c
->lxc_conf
)
1621 if (container_mem_lock(c
))
1623 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1624 container_mem_unlock(c
);
1628 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1631 return lxc_listconfigs(retv
, inlen
);
1633 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1634 * This is an intelligent result to show which keys are valid given
1635 * the type of nic it is
1637 if (!c
|| !c
->lxc_conf
)
1639 if (container_mem_lock(c
))
1642 if (strncmp(key
, "lxc.network.", 12) == 0)
1643 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1644 container_mem_unlock(c
);
1648 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1651 bool ret
= false, need_disklock
= false;
1655 alt_file
= c
->configfile
;
1657 return false; // should we write to stdout if no file is specified?
1659 // If we haven't yet loaded a config, load the stock config
1661 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1662 ERROR("Error loading default configuration file %s while saving %s\n", lxc_global_config_value("lxc.default_config"), c
->name
);
1667 if (!create_container_dir(c
))
1671 * If we're writing to the container's config file, take the
1672 * disk lock. Otherwise just take the memlock to protect the
1673 * struct lxc_container while we're traversing it.
1675 if (strcmp(c
->configfile
, alt_file
) == 0)
1676 need_disklock
= true;
1679 lret
= container_disk_lock(c
);
1681 lret
= container_mem_lock(c
);
1686 fout
= fopen(alt_file
, "w");
1689 write_config(fout
, c
->lxc_conf
);
1695 container_disk_unlock(c
);
1697 container_mem_unlock(c
);
1701 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1703 char path
[MAXPATHLEN
];
1708 if (container_disk_lock(c
))
1710 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1712 if (ret
< 0 || ret
> MAXPATHLEN
)
1714 f
= fopen(path
, "r");
1716 ret
= fscanf(f
, "%d", &v
);
1719 ERROR("Corrupted file %s", path
);
1724 f
= fopen(path
, "w");
1727 if (fprintf(f
, "%d\n", v
) < 0) {
1728 ERROR("Error writing new snapshots value");
1734 SYSERROR("Error writing to or closing snapshots file");
1741 container_disk_unlock(c
);
1745 static void strip_newline(char *p
)
1747 size_t len
= strlen(p
);
1750 if (p
[len
-1] == '\n')
1754 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1756 struct lxc_container
*p
;
1757 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1758 size_t pathlen
= 0, namelen
= 0;
1762 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1763 c
->config_path
, c
->name
);
1764 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1765 ERROR("Path name too long");
1768 f
= fopen(path
, "r");
1771 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1772 if (getline(&lxcname
, &namelen
, f
) == -1) {
1773 ERROR("badly formatted file %s\n", path
);
1776 strip_newline(lxcpath
);
1777 strip_newline(lxcname
);
1778 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1779 ERROR("Unable to find dependent container %s:%s",
1783 if (!mod_rdep(p
, inc
))
1784 ERROR("Failed to increase numsnapshots for %s:%s",
1786 lxc_container_put(p
);
1789 if (lxcpath
) free(lxcpath
);
1790 if (lxcname
) free(lxcname
);
1794 static bool has_snapshots(struct lxc_container
*c
)
1796 char path
[MAXPATHLEN
];
1801 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1803 if (ret
< 0 || ret
> MAXPATHLEN
)
1805 f
= fopen(path
, "r");
1808 ret
= fscanf(f
, "%d", &v
);
1818 static int lxc_rmdir_onedev_wrapper(void *data
)
1820 char *arg
= (char *) data
;
1821 return lxc_rmdir_onedev(arg
);
1824 // do we want the api to support --force, or leave that to the caller?
1825 static bool lxcapi_destroy(struct lxc_container
*c
)
1827 struct bdev
*r
= NULL
;
1828 bool bret
= false, am_unpriv
;
1831 if (!c
|| !lxcapi_is_defined(c
))
1834 if (container_disk_lock(c
))
1837 if (!is_stopped(c
)) {
1838 // we should queue some sort of error - in c->error_string?
1839 ERROR("container %s is not stopped", c
->name
);
1843 am_unpriv
= c
->lxc_conf
&& geteuid() != 0 && !lxc_list_empty(&c
->lxc_conf
->id_map
);
1845 if (c
->lxc_conf
&& has_snapshots(c
)) {
1846 ERROR("container %s has dependent snapshots", c
->name
);
1850 if (!am_unpriv
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
1851 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1853 if (r
->ops
->destroy(r
) < 0) {
1855 ERROR("Error destroying rootfs for %s", c
->name
);
1862 mod_all_rdeps(c
, false);
1864 const char *p1
= lxcapi_get_config_path(c
);
1865 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
1866 sprintf(path
, "%s/%s", p1
, c
->name
);
1868 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
1870 ret
= lxc_rmdir_onedev(path
);
1872 ERROR("Error destroying container directory for %s", c
->name
);
1878 container_disk_unlock(c
);
1882 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
1884 struct lxc_config_t
*config
;
1887 c
->lxc_conf
= lxc_conf_init();
1890 config
= lxc_getconfig(key
);
1893 return (0 == config
->cb(key
, v
, c
->lxc_conf
));
1896 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
1903 if (container_mem_lock(c
))
1906 b
= set_config_item_locked(c
, key
, v
);
1908 container_mem_unlock(c
);
1912 static char *lxcapi_config_file_name(struct lxc_container
*c
)
1914 if (!c
|| !c
->configfile
)
1916 return strdup(c
->configfile
);
1919 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
1921 if (!c
|| !c
->config_path
)
1923 return (const char *)(c
->config_path
);
1928 * Just recalculate the c->configfile based on the
1929 * c->config_path, which must be set.
1930 * The lxc_container must be locked or not yet public.
1932 static bool set_config_filename(struct lxc_container
*c
)
1937 if (!c
->config_path
)
1940 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1941 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
1942 newpath
= malloc(len
);
1946 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
1947 if (ret
< 0 || ret
>= len
) {
1948 fprintf(stderr
, "Error printing out config file name\n");
1954 free(c
->configfile
);
1955 c
->configfile
= newpath
;
1960 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
1964 char *oldpath
= NULL
;
1969 if (container_mem_lock(c
))
1974 ERROR("Out of memory setting new lxc path");
1980 oldpath
= c
->config_path
;
1983 /* Since we've changed the config path, we have to change the
1984 * config file name too */
1985 if (!set_config_filename(c
)) {
1986 ERROR("Out of memory setting new config filename");
1988 free(c
->config_path
);
1989 c
->config_path
= oldpath
;
1995 container_mem_unlock(c
);
2000 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2010 if (container_disk_lock(c
))
2013 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2015 container_disk_unlock(c
);
2019 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2029 if (container_disk_lock(c
))
2032 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2034 container_disk_unlock(c
);
2038 const char *lxc_get_global_config_item(const char *key
)
2040 return lxc_global_config_value(key
);
2043 const char *lxc_get_version(void)
2048 static int copy_file(const char *old
, const char *new)
2055 if (file_exists(new)) {
2056 ERROR("copy destination %s exists", new);
2059 ret
= stat(old
, &sbuf
);
2061 INFO("Error stat'ing %s", old
);
2065 in
= open(old
, O_RDONLY
);
2067 SYSERROR("Error opening original file %s", old
);
2070 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2072 SYSERROR("Error opening new file %s", new);
2078 len
= read(in
, buf
, 8096);
2080 SYSERROR("Error reading old file %s", old
);
2085 ret
= write(out
, buf
, len
);
2086 if (ret
< len
) { // should we retry?
2087 SYSERROR("Error: write to new file %s was interrupted", new);
2094 // we set mode, but not owner/group
2095 ret
= chmod(new, sbuf
.st_mode
);
2097 SYSERROR("Error setting mode on %s", new);
2109 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2112 struct lxc_list
*it
;
2115 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2116 cpath
= alloca(len
);
2117 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2118 if (ret
< 0 || ret
>= len
)
2121 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2122 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2123 char *hookname
= it
->elem
;
2124 char *fname
= strrchr(hookname
, '/');
2125 char tmppath
[MAXPATHLEN
];
2126 if (!fname
) // relative path - we don't support, but maybe we should
2128 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2129 // this hook is public - ignore
2132 // copy the script, and change the entry in confile
2133 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2134 c
->config_path
, c
->name
, fname
+1);
2135 if (ret
< 0 || ret
>= MAXPATHLEN
)
2137 ret
= copy_file(it
->elem
, tmppath
);
2141 it
->elem
= strdup(tmppath
);
2143 ERROR("out of memory copying hook path");
2149 c
->save_config(c
, NULL
);
2153 static void new_hwaddr(char *hwaddr
)
2156 f
= fopen("/dev/urandom", "r");
2159 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2166 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2167 rand() % 255, rand() % 255, rand() % 255);
2170 static void network_new_hwaddrs(struct lxc_container
*c
)
2172 struct lxc_list
*it
;
2174 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2175 struct lxc_netdev
*n
= it
->elem
;
2177 new_hwaddr(n
->hwaddr
);
2181 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2183 char newpath
[MAXPATHLEN
];
2184 char *oldpath
= oldc
->lxc_conf
->fstab
;
2190 char *p
= strrchr(oldpath
, '/');
2193 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2194 c
->config_path
, c
->name
, p
);
2195 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2196 ERROR("error printing new path for %s", oldpath
);
2199 if (file_exists(newpath
)) {
2200 ERROR("error: fstab file %s exists", newpath
);
2204 if (copy_file(oldpath
, newpath
) < 0) {
2205 ERROR("error: copying %s to %s", oldpath
, newpath
);
2208 free(c
->lxc_conf
->fstab
);
2209 c
->lxc_conf
->fstab
= strdup(newpath
);
2210 if (!c
->lxc_conf
->fstab
) {
2211 ERROR("error: allocating pathname");
2218 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2220 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2223 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2225 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2226 WARN("Error copying reverse dependencies");
2229 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2231 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2232 WARN("Error copying reverse dependencies");
2235 if (copy_file(path0
, path1
) < 0) {
2236 INFO("Error copying reverse dependencies");
2241 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2244 char path
[MAXPATHLEN
];
2248 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2250 if (ret
< 0 || ret
>= MAXPATHLEN
)
2252 f
= fopen(path
, "a");
2256 // if anything goes wrong, just return an error
2257 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2264 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2265 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2270 bdev
= bdev_copy(c0
->lxc_conf
->rootfs
.path
, c0
->name
, c
->name
,
2271 c0
->config_path
, c
->config_path
, newtype
, flags
,
2272 bdevdata
, newsize
, &need_rdep
);
2274 ERROR("Error copying storage");
2277 free(c
->lxc_conf
->rootfs
.path
);
2278 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2280 if (!c
->lxc_conf
->rootfs
.path
) {
2281 ERROR("Out of memory while setting storage path");
2284 if (flags
& LXC_CLONE_SNAPSHOT
)
2285 copy_rdepends(c
, c0
);
2287 if (!add_rdepends(c
, c0
))
2288 WARN("Error adding reverse dependency from %s to %s",
2292 mod_all_rdeps(c
, true);
2297 static int clone_update_rootfs(struct lxc_container
*c0
,
2298 struct lxc_container
*c
, int flags
,
2302 char path
[MAXPATHLEN
];
2306 struct lxc_conf
*conf
= c
->lxc_conf
;
2308 /* update hostname in rootfs */
2309 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2315 return wait_for_pid(pid
);
2317 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2320 if (strcmp(bdev
->type
, "dir") != 0) {
2321 if (unshare(CLONE_NEWNS
) < 0) {
2322 ERROR("error unsharing mounts");
2325 if (bdev
->ops
->mount(bdev
) < 0)
2327 } else { // TODO come up with a better way
2330 bdev
->dest
= strdup(bdev
->src
);
2333 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2334 /* Start of environment variable setup for hooks */
2335 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2336 SYSERROR("failed to set environment variable for source container name");
2338 if (setenv("LXC_NAME", c
->name
, 1)) {
2339 SYSERROR("failed to set environment variable for container name");
2341 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2342 SYSERROR("failed to set environment variable for config path");
2344 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2345 SYSERROR("failed to set environment variable for rootfs mount");
2347 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2348 SYSERROR("failed to set environment variable for rootfs mount");
2351 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2352 ERROR("Error executing clone hook for %s", c
->name
);
2357 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2358 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2359 if (ret
< 0 || ret
>= MAXPATHLEN
)
2361 if (!file_exists(path
))
2363 if (!(fout
= fopen(path
, "w"))) {
2364 SYSERROR("unable to open %s: ignoring\n", path
);
2367 if (fprintf(fout
, "%s", c
->name
) < 0)
2369 if (fclose(fout
) < 0)
2376 * We want to support:
2377 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2378 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2380 -s [ implies overlayfs]
2384 only rootfs gets converted (copied/snapshotted) on clone.
2387 static int create_file_dirname(char *path
)
2389 char *p
= strrchr(path
, '/');
2395 ret
= mkdir(path
, 0755);
2396 if (ret
&& errno
!= EEXIST
)
2397 SYSERROR("creating container path %s\n", path
);
2402 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2403 const char *lxcpath
, int flags
,
2404 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2407 struct lxc_container
*c2
= NULL
;
2408 char newpath
[MAXPATHLEN
];
2409 int ret
, storage_copied
= 0;
2413 if (!c
|| !c
->is_defined(c
))
2416 if (container_mem_lock(c
))
2419 if (!is_stopped(c
)) {
2420 ERROR("error: Original container (%s) is running", c
->name
);
2424 // Make sure the container doesn't yet exist.
2425 n
= newname
? newname
: c
->name
;
2426 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2427 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2428 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2429 SYSERROR("clone: failed making config pathname");
2432 if (file_exists(newpath
)) {
2433 ERROR("error: clone: %s exists", newpath
);
2437 ret
= create_file_dirname(newpath
);
2438 if (ret
< 0 && errno
!= EEXIST
) {
2439 ERROR("Error creating container dir for %s", newpath
);
2443 // copy the configuration, tweak it as needed,
2444 fout
= fopen(newpath
, "w");
2446 SYSERROR("open %s", newpath
);
2449 write_config(fout
, c
->lxc_conf
);
2452 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2453 if (mkdir(newpath
, 0755) < 0) {
2454 SYSERROR("error creating %s", newpath
);
2458 c2
= lxc_container_new(n
, l
);
2460 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2465 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2466 ERROR("Error setting new hostname");
2471 ret
= copyhooks(c
, c2
);
2473 ERROR("error copying hooks");
2477 if (copy_fstab(c
, c2
) < 0) {
2478 ERROR("error copying fstab");
2483 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
2484 network_new_hwaddrs(c2
);
2486 // copy/snapshot rootfs's
2487 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2491 // We've now successfully created c2's storage, so clear it out if we
2495 if (!c2
->save_config(c2
, NULL
))
2498 if (clone_update_rootfs(c
, c2
, flags
, hookargs
) < 0)
2501 // TODO: update c's lxc.snapshot = count
2502 container_mem_unlock(c
);
2506 container_mem_unlock(c
);
2508 if (!storage_copied
)
2509 c2
->lxc_conf
->rootfs
.path
= NULL
;
2511 lxc_container_put(c2
);
2517 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2520 struct lxc_container
*newc
;
2522 if (!c
|| !c
->name
|| !c
->config_path
)
2525 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2527 ERROR("Failed to find original backing store type");
2531 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2534 lxc_container_put(newc
);
2538 if (newc
&& lxcapi_is_defined(newc
))
2539 lxc_container_put(newc
);
2541 if (!lxcapi_destroy(c
)) {
2542 ERROR("Could not destroy existing container %s", c
->name
);
2548 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
)
2553 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2556 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2558 lxc_attach_command_t command
;
2565 command
.program
= (char*)program
;
2566 command
.argv
= (char**)argv
;
2567 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2572 return lxc_wait_for_pid_status(pid
);
2575 static int get_next_index(const char *lxcpath
, char *cname
)
2581 fname
= alloca(strlen(lxcpath
) + 20);
2583 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2584 ret
= stat(fname
, &sb
);
2591 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2594 struct lxc_container
*c2
;
2595 char snappath
[MAXPATHLEN
], newname
[20];
2597 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2598 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2599 if (ret
< 0 || ret
>= MAXPATHLEN
)
2601 i
= get_next_index(snappath
, c
->name
);
2603 if (mkdir_p(snappath
, 0755) < 0) {
2604 ERROR("Failed to create snapshot directory %s", snappath
);
2608 ret
= snprintf(newname
, 20, "snap%d", i
);
2609 if (ret
< 0 || ret
>= 20)
2613 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2614 * created in the original container
2616 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2617 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2618 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2620 ERROR("clone of %s:%s failed\n", c
->config_path
, c
->name
);
2624 lxc_container_put(c2
);
2626 // Now write down the creation time
2633 tm_info
= localtime(&timer
);
2635 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2637 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2638 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2639 f
= fopen(dfnam
, "w");
2641 ERROR("Failed to open %s\n", dfnam
);
2644 if (fprintf(f
, "%s", buffer
) < 0) {
2645 SYSERROR("Writing timestamp");
2651 SYSERROR("Writing timestamp");
2656 // $p / $name / comment \0
2657 int len
= strlen(snappath
) + strlen(newname
) + 10;
2658 char *path
= alloca(len
);
2659 sprintf(path
, "%s/%s/comment", snappath
, newname
);
2660 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
2666 static void lxcsnap_free(struct lxc_snapshot
*s
)
2670 if (s
->comment_pathname
)
2671 free(s
->comment_pathname
);
2678 static char *get_snapcomment_path(char* snappath
, char *name
)
2680 // $snappath/$name/comment
2681 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
2682 char *s
= malloc(len
);
2685 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
2686 if (ret
< 0 || ret
>= len
) {
2694 static char *get_timestamp(char* snappath
, char *name
)
2696 char path
[MAXPATHLEN
], *s
= NULL
;
2700 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
2701 if (ret
< 0 || ret
>= MAXPATHLEN
)
2703 fin
= fopen(path
, "r");
2706 (void) fseek(fin
, 0, SEEK_END
);
2708 (void) fseek(fin
, 0, SEEK_SET
);
2713 if (fread(s
, 1, len
, fin
) != len
) {
2714 SYSERROR("reading timestamp");
2724 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
2726 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
2727 int dirlen
, count
= 0, ret
;
2728 struct dirent dirent
, *direntp
;
2729 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
2732 if (!c
|| !lxcapi_is_defined(c
))
2734 // snappath is ${lxcpath}snaps/${lxcname}/
2735 dirlen
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2736 if (dirlen
< 0 || dirlen
>= MAXPATHLEN
) {
2737 ERROR("path name too long");
2740 dir
= opendir(snappath
);
2742 INFO("failed to open %s - assuming no snapshots", snappath
);
2746 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2750 if (!strcmp(direntp
->d_name
, "."))
2753 if (!strcmp(direntp
->d_name
, ".."))
2756 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
2757 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2758 ERROR("pathname too long");
2761 if (!file_exists(path2
))
2763 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
2765 SYSERROR("Out of memory");
2769 snaps
[count
].free
= lxcsnap_free
;
2770 snaps
[count
].name
= strdup(direntp
->d_name
);
2771 if (!snaps
[count
].name
)
2773 snaps
[count
].lxcpath
= strdup(snappath
);
2774 if (!snaps
[count
].lxcpath
) {
2775 free(snaps
[count
].name
);
2778 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
2779 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
2784 WARN("failed to close directory");
2792 for (i
=0; i
<count
; i
++)
2793 lxcsnap_free(&snaps
[i
]);
2797 WARN("failed to close directory");
2801 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
2803 char clonelxcpath
[MAXPATHLEN
];
2805 struct lxc_container
*snap
, *rest
;
2809 if (!c
|| !c
->name
|| !c
->config_path
)
2812 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2814 ERROR("Failed to find original backing store type");
2820 if (strcmp(c
->name
, newname
) == 0) {
2821 if (!lxcapi_destroy(c
)) {
2822 ERROR("Could not destroy existing container %s", newname
);
2827 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2828 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2832 // how should we lock this?
2834 snap
= lxc_container_new(snapname
, clonelxcpath
);
2835 if (!snap
|| !lxcapi_is_defined(snap
)) {
2836 ERROR("Could not open snapshot %s", snapname
);
2837 if (snap
) lxc_container_put(snap
);
2842 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, 0, bdev
->type
, NULL
, 0, NULL
);
2844 if (rest
&& lxcapi_is_defined(rest
))
2847 lxc_container_put(rest
);
2848 lxc_container_put(snap
);
2852 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
2855 char clonelxcpath
[MAXPATHLEN
];
2856 struct lxc_container
*snap
= NULL
;
2858 if (!c
|| !c
->name
|| !c
->config_path
)
2861 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2862 if (ret
< 0 || ret
>= MAXPATHLEN
)
2865 snap
= lxc_container_new(snapname
, clonelxcpath
);
2866 if (!snap
|| !lxcapi_is_defined(snap
)) {
2867 ERROR("Could not find snapshot %s", snapname
);
2871 if (!lxcapi_destroy(snap
)) {
2872 ERROR("Could not destroy snapshot %s", snapname
);
2875 lxc_container_put(snap
);
2880 lxc_container_put(snap
);
2884 static bool lxcapi_may_control(struct lxc_container
*c
)
2886 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
2889 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
2893 char path
[MAXPATHLEN
];
2894 char value
[MAX_BUFFER
];
2895 char *directory_path
= NULL
;
2898 /* make sure container is running */
2899 if (!c
->is_running(c
)) {
2900 ERROR("container is not running");
2904 /* use src_path if dest_path is NULL otherwise use dest_path */
2905 p
= dest_path
? dest_path
: src_path
;
2907 /* prepare the path */
2908 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/root/%s", c
->init_pid(c
), p
);
2909 if (ret
< 0 || ret
>= MAXPATHLEN
)
2911 remove_trailing_slashes(path
);
2913 p
= add
? src_path
: path
;
2914 /* make sure we can access p */
2915 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
2918 /* continue if path is character device or block device */
2919 if (S_ISCHR(st
.st_mode
))
2920 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
2921 else if (S_ISBLK(st
.st_mode
))
2922 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
2926 /* check snprintf return code */
2927 if (ret
< 0 || ret
>= MAX_BUFFER
)
2930 directory_path
= dirname(strdup(path
));
2931 /* remove path and directory_path (if empty) */
2932 if(access(path
, F_OK
) == 0) {
2933 if (unlink(path
) < 0) {
2934 ERROR("unlink failed");
2937 if (rmdir(directory_path
) < 0 && errno
!= ENOTEMPTY
) {
2938 ERROR("rmdir failed");
2944 /* create the missing directories */
2945 if (mkdir_p(directory_path
, 0755) < 0) {
2946 ERROR("failed to create directory");
2950 /* create the device node */
2951 if (mknod(path
, st
.st_mode
, st
.st_rdev
) < 0) {
2952 ERROR("mknod failed");
2956 /* add device node to device list */
2957 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
2958 ERROR("set_cgroup_item failed while adding the device node");
2962 /* remove device node from device list */
2963 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
2964 ERROR("set_cgroup_item failed while removing the device node");
2971 free(directory_path
);
2975 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
2977 return add_remove_device_node(c
, src_path
, dest_path
, true);
2980 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
2982 return add_remove_device_node(c
, src_path
, dest_path
, false);
2985 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
2995 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
2999 ERROR("Memory allocation error.");
3004 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3009 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3011 struct lxc_container
*c
;
3013 c
= malloc(sizeof(*c
));
3015 fprintf(stderr
, "failed to malloc lxc_container\n");
3018 memset(c
, 0, sizeof(*c
));
3021 c
->config_path
= strdup(configpath
);
3023 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
3025 if (!c
->config_path
) {
3026 fprintf(stderr
, "Out of memory");
3030 remove_trailing_slashes(c
->config_path
);
3031 c
->name
= malloc(strlen(name
)+1);
3033 fprintf(stderr
, "Error allocating lxc_container name\n");
3036 strcpy(c
->name
, name
);
3039 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3040 fprintf(stderr
, "failed to create lock\n");
3044 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3045 fprintf(stderr
, "failed to alloc privlock\n");
3049 if (!set_config_filename(c
)) {
3050 fprintf(stderr
, "Error allocating config file pathname\n");
3054 if (file_exists(c
->configfile
))
3055 lxcapi_load_config(c
, NULL
);
3057 if (ongoing_create(c
) == 2) {
3058 ERROR("Error: %s creation was not completed", c
->name
);
3060 lxcapi_clear_config(c
);
3063 // assign the member functions
3064 c
->is_defined
= lxcapi_is_defined
;
3065 c
->state
= lxcapi_state
;
3066 c
->is_running
= lxcapi_is_running
;
3067 c
->freeze
= lxcapi_freeze
;
3068 c
->unfreeze
= lxcapi_unfreeze
;
3069 c
->console
= lxcapi_console
;
3070 c
->console_getfd
= lxcapi_console_getfd
;
3071 c
->init_pid
= lxcapi_init_pid
;
3072 c
->load_config
= lxcapi_load_config
;
3073 c
->want_daemonize
= lxcapi_want_daemonize
;
3074 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3075 c
->start
= lxcapi_start
;
3076 c
->startl
= lxcapi_startl
;
3077 c
->stop
= lxcapi_stop
;
3078 c
->config_file_name
= lxcapi_config_file_name
;
3079 c
->wait
= lxcapi_wait
;
3080 c
->set_config_item
= lxcapi_set_config_item
;
3081 c
->destroy
= lxcapi_destroy
;
3082 c
->rename
= lxcapi_rename
;
3083 c
->save_config
= lxcapi_save_config
;
3084 c
->get_keys
= lxcapi_get_keys
;
3085 c
->create
= lxcapi_create
;
3086 c
->createl
= lxcapi_createl
;
3087 c
->shutdown
= lxcapi_shutdown
;
3088 c
->reboot
= lxcapi_reboot
;
3089 c
->clear_config
= lxcapi_clear_config
;
3090 c
->clear_config_item
= lxcapi_clear_config_item
;
3091 c
->get_config_item
= lxcapi_get_config_item
;
3092 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3093 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3094 c
->get_config_path
= lxcapi_get_config_path
;
3095 c
->set_config_path
= lxcapi_set_config_path
;
3096 c
->clone
= lxcapi_clone
;
3097 c
->get_interfaces
= lxcapi_get_interfaces
;
3098 c
->get_ips
= lxcapi_get_ips
;
3099 c
->attach
= lxcapi_attach
;
3100 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3101 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3102 c
->snapshot
= lxcapi_snapshot
;
3103 c
->snapshot_list
= lxcapi_snapshot_list
;
3104 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3105 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3106 c
->may_control
= lxcapi_may_control
;
3107 c
->add_device_node
= lxcapi_add_device_node
;
3108 c
->remove_device_node
= lxcapi_remove_device_node
;
3110 /* we'll allow the caller to update these later */
3111 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3112 fprintf(stderr
, "failed to open log\n");
3119 lxc_container_free(c
);
3123 int lxc_get_wait_states(const char **states
)
3128 for (i
=0; i
<MAX_STATE
; i
++)
3129 states
[i
] = lxc_state2str(i
);
3134 * These next two could probably be done smarter with reusing a common function
3135 * with different iterators and tests...
3137 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3140 int i
, cfound
= 0, nfound
= 0;
3141 struct dirent dirent
, *direntp
;
3142 struct lxc_container
*c
;
3145 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3147 dir
= opendir(lxcpath
);
3149 SYSERROR("opendir on lxcpath");
3158 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3161 if (!strcmp(direntp
->d_name
, "."))
3163 if (!strcmp(direntp
->d_name
, ".."))
3166 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3170 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3180 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3182 INFO("Container %s:%s has a config but could not be loaded",
3183 lxcpath
, direntp
->d_name
);
3185 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3189 if (!lxcapi_is_defined(c
)) {
3190 INFO("Container %s:%s has a config but is not defined",
3191 lxcpath
, direntp
->d_name
);
3193 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3195 lxc_container_put(c
);
3199 if (!add_to_clist(cret
, c
, nfound
, true)) {
3200 lxc_container_put(c
);
3210 if (names
&& *names
) {
3211 for (i
=0; i
<cfound
; i
++)
3215 if (cret
&& *cret
) {
3216 for (i
=0; i
<nfound
; i
++)
3217 lxc_container_put((*cret
)[i
]);
3224 int list_active_containers(const char *lxcpath
, char ***nret
,
3225 struct lxc_container
***cret
)
3227 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3230 char **ct_name
= NULL
;
3232 struct lxc_container
*c
;
3235 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3236 lxcpath_len
= strlen(lxcpath
);
3243 FILE *f
= fopen("/proc/net/unix", "r");
3247 while (getline(&line
, &len
, f
) != -1) {
3248 char *p
= strrchr(line
, ' '), *p2
;
3255 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3261 // Now p is the start of lxc_name
3263 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3267 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3270 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3271 goto free_cret_list
;
3278 c
= lxc_container_new(p
, lxcpath
);
3280 INFO("Container %s:%s is running but could not be loaded",
3282 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3287 * If this is an anonymous container, then is_defined *can*
3288 * return false. So we don't do that check. Count on the
3289 * fact that the command socket exists.
3292 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3293 lxc_container_put(c
);
3294 goto free_cret_list
;
3299 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3308 if (cret
&& *cret
) {
3309 for (i
= 0; i
< cret_cnt
; i
++)
3310 lxc_container_put((*cret
)[i
]);
3316 for (i
= 0; i
< ct_name_cnt
; i
++)
3329 int list_all_containers(const char *lxcpath
, char ***nret
,
3330 struct lxc_container
***cret
)
3332 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3335 struct lxc_container
**ct_list
= NULL
;
3337 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3341 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3342 if (active_cnt
< 0) {
3347 for (i
= 0; i
< active_cnt
; i
++) {
3348 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3349 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3351 goto free_active_name
;
3355 free(active_name
[i
]);
3356 active_name
[i
] = NULL
;
3362 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3363 struct lxc_container
*c
;
3365 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3367 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3368 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3372 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3373 lxc_container_put(c
);
3392 for (i
= 0; i
< ct_list_cnt
; i
++) {
3393 lxc_container_put(ct_list
[i
]);
3399 for (i
= 0; i
< active_cnt
; i
++) {
3401 free(active_name
[i
]);
3407 for (i
= 0; i
< ct_cnt
; i
++) {