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>
54 #include "namespace.h"
60 #include <../include/ifaddrs.h>
63 #define MAX_BUFFER 4096
65 #define NOT_SUPPORTED_ERROR "the requested function %s is not currently supported with unprivileged containers"
67 lxc_log_define(lxc_container
, lxc
);
69 inline static bool am_unpriv() {
70 return geteuid() != 0;
73 static bool file_exists(const char *f
)
77 return stat(f
, &statbuf
) == 0;
80 static bool config_file_exists(const char *lxcpath
, const char *cname
)
82 /* $lxcpath + '/' + $cname + '/config' + \0 */
83 int ret
, len
= strlen(lxcpath
) + strlen(cname
) + 9;
84 char *fname
= alloca(len
);
86 ret
= snprintf(fname
, len
, "%s/%s/config", lxcpath
, cname
);
87 if (ret
< 0 || ret
>= len
)
90 return file_exists(fname
);
94 * A few functions to help detect when a container creation failed.
95 * If a container creation was killed partway through, then trying
96 * to actually start that container could harm the host. We detect
97 * this by creating a 'partial' file under the container directory,
98 * and keeping an advisory lock. When container creation completes,
99 * we remove that file. When we load or try to start a container, if
100 * we find that file, without a flock, we remove the container.
102 static int ongoing_create(struct lxc_container
*c
)
104 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
105 char *path
= alloca(len
);
109 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
110 if (ret
< 0 || ret
>= len
) {
111 ERROR("Error writing partial pathname");
115 if (!file_exists(path
))
117 fd
= open(path
, O_RDWR
);
119 // give benefit of the doubt
120 SYSERROR("Error opening partial file");
124 lk
.l_whence
= SEEK_SET
;
128 if (fcntl(fd
, F_GETLK
, &lk
) == 0 && lk
.l_pid
!= -1) {
129 // create is still ongoing
133 // create completed but partial is still there.
138 static 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");
151 if ((fd
=open(path
, O_RDWR
| O_CREAT
| O_EXCL
, 0755)) < 0) {
152 SYSERROR("Erorr creating partial file");
156 lk
.l_whence
= SEEK_SET
;
159 if (fcntl(fd
, F_SETLKW
, &lk
) < 0) {
160 SYSERROR("Error locking partial file %s", path
);
168 static void remove_partial(struct lxc_container
*c
, int fd
)
170 // $lxcpath + '/' + $name + '/partial' + \0
171 int len
= strlen(c
->config_path
) + strlen(c
->name
) + 10;
172 char *path
= alloca(len
);
176 ret
= snprintf(path
, len
, "%s/%s/partial", c
->config_path
, c
->name
);
177 if (ret
< 0 || ret
>= len
) {
178 ERROR("Error writing partial pathname");
181 if (unlink(path
) < 0)
182 SYSERROR("Error unlink partial file %s", path
);
186 * 1. container_mem_lock(c) protects the struct lxc_container from multiple threads.
187 * 2. container_disk_lock(c) protects the on-disk container data - in particular the
188 * container configuration file.
189 * The container_disk_lock also takes the container_mem_lock.
190 * 3. thread_mutex protects process data (ex: fd table) from multiple threads.
191 * NOTHING mutexes two independent programs with their own struct
192 * lxc_container for the same c->name, between API calls. For instance,
193 * c->config_read(); c->start(); Between those calls, data on disk
194 * could change (which shouldn't bother the caller unless for instance
195 * the rootfs get moved). c->config_read(); update; c->config_write();
196 * Two such updaters could race. The callers should therefore check their
197 * results. Trying to prevent that would necessarily expose us to deadlocks
198 * due to hung callers. So I prefer to keep the locks only within our own
199 * functions, not across functions.
201 * If you're going to clone while holding a lxccontainer, increment
202 * c->numthreads (under privlock) before forking. When deleting,
203 * decrement numthreads under privlock, then if it hits 0 you can delete.
204 * Do not ever use a lxccontainer whose numthreads you did not bump.
207 static void lxc_container_free(struct lxc_container
*c
)
214 c
->configfile
= NULL
;
216 if (c
->error_string
) {
217 free(c
->error_string
);
218 c
->error_string
= NULL
;
221 lxc_putlock(c
->slock
);
225 lxc_putlock(c
->privlock
);
233 lxc_conf_free(c
->lxc_conf
);
236 if (c
->config_path
) {
237 free(c
->config_path
);
238 c
->config_path
= NULL
;
244 * Consider the following case:
245 freer | racing get()er
246 ==================================================================
247 lxc_container_put() | lxc_container_get()
248 \ lxclock(c->privlock) | c->numthreads < 1? (no)
249 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
251 \ lxc_container_free() | \ lxclock() returns
252 | \ c->numthreads < 1 -> return 0
254 \ \ sem_destroy(privlock) |
256 * When the get()er checks numthreads the first time, one of the following
258 * 1. freer has set numthreads = 0. get() returns 0
259 * 2. freer is between lxclock and setting numthreads to 0. get()er will
260 * sem_wait on privlock, get lxclock after freer() drops it, then see
261 * numthreads is 0 and exit without touching lxclock again..
262 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
263 * will see --numthreads = 1 and not call lxc_container_free().
266 int lxc_container_get(struct lxc_container
*c
)
271 // if someone else has already started freeing the container, don't
272 // try to take the lock, which may be invalid
273 if (c
->numthreads
< 1)
276 if (container_mem_lock(c
))
278 if (c
->numthreads
< 1) {
279 // bail without trying to unlock, bc the privlock is now probably
284 container_mem_unlock(c
);
288 int lxc_container_put(struct lxc_container
*c
)
292 if (container_mem_lock(c
))
294 if (--c
->numthreads
< 1) {
295 container_mem_unlock(c
);
296 lxc_container_free(c
);
299 container_mem_unlock(c
);
303 static bool lxcapi_is_defined(struct lxc_container
*c
)
312 if (container_mem_lock(c
))
316 statret
= stat(c
->configfile
, &statbuf
);
322 container_mem_unlock(c
);
326 static const char *lxcapi_state(struct lxc_container
*c
)
332 s
= lxc_getstate(c
->name
, c
->config_path
);
333 return lxc_state2str(s
);
336 static bool is_stopped(struct lxc_container
*c
)
339 s
= lxc_getstate(c
->name
, c
->config_path
);
340 return (s
== STOPPED
);
343 static bool lxcapi_is_running(struct lxc_container
*c
)
350 if (!s
|| strcmp(s
, "STOPPED") == 0)
355 static bool lxcapi_freeze(struct lxc_container
*c
)
361 ret
= lxc_freeze(c
->name
, c
->config_path
);
367 static bool lxcapi_unfreeze(struct lxc_container
*c
)
373 ret
= lxc_unfreeze(c
->name
, c
->config_path
);
379 static int lxcapi_console_getfd(struct lxc_container
*c
, int *ttynum
, int *masterfd
)
385 ttyfd
= lxc_console_getfd(c
, ttynum
, masterfd
);
389 static int lxcapi_console(struct lxc_container
*c
, int ttynum
, int stdinfd
,
390 int stdoutfd
, int stderrfd
, int escape
)
392 return lxc_console(c
, ttynum
, stdinfd
, stdoutfd
, stderrfd
, escape
);
395 static pid_t
lxcapi_init_pid(struct lxc_container
*c
)
400 return lxc_cmd_get_init_pid(c
->name
, c
->config_path
);
403 static bool load_config_locked(struct lxc_container
*c
, const char *fname
)
406 c
->lxc_conf
= lxc_conf_init();
407 if (c
->lxc_conf
&& !lxc_config_read(fname
, c
->lxc_conf
))
412 static bool lxcapi_load_config(struct lxc_container
*c
, const char *alt_file
)
414 bool ret
= false, need_disklock
= false;
420 fname
= c
->configfile
;
426 * If we're reading something other than the container's config,
427 * we only need to lock the in-memory container. If loading the
428 * container's config file, take the disk lock.
430 if (strcmp(fname
, c
->configfile
) == 0)
431 need_disklock
= true;
434 lret
= container_disk_lock(c
);
436 lret
= container_mem_lock(c
);
440 ret
= load_config_locked(c
, fname
);
443 container_disk_unlock(c
);
445 container_mem_unlock(c
);
449 static bool lxcapi_want_daemonize(struct lxc_container
*c
, bool state
)
451 if (!c
|| !c
->lxc_conf
)
453 if (container_mem_lock(c
)) {
454 ERROR("Error getting mem lock");
457 c
->daemonize
= state
;
458 /* daemonize implies close_all_fds so set it */
460 c
->lxc_conf
->close_all_fds
= 1;
461 container_mem_unlock(c
);
465 static bool lxcapi_want_close_all_fds(struct lxc_container
*c
, bool state
)
467 if (!c
|| !c
->lxc_conf
)
469 if (container_mem_lock(c
)) {
470 ERROR("Error getting mem lock");
473 c
->lxc_conf
->close_all_fds
= state
;
474 container_mem_unlock(c
);
478 static bool lxcapi_wait(struct lxc_container
*c
, const char *state
, int timeout
)
485 ret
= lxc_wait(c
->name
, state
, timeout
, c
->config_path
);
490 static bool wait_on_daemonized_start(struct lxc_container
*c
, int pid
)
492 /* we'll probably want to make this timeout configurable? */
493 int timeout
= 5, ret
, status
;
496 * our child is going to fork again, then exit. reap the
499 ret
= waitpid(pid
, &status
, 0);
500 if (ret
== -1 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
501 DEBUG("failed waiting for first dual-fork child");
502 return lxcapi_wait(c
, "RUNNING", timeout
);
505 static bool am_single_threaded(void)
507 struct dirent dirent
, *direntp
;
511 dir
= opendir("/proc/self/task");
513 INFO("failed to open /proc/self/task");
517 while (!readdir_r(dir
, &dirent
, &direntp
)) {
521 if (!strcmp(direntp
->d_name
, "."))
524 if (!strcmp(direntp
->d_name
, ".."))
534 * I can't decide if it'd be more convenient for callers if we accept '...',
535 * or a null-terminated array (i.e. execl vs execv)
537 static bool lxcapi_start(struct lxc_container
*c
, int useinit
, char * const argv
[])
540 struct lxc_conf
*conf
;
541 bool daemonize
= false;
542 char *default_args
[] = {
547 /* container exists */
550 /* container has been setup */
554 if ((ret
= ongoing_create(c
)) < 0) {
555 ERROR("Error checking for incomplete creation");
559 ERROR("Error: %s creation was not completed", c
->name
);
562 } else if (ret
== 1) {
563 ERROR("Error: creation of %s is ongoing", c
->name
);
567 /* is this app meant to be run through lxcinit, as in lxc-execute? */
568 if (useinit
&& !argv
)
571 if (container_mem_lock(c
))
574 daemonize
= c
->daemonize
;
575 container_mem_unlock(c
);
578 ret
= lxc_execute(c
->name
, argv
, 1, conf
, c
->config_path
);
579 return ret
== 0 ? true : false;
586 * say, I'm not sure - what locks do we want here? Any?
587 * Is liblxc's locking enough here to protect the on disk
588 * container? We don't want to exclude things like lxc_info
589 * while container is running...
592 if (!lxc_container_get(c
))
594 lxc_monitord_spawn(c
->config_path
);
598 lxc_container_put(c
);
602 return wait_on_daemonized_start(c
, pid
);
604 /* second fork to be reparented by init */
607 SYSERROR("Error doing dual-fork");
612 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
614 SYSERROR("Error chdir()ing to /.");
620 open("/dev/zero", O_RDONLY
);
621 open("/dev/null", O_RDWR
);
622 open("/dev/null", O_RDWR
);
625 if (!am_single_threaded()) {
626 ERROR("Cannot start non-daemonized container when threaded");
633 ret
= lxc_start(c
->name
, argv
, conf
, c
->config_path
);
636 INFO("container requested reboot");
642 lxc_container_put(c
);
643 exit (ret
== 0 ? true : false);
645 return (ret
== 0 ? true : false);
650 * note there MUST be an ending NULL
652 static bool lxcapi_startl(struct lxc_container
*c
, int useinit
, ...)
655 char **inargs
= NULL
;
658 /* container exists */
662 va_start(ap
, useinit
);
663 inargs
= lxc_va_arg_list_to_argv(ap
, 0, 1);
667 ERROR("Memory allocation error.");
671 /* pass NULL if no arguments were supplied */
672 bret
= lxcapi_start(c
, useinit
, *inargs
? inargs
: NULL
);
677 for (arg
= inargs
; *arg
; arg
++)
685 static bool lxcapi_stop(struct lxc_container
*c
)
692 ret
= lxc_cmd_stop(c
->name
, c
->config_path
);
698 * create the standard expected container dir
700 static bool create_container_dir(struct lxc_container
*c
)
705 len
= strlen(c
->config_path
) + strlen(c
->name
) + 2;
709 ret
= snprintf(s
, len
, "%s/%s", c
->config_path
, c
->name
);
710 if (ret
< 0 || ret
>= len
) {
714 ret
= mkdir(s
, 0755);
719 SYSERROR("failed to create container path for %s\n", c
->name
);
725 static const char *lxcapi_get_config_path(struct lxc_container
*c
);
726 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
);
729 * do_bdev_create: thin wrapper around bdev_create(). Like bdev_create(),
730 * it returns a mounted bdev on success, NULL on error.
732 static struct bdev
*do_bdev_create(struct lxc_container
*c
, const char *type
,
733 struct bdev_specs
*specs
)
740 /* rootfs.path or lxcpath/lxcname/rootfs */
741 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0) {
742 const char *rpath
= c
->lxc_conf
->rootfs
.path
;
743 len
= strlen(rpath
) + 1;
745 ret
= snprintf(dest
, len
, "%s", rpath
);
747 const char *lxcpath
= lxcapi_get_config_path(c
);
748 len
= strlen(c
->name
) + strlen(lxcpath
) + 9;
750 ret
= snprintf(dest
, len
, "%s/%s/rootfs", lxcpath
, c
->name
);
752 if (ret
< 0 || ret
>= len
)
755 bdev
= bdev_create(dest
, type
, c
->name
, specs
);
757 ERROR("Failed to create backing store type %s\n", type
);
761 lxcapi_set_config_item(c
, "lxc.rootfs", bdev
->src
);
763 /* if we are not root, chown the rootfs dir to root in the
766 if (geteuid() != 0) {
767 if (chown_mapped_root(bdev
->dest
, c
->lxc_conf
) < 0) {
768 ERROR("Error chowning %s to container root\n", bdev
->dest
);
778 * Given the '-t' template option to lxc-create, figure out what to
779 * do. If the template is a full executable path, use that. If it
780 * is something like 'sshd', then return $templatepath/lxc-sshd.
781 * On success return the template, on error return NULL.
783 static char *get_template_path(const char *t
)
788 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
793 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
797 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
798 if (ret
< 0 || ret
>= len
) {
802 if (access(tpath
, X_OK
) < 0) {
803 SYSERROR("bad template: %s\n", t
);
811 static char *lxcbasename(char *path
)
813 char *p
= path
+ strlen(path
) - 1;
814 while (*p
!= '/' && p
> path
)
819 static bool create_run_template(struct lxc_container
*c
, char *tpath
, bool quiet
,
829 SYSERROR("failed to fork task for container creation template\n");
833 if (pid
== 0) { // child
834 char *patharg
, *namearg
, *rootfsarg
, *src
;
835 struct bdev
*bdev
= NULL
;
837 int ret
, len
, nargs
= 0;
839 struct lxc_conf
*conf
= c
->lxc_conf
;
845 open("/dev/zero", O_RDONLY
);
846 open("/dev/null", O_RDWR
);
847 open("/dev/null", O_RDWR
);
850 src
= c
->lxc_conf
->rootfs
.path
;
852 * for an overlayfs create, what the user wants is the template to fill
853 * in what will become the readonly lower layer. So don't mount for
856 if (strncmp(src
, "overlayfs:", 10) == 0) {
857 src
= overlayfs_getlower(src
+10);
859 bdev
= bdev_init(src
, c
->lxc_conf
->rootfs
.mount
, NULL
);
861 ERROR("Error opening rootfs");
865 if (geteuid() == 0) {
866 if (unshare(CLONE_NEWNS
) < 0) {
867 ERROR("error unsharing mounts");
870 if (detect_shared_rootfs()) {
871 if (mount("", "", NULL
, MS_SLAVE
|MS_REC
, 0)) {
872 SYSERROR("Failed to make / rslave to run template");
873 ERROR("Continuing...");
877 if (strcmp(bdev
->type
, "dir") != 0) {
878 if (geteuid() != 0) {
879 ERROR("non-root users can only create directory-backed containers");
882 if (bdev
->ops
->mount(bdev
) < 0) {
883 ERROR("Error mounting rootfs");
886 } else { // TODO come up with a better way here!
889 bdev
->dest
= strdup(bdev
->src
);
893 * create our new array, pre-pend the template name and
897 for (nargs
= 0; argv
[nargs
]; nargs
++) ;
898 nargs
+= 4; // template, path, rootfs and name args
900 newargv
= malloc(nargs
* sizeof(*newargv
));
903 newargv
[0] = lxcbasename(tpath
);
905 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("--path=") + 2;
906 patharg
= malloc(len
);
909 ret
= snprintf(patharg
, len
, "--path=%s/%s", c
->config_path
, c
->name
);
910 if (ret
< 0 || ret
>= len
)
912 newargv
[1] = patharg
;
913 len
= strlen("--name=") + strlen(c
->name
) + 1;
914 namearg
= malloc(len
);
917 ret
= snprintf(namearg
, len
, "--name=%s", c
->name
);
918 if (ret
< 0 || ret
>= len
)
920 newargv
[2] = namearg
;
922 len
= strlen("--rootfs=") + 1 + strlen(bdev
->dest
);
923 rootfsarg
= malloc(len
);
926 ret
= snprintf(rootfsarg
, len
, "--rootfs=%s", bdev
->dest
);
927 if (ret
< 0 || ret
>= len
)
929 newargv
[3] = rootfsarg
;
931 /* add passed-in args */
933 for (i
= 4; i
< nargs
; i
++)
934 newargv
[i
] = argv
[i
-4];
936 /* add trailing NULL */
938 newargv
= realloc(newargv
, nargs
* sizeof(*newargv
));
941 newargv
[nargs
- 1] = NULL
;
944 * If we're running the template in a mapped userns, then
945 * we prepend the template command with:
946 * lxc-usernsexec <-m map1> ... <-m mapn> --
947 * and we append "--mapped-uid x", where x is the mapped uid
950 if (geteuid() != 0 && !lxc_list_empty(&conf
->id_map
)) {
953 char **n2
= malloc(n2args
* sizeof(*n2
));
958 SYSERROR("out of memory");
962 tpath
= "lxc-usernsexec";
963 n2
[0] = "lxc-usernsexec";
964 lxc_list_for_each(it
, &conf
->id_map
) {
967 n2
= realloc(n2
, n2args
* sizeof(char *));
971 n2
[n2args
-1] = malloc(200);
974 ret
= snprintf(n2
[n2args
-1], 200, "%c:%lu:%lu:%lu",
975 map
->idtype
== ID_TYPE_UID
? 'u' : 'g',
976 map
->nsid
, map
->hostid
, map
->range
);
977 if (ret
< 0 || ret
>= 200)
980 int hostid_mapped
= mapped_hostid(geteuid(), conf
);
981 int extraargs
= hostid_mapped
>= 0 ? 1 : 3;
982 n2
= realloc(n2
, (nargs
+ n2args
+ extraargs
) * sizeof(char *));
985 if (hostid_mapped
< 0) {
986 hostid_mapped
= find_unmapped_nsuid(conf
);
988 if (hostid_mapped
< 0) {
989 ERROR("Could not find free uid to map");
992 n2
[n2args
++] = malloc(200);
994 SYSERROR("out of memory");
997 ret
= snprintf(n2
[n2args
-1], 200, "u:%d:%d:1",
998 hostid_mapped
, geteuid());
999 if (ret
< 0 || ret
>= 200) {
1000 ERROR("string too long");
1004 n2
[n2args
++] = "--";
1005 for (i
= 0; i
< nargs
; i
++)
1006 n2
[i
+ n2args
] = newargv
[i
];
1008 // Finally add "--mapped-uid $uid" to tell template what to chown
1011 n2
= realloc(n2
, n2args
* sizeof(char *));
1013 SYSERROR("out of memory");
1016 // note n2[n2args-1] is NULL
1017 n2
[n2args
-3] = "--mapped-uid";
1018 snprintf(txtuid
, 20, "%d", hostid_mapped
);
1019 n2
[n2args
-2] = txtuid
;
1020 n2
[n2args
-1] = NULL
;
1025 execvp(tpath
, newargv
);
1026 SYSERROR("failed to execute template %s", tpath
);
1030 if (wait_for_pid(pid
) != 0) {
1031 ERROR("container creation template for %s failed\n", c
->name
);
1038 static bool prepend_lxc_header(char *path
, const char *t
, char *const argv
[])
1046 unsigned char md_value
[SHA_DIGEST_LENGTH
];
1050 f
= fopen(path
, "r");
1054 if (fseek(f
, 0, SEEK_END
) < 0)
1056 if ((flen
= ftell(f
)) < 0)
1058 if (fseek(f
, 0, SEEK_SET
) < 0)
1060 if ((contents
= malloc(flen
+ 1)) == NULL
)
1062 if (fread(contents
, 1, flen
, f
) != flen
)
1063 goto out_free_contents
;
1065 contents
[flen
] = '\0';
1069 goto out_free_contents
;
1072 tpath
= get_template_path(t
);
1074 ERROR("bad template: %s\n", t
);
1075 goto out_free_contents
;
1078 ret
= sha1sum_file(tpath
, md_value
);
1080 ERROR("Error getting sha1sum of %s", tpath
);
1082 goto out_free_contents
;
1087 f
= fopen(path
, "w");
1089 SYSERROR("reopening config for writing");
1093 fprintf(f
, "# Template used to create this container: %s\n", t
);
1095 fprintf(f
, "# Parameters passed to the template:");
1097 fprintf(f
, " %s", *argv
);
1103 fprintf(f
, "# Template script checksum (SHA-1): ");
1104 for (i
=0; i
<SHA_DIGEST_LENGTH
; i
++)
1105 fprintf(f
, "%02x", md_value
[i
]);
1108 fprintf(f
, "# For additional config options, please look at lxc.conf(5)\n");
1109 if (fwrite(contents
, 1, flen
, f
) != flen
) {
1110 SYSERROR("Writing original contents");
1126 SYSERROR("Error prepending header");
1132 static void lxcapi_clear_config(struct lxc_container
*c
)
1134 if (c
&& c
->lxc_conf
) {
1135 lxc_conf_free(c
->lxc_conf
);
1140 static bool lxcapi_destroy(struct lxc_container
*c
);
1143 * create a container with the given parameters.
1144 * @c: container to be created. It has the lxcpath, name, and a starting
1145 * configuration already set
1146 * @t: the template to execute to instantiate the root filesystem and
1147 * adjust the configuration.
1148 * @bdevtype: backing store type to use. If NULL, dir will be used.
1149 * @specs: additional parameters for the backing store, i.e. LVM vg to
1152 * @argv: the arguments to pass to the template, terminated by NULL. If no
1153 * arguments, you can just pass NULL.
1155 static bool lxcapi_create(struct lxc_container
*c
, const char *t
,
1156 const char *bdevtype
, struct bdev_specs
*specs
, int flags
,
1168 tpath
= get_template_path(t
);
1170 ERROR("bad template: %s\n", t
);
1176 * If a template is passed in, and the rootfs already is defined in
1177 * the container config and exists, then * caller is trying to create
1178 * an existing container. Return an error, but do NOT delete the
1181 if (lxcapi_is_defined(c
) && c
->lxc_conf
&& c
->lxc_conf
->rootfs
.path
&&
1182 access(c
->lxc_conf
->rootfs
.path
, F_OK
) == 0 && tpath
) {
1183 ERROR("Container %s:%s already exists", c
->config_path
, c
->name
);
1188 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1189 ERROR("Error loading default configuration file %s\n", lxc_global_config_value("lxc.default_config"));
1194 if (!create_container_dir(c
))
1198 * either template or rootfs.path should be set.
1199 * if both template and rootfs.path are set, template is setup as rootfs.path.
1200 * container is already created if we have a config and rootfs.path is accessible
1202 if (!c
->lxc_conf
->rootfs
.path
&& !tpath
)
1203 /* no template passed in and rootfs does not exist: error */
1205 if (c
->lxc_conf
->rootfs
.path
&& access(c
->lxc_conf
->rootfs
.path
, F_OK
) != 0)
1206 /* rootfs passed into configuration, but does not exist: error */
1208 if (lxcapi_is_defined(c
) && c
->lxc_conf
->rootfs
.path
&& !tpath
) {
1209 /* Rootfs already existed, user just wanted to save the
1210 * loaded configuration */
1215 /* Mark that this container is being created */
1216 if ((partial_fd
= create_partial(c
)) < 0)
1219 /* no need to get disk lock bc we have the partial locked */
1222 * Create the backing store
1223 * Note we can't do this in the same task as we use to execute the
1224 * template because of the way zfs works.
1225 * After you 'zfs create', zfs mounts the fs only in the initial
1230 SYSERROR("failed to fork task for container creation template\n");
1234 if (pid
== 0) { // child
1235 struct bdev
*bdev
= NULL
;
1237 if (!(bdev
= do_bdev_create(c
, bdevtype
, specs
))) {
1238 ERROR("Error creating backing store type %s for %s",
1239 bdevtype
? bdevtype
: "(none)", c
->name
);
1243 /* save config file again to store the new rootfs location */
1244 if (!c
->save_config(c
, NULL
)) {
1245 ERROR("failed to save starting configuration for %s\n", c
->name
);
1246 // parent task won't see bdev in config so we delete it
1247 bdev
->ops
->umount(bdev
);
1248 bdev
->ops
->destroy(bdev
);
1253 if (wait_for_pid(pid
) != 0)
1256 /* reload config to get the rootfs */
1257 lxc_conf_free(c
->lxc_conf
);
1259 if (!load_config_locked(c
, c
->configfile
))
1262 if (!create_run_template(c
, tpath
, !!(flags
& LXC_CREATE_QUIET
), argv
))
1265 // now clear out the lxc_conf we have, reload from the created
1267 lxcapi_clear_config(c
);
1270 if (!prepend_lxc_header(c
->configfile
, tpath
, argv
)) {
1271 ERROR("Error prepending header to configuration file");
1275 ret
= load_config_locked(c
, c
->configfile
);
1278 if (partial_fd
>= 0)
1279 remove_partial(c
, partial_fd
);
1289 static bool lxcapi_reboot(struct lxc_container
*c
)
1295 if (!c
->is_running(c
))
1297 pid
= c
->init_pid(c
);
1300 if (kill(pid
, SIGINT
) < 0)
1306 static bool lxcapi_shutdown(struct lxc_container
*c
, int timeout
)
1310 int haltsignal
= SIGPWR
;
1317 if (!c
->is_running(c
))
1319 pid
= c
->init_pid(c
);
1322 if (c
->lxc_conf
&& c
->lxc_conf
->haltsignal
)
1323 haltsignal
= c
->lxc_conf
->haltsignal
;
1324 kill(pid
, haltsignal
);
1325 retv
= c
->wait(c
, "STOPPED", timeout
);
1326 if (!retv
&& timeout
> 0) {
1328 retv
= c
->wait(c
, "STOPPED", 0); // 0 means don't wait
1333 static bool lxcapi_createl(struct lxc_container
*c
, const char *t
,
1334 const char *bdevtype
, struct bdev_specs
*specs
, int flags
, ...)
1344 * since we're going to wait for create to finish, I don't think we
1345 * need to get a copy of the arguments.
1347 va_start(ap
, flags
);
1348 args
= lxc_va_arg_list_to_argv(ap
, 0, 0);
1351 ERROR("Memory allocation error.");
1355 bret
= c
->create(c
, t
, bdevtype
, specs
, flags
, args
);
1362 static bool lxcapi_clear_config_item(struct lxc_container
*c
, const char *key
)
1366 if (!c
|| !c
->lxc_conf
)
1368 if (container_mem_lock(c
))
1370 ret
= lxc_clear_config_item(c
->lxc_conf
, key
);
1371 container_mem_unlock(c
);
1375 static inline bool enter_to_ns(struct lxc_container
*c
) {
1376 int netns
, userns
, ret
= 0, init_pid
= 0;;
1377 char new_netns_path
[MAXPATHLEN
];
1378 char new_userns_path
[MAXPATHLEN
];
1380 if (!c
->is_running(c
))
1383 init_pid
= c
->init_pid(c
);
1385 /* Switch to new userns */
1386 if (geteuid() && access("/proc/self/ns/user", F_OK
) == 0) {
1387 ret
= snprintf(new_userns_path
, MAXPATHLEN
, "/proc/%d/ns/user", init_pid
);
1388 if (ret
< 0 || ret
>= MAXPATHLEN
)
1391 userns
= open(new_userns_path
, O_RDONLY
);
1393 SYSERROR("failed to open %s", new_userns_path
);
1397 if (setns(userns
, CLONE_NEWUSER
)) {
1398 SYSERROR("failed to setns for CLONE_NEWUSER");
1405 /* Switch to new netns */
1406 ret
= snprintf(new_netns_path
, MAXPATHLEN
, "/proc/%d/ns/net", init_pid
);
1407 if (ret
< 0 || ret
>= MAXPATHLEN
)
1410 netns
= open(new_netns_path
, O_RDONLY
);
1412 SYSERROR("failed to open %s", new_netns_path
);
1416 if (setns(netns
, CLONE_NEWNET
)) {
1417 SYSERROR("failed to setns for CLONE_NEWNET");
1427 // used by qsort and bsearch functions for comparing names
1428 static inline int string_cmp(char **first
, char **second
)
1430 return strcmp(*first
, *second
);
1433 // used by qsort and bsearch functions for comparing container names
1434 static inline int container_cmp(struct lxc_container
**first
, struct lxc_container
**second
)
1436 return strcmp((*first
)->name
, (*second
)->name
);
1439 static bool add_to_array(char ***names
, char *cname
, int pos
)
1441 char **newnames
= realloc(*names
, (pos
+1) * sizeof(char *));
1443 ERROR("Out of memory");
1448 newnames
[pos
] = strdup(cname
);
1452 // sort the arrray as we will use binary search on it
1453 qsort(newnames
, pos
+ 1, sizeof(char *), (int (*)(const void *,const void *))string_cmp
);
1458 static bool add_to_clist(struct lxc_container
***list
, struct lxc_container
*c
, int pos
, bool sort
)
1460 struct lxc_container
**newlist
= realloc(*list
, (pos
+1) * sizeof(struct lxc_container
*));
1462 ERROR("Out of memory");
1469 // sort the arrray as we will use binary search on it
1471 qsort(newlist
, pos
+ 1, sizeof(struct lxc_container
*), (int (*)(const void *,const void *))container_cmp
);
1476 static char** get_from_array(char ***names
, char *cname
, int size
)
1478 return (char **)bsearch(&cname
, *names
, size
, sizeof(char *), (int (*)(const void *, const void *))string_cmp
);
1482 static bool array_contains(char ***names
, char *cname
, int size
) {
1483 if(get_from_array(names
, cname
, size
) != NULL
)
1488 static bool remove_from_array(char ***names
, char *cname
, int size
)
1490 char **result
= get_from_array(names
, cname
, size
);
1491 if (result
!= NULL
) {
1498 static char** lxcapi_get_interfaces(struct lxc_container
*c
)
1501 int i
, count
= 0, pipefd
[2];
1502 char **interfaces
= NULL
;
1503 char interface
[IFNAMSIZ
];
1505 if(pipe(pipefd
) < 0) {
1506 SYSERROR("pipe failed");
1512 SYSERROR("failed to fork task to get interfaces information\n");
1518 if (pid
== 0) { // child
1519 int ret
= 1, nbytes
;
1520 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1522 /* close the read-end of the pipe */
1525 if (!enter_to_ns(c
)) {
1526 SYSERROR("failed to enter namespace");
1530 /* Grab the list of interfaces */
1531 if (getifaddrs(&interfaceArray
)) {
1532 SYSERROR("failed to get interfaces list");
1536 /* Iterate through the interfaces */
1537 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1538 nbytes
= write(pipefd
[1], tempIfAddr
->ifa_name
, IFNAMSIZ
);
1540 ERROR("write failed");
1549 freeifaddrs(interfaceArray
);
1551 /* close the write-end of the pipe, thus sending EOF to the reader */
1556 /* close the write-end of the pipe */
1559 while (read(pipefd
[0], &interface
, IFNAMSIZ
) == IFNAMSIZ
) {
1560 if (array_contains(&interfaces
, interface
, count
))
1563 if(!add_to_array(&interfaces
, interface
, count
))
1564 ERROR("PARENT: add_to_array failed");
1568 if (wait_for_pid(pid
) != 0) {
1569 for(i
=0;i
<count
;i
++)
1570 free(interfaces
[i
]);
1575 /* close the read-end of the pipe */
1578 /* Append NULL to the array */
1580 interfaces
= (char **)lxc_append_null_to_array((void **)interfaces
, count
);
1585 static char** lxcapi_get_ips(struct lxc_container
*c
, const char* interface
, const char* family
, int scope
)
1588 int i
, count
= 0, pipefd
[2];
1589 char **addresses
= NULL
;
1590 char address
[INET6_ADDRSTRLEN
];
1592 if(pipe(pipefd
) < 0) {
1593 SYSERROR("pipe failed");
1599 SYSERROR("failed to fork task to get container ips\n");
1605 if (pid
== 0) { // child
1606 int ret
= 1, nbytes
;
1607 struct ifaddrs
*interfaceArray
= NULL
, *tempIfAddr
= NULL
;
1608 char addressOutputBuffer
[INET6_ADDRSTRLEN
];
1609 void *tempAddrPtr
= NULL
;
1610 char *address
= NULL
;
1612 /* close the read-end of the pipe */
1615 if (!enter_to_ns(c
)) {
1616 SYSERROR("failed to enter namespace");
1620 /* Grab the list of interfaces */
1621 if (getifaddrs(&interfaceArray
)) {
1622 SYSERROR("failed to get interfaces list");
1626 /* Iterate through the interfaces */
1627 for (tempIfAddr
= interfaceArray
; tempIfAddr
!= NULL
; tempIfAddr
= tempIfAddr
->ifa_next
) {
1628 if (tempIfAddr
->ifa_addr
== NULL
)
1631 if(tempIfAddr
->ifa_addr
->sa_family
== AF_INET
) {
1632 if (family
&& strcmp(family
, "inet"))
1634 tempAddrPtr
= &((struct sockaddr_in
*)tempIfAddr
->ifa_addr
)->sin_addr
;
1637 if (family
&& strcmp(family
, "inet6"))
1640 if (((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_scope_id
!= scope
)
1643 tempAddrPtr
= &((struct sockaddr_in6
*)tempIfAddr
->ifa_addr
)->sin6_addr
;
1646 if (interface
&& strcmp(interface
, tempIfAddr
->ifa_name
))
1648 else if (!interface
&& strcmp("lo", tempIfAddr
->ifa_name
) == 0)
1651 address
= (char *)inet_ntop(tempIfAddr
->ifa_addr
->sa_family
,
1653 addressOutputBuffer
,
1654 sizeof(addressOutputBuffer
));
1658 nbytes
= write(pipefd
[1], address
, INET6_ADDRSTRLEN
);
1660 ERROR("write failed");
1669 freeifaddrs(interfaceArray
);
1671 /* close the write-end of the pipe, thus sending EOF to the reader */
1676 /* close the write-end of the pipe */
1679 while (read(pipefd
[0], &address
, INET6_ADDRSTRLEN
) == INET6_ADDRSTRLEN
) {
1680 if(!add_to_array(&addresses
, address
, count
))
1681 ERROR("PARENT: add_to_array failed");
1685 if (wait_for_pid(pid
) != 0) {
1686 for(i
=0;i
<count
;i
++)
1692 /* close the read-end of the pipe */
1695 /* Append NULL to the array */
1697 addresses
= (char **)lxc_append_null_to_array((void **)addresses
, count
);
1702 static int lxcapi_get_config_item(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1706 if (!c
|| !c
->lxc_conf
)
1708 if (container_mem_lock(c
))
1710 ret
= lxc_get_config_item(c
->lxc_conf
, key
, retv
, inlen
);
1711 container_mem_unlock(c
);
1715 static int lxcapi_get_keys(struct lxc_container
*c
, const char *key
, char *retv
, int inlen
)
1718 return lxc_listconfigs(retv
, inlen
);
1720 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1721 * This is an intelligent result to show which keys are valid given
1722 * the type of nic it is
1724 if (!c
|| !c
->lxc_conf
)
1726 if (container_mem_lock(c
))
1729 if (strncmp(key
, "lxc.network.", 12) == 0)
1730 ret
= lxc_list_nicconfigs(c
->lxc_conf
, key
, retv
, inlen
);
1731 container_mem_unlock(c
);
1735 static bool lxcapi_save_config(struct lxc_container
*c
, const char *alt_file
)
1738 bool ret
= false, need_disklock
= false;
1742 alt_file
= c
->configfile
;
1744 return false; // should we write to stdout if no file is specified?
1746 // If we haven't yet loaded a config, load the stock config
1748 if (!c
->load_config(c
, lxc_global_config_value("lxc.default_config"))) {
1749 ERROR("Error loading default configuration file %s while saving %s\n", lxc_global_config_value("lxc.default_config"), c
->name
);
1754 if (!create_container_dir(c
))
1758 * If we're writing to the container's config file, take the
1759 * disk lock. Otherwise just take the memlock to protect the
1760 * struct lxc_container while we're traversing it.
1762 if (strcmp(c
->configfile
, alt_file
) == 0)
1763 need_disklock
= true;
1766 lret
= container_disk_lock(c
);
1768 lret
= container_mem_lock(c
);
1773 fout
= fopen(alt_file
, "w");
1776 write_config(fout
, c
->lxc_conf
);
1782 container_disk_unlock(c
);
1784 container_mem_unlock(c
);
1788 static bool mod_rdep(struct lxc_container
*c
, bool inc
)
1790 char path
[MAXPATHLEN
];
1795 if (container_disk_lock(c
))
1797 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1799 if (ret
< 0 || ret
> MAXPATHLEN
)
1801 f
= fopen(path
, "r");
1803 ret
= fscanf(f
, "%d", &v
);
1806 ERROR("Corrupted file %s", path
);
1811 f
= fopen(path
, "w");
1814 if (fprintf(f
, "%d\n", v
) < 0) {
1815 ERROR("Error writing new snapshots value");
1821 SYSERROR("Error writing to or closing snapshots file");
1828 container_disk_unlock(c
);
1832 static void strip_newline(char *p
)
1834 size_t len
= strlen(p
);
1837 if (p
[len
-1] == '\n')
1841 static void mod_all_rdeps(struct lxc_container
*c
, bool inc
)
1843 struct lxc_container
*p
;
1844 char *lxcpath
= NULL
, *lxcname
= NULL
, path
[MAXPATHLEN
];
1845 size_t pathlen
= 0, namelen
= 0;
1849 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends",
1850 c
->config_path
, c
->name
);
1851 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1852 ERROR("Path name too long");
1855 f
= fopen(path
, "r");
1858 while (getline(&lxcpath
, &pathlen
, f
) != -1) {
1859 if (getline(&lxcname
, &namelen
, f
) == -1) {
1860 ERROR("badly formatted file %s\n", path
);
1863 strip_newline(lxcpath
);
1864 strip_newline(lxcname
);
1865 if ((p
= lxc_container_new(lxcname
, lxcpath
)) == NULL
) {
1866 ERROR("Unable to find dependent container %s:%s",
1870 if (!mod_rdep(p
, inc
))
1871 ERROR("Failed to increase numsnapshots for %s:%s",
1873 lxc_container_put(p
);
1876 if (lxcpath
) free(lxcpath
);
1877 if (lxcname
) free(lxcname
);
1881 static bool has_snapshots(struct lxc_container
*c
)
1883 char path
[MAXPATHLEN
];
1888 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_snapshots", c
->config_path
,
1890 if (ret
< 0 || ret
> MAXPATHLEN
)
1892 f
= fopen(path
, "r");
1895 ret
= fscanf(f
, "%d", &v
);
1905 static int lxc_rmdir_onedev_wrapper(void *data
)
1907 char *arg
= (char *) data
;
1908 return lxc_rmdir_onedev(arg
);
1911 // do we want the api to support --force, or leave that to the caller?
1912 static bool lxcapi_destroy(struct lxc_container
*c
)
1914 struct bdev
*r
= NULL
;
1918 if (!c
|| !lxcapi_is_defined(c
))
1921 if (container_disk_lock(c
))
1924 if (!is_stopped(c
)) {
1925 // we should queue some sort of error - in c->error_string?
1926 ERROR("container %s is not stopped", c
->name
);
1930 if (c
->lxc_conf
&& has_snapshots(c
)) {
1931 ERROR("container %s has dependent snapshots", c
->name
);
1935 if (!am_unpriv() && c
->lxc_conf
->rootfs
.path
&& c
->lxc_conf
->rootfs
.mount
) {
1936 r
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
1938 if (r
->ops
->destroy(r
) < 0) {
1940 ERROR("Error destroying rootfs for %s", c
->name
);
1947 mod_all_rdeps(c
, false);
1949 const char *p1
= lxcapi_get_config_path(c
);
1950 char *path
= alloca(strlen(p1
) + strlen(c
->name
) + 2);
1951 sprintf(path
, "%s/%s", p1
, c
->name
);
1953 ret
= userns_exec_1(c
->lxc_conf
, lxc_rmdir_onedev_wrapper
, path
);
1955 ret
= lxc_rmdir_onedev(path
);
1957 ERROR("Error destroying container directory for %s", c
->name
);
1963 container_disk_unlock(c
);
1967 static bool set_config_item_locked(struct lxc_container
*c
, const char *key
, const char *v
)
1969 struct lxc_config_t
*config
;
1972 c
->lxc_conf
= lxc_conf_init();
1975 config
= lxc_getconfig(key
);
1978 return (0 == config
->cb(key
, v
, c
->lxc_conf
));
1981 static bool lxcapi_set_config_item(struct lxc_container
*c
, const char *key
, const char *v
)
1988 if (container_mem_lock(c
))
1991 b
= set_config_item_locked(c
, key
, v
);
1993 container_mem_unlock(c
);
1997 static char *lxcapi_config_file_name(struct lxc_container
*c
)
1999 if (!c
|| !c
->configfile
)
2001 return strdup(c
->configfile
);
2004 static const char *lxcapi_get_config_path(struct lxc_container
*c
)
2006 if (!c
|| !c
->config_path
)
2008 return (const char *)(c
->config_path
);
2013 * Just recalculate the c->configfile based on the
2014 * c->config_path, which must be set.
2015 * The lxc_container must be locked or not yet public.
2017 static bool set_config_filename(struct lxc_container
*c
)
2022 if (!c
->config_path
)
2025 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
2026 len
= strlen(c
->config_path
) + strlen(c
->name
) + strlen("config") + 3;
2027 newpath
= malloc(len
);
2031 ret
= snprintf(newpath
, len
, "%s/%s/config", c
->config_path
, c
->name
);
2032 if (ret
< 0 || ret
>= len
) {
2033 fprintf(stderr
, "Error printing out config file name\n");
2039 free(c
->configfile
);
2040 c
->configfile
= newpath
;
2045 static bool lxcapi_set_config_path(struct lxc_container
*c
, const char *path
)
2049 char *oldpath
= NULL
;
2054 if (container_mem_lock(c
))
2059 ERROR("Out of memory setting new lxc path");
2065 oldpath
= c
->config_path
;
2068 /* Since we've changed the config path, we have to change the
2069 * config file name too */
2070 if (!set_config_filename(c
)) {
2071 ERROR("Out of memory setting new config filename");
2073 free(c
->config_path
);
2074 c
->config_path
= oldpath
;
2080 container_mem_unlock(c
);
2085 static bool lxcapi_set_cgroup_item(struct lxc_container
*c
, const char *subsys
, const char *value
)
2095 if (container_disk_lock(c
))
2098 ret
= lxc_cgroup_set(subsys
, value
, c
->name
, c
->config_path
);
2100 container_disk_unlock(c
);
2104 static int lxcapi_get_cgroup_item(struct lxc_container
*c
, const char *subsys
, char *retv
, int inlen
)
2114 if (container_disk_lock(c
))
2117 ret
= lxc_cgroup_get(subsys
, retv
, inlen
, c
->name
, c
->config_path
);
2119 container_disk_unlock(c
);
2123 const char *lxc_get_global_config_item(const char *key
)
2125 return lxc_global_config_value(key
);
2128 const char *lxc_get_version(void)
2133 static int copy_file(const char *old
, const char *new)
2140 if (file_exists(new)) {
2141 ERROR("copy destination %s exists", new);
2144 ret
= stat(old
, &sbuf
);
2146 INFO("Error stat'ing %s", old
);
2150 in
= open(old
, O_RDONLY
);
2152 SYSERROR("Error opening original file %s", old
);
2155 out
= open(new, O_CREAT
| O_EXCL
| O_WRONLY
, 0644);
2157 SYSERROR("Error opening new file %s", new);
2163 len
= read(in
, buf
, 8096);
2165 SYSERROR("Error reading old file %s", old
);
2170 ret
= write(out
, buf
, len
);
2171 if (ret
< len
) { // should we retry?
2172 SYSERROR("Error: write to new file %s was interrupted", new);
2179 // we set mode, but not owner/group
2180 ret
= chmod(new, sbuf
.st_mode
);
2182 SYSERROR("Error setting mode on %s", new);
2194 static int copyhooks(struct lxc_container
*oldc
, struct lxc_container
*c
)
2197 struct lxc_list
*it
;
2200 len
= strlen(oldc
->config_path
) + strlen(oldc
->name
) + 3;
2201 cpath
= alloca(len
);
2202 ret
= snprintf(cpath
, len
, "%s/%s/", oldc
->config_path
, oldc
->name
);
2203 if (ret
< 0 || ret
>= len
)
2206 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
2207 lxc_list_for_each(it
, &c
->lxc_conf
->hooks
[i
]) {
2208 char *hookname
= it
->elem
;
2209 char *fname
= strrchr(hookname
, '/');
2210 char tmppath
[MAXPATHLEN
];
2211 if (!fname
) // relative path - we don't support, but maybe we should
2213 if (strncmp(hookname
, cpath
, len
- 1) != 0) {
2214 // this hook is public - ignore
2217 // copy the script, and change the entry in confile
2218 ret
= snprintf(tmppath
, MAXPATHLEN
, "%s/%s/%s",
2219 c
->config_path
, c
->name
, fname
+1);
2220 if (ret
< 0 || ret
>= MAXPATHLEN
)
2222 ret
= copy_file(it
->elem
, tmppath
);
2226 it
->elem
= strdup(tmppath
);
2228 ERROR("out of memory copying hook path");
2234 c
->save_config(c
, NULL
);
2238 static void new_hwaddr(char *hwaddr
)
2241 f
= fopen("/dev/urandom", "r");
2244 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
2251 snprintf(hwaddr
, 18, "00:16:3e:%02x:%02x:%02x",
2252 rand() % 255, rand() % 255, rand() % 255);
2255 static void network_new_hwaddrs(struct lxc_container
*c
)
2257 struct lxc_list
*it
;
2259 lxc_list_for_each(it
, &c
->lxc_conf
->network
) {
2260 struct lxc_netdev
*n
= it
->elem
;
2262 new_hwaddr(n
->hwaddr
);
2266 static int copy_fstab(struct lxc_container
*oldc
, struct lxc_container
*c
)
2268 char newpath
[MAXPATHLEN
];
2269 char *oldpath
= oldc
->lxc_conf
->fstab
;
2275 char *p
= strrchr(oldpath
, '/');
2278 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s%s",
2279 c
->config_path
, c
->name
, p
);
2280 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2281 ERROR("error printing new path for %s", oldpath
);
2284 if (file_exists(newpath
)) {
2285 ERROR("error: fstab file %s exists", newpath
);
2289 if (copy_file(oldpath
, newpath
) < 0) {
2290 ERROR("error: copying %s to %s", oldpath
, newpath
);
2293 free(c
->lxc_conf
->fstab
);
2294 c
->lxc_conf
->fstab
= strdup(newpath
);
2295 if (!c
->lxc_conf
->fstab
) {
2296 ERROR("error: allocating pathname");
2303 static void copy_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2305 char path0
[MAXPATHLEN
], path1
[MAXPATHLEN
];
2308 ret
= snprintf(path0
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c0
->config_path
,
2310 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2311 WARN("Error copying reverse dependencies");
2314 ret
= snprintf(path1
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2316 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2317 WARN("Error copying reverse dependencies");
2320 if (copy_file(path0
, path1
) < 0) {
2321 INFO("Error copying reverse dependencies");
2326 static bool add_rdepends(struct lxc_container
*c
, struct lxc_container
*c0
)
2329 char path
[MAXPATHLEN
];
2333 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/lxc_rdepends", c
->config_path
,
2335 if (ret
< 0 || ret
>= MAXPATHLEN
)
2337 f
= fopen(path
, "a");
2341 // if anything goes wrong, just return an error
2342 if (fprintf(f
, "%s\n%s\n", c0
->config_path
, c0
->name
) < 0)
2349 static int copy_storage(struct lxc_container
*c0
, struct lxc_container
*c
,
2350 const char *newtype
, int flags
, const char *bdevdata
, uint64_t newsize
)
2355 bdev
= bdev_copy(c0
->lxc_conf
->rootfs
.path
, c0
->name
, c
->name
,
2356 c0
->config_path
, c
->config_path
, newtype
, flags
,
2357 bdevdata
, newsize
, &need_rdep
);
2359 ERROR("Error copying storage");
2362 free(c
->lxc_conf
->rootfs
.path
);
2363 c
->lxc_conf
->rootfs
.path
= strdup(bdev
->src
);
2365 if (!c
->lxc_conf
->rootfs
.path
) {
2366 ERROR("Out of memory while setting storage path");
2369 if (flags
& LXC_CLONE_SNAPSHOT
)
2370 copy_rdepends(c
, c0
);
2372 if (!add_rdepends(c
, c0
))
2373 WARN("Error adding reverse dependency from %s to %s",
2377 mod_all_rdeps(c
, true);
2382 static int clone_update_rootfs(struct lxc_container
*c0
,
2383 struct lxc_container
*c
, int flags
,
2387 char path
[MAXPATHLEN
];
2391 struct lxc_conf
*conf
= c
->lxc_conf
;
2393 /* update hostname in rootfs */
2394 /* we're going to mount, so run in a clean namespace to simplify cleanup */
2400 return wait_for_pid(pid
);
2402 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2405 if (strcmp(bdev
->type
, "dir") != 0) {
2406 if (unshare(CLONE_NEWNS
) < 0) {
2407 ERROR("error unsharing mounts");
2410 if (bdev
->ops
->mount(bdev
) < 0)
2412 } else { // TODO come up with a better way
2415 bdev
->dest
= strdup(bdev
->src
);
2418 if (!lxc_list_empty(&conf
->hooks
[LXCHOOK_CLONE
])) {
2419 /* Start of environment variable setup for hooks */
2420 if (setenv("LXC_SRC_NAME", c0
->name
, 1)) {
2421 SYSERROR("failed to set environment variable for source container name");
2423 if (setenv("LXC_NAME", c
->name
, 1)) {
2424 SYSERROR("failed to set environment variable for container name");
2426 if (setenv("LXC_CONFIG_FILE", conf
->rcfile
, 1)) {
2427 SYSERROR("failed to set environment variable for config path");
2429 if (setenv("LXC_ROOTFS_MOUNT", bdev
->dest
, 1)) {
2430 SYSERROR("failed to set environment variable for rootfs mount");
2432 if (setenv("LXC_ROOTFS_PATH", conf
->rootfs
.path
, 1)) {
2433 SYSERROR("failed to set environment variable for rootfs mount");
2436 if (run_lxc_hooks(c
->name
, "clone", conf
, c
->get_config_path(c
), hookargs
)) {
2437 ERROR("Error executing clone hook for %s", c
->name
);
2442 if (!(flags
& LXC_CLONE_KEEPNAME
)) {
2443 ret
= snprintf(path
, MAXPATHLEN
, "%s/etc/hostname", bdev
->dest
);
2444 if (ret
< 0 || ret
>= MAXPATHLEN
)
2446 if (!file_exists(path
))
2448 if (!(fout
= fopen(path
, "w"))) {
2449 SYSERROR("unable to open %s: ignoring\n", path
);
2452 if (fprintf(fout
, "%s", c
->name
) < 0)
2454 if (fclose(fout
) < 0)
2461 * We want to support:
2462 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
2463 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
2465 -s [ implies overlayfs]
2469 only rootfs gets converted (copied/snapshotted) on clone.
2472 static int create_file_dirname(char *path
)
2474 char *p
= strrchr(path
, '/');
2480 ret
= mkdir(path
, 0755);
2481 if (ret
&& errno
!= EEXIST
)
2482 SYSERROR("creating container path %s\n", path
);
2487 static struct lxc_container
*lxcapi_clone(struct lxc_container
*c
, const char *newname
,
2488 const char *lxcpath
, int flags
,
2489 const char *bdevtype
, const char *bdevdata
, uint64_t newsize
,
2492 struct lxc_container
*c2
= NULL
;
2493 char newpath
[MAXPATHLEN
];
2494 int ret
, storage_copied
= 0;
2498 if (!c
|| !c
->is_defined(c
))
2502 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
2506 if (container_mem_lock(c
))
2509 if (!is_stopped(c
)) {
2510 ERROR("error: Original container (%s) is running", c
->name
);
2514 // Make sure the container doesn't yet exist.
2515 n
= newname
? newname
: c
->name
;
2516 l
= lxcpath
? lxcpath
: c
->get_config_path(c
);
2517 ret
= snprintf(newpath
, MAXPATHLEN
, "%s/%s/config", l
, n
);
2518 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2519 SYSERROR("clone: failed making config pathname");
2522 if (file_exists(newpath
)) {
2523 ERROR("error: clone: %s exists", newpath
);
2527 ret
= create_file_dirname(newpath
);
2528 if (ret
< 0 && errno
!= EEXIST
) {
2529 ERROR("Error creating container dir for %s", newpath
);
2533 // copy the configuration, tweak it as needed,
2534 fout
= fopen(newpath
, "w");
2536 SYSERROR("open %s", newpath
);
2539 write_config(fout
, c
->lxc_conf
);
2542 sprintf(newpath
, "%s/%s/rootfs", l
, n
);
2543 if (mkdir(newpath
, 0755) < 0) {
2544 SYSERROR("error creating %s", newpath
);
2548 c2
= lxc_container_new(n
, l
);
2550 ERROR("clone: failed to create new container (%s %s)", n
, l
);
2555 if (!set_config_item_locked(c2
, "lxc.utsname", newname
)) {
2556 ERROR("Error setting new hostname");
2561 ret
= copyhooks(c
, c2
);
2563 ERROR("error copying hooks");
2567 if (copy_fstab(c
, c2
) < 0) {
2568 ERROR("error copying fstab");
2573 if (!(flags
& LXC_CLONE_KEEPMACADDR
))
2574 network_new_hwaddrs(c2
);
2576 // copy/snapshot rootfs's
2577 ret
= copy_storage(c
, c2
, bdevtype
, flags
, bdevdata
, newsize
);
2581 // We've now successfully created c2's storage, so clear it out if we
2585 if (!c2
->save_config(c2
, NULL
))
2588 if (clone_update_rootfs(c
, c2
, flags
, hookargs
) < 0)
2591 // TODO: update c's lxc.snapshot = count
2592 container_mem_unlock(c
);
2596 container_mem_unlock(c
);
2598 if (!storage_copied
)
2599 c2
->lxc_conf
->rootfs
.path
= NULL
;
2601 lxc_container_put(c2
);
2607 static bool lxcapi_rename(struct lxc_container
*c
, const char *newname
)
2610 struct lxc_container
*newc
;
2612 if (!c
|| !c
->name
|| !c
->config_path
)
2616 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
2620 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2622 ERROR("Failed to find original backing store type");
2626 newc
= lxcapi_clone(c
, newname
, c
->config_path
, LXC_CLONE_KEEPMACADDR
, NULL
, bdev
->type
, 0, NULL
);
2629 lxc_container_put(newc
);
2633 if (newc
&& lxcapi_is_defined(newc
))
2634 lxc_container_put(newc
);
2636 if (!lxcapi_destroy(c
)) {
2637 ERROR("Could not destroy existing container %s", c
->name
);
2643 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
)
2648 return lxc_attach(c
->name
, c
->config_path
, exec_function
, exec_payload
, options
, attached_process
);
2651 static int lxcapi_attach_run_wait(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char * const argv
[])
2653 lxc_attach_command_t command
;
2660 command
.program
= (char*)program
;
2661 command
.argv
= (char**)argv
;
2662 r
= lxc_attach(c
->name
, c
->config_path
, lxc_attach_run_command
, &command
, options
, &pid
);
2667 return lxc_wait_for_pid_status(pid
);
2670 static int get_next_index(const char *lxcpath
, char *cname
)
2676 fname
= alloca(strlen(lxcpath
) + 20);
2678 sprintf(fname
, "%s/snap%d", lxcpath
, i
);
2679 ret
= stat(fname
, &sb
);
2686 static int lxcapi_snapshot(struct lxc_container
*c
, const char *commentfile
)
2689 struct lxc_container
*c2
;
2690 char snappath
[MAXPATHLEN
], newname
[20];
2693 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
2697 // /var/lib/lxc -> /var/lib/lxcsnaps \0
2698 ret
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2699 if (ret
< 0 || ret
>= MAXPATHLEN
)
2701 i
= get_next_index(snappath
, c
->name
);
2703 if (mkdir_p(snappath
, 0755) < 0) {
2704 ERROR("Failed to create snapshot directory %s", snappath
);
2708 ret
= snprintf(newname
, 20, "snap%d", i
);
2709 if (ret
< 0 || ret
>= 20)
2713 * We pass LXC_CLONE_SNAPSHOT to make sure that a rdepends file entry is
2714 * created in the original container
2716 flags
= LXC_CLONE_SNAPSHOT
| LXC_CLONE_KEEPMACADDR
| LXC_CLONE_KEEPNAME
|
2717 LXC_CLONE_KEEPBDEVTYPE
| LXC_CLONE_MAYBE_SNAPSHOT
;
2718 c2
= c
->clone(c
, newname
, snappath
, flags
, NULL
, NULL
, 0, NULL
);
2720 ERROR("clone of %s:%s failed\n", c
->config_path
, c
->name
);
2724 lxc_container_put(c2
);
2726 // Now write down the creation time
2733 tm_info
= localtime(&timer
);
2735 strftime(buffer
, 25, "%Y:%m:%d %H:%M:%S", tm_info
);
2737 char *dfnam
= alloca(strlen(snappath
) + strlen(newname
) + 5);
2738 sprintf(dfnam
, "%s/%s/ts", snappath
, newname
);
2739 f
= fopen(dfnam
, "w");
2741 ERROR("Failed to open %s\n", dfnam
);
2744 if (fprintf(f
, "%s", buffer
) < 0) {
2745 SYSERROR("Writing timestamp");
2751 SYSERROR("Writing timestamp");
2756 // $p / $name / comment \0
2757 int len
= strlen(snappath
) + strlen(newname
) + 10;
2758 char *path
= alloca(len
);
2759 sprintf(path
, "%s/%s/comment", snappath
, newname
);
2760 return copy_file(commentfile
, path
) < 0 ? -1 : i
;
2766 static void lxcsnap_free(struct lxc_snapshot
*s
)
2770 if (s
->comment_pathname
)
2771 free(s
->comment_pathname
);
2778 static char *get_snapcomment_path(char* snappath
, char *name
)
2780 // $snappath/$name/comment
2781 int ret
, len
= strlen(snappath
) + strlen(name
) + 10;
2782 char *s
= malloc(len
);
2785 ret
= snprintf(s
, len
, "%s/%s/comment", snappath
, name
);
2786 if (ret
< 0 || ret
>= len
) {
2794 static char *get_timestamp(char* snappath
, char *name
)
2796 char path
[MAXPATHLEN
], *s
= NULL
;
2800 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s/ts", snappath
, name
);
2801 if (ret
< 0 || ret
>= MAXPATHLEN
)
2803 fin
= fopen(path
, "r");
2806 (void) fseek(fin
, 0, SEEK_END
);
2808 (void) fseek(fin
, 0, SEEK_SET
);
2813 if (fread(s
, 1, len
, fin
) != len
) {
2814 SYSERROR("reading timestamp");
2824 static int lxcapi_snapshot_list(struct lxc_container
*c
, struct lxc_snapshot
**ret_snaps
)
2826 char snappath
[MAXPATHLEN
], path2
[MAXPATHLEN
];
2827 int dirlen
, count
= 0, ret
;
2828 struct dirent dirent
, *direntp
;
2829 struct lxc_snapshot
*snaps
=NULL
, *nsnaps
;
2832 if (!c
|| !lxcapi_is_defined(c
))
2836 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
2840 // snappath is ${lxcpath}snaps/${lxcname}/
2841 dirlen
= snprintf(snappath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2842 if (dirlen
< 0 || dirlen
>= MAXPATHLEN
) {
2843 ERROR("path name too long");
2846 dir
= opendir(snappath
);
2848 INFO("failed to open %s - assuming no snapshots", snappath
);
2852 while (!readdir_r(dir
, &dirent
, &direntp
)) {
2856 if (!strcmp(direntp
->d_name
, "."))
2859 if (!strcmp(direntp
->d_name
, ".."))
2862 ret
= snprintf(path2
, MAXPATHLEN
, "%s/%s/config", snappath
, direntp
->d_name
);
2863 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2864 ERROR("pathname too long");
2867 if (!file_exists(path2
))
2869 nsnaps
= realloc(snaps
, (count
+ 1)*sizeof(*snaps
));
2871 SYSERROR("Out of memory");
2875 snaps
[count
].free
= lxcsnap_free
;
2876 snaps
[count
].name
= strdup(direntp
->d_name
);
2877 if (!snaps
[count
].name
)
2879 snaps
[count
].lxcpath
= strdup(snappath
);
2880 if (!snaps
[count
].lxcpath
) {
2881 free(snaps
[count
].name
);
2884 snaps
[count
].comment_pathname
= get_snapcomment_path(snappath
, direntp
->d_name
);
2885 snaps
[count
].timestamp
= get_timestamp(snappath
, direntp
->d_name
);
2890 WARN("failed to close directory");
2898 for (i
=0; i
<count
; i
++)
2899 lxcsnap_free(&snaps
[i
]);
2903 WARN("failed to close directory");
2907 static bool lxcapi_snapshot_restore(struct lxc_container
*c
, const char *snapname
, const char *newname
)
2909 char clonelxcpath
[MAXPATHLEN
];
2911 struct lxc_container
*snap
, *rest
;
2915 if (!c
|| !c
->name
|| !c
->config_path
)
2919 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
2923 bdev
= bdev_init(c
->lxc_conf
->rootfs
.path
, c
->lxc_conf
->rootfs
.mount
, NULL
);
2925 ERROR("Failed to find original backing store type");
2931 if (strcmp(c
->name
, newname
) == 0) {
2932 if (!lxcapi_destroy(c
)) {
2933 ERROR("Could not destroy existing container %s", newname
);
2938 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2939 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2943 // how should we lock this?
2945 snap
= lxc_container_new(snapname
, clonelxcpath
);
2946 if (!snap
|| !lxcapi_is_defined(snap
)) {
2947 ERROR("Could not open snapshot %s", snapname
);
2948 if (snap
) lxc_container_put(snap
);
2953 rest
= lxcapi_clone(snap
, newname
, c
->config_path
, 0, bdev
->type
, NULL
, 0, NULL
);
2955 if (rest
&& lxcapi_is_defined(rest
))
2958 lxc_container_put(rest
);
2959 lxc_container_put(snap
);
2963 static bool lxcapi_snapshot_destroy(struct lxc_container
*c
, const char *snapname
)
2966 char clonelxcpath
[MAXPATHLEN
];
2967 struct lxc_container
*snap
= NULL
;
2969 if (!c
|| !c
->name
|| !c
->config_path
)
2973 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
2977 ret
= snprintf(clonelxcpath
, MAXPATHLEN
, "%ssnaps/%s", c
->config_path
, c
->name
);
2978 if (ret
< 0 || ret
>= MAXPATHLEN
)
2981 snap
= lxc_container_new(snapname
, clonelxcpath
);
2982 if (!snap
|| !lxcapi_is_defined(snap
)) {
2983 ERROR("Could not find snapshot %s", snapname
);
2987 if (!lxcapi_destroy(snap
)) {
2988 ERROR("Could not destroy snapshot %s", snapname
);
2991 lxc_container_put(snap
);
2996 lxc_container_put(snap
);
3000 static bool lxcapi_may_control(struct lxc_container
*c
)
3002 return lxc_try_cmd(c
->name
, c
->config_path
) == 0;
3005 static bool add_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
, bool add
)
3009 char path
[MAXPATHLEN
];
3010 char value
[MAX_BUFFER
];
3011 char *directory_path
= NULL
;
3014 /* make sure container is running */
3015 if (!c
->is_running(c
)) {
3016 ERROR("container is not running");
3020 /* use src_path if dest_path is NULL otherwise use dest_path */
3021 p
= dest_path
? dest_path
: src_path
;
3023 /* prepare the path */
3024 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/root/%s", c
->init_pid(c
), p
);
3025 if (ret
< 0 || ret
>= MAXPATHLEN
)
3027 remove_trailing_slashes(path
);
3029 p
= add
? src_path
: path
;
3030 /* make sure we can access p */
3031 if(access(p
, F_OK
) < 0 || stat(p
, &st
) < 0)
3034 /* continue if path is character device or block device */
3035 if (S_ISCHR(st
.st_mode
))
3036 ret
= snprintf(value
, MAX_BUFFER
, "c %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3037 else if (S_ISBLK(st
.st_mode
))
3038 ret
= snprintf(value
, MAX_BUFFER
, "b %d:%d rwm", major(st
.st_rdev
), minor(st
.st_rdev
));
3042 /* check snprintf return code */
3043 if (ret
< 0 || ret
>= MAX_BUFFER
)
3046 directory_path
= dirname(strdup(path
));
3047 /* remove path and directory_path (if empty) */
3048 if(access(path
, F_OK
) == 0) {
3049 if (unlink(path
) < 0) {
3050 ERROR("unlink failed");
3053 if (rmdir(directory_path
) < 0 && errno
!= ENOTEMPTY
) {
3054 ERROR("rmdir failed");
3060 /* create the missing directories */
3061 if (mkdir_p(directory_path
, 0755) < 0) {
3062 ERROR("failed to create directory");
3066 /* create the device node */
3067 if (mknod(path
, st
.st_mode
, st
.st_rdev
) < 0) {
3068 ERROR("mknod failed");
3072 /* add device node to device list */
3073 if (!c
->set_cgroup_item(c
, "devices.allow", value
)) {
3074 ERROR("set_cgroup_item failed while adding the device node");
3078 /* remove device node from device list */
3079 if (!c
->set_cgroup_item(c
, "devices.deny", value
)) {
3080 ERROR("set_cgroup_item failed while removing the device node");
3087 free(directory_path
);
3091 static bool lxcapi_add_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3094 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3097 return add_remove_device_node(c
, src_path
, dest_path
, true);
3100 static bool lxcapi_remove_device_node(struct lxc_container
*c
, const char *src_path
, const char *dest_path
)
3103 ERROR(NOT_SUPPORTED_ERROR
, __FUNCTION__
);
3106 return add_remove_device_node(c
, src_path
, dest_path
, false);
3109 static int lxcapi_attach_run_waitl(struct lxc_container
*c
, lxc_attach_options_t
*options
, const char *program
, const char *arg
, ...)
3119 argv
= lxc_va_arg_list_to_argv_const(ap
, 1);
3123 ERROR("Memory allocation error.");
3128 ret
= lxcapi_attach_run_wait(c
, options
, program
, (const char * const *)argv
);
3133 struct lxc_container
*lxc_container_new(const char *name
, const char *configpath
)
3135 struct lxc_container
*c
;
3137 c
= malloc(sizeof(*c
));
3139 fprintf(stderr
, "failed to malloc lxc_container\n");
3142 memset(c
, 0, sizeof(*c
));
3145 c
->config_path
= strdup(configpath
);
3147 c
->config_path
= strdup(lxc_global_config_value("lxc.lxcpath"));
3149 if (!c
->config_path
) {
3150 fprintf(stderr
, "Out of memory");
3154 remove_trailing_slashes(c
->config_path
);
3155 c
->name
= malloc(strlen(name
)+1);
3157 fprintf(stderr
, "Error allocating lxc_container name\n");
3160 strcpy(c
->name
, name
);
3163 if (!(c
->slock
= lxc_newlock(c
->config_path
, name
))) {
3164 fprintf(stderr
, "failed to create lock\n");
3168 if (!(c
->privlock
= lxc_newlock(NULL
, NULL
))) {
3169 fprintf(stderr
, "failed to alloc privlock\n");
3173 if (!set_config_filename(c
)) {
3174 fprintf(stderr
, "Error allocating config file pathname\n");
3178 if (file_exists(c
->configfile
))
3179 lxcapi_load_config(c
, NULL
);
3181 if (ongoing_create(c
) == 2) {
3182 ERROR("Error: %s creation was not completed", c
->name
);
3184 lxcapi_clear_config(c
);
3186 c
->daemonize
= true;
3188 // assign the member functions
3189 c
->is_defined
= lxcapi_is_defined
;
3190 c
->state
= lxcapi_state
;
3191 c
->is_running
= lxcapi_is_running
;
3192 c
->freeze
= lxcapi_freeze
;
3193 c
->unfreeze
= lxcapi_unfreeze
;
3194 c
->console
= lxcapi_console
;
3195 c
->console_getfd
= lxcapi_console_getfd
;
3196 c
->init_pid
= lxcapi_init_pid
;
3197 c
->load_config
= lxcapi_load_config
;
3198 c
->want_daemonize
= lxcapi_want_daemonize
;
3199 c
->want_close_all_fds
= lxcapi_want_close_all_fds
;
3200 c
->start
= lxcapi_start
;
3201 c
->startl
= lxcapi_startl
;
3202 c
->stop
= lxcapi_stop
;
3203 c
->config_file_name
= lxcapi_config_file_name
;
3204 c
->wait
= lxcapi_wait
;
3205 c
->set_config_item
= lxcapi_set_config_item
;
3206 c
->destroy
= lxcapi_destroy
;
3207 c
->rename
= lxcapi_rename
;
3208 c
->save_config
= lxcapi_save_config
;
3209 c
->get_keys
= lxcapi_get_keys
;
3210 c
->create
= lxcapi_create
;
3211 c
->createl
= lxcapi_createl
;
3212 c
->shutdown
= lxcapi_shutdown
;
3213 c
->reboot
= lxcapi_reboot
;
3214 c
->clear_config
= lxcapi_clear_config
;
3215 c
->clear_config_item
= lxcapi_clear_config_item
;
3216 c
->get_config_item
= lxcapi_get_config_item
;
3217 c
->get_cgroup_item
= lxcapi_get_cgroup_item
;
3218 c
->set_cgroup_item
= lxcapi_set_cgroup_item
;
3219 c
->get_config_path
= lxcapi_get_config_path
;
3220 c
->set_config_path
= lxcapi_set_config_path
;
3221 c
->clone
= lxcapi_clone
;
3222 c
->get_interfaces
= lxcapi_get_interfaces
;
3223 c
->get_ips
= lxcapi_get_ips
;
3224 c
->attach
= lxcapi_attach
;
3225 c
->attach_run_wait
= lxcapi_attach_run_wait
;
3226 c
->attach_run_waitl
= lxcapi_attach_run_waitl
;
3227 c
->snapshot
= lxcapi_snapshot
;
3228 c
->snapshot_list
= lxcapi_snapshot_list
;
3229 c
->snapshot_restore
= lxcapi_snapshot_restore
;
3230 c
->snapshot_destroy
= lxcapi_snapshot_destroy
;
3231 c
->may_control
= lxcapi_may_control
;
3232 c
->add_device_node
= lxcapi_add_device_node
;
3233 c
->remove_device_node
= lxcapi_remove_device_node
;
3235 /* we'll allow the caller to update these later */
3236 if (lxc_log_init(NULL
, "none", NULL
, "lxc_container", 0, c
->config_path
)) {
3237 fprintf(stderr
, "failed to open log\n");
3244 lxc_container_free(c
);
3248 int lxc_get_wait_states(const char **states
)
3253 for (i
=0; i
<MAX_STATE
; i
++)
3254 states
[i
] = lxc_state2str(i
);
3259 * These next two could probably be done smarter with reusing a common function
3260 * with different iterators and tests...
3262 int list_defined_containers(const char *lxcpath
, char ***names
, struct lxc_container
***cret
)
3265 int i
, cfound
= 0, nfound
= 0;
3266 struct dirent dirent
, *direntp
;
3267 struct lxc_container
*c
;
3270 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3272 dir
= opendir(lxcpath
);
3274 SYSERROR("opendir on lxcpath");
3283 while (!readdir_r(dir
, &dirent
, &direntp
)) {
3286 if (!strcmp(direntp
->d_name
, "."))
3288 if (!strcmp(direntp
->d_name
, ".."))
3291 if (!config_file_exists(lxcpath
, direntp
->d_name
))
3295 if (!add_to_array(names
, direntp
->d_name
, cfound
))
3305 c
= lxc_container_new(direntp
->d_name
, lxcpath
);
3307 INFO("Container %s:%s has a config but could not be loaded",
3308 lxcpath
, direntp
->d_name
);
3310 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3314 if (!lxcapi_is_defined(c
)) {
3315 INFO("Container %s:%s has a config but is not defined",
3316 lxcpath
, direntp
->d_name
);
3318 if(!remove_from_array(names
, direntp
->d_name
, cfound
--))
3320 lxc_container_put(c
);
3324 if (!add_to_clist(cret
, c
, nfound
, true)) {
3325 lxc_container_put(c
);
3335 if (names
&& *names
) {
3336 for (i
=0; i
<cfound
; i
++)
3340 if (cret
&& *cret
) {
3341 for (i
=0; i
<nfound
; i
++)
3342 lxc_container_put((*cret
)[i
]);
3349 int list_active_containers(const char *lxcpath
, char ***nret
,
3350 struct lxc_container
***cret
)
3352 int i
, ret
= -1, cret_cnt
= 0, ct_name_cnt
= 0;
3355 char **ct_name
= NULL
;
3357 struct lxc_container
*c
;
3360 lxcpath
= lxc_global_config_value("lxc.lxcpath");
3361 lxcpath_len
= strlen(lxcpath
);
3368 FILE *f
= fopen("/proc/net/unix", "r");
3372 while (getline(&line
, &len
, f
) != -1) {
3373 char *p
= strrchr(line
, ' '), *p2
;
3380 if (strncmp(p
, lxcpath
, lxcpath_len
) != 0)
3386 // Now p is the start of lxc_name
3388 if (!p2
|| strncmp(p2
, "/command", 8) != 0)
3392 if (array_contains(&ct_name
, p
, ct_name_cnt
))
3395 if (!add_to_array(&ct_name
, p
, ct_name_cnt
))
3396 goto free_cret_list
;
3403 c
= lxc_container_new(p
, lxcpath
);
3405 INFO("Container %s:%s is running but could not be loaded",
3407 remove_from_array(&ct_name
, p
, ct_name_cnt
--);
3412 * If this is an anonymous container, then is_defined *can*
3413 * return false. So we don't do that check. Count on the
3414 * fact that the command socket exists.
3417 if (!add_to_clist(cret
, c
, cret_cnt
, true)) {
3418 lxc_container_put(c
);
3419 goto free_cret_list
;
3424 assert(!nret
|| !cret
|| cret_cnt
== ct_name_cnt
);
3433 if (cret
&& *cret
) {
3434 for (i
= 0; i
< cret_cnt
; i
++)
3435 lxc_container_put((*cret
)[i
]);
3441 for (i
= 0; i
< ct_name_cnt
; i
++)
3454 int list_all_containers(const char *lxcpath
, char ***nret
,
3455 struct lxc_container
***cret
)
3457 int i
, ret
, active_cnt
, ct_cnt
, ct_list_cnt
;
3460 struct lxc_container
**ct_list
= NULL
;
3462 ct_cnt
= list_defined_containers(lxcpath
, &ct_name
, NULL
);
3466 active_cnt
= list_active_containers(lxcpath
, &active_name
, NULL
);
3467 if (active_cnt
< 0) {
3472 for (i
= 0; i
< active_cnt
; i
++) {
3473 if (!array_contains(&ct_name
, active_name
[i
], ct_cnt
)) {
3474 if (!add_to_array(&ct_name
, active_name
[i
], ct_cnt
)) {
3476 goto free_active_name
;
3480 free(active_name
[i
]);
3481 active_name
[i
] = NULL
;
3487 for (i
= 0, ct_list_cnt
= 0; i
< ct_cnt
&& cret
; i
++) {
3488 struct lxc_container
*c
;
3490 c
= lxc_container_new(ct_name
[i
], lxcpath
);
3492 WARN("Container %s:%s could not be loaded", lxcpath
, ct_name
[i
]);
3493 remove_from_array(&ct_name
, ct_name
[i
], ct_cnt
--);
3497 if (!add_to_clist(&ct_list
, c
, ct_list_cnt
, false)) {
3498 lxc_container_put(c
);
3517 for (i
= 0; i
< ct_list_cnt
; i
++) {
3518 lxc_container_put(ct_list
[i
]);
3524 for (i
= 0; i
< active_cnt
; i
++) {
3526 free(active_name
[i
]);
3532 for (i
= 0; i
< ct_cnt
; i
++) {