]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lxccontainer.c
destroy: implement in the api
[mirror_lxc.git] / src / lxc / lxccontainer.c
1 /* liblxcapi
2 *
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2, as
8 * published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _GNU_SOURCE
21 #include <pthread.h>
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <sys/wait.h>
25 #include <errno.h>
26 #include <sched.h>
27 #include "config.h"
28 #include "lxc.h"
29 #include "state.h"
30 #include "lxccontainer.h"
31 #include "conf.h"
32 #include "confile.h"
33 #include "cgroup.h"
34 #include "commands.h"
35 #include "version.h"
36 #include "log.h"
37 #include "bdev.h"
38 #include "utils.h"
39 #include <lxc/utils.h>
40 #include <lxc/monitor.h>
41 #include <sched.h>
42 #include <fcntl.h>
43 #include <arpa/inet.h>
44 #include <ifaddrs.h>
45
46 lxc_log_define(lxc_container, lxc);
47
48 static bool file_exists(char *f)
49 {
50 struct stat statbuf;
51
52 return stat(f, &statbuf) == 0;
53 }
54
55 /*
56 * A few functions to help detect when a container creation failed.
57 * If a container creation was killed partway through, then trying
58 * to actually start that container could harm the host. We detect
59 * this by creating a 'partial' file under the container directory,
60 * and keeping an advisory lock. When container creation completes,
61 * we remove that file. When we load or try to start a container, if
62 * we find that file, without a flock, we remove the container.
63 */
64 int ongoing_create(struct lxc_container *c)
65 {
66 int len = strlen(c->config_path) + strlen(c->name) + 10;
67 char *path = alloca(len);
68 int fd, ret;
69 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
70 if (ret < 0 || ret >= len) {
71 ERROR("Error writing partial pathname");
72 return -1;
73 }
74
75 if (!file_exists(path))
76 return 0;
77 if (process_lock())
78 return -1;
79 if ((fd = open(path, O_RDWR)) < 0) {
80 // give benefit of the doubt
81 SYSERROR("Error opening partial file");
82 process_unlock();
83 return 0;
84 }
85 if ((ret = flock(fd, LOCK_EX | LOCK_NB)) == -1 &&
86 errno == EWOULDBLOCK) {
87 // create is still ongoing
88 close(fd);
89 process_unlock();
90 return 1;
91 }
92 // create completed but partial is still there.
93 close(fd);
94 process_unlock();
95 return 2;
96 }
97
98 int create_partial(struct lxc_container *c)
99 {
100 // $lxcpath + '/' + $name + '/partial' + \0
101 int len = strlen(c->config_path) + strlen(c->name) + 10;
102 char *path = alloca(len);
103 int fd, ret;
104 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
105 if (ret < 0 || ret >= len) {
106 ERROR("Error writing partial pathname");
107 return -1;
108 }
109 if (process_lock() < 0)
110 return -1;
111 if ((fd=open(path, O_CREAT | O_EXCL, 0755)) < 0) {
112 SYSERROR("Erorr creating partial file");
113 process_unlock();
114 return -1;
115 }
116 if (flock(fd, LOCK_EX) < 0) {
117 SYSERROR("Error locking partial file %s", path);
118 close(fd);
119 process_unlock();
120 return -1;
121 }
122 process_unlock();
123
124 return fd;
125 }
126
127 void remove_partial(struct lxc_container *c, int fd)
128 {
129 // $lxcpath + '/' + $name + '/partial' + \0
130 int len = strlen(c->config_path) + strlen(c->name) + 10;
131 char *path = alloca(len);
132 int ret;
133
134 close(fd);
135 ret = snprintf(path, len, "%s/%s/partial", c->config_path, c->name);
136 if (ret < 0 || ret >= len) {
137 ERROR("Error writing partial pathname");
138 return;
139 }
140 if (process_lock())
141 return;
142 if (unlink(path) < 0)
143 SYSERROR("Error unlink partial file %s", path);
144 process_unlock();
145 }
146
147 /* LOCKING
148 * 1. c->privlock protects the struct lxc_container from multiple threads.
149 * 2. c->slock protects the on-disk container data
150 * 3. thread_mutex protects process data (ex: fd table) from multiple threads
151 * slock is an flock, which does not exclude threads. Therefore slock should
152 * always be wrapped inside privlock.
153 * NOTHING mutexes two independent programs with their own struct
154 * lxc_container for the same c->name, between API calls. For instance,
155 * c->config_read(); c->start(); Between those calls, data on disk
156 * could change (which shouldn't bother the caller unless for instance
157 * the rootfs get moved). c->config_read(); update; c->config_write();
158 * Two such updaters could race. The callers should therefore check their
159 * results. Trying to prevent that would necessarily expose us to deadlocks
160 * due to hung callers. So I prefer to keep the locks only within our own
161 * functions, not across functions.
162 *
163 * If you're going to fork while holding a lxccontainer, increment
164 * c->numthreads (under privlock) before forking. When deleting,
165 * decrement numthreads under privlock, then if it hits 0 you can delete.
166 * Do not ever use a lxccontainer whose numthreads you did not bump.
167 */
168
169 static void lxc_container_free(struct lxc_container *c)
170 {
171 if (!c)
172 return;
173
174 if (c->configfile) {
175 free(c->configfile);
176 c->configfile = NULL;
177 }
178 if (c->error_string) {
179 free(c->error_string);
180 c->error_string = NULL;
181 }
182 if (c->slock) {
183 lxc_putlock(c->slock);
184 c->slock = NULL;
185 }
186 if (c->privlock) {
187 lxc_putlock(c->privlock);
188 c->privlock = NULL;
189 }
190 if (c->name) {
191 free(c->name);
192 c->name = NULL;
193 }
194 if (c->lxc_conf) {
195 lxc_conf_free(c->lxc_conf);
196 c->lxc_conf = NULL;
197 }
198 if (c->config_path) {
199 free(c->config_path);
200 c->config_path = NULL;
201 }
202 free(c);
203 }
204
205 /*
206 * Consider the following case:
207 freer | racing get()er
208 ==================================================================
209 lxc_container_put() | lxc_container_get()
210 \ lxclock(c->privlock) | c->numthreads < 1? (no)
211 \ c->numthreads = 0 | \ lxclock(c->privlock) -> waits
212 \ lxcunlock() | \
213 \ lxc_container_free() | \ lxclock() returns
214 | \ c->numthreads < 1 -> return 0
215 \ \ (free stuff) |
216 \ \ sem_destroy(privlock) |
217
218 * When the get()er checks numthreads the first time, one of the following
219 * is true:
220 * 1. freer has set numthreads = 0. get() returns 0
221 * 2. freer is between lxclock and setting numthreads to 0. get()er will
222 * sem_wait on privlock, get lxclock after freer() drops it, then see
223 * numthreads is 0 and exit without touching lxclock again..
224 * 3. freer has not yet locked privlock. If get()er runs first, then put()er
225 * will see --numthreads = 1 and not call lxc_container_free().
226 */
227
228 int lxc_container_get(struct lxc_container *c)
229 {
230 if (!c)
231 return 0;
232
233 // if someone else has already started freeing the container, don't
234 // try to take the lock, which may be invalid
235 if (c->numthreads < 1)
236 return 0;
237
238 if (container_mem_lock(c))
239 return 0;
240 if (c->numthreads < 1) {
241 // bail without trying to unlock, bc the privlock is now probably
242 // in freed memory
243 return 0;
244 }
245 c->numthreads++;
246 container_mem_unlock(c);
247 return 1;
248 }
249
250 int lxc_container_put(struct lxc_container *c)
251 {
252 if (!c)
253 return -1;
254 if (container_mem_lock(c))
255 return -1;
256 if (--c->numthreads < 1) {
257 container_mem_unlock(c);
258 lxc_container_free(c);
259 return 1;
260 }
261 container_mem_unlock(c);
262 return 0;
263 }
264
265 static bool lxcapi_is_defined(struct lxc_container *c)
266 {
267 struct stat statbuf;
268 bool ret = false;
269 int statret;
270
271 if (!c)
272 return false;
273
274 if (container_mem_lock(c))
275 return false;
276 if (!c->configfile)
277 goto out;
278 statret = stat(c->configfile, &statbuf);
279 if (statret != 0)
280 goto out;
281 ret = true;
282
283 out:
284 container_mem_unlock(c);
285 return ret;
286 }
287
288 static const char *lxcapi_state(struct lxc_container *c)
289 {
290 const char *ret;
291 lxc_state_t s;
292
293 if (!c)
294 return NULL;
295 if (container_disk_lock(c))
296 return NULL;
297 s = lxc_getstate(c->name, c->config_path);
298 ret = lxc_state2str(s);
299 container_disk_unlock(c);
300
301 return ret;
302 }
303
304 static bool is_stopped_locked(struct lxc_container *c)
305 {
306 lxc_state_t s;
307 s = lxc_getstate(c->name, c->config_path);
308 return (s == STOPPED);
309 }
310
311 static bool lxcapi_is_running(struct lxc_container *c)
312 {
313 const char *s;
314
315 if (!c)
316 return false;
317 s = lxcapi_state(c);
318 if (!s || strcmp(s, "STOPPED") == 0)
319 return false;
320 return true;
321 }
322
323 static bool lxcapi_freeze(struct lxc_container *c)
324 {
325 int ret;
326 if (!c)
327 return false;
328
329 if (container_disk_lock(c))
330 return false;
331 ret = lxc_freeze(c->name, c->config_path);
332 container_disk_unlock(c);
333 if (ret)
334 return false;
335 return true;
336 }
337
338 static bool lxcapi_unfreeze(struct lxc_container *c)
339 {
340 int ret;
341 if (!c)
342 return false;
343
344 if (container_disk_lock(c))
345 return false;
346 ret = lxc_unfreeze(c->name, c->config_path);
347 container_disk_unlock(c);
348 if (ret)
349 return false;
350 return true;
351 }
352
353 static pid_t lxcapi_init_pid(struct lxc_container *c)
354 {
355 if (!c)
356 return -1;
357
358 return lxc_cmd_get_init_pid(c->name, c->config_path);
359 }
360
361 static bool load_config_locked(struct lxc_container *c, const char *fname)
362 {
363 if (!c->lxc_conf)
364 c->lxc_conf = lxc_conf_init();
365 if (c->lxc_conf && !lxc_config_read(fname, c->lxc_conf))
366 return true;
367 return false;
368 }
369
370 static bool lxcapi_load_config(struct lxc_container *c, const char *alt_file)
371 {
372 bool ret = false;
373 const char *fname;
374 if (!c)
375 return false;
376
377 fname = c->configfile;
378 if (alt_file)
379 fname = alt_file;
380 if (!fname)
381 return false;
382 if (container_disk_lock(c))
383 return false;
384 ret = load_config_locked(c, fname);
385 container_disk_unlock(c);
386 return ret;
387 }
388
389 static void lxcapi_want_daemonize(struct lxc_container *c)
390 {
391 if (!c)
392 return;
393 c->daemonize = 1;
394 }
395
396 static bool lxcapi_wait(struct lxc_container *c, const char *state, int timeout)
397 {
398 int ret;
399
400 if (!c)
401 return false;
402
403 ret = lxc_wait(c->name, state, timeout, c->config_path);
404 return ret == 0;
405 }
406
407
408 static bool wait_on_daemonized_start(struct lxc_container *c)
409 {
410 /* we'll probably want to make this timeout configurable? */
411 int timeout = 5, ret, status;
412
413 /*
414 * our child is going to fork again, then exit. reap the
415 * child
416 */
417 ret = wait(&status);
418 if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
419 DEBUG("failed waiting for first dual-fork child");
420 return lxcapi_wait(c, "RUNNING", timeout);
421 }
422
423 /*
424 * I can't decide if it'd be more convenient for callers if we accept '...',
425 * or a null-terminated array (i.e. execl vs execv)
426 */
427 static bool lxcapi_start(struct lxc_container *c, int useinit, char * const argv[])
428 {
429 int ret;
430 struct lxc_conf *conf;
431 int daemonize = 0;
432 char *default_args[] = {
433 "/sbin/init",
434 '\0',
435 };
436
437 /* container exists */
438 if (!c)
439 return false;
440 /* container has been setup */
441 if (!c->lxc_conf)
442 return false;
443
444 if ((ret = ongoing_create(c)) < 0) {
445 ERROR("Error checking for incomplete creation");
446 return false;
447 }
448 if (ret == 2) {
449 ERROR("Error: %s creation was not completed", c->name);
450 c->destroy(c);
451 return false;
452 } else if (ret == 1) {
453 ERROR("Error: creation of %s is ongoing", c->name);
454 return false;
455 }
456
457 /* is this app meant to be run through lxcinit, as in lxc-execute? */
458 if (useinit && !argv)
459 return false;
460
461 if (container_mem_lock(c))
462 return false;
463 conf = c->lxc_conf;
464 daemonize = c->daemonize;
465 container_mem_unlock(c);
466
467 if (useinit) {
468 ret = lxc_execute(c->name, argv, 1, conf, c->config_path);
469 return ret == 0 ? true : false;
470 }
471
472 if (!argv)
473 argv = default_args;
474
475 /*
476 * say, I'm not sure - what locks do we want here? Any?
477 * Is liblxc's locking enough here to protect the on disk
478 * container? We don't want to exclude things like lxc_info
479 * while container is running...
480 */
481 if (daemonize) {
482 if (!lxc_container_get(c))
483 return false;
484 lxc_monitord_spawn(c->config_path);
485
486 if (process_lock())
487 return false;
488 pid_t pid = fork();
489 if (pid < 0) {
490 lxc_container_put(c);
491 process_unlock();
492 return false;
493 }
494 if (pid != 0) {
495 ret = wait_on_daemonized_start(c);
496 process_unlock();
497 return ret;
498 }
499 process_unlock();
500 /* second fork to be reparented by init */
501 pid = fork();
502 if (pid < 0) {
503 SYSERROR("Error doing dual-fork");
504 return false;
505 }
506 if (pid != 0)
507 exit(0);
508 /* like daemon(), chdir to / and redirect 0,1,2 to /dev/null */
509 if (chdir("/")) {
510 SYSERROR("Error chdir()ing to /.");
511 return false;
512 }
513 close(0);
514 close(1);
515 close(2);
516 open("/dev/null", O_RDONLY);
517 open("/dev/null", O_RDWR);
518 open("/dev/null", O_RDWR);
519 setsid();
520 }
521
522 reboot:
523 conf->reboot = 0;
524 ret = lxc_start(c->name, argv, conf, c->config_path);
525
526 if (conf->reboot) {
527 INFO("container requested reboot");
528 conf->reboot = 0;
529 goto reboot;
530 }
531
532 if (daemonize) {
533 lxc_container_put(c);
534 exit (ret == 0 ? true : false);
535 } else {
536 return (ret == 0 ? true : false);
537 }
538 }
539
540 /*
541 * note there MUST be an ending NULL
542 */
543 static bool lxcapi_startl(struct lxc_container *c, int useinit, ...)
544 {
545 va_list ap;
546 char **inargs = NULL, **temp;
547 int n_inargs = 0;
548 bool bret = false;
549
550 /* container exists */
551 if (!c)
552 return false;
553
554 /* build array of arguments if any */
555 va_start(ap, useinit);
556 while (1) {
557 char *arg;
558 arg = va_arg(ap, char *);
559 if (!arg)
560 break;
561 n_inargs++;
562 temp = realloc(inargs, n_inargs * sizeof(*inargs));
563 if (!temp) {
564 va_end(ap);
565 goto out;
566 }
567 inargs = temp;
568 inargs[n_inargs - 1] = strdup(arg); // not sure if it's safe not to copy
569 }
570 va_end(ap);
571
572 /* add trailing NULL */
573 if (n_inargs) {
574 n_inargs++;
575 temp = realloc(inargs, n_inargs * sizeof(*inargs));
576 if (!temp)
577 goto out;
578 inargs = temp;
579 inargs[n_inargs - 1] = NULL;
580 }
581
582 bret = lxcapi_start(c, useinit, inargs);
583
584 out:
585 if (inargs) {
586 int i;
587 for (i = 0; i < n_inargs; i++) {
588 if (inargs[i])
589 free(inargs[i]);
590 }
591 free(inargs);
592 }
593
594 return bret;
595 }
596
597 static bool lxcapi_stop(struct lxc_container *c)
598 {
599 int ret;
600
601 if (!c)
602 return false;
603
604 ret = lxc_cmd_stop(c->name, c->config_path);
605
606 return ret == 0;
607 }
608
609 static bool valid_template(char *t)
610 {
611 struct stat statbuf;
612 int statret;
613
614 statret = stat(t, &statbuf);
615 if (statret == 0)
616 return true;
617 return false;
618 }
619
620 /*
621 * create the standard expected container dir
622 */
623 static bool create_container_dir(struct lxc_container *c)
624 {
625 char *s;
626 int len, ret;
627
628 len = strlen(c->config_path) + strlen(c->name) + 2;
629 s = malloc(len);
630 if (!s)
631 return false;
632 ret = snprintf(s, len, "%s/%s", c->config_path, c->name);
633 if (ret < 0 || ret >= len) {
634 free(s);
635 return false;
636 }
637 ret = mkdir(s, 0755);
638 if (ret) {
639 if (errno == EEXIST)
640 ret = 0;
641 else
642 SYSERROR("failed to create container path for %s\n", c->name);
643 }
644 free(s);
645 return ret == 0;
646 }
647
648 /*
649 * backing stores not (yet) supported
650 * for ->create, argv contains the arguments to pass to the template,
651 * terminated by NULL. If no arguments, you can just pass NULL.
652 */
653 static bool lxcapi_create(struct lxc_container *c, const char *t, char *const argv[])
654 {
655 bool bret = false;
656 pid_t pid;
657 char *tpath = NULL, **newargv;
658 int partial_fd, ret, len, nargs = 0;
659
660 if (!c)
661 return false;
662
663 len = strlen(LXCTEMPLATEDIR) + strlen(t) + strlen("/lxc-") + 1;
664 tpath = malloc(len);
665 if (!tpath)
666 return false;
667 ret = snprintf(tpath, len, "%s/lxc-%s", LXCTEMPLATEDIR, t);
668 if (ret < 0 || ret >= len)
669 goto out;
670 if (!valid_template(tpath)) {
671 ERROR("bad template: %s\n", t);
672 goto out;
673 }
674
675 if (!c->save_config(c, NULL)) {
676 ERROR("failed to save starting configuration for %s\n", c->name);
677 goto out;
678 }
679
680 /* container is already created if we have a config and rootfs.path is accessible */
681 if (lxcapi_is_defined(c) && c->lxc_conf && c->lxc_conf->rootfs.path && access(c->lxc_conf->rootfs.path, F_OK) == 0)
682 goto out;
683
684 /* Mark that this container is being created */
685 if ((partial_fd = create_partial(c)) < 0)
686 goto out;
687
688 /* we're going to fork. but since we'll wait for our child, we
689 * don't need to lxc_container_get */
690
691 if (container_disk_lock(c))
692 goto out;
693
694 pid = fork();
695 if (pid < 0) {
696 SYSERROR("failed to fork task for container creation template\n");
697 goto out_unlock;
698 }
699
700 if (pid == 0) { // child
701 char *patharg, *namearg;
702 int i;
703
704 close(0);
705 close(1);
706 close(2);
707 open("/dev/null", O_RDONLY);
708 open("/dev/null", O_RDWR);
709 open("/dev/null", O_RDWR);
710
711 /*
712 * create our new array, pre-pend the template name and
713 * base args
714 */
715 if (argv)
716 for (; argv[nargs]; nargs++) ;
717 nargs += 3; // template, path and name args
718 newargv = malloc(nargs * sizeof(*newargv));
719 if (!newargv)
720 exit(1);
721 newargv[0] = (char *)t;
722
723 len = strlen(c->config_path) + strlen(c->name) + strlen("--path=") + 2;
724 patharg = malloc(len);
725 if (!patharg)
726 exit(1);
727 ret = snprintf(patharg, len, "--path=%s/%s", c->config_path, c->name);
728 if (ret < 0 || ret >= len)
729 exit(1);
730 newargv[1] = patharg;
731 len = strlen("--name=") + strlen(c->name) + 1;
732 namearg = malloc(len);
733 if (!namearg)
734 exit(1);
735 ret = snprintf(namearg, len, "--name=%s", c->name);
736 if (ret < 0 || ret >= len)
737 exit(1);
738 newargv[2] = namearg;
739
740 /* add passed-in args */
741 if (argv)
742 for (i = 3; i < nargs; i++)
743 newargv[i] = argv[i-3];
744
745 /* add trailing NULL */
746 nargs++;
747 newargv = realloc(newargv, nargs * sizeof(*newargv));
748 if (!newargv)
749 exit(1);
750 newargv[nargs - 1] = NULL;
751
752 /* execute */
753 execv(tpath, newargv);
754 SYSERROR("failed to execute template %s", tpath);
755 exit(1);
756 }
757
758 if (wait_for_pid(pid) != 0) {
759 ERROR("container creation template for %s failed\n", c->name);
760 goto out_unlock;
761 }
762
763 // now clear out the lxc_conf we have, reload from the created
764 // container
765 if (c->lxc_conf)
766 lxc_conf_free(c->lxc_conf);
767 c->lxc_conf = NULL;
768 bret = load_config_locked(c, c->configfile);
769
770 out_unlock:
771 if (partial_fd >= 0)
772 remove_partial(c, partial_fd);
773 container_disk_unlock(c);
774 out:
775 if (tpath)
776 free(tpath);
777 return bret;
778 }
779
780 static bool lxcapi_reboot(struct lxc_container *c)
781 {
782 pid_t pid;
783
784 if (!c)
785 return false;
786 if (!c->is_running(c))
787 return false;
788 pid = c->init_pid(c);
789 if (pid <= 0)
790 return false;
791 if (kill(pid, SIGINT) < 0)
792 return false;
793 return true;
794
795 }
796
797 static bool lxcapi_shutdown(struct lxc_container *c, int timeout)
798 {
799 bool retv;
800 pid_t pid;
801
802 if (!c)
803 return false;
804
805 if (!timeout)
806 timeout = -1;
807 if (!c->is_running(c))
808 return true;
809 pid = c->init_pid(c);
810 if (pid <= 0)
811 return true;
812 kill(pid, SIGPWR);
813 retv = c->wait(c, "STOPPED", timeout);
814 if (!retv && timeout > 0) {
815 c->stop(c);
816 retv = c->wait(c, "STOPPED", 0); // 0 means don't wait
817 }
818 return retv;
819 }
820
821 static bool lxcapi_createl(struct lxc_container *c, const char *t, ...)
822 {
823 bool bret = false;
824 char **args = NULL, **temp;
825 va_list ap;
826 int nargs = 0;
827
828 if (!c)
829 return false;
830
831 /*
832 * since we're going to wait for create to finish, I don't think we
833 * need to get a copy of the arguments.
834 */
835 va_start(ap, t);
836 while (1) {
837 char *arg;
838 arg = va_arg(ap, char *);
839 if (!arg)
840 break;
841 nargs++;
842 temp = realloc(args, (nargs+1) * sizeof(*args));
843 if (!temp) {
844 va_end(ap);
845 goto out;
846 }
847 args = temp;
848 args[nargs - 1] = arg;
849 }
850 va_end(ap);
851 if (args)
852 args[nargs] = NULL;
853
854 bret = c->create(c, t, args);
855
856 out:
857 if (args)
858 free(args);
859 return bret;
860 }
861
862 static bool lxcapi_clear_config_item(struct lxc_container *c, const char *key)
863 {
864 int ret;
865
866 if (!c || !c->lxc_conf)
867 return false;
868 if (container_mem_lock(c))
869 return false;
870 ret = lxc_clear_config_item(c->lxc_conf, key);
871 container_mem_unlock(c);
872 return ret == 0;
873 }
874
875 char** lxcapi_get_ips(struct lxc_container *c, char* interface, char* family, int scope)
876 {
877 int count = 0;
878 struct ifaddrs *interfaceArray = NULL, *tempIfAddr = NULL;
879 char addressOutputBuffer[INET6_ADDRSTRLEN];
880 void *tempAddrPtr = NULL;
881 char **addresses = NULL, **temp;
882 char *address = NULL;
883 char new_netns_path[MAXPATHLEN];
884 int old_netns = -1, new_netns = -1, ret = 0;
885
886 if (!c->is_running(c))
887 goto out;
888
889 /* Save reference to old netns */
890 old_netns = open("/proc/self/ns/net", O_RDONLY);
891 if (old_netns < 0) {
892 SYSERROR("failed to open /proc/self/ns/net");
893 goto out;
894 }
895
896 /* Switch to new netns */
897 ret = snprintf(new_netns_path, MAXPATHLEN, "/proc/%d/ns/net", c->init_pid(c));
898 if (ret < 0 || ret >= MAXPATHLEN)
899 goto out;
900
901 new_netns = open(new_netns_path, O_RDONLY);
902 if (new_netns < 0) {
903 SYSERROR("failed to open %s", new_netns_path);
904 goto out;
905 }
906
907 if (setns(new_netns, CLONE_NEWNET)) {
908 SYSERROR("failed to setns");
909 goto out;
910 }
911
912 /* Grab the list of interfaces */
913 if (getifaddrs(&interfaceArray)) {
914 SYSERROR("failed to get interfaces list");
915 goto out;
916 }
917
918 /* Iterate through the interfaces */
919 for (tempIfAddr = interfaceArray; tempIfAddr != NULL; tempIfAddr = tempIfAddr->ifa_next) {
920 if(tempIfAddr->ifa_addr->sa_family == AF_INET) {
921 if (family && strcmp(family, "inet"))
922 continue;
923 tempAddrPtr = &((struct sockaddr_in *)tempIfAddr->ifa_addr)->sin_addr;
924 }
925 else {
926 if (family && strcmp(family, "inet6"))
927 continue;
928
929 if (((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_scope_id != scope)
930 continue;
931
932 tempAddrPtr = &((struct sockaddr_in6 *)tempIfAddr->ifa_addr)->sin6_addr;
933 }
934
935 if (interface && strcmp(interface, tempIfAddr->ifa_name))
936 continue;
937 else if (!interface && strcmp("lo", tempIfAddr->ifa_name) == 0)
938 continue;
939
940 address = (char *)inet_ntop(tempIfAddr->ifa_addr->sa_family,
941 tempAddrPtr,
942 addressOutputBuffer,
943 sizeof(addressOutputBuffer));
944 if (!address)
945 continue;
946
947 count += 1;
948 temp = realloc(addresses, count * sizeof(*addresses));
949 if (!temp) {
950 count--;
951 goto out;
952 }
953 addresses = temp;
954 addresses[count - 1] = strdup(address);
955 }
956
957 out:
958 if(interfaceArray)
959 freeifaddrs(interfaceArray);
960
961 /* Switch back to original netns */
962 if (old_netns >= 0 && setns(old_netns, CLONE_NEWNET))
963 SYSERROR("failed to setns");
964 if (new_netns >= 0)
965 close(new_netns);
966 if (old_netns >= 0)
967 close(old_netns);
968
969 /* Append NULL to the array */
970 if (count) {
971 count++;
972 temp = realloc(addresses, count * sizeof(*addresses));
973 if (!temp) {
974 int i;
975 for (i = 0; i < count-1; i++)
976 free(addresses[i]);
977 free(addresses);
978 return NULL;
979 }
980 addresses = temp;
981 addresses[count - 1] = NULL;
982 }
983
984 return addresses;
985 }
986
987 static int lxcapi_get_config_item(struct lxc_container *c, const char *key, char *retv, int inlen)
988 {
989 int ret;
990
991 if (!c || !c->lxc_conf)
992 return -1;
993 if (container_mem_lock(c))
994 return -1;
995 ret = lxc_get_config_item(c->lxc_conf, key, retv, inlen);
996 container_mem_unlock(c);
997 return ret;
998 }
999
1000 static int lxcapi_get_keys(struct lxc_container *c, const char *key, char *retv, int inlen)
1001 {
1002 if (!key)
1003 return lxc_listconfigs(retv, inlen);
1004 /*
1005 * Support 'lxc.network.<idx>', i.e. 'lxc.network.0'
1006 * This is an intelligent result to show which keys are valid given
1007 * the type of nic it is
1008 */
1009 if (!c || !c->lxc_conf)
1010 return -1;
1011 if (container_mem_lock(c))
1012 return -1;
1013 int ret = -1;
1014 if (strncmp(key, "lxc.network.", 12) == 0)
1015 ret = lxc_list_nicconfigs(c->lxc_conf, key, retv, inlen);
1016 container_mem_unlock(c);
1017 return ret;
1018 }
1019
1020
1021 /* default config file - should probably come through autoconf */
1022 #define LXC_DEFAULT_CONFIG "/etc/lxc/default.conf"
1023 static bool lxcapi_save_config(struct lxc_container *c, const char *alt_file)
1024 {
1025 if (!alt_file)
1026 alt_file = c->configfile;
1027 if (!alt_file)
1028 return false; // should we write to stdout if no file is specified?
1029 if (!c->lxc_conf)
1030 if (!c->load_config(c, LXC_DEFAULT_CONFIG)) {
1031 ERROR("Error loading default configuration file %s while saving %s\n", LXC_DEFAULT_CONFIG, c->name);
1032 return false;
1033 }
1034
1035 if (!create_container_dir(c))
1036 return false;
1037
1038 FILE *fout = fopen(alt_file, "w");
1039 if (!fout)
1040 return false;
1041 if (container_mem_lock(c)) {
1042 fclose(fout);
1043 return false;
1044 }
1045 write_config(fout, c->lxc_conf);
1046 fclose(fout);
1047 container_mem_unlock(c);
1048 return true;
1049 }
1050
1051 static const char *lxcapi_get_config_path(struct lxc_container *c);
1052 // do we want the api to support --force, or leave that to the caller?
1053 static bool lxcapi_destroy(struct lxc_container *c)
1054 {
1055 struct bdev *r;
1056 bool ret = false;
1057
1058 /* container is already destroyed if we don't have a config and rootfs.path is not accessible */
1059 if (!c || !lxcapi_is_defined(c) || !c->lxc_conf || !c->lxc_conf->rootfs.path)
1060 return false;
1061
1062 if (lxclock(c->privlock, 0))
1063 return false;
1064 if (lxclock(c->slock, 0)) {
1065 lxcunlock(c->privlock);
1066 return false;
1067 }
1068
1069 if (!is_stopped_locked(c)) {
1070 // we should queue some sort of error - in c->error_string?
1071 ERROR("container %s is not stopped", c->name);
1072 goto out;
1073 }
1074
1075 r = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
1076 if (r) {
1077 if (r->ops->destroy(r) < 0) {
1078 ERROR("Error destroying rootfs for %s", c->name);
1079 goto out;
1080 }
1081 }
1082
1083 const char *p1 = lxcapi_get_config_path(c);
1084 char *path = alloca(strlen(p1) + strlen(c->name) + 2);
1085 sprintf(path, "%s/%s", p1, c->name);
1086 if (lxc_rmdir_onedev(path) < 0) {
1087 ERROR("Error destroying container directory for %s", c->name);
1088 goto out;
1089 }
1090 ret = true;
1091
1092 out:
1093 lxcunlock(c->privlock);
1094 lxcunlock(c->slock);
1095 return ret;
1096 }
1097
1098 static bool lxcapi_set_config_item(struct lxc_container *c, const char *key, const char *v)
1099 {
1100 int ret;
1101 bool b = false;
1102 struct lxc_config_t *config;
1103
1104 if (!c)
1105 return false;
1106
1107 if (container_mem_lock(c))
1108 return false;
1109
1110 if (!c->lxc_conf)
1111 c->lxc_conf = lxc_conf_init();
1112 if (!c->lxc_conf)
1113 goto err;
1114 config = lxc_getconfig(key);
1115 if (!config)
1116 goto err;
1117 ret = config->cb(key, v, c->lxc_conf);
1118 if (!ret)
1119 b = true;
1120
1121 err:
1122 container_mem_unlock(c);
1123 return b;
1124 }
1125
1126 static char *lxcapi_config_file_name(struct lxc_container *c)
1127 {
1128 if (!c || !c->configfile)
1129 return NULL;
1130 return strdup(c->configfile);
1131 }
1132
1133 static const char *lxcapi_get_config_path(struct lxc_container *c)
1134 {
1135 if (!c || !c->config_path)
1136 return NULL;
1137 return (const char *)(c->config_path);
1138 }
1139
1140 /*
1141 * not for export
1142 * Just recalculate the c->configfile based on the
1143 * c->config_path, which must be set.
1144 * The lxc_container must be locked or not yet public.
1145 */
1146 static bool set_config_filename(struct lxc_container *c)
1147 {
1148 char *newpath;
1149 int len, ret;
1150
1151 if (!c->config_path)
1152 return false;
1153
1154 /* $lxc_path + "/" + c->name + "/" + "config" + '\0' */
1155 len = strlen(c->config_path) + strlen(c->name) + strlen("config") + 3;
1156 newpath = malloc(len);
1157 if (!newpath)
1158 return false;
1159
1160 ret = snprintf(newpath, len, "%s/%s/config", c->config_path, c->name);
1161 if (ret < 0 || ret >= len) {
1162 fprintf(stderr, "Error printing out config file name\n");
1163 free(newpath);
1164 return false;
1165 }
1166
1167 if (c->configfile)
1168 free(c->configfile);
1169 c->configfile = newpath;
1170
1171 return true;
1172 }
1173
1174 static bool lxcapi_set_config_path(struct lxc_container *c, const char *path)
1175 {
1176 char *p;
1177 bool b = false;
1178 char *oldpath = NULL;
1179
1180 if (!c)
1181 return b;
1182
1183 if (container_mem_lock(c))
1184 return b;
1185
1186 p = strdup(path);
1187 if (!p) {
1188 ERROR("Out of memory setting new lxc path");
1189 goto err;
1190 }
1191
1192 b = true;
1193 if (c->config_path)
1194 oldpath = c->config_path;
1195 c->config_path = p;
1196
1197 /* Since we've changed the config path, we have to change the
1198 * config file name too */
1199 if (!set_config_filename(c)) {
1200 ERROR("Out of memory setting new config filename");
1201 b = false;
1202 free(c->config_path);
1203 c->config_path = oldpath;
1204 oldpath = NULL;
1205 }
1206 err:
1207 if (oldpath)
1208 free(oldpath);
1209 container_mem_unlock(c);
1210 return b;
1211 }
1212
1213
1214 static bool lxcapi_set_cgroup_item(struct lxc_container *c, const char *subsys, const char *value)
1215 {
1216 int ret;
1217 bool b = false;
1218
1219 if (!c)
1220 return false;
1221
1222 if (container_mem_lock(c))
1223 return false;
1224
1225 if (is_stopped_locked(c))
1226 goto err;
1227
1228 ret = lxc_cgroup_set(c->name, subsys, value, c->config_path);
1229 if (!ret)
1230 b = true;
1231 err:
1232 container_mem_unlock(c);
1233 return b;
1234 }
1235
1236 static int lxcapi_get_cgroup_item(struct lxc_container *c, const char *subsys, char *retv, int inlen)
1237 {
1238 int ret = -1;
1239
1240 if (!c || !c->lxc_conf)
1241 return -1;
1242
1243 if (container_mem_lock(c))
1244 return -1;
1245
1246 if (is_stopped_locked(c))
1247 goto out;
1248
1249 ret = lxc_cgroup_get(c->name, subsys, retv, inlen, c->config_path);
1250
1251 out:
1252 container_mem_unlock(c);
1253 return ret;
1254 }
1255
1256 const char *lxc_get_default_config_path(void)
1257 {
1258 return default_lxc_path();
1259 }
1260
1261 const char *lxc_get_default_lvm_vg(void)
1262 {
1263 return default_lvm_vg();
1264 }
1265
1266 const char *lxc_get_default_zfs_root(void)
1267 {
1268 return default_zfs_root();
1269 }
1270
1271 const char *lxc_get_version(void)
1272 {
1273 return lxc_version();
1274 }
1275
1276 static int copy_file(char *old, char *new)
1277 {
1278 int in, out;
1279 ssize_t len, ret;
1280 char buf[8096];
1281 struct stat sbuf;
1282
1283 if (file_exists(new)) {
1284 ERROR("copy destination %s exists", new);
1285 return -1;
1286 }
1287 ret = stat(old, &sbuf);
1288 if (ret < 0) {
1289 SYSERROR("stat'ing %s", old);
1290 return -1;
1291 }
1292
1293 in = open(old, O_RDONLY);
1294 if (in < 0) {
1295 SYSERROR("opening original file %s", old);
1296 return -1;
1297 }
1298 out = open(new, O_CREAT | O_EXCL | O_WRONLY, 0644);
1299 if (out < 0) {
1300 SYSERROR("opening new file %s", new);
1301 close(in);
1302 return -1;
1303 }
1304
1305 while (1) {
1306 len = read(in, buf, 8096);
1307 if (len < 0) {
1308 SYSERROR("reading old file %s", old);
1309 goto err;
1310 }
1311 if (len == 0)
1312 break;
1313 ret = write(out, buf, len);
1314 if (ret < len) { // should we retry?
1315 SYSERROR("write to new file %s was interrupted", new);
1316 goto err;
1317 }
1318 }
1319 close(in);
1320 close(out);
1321
1322 // we set mode, but not owner/group
1323 ret = chmod(new, sbuf.st_mode);
1324 if (ret) {
1325 SYSERROR("setting mode on %s", new);
1326 return -1;
1327 }
1328
1329 return 0;
1330
1331 err:
1332 close(in);
1333 close(out);
1334 return -1;
1335 }
1336
1337 /*
1338 * we're being passed result of two strstrs(x, y). We want to write
1339 * all data up to the first found string, or to end of the string if
1340 * neither string was found.
1341 * This function will return the earliest found string if any, or else
1342 * NULL
1343 */
1344 static const char *lowest_nonnull(const char *p1, const char *p2)
1345 {
1346 if (!p1)
1347 return p2;
1348 if (!p2)
1349 return p1;
1350 return p1 < p2 ? p1 : p2;
1351 }
1352
1353 static int is_word_sep(char c)
1354 {
1355 switch(c) {
1356 case '\0':
1357 case '\n':
1358 case '\r':
1359 case '\t':
1360 case ' ':
1361 case '=':
1362 case '/':
1363 return 1;
1364 default: return 0;
1365 }
1366 }
1367
1368 static const char *find_first_wholeword(const char *p, const char *word)
1369 {
1370 if (!p)
1371 return NULL;
1372
1373 while ((p = strstr(p, word)) != NULL) {
1374 if (is_word_sep(*(p-1)) && is_word_sep(p[strlen(word)]))
1375 return p;
1376 p++;
1377 }
1378 return NULL;
1379 }
1380
1381 static int update_name_and_paths(const char *path, struct lxc_container *oldc,
1382 const char *newname, const char *newpath)
1383 {
1384 FILE *f;
1385 long flen;
1386 char *contents;
1387 const char *p0, *p1, *p2, *end;
1388 const char *oldpath = oldc->get_config_path(oldc);
1389 const char *oldname = oldc->name;
1390
1391 f = fopen(path, "r");
1392 if (!f) {
1393 SYSERROR("opening old config");
1394 return -1;
1395 }
1396 if (fseek(f, 0, SEEK_END) < 0) {
1397 SYSERROR("seeking to end of old config");
1398 fclose(f);
1399 return -1;
1400 }
1401 flen = ftell(f);
1402 if (flen < 0) {
1403 fclose(f);
1404 SYSERROR("telling size of old config");
1405 return -1;
1406 }
1407 if (fseek(f, 0, SEEK_SET) < 0) {
1408 fclose(f);
1409 SYSERROR("rewinding old config");
1410 return -1;
1411 }
1412 contents = malloc(flen+1);
1413 if (!contents) {
1414 SYSERROR("out of memory");
1415 fclose(f);
1416 return -1;
1417 }
1418 if (fread(contents, 1, flen, f) != flen) {
1419 free(contents);
1420 fclose(f);
1421 SYSERROR("reading old config");
1422 return -1;
1423 }
1424 contents[flen] = '\0';
1425 if (fclose(f) < 0) {
1426 free(contents);
1427 SYSERROR("closing old config");
1428 return -1;
1429 }
1430
1431 f = fopen(path, "w");
1432 if (!f) {
1433 SYSERROR("reopening config");
1434 free(contents);
1435 return -1;
1436 }
1437
1438 p0 = contents;
1439 end = contents + flen;
1440 while (1) {
1441 p1 = find_first_wholeword(p0, oldpath);
1442 p2 = find_first_wholeword(p0, oldname);
1443 if (!p1 && !p2) {
1444 // write the rest and be done
1445 if (fwrite(p0, 1, (end-p0), f) != (end-p0)) {
1446 SYSERROR("writing new config");
1447 free(contents);
1448 fclose(f);
1449 return -1;
1450 }
1451 free(contents);
1452 fclose(f);
1453 // success
1454 return 0;
1455 } else {
1456 const char *p = lowest_nonnull(p1, p2);
1457 const char *new = (p == p2) ? newname : newpath;
1458 if (fwrite(p0, 1, (p-p0), f) != (p-p0)) {
1459 SYSERROR("writing new config");
1460 free(contents);
1461 fclose(f);
1462 return -1;
1463 }
1464 p0 = p;
1465 // now write the newpath or newname
1466 if (fwrite(new, 1, strlen(new), f) != strlen(new)) {
1467 SYSERROR("writing new name or path in new config");
1468 free(contents);
1469 fclose(f);
1470 return -1;
1471 }
1472 p0 += (p == p2) ? strlen(oldname) : strlen(oldpath);
1473 }
1474 }
1475 }
1476
1477 static int copyhooks(struct lxc_container *oldc, struct lxc_container *c)
1478 {
1479 int i;
1480 int ret;
1481 struct lxc_list *it;
1482
1483 for (i=0; i<NUM_LXC_HOOKS; i++) {
1484 lxc_list_for_each(it, &c->lxc_conf->hooks[i]) {
1485 char *hookname = it->elem;
1486 char *fname = rindex(hookname, '/');
1487 char tmppath[MAXPATHLEN];
1488 if (!fname) // relative path - we don't support, but maybe we should
1489 return 0;
1490 // copy the script, and change the entry in confile
1491 ret = snprintf(tmppath, MAXPATHLEN, "%s/%s/%s",
1492 c->config_path, c->name, fname+1);
1493 if (ret < 0 || ret >= MAXPATHLEN)
1494 return -1;
1495 ret = copy_file(it->elem, tmppath);
1496 if (ret < 0)
1497 return -1;
1498 free(it->elem);
1499 it->elem = strdup(tmppath);
1500 if (!it->elem) {
1501 ERROR("out of memory copying hook path");
1502 return -1;
1503 }
1504 update_name_and_paths(it->elem, oldc, c->name, c->get_config_path(c));
1505 }
1506 }
1507
1508 c->save_config(c, NULL);
1509 return 0;
1510 }
1511
1512 static void new_hwaddr(char *hwaddr)
1513 {
1514 FILE *f = fopen("/dev/urandom", "r");
1515 if (f) {
1516 unsigned int seed;
1517 int ret = fread(&seed, sizeof(seed), 1, f);
1518 if (ret != 1)
1519 seed = time(NULL);
1520 fclose(f);
1521 srand(seed);
1522 } else
1523 srand(time(NULL));
1524 snprintf(hwaddr, 18, "00:16:3e:%02x:%02x:%02x",
1525 rand() % 255, rand() % 255, rand() % 255);
1526 }
1527
1528 static void network_new_hwaddrs(struct lxc_container *c)
1529 {
1530 struct lxc_list *it;
1531
1532 lxc_list_for_each(it, &c->lxc_conf->network) {
1533 struct lxc_netdev *n = it->elem;
1534 if (n->hwaddr)
1535 new_hwaddr(n->hwaddr);
1536 }
1537 }
1538
1539 static int copy_fstab(struct lxc_container *oldc, struct lxc_container *c)
1540 {
1541 char newpath[MAXPATHLEN];
1542 char *oldpath = oldc->lxc_conf->fstab;
1543 int ret;
1544
1545 if (!oldpath)
1546 return 0;
1547
1548 char *p = rindex(oldpath, '/');
1549 if (!p)
1550 return -1;
1551 ret = snprintf(newpath, MAXPATHLEN, "%s/%s%s",
1552 c->config_path, c->name, p);
1553 if (ret < 0 || ret >= MAXPATHLEN) {
1554 ERROR("error printing new path for %s", oldpath);
1555 return -1;
1556 }
1557 if (file_exists(newpath)) {
1558 ERROR("error: fstab file %s exists", newpath);
1559 return -1;
1560 }
1561
1562 if (copy_file(oldpath, newpath) < 0) {
1563 ERROR("error: copying %s to %s", oldpath, newpath);
1564 return -1;
1565 }
1566 free(c->lxc_conf->fstab);
1567 c->lxc_conf->fstab = strdup(newpath);
1568 if (!c->lxc_conf->fstab) {
1569 ERROR("error: allocating pathname");
1570 return -1;
1571 }
1572
1573 return 0;
1574 }
1575
1576 static int copy_storage(struct lxc_container *c0, struct lxc_container *c,
1577 const char *newtype, int flags, const char *bdevdata, unsigned long newsize)
1578 {
1579 struct bdev *bdev;
1580
1581 bdev = bdev_copy(c0->lxc_conf->rootfs.path, c0->name, c->name,
1582 c0->config_path, c->config_path, newtype, !!(flags & LXC_CLONE_SNAPSHOT),
1583 bdevdata, newsize);
1584 if (!bdev) {
1585 ERROR("error copying storage");
1586 return -1;
1587 }
1588 free(c->lxc_conf->rootfs.path);
1589 c->lxc_conf->rootfs.path = strdup(bdev->src);
1590 bdev_put(bdev);
1591 if (!c->lxc_conf->rootfs.path)
1592 return -1;
1593 // here we could also update all lxc.mount.entries or even
1594 // items in the lxc.mount fstab list. As discussed on m-l,
1595 // we could do either any source paths starting with the
1596 // lxcpath/oldname, or simply anythign which is not a virtual
1597 // fs or a bind mount.
1598 return 0;
1599 }
1600
1601 static int clone_update_rootfs(struct lxc_container *c, int flags, char **hookargs)
1602 {
1603 int ret = -1;
1604 char path[MAXPATHLEN];
1605 struct bdev *bdev;
1606 FILE *fout;
1607 pid_t pid;
1608 struct lxc_conf *conf = c->lxc_conf;
1609
1610 /* update hostname in rootfs */
1611 /* we're going to mount, so run in a clean namespace to simplify cleanup */
1612
1613 pid = fork();
1614 if (pid < 0)
1615 return -1;
1616 if (pid > 0)
1617 return wait_for_pid(pid);
1618
1619 if (unshare(CLONE_NEWNS) < 0) {
1620 ERROR("error unsharing mounts");
1621 exit(1);
1622 }
1623 bdev = bdev_init(c->lxc_conf->rootfs.path, c->lxc_conf->rootfs.mount, NULL);
1624 if (!bdev)
1625 exit(1);
1626 if (bdev->ops->mount(bdev) < 0)
1627 exit(1);
1628
1629 if (!lxc_list_empty(&conf->hooks[LXCHOOK_CLONE])) {
1630 /* Start of environment variable setup for hooks */
1631 if (setenv("LXC_NAME", c->name, 1)) {
1632 SYSERROR("failed to set environment variable for container name");
1633 }
1634 if (setenv("LXC_CONFIG_FILE", conf->rcfile, 1)) {
1635 SYSERROR("failed to set environment variable for config path");
1636 }
1637 if (setenv("LXC_ROOTFS_MOUNT", conf->rootfs.mount, 1)) {
1638 SYSERROR("failed to set environment variable for rootfs mount");
1639 }
1640 if (setenv("LXC_ROOTFS_PATH", conf->rootfs.path, 1)) {
1641 SYSERROR("failed to set environment variable for rootfs mount");
1642 }
1643
1644 if (run_lxc_hooks(c->name, "clone", conf, hookargs)) {
1645 ERROR("Error executing clone hook for %s", c->name);
1646 exit(1);
1647 }
1648 }
1649
1650 if (!(flags & LXC_CLONE_KEEPNAME)) {
1651 ret = snprintf(path, MAXPATHLEN, "%s/etc/hostname", bdev->dest);
1652 if (ret < 0 || ret >= MAXPATHLEN)
1653 exit(1);
1654 if (!(fout = fopen(path, "w"))) {
1655 SYSERROR("unable to open %s: ignoring\n", path);
1656 exit(0);
1657 }
1658 if (fprintf(fout, "%s", c->name) < 0)
1659 exit(1);
1660 if (fclose(fout) < 0)
1661 exit(1);
1662 }
1663 exit(0);
1664 }
1665
1666 /*
1667 * We want to support:
1668 sudo lxc-clone -o o1 -n n1 -s -L|-fssize fssize -v|--vgname vgname \
1669 -p|--lvprefix lvprefix -t|--fstype fstype -B backingstore
1670
1671 -s [ implies overlayfs]
1672 -s -B overlayfs
1673 -s -B aufs
1674
1675 only rootfs gets converted (copied/snapshotted) on clone.
1676 */
1677
1678 static int create_file_dirname(char *path)
1679 {
1680 char *p = rindex(path, '/');
1681 int ret;
1682
1683 if (!p)
1684 return -1;
1685 *p = '\0';
1686 ret = mkdir(path, 0755);
1687 if (ret && errno != EEXIST)
1688 SYSERROR("creating container path %s\n", path);
1689 *p = '/';
1690 return ret;
1691 }
1692
1693 struct lxc_container *lxcapi_clone(struct lxc_container *c, const char *newname,
1694 const char *lxcpath, int flags,
1695 const char *bdevtype, const char *bdevdata, unsigned long newsize,
1696 char **hookargs)
1697 {
1698 struct lxc_container *c2 = NULL;
1699 char newpath[MAXPATHLEN];
1700 int ret;
1701 const char *n, *l;
1702 FILE *fout;
1703
1704 if (!c || !c->is_defined(c))
1705 return NULL;
1706
1707 if (container_mem_lock(c))
1708 return NULL;
1709
1710 if (c->is_running(c)) {
1711 ERROR("error: Original container (%s) is running", c->name);
1712 goto out;
1713 }
1714
1715 // Make sure the container doesn't yet exist.
1716 n = newname ? newname : c->name;
1717 l = lxcpath ? lxcpath : c->get_config_path(c);
1718 ret = snprintf(newpath, MAXPATHLEN, "%s/%s/config", l, n);
1719 if (ret < 0 || ret >= MAXPATHLEN) {
1720 SYSERROR("clone: failed making config pathname");
1721 goto out;
1722 }
1723 if (file_exists(newpath)) {
1724 ERROR("error: clone: %s exists", newpath);
1725 goto out;
1726 }
1727
1728 if (create_file_dirname(newpath) < 0) {
1729 ERROR("Error creating container dir for %s", newpath);
1730 goto out;
1731 }
1732
1733 // copy the configuration, tweak it as needed,
1734 fout = fopen(newpath, "w");
1735 if (!fout) {
1736 SYSERROR("open %s", newpath);
1737 goto out;
1738 }
1739 write_config(fout, c->lxc_conf);
1740 fclose(fout);
1741
1742 if (update_name_and_paths(newpath, c, n, l) < 0) {
1743 ERROR("Error updating name in cloned config");
1744 goto out;
1745 }
1746
1747 sprintf(newpath, "%s/%s/rootfs", l, n);
1748 if (mkdir(newpath, 0755) < 0) {
1749 SYSERROR("error creating %s", newpath);
1750 goto out;
1751 }
1752
1753 c2 = lxc_container_new(n, l);
1754 if (!c2) {
1755 ERROR("clone: failed to create new container (%s %s)", n, l);
1756 goto out;
1757 }
1758
1759 // copy hooks if requested
1760 if (flags & LXC_CLONE_COPYHOOKS) {
1761 ret = copyhooks(c, c2);
1762 if (ret < 0) {
1763 ERROR("error copying hooks");
1764 goto out;
1765 }
1766 }
1767
1768 if (copy_fstab(c, c2) < 0) {
1769 ERROR("error copying fstab");
1770 goto out;
1771 }
1772
1773 // update macaddrs
1774 if (!(flags & LXC_CLONE_KEEPMACADDR))
1775 network_new_hwaddrs(c2);
1776
1777 // copy/snapshot rootfs's
1778 ret = copy_storage(c, c2, bdevtype, flags, bdevdata, newsize);
1779 if (ret < 0)
1780 goto out;
1781
1782 if (!c2->save_config(c2, NULL))
1783 goto out;
1784
1785 if (clone_update_rootfs(c2, flags, hookargs) < 0)
1786 goto out;
1787
1788 // TODO: update c's lxc.snapshot = count
1789 container_mem_unlock(c);
1790 return c2;
1791
1792 out:
1793 container_mem_unlock(c);
1794 if (c2) {
1795 c2->destroy(c2);
1796 lxc_container_put(c2);
1797 }
1798
1799 return NULL;
1800 }
1801
1802 struct lxc_container *lxc_container_new(const char *name, const char *configpath)
1803 {
1804 struct lxc_container *c;
1805
1806 c = malloc(sizeof(*c));
1807 if (!c) {
1808 fprintf(stderr, "failed to malloc lxc_container\n");
1809 return NULL;
1810 }
1811 memset(c, 0, sizeof(*c));
1812
1813 if (configpath)
1814 c->config_path = strdup(configpath);
1815 else
1816 c->config_path = strdup(default_lxc_path());
1817
1818 if (!c->config_path) {
1819 fprintf(stderr, "Out of memory");
1820 goto err;
1821 }
1822
1823 c->name = malloc(strlen(name)+1);
1824 if (!c->name) {
1825 fprintf(stderr, "Error allocating lxc_container name\n");
1826 goto err;
1827 }
1828 strcpy(c->name, name);
1829
1830 c->numthreads = 1;
1831 if (!(c->slock = lxc_newlock(c->config_path, name))) {
1832 fprintf(stderr, "failed to create lock\n");
1833 goto err;
1834 }
1835
1836 if (!(c->privlock = lxc_newlock(NULL, NULL))) {
1837 fprintf(stderr, "failed to alloc privlock\n");
1838 goto err;
1839 }
1840
1841 if (!set_config_filename(c)) {
1842 fprintf(stderr, "Error allocating config file pathname\n");
1843 goto err;
1844 }
1845
1846 if (file_exists(c->configfile))
1847 lxcapi_load_config(c, NULL);
1848
1849 if (ongoing_create(c) == 2) {
1850 ERROR("Error: %s creation was not completed", c->name);
1851 c->destroy(c);
1852 goto err;
1853 }
1854
1855 // assign the member functions
1856 c->is_defined = lxcapi_is_defined;
1857 c->state = lxcapi_state;
1858 c->is_running = lxcapi_is_running;
1859 c->freeze = lxcapi_freeze;
1860 c->unfreeze = lxcapi_unfreeze;
1861 c->init_pid = lxcapi_init_pid;
1862 c->load_config = lxcapi_load_config;
1863 c->want_daemonize = lxcapi_want_daemonize;
1864 c->start = lxcapi_start;
1865 c->startl = lxcapi_startl;
1866 c->stop = lxcapi_stop;
1867 c->config_file_name = lxcapi_config_file_name;
1868 c->wait = lxcapi_wait;
1869 c->set_config_item = lxcapi_set_config_item;
1870 c->destroy = lxcapi_destroy;
1871 c->save_config = lxcapi_save_config;
1872 c->get_keys = lxcapi_get_keys;
1873 c->create = lxcapi_create;
1874 c->createl = lxcapi_createl;
1875 c->shutdown = lxcapi_shutdown;
1876 c->reboot = lxcapi_reboot;
1877 c->clear_config_item = lxcapi_clear_config_item;
1878 c->get_config_item = lxcapi_get_config_item;
1879 c->get_cgroup_item = lxcapi_get_cgroup_item;
1880 c->set_cgroup_item = lxcapi_set_cgroup_item;
1881 c->get_config_path = lxcapi_get_config_path;
1882 c->set_config_path = lxcapi_set_config_path;
1883 c->clone = lxcapi_clone;
1884 c->get_ips = lxcapi_get_ips;
1885
1886 /* we'll allow the caller to update these later */
1887 if (lxc_log_init(NULL, "none", NULL, "lxc_container", 0, c->config_path)) {
1888 fprintf(stderr, "failed to open log\n");
1889 goto err;
1890 }
1891
1892 return c;
1893
1894 err:
1895 lxc_container_free(c);
1896 return NULL;
1897 }
1898
1899 int lxc_get_wait_states(const char **states)
1900 {
1901 int i;
1902
1903 if (states)
1904 for (i=0; i<MAX_STATE; i++)
1905 states[i] = lxc_state2str(i);
1906 return MAX_STATE;
1907 }