You need to sign in or sign up before continuing.
openvz_conf.c 25.8 KB
Newer Older
1 2 3
/*
 * openvz_conf.c: config functions for managing OpenVZ VEs
 *
4
 * Copyright (C) 2010-2011 Red Hat, Inc.
5 6
 * Copyright (C) 2006, 2007 Binary Karma
 * Copyright (C) 2006 Shuveb Hussain
7
 * Copyright (C) 2007 Anoop Joe Cyriac
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
23
 * Authors:
24 25 26
 * Shuveb Hussain <shuveb@binarykarma.com>
 * Anoop Joe Cyriac <anoop@binarykarma.com>
 *
27 28
 */

29
#include <config.h>
J
Jim Meyering 已提交
30

31 32 33 34 35 36 37
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
38 39 40 41
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
D
Daniel P. Berrange 已提交
42
#include <string.h>
43
#include <sys/utsname.h>
44
#include <sys/wait.h>
45

46
#include "virterror_internal.h"
47
#include "openvz_conf.h"
48 49
#include "uuid.h"
#include "buf.h"
50
#include "memory.h"
51
#include "util.h"
52
#include "nodeinfo.h"
53
#include "files.h"
E
Eric Blake 已提交
54
#include "command.h"
55
#include "ignore-value.h"
56

57 58
#define VIR_FROM_THIS VIR_FROM_OPENVZ

59
static char *openvzLocateConfDir(void);
60
static int openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len);
61
static int openvzLocateConfFile(int vpsid, char **conffile, const char *ext);
62
static int openvzAssignUUIDs(void);
63

64
int
65
strtoI(const char *str)
66 67 68
{
    int val;

69
    if (virStrToLong_i(str, NULL, 10, &val) < 0)
E
Eric Blake 已提交
70
        return 0;
71

72 73 74
    return val;
}

75 76

static int
77
openvzExtractVersionInfo(const char *cmdstr, int *retversion)
78
{
79
    int ret = -1;
80
    unsigned long version;
81
    char *help = NULL;
82
    char *tmp;
83
    virCommandPtr cmd = virCommandNewArgList(cmdstr, "--help", NULL);
84 85 86 87

    if (retversion)
        *retversion = 0;

88 89
    virCommandAddEnvString(cmd, "LC_ALL=C");
    virCommandSetOutputBuffer(cmd, &help);
90

91 92
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
93

94 95 96 97
    tmp = help;

    /* expected format: vzctl version <major>.<minor>.<micro> */
    if ((tmp = STRSKIP(tmp, "vzctl version ")) == NULL)
98
        goto cleanup;
99

100
    if (virParseVersionString(tmp, &version) < 0)
101
        goto cleanup;
102 103 104 105 106 107

    if (retversion)
        *retversion = version;

    ret = 0;

108 109
cleanup:
    virCommandFree(cmd);
110 111 112 113 114
    VIR_FREE(help);

    return ret;
}

115
int openvzExtractVersion(struct openvz_driver *driver)
116 117 118 119 120
{
    if (driver->version > 0)
        return 0;

    if (openvzExtractVersionInfo(VZCTL, &driver->version) < 0) {
121 122
        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Could not extract vzctl version"));
123 124 125 126 127 128 129
        return -1;
    }

    return 0;
}


130 131 132 133 134 135 136 137 138 139 140 141
virCapsPtr openvzCapsInit(void)
{
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

    if ((caps = virCapabilitiesNew(utsname.machine,
                                   0, 0)) == NULL)
        goto no_memory;

142
    if (nodeCapsInitNUMA(caps) < 0)
143 144
        goto no_memory;

145 146
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x52, 0x54, 0x00 });

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    if ((guest = virCapabilitiesAddGuest(caps,
                                         "exe",
                                         utsname.machine,
                                         sizeof(int) == 4 ? 32 : 8,
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
                                      "openvz",
                                      NULL,
                                      NULL,
                                      0,
                                      NULL) == NULL)
        goto no_memory;

165 166 167
    caps->defaultInitPath = "/sbin/init";

    return caps;
168 169 170 171 172 173
no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}


174
static int
175
openvzReadNetworkConf(virDomainDefPtr def,
176
                      int veid) {
177
    int ret;
178
    virDomainNetDefPtr net = NULL;
179
    char *temp = NULL;
180 181 182 183 184 185 186
    char *token, *saveptr = NULL;

    /*parse routing network configuration*
     * Sample from config:
     *   IP_ADDRESS="1.1.1.1 1.1.1.2"
     *   splited IPs by space
     */
187
    ret = openvzReadVPSConfigParam(veid, "IP_ADDRESS", &temp);
188
    if (ret < 0) {
189 190 191
        openvzError(VIR_ERR_INTERNAL_ERROR,
                    _("Could not read 'IP_ADDRESS' from config for container %d"),
                    veid);
192 193 194 195
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, " ", &saveptr);
        while (token != NULL) {
196
            if (VIR_ALLOC(net) < 0)
197 198 199 200 201 202 203 204
                goto no_memory;

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.ipaddr = strdup(token);

            if (net->data.ethernet.ipaddr == NULL)
                goto no_memory;

205 206 207 208 209
            if (VIR_REALLOC_N(def->nets, def->nnets + 1) < 0)
                goto no_memory;
            def->nets[def->nnets++] = net;
            net = NULL;

210 211 212 213 214 215 216 217 218
            token = strtok_r(NULL, " ", &saveptr);
        }
    }

    /*parse bridge devices*/
    /*Sample from config:
     *NETIF="ifname=eth10,mac=00:18:51:C1:05:EE,host_ifname=veth105.10,host_mac=00:18:51:8F:D9:F3"
     *devices splited by ';'
     */
219
    ret = openvzReadVPSConfigParam(veid, "NETIF", &temp);
220
    if (ret < 0) {
221 222 223
        openvzError(VIR_ERR_INTERNAL_ERROR,
                    _("Could not read 'NETIF' from config for container %d"),
                    veid);
224 225 226 227 228
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, ";", &saveptr);
        while (token != NULL) {
            /*add new device to list*/
229
            if (VIR_ALLOC(net) < 0)
230 231 232 233
                goto no_memory;

            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

234
            char *p = token;
235 236 237 238 239
            char cpy_temp[32];
            int len;

            /*parse string*/
            do {
240
                char *next = strchrnul (token, ',');
241
                if (STRPREFIX(p, "ifname=")) {
242 243 244
                    /* skip in libvirt */
                } else if (STRPREFIX(p, "host_ifname=")) {
                    p += 12;
245 246
                    len = next - p;
                    if (len > 16) {
247 248
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Too long network device name"));
249 250 251
                        goto error;
                    }

252 253 254
                    if (VIR_ALLOC_N(net->ifname, len+1) < 0)
                        goto no_memory;

C
Chris Lalancette 已提交
255
                    if (virStrncpy(net->ifname, p, len, len+1) == NULL) {
256
                        openvzError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
257 258 259
                                    _("Network ifname %s too long for destination"), p);
                        goto error;
                    }
260 261 262 263
                } else if (STRPREFIX(p, "bridge=")) {
                    p += 7;
                    len = next - p;
                    if (len > 16) {
264 265
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Too long bridge device name"));
266 267 268
                        goto error;
                    }

269 270 271
                    if (VIR_ALLOC_N(net->data.bridge.brname, len+1) < 0)
                        goto no_memory;

C
Chris Lalancette 已提交
272
                    if (virStrncpy(net->data.bridge.brname, p, len, len+1) == NULL) {
273
                        openvzError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
274 275 276
                                    _("Bridge name %s too long for destination"), p);
                        goto error;
                    }
277 278 279
                } else if (STRPREFIX(p, "mac=")) {
                    p += 4;
                    len = next - p;
280
                    if (len != 17) { /* should be 17 */
281 282
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Wrong length MAC address"));
283 284
                        goto error;
                    }
C
Chris Lalancette 已提交
285
                    if (virStrncpy(cpy_temp, p, len, sizeof(cpy_temp)) == NULL) {
286
                        openvzError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
287 288 289
                                    _("MAC address %s too long for destination"), p);
                        goto error;
                    }
290
                    if (virParseMacAddr(cpy_temp, net->mac) < 0) {
291 292
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Wrong MAC address"));
293 294 295 296 297 298
                        goto error;
                    }
                }
                p = ++next;
            } while (p < token + strlen(token));

299 300 301 302 303
            if (VIR_REALLOC_N(def->nets, def->nnets + 1) < 0)
                goto no_memory;
            def->nets[def->nnets++] = net;
            net = NULL;

304 305 306 307
            token = strtok_r(NULL, ";", &saveptr);
        }
    }

308 309
    VIR_FREE(temp);

310
    return 0;
311
no_memory:
312
    virReportOOMError();
313
error:
314
    VIR_FREE(temp);
315
    virDomainNetDefFree(net);
316
    return -1;
317 318 319
}


320 321 322 323 324 325 326
/* utility function to replace 'from' by 'to' in 'str' */
static char*
openvz_replace(const char* str,
               const char* from,
               const char* to) {
    const char* offset = NULL;
    const char* str_start = str;
327 328
    int to_len;
    int from_len;
329 330
    virBuffer buf = VIR_BUFFER_INITIALIZER;

331
    if ((!from) || (!to))
332
        return NULL;
333 334
    from_len = strlen(from);
    to_len = strlen(to);
335

E
Eric Blake 已提交
336
    while ((offset = strstr(str_start, from)))
337 338 339 340 341 342
    {
        virBufferAdd(&buf, str_start, offset-str_start);
        virBufferAdd(&buf, to, to_len);
        str_start = offset + from_len;
    }

343
    virBufferAdd(&buf, str_start, -1);
344

345 346 347 348
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        return NULL;
    }
349 350 351 352 353

    return virBufferContentAndReset(&buf);
}


354
static int
355
openvzReadFSConf(virDomainDefPtr def,
356 357 358
                 int veid) {
    int ret;
    virDomainFSDefPtr fs = NULL;
359 360
    char *veid_str = NULL;
    char *temp = NULL;
361

362
    ret = openvzReadVPSConfigParam(veid, "OSTEMPLATE", &temp);
363
    if (ret < 0) {
364
        openvzError(VIR_ERR_INTERNAL_ERROR,
365
                    _("Could not read 'OSTEMPLATE' from config for container %d"),
366 367 368 369 370 371 372 373
                    veid);
        goto error;
    } else if (ret > 0) {
        if (VIR_ALLOC(fs) < 0)
            goto no_memory;

        fs->type = VIR_DOMAIN_FS_TYPE_TEMPLATE;
        fs->src = strdup(temp);
374 375
    } else {
        /* OSTEMPLATE was not found, VE was booted from a private dir directly */
376
        ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp);
377
        if (ret <= 0) {
378
            openvzError(VIR_ERR_INTERNAL_ERROR,
379
                        _("Could not read 'VE_PRIVATE' from config for container %d"),
380 381 382
                        veid);
            goto error;
        }
383

384
        if (VIR_ALLOC(fs) < 0)
385 386
            goto no_memory;

387 388
        if (virAsprintf(&veid_str, "%d", veid) < 0)
            goto no_memory;
389 390 391

        fs->type = VIR_DOMAIN_FS_TYPE_MOUNT;
        fs->src = openvz_replace(temp, "$VEID", veid_str);
392

393
        VIR_FREE(veid_str);
394 395
    }

396 397 398 399 400 401 402 403 404 405
    fs->dst = strdup("/");

    if (fs->src == NULL || fs->dst == NULL)
        goto no_memory;

    if (VIR_REALLOC_N(def->fss, def->nfss + 1) < 0)
        goto no_memory;
    def->fss[def->nfss++] = fs;
    fs = NULL;

406 407
    VIR_FREE(temp);

408 409
    return 0;
no_memory:
410
    virReportOOMError();
411
error:
412
    VIR_FREE(temp);
413 414 415 416 417
    virDomainFSDefFree(fs);
    return -1;
}


418 419 420 421 422 423
/* Free all memory associated with a openvz_driver structure */
void
openvzFreeDriver(struct openvz_driver *driver)
{
    if (!driver)
        return;
424

425
    virDomainObjListDeinit(&driver->domains);
426
    virCapabilitiesFree(driver->caps);
427
    VIR_FREE(driver);
428
}
D
Daniel Veillard 已提交
429 430 431



432
int openvzLoadDomains(struct openvz_driver *driver) {
433
    int veid, ret;
434
    char *status;
435
    char uuidstr[VIR_UUID_STRING_BUFLEN];
436
    virDomainObjPtr dom = NULL;
437
    char *temp = NULL;
E
Eric Blake 已提交
438 439 440
    char *outbuf = NULL;
    char *line;
    virCommandPtr cmd = NULL;
441

442 443
    if (openvzAssignUUIDs() < 0)
        return -1;
444

E
Eric Blake 已提交
445 446 447 448
    cmd = virCommandNewArgList(VZLIST, "-a", "-ovpsid,status", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
449

450 451 452 453 454
    line = outbuf;
    while (line[0] != '\0') {
        if (virStrToLong_i(line, &status, 10, &veid) < 0 ||
            *status++ != ' ' ||
            (line = strchr(status, '\n')) == NULL) {
455 456
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("Failed to parse vzlist output"));
457
            goto cleanup;
458
        }
459
        *line++ = '\0';
460

461
        if (VIR_ALLOC(dom) < 0)
462
            goto no_memory;
463

464
        if (virMutexInit(&dom->lock) < 0) {
465 466
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot initialize mutex"));
467 468 469 470
            VIR_FREE(dom);
            goto cleanup;
        }

471 472
        virDomainObjLock(dom);

473 474
        if (VIR_ALLOC(dom->def) < 0)
            goto no_memory;
475

J
Jiri Denemark 已提交
476 477 478 479 480 481 482
        if (STREQ(status, "stopped")) {
            virDomainObjSetState(dom, VIR_DOMAIN_SHUTOFF,
                                 VIR_DOMAIN_SHUTOFF_UNKNOWN);
        } else {
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNKNOWN);
        }
483

484
        dom->refs = 1;
485
        dom->pid = veid;
J
Jiri Denemark 已提交
486 487 488 489
        if (virDomainObjGetState(dom, NULL) == VIR_DOMAIN_SHUTOFF)
            dom->def->id = -1;
        else
            dom->def->id = veid;
490 491
        /* XXX OpenVZ doesn't appear to have concept of a transient domain */
        dom->persistent = 1;
492

493
        if (virAsprintf(&dom->def->name, "%i", veid) < 0)
494
            goto no_memory;
495

496
        openvzGetVPSUUID(veid, uuidstr, sizeof(uuidstr));
497
        ret = virUUIDParse(uuidstr, dom->def->uuid);
498

499
        if (ret == -1) {
500 501
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("UUID in config file malformed"));
502
            goto cleanup;
503
        }
504

505 506 507 508
        if (!(dom->def->os.type = strdup("exe")))
            goto no_memory;
        if (!(dom->def->os.init = strdup("/sbin/init")))
            goto no_memory;
509

510
        ret = openvzReadVPSConfigParam(veid, "CPUS", &temp);
511
        if (ret < 0) {
512
            openvzError(VIR_ERR_INTERNAL_ERROR,
513
                        _("Could not read config for container %d"),
514 515
                        veid);
            goto cleanup;
516
        } else if (ret > 0) {
E
Eric Blake 已提交
517
            dom->def->maxvcpus = strtoI(temp);
518 519
        }

E
Eric Blake 已提交
520 521 522
        if (ret == 0 || dom->def->maxvcpus == 0)
            dom->def->maxvcpus = openvzGetNodeCPUs();
        dom->def->vcpus = dom->def->maxvcpus;
523

524
        /* XXX load rest of VM config data .... */
525

526 527
        openvzReadNetworkConf(dom->def, veid);
        openvzReadFSConf(dom->def, veid);
528

529 530
        virUUIDFormat(dom->def->uuid, uuidstr);
        if (virHashAddEntry(driver->domains.objs, uuidstr, dom) < 0)
531
            goto cleanup;
532

533
        virDomainObjUnlock(dom);
534
        dom = NULL;
535
    }
536

E
Eric Blake 已提交
537
    virCommandFree(cmd);
538
    VIR_FREE(temp);
E
Eric Blake 已提交
539
    VIR_FREE(outbuf);
540

541
    return 0;
542

543
 no_memory:
544
    virReportOOMError();
545

546
 cleanup:
E
Eric Blake 已提交
547
    virCommandFree(cmd);
548
    VIR_FREE(temp);
E
Eric Blake 已提交
549
    VIR_FREE(outbuf);
550
    /* dom hasn't been shared yet, so unref should return 0 */
551
    if (dom)
552
        ignore_value(virDomainObjUnref(dom));
553
    return -1;
554 555
}

556 557 558 559 560
unsigned int
openvzGetNodeCPUs(void)
{
    virNodeInfo nodeinfo;

561
    if (nodeGetInfo(NULL, &nodeinfo) < 0)
562 563 564 565
        return 0;

    return nodeinfo.cpus;
}
566

567 568
static int
openvzWriteConfigParam(const char * conf_file, const char *param, const char *value)
569
{
570
    char * temp_file = NULL;
571 572 573 574
    int temp_fd = -1;
    FILE *fp;
    char *line = NULL;
    size_t line_size = 0;
575

576
    if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0) {
577
        virReportOOMError();
578
        return -1;
579
    }
580

581 582
    fp = fopen(conf_file, "r");
    if (fp == NULL)
583
        goto error;
584 585
    temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (temp_fd == -1) {
586
        goto error;
587 588
    }

E
Eric Blake 已提交
589
    while (1) {
590
        if (getline(&line, &line_size, fp) <= 0)
591 592
            break;

593
        if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) {
594 595 596 597 598 599 600 601 602 603 604 605
            if (safewrite(temp_fd, line, strlen(line)) !=
                strlen(line))
                goto error;
        }
    }

    if (safewrite(temp_fd, param, strlen(param)) < 0 ||
        safewrite(temp_fd, "=\"", 2) < 0 ||
        safewrite(temp_fd, value, strlen(value)) < 0 ||
        safewrite(temp_fd, "\"\n", 2) < 0)
        goto error;

606
    if (VIR_FCLOSE(fp) < 0)
607
        goto error;
608
    if (VIR_CLOSE(temp_fd) < 0)
609 610 611 612 613
        goto error;

    if (rename(temp_file, conf_file) < 0)
        goto error;

614 615
    VIR_FREE(line);

616 617 618
    return 0;

error:
619 620
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
621
    VIR_FORCE_CLOSE(temp_fd);
E
Eric Blake 已提交
622
    if (temp_file)
623 624
        unlink(temp_file);
    VIR_FREE(temp_file);
625 626 627
    return -1;
}

628
int
629 630
openvzWriteVPSConfigParam(int vpsid, const char *param, const char *value)
{
631 632
    char *conf_file;
    int ret;
633

634
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
635 636
        return -1;

637 638 639
    ret = openvzWriteConfigParam(conf_file, param, value);
    VIR_FREE(conf_file);
    return ret;
640 641
}

642 643 644
/*
 * value will be freed before a new value is assigned to it, the caller is
 * responsible for freeing it afterwards.
645 646
 *
 * Returns <0 on error, 0 if not found, 1 if found.
647
 */
648
int
649
openvzReadConfigParam(const char *conf_file, const char *param, char **value)
650
{
651 652 653
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
654 655
    int err = 0;
    char *sf, *token, *saveptr = NULL;
656

657 658
    fp = fopen(conf_file, "r");
    if (fp == NULL)
659 660
        return -1;

661 662 663 664 665 666 667 668
    VIR_FREE(*value);
    while (getline(&line, &line_size, fp) >= 0) {
        if (! STREQLEN(line, param, strlen(param)))
            continue;

        sf = line + strlen(param);
        if (*sf++ != '=') continue;

669
        saveptr = NULL;
670 671 672 673 674 675
        if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) {
            VIR_FREE(*value);
            *value = strdup(token);
            if (*value == NULL) {
                err = 1;
                break;
676
            }
677 678
            /* keep going - last entry wins */
        }
679
    }
680 681
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
682

683
    return err ? -1 : *value ? 1 : 0;
684 685
}

686
/*
687 688 689 690 691 692 693 694 695 696
 * Read parameter from container config
 *
 * value will be freed before a new value is assined to it, the caller is
 * responsible for freeing it afterwards.
 *
 * sample: 133, "OSTEMPLATE", &value
 * return: -1 - error
 *          0 - don't found
 *          1 - OK
 */
697
int
698
openvzReadVPSConfigParam(int vpsid, const char *param, char **value)
699
{
700 701
    char *conf_file;
    int ret;
702

703
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
704 705
        return -1;

706
    ret = openvzReadConfigParam(conf_file, param, value);
707 708
    VIR_FREE(conf_file);
    return ret;
709 710 711 712 713
}

static int
openvz_copyfile(char* from_path, char* to_path)
{
714 715 716 717
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
    int copy_fd;
718 719
    int bytes_read;

720 721
    fp = fopen(from_path, "r");
    if (fp == NULL)
722 723 724
        return -1;
    copy_fd = open(to_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (copy_fd == -1) {
725
        VIR_FORCE_FCLOSE(fp);
726 727 728
        return -1;
    }

E
Eric Blake 已提交
729
    while (1) {
730
        if (getline(&line, &line_size, fp) <= 0)
731 732 733 734 735 736 737
            break;

        bytes_read = strlen(line);
        if (safewrite(copy_fd, line, bytes_read) != bytes_read)
            goto error;
    }

738
    if (VIR_FCLOSE(fp) < 0)
739
        goto error;
740
    if (VIR_CLOSE(copy_fd) < 0)
741 742
        goto error;

743 744
    VIR_FREE(line);

745 746 747
    return 0;

error:
748 749
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
750
    VIR_FORCE_CLOSE(copy_fd);
751 752 753 754 755 756 757 758 759 760 761
    return -1;
}

/*
* Copy the default config to the VE conf file
* return: -1 - error
*          0 - OK
*/
int
openvzCopyDefaultConfig(int vpsid)
{
762 763 764
    char *confdir = NULL;
    char *default_conf_file = NULL;
    char *configfile_value = NULL;
765
    char *conf_file = NULL;
766 767
    int ret = -1;

768
    if (openvzReadConfigParam(VZ_CONF_FILE, "CONFIGFILE", &configfile_value) < 0)
769 770 771 772 773 774
        goto cleanup;

    confdir = openvzLocateConfDir();
    if (confdir == NULL)
        goto cleanup;

775 776
    if (virAsprintf(&default_conf_file, "%s/ve-%s.conf-sample", confdir,
                    configfile_value) < 0) {
777
        virReportOOMError();
778
        goto cleanup;
779
    }
780

781
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
782 783 784 785 786 787 788 789 790
        goto cleanup;

    if (openvz_copyfile(default_conf_file, conf_file)<0)
        goto cleanup;

    ret = 0;
cleanup:
    VIR_FREE(confdir);
    VIR_FREE(default_conf_file);
791
    VIR_FREE(configfile_value);
792
    VIR_FREE(conf_file);
793 794 795
    return ret;
}

796 797 798 799 800
/* Locate config file of container
* return -1 - error
*         0 - OK
*/
static int
801
openvzLocateConfFile(int vpsid, char **conffile, const char *ext)
802 803 804 805 806 807 808 809
{
    char * confdir;
    int ret = 0;

    confdir = openvzLocateConfDir();
    if (confdir == NULL)
        return -1;

810 811 812
    if (virAsprintf(conffile, "%s/%d.%s", confdir, vpsid,
                    ext ? ext : "conf") < 0) {
        virReportOOMError();
813
        ret = -1;
814
    }
815 816 817 818 819

    VIR_FREE(confdir);
    return ret;
}

820
static char
821
*openvzLocateConfDir(void)
822 823 824 825
{
    const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL};
    int i=0;

E
Eric Blake 已提交
826 827
    while (conf_dir_list[i]) {
        if (!access(conf_dir_list[i], F_OK))
828
            return strdup(conf_dir_list[i]);
E
Eric Blake 已提交
829
        i++;
830 831 832 833 834 835
    }

    return NULL;
}

/* Richard Steven's classic readline() function */
836
int
837
openvz_readline(int fd, char *ptr, int maxlen)
838 839 840 841
{
    int n, rc;
    char c;

E
Eric Blake 已提交
842 843
    for (n = 1; n < maxlen; n++) {
        if ( (rc = read(fd, &c, 1)) == 1) {
844
            *ptr++ = c;
E
Eric Blake 已提交
845
            if (c == '\n')
846
                break;
E
Eric Blake 已提交
847 848
        } else if (rc == 0) {
            if (n == 1)
849 850 851 852 853 854 855 856 857 858 859
                return 0; /* EOF condition */
            else
                break;
        }
        else
            return -1; /* error */
    }
    *ptr = 0;
    return n;
}

860
static int
861
openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len)
862
{
863
    char *conf_file;
864 865
    char *line = NULL;
    size_t line_size = 0;
866
    char *saveptr = NULL;
867 868
    char *uuidbuf;
    char *iden;
869
    FILE *fp;
870
    int retval = -1;
871

872
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
873
        return -1;
874

875 876
    fp = fopen(conf_file, "r");
    if (fp == NULL)
877
        goto cleanup;
878

E
Eric Blake 已提交
879
    while (1) {
880 881 882 883 884 885 886
        if (getline(&line, &line_size, fp) < 0) {
            if (feof(fp)) { /* EOF, UUID was not found */
                uuidstr[0] = 0;
                break;
            } else {
                goto cleanup;
            }
887 888
        }

889 890 891 892
        iden = strtok_r(line, " ", &saveptr);
        uuidbuf = strtok_r(NULL, "\n", &saveptr);

        if (iden != NULL && uuidbuf != NULL && STREQ(iden, "#UUID:")) {
893 894 895 896 897
            if (virStrcpy(uuidstr, uuidbuf, len) == NULL) {
                openvzError(VIR_ERR_INTERNAL_ERROR,
                            _("invalid uuid %s"), uuidbuf);
                goto cleanup;
            }
898 899 900
            break;
        }
    }
901 902
    retval = 0;
cleanup:
903 904
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
905
    VIR_FREE(conf_file);
906

C
Chris Lalancette 已提交
907
    return retval;
908 909 910 911 912
}

/* Do actual checking for UUID presence in conf file,
 * assign if not present.
 */
913 914
int
openvzSetDefinedUUID(int vpsid, unsigned char *uuid)
915
{
916
    char *conf_file;
917
    char uuidstr[VIR_UUID_STRING_BUFLEN];
918
    FILE *fp = NULL;
919
    int ret = -1;
920 921 922

    if (uuid == NULL)
        return -1;
923

924
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
925
        return -1;
926

927
    if (openvzGetVPSUUID(vpsid, uuidstr, sizeof(uuidstr)))
928
        goto cleanup;
929

J
Jim Meyering 已提交
930
    if (uuidstr[0] == 0) {
931
        fp = fopen(conf_file, "a"); /* append */
932
        if (fp == NULL)
933
            goto cleanup;
934

935 936
        virUUIDFormat(uuid, uuidstr);

937
        /* Record failure if fprintf or VIR_FCLOSE fails,
938
           and be careful always to close the stream.  */
939 940
        if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0) ||
            (VIR_FCLOSE(fp) == EOF))
941
            goto cleanup;
942 943
    }

944 945
    ret = 0;
cleanup:
946
    VIR_FORCE_FCLOSE(fp);
947 948
    VIR_FREE(conf_file);
    return ret;
949 950
}

951 952 953 954
static int
openvzSetUUID(int vpsid){
    unsigned char uuid[VIR_UUID_BUFLEN];

955
    if (virUUIDGenerate(uuid)) {
956 957
        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Failed to generate UUID"));
958 959
        return -1;
    }
960 961 962 963

    return openvzSetDefinedUUID(vpsid, uuid);
}

964 965 966 967 968 969 970
/*
 * Scan VPS config files and see if they have a UUID.
 * If not, assign one. Just append one to the config
 * file as comment so that the OpenVZ tools ignore it.
 *
 */

971
static int openvzAssignUUIDs(void)
972 973 974 975
{
    DIR *dp;
    struct dirent *dent;
    char *conf_dir;
976 977 978
    int vpsid;
    char *ext;
    int ret = 0;
979 980

    conf_dir = openvzLocateConfDir();
981 982
    if (conf_dir == NULL)
        return -1;
983 984

    dp = opendir(conf_dir);
E
Eric Blake 已提交
985
    if (dp == NULL) {
986
        VIR_FREE(conf_dir);
987 988 989
        return 0;
    }

990
    errno = 0;
E
Eric Blake 已提交
991
    while ((dent = readdir(dp))) {
992 993 994
        if (virStrToLong_i(dent->d_name, &ext, 10, &vpsid) < 0 ||
            *ext++ != '.' ||
            STRNEQ(ext, "conf"))
995
            continue;
E
Eric Blake 已提交
996
        if (vpsid > 0) /* '0.conf' belongs to the host, ignore it */
997
            openvzSetUUID(vpsid);
998 999 1000 1001 1002 1003
        errno = 0;
    }
    if (errno) {
        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Failed to scan configuration directory"));
        ret = -1;
1004
    }
1005

1006
    closedir(dp);
1007
    VIR_FREE(conf_dir);
1008
    return ret;
1009
}
1010 1011 1012 1013 1014 1015 1016 1017


/*
 * Return CTID from name
 *
 */

int openvzGetVEID(const char *name) {
E
Eric Blake 已提交
1018 1019
    virCommandPtr cmd;
    char *outbuf;
1020
    char *temp;
1021
    int veid;
1022
    bool ok;
1023

E
Eric Blake 已提交
1024 1025 1026 1027 1028
    cmd = virCommandNewArgList(VZLIST, name, "-ovpsid", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0) {
        virCommandFree(cmd);
        VIR_FREE(outbuf);
1029 1030 1031
        return -1;
    }

E
Eric Blake 已提交
1032
    virCommandFree(cmd);
1033
    ok = virStrToLong_i(outbuf, &temp, 10, &veid) == 0 && *temp == '\n';
E
Eric Blake 已提交
1034
    VIR_FREE(outbuf);
1035

1036 1037 1038
    if (ok && veid >= 0)
        return veid;

1039 1040
    openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                _("Failed to parse vzlist output"));
1041 1042
    return -1;
}