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>
36 #include <lxc/lxccontainer.h>
47 #include <lxc/utils.h>
48 #include <lxc/monitor.h>
49 #include <lxc/namespace.h>
51 #include <arpa/inet.h>
56 #include <../include/ifaddrs.h>
61 #include <../include/getline.h>
65 lxc_log_define(lxc_container
, lxc
);
67 static bool file_exists(char *f
)
71 return stat(f
, &statbuf
) == 0;
74 static bool config_file_exists(const char *lxcpath
, const char *cname
)
76 /* $lxcpath + '/' + $cname + '/config' + \0 */
77 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
78 char *fname
= alloca(len
);
80 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
81 if (ret
< 0 || ret
>= len
)
84 return file_exists(fname
);
88 * A few functions to help detect when a container creation failed.
89 * If a container creation was killed partway through, then trying
90 * to actually start that container could harm the host. We detect
91 * this by creating a 'partial' file under the container directory,
92 * and keeping an advisory lock. When container creation completes,
93 * we remove that file. When we load or try to start a container, if
94 * we find that file, without a flock, we remove the container.
96 int ongoing_create(struct lxc_container
*c
)
98 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
99 char *path
= alloca(len
);
103 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
104 if (ret
< 0 || ret
>= len
) {
105 ERROR("Error writing partial pathname");
109 if (!file_exists(path
))
112 fd
= open(path
, O_RDWR
);
115 // give benefit of the doubt
116 SYSERROR("Error opening partial file");
120 lk
.l_whence
= SEEK_SET
;
124 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
125 // create is still ongoing
131 // create completed but partial is still there.
138 int create_partial(struct lxc_container
*c
)
140 // $lxcpath + '/' + $name + '/partial' + \0
141 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
142 char *path
= alloca(len
);
146 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
147 if (ret
< 0 || ret
>= len
) {
148 ERROR("Error writing partial pathname");
152 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
153 SYSERROR("Erorr creating partial file");
158 lk
.l_whence
= SEEK_SET
;
161 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
162 SYSERROR("Error locking partial file %s", path
);
172 void remove_partial(struct lxc_container
*c
, int fd
)
174 // $lxcpath + '/' + $name + '/partial' + \0
175 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
176 char *path
= alloca(len
);
182 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
183 if (ret
< 0 || ret
>= len
) {
184 ERROR("Error writing partial pathname");
187 if (unlink(path
) < 0)
188 SYSERROR("Error unlink partial file %s", path
);
192 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
193 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
194 * container configuration file.
195 * The container_disk_lock also takes the container_mem_lock.
196 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
197 * NOTHING mutexes two independent programs with their own struct
198 * lxc_container for the same c->name, between API calls. For instance,
199 * c->config_read(); c->start(); Between those calls, data on disk
200 * could change (which shouldn't bother the caller unless for instance
201 * the rootfs get moved). c->config_read(); update; c->config_write();
202 * Two such updaters could race. The callers should therefore check their
203 * results. Trying to prevent that would necessarily expose us to deadlocks
204 * due to hung callers. So I prefer to keep the locks only within our own
205 * functions, not across functions.
207 * If you're going to clone while holding a lxccontainer, increment
208 * c->numthreads (under privlock) before forking. When deleting,
209 * decrement numthreads under privlock, then if it hits 0 you can delete.
210 * Do not ever use a lxccontainer whose numthreads you did not bump.
213 static void lxc_container_free(struct lxc_container
*c
)
220 c
->configfile
= NULL
;
222 if (c
->error_string
) {
223 free(c
->error_string
);
224 c
->error_string
= NULL
;
227 lxc_putlock(c
->slock
);
231 lxc_putlock(c
->privlock
);
239 lxc_conf_free(c
->lxc_conf
);
242 if (c
->config_path
) {
243 free(c
->config_path
);
244 c
->config_path
= NULL
;
250 * Consider the following case:
251 freer | racing get()er
252 ==================================================================
253 lxc_container_put() | lxc_container_get()
254 \ lxclock(c->privlock) | c->numthreads < 1? (no)
255 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
257 \ lxc_container_free() | \ lxclock() returns
258 | \ c->numthreads < 1 -> return 0
260 \ \ sem_destroy(privlock) |
262 * When the get()er checks numthreads the first time, one of the following
264 * 1. freer has set numthreads = 0. get() returns 0
265 * 2. freer is between lxclock and setting numthreads to 0. get()er will
266 * sem_wait on privlock, get lxclock after freer() drops it, then see
267 * numthreads is 0 and exit without touching lxclock again..
268 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
269 * will see --numthreads = 1 and not call lxc_container_free().
272 int lxc_container_get(struct lxc_container
*c
)
277 // if someone else has already started freeing the container, don't
278 // try to take the lock, which may be invalid
279 if (c
->numthreads
< 1)
282 if (container_mem_lock(c
))
284 if (c
->numthreads
< 1) {
285 // bail without trying to unlock, bc the privlock is now probably
290 container_mem_unlock(c
);
294 int lxc_container_put(struct lxc_container
*c
)
298 if (container_mem_lock(c
))
300 if (--c
->numthreads
< 1) {
301 container_mem_unlock(c
);
302 lxc_container_free(c
);
305 container_mem_unlock(c
);
309 static bool lxcapi_is_defined(struct lxc_container
*c
)
318 if (container_mem_lock(c
))
322 statret
= stat(c
->configfile
, &statbuf
);
328 container_mem_unlock(c
);
332 static const char *lxcapi_state(struct lxc_container
*c
)
338 s
= lxc_getstate(c
->name
, c
->config_path
);
339 return lxc_state2str(s
);
342 static bool is_stopped(struct lxc_container
*c
)
345 s
= lxc_getstate(c
->name
, c
->config_path
);
346 return (s
== STOPPED
);
349 static bool lxcapi_is_running(struct lxc_container
*c
)
356 if (!s
|| strcmp(s
, "STOPPED") == 0)
361 static bool lxcapi_freeze(struct lxc_container
*c
)
367 ret
= lxc_freeze(c
->name
, c
->config_path
);
373 static bool lxcapi_unfreeze(struct lxc_container
*c
)
379 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
385 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
391 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
395 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
396 int stdoutfd
, int stderrfd
, int escape
)
398 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
401 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
406 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
409 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
412 c
->lxc_conf
= lxc_conf_init();
413 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
418 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
420 bool ret
= false, need_disklock
= false;
426 fname
= c
->configfile
;
432 * If we're reading something other than the container's config,
433 * we only need to lock the in-memory container. If loading the
434 * container's config file, take the disk lock.
436 if (strcmp(fname
, c
->configfile
) == 0)
437 need_disklock
= true;
440 lret
= container_disk_lock(c
);
442 lret
= container_mem_lock(c
);
446 ret
= load_config_locked(c
, fname
);
449 container_disk_unlock(c
);
451 container_mem_unlock(c
);
455 static void lxcapi_want_daemonize(struct lxc_container
*c
)
457 if (!c
|| !c
->lxc_conf
)
459 if (container_mem_lock(c
)) {
460 ERROR("Error getting mem lock");
464 /* daemonize implies close_all_fds so set it */
465 c
->lxc_conf
->close_all_fds
= 1;
466 container_mem_unlock(c
);
469 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
)
471 if (!c
|| !c
->lxc_conf
)
473 if (container_mem_lock(c
)) {
474 ERROR("Error getting mem lock");
477 c
->lxc_conf
->close_all_fds
= 1;
478 container_mem_unlock(c
);
482 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
489 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
494 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
496 /* we'll probably want to make this timeout configurable? */
497 int timeout
= 5, ret
, status
;
500 * our child is going to fork again, then exit. reap the
503 ret
= waitpid(pid
, &status
, 0);
504 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
505 DEBUG("failed waiting for first dual-fork child");
506 return lxcapi_wait(c
, "RUNNING", timeout
);
509 static bool am_single_threaded(void)
511 struct dirent dirent
, *direntp
;
516 dir
= opendir("/proc/self/task");
519 INFO("failed to open /proc/self/task");
523 while (!readdir_r(dir
, &dirent
, &direntp
)) {
527 if (!strcmp(direntp
->d_name
, "."))
530 if (!strcmp(direntp
->d_name
, ".."))
542 * I can't decide if it'd be more convenient for callers if we accept '...',
543 * or a null-terminated array (i.e. execl vs execv)
545 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
548 struct lxc_conf
*conf
;
550 char *default_args
[] = {
555 /* container exists */
558 /* container has been setup */
562 if ((ret
= ongoing_create(c
)) < 0) {
563 ERROR("Error checking for incomplete creation");
567 ERROR("Error: %s creation was not completed", c
->name
);
570 } else if (ret
== 1) {
571 ERROR("Error: creation of %s is ongoing", c
->name
);
575 /* is this app meant to be run through lxcinit, as in lxc-execute? */
576 if (useinit
&& !argv
)
579 if (container_mem_lock(c
))
582 daemonize
= c
->daemonize
;
583 container_mem_unlock(c
);
586 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
587 return ret
== 0 ? true : false;
594 * say, I'm not sure - what locks do we want here? Any?
595 * Is liblxc's locking enough here to protect the on disk
596 * container? We don't want to exclude things like lxc_info
597 * while container is running...
600 if (!lxc_container_get(c
))
602 lxc_monitord_spawn(c
->config_path
);
606 lxc_container_put(c
);
610 return wait_on_daemonized_start(c
, pid
);
612 process_unlock(); // we're no longer sharing
613 /* second fork to be reparented by init */
616 SYSERROR("Error doing dual-fork");
621 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
623 SYSERROR("Error chdir()ing to /.");
629 open("/dev/zero", O_RDONLY
);
630 open("/dev/null", O_RDWR
);
631 open("/dev/null", O_RDWR
);
634 if (!am_single_threaded()) {
635 ERROR("Cannot start non-daemonized container when threaded");
642 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
645 INFO("container requested reboot");
651 lxc_container_put(c
);
652 exit (ret
== 0 ? true : false);
654 return (ret
== 0 ? true : false);
659 * note there MUST be an ending NULL
661 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
664 char **inargs
= NULL
;
667 /* container exists */
671 va_start(ap
, useinit
);
672 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
676 ERROR("Memory allocation error.");
680 /* pass NULL if no arguments were supplied */
681 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
686 for (arg
= inargs
; *arg
; arg
++)
694 static bool lxcapi_stop(struct lxc_container
*c
)
701 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
707 * create the standard expected container dir
709 static bool create_container_dir(struct lxc_container
*c
)
714 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
718 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
719 if (ret
< 0 || ret
>= len
) {
723 ret
= mkdir(s
, 0755);
728 SYSERROR("failed to create container path for %s\n", c
->name
);
734 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
735 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
738 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
739 * it returns a mounted bdev on success, NULL on error.
741 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
742 struct bdev_specs
*specs
)
749 /* rootfs.path or lxcpath/lxcname/rootfs */
750 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
751 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
752 len
= strlen(rpath
) + 1;
754 ret
= snprintf(dest
, len
, "%s", rpath
);
756 const char *lxcpath
= lxcapi_get_config_path(c
);
757 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
759 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
761 if (ret
< 0 || ret
>= len
)
764 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
766 ERROR("Failed to create backing store type %s\n", type
);
770 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
772 /* if we are not root, chown the rootfs dir to root in the
775 if (geteuid() != 0) {
776 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
777 ERROR("Error chowning %s to container root\n", bdev
->dest
);
787 * Given the '-t' template option to lxc-create, figure out what to
788 * do. If the template is a full executable path, use that. If it
789 * is something like 'sshd', then return $templatepath/lxc-sshd.
790 * On success return the template, on error return NULL.
792 static char *get_template_path(const char *t
)
797 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
802 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
806 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
807 if (ret
< 0 || ret
>= len
) {
811 if (access(tpath
, X_OK
) < 0) {
812 SYSERROR("bad template: %s\n", t
);
820 static char *lxcbasename(char *path
)
822 char *p
= path
+ strlen(path
) - 1;
823 while (*p
!= '/' && p
> path
)
828 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
838 SYSERROR("failed to fork task for container creation template\n");
842 if (pid
== 0) { // child
843 char *patharg
, *namearg
, *rootfsarg
, *src
;
844 struct bdev
*bdev
= NULL
;
846 int ret
, len
, nargs
= 0;
848 struct lxc_conf
*conf
= c
->lxc_conf
;
850 process_unlock(); // we're no longer sharing
855 open("/dev/zero", O_RDONLY
);
856 open("/dev/null", O_RDWR
);
857 open("/dev/null", O_RDWR
);
860 src
= c
->lxc_conf
->rootfs
.path
;
862 * for an overlayfs create, what the user wants is the template to fill
863 * in what will become the readonly lower layer. So don't mount for
866 if (strncmp(src
, "overlayfs:", 10) == 0) {
867 src
= overlayfs_getlower(src
+10);
869 bdev
= bdev_init(src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
871 ERROR("Error opening rootfs");
875 if (geteuid() == 0) {
876 if (unshare(CLONE_NEWNS
) < 0) {
877 ERROR("error unsharing mounts");
880 if (detect_shared_rootfs()) {
881 if (mount("", "", NULL
, MS_SLAVE
|MS_REC
, 0)) {
882 SYSERROR("Failed to make / rslave to run template");
883 ERROR("Continuing...");
887 if (strcmp(bdev
->type
, "dir") != 0) {
888 if (geteuid() != 0) {
889 ERROR("non-root users can only create directory-backed containers");
892 if (bdev
->ops
->mount(bdev
) < 0) {
893 ERROR("Error mounting rootfs");
896 } else { // TODO come up with a better way here!
899 bdev
->dest
= strdup(bdev
->src
);
903 * create our new array, pre-pend the template name and
907 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
908 nargs
+= 4; // template, path, rootfs and name args
910 newargv
= malloc(nargs
* sizeof(*newargv
));
913 newargv
[0] = lxcbasename(tpath
);
915 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
916 patharg
= malloc(len
);
919 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
920 if (ret
< 0 || ret
>= len
)
922 newargv
[1] = patharg
;
923 len
= strlen("--name=") + strlen(c
->name
) + 1;
924 namearg
= malloc(len
);
927 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
928 if (ret
< 0 || ret
>= len
)
930 newargv
[2] = namearg
;
932 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
933 rootfsarg
= malloc(len
);
936 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
937 if (ret
< 0 || ret
>= len
)
939 newargv
[3] = rootfsarg
;
941 /* add passed-in args */
943 for (i
= 4; i
< nargs
; i
++)
944 newargv
[i
] = argv
[i
-4];
946 /* add trailing NULL */
948 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
951 newargv
[nargs
- 1] = NULL
;
954 * If we're running the template in a mapped userns, then
955 * we prepend the template command with:
956 * lxc-usernsexec <-m map1> ... <-m mapn> --
957 * and we append "--mapped-uid x", where x is the mapped uid
960 if (geteuid() != 0 && !lxc_list_empty(&conf
->id_map
)) {
963 char **n2
= malloc(n2args
* sizeof(*n2
));
968 SYSERROR("out of memory");
972 tpath
= "lxc-usernsexec";
973 n2
[0] = "lxc-usernsexec";
974 lxc_list_for_each(it
, &conf
->id_map
) {
977 n2
= realloc(n2
, n2args
* sizeof(char *));
981 n2
[n2args
-1] = malloc(200);
984 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
985 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
986 map
->nsid
, map
->hostid
, map
->range
);
987 if (ret
< 0 || ret
>= 200)
990 int hostid_mapped
= mapped_hostid(geteuid(), conf
);
991 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
992 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
995 if (hostid_mapped
< 0) {
996 hostid_mapped
= find_unmapped_nsuid(conf
);
998 if (hostid_mapped
< 0) {
999 ERROR("Could not find free uid to map");
1002 n2
[n2args
++] = malloc(200);
1003 if (!n2
[n2args
-1]) {
1004 SYSERROR("out of memory");
1007 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
1008 hostid_mapped
, geteuid());
1009 if (ret
< 0 || ret
>= 200) {
1010 ERROR("string too long");
1014 n2
[n2args
++] = "--";
1015 for (i
= 0; i
< nargs
; i
++)
1016 n2
[i
+ n2args
] = newargv
[i
];
1018 // Finally add "--mapped-uid $uid" to tell template what to chown
1021 n2
= realloc(n2
, n2args
* sizeof(char *));
1023 SYSERROR("out of memory");
1026 // note n2[n2args-1] is NULL
1027 n2
[n2args
-3] = "--mapped-uid";
1028 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1029 n2
[n2args
-2] = txtuid
;
1030 n2
[n2args
-1] = NULL
;
1035 execvp(tpath
, newargv
);
1036 SYSERROR("failed to execute template %s", tpath
);
1040 if (wait_for_pid(pid
) != 0) {
1041 ERROR("container creation template for %s failed\n", c
->name
);
1048 bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1056 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1061 f
= fopen(path
, "r");
1066 if (fseek(f
, 0, SEEK_END
) < 0)
1068 if ((flen
= ftell(f
)) < 0)
1070 if (fseek(f
, 0, SEEK_SET
) < 0)
1072 if ((contents
= malloc(flen
+ 1)) == NULL
)
1074 if (fread(contents
, 1, flen
, f
) != flen
)
1075 goto out_free_contents
;
1077 contents
[flen
] = '\0';
1083 goto out_free_contents
;
1086 tpath
= get_template_path(t
);
1088 ERROR("bad template: %s\n", t
);
1089 goto out_free_contents
;
1092 ret
= sha1sum_file(tpath
, md_value
);
1094 ERROR("Error getting sha1sum of %s", tpath
);
1096 goto out_free_contents
;
1102 f
= fopen(path
, "w");
1105 SYSERROR("reopening config for writing");
1109 fprintf(f
, "# Template used to create this container: %s\n", t
);
1111 fprintf(f
, "# Parameters passed to the template:");
1113 fprintf(f
, " %s", *argv
);
1119 fprintf(f
, "# Template script checksum (SHA-1): ");
1120 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1121 fprintf(f
, "%02x", md_value
[i
]);
1124 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1125 SYSERROR("Writing original contents");
1145 SYSERROR("Error prepending header");
1151 static bool lxcapi_destroy(struct lxc_container
*c
);
1154 * create a container with the given parameters.
1155 * @c: container to be created. It has the lxcpath, name, and a starting
1156 * configuration already set
1157 * @t: the template to execute to instantiate the root filesystem and
1158 * adjust the configuration.
1159 * @bdevtype: backing store type to use. If NULL, dir will be used.
1160 * @specs: additional parameters for the backing store, i.e. LVM vg to
1163 * @argv: the arguments to pass to the template, terminated by NULL. If no
1164 * arguments, you can just pass NULL.
1166 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1167 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1179 tpath
= get_template_path(t
);
1181 ERROR("bad template: %s\n", t
);
1187 * If a template is passed in, and the rootfs already is defined in
1188 * the container config and exists, then * caller is trying to create
1189 * an existing container. Return an error, but do NOT delete the
1192 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1193 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1194 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1199 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1200 ERROR("Error loading default configuration file %s\n", LXC_DEFAULT_CONFIG
);
1205 if (!create_container_dir(c
))
1209 * either template or rootfs.path should be set.
1210 * if both template and rootfs.path are set, template is setup as rootfs.path.
1211 * container is already created if we have a config and rootfs.path is accessible
1213 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1214 /* no template passed in and rootfs does not exist: error */
1216 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1217 /* rootfs passed into configuration, but does not exist: error */
1219 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1220 /* Rootfs already existed, user just wanted to save the
1221 * loaded configuration */
1226 /* Mark that this container is being created */
1227 if ((partial_fd
= create_partial(c
)) < 0)
1230 /* no need to get disk lock bc we have the partial locked */
1233 * Create the backing store
1234 * Note we can't do this in the same task as we use to execute the
1235 * template because of the way zfs works.
1236 * After you 'zfs create', zfs mounts the fs only in the initial
1241 SYSERROR("failed to fork task for container creation template\n");
1245 if (pid
== 0) { // child
1246 struct bdev
*bdev
= NULL
;
1248 process_unlock(); // we're no longer sharing
1249 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1250 ERROR("Error creating backing store type %s for %s",
1251 bdevtype
? bdevtype
: "(none)", c
->name
);
1255 /* save config file again to store the new rootfs location */
1256 if (!c
->save_config(c
, NULL
)) {
1257 ERROR("failed to save starting configuration for %s\n", c
->name
);
1258 // parent task won't see bdev in config so we delete it
1259 bdev
->ops
->umount(bdev
);
1260 bdev
->ops
->destroy(bdev
);
1265 if (wait_for_pid(pid
) != 0)
1268 /* reload config to get the rootfs */
1270 lxc_conf_free(c
->lxc_conf
);
1272 if (!load_config_locked(c
, c
->configfile
))
1275 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1278 // now clear out the lxc_conf we have, reload from the created
1281 lxc_conf_free(c
->lxc_conf
);
1285 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1286 ERROR("Error prepending header to configuration file");
1290 ret
= load_config_locked(c
, c
->configfile
);
1293 if (partial_fd
>= 0)
1294 remove_partial(c
, partial_fd
);
1304 static bool lxcapi_reboot(struct lxc_container
*c
)
1310 if (!c
->is_running(c
))
1312 pid
= c
->init_pid(c
);
1315 if (kill(pid
, SIGINT
) < 0)
1321 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1331 if (!c
->is_running(c
))
1333 pid
= c
->init_pid(c
);
1337 retv
= c
->wait(c
, "STOPPED", timeout
);
1338 if (!retv
&& timeout
> 0) {
1340 retv
= c
->wait(c
, "STOPPED", 0); // 0 means don't wait
1345 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1346 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1356 * since we're going to wait for create to finish, I don't think we
1357 * need to get a copy of the arguments.
1359 va_start(ap
, flags
);
1360 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1363 ERROR("Memory allocation error.");
1367 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1374 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1378 if (!c
|| !c
->lxc_conf
)
1380 if (container_mem_lock(c
))
1382 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1383 container_mem_unlock(c
);
1387 static inline void exit_from_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1388 /* Switch back to original netns */
1389 if (*old_netns
>= 0 && setns(*old_netns
, CLONE_NEWNET
))
1390 SYSERROR("failed to setns");
1392 if (*new_netns
>= 0)
1394 if (*old_netns
>= 0)
1399 static inline bool enter_to_ns(struct lxc_container
*c
, int *old_netns
, int *new_netns
) {
1401 char new_netns_path
[MAXPATHLEN
];
1403 if (!c
->is_running(c
))
1406 /* Save reference to old netns */
1408 *old_netns
= open("/proc/self/ns/net", O_RDONLY
);
1410 if (*old_netns
< 0) {
1411 SYSERROR("failed to open /proc/self/ns/net");
1415 /* Switch to new netns */
1416 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", c
->init_pid(c
));
1417 if (ret
< 0 || ret
>= MAXPATHLEN
)
1421 *new_netns
= open(new_netns_path
, O_RDONLY
);
1423 if (*new_netns
< 0) {
1424 SYSERROR("failed to open %s", new_netns_path
);
1428 if (setns(*new_netns
, CLONE_NEWNET
)) {
1429 SYSERROR("failed to setns");
1434 exit_from_ns(c
, old_netns
, new_netns
);
1438 // used by qsort and bsearch functions for comparing names
1439 static inline int string_cmp(char **first
, char **second
)
1441 return strcmp(*first
, *second
);
1444 // used by qsort and bsearch functions for comparing container names
1445 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1447 return strcmp((*first
)->name
, (*second
)->name
);
1450 static bool add_to_array(char ***names
, char *cname
, int pos
)
1452 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1454 ERROR("Out of memory");
1459 newnames
[pos
] = strdup(cname
);
1463 // sort the arrray as we will use binary search on it
1464 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1469 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1471 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1473 ERROR("Out of memory");
1480 // sort the arrray as we will use binary search on it
1482 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1487 static char** get_from_array(char ***names
, char *cname
, int size
)
1489 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1493 static bool array_contains(char ***names
, char *cname
, int size
) {
1494 if(get_from_array(names
, cname
, size
) != NULL
)
1499 static bool remove_from_array(char ***names
, char *cname
, int size
)
1501 char **result
= get_from_array(names
, cname
, size
);
1502 if (result
!= NULL
) {
1509 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1512 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1513 char **interfaces
= NULL
;
1514 int old_netns
= -1, new_netns
= -1;
1516 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1519 /* Grab the list of interfaces */
1520 if (getifaddrs(&interfaceArray
)) {
1521 SYSERROR("failed to get interfaces list");
1525 /* Iterate through the interfaces */
1526 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1527 if (array_contains(&interfaces
, tempIfAddr
->ifa_name
, count
))
1530 if(!add_to_array(&interfaces
, tempIfAddr
->ifa_name
, count
))
1537 freeifaddrs(interfaceArray
);
1539 exit_from_ns(c
, &old_netns
, &new_netns
);
1541 /* Append NULL to the array */
1543 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1548 for(i
=0;i
<count
;i
++)
1549 free(interfaces
[i
]);
1555 static char** lxcapi_get_ips(struct lxc_container
*c
, char* interface
, char* family
, int scope
)
1558 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1559 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1560 void *tempAddrPtr
= NULL
;
1561 char **addresses
= NULL
;
1562 char *address
= NULL
;
1563 int old_netns
= -1, new_netns
= -1;
1565 if (!enter_to_ns(c
, &old_netns
, &new_netns
))
1568 /* Grab the list of interfaces */
1569 if (getifaddrs(&interfaceArray
)) {
1570 SYSERROR("failed to get interfaces list");
1574 /* Iterate through the interfaces */
1575 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1576 if (tempIfAddr
->ifa_addr
== NULL
)
1579 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1580 if (family
&& strcmp(family
, "inet"))
1582 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1585 if (family
&& strcmp(family
, "inet6"))
1588 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1591 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1594 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1596 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1599 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1601 addressOutputBuffer
,
1602 sizeof(addressOutputBuffer
));
1606 if(!add_to_array(&addresses
, address
, count
))
1613 freeifaddrs(interfaceArray
);
1615 exit_from_ns(c
, &old_netns
, &new_netns
);
1617 /* Append NULL to the array */
1619 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1624 for(i
=0;i
<count
;i
++)
1632 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1636 if (!c
|| !c
->lxc_conf
)
1638 if (container_mem_lock(c
))
1640 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1641 container_mem_unlock(c
);
1645 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1648 return lxc_listconfigs(retv
, inlen
);
1650 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1651 * This is an intelligent result to show which keys are valid given
1652 * the type of nic it is
1654 if (!c
|| !c
->lxc_conf
)
1656 if (container_mem_lock(c
))
1659 if (strncmp(key
, "lxc.network.", 12) == 0)
1660 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1661 container_mem_unlock(c
);
1665 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1668 bool ret
= false, need_disklock
= false;
1672 alt_file
= c
->configfile
;
1674 return false; // should we write to stdout if no file is specified?
1676 // If we haven't yet loaded a config, load the stock config
1678 if (!c
->load_config(c
, LXC_DEFAULT_CONFIG
)) {
1679 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG
, c
->name
);
1684 if (!create_container_dir(c
))
1688 * If we're writing to the container's config file, take the
1689 * disk lock. Otherwise just take the memlock to protect the
1690 * struct lxc_container while we're traversing it.
1692 if (strcmp(c
->configfile
, alt_file
) == 0)
1693 need_disklock
= true;
1696 lret
= container_disk_lock(c
);
1698 lret
= container_mem_lock(c
);
1704 fout
= fopen(alt_file
, "w");
1708 write_config(fout
, c
->lxc_conf
);
1716 container_disk_unlock(c
);
1718 container_mem_unlock(c
);
1722 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1724 char path
[MAXPATHLEN
];
1729 if (container_disk_lock(c
))
1731 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1733 if (ret
< 0 || ret
> MAXPATHLEN
)
1736 f
= fopen(path
, "r");
1739 ret
= fscanf(f
, "%d", &v
);
1744 ERROR("Corrupted file %s", path
);
1750 f
= fopen(path
, "w");
1754 if (fprintf(f
, "%d\n", v
) < 0) {
1755 ERROR("Error writing new snapshots value");
1765 SYSERROR("Error writing to or closing snapshots file");
1772 container_disk_unlock(c
);
1776 static void strip_newline(char *p
)
1778 size_t len
= strlen(p
);
1781 if (p
[len
-1] == '\n')
1785 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1787 struct lxc_container
*p
;
1788 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1789 size_t pathlen
= 0, namelen
= 0;
1793 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1794 c
->config_path
, c
->name
);
1795 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1796 ERROR("Path name too long");
1800 f
= fopen(path
, "r");
1804 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1805 if (getline(&lxcname
, &namelen
, f
) == -1) {
1806 ERROR("badly formatted file %s\n", path
);
1809 strip_newline(lxcpath
);
1810 strip_newline(lxcname
);
1811 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1812 ERROR("Unable to find dependent container %s:%s",
1816 if (!mod_rdep(p
, inc
))
1817 ERROR("Failed to increase numsnapshots for %s:%s",
1819 lxc_container_put(p
);
1822 if (lxcpath
) free(lxcpath
);
1823 if (lxcname
) free(lxcname
);
1829 static bool has_snapshots(struct lxc_container
*c
)
1831 char path
[MAXPATHLEN
];
1836 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1838 if (ret
< 0 || ret
> MAXPATHLEN
)
1841 f
= fopen(path
, "r");
1845 ret
= fscanf(f
, "%d", &v
);
1857 // do we want the api to support --force, or leave that to the caller?
1858 static bool lxcapi_destroy(struct lxc_container
*c
)
1860 struct bdev
*r
= NULL
;
1863 if (!c
|| !lxcapi_is_defined(c
))
1866 if (container_disk_lock(c
))
1869 if (!is_stopped(c
)) {
1870 // we should queue some sort of error - in c->error_string?
1871 ERROR("container %s is not stopped", c
->name
);
1875 if (c
->lxc_conf
&& has_snapshots(c
)) {
1876 ERROR("container %s has dependent snapshots", c
->name
);
1880 if (c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
)
1881 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1883 if (r
->ops
->destroy(r
) < 0) {
1885 ERROR("Error destroying rootfs for %s", c
->name
);
1891 mod_all_rdeps(c
, false);
1893 const char *p1
= lxcapi_get_config_path(c
);
1894 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
1895 sprintf(path
, "%s/%s", p1
, c
->name
);
1896 if (lxc_rmdir_onedev(path
) < 0) {
1897 ERROR("Error destroying container directory for %s", c
->name
);
1903 container_disk_unlock(c
);
1907 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
1909 struct lxc_config_t
*config
;
1912 c
->lxc_conf
= lxc_conf_init();
1915 config
= lxc_getconfig(key
);
1918 return (0 == config
->cb(key
, v
, c
->lxc_conf
));
1921 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
1928 if (container_mem_lock(c
))
1931 b
= set_config_item_locked(c
, key
, v
);
1933 container_mem_unlock(c
);
1937 static char *lxcapi_config_file_name(struct lxc_container
*c
)
1939 if (!c
|| !c
->configfile
)
1941 return strdup(c
->configfile
);
1944 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
1946 if (!c
|| !c
->config_path
)
1948 return (const char *)(c
->config_path
);
1953 * Just recalculate the c->configfile based on the
1954 * c->config_path, which must be set.
1955 * The lxc_container must be locked or not yet public.
1957 static bool set_config_filename(struct lxc_container
*c
)
1962 if (!c
->config_path
)
1965 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1966 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
1967 newpath
= malloc(len
);
1971 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
1972 if (ret
< 0 || ret
>= len
) {
1973 fprintf(stderr
, "Error printing out config file name\n");
1979 free(c
->configfile
);
1980 c
->configfile
= newpath
;
1985 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
1989 char *oldpath
= NULL
;
1994 if (container_mem_lock(c
))
1999 ERROR("Out of memory setting new lxc path");
2005 oldpath
= c
->config_path
;
2008 /* Since we've changed the config path, we have to change the
2009 * config file name too */
2010 if (!set_config_filename(c
)) {
2011 ERROR("Out of memory setting new config filename");
2013 free(c
->config_path
);
2014 c
->config_path
= oldpath
;
2020 container_mem_unlock(c
);
2025 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2035 if (container_disk_lock(c
))
2038 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2040 container_disk_unlock(c
);
2044 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2054 if (container_disk_lock(c
))
2057 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2059 container_disk_unlock(c
);
2063 const char *lxc_get_default_config_path(void)
2065 return default_lxc_path();
2068 const char *lxc_get_default_lvm_vg(void)
2070 return default_lvm_vg();
2073 const char *lxc_get_default_lvm_thin_pool(void)
2075 return default_lvm_thin_pool();
2078 const char *lxc_get_default_zfs_root(void)
2080 return default_zfs_root();
2083 const char *lxc_get_version(void)
2085 return lxc_version();
2088 static int copy_file(char *old
, char *new)
2095 if (file_exists(new)) {
2096 ERROR("copy destination %s exists", new);
2099 ret
= stat(old
, &sbuf
);
2101 INFO("Error stat'ing %s", old
);
2106 in
= open(old
, O_RDONLY
);
2109 SYSERROR("Error opening original file %s", old
);
2113 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2116 SYSERROR("Error opening new file %s", new);
2124 len
= read(in
, buf
, 8096);
2126 SYSERROR("Error reading old file %s", old
);
2131 ret
= write(out
, buf
, len
);
2132 if (ret
< len
) { // should we retry?
2133 SYSERROR("Error: write to new file %s was interrupted", new);
2142 // we set mode, but not owner/group
2143 ret
= chmod(new, sbuf
.st_mode
);
2145 SYSERROR("Error setting mode on %s", new);
2159 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2163 struct lxc_list
*it
;
2165 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2166 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2167 char *hookname
= it
->elem
;
2168 char *fname
= strrchr(hookname
, '/');
2169 char tmppath
[MAXPATHLEN
];
2170 if (!fname
) // relative path - we don't support, but maybe we should
2172 // copy the script, and change the entry in confile
2173 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2174 c
->config_path
, c
->name
, fname
+1);
2175 if (ret
< 0 || ret
>= MAXPATHLEN
)
2177 ret
= copy_file(it
->elem
, tmppath
);
2181 it
->elem
= strdup(tmppath
);
2183 ERROR("out of memory copying hook path");
2189 c
->save_config(c
, NULL
);
2193 static void new_hwaddr(char *hwaddr
)
2197 f
= fopen("/dev/urandom", "r");
2201 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2210 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2211 rand() % 255, rand() % 255, rand() % 255);
2214 static void network_new_hwaddrs(struct lxc_container
*c
)
2216 struct lxc_list
*it
;
2218 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2219 struct lxc_netdev
*n
= it
->elem
;
2221 new_hwaddr(n
->hwaddr
);
2225 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2227 char newpath
[MAXPATHLEN
];
2228 char *oldpath
= oldc
->lxc_conf
->fstab
;
2234 char *p
= strrchr(oldpath
, '/');
2237 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2238 c
->config_path
, c
->name
, p
);
2239 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2240 ERROR("error printing new path for %s", oldpath
);
2243 if (file_exists(newpath
)) {
2244 ERROR("error: fstab file %s exists", newpath
);
2248 if (copy_file(oldpath
, newpath
) < 0) {
2249 ERROR("error: copying %s to %s", oldpath
, newpath
);
2252 free(c
->lxc_conf
->fstab
);
2253 c
->lxc_conf
->fstab
= strdup(newpath
);
2254 if (!c
->lxc_conf
->fstab
) {
2255 ERROR("error: allocating pathname");
2262 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2264 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2267 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2269 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2270 WARN("Error copying reverse dependencies");
2273 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2275 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2276 WARN("Error copying reverse dependencies");
2279 if (copy_file(path0
, path1
) < 0) {
2280 INFO("Error copying reverse dependencies");
2285 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2288 char path
[MAXPATHLEN
];
2292 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2294 if (ret
< 0 || ret
>= MAXPATHLEN
)
2297 f
= fopen(path
, "a");
2302 // if anything goes wrong, just return an error
2303 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2312 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2313 const char *newtype
, int flags
, const char *bdevdata
, unsigned long newsize
)
2318 bdev
= bdev_copy(c0
->lxc_conf
->rootfs
.path
, c0
->name
, c
->name
,
2319 c0
->config_path
, c
->config_path
, newtype
, !!(flags
& LXC_CLONE_SNAPSHOT
),
2320 bdevdata
, newsize
, &need_rdep
);
2322 ERROR("Error copying storage");
2325 free(c
->lxc_conf
->rootfs
.path
);
2326 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2328 if (!c
->lxc_conf
->rootfs
.path
) {
2329 ERROR("Out of memory while setting storage path");
2332 if (flags
& LXC_CLONE_SNAPSHOT
)
2333 copy_rdepends(c
, c0
);
2335 if (!add_rdepends(c
, c0
))
2336 WARN("Error adding reverse dependency from %s to %s",
2340 mod_all_rdeps(c
, true);
2345 static int clone_update_rootfs(struct lxc_container
*c0
,
2346 struct lxc_container
*c
, int flags
,
2350 char path
[MAXPATHLEN
];
2354 struct lxc_conf
*conf
= c
->lxc_conf
;
2356 /* update hostname in rootfs */
2357 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2363 return wait_for_pid(pid
);
2365 process_unlock(); // we're no longer sharing
2366 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2369 if (strcmp(bdev
->type
, "dir") != 0) {
2370 if (unshare(CLONE_NEWNS
) < 0) {
2371 ERROR("error unsharing mounts");
2374 if (bdev
->ops
->mount(bdev
) < 0)
2376 } else { // TODO come up with a better way
2379 bdev
->dest
= strdup(bdev
->src
);
2382 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2383 /* Start of environment variable setup for hooks */
2384 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2385 SYSERROR("failed to set environment variable for source container name");
2387 if (setenv("LXC_NAME", c
->name
, 1)) {
2388 SYSERROR("failed to set environment variable for container name");
2390 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2391 SYSERROR("failed to set environment variable for config path");
2393 if (setenv("LXC_ROOTFS_MOUNT", conf
->rootfs
.mount
, 1)) {
2394 SYSERROR("failed to set environment variable for rootfs mount");
2396 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2397 SYSERROR("failed to set environment variable for rootfs mount");
2400 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2401 ERROR("Error executing clone hook for %s", c
->name
);
2406 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2407 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2408 if (ret
< 0 || ret
>= MAXPATHLEN
)
2410 if (!file_exists(path
))
2412 if (!(fout
= fopen(path
, "w"))) {
2413 SYSERROR("unable to open %s: ignoring\n", path
);
2416 if (fprintf(fout
, "%s", c
->name
) < 0)
2418 if (fclose(fout
) < 0)
2425 * We want to support:
2426 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2427 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2429 -s [ implies overlayfs]
2433 only rootfs gets converted (copied/snapshotted) on clone.
2436 static int create_file_dirname(char *path
)
2438 char *p
= strrchr(path
, '/');
2444 ret
= mkdir(path
, 0755);
2445 if (ret
&& errno
!= EEXIST
)
2446 SYSERROR("creating container path %s\n", path
);
2451 struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2452 const char *lxcpath
, int flags
,
2453 const char *bdevtype
, const char *bdevdata
, unsigned long newsize
,
2456 struct lxc_container
*c2
= NULL
;
2457 char newpath
[MAXPATHLEN
];
2458 int ret
, storage_copied
= 0;
2462 if (!c
|| !c
->is_defined(c
))
2465 if (container_mem_lock(c
))
2468 if (!is_stopped(c
)) {
2469 ERROR("error: Original container (%s) is running", c
->name
);
2473 // Make sure the container doesn't yet exist.
2474 n
= newname
? newname
: c
->name
;
2475 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2476 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2477 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2478 SYSERROR("clone: failed making config pathname");
2481 if (file_exists(newpath
)) {
2482 ERROR("error: clone: %s exists", newpath
);
2486 ret
= create_file_dirname(newpath
);
2487 if (ret
< 0 && errno
!= EEXIST
) {
2488 ERROR("Error creating container dir for %s", newpath
);
2492 // copy the configuration, tweak it as needed,
2494 fout
= fopen(newpath
, "w");
2497 SYSERROR("open %s", newpath
);
2500 write_config(fout
, c
->lxc_conf
);
2505 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2506 if (mkdir(newpath
, 0755) < 0) {
2507 SYSERROR("error creating %s", newpath
);
2511 c2
= lxc_container_new(n
, l
);
2513 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2518 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2519 ERROR("Error setting new hostname");
2524 // copy hooks if requested
2525 if (flags
& LXC_CLONE_COPYHOOKS
) {
2526 ret
= copyhooks(c
, c2
);
2528 ERROR("error copying hooks");
2533 if (copy_fstab(c
, c2
) < 0) {
2534 ERROR("error copying fstab");
2539 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
2540 network_new_hwaddrs(c2
);
2542 // copy/snapshot rootfs's
2543 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2547 // We've now successfully created c2's storage, so clear it out if we
2551 if (!c2
->save_config(c2
, NULL
))
2554 if (clone_update_rootfs(c
, c2
, flags
, hookargs
) < 0)
2557 // TODO: update c's lxc.snapshot = count
2558 container_mem_unlock(c
);
2562 container_mem_unlock(c
);
2564 if (!storage_copied
)
2565 c2
->lxc_conf
->rootfs
.path
= NULL
;
2567 lxc_container_put(c2
);
2573 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
)
2578 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2581 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2583 lxc_attach_command_t command
;
2590 command
.program
= (char*)program
;
2591 command
.argv
= (char**)argv
;
2592 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2597 return lxc_wait_for_pid_status(pid
);
2600 int get_next_index(const char *lxcpath
, char *cname
)
2606 fname
= alloca(strlen(lxcpath
) + 20);
2608 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2609 ret
= stat(fname
, &sb
);
2616 static int lxcapi_snapshot(struct lxc_container
*c
, char *commentfile
)
2619 struct lxc_container
*c2
;
2620 char snappath
[MAXPATHLEN
], newname
[20];
2622 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2623 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2624 if (ret
< 0 || ret
>= MAXPATHLEN
)
2626 i
= get_next_index(snappath
, c
->name
);
2628 if (mkdir_p(snappath
, 0755) < 0) {
2629 ERROR("Failed to create snapshot directory %s", snappath
);
2633 ret
= snprintf(newname
, 20, "snap%d", i
);
2634 if (ret
< 0 || ret
>= 20)
2637 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
;
2638 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2640 ERROR("clone of %s:%s failed\n", c
->config_path
, c
->name
);
2644 lxc_container_put(c2
);
2646 // Now write down the creation time
2653 tm_info
= localtime(&timer
);
2655 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2657 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2658 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2660 f
= fopen(dfnam
, "w");
2663 ERROR("Failed to open %s\n", dfnam
);
2666 if (fprintf(f
, "%s", buffer
) < 0) {
2667 SYSERROR("Writing timestamp");
2675 SYSERROR("Writing timestamp");
2680 // $p / $name / comment \0
2681 int len
= strlen(snappath
) + strlen(newname
) + 10;
2682 char *path
= alloca(len
);
2683 sprintf(path
, "%s/%s/comment", snappath
, newname
);
2684 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
2690 static void lxcsnap_free(struct lxc_snapshot
*s
)
2694 if (s
->comment_pathname
)
2695 free(s
->comment_pathname
);
2702 static char *get_snapcomment_path(char* snappath
, char *name
)
2704 // $snappath/$name/comment
2705 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
2706 char *s
= malloc(len
);
2709 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
2710 if (ret
< 0 || ret
>= len
) {
2718 static char *get_timestamp(char* snappath
, char *name
)
2720 char path
[MAXPATHLEN
], *s
= NULL
;
2724 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
2725 if (ret
< 0 || ret
>= MAXPATHLEN
)
2728 fin
= fopen(path
, "r");
2732 (void) fseek(fin
, 0, SEEK_END
);
2734 (void) fseek(fin
, 0, SEEK_SET
);
2739 if (fread(s
, 1, len
, fin
) != len
) {
2740 SYSERROR("reading timestamp");
2752 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
2754 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
2755 int dirlen
, count
= 0, ret
;
2756 struct dirent dirent
, *direntp
;
2757 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
2760 if (!c
|| !lxcapi_is_defined(c
))
2762 // snappath is ${lxcpath}snaps/${lxcname}/
2763 dirlen
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2764 if (dirlen
< 0 || dirlen
>= MAXPATHLEN
) {
2765 ERROR("path name too long");
2769 dir
= opendir(snappath
);
2772 INFO("failed to open %s - assuming no snapshots", snappath
);
2776 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2780 if (!strcmp(direntp
->d_name
, "."))
2783 if (!strcmp(direntp
->d_name
, ".."))
2786 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
2787 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2788 ERROR("pathname too long");
2791 if (!file_exists(path2
))
2793 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
2795 SYSERROR("Out of memory");
2799 snaps
[count
].free
= lxcsnap_free
;
2800 snaps
[count
].name
= strdup(direntp
->d_name
);
2801 if (!snaps
[count
].name
)
2803 snaps
[count
].lxcpath
= strdup(snappath
);
2804 if (!snaps
[count
].lxcpath
) {
2805 free(snaps
[count
].name
);
2808 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
2809 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
2815 WARN("failed to close directory");
2824 for (i
=0; i
<count
; i
++)
2825 lxcsnap_free(&snaps
[i
]);
2830 WARN("failed to close directory");
2835 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, char *snapname
, char *newname
)
2837 char clonelxcpath
[MAXPATHLEN
];
2839 struct lxc_container
*snap
, *rest
;
2843 if (!c
|| !c
->name
|| !c
->config_path
)
2846 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2848 ERROR("Failed to find original backing store type");
2854 if (strcmp(c
->name
, newname
) == 0) {
2855 if (!lxcapi_destroy(c
)) {
2856 ERROR("Could not destroy existing container %s", newname
);
2861 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2862 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2866 // how should we lock this?
2868 snap
= lxc_container_new(snapname
, clonelxcpath
);
2869 if (!snap
|| !lxcapi_is_defined(snap
)) {
2870 ERROR("Could not open snapshot %s", snapname
);
2871 if (snap
) lxc_container_put(snap
);
2876 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, 0, bdev
->type
, NULL
, 0, NULL
);
2878 if (rest
&& lxcapi_is_defined(rest
))
2881 lxc_container_put(rest
);
2882 lxc_container_put(snap
);
2886 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, char *snapname
)
2889 char clonelxcpath
[MAXPATHLEN
];
2890 struct lxc_container
*snap
= NULL
;
2892 if (!c
|| !c
->name
|| !c
->config_path
)
2895 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2896 if (ret
< 0 || ret
>= MAXPATHLEN
)
2899 snap
= lxc_container_new(snapname
, clonelxcpath
);
2900 if (!snap
|| !lxcapi_is_defined(snap
)) {
2901 ERROR("Could not find snapshot %s", snapname
);
2905 if (!lxcapi_destroy(snap
)) {
2906 ERROR("Could not destroy snapshot %s", snapname
);
2909 lxc_container_put(snap
);
2914 lxc_container_put(snap
);
2918 static bool lxcapi_may_control(struct lxc_container
*c
)
2920 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
2923 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
2933 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
2937 ERROR("Memory allocation error.");
2942 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
2947 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
2949 struct lxc_container
*c
;
2951 c
= malloc(sizeof(*c
));
2953 fprintf(stderr
, "failed to malloc lxc_container\n");
2956 memset(c
, 0, sizeof(*c
));
2959 c
->config_path
= strdup(configpath
);
2961 c
->config_path
= strdup(default_lxc_path());
2963 if (!c
->config_path
) {
2964 fprintf(stderr
, "Out of memory");
2968 remove_trailing_slashes(c
->config_path
);
2969 c
->name
= malloc(strlen(name
)+1);
2971 fprintf(stderr
, "Error allocating lxc_container name\n");
2974 strcpy(c
->name
, name
);
2977 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
2978 fprintf(stderr
, "failed to create lock\n");
2982 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
2983 fprintf(stderr
, "failed to alloc privlock\n");
2987 if (!set_config_filename(c
)) {
2988 fprintf(stderr
, "Error allocating config file pathname\n");
2992 if (file_exists(c
->configfile
))
2993 lxcapi_load_config(c
, NULL
);
2995 if (ongoing_create(c
) == 2) {
2996 ERROR("Error: %s creation was not completed", c
->name
);
2998 lxc_conf_free(c
->lxc_conf
);
3002 // assign the member functions
3003 c
->is_defined
= lxcapi_is_defined
;
3004 c
->state
= lxcapi_state
;
3005 c
->is_running
= lxcapi_is_running
;
3006 c
->freeze
= lxcapi_freeze
;
3007 c
->unfreeze
= lxcapi_unfreeze
;
3008 c
->console
= lxcapi_console
;
3009 c
->console_getfd
= lxcapi_console_getfd
;
3010 c
->init_pid
= lxcapi_init_pid
;
3011 c
->load_config
= lxcapi_load_config
;
3012 c
->want_daemonize
= lxcapi_want_daemonize
;
3013 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3014 c
->start
= lxcapi_start
;
3015 c
->startl
= lxcapi_startl
;
3016 c
->stop
= lxcapi_stop
;
3017 c
->config_file_name
= lxcapi_config_file_name
;
3018 c
->wait
= lxcapi_wait
;
3019 c
->set_config_item
= lxcapi_set_config_item
;
3020 c
->destroy
= lxcapi_destroy
;
3021 c
->save_config
= lxcapi_save_config
;
3022 c
->get_keys
= lxcapi_get_keys
;
3023 c
->create
= lxcapi_create
;
3024 c
->createl
= lxcapi_createl
;
3025 c
->shutdown
= lxcapi_shutdown
;
3026 c
->reboot
= lxcapi_reboot
;
3027 c
->clear_config_item
= lxcapi_clear_config_item
;
3028 c
->get_config_item
= lxcapi_get_config_item
;
3029 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3030 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3031 c
->get_config_path
= lxcapi_get_config_path
;
3032 c
->set_config_path
= lxcapi_set_config_path
;
3033 c
->clone
= lxcapi_clone
;
3034 c
->get_interfaces
= lxcapi_get_interfaces
;
3035 c
->get_ips
= lxcapi_get_ips
;
3036 c
->attach
= lxcapi_attach
;
3037 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3038 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3039 c
->snapshot
= lxcapi_snapshot
;
3040 c
->snapshot_list
= lxcapi_snapshot_list
;
3041 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3042 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3043 c
->may_control
= lxcapi_may_control
;
3045 /* we'll allow the caller to update these later */
3046 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3047 fprintf(stderr
, "failed to open log\n");
3054 lxc_container_free(c
);
3058 int lxc_get_wait_states(const char **states
)
3063 for (i
=0; i
<MAX_STATE
; i
++)
3064 states
[i
] = lxc_state2str(i
);
3069 * These next two could probably be done smarter with reusing a common function
3070 * with different iterators and tests...
3072 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3075 int i
, cfound
= 0, nfound
= 0;
3076 struct dirent dirent
, *direntp
;
3077 struct lxc_container
*c
;
3080 lxcpath
= default_lxc_path();
3083 dir
= opendir(lxcpath
);
3087 SYSERROR("opendir on lxcpath");
3096 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3099 if (!strcmp(direntp
->d_name
, "."))
3101 if (!strcmp(direntp
->d_name
, ".."))
3104 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3108 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3118 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3120 INFO("Container %s:%s has a config but could not be loaded",
3121 lxcpath
, direntp
->d_name
);
3123 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3127 if (!lxcapi_is_defined(c
)) {
3128 INFO("Container %s:%s has a config but is not defined",
3129 lxcpath
, direntp
->d_name
);
3131 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3133 lxc_container_put(c
);
3137 if (!add_to_clist(cret
, c
, nfound
, true)) {
3138 lxc_container_put(c
);
3150 if (names
&& *names
) {
3151 for (i
=0; i
<cfound
; i
++)
3155 if (cret
&& *cret
) {
3156 for (i
=0; i
<nfound
; i
++)
3157 lxc_container_put((*cret
)[i
]);
3166 int list_active_containers(const char *lxcpath
, char ***nret
,
3167 struct lxc_container
***cret
)
3169 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3172 char **ct_name
= NULL
;
3174 struct lxc_container
*c
;
3177 lxcpath
= default_lxc_path();
3178 lxcpath_len
= strlen(lxcpath
);
3186 FILE *f
= fopen("/proc/net/unix", "r");
3191 while (getline(&line
, &len
, f
) != -1) {
3192 char *p
= strrchr(line
, ' '), *p2
;
3199 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3205 // Now p is the start of lxc_name
3207 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3211 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3214 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3215 goto free_cret_list
;
3222 c
= lxc_container_new(p
, lxcpath
);
3224 INFO("Container %s:%s is running but could not be loaded",
3226 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3231 * If this is an anonymous container, then is_defined *can*
3232 * return false. So we don't do that check. Count on the
3233 * fact that the command socket exists.
3236 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3237 lxc_container_put(c
);
3238 goto free_cret_list
;
3243 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3252 if (cret
&& *cret
) {
3253 for (i
= 0; i
< cret_cnt
; i
++)
3254 lxc_container_put((*cret
)[i
]);
3260 for (i
= 0; i
< ct_name_cnt
; i
++)
3275 int list_all_containers(const char *lxcpath
, char ***nret
,
3276 struct lxc_container
***cret
)
3278 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3281 struct lxc_container
**ct_list
= NULL
;
3283 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3287 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3288 if (active_cnt
< 0) {
3293 for (i
= 0; i
< active_cnt
; i
++) {
3294 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3295 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3297 goto free_active_name
;
3301 free(active_name
[i
]);
3302 active_name
[i
] = NULL
;
3308 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3309 struct lxc_container
*c
;
3311 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3313 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3314 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3318 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3319 lxc_container_put(c
);
3338 for (i
= 0; i
< ct_list_cnt
; i
++) {
3339 lxc_container_put(ct_list
[i
]);
3345 for (i
= 0; i
< active_cnt
; i
++) {
3347 free(active_name
[i
]);
3353 for (i
= 0; i
< ct_cnt
; i
++) {