openvz_conf.c 28.3 KB
Newer Older
1 2 3
/*
 * openvz_conf.c: config functions for managing OpenVZ VEs
 *
4
 * Copyright (C) 2010-2012, 2014 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
 *
 * 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
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22
 *
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
#include <sys/stat.h>
#include <limits.h>
#include <errno.h>
D
Daniel P. Berrange 已提交
41
#include <string.h>
42
#include <sys/wait.h>
43

44
#include "virerror.h"
45
#include "openvz_conf.h"
46
#include "openvz_util.h"
47
#include "viruuid.h"
48
#include "virbuffer.h"
49
#include "viralloc.h"
50
#include "nodeinfo.h"
E
Eric Blake 已提交
51
#include "virfile.h"
52
#include "vircommand.h"
53
#include "virstring.h"
54

55 56
#define VIR_FROM_THIS VIR_FROM_OPENVZ

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

openvzLocateConfFileFunc openvzLocateConfFile = openvzLocateConfFileDefault;
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

I
Ilja Livenson 已提交
100
    if (virParseVersionString(tmp, &version, true) < 0)
101
        goto cleanup;
102 103 104 105 106 107

    if (retversion)
        *retversion = version;

    ret = 0;

108
 cleanup:
109
    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
        virReportError(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
/* Parse config values of the form barrier:limit into barrier and limit */
static int
openvzParseBarrierLimit(const char* value,
                        unsigned long long *barrier,
                        unsigned long long *limit)
{
136 137
    char **tmp = NULL;
    size_t ntmp = 0;
P
Pavel Hrdina 已提交
138
    int ret = -1;
139

140
    if (!(tmp = virStringSplitCount(value, ":", 0, &ntmp)))
141 142
        goto error;

143
    if (ntmp != 2)
144
        goto error;
145 146

    if (barrier && virStrToLong_ull(tmp[0], NULL, 10, barrier) < 0)
147
        goto error;
148 149 150 151

    if (limit && virStrToLong_ull(tmp[1], NULL, 10, limit) < 0)
        goto error;

P
Pavel Hrdina 已提交
152
    ret = 0;
153
 error:
154
    virStringListFreeCount(tmp, ntmp);
P
Pavel Hrdina 已提交
155
    return ret;
156 157 158
}


159 160 161 162 163
virCapsPtr openvzCapsInit(void)
{
    virCapsPtr caps;
    virCapsGuestPtr guest;

164
    if ((caps = virCapabilitiesNew(virArchFromHost(),
165
                                   false, false)) == NULL)
166 167
        goto no_memory;

168
    if (nodeCapsInitNUMA(caps) < 0)
169 170
        goto no_memory;

171
    if ((guest = virCapabilitiesAddGuest(caps,
172
                                         VIR_DOMAIN_OSTYPE_EXE,
173
                                         caps->host.arch,
174 175 176 177 178 179 180
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
181
                                      VIR_DOMAIN_VIRT_OPENVZ,
182 183 184 185 186 187
                                      NULL,
                                      NULL,
                                      0,
                                      NULL) == NULL)
        goto no_memory;

188
    return caps;
189

190
 no_memory:
191
    virObjectUnref(caps);
192 193 194 195
    return NULL;
}


196
int
197
openvzReadNetworkConf(virDomainDefPtr def,
198 199
                      int veid)
{
200
    int ret;
201
    virDomainNetDefPtr net = NULL;
202
    char *temp = NULL;
203 204 205 206 207
    char *token, *saveptr = NULL;

    /*parse routing network configuration*
     * Sample from config:
     *   IP_ADDRESS="1.1.1.1 1.1.1.2"
N
Nehal J Wani 已提交
208
     * IPs split by space
209
     */
210
    ret = openvzReadVPSConfigParam(veid, "IP_ADDRESS", &temp);
211
    if (ret < 0) {
212 213 214
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'IP_ADDRESS' from config for container %d"),
                       veid);
215 216 217 218
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, " ", &saveptr);
        while (token != NULL) {
219
            if (VIR_ALLOC(net) < 0)
220
                goto error;
221 222

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
223
            if (virDomainNetAppendIPAddress(net, token, AF_UNSPEC, 0) < 0)
224
                goto error;
225

226
            if (VIR_APPEND_ELEMENT_COPY(def->nets, def->nnets, net) < 0)
227
                goto error;
228

229 230 231 232 233 234
            token = strtok_r(NULL, " ", &saveptr);
        }
    }

    /*parse bridge devices*/
    /*Sample from config:
N
Nehal J Wani 已提交
235 236
     * NETIF="ifname=eth10,mac=00:18:51:C1:05:EE,host_ifname=veth105.10,host_mac=00:18:51:8F:D9:F3"
     *devices split by ';'
237
     */
238
    ret = openvzReadVPSConfigParam(veid, "NETIF", &temp);
239
    if (ret < 0) {
240 241 242
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'NETIF' from config for container %d"),
                       veid);
243 244 245 246 247
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, ";", &saveptr);
        while (token != NULL) {
            /*add new device to list*/
248
            if (VIR_ALLOC(net) < 0)
249
                goto error;
250 251 252

            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

253
            char *p = token;
254 255 256 257 258
            char cpy_temp[32];
            int len;

            /*parse string*/
            do {
259
                char *next = strchrnul(p, ',');
260
                if (STRPREFIX(p, "ifname=")) {
261 262 263
                    /* skip in libvirt */
                } else if (STRPREFIX(p, "host_ifname=")) {
                    p += 12;
264 265
                    len = next - p;
                    if (len > 16) {
266 267
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Too long network device name"));
268 269 270
                        goto error;
                    }

271
                    if (VIR_ALLOC_N(net->ifname, len+1) < 0)
272
                        goto error;
273

C
Chris Lalancette 已提交
274
                    if (virStrncpy(net->ifname, p, len, len+1) == NULL) {
275 276
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Network ifname %s too long for destination"), p);
C
Chris Lalancette 已提交
277 278
                        goto error;
                    }
279 280 281 282
                } else if (STRPREFIX(p, "bridge=")) {
                    p += 7;
                    len = next - p;
                    if (len > 16) {
283 284
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Too long bridge device name"));
285 286 287
                        goto error;
                    }

288
                    if (VIR_ALLOC_N(net->data.bridge.brname, len+1) < 0)
289
                        goto error;
290

C
Chris Lalancette 已提交
291
                    if (virStrncpy(net->data.bridge.brname, p, len, len+1) == NULL) {
292 293
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Bridge name %s too long for destination"), p);
C
Chris Lalancette 已提交
294 295
                        goto error;
                    }
296 297 298
                } else if (STRPREFIX(p, "mac=")) {
                    p += 4;
                    len = next - p;
299
                    if (len != 17) { /* should be 17 */
300 301
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Wrong length MAC address"));
302 303
                        goto error;
                    }
C
Chris Lalancette 已提交
304
                    if (virStrncpy(cpy_temp, p, len, sizeof(cpy_temp)) == NULL) {
305 306
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("MAC address %s too long for destination"), p);
C
Chris Lalancette 已提交
307 308
                        goto error;
                    }
309
                    if (virMacAddrParse(cpy_temp, &net->mac) < 0) {
310 311
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Wrong MAC address"));
312 313 314 315 316 317
                        goto error;
                    }
                }
                p = ++next;
            } while (p < token + strlen(token));

318
            if (VIR_APPEND_ELEMENT_COPY(def->nets, def->nnets, net) < 0)
319
                goto error;
320

321 322 323 324
            token = strtok_r(NULL, ";", &saveptr);
        }
    }

325 326
    VIR_FREE(temp);

327
    return 0;
328

329
 error:
330
    VIR_FREE(temp);
331
    virDomainNetDefFree(net);
332
    return -1;
333 334 335
}


336
static int
337
openvzReadFSConf(virDomainDefPtr def,
338 339
                 int veid)
{
340 341
    int ret;
    virDomainFSDefPtr fs = NULL;
342 343
    char *veid_str = NULL;
    char *temp = NULL;
344 345
    const char *param;
    unsigned long long barrier, limit;
346

347
    ret = openvzReadVPSConfigParam(veid, "OSTEMPLATE", &temp);
348
    if (ret < 0) {
349 350 351
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'OSTEMPLATE' from config for container %d"),
                       veid);
352 353
        goto error;
    } else if (ret > 0) {
354
        if (!(fs = virDomainFSDefNew()))
355
            goto error;
356 357

        fs->type = VIR_DOMAIN_FS_TYPE_TEMPLATE;
358
        if (VIR_STRDUP(fs->src->path, temp) < 0)
359
            goto error;
360 361
    } else {
        /* OSTEMPLATE was not found, VE was booted from a private dir directly */
362
        ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp);
363
        if (ret <= 0) {
364 365 366
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read 'VE_PRIVATE' from config for container %d"),
                           veid);
367 368
            goto error;
        }
369

370
        if (VIR_ALLOC(fs) < 0)
371
            goto error;
372

373
        if (virAsprintf(&veid_str, "%d", veid) < 0)
374
            goto error;
375 376

        fs->type = VIR_DOMAIN_FS_TYPE_MOUNT;
377
        if (!(fs->src->path = virStringReplace(temp, "$VEID", veid_str)))
378
            goto error;
379

380
        VIR_FREE(veid_str);
381 382
    }

383 384
    if (VIR_STRDUP(fs->dst, "/") < 0)
        goto error;
385

386 387 388 389
    param = "DISKSPACE";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret > 0) {
        if (openvzParseBarrierLimit(temp, &barrier, &limit)) {
390 391 392
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read '%s' from config for container %d"),
                           param, veid);
393 394 395
            goto error;
        } else {
            /* Ensure that we can multiply by 1024 without overflowing. */
396
            if (barrier > ULLONG_MAX / 1024 ||
397
                limit > ULLONG_MAX / 1024) {
J
Jiri Denemark 已提交
398 399
                virReportError(VIR_ERR_OVERFLOW, "%s",
                               _("Unable to parse quota"));
400 401 402 403 404 405 406
                goto error;
            }
            fs->space_soft_limit = barrier * 1024; /* unit is bytes */
            fs->space_hard_limit = limit * 1024;   /* unit is bytes */
        }
    }

407
    if (VIR_APPEND_ELEMENT(def->fss, def->nfss, fs) < 0)
408
        goto error;
409

410 411
    VIR_FREE(temp);

412
    return 0;
413
 error:
414
    VIR_FREE(temp);
415 416 417 418 419
    virDomainFSDefFree(fs);
    return -1;
}


420 421 422
static int
openvzReadMemConf(virDomainDefPtr def, int veid)
{
423
    int ret = -1;
424 425 426
    char *temp = NULL;
    unsigned long long barrier, limit;
    const char *param;
427
    long kb_per_pages;
428

429 430
    kb_per_pages = openvzKBPerPages();
    if (kb_per_pages < 0)
431 432 433 434 435 436
        goto error;

    /* Memory allocation guarantee */
    param = "VMGUARPAGES";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret < 0) {
437 438 439
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read '%s' from config for container %d"),
                       param, veid);
440 441 442 443
        goto error;
    } else if (ret > 0) {
        ret = openvzParseBarrierLimit(temp, &barrier, NULL);
        if (ret < 0) {
444 445 446
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse barrier of '%s' "
                             "from config for container %d"), param, veid);
447 448 449 450 451 452 453 454 455 456 457 458
            goto error;
        }
        if (barrier == LONG_MAX)
            def->mem.min_guarantee = 0ull;
        else
            def->mem.min_guarantee = barrier * kb_per_pages;
    }

    /* Memory hard and soft limits */
    param = "PRIVVMPAGES";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret < 0) {
459 460 461
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read '%s' from config for container %d"),
                       param, veid);
462 463 464 465
        goto error;
    } else if (ret > 0) {
        ret = openvzParseBarrierLimit(temp, &barrier, &limit);
        if (ret < 0) {
466 467 468
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse barrier and limit of '%s' "
                             "from config for container %d"), param, veid);
469 470 471
            goto error;
        }
        if (barrier == LONG_MAX)
472
            def->mem.soft_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
473 474 475 476
        else
            def->mem.soft_limit = barrier * kb_per_pages;

        if (limit == LONG_MAX)
477
            def->mem.hard_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
478 479 480 481 482
        else
            def->mem.hard_limit = limit * kb_per_pages;
    }

    ret = 0;
483
 error:
484 485 486 487 488
    VIR_FREE(temp);
    return ret;
}


489 490 491 492 493 494
/* Free all memory associated with a openvz_driver structure */
void
openvzFreeDriver(struct openvz_driver *driver)
{
    if (!driver)
        return;
495

496
    virObjectUnref(driver->xmlopt);
497
    virObjectUnref(driver->domains);
498
    virObjectUnref(driver->caps);
499
    VIR_FREE(driver);
500
}
D
Daniel Veillard 已提交
501 502 503



504 505
int openvzLoadDomains(struct openvz_driver *driver)
{
506
    int veid, ret;
507
    char *status;
508
    char uuidstr[VIR_UUID_STRING_BUFLEN];
509
    virDomainObjPtr dom = NULL;
510
    virDomainDefPtr def = NULL;
511
    char *temp = NULL;
E
Eric Blake 已提交
512 513 514
    char *outbuf = NULL;
    char *line;
    virCommandPtr cmd = NULL;
515
    unsigned int vcpus = 0;
516

517 518
    if (openvzAssignUUIDs() < 0)
        return -1;
519

E
Eric Blake 已提交
520 521 522 523
    cmd = virCommandNewArgList(VZLIST, "-a", "-ovpsid,status", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
524

525 526
    line = outbuf;
    while (line[0] != '\0') {
527
        unsigned int flags = 0;
528 529 530
        if (virStrToLong_i(line, &status, 10, &veid) < 0 ||
            *status++ != ' ' ||
            (line = strchr(status, '\n')) == NULL) {
531 532
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Failed to parse vzlist output"));
533
            goto cleanup;
534
        }
535
        *line++ = '\0';
536

537
        if (!(def = virDomainDefNew()))
538
            goto cleanup;
539

540
        def->virtType = VIR_DOMAIN_VIRT_OPENVZ;
541

542 543
        if (STREQ(status, "stopped"))
            def->id = -1;
J
Jiri Denemark 已提交
544
        else
545 546
            def->id = veid;
        if (virAsprintf(&def->name, "%i", veid) < 0)
547
            goto cleanup;
548

549
        openvzGetVPSUUID(veid, uuidstr, sizeof(uuidstr));
550
        ret = virUUIDParse(uuidstr, def->uuid);
551

552
        if (ret == -1) {
553 554
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("UUID in config file malformed"));
555
            goto cleanup;
556
        }
557

558
        def->os.type = VIR_DOMAIN_OSTYPE_EXE;
559 560
        if (VIR_STRDUP(def->os.init, "/sbin/init") < 0)
            goto cleanup;
561

562
        ret = openvzReadVPSConfigParam(veid, "CPUS", &temp);
563
        if (ret < 0) {
564 565 566
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read config for container %d"),
                           veid);
567
            goto cleanup;
568
        } else if (ret > 0) {
569
            vcpus = strtoI(temp);
570 571
        }

572 573 574
        if (ret == 0 || vcpus == 0)
            vcpus = openvzGetNodeCPUs();

575
        if (virDomainDefSetVcpusMax(def, vcpus, driver->xmlopt) < 0)
576 577
            goto cleanup;

578 579
        if (virDomainDefSetVcpus(def, vcpus) < 0)
            goto cleanup;
580

581
        /* XXX load rest of VM config data .... */
582

583 584 585
        openvzReadNetworkConf(def, veid);
        openvzReadFSConf(def, veid);
        openvzReadMemConf(def, veid);
586

587
        virUUIDFormat(def->uuid, uuidstr);
588 589 590 591
        flags = VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE;
        if (STRNEQ(status, "stopped"))
            flags |= VIR_DOMAIN_OBJ_LIST_ADD_LIVE;

592 593
        if (!(dom = virDomainObjListAdd(driver->domains,
                                        def,
594
                                        driver->xmlopt,
595 596
                                        flags,
                                        NULL)))
597
            goto cleanup;
598 599 600 601 602 603 604 605 606

        if (STREQ(status, "stopped")) {
            virDomainObjSetState(dom, VIR_DOMAIN_SHUTOFF,
                                 VIR_DOMAIN_SHUTOFF_UNKNOWN);
            dom->pid = -1;
        } else {
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNKNOWN);
            dom->pid = veid;
607
        }
608 609
        /* XXX OpenVZ doesn't appear to have concept of a transient domain */
        dom->persistent = 1;
610

611
        virObjectUnlock(dom);
612
        dom = NULL;
613
        def = NULL;
614
    }
615

E
Eric Blake 已提交
616
    virCommandFree(cmd);
617
    VIR_FREE(temp);
E
Eric Blake 已提交
618
    VIR_FREE(outbuf);
619

620
    return 0;
621

622
 cleanup:
E
Eric Blake 已提交
623
    virCommandFree(cmd);
624
    VIR_FREE(temp);
E
Eric Blake 已提交
625
    VIR_FREE(outbuf);
626
    virObjectUnref(dom);
627
    virDomainDefFree(def);
628
    return -1;
629 630
}

631 632 633 634 635
unsigned int
openvzGetNodeCPUs(void)
{
    virNodeInfo nodeinfo;

636
    if (nodeGetInfo(&nodeinfo) < 0)
637 638 639 640
        return 0;

    return nodeinfo.cpus;
}
641

642 643
static int
openvzWriteConfigParam(const char * conf_file, const char *param, const char *value)
644
{
645
    char * temp_file = NULL;
646 647 648 649
    int temp_fd = -1;
    FILE *fp;
    char *line = NULL;
    size_t line_size = 0;
650

651
    if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0)
652 653
        return -1;

654 655
    fp = fopen(conf_file, "r");
    if (fp == NULL)
656
        goto error;
657
    temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
658
    if (temp_fd == -1)
659
        goto error;
660

E
Eric Blake 已提交
661
    while (1) {
662
        if (getline(&line, &line_size, fp) <= 0)
663 664
            break;

665
        if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) {
666 667 668 669 670 671 672 673 674 675 676 677
            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;

678
    if (VIR_FCLOSE(fp) < 0)
679
        goto error;
680
    if (VIR_CLOSE(temp_fd) < 0)
681 682 683 684 685
        goto error;

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

686 687
    VIR_FREE(line);

688 689
    return 0;

690
 error:
691 692
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
693
    VIR_FORCE_CLOSE(temp_fd);
E
Eric Blake 已提交
694
    if (temp_file)
695 696
        unlink(temp_file);
    VIR_FREE(temp_file);
697 698 699
    return -1;
}

700
int
701 702
openvzWriteVPSConfigParam(int vpsid, const char *param, const char *value)
{
703 704
    char *conf_file;
    int ret;
705

706
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
707 708
        return -1;

709 710 711
    ret = openvzWriteConfigParam(conf_file, param, value);
    VIR_FREE(conf_file);
    return ret;
712 713
}

714 715 716
/*
 * value will be freed before a new value is assigned to it, the caller is
 * responsible for freeing it afterwards.
717 718
 *
 * Returns <0 on error, 0 if not found, 1 if found.
719
 */
720
int
721
openvzReadConfigParam(const char *conf_file, const char *param, char **value)
722
{
723 724 725
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
726 727
    int err = 0;
    char *sf, *token, *saveptr = NULL;
728

729 730
    fp = fopen(conf_file, "r");
    if (fp == NULL)
731 732
        return -1;

733
    VIR_FREE(*value);
734 735 736 737 738 739
    while (1) {
        if (getline(&line, &line_size, fp) < 0) {
            err = !feof(fp);
            break;
        }

J
Ján Tomko 已提交
740
        if (!(sf = STRSKIP(line, param)))
741 742
            continue;

J
Ján Tomko 已提交
743 744
        if (*sf++ != '=')
            continue;
745

746
        saveptr = NULL;
747 748
        if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) {
            VIR_FREE(*value);
749
            if (VIR_STRDUP(*value, token) < 0) {
750 751
                err = 1;
                break;
752
            }
753 754
            /* keep going - last entry wins */
        }
755
    }
756 757
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
758

759
    return err ? -1 : *value ? 1 : 0;
760 761
}

762
/*
763 764
 * Read parameter from container config
 *
N
Nitesh Konkar 已提交
765
 * value will be freed before a new value is assigned to it, the caller is
766 767 768 769 770 771 772
 * responsible for freeing it afterwards.
 *
 * sample: 133, "OSTEMPLATE", &value
 * return: -1 - error
 *          0 - don't found
 *          1 - OK
 */
773
int
774
openvzReadVPSConfigParam(int vpsid, const char *param, char **value)
775
{
776 777
    char *conf_file;
    int ret;
778

779
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
780 781
        return -1;

782
    ret = openvzReadConfigParam(conf_file, param, value);
783 784
    VIR_FREE(conf_file);
    return ret;
785 786 787 788 789
}

static int
openvz_copyfile(char* from_path, char* to_path)
{
790 791 792 793
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
    int copy_fd;
794 795
    int bytes_read;

796 797
    fp = fopen(from_path, "r");
    if (fp == NULL)
798 799 800
        return -1;
    copy_fd = open(to_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (copy_fd == -1) {
801
        VIR_FORCE_FCLOSE(fp);
802 803 804
        return -1;
    }

E
Eric Blake 已提交
805
    while (1) {
806
        if (getline(&line, &line_size, fp) <= 0)
807 808 809 810 811 812 813
            break;

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

814
    if (VIR_FCLOSE(fp) < 0)
815
        goto error;
816
    if (VIR_CLOSE(copy_fd) < 0)
817 818
        goto error;

819 820
    VIR_FREE(line);

821 822
    return 0;

823
 error:
824 825
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
826
    VIR_FORCE_CLOSE(copy_fd);
827 828 829 830 831 832 833 834 835 836 837
    return -1;
}

/*
* Copy the default config to the VE conf file
* return: -1 - error
*          0 - OK
*/
int
openvzCopyDefaultConfig(int vpsid)
{
838 839 840
    char *confdir = NULL;
    char *default_conf_file = NULL;
    char *configfile_value = NULL;
841
    char *conf_file = NULL;
842 843
    int ret = -1;

844
    if (openvzReadConfigParam(VZ_CONF_FILE, "CONFIGFILE", &configfile_value) < 0)
845 846 847 848 849 850
        goto cleanup;

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

851
    if (virAsprintf(&default_conf_file, "%s/ve-%s.conf-sample", confdir,
852
                    configfile_value) < 0)
853 854
        goto cleanup;

855
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
856 857 858 859 860 861
        goto cleanup;

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

    ret = 0;
862
 cleanup:
863 864
    VIR_FREE(confdir);
    VIR_FREE(default_conf_file);
865
    VIR_FREE(configfile_value);
866
    VIR_FREE(conf_file);
867 868 869
    return ret;
}

870
/* Locate config file of container
871 872
 * return -1 - error
 *         0 - OK */
873
static int
874
openvzLocateConfFileDefault(int vpsid, char **conffile, const char *ext)
875
{
876
    char *confdir;
877 878 879 880 881 882
    int ret = 0;

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

883
    if (virAsprintf(conffile, "%s/%d.%s", confdir, vpsid,
884
                    ext ? ext : "conf") < 0)
885 886 887 888 889 890
        ret = -1;

    VIR_FREE(confdir);
    return ret;
}

891 892
static char *
openvzLocateConfDir(void)
893 894
{
    const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL};
895
    size_t i = 0;
896
    char *ret = NULL;
897

E
Eric Blake 已提交
898
    while (conf_dir_list[i]) {
899
        if (virFileExists(conf_dir_list[i])) {
900 901 902
            ignore_value(VIR_STRDUP(ret, conf_dir_list[i]));
            goto cleanup;
        }
E
Eric Blake 已提交
903
        i++;
904 905
    }

906
 cleanup:
907
    return ret;
908 909 910
}

/* Richard Steven's classic readline() function */
911
int
912
openvz_readline(int fd, char *ptr, int maxlen)
913 914 915 916
{
    int n, rc;
    char c;

E
Eric Blake 已提交
917
    for (n = 1; n < maxlen; n++) {
918
        if ((rc = read(fd, &c, 1)) == 1) {
919
            *ptr++ = c;
E
Eric Blake 已提交
920
            if (c == '\n')
921
                break;
E
Eric Blake 已提交
922 923
        } else if (rc == 0) {
            if (n == 1)
924 925 926 927 928 929 930 931 932 933 934
                return 0; /* EOF condition */
            else
                break;
        }
        else
            return -1; /* error */
    }
    *ptr = 0;
    return n;
}

935
static int
936
openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len)
937
{
938
    char *conf_file;
939 940
    char *line = NULL;
    size_t line_size = 0;
941
    char *saveptr = NULL;
942 943
    char *uuidbuf;
    char *iden;
944
    FILE *fp;
945
    int retval = -1;
946

947
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
948
        return -1;
949

950 951
    fp = fopen(conf_file, "r");
    if (fp == NULL)
952
        goto cleanup;
953

E
Eric Blake 已提交
954
    while (1) {
955 956 957 958 959 960 961
        if (getline(&line, &line_size, fp) < 0) {
            if (feof(fp)) { /* EOF, UUID was not found */
                uuidstr[0] = 0;
                break;
            } else {
                goto cleanup;
            }
962 963
        }

964 965 966 967
        iden = strtok_r(line, " ", &saveptr);
        uuidbuf = strtok_r(NULL, "\n", &saveptr);

        if (iden != NULL && uuidbuf != NULL && STREQ(iden, "#UUID:")) {
968
            if (virStrcpy(uuidstr, uuidbuf, len) == NULL) {
969 970
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("invalid uuid %s"), uuidbuf);
971 972
                goto cleanup;
            }
973 974 975
            break;
        }
    }
976
    retval = 0;
977
 cleanup:
978 979
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
980
    VIR_FREE(conf_file);
981

C
Chris Lalancette 已提交
982
    return retval;
983 984 985 986 987
}

/* Do actual checking for UUID presence in conf file,
 * assign if not present.
 */
988 989
int
openvzSetDefinedUUID(int vpsid, unsigned char *uuid)
990
{
991
    char *conf_file;
992
    char uuidstr[VIR_UUID_STRING_BUFLEN];
993
    FILE *fp = NULL;
994
    int ret = -1;
995 996 997

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

999
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
1000
        return -1;
1001

1002
    if (openvzGetVPSUUID(vpsid, uuidstr, sizeof(uuidstr)))
1003
        goto cleanup;
1004

J
Jim Meyering 已提交
1005
    if (uuidstr[0] == 0) {
1006
        fp = fopen(conf_file, "a"); /* append */
1007
        if (fp == NULL)
1008
            goto cleanup;
1009

1010 1011
        virUUIDFormat(uuid, uuidstr);

1012
        /* Record failure if fprintf or VIR_FCLOSE fails,
1013
           and be careful always to close the stream.  */
1014 1015
        if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0) ||
            (VIR_FCLOSE(fp) == EOF))
1016
            goto cleanup;
1017 1018
    }

1019
    ret = 0;
1020
 cleanup:
1021
    VIR_FORCE_FCLOSE(fp);
1022 1023
    VIR_FREE(conf_file);
    return ret;
1024 1025
}

1026
static int
1027 1028
openvzSetUUID(int vpsid)
{
1029 1030
    unsigned char uuid[VIR_UUID_BUFLEN];

1031
    if (virUUIDGenerate(uuid)) {
1032 1033
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to generate UUID"));
1034 1035
        return -1;
    }
1036 1037 1038 1039

    return openvzSetDefinedUUID(vpsid, uuid);
}

1040 1041 1042 1043 1044 1045 1046
/*
 * 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.
 *
 */

1047
static int openvzAssignUUIDs(void)
1048 1049 1050 1051
{
    DIR *dp;
    struct dirent *dent;
    char *conf_dir;
1052 1053 1054
    int vpsid;
    char *ext;
    int ret = 0;
1055 1056

    conf_dir = openvzLocateConfDir();
1057 1058
    if (conf_dir == NULL)
        return -1;
1059

J
Ján Tomko 已提交
1060
    if (virDirOpenQuiet(&dp, conf_dir) < 0) {
1061
        VIR_FREE(conf_dir);
1062 1063 1064
        return 0;
    }

E
Eric Blake 已提交
1065
    while ((ret = virDirRead(dp, &dent, conf_dir)) > 0) {
1066 1067 1068
        if (virStrToLong_i(dent->d_name, &ext, 10, &vpsid) < 0 ||
            *ext++ != '.' ||
            STRNEQ(ext, "conf"))
1069
            continue;
E
Eric Blake 已提交
1070
        if (vpsid > 0) /* '0.conf' belongs to the host, ignore it */
1071 1072
            openvzSetUUID(vpsid);
    }
1073

J
Ján Tomko 已提交
1074
    VIR_DIR_CLOSE(dp);
1075
    VIR_FREE(conf_dir);
1076
    return ret;
1077
}
1078 1079 1080 1081 1082 1083 1084


/*
 * Return CTID from name
 *
 */

1085 1086
int openvzGetVEID(const char *name)
{
E
Eric Blake 已提交
1087 1088
    virCommandPtr cmd;
    char *outbuf;
1089
    char *temp;
1090
    int veid;
1091
    bool ok;
1092

E
Eric Blake 已提交
1093 1094 1095 1096 1097
    cmd = virCommandNewArgList(VZLIST, name, "-ovpsid", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0) {
        virCommandFree(cmd);
        VIR_FREE(outbuf);
1098 1099 1100
        return -1;
    }

E
Eric Blake 已提交
1101
    virCommandFree(cmd);
1102
    ok = virStrToLong_i(outbuf, &temp, 10, &veid) == 0 && *temp == '\n';
E
Eric Blake 已提交
1103
    VIR_FREE(outbuf);
1104

1105 1106 1107
    if (ok && veid >= 0)
        return veid;

1108 1109
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Failed to parse vzlist output"));
1110 1111
    return -1;
}