phyp_driver.c 63.8 KB
Newer Older
1 2

/*
3
 * Copyright (C) 2010 Red Hat, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * Copyright IBM Corp. 2009
 *
 * phyp_driver.c: ssh layer to access Power Hypervisors
 *
 * Authors:
 *  Eduardo Otubo <otubo at linux.vnet.ibm.com>
 *
 * 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
 */

#include <config.h>

#include <sys/types.h>
29
#include <sys/stat.h>
30 31 32 33 34 35 36 37
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
38 39 40 41 42
#include <libssh2.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
43 44 45
#include <fcntl.h>
#include <sys/utsname.h>
#include <domain_event.h>
46 47

#include "internal.h"
48
#include "authhelper.h"
49 50 51 52 53 54 55 56 57 58
#include "util.h"
#include "datatypes.h"
#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "driver.h"
#include "libvirt/libvirt.h"
#include "virterror_internal.h"
#include "uuid.h"
#include "domain_conf.h"
59
#include "nodeinfo.h"
60 61 62 63 64

#include "phyp_driver.h"

#define VIR_FROM_THIS VIR_FROM_PHYP

65 66
#define PHYP_ERROR(code, ...)                                                 \
    virReportErrorHelper(NULL, VIR_FROM_PHYP, code, __FILE__, __FUNCTION__,   \
67
                         __LINE__, __VA_ARGS__)
68

E
Eduardo Otubo 已提交
69 70 71
static unsigned const int HMC = 0;
static unsigned const int IVM = 127;

72 73 74 75 76 77 78 79
/*
 * URI: phyp://user@[hmc|ivm]/managed_system
 * */

static virDrvOpenStatus
phypOpen(virConnectPtr conn,
         virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
80
    LIBSSH2_SESSION *session = NULL;
81
    ConnectionData *connection_data = NULL;
82
    char *string = NULL;
83
    size_t len = 0;
84
    int internal_socket;
85 86 87
    uuid_tablePtr uuid_table = NULL;
    phyp_driverPtr phyp_driver = NULL;
    char *char_ptr;
E
Eduardo Otubo 已提交
88
    char *managed_system = NULL;
89 90 91 92 93 94 95 96

    if (!conn || !conn->uri)
        return VIR_DRV_OPEN_DECLINED;

    if (conn->uri->scheme == NULL || STRNEQ(conn->uri->scheme, "phyp"))
        return VIR_DRV_OPEN_DECLINED;

    if (conn->uri->server == NULL) {
97
        PHYP_ERROR(VIR_ERR_INTERNAL_ERROR,
98
                   "%s", _("Missing server name in phyp:// URI"));
99 100 101 102
        return VIR_DRV_OPEN_ERROR;
    }

    if (VIR_ALLOC(phyp_driver) < 0) {
103
        virReportOOMError();
104 105 106 107
        goto failure;
    }

    if (VIR_ALLOC(uuid_table) < 0) {
108
        virReportOOMError();
109 110 111 112
        goto failure;
    }

    if (VIR_ALLOC(connection_data) < 0) {
113
        virReportOOMError();
114 115 116
        goto failure;
    }

E
Eduardo Otubo 已提交
117 118
    if (conn->uri->path) {
        len = strlen(conn->uri->path) + 1;
119

E
Eduardo Otubo 已提交
120 121 122 123
        if (VIR_ALLOC_N(string, len) < 0) {
            virReportOOMError();
            goto failure;
        }
124

E
Eduardo Otubo 已提交
125 126 127 128 129
        /* need to shift one byte in order to remove the first "/" of URI component */
        if (conn->uri->path[0] == '/')
            managed_system = strdup(conn->uri->path + 1);
        else
            managed_system = strdup(conn->uri->path);
130

E
Eduardo Otubo 已提交
131 132 133 134
        if (!managed_system) {
            virReportOOMError();
            goto failure;
        }
135

E
Eduardo Otubo 已提交
136 137 138 139
        /* here we are handling only the first component of the path,
         * so skipping the second:
         * */
        char_ptr = strchr(managed_system, '/');
140

E
Eduardo Otubo 已提交
141 142
        if (char_ptr)
            *char_ptr = '\0';
143

E
Eduardo Otubo 已提交
144 145 146 147 148 149
        if (escape_specialcharacters(conn->uri->path, string, len) == -1) {
            PHYP_ERROR(VIR_ERR_INTERNAL_ERROR,
                       "%s",
                       _("Error parsing 'path'. Invalid characters."));
            goto failure;
        }
150 151
    }

152
    if ((session = openSSHSession(conn, auth, &internal_socket)) == NULL) {
153
        PHYP_ERROR(VIR_ERR_INTERNAL_ERROR,
154
                   "%s", _("Error while opening SSH session."));
155
        goto failure;
156
    }
157

158 159
    connection_data->session = session;

160 161 162
    uuid_table->nlpars = 0;
    uuid_table->lpars = NULL;

E
Eduardo Otubo 已提交
163 164 165
    if (conn->uri->path)
        phyp_driver->managed_system = managed_system;

166 167
    phyp_driver->uuid_table = uuid_table;
    if ((phyp_driver->caps = phypCapsInit()) == NULL) {
168
        virReportOOMError();
169 170
        goto failure;
    }
171

172
    conn->privateData = phyp_driver;
173
    conn->networkPrivateData = connection_data;
E
Eduardo Otubo 已提交
174 175

    if ((phyp_driver->system_type = phypGetSystemType(conn)) == -1)
176 177
        goto failure;

E
Eduardo Otubo 已提交
178
    if (phypUUIDTable_Init(conn) == -1)
179
        goto failure;
180

E
Eduardo Otubo 已提交
181 182 183 184 185
    if (phyp_driver->system_type == HMC) {
        if ((phyp_driver->vios_id = phypGetVIOSPartitionID(conn)) == -1)
            goto failure;
    }

186
    return VIR_DRV_OPEN_SUCCESS;
187

188
  failure:
189 190 191 192 193 194 195 196 197 198 199 200 201
    if (phyp_driver != NULL) {
        virCapabilitiesFree(phyp_driver->caps);
        VIR_FREE(phyp_driver->managed_system);
        VIR_FREE(phyp_driver);
    }

    phypUUIDTable_Free(uuid_table);

    if (session != NULL) {
        libssh2_session_disconnect(session, "Disconnecting...");
        libssh2_session_free(session);
    }

202 203 204 205
    VIR_FREE(connection_data);
    VIR_FREE(string);

    return VIR_DRV_OPEN_ERROR;
206 207 208 209 210 211
}

static int
phypClose(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
212
    phyp_driverPtr phyp_driver = conn->privateData;
213
    LIBSSH2_SESSION *session = connection_data->session;
214

215 216
    libssh2_session_disconnect(session, "Disconnecting...");
    libssh2_session_free(session);
217

218
    virCapabilitiesFree(phyp_driver->caps);
219
    phypUUIDTable_Free(phyp_driver->uuid_table);
220 221
    VIR_FREE(phyp_driver->managed_system);
    VIR_FREE(phyp_driver);
222 223 224 225
    VIR_FREE(connection_data);
    return 0;
}

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

static int
phypIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Phyp uses an SSH tunnel, so is always encrypted */
    return 1;
}


static int
phypIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Phyp uses an SSH tunnel, so is always secure */
    return 1;
}


243 244 245
LIBSSH2_SESSION *
openSSHSession(virConnectPtr conn, virConnectAuthPtr auth,
               int *internal_socket)
246
{
247 248
    LIBSSH2_SESSION *session;
    const char *hostname = conn->uri->server;
249 250
    char *username = NULL;
    char *password = NULL;
251 252 253 254 255
    int sock;
    int rc;
    struct addrinfo *ai = NULL, *cur;
    struct addrinfo hints;
    int ret;
256 257
    char *pubkey = NULL;
    char *pvtkey = NULL;
258
    char *userhome = virGetUserDirectory(geteuid());
259 260 261 262 263 264
    struct stat pvt_stat, pub_stat;

    if (userhome == NULL)
        goto err;

    if (virAsprintf(&pubkey, "%s/.ssh/id_rsa.pub", userhome) < 0) {
265
        virReportOOMError();
266 267 268 269
        goto err;
    }

    if (virAsprintf(&pvtkey, "%s/.ssh/id_rsa", userhome) < 0) {
270
        virReportOOMError();
271 272
        goto err;
    }
273

274 275 276 277 278 279 280 281 282
    if (conn->uri->user != NULL) {
        username = strdup(conn->uri->user);

        if (username == NULL) {
            virReportOOMError();
            goto err;
        }
    } else {
        if (auth == NULL || auth->cb == NULL) {
283
            PHYP_ERROR(VIR_ERR_AUTH_FAILED,
284 285 286 287 288 289 290
                       "%s", _("No authentication callback provided."));
            goto err;
        }

        username = virRequestUsername(auth, NULL, conn->uri->server);

        if (username == NULL) {
E
Eduardo Otubo 已提交
291 292
            PHYP_ERROR(VIR_ERR_AUTH_FAILED, "%s",
                       _("Username request failed"));
293 294 295 296
            goto err;
        }
    }

297
    memset(&hints, 0, sizeof(hints));
298 299 300 301
    hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;

302
    ret = getaddrinfo(hostname, "22", &hints, &ai);
303
    if (ret != 0) {
304
        PHYP_ERROR(VIR_ERR_INTERNAL_ERROR,
305
                   _("Error while getting %s address info"), hostname);
306 307 308
        goto err;
    }

309 310 311 312
    cur = ai;
    while (cur != NULL) {
        sock = socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
        if (sock >= 0) {
313
            if (connect(sock, cur->ai_addr, cur->ai_addrlen) == 0) {
314 315
                goto connected;
            }
316
            close(sock);
317 318
        }
        cur = cur->ai_next;
319 320
    }

321
    PHYP_ERROR(VIR_ERR_INTERNAL_ERROR,
322
               _("Failed to connect to %s"), hostname);
323
    freeaddrinfo(ai);
324 325
    goto err;

326
  connected:
327 328 329 330 331 332 333 334 335 336 337 338 339 340

    (*internal_socket) = sock;

    /* Create a session instance */
    session = libssh2_session_init();
    if (!session)
        goto err;

    /* tell libssh2 we want it all done non-blocking */
    libssh2_session_set_blocking(session, 0);

    while ((rc = libssh2_session_startup(session, sock)) ==
           LIBSSH2_ERROR_EAGAIN) ;
    if (rc) {
341
        PHYP_ERROR(VIR_ERR_INTERNAL_ERROR,
342
                   "%s", _("Failure establishing SSH session."));
343
        goto disconnect;
344 345
    }

346
    /* Trying authentication by pubkey */
347 348
    if (stat(pvtkey, &pvt_stat) || stat(pubkey, &pub_stat)) {
        rc = LIBSSH2_ERROR_SOCKET_NONE;
349
        goto keyboard_interactive;
350
    }
351

352 353
    while ((rc =
            libssh2_userauth_publickey_fromfile(session, username,
354 355 356
                                                pubkey,
                                                pvtkey,
                                                NULL)) ==
357
           LIBSSH2_ERROR_EAGAIN) ;
358

359
  keyboard_interactive:
360 361 362
    if (rc == LIBSSH2_ERROR_SOCKET_NONE
        || rc == LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED
        || rc == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED) {
363
        if (auth == NULL || auth->cb == NULL) {
364
            PHYP_ERROR(VIR_ERR_AUTH_FAILED,
365
                       "%s", _("No authentication callback provided."));
366
            goto disconnect;
367 368
        }

369
        password = virRequestPassword(auth, username, conn->uri->server);
370

371
        if (password == NULL) {
E
Eduardo Otubo 已提交
372 373
            PHYP_ERROR(VIR_ERR_AUTH_FAILED, "%s",
                       _("Password request failed"));
374
            goto disconnect;
375 376
        }

377 378 379 380
        while ((rc =
                libssh2_userauth_password(session, username,
                                          password)) ==
               LIBSSH2_ERROR_EAGAIN) ;
381

382
        if (rc) {
383
            PHYP_ERROR(VIR_ERR_AUTH_FAILED,
384
                       "%s", _("Authentication failed"));
385
            goto disconnect;
386 387
        } else
            goto exit;
388 389 390 391 392 393 394

    } else if (rc == LIBSSH2_ERROR_NONE) {
        goto exit;

    } else if (rc == LIBSSH2_ERROR_ALLOC || rc == LIBSSH2_ERROR_SOCKET_SEND
               || rc == LIBSSH2_ERROR_SOCKET_TIMEOUT) {
        goto err;
395
    }
396

397 398 399
  disconnect:
    libssh2_session_disconnect(session, "Disconnecting...");
    libssh2_session_free(session);
400
  err:
401 402 403
    VIR_FREE(userhome);
    VIR_FREE(pubkey);
    VIR_FREE(pvtkey);
404
    VIR_FREE(username);
405
    VIR_FREE(password);
406 407 408
    return NULL;

  exit:
409 410 411
    VIR_FREE(userhome);
    VIR_FREE(pubkey);
    VIR_FREE(pvtkey);
412
    VIR_FREE(username);
413
    VIR_FREE(password);
414 415 416 417 418 419
    return session;
}

/* this functions is the layer that manipulates the ssh channel itself
 * and executes the commands on the remote machine */
static char *
420
phypExec(LIBSSH2_SESSION * session, char *cmd, int *exit_status,
421 422
         virConnectPtr conn)
{
423 424
    LIBSSH2_CHANNEL *channel;
    ConnectionData *connection_data = conn->networkPrivateData;
425
    virBuffer tex_ret = VIR_BUFFER_INITIALIZER;
426 427 428 429 430 431 432 433 434 435 436 437
    char buffer[0x4000] = { 0 };
    int exitcode;
    int bytecount = 0;
    int sock = connection_data->sock;
    int rc = 0;

    /* Exec non-blocking on the remove host */
    while ((channel = libssh2_channel_open_session(session)) == NULL &&
           libssh2_session_last_error(session, NULL, NULL, 0) ==
           LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
438

439
    if (channel == NULL) {
440 441 442
        goto err;
    }

443 444 445
    while ((rc = libssh2_channel_exec(channel, cmd)) ==
           LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
446 447
    }

448
    if (rc != 0) {
449 450 451
        goto err;
    }

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    for (;;) {
        /* loop until we block */
        do {
            rc = libssh2_channel_read(channel, buffer, sizeof(buffer));
            if (rc > 0) {
                bytecount += rc;
                virBufferVSprintf(&tex_ret, "%s", buffer);
            }
        }
        while (rc > 0);

        /* this is due to blocking that would occur otherwise so we loop on
         * this condition */
        if (rc == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
        } else {
            break;
        }
    }
471

472
    exitcode = 127;
473

474 475 476
    while ((rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
477

478 479
    if (rc == 0) {
        exitcode = libssh2_channel_get_exit_status(channel);
480 481
    }

482 483 484 485 486
    (*exit_status) = exitcode;
    libssh2_channel_free(channel);
    channel = NULL;
    goto exit;

487 488
  err:
    (*exit_status) = SSH_CMD_ERR;
489
    virBufferFreeAndReset(&tex_ret);
490 491 492 493
    return NULL;

  exit:
    if (virBufferError(&tex_ret)) {
494
        virBufferFreeAndReset(&tex_ret);
495
        virReportOOMError();
496 497 498 499 500
        return NULL;
    }
    return virBufferContentAndReset(&tex_ret);
}

E
Eduardo Otubo 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
int
phypGetSystemType(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    char *cmd = NULL;
    char *ret = NULL;
    int exit_status = 0;

    if (virAsprintf(&cmd, "lshmc -V") < 0) {
        virReportOOMError();
        exit_status = -1;
    }
    ret = phypExec(session, cmd, &exit_status, conn);

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return exit_status;
}


522 523
/* return the lpar_id given a name and a managed system name */
static int
524
phypGetLparID(LIBSSH2_SESSION * session, const char *managed_system,
525 526
              const char *name, virConnectPtr conn)
{
E
Eduardo Otubo 已提交
527 528
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
529 530 531
    int exit_status = 0;
    int lpar_id = 0;
    char *char_ptr;
532 533
    char *cmd = NULL;
    char *ret = NULL;
E
Eduardo Otubo 已提交
534 535 536 537 538 539 540 541
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lssyscfg -r lpar");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " --filter lpar_names=%s -F lpar_id", name);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
542
        virReportOOMError();
E
Eduardo Otubo 已提交
543
        return -1;
544
    }
E
Eduardo Otubo 已提交
545
    cmd = virBufferContentAndReset(&buf);
546

547
    ret = phypExec(session, cmd, &exit_status, conn);
548

549
    if (exit_status < 0 || ret == NULL)
550 551
        goto err;

552
    if (virStrToLong_i(ret, &char_ptr, 10, &lpar_id) == -1)
553 554 555
        goto err;

    VIR_FREE(cmd);
556
    VIR_FREE(ret);
557 558 559 560
    return lpar_id;

  err:
    VIR_FREE(cmd);
561
    VIR_FREE(ret);
562 563 564 565 566
    return -1;
}

/* return the lpar name given a lpar_id and a managed system name */
static char *
567
phypGetLparNAME(LIBSSH2_SESSION * session, const char *managed_system,
568 569
                unsigned int lpar_id, virConnectPtr conn)
{
E
Eduardo Otubo 已提交
570 571
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
572 573
    char *cmd = NULL;
    char *ret = NULL;
574
    int exit_status = 0;
E
Eduardo Otubo 已提交
575 576 577 578 579 580 581 582
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lssyscfg -r lpar");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " --filter lpar_ids=%d -F name", lpar_id);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
583
        virReportOOMError();
E
Eduardo Otubo 已提交
584
        return NULL;
585
    }
E
Eduardo Otubo 已提交
586
    cmd = virBufferContentAndReset(&buf);
587

588
    ret = phypExec(session, cmd, &exit_status, conn);
589

590
    if (exit_status < 0 || ret == NULL)
591 592
        goto err;

593
    char *char_ptr = strchr(ret, '\n');
594 595 596 597 598

    if (char_ptr)
        *char_ptr = '\0';

    VIR_FREE(cmd);
599
    return ret;
600 601 602

  err:
    VIR_FREE(cmd);
603
    VIR_FREE(ret);
604 605 606 607
    return NULL;
}


608
/* Search into the uuid_table for a lpar_uuid given a lpar_id
609 610 611 612 613 614 615 616
 * and a managed system name
 *
 * return:  0 - record found
 *         -1 - not found
 * */
int
phypGetLparUUID(unsigned char *uuid, int lpar_id, virConnectPtr conn)
{
617 618 619
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    lparPtr *lpars = uuid_table->lpars;
620 621
    unsigned int i = 0;

622
    for (i = 0; i < uuid_table->nlpars; i++) {
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        if (lpars[i]->id == lpar_id) {
            memmove(uuid, lpars[i]->uuid, VIR_UUID_BUFLEN);
            return 0;
        }
    }

    return -1;
}

/*
 * type:
 * 0 - maxmem
 * 1 - memory
 * */
unsigned long
phypGetLparMem(virConnectPtr conn, const char *managed_system, int lpar_id,
               int type)
{
    ConnectionData *connection_data = conn->networkPrivateData;
642
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
643 644
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
645 646
    char *cmd = NULL;
    char *ret = NULL;
647 648 649
    char *char_ptr;
    int memory = 0;
    int exit_status = 0;
E
Eduardo Otubo 已提交
650
    virBuffer buf = VIR_BUFFER_INITIALIZER;
651 652

    if (type != 1 && type != 0)
E
Eduardo Otubo 已提交
653 654 655 656 657
        return 0;

    virBufferAddLit(&buf, "lshwres");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
658 659
    virBufferVSprintf(&buf,
                      " -r mem --level lpar -F %s --filter lpar_ids=%d",
E
Eduardo Otubo 已提交
660 661 662 663 664
                      type ? "curr_mem" : "curr_max_mem", lpar_id);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return 0;
665
    }
E
Eduardo Otubo 已提交
666
    cmd = virBufferContentAndReset(&buf);
667

668
    ret = phypExec(session, cmd, &exit_status, conn);
669

670
    if (exit_status < 0 || ret == NULL)
671 672
        goto err;

673
    char_ptr = strchr(ret, '\n');
674

675 676
    if (char_ptr)
        *char_ptr = '\0';
677

678
    if (virStrToLong_i(ret, &char_ptr, 10, &memory) == -1)
679 680 681
        goto err;

    VIR_FREE(cmd);
682
    VIR_FREE(ret);
683 684 685 686
    return memory;

  err:
    VIR_FREE(cmd);
687
    VIR_FREE(ret);
688 689 690 691 692 693
    return 0;

}

unsigned long
phypGetLparCPU(virConnectPtr conn, const char *managed_system, int lpar_id)
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
{
    return phypGetLparCPUGeneric(conn, managed_system, lpar_id, 0);
}

static int
phypGetLparCPUMAX(virDomainPtr dom)
{
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    char *managed_system = phyp_driver->managed_system;

    return phypGetLparCPUGeneric(dom->conn, managed_system, dom->id, 1);
}

unsigned long
phypGetLparCPUGeneric(virConnectPtr conn, const char *managed_system,
                      int lpar_id, int type)
710 711
{
    ConnectionData *connection_data = conn->networkPrivateData;
712
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
713 714
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
715 716
    char *cmd = NULL;
    char *ret = NULL;
717
    char *char_ptr;
718 719
    int exit_status = 0;
    int vcpus = 0;
E
Eduardo Otubo 已提交
720 721 722 723 724
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lshwres");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
725 726
    virBufferVSprintf(&buf,
                      " -r proc --level lpar -F %s --filter lpar_ids=%d",
E
Eduardo Otubo 已提交
727 728 729 730 731
                      type ? "curr_max_procs" : "curr_procs", lpar_id);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return 0;
732
    }
E
Eduardo Otubo 已提交
733 734
    cmd = virBufferContentAndReset(&buf);

735
    ret = phypExec(session, cmd, &exit_status, conn);
736

737
    if (exit_status < 0 || ret == NULL)
738 739
        goto err;

740
    char_ptr = strchr(ret, '\n');
741 742 743 744

    if (char_ptr)
        *char_ptr = '\0';

745
    if (virStrToLong_i(ret, &char_ptr, 10, &vcpus) == -1)
746 747 748
        goto err;

    VIR_FREE(cmd);
749
    VIR_FREE(ret);
750 751 752 753
    return (unsigned long) vcpus;

  err:
    VIR_FREE(cmd);
754
    VIR_FREE(ret);
755 756 757 758 759 760 761 762
    return 0;
}

int
phypGetRemoteSlot(virConnectPtr conn, const char *managed_system,
                  const char *lpar_name)
{
    ConnectionData *connection_data = conn->networkPrivateData;
763
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
764 765
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
766 767
    char *cmd = NULL;
    char *ret = NULL;
768 769 770
    char *char_ptr;
    int remote_slot = 0;
    int exit_status = 0;
E
Eduardo Otubo 已提交
771 772 773 774 775 776
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lshwres");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -r virtualio --rsubtype scsi -F "
777
                      "remote_slot_num --filter lpar_names=%s", lpar_name);
E
Eduardo Otubo 已提交
778 779
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
780
        virReportOOMError();
E
Eduardo Otubo 已提交
781
        return -1;
782
    }
E
Eduardo Otubo 已提交
783 784
    cmd = virBufferContentAndReset(&buf);

785
    ret = phypExec(session, cmd, &exit_status, conn);
786

787
    if (exit_status < 0 || ret == NULL)
788 789
        goto err;

790
    char_ptr = strchr(ret, '\n');
791

792 793
    if (char_ptr)
        *char_ptr = '\0';
794

795
    if (virStrToLong_i(ret, &char_ptr, 10, &remote_slot) == -1)
796 797 798
        goto err;

    VIR_FREE(cmd);
799
    VIR_FREE(ret);
800 801 802 803
    return remote_slot;

  err:
    VIR_FREE(cmd);
804
    VIR_FREE(ret);
805
    return -1;
806 807 808 809 810 811 812
}

char *
phypGetBackingDevice(virConnectPtr conn, const char *managed_system,
                     char *lpar_name)
{
    ConnectionData *connection_data = conn->networkPrivateData;
813
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
814 815
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
816 817
    char *cmd = NULL;
    char *ret = NULL;
818 819
    int remote_slot = 0;
    int exit_status = 0;
820 821
    char *char_ptr;
    char *backing_device = NULL;
E
Eduardo Otubo 已提交
822
    virBuffer buf = VIR_BUFFER_INITIALIZER;
823 824

    if ((remote_slot =
825
         phypGetRemoteSlot(conn, managed_system, lpar_name)) == -1)
E
Eduardo Otubo 已提交
826
        return NULL;
827

E
Eduardo Otubo 已提交
828 829 830 831 832 833 834
    virBufferAddLit(&buf, "lshwres");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -r virtualio --rsubtype scsi -F "
                      "backing_devices --filter slots=%d", remote_slot);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
835
        virReportOOMError();
E
Eduardo Otubo 已提交
836
        return NULL;
837
    }
E
Eduardo Otubo 已提交
838
    cmd = virBufferContentAndReset(&buf);
839

840
    ret = phypExec(session, cmd, &exit_status, conn);
841

842
    if (exit_status < 0 || ret == NULL)
843 844 845 846 847 848 849 850 851
        goto err;

    /* here is a little trick to deal returns of this kind:
     *
     * 0x8100000000000000//lv01
     *
     * the information we really need is only lv01, so we
     * need to skip a lot of things on the string.
     * */
852
    char_ptr = strchr(ret, '/');
853

854 855 856 857
    if (char_ptr) {
        char_ptr++;
        if (char_ptr[0] == '/')
            char_ptr++;
858 859
        else
            goto err;
860 861 862 863

        backing_device = strdup(char_ptr);

        if (backing_device == NULL) {
864
            virReportOOMError();
865 866
            goto err;
        }
867 868
    } else {
        backing_device = ret;
869
        ret = NULL;
870 871
    }

872
    char_ptr = strchr(backing_device, '\n');
873 874 875 876 877

    if (char_ptr)
        *char_ptr = '\0';

    VIR_FREE(cmd);
878
    VIR_FREE(ret);
879 880 881 882
    return backing_device;

  err:
    VIR_FREE(cmd);
883
    VIR_FREE(ret);
884 885 886 887 888 889 890 891
    return NULL;

}

int
phypGetLparState(virConnectPtr conn, unsigned int lpar_id)
{
    ConnectionData *connection_data = conn->networkPrivateData;
892
    phyp_driverPtr phyp_driver = conn->privateData;
893
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
894
    int system_type = phyp_driver->system_type;
895 896
    char *cmd = NULL;
    char *ret = NULL;
897 898
    int exit_status = 0;
    char *char_ptr = NULL;
899
    char *managed_system = phyp_driver->managed_system;
900
    int state = VIR_DOMAIN_NOSTATE;
E
Eduardo Otubo 已提交
901 902 903 904 905 906 907 908
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lssyscfg -r lpar");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -F state --filter lpar_ids=%d", lpar_id);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
909
        virReportOOMError();
E
Eduardo Otubo 已提交
910
        return state;
911
    }
E
Eduardo Otubo 已提交
912
    cmd = virBufferContentAndReset(&buf);
913

914
    ret = phypExec(session, cmd, &exit_status, conn);
915

916 917
    if (exit_status < 0 || ret == NULL)
        goto cleanup;
918 919 920 921 922 923 924

    char_ptr = strchr(ret, '\n');

    if (char_ptr)
        *char_ptr = '\0';

    if (STREQ(ret, "Running"))
925
        state = VIR_DOMAIN_RUNNING;
926
    else if (STREQ(ret, "Not Activated"))
927
        state = VIR_DOMAIN_SHUTOFF;
928
    else if (STREQ(ret, "Shutting Down"))
929
        state = VIR_DOMAIN_SHUTDOWN;
930

931
  cleanup:
932
    VIR_FREE(cmd);
933 934
    VIR_FREE(ret);
    return state;
935 936
}

937 938 939 940 941 942
int
phypGetVIOSPartitionID(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    phyp_driverPtr phyp_driver = conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
943
    int system_type = phyp_driver->system_type;
944 945
    char *cmd = NULL;
    char *ret = NULL;
946 947 948 949
    int exit_status = 0;
    int id = -1;
    char *char_ptr;
    char *managed_system = phyp_driver->managed_system;
E
Eduardo Otubo 已提交
950 951 952 953 954 955 956 957 958
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lssyscfg");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferAddLit(&buf, " -r lpar -F lpar_id,lpar_env|grep "
                    "vioserver|sed -s 's/,.*$//'");
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
959
        virReportOOMError();
E
Eduardo Otubo 已提交
960
        return -1;
961
    }
E
Eduardo Otubo 已提交
962
    cmd = virBufferContentAndReset(&buf);
963

964
    ret = phypExec(session, cmd, &exit_status, conn);
965 966 967 968 969 970 971

    if (exit_status < 0 || ret == NULL)
        goto err;

    if (virStrToLong_i(ret, &char_ptr, 10, &id) == -1)
        goto err;

972 973
    VIR_FREE(cmd);
    VIR_FREE(ret);
974 975 976 977
    return id;

  err:
    VIR_FREE(cmd);
978
    VIR_FREE(ret);
979 980 981
    return -1;
}

982 983 984
int
phypDiskType(virConnectPtr conn, char *backing_device)
{
985
    phyp_driverPtr phyp_driver = conn->privateData;
986
    ConnectionData *connection_data = conn->networkPrivateData;
987
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
988
    int system_type = phyp_driver->system_type;
989 990
    char *cmd = NULL;
    char *ret = NULL;
991
    int exit_status = 0;
992 993 994
    char *char_ptr;
    char *managed_system = phyp_driver->managed_system;
    int vios_id = phyp_driver->vios_id;
995
    int disk_type = -1;
E
Eduardo Otubo 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "viosvrcmd");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -p %d -c \"lssp -field name type "
                      "-fmt , -all|grep %s|sed -e 's/^.*,//'\"",
                      vios_id, backing_device);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1006
        virReportOOMError();
E
Eduardo Otubo 已提交
1007
        return disk_type;
1008
    }
E
Eduardo Otubo 已提交
1009
    cmd = virBufferContentAndReset(&buf);
1010

1011
    ret = phypExec(session, cmd, &exit_status, conn);
1012

1013 1014
    if (exit_status < 0 || ret == NULL)
        goto cleanup;
1015

1016
    char_ptr = strchr(ret, '\n');
1017 1018 1019 1020 1021

    if (char_ptr)
        *char_ptr = '\0';

    if (STREQ(ret, "LVPOOL"))
1022
        disk_type = VIR_DOMAIN_DISK_TYPE_BLOCK;
1023
    else if (STREQ(ret, "FBPOOL"))
1024
        disk_type = VIR_DOMAIN_DISK_TYPE_FILE;
1025

1026
  cleanup:
1027
    VIR_FREE(cmd);
1028 1029
    VIR_FREE(ret);
    return disk_type;
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
}

/* This is a generic function that won't be used directly by
 * libvirt api. The function returns the number of domains
 * in different states: Running, Not Activated and all:
 *
 * type: 0 - Running
 *       1 - Not Activated
 *       * - All
 * */
static int
phypNumDomainsGeneric(virConnectPtr conn, unsigned int type)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1044
    phyp_driverPtr phyp_driver = conn->privateData;
1045
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1046
    int system_type = phyp_driver->system_type;
1047 1048 1049
    int exit_status = 0;
    int ndom = 0;
    char *char_ptr;
1050 1051
    char *cmd = NULL;
    char *ret = NULL;
1052
    char *managed_system = phyp_driver->managed_system;
1053
    const char *state;
E
Eduardo Otubo 已提交
1054
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1055 1056 1057

    if (type == 0)
        state = "|grep Running";
E
Eduardo Otubo 已提交
1058 1059 1060 1061 1062 1063 1064
    else if (type == 1) {
        if (system_type == HMC) {
            state = "|grep \"Not Activated\"";
        } else {
            state = "|grep \"Open Firmware\"";
        }
    } else
1065 1066
        state = " ";

E
Eduardo Otubo 已提交
1067 1068 1069
    virBufferAddLit(&buf, "lssyscfg -r lpar");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
1070 1071
    virBufferVSprintf(&buf, " -F lpar_id,state %s |grep -c '^[0-9]*'",
                      state);
E
Eduardo Otubo 已提交
1072 1073
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1074
        virReportOOMError();
E
Eduardo Otubo 已提交
1075
        return -1;
1076
    }
E
Eduardo Otubo 已提交
1077
    cmd = virBufferContentAndReset(&buf);
1078

1079
    ret = phypExec(session, cmd, &exit_status, conn);
1080 1081 1082 1083 1084 1085 1086 1087

    if (exit_status < 0 || ret == NULL)
        goto err;

    if (virStrToLong_i(ret, &char_ptr, 10, &ndom) == -1)
        goto err;

    VIR_FREE(cmd);
1088
    VIR_FREE(ret);
1089 1090 1091 1092
    return ndom;

  err:
    VIR_FREE(cmd);
1093
    VIR_FREE(ret);
1094
    return -1;
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
}

static int
phypNumDefinedDomains(virConnectPtr conn)
{
    return phypNumDomainsGeneric(conn, 1);
}

static int
phypNumDomains(virConnectPtr conn)
{
    return phypNumDomainsGeneric(conn, 0);
}

/* This is a generic function that won't be used directly by
 * libvirt api. The function returns the ids of domains
 * in different states: Running, and all:
 *
 * type: 0 - Running
1114
 *       1 - all
1115 1116 1117 1118 1119 1120
 * */
static int
phypListDomainsGeneric(virConnectPtr conn, int *ids, int nids,
                       unsigned int type)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1121
    phyp_driverPtr phyp_driver = conn->privateData;
1122
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1123
    int system_type = phyp_driver->system_type;
1124
    char *managed_system = phyp_driver->managed_system;
1125 1126 1127 1128 1129
    int exit_status = 0;
    int got = 0;
    char *char_ptr;
    unsigned int i = 0, j = 0;
    char id_c[10];
1130 1131
    char *cmd = NULL;
    char *ret = NULL;
1132
    const char *state;
E
Eduardo Otubo 已提交
1133
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1134 1135 1136 1137 1138 1139 1140 1141

    if (type == 0)
        state = "|grep Running";
    else
        state = " ";

    memset(id_c, 0, 10);

E
Eduardo Otubo 已提交
1142 1143 1144
    virBufferAddLit(&buf, "lssyscfg -r lpar");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
1145 1146
    virBufferVSprintf(&buf, " -F lpar_id,state %s | sed -e 's/,.*$//'",
                      state);
E
Eduardo Otubo 已提交
1147 1148
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1149
        virReportOOMError();
E
Eduardo Otubo 已提交
1150
        return -1;
1151
    }
E
Eduardo Otubo 已提交
1152 1153
    cmd = virBufferContentAndReset(&buf);

1154
    ret = phypExec(session, cmd, &exit_status, conn);
1155

1156 1157
    /* I need to parse the textual return in order to get the ret */
    if (exit_status < 0 || ret == NULL)
1158 1159 1160
        goto err;
    else {
        while (got < nids) {
1161 1162 1163 1164
            if (ret[i] == '\0')
                break;
            else if (ret[i] == '\n') {
                if (virStrToLong_i(id_c, &char_ptr, 10, &ids[got]) == -1) {
1165
                    VIR_ERROR(_("Cannot parse number from '%s'"), id_c);
1166 1167
                    goto err;
                }
1168 1169 1170 1171
                memset(id_c, 0, 10);
                j = 0;
                got++;
            } else {
1172
                id_c[j] = ret[i];
1173 1174 1175 1176 1177 1178 1179
                j++;
            }
            i++;
        }
    }

    VIR_FREE(cmd);
1180
    VIR_FREE(ret);
1181 1182 1183 1184
    return got;

  err:
    VIR_FREE(cmd);
1185
    VIR_FREE(ret);
1186
    return -1;
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
}

static int
phypListDomains(virConnectPtr conn, int *ids, int nids)
{
    return phypListDomainsGeneric(conn, ids, nids, 0);
}

static int
phypListDefinedDomains(virConnectPtr conn, char **const names, int nnames)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1199
    phyp_driverPtr phyp_driver = conn->privateData;
1200
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1201
    int system_type = phyp_driver->system_type;
1202
    char *managed_system = phyp_driver->managed_system;
1203 1204
    int exit_status = 0;
    int got = 0;
1205 1206 1207 1208 1209
    int i;
    char *cmd = NULL;
    char *ret = NULL;
    char *domains = NULL;
    char *char_ptr2 = NULL;
E
Eduardo Otubo 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "lssyscfg -r lpar");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -F name,state | grep \"Not Activated\" | "
                      "sed -e 's/,.*$//'");
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1219
        virReportOOMError();
E
Eduardo Otubo 已提交
1220
        return -1;
1221
    }
E
Eduardo Otubo 已提交
1222
    cmd = virBufferContentAndReset(&buf);
1223

1224
    ret = phypExec(session, cmd, &exit_status, conn);
1225 1226

    /* I need to parse the textual return in order to get the domains */
1227
    if (exit_status < 0 || ret == NULL)
1228 1229
        goto err;
    else {
1230 1231
        domains = ret;

1232 1233 1234 1235 1236
        while (got < nnames) {
            char_ptr2 = strchr(domains, '\n');

            if (char_ptr2) {
                *char_ptr2 = '\0';
1237
                if ((names[got++] = strdup(domains)) == NULL) {
1238
                    virReportOOMError();
1239
                    goto err;
1240
                }
1241 1242
                char_ptr2++;
                domains = char_ptr2;
1243 1244
            } else
                break;
1245 1246 1247 1248 1249 1250 1251 1252
        }
    }

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return got;

  err:
1253 1254 1255
    for (i = 0; i < got; i++)
        VIR_FREE(names[i]);
    VIR_FREE(cmd);
1256
    VIR_FREE(ret);
1257
    return -1;
1258 1259 1260 1261 1262 1263
}

static virDomainPtr
phypDomainLookupByName(virConnectPtr conn, const char *lpar_name)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1264
    phyp_driverPtr phyp_driver = conn->privateData;
1265
    LIBSSH2_SESSION *session = connection_data->session;
1266 1267
    virDomainPtr dom = NULL;
    int lpar_id = 0;
1268
    char *managed_system = phyp_driver->managed_system;
1269
    unsigned char lpar_uuid[VIR_UUID_BUFLEN];
1270

1271
    lpar_id = phypGetLparID(session, managed_system, lpar_name, conn);
1272
    if (lpar_id == -1)
1273
        return NULL;
1274 1275

    if (phypGetLparUUID(lpar_uuid, lpar_id, conn) == -1)
1276
        return NULL;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

    dom = virGetDomain(conn, lpar_name, lpar_uuid);

    if (dom)
        dom->id = lpar_id;

    return dom;
}

static virDomainPtr
phypDomainLookupByID(virConnectPtr conn, int lpar_id)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1290
    phyp_driverPtr phyp_driver = conn->privateData;
1291
    LIBSSH2_SESSION *session = connection_data->session;
1292
    virDomainPtr dom = NULL;
1293
    char *managed_system = phyp_driver->managed_system;
1294
    int exit_status = 0;
1295
    unsigned char lpar_uuid[VIR_UUID_BUFLEN];
1296

1297
    char *lpar_name = phypGetLparNAME(session, managed_system, lpar_id,
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
                                      conn);

    if (phypGetLparUUID(lpar_uuid, lpar_id, conn) == -1)
        goto err;

    if (exit_status < 0)
        goto err;

    dom = virGetDomain(conn, lpar_name, lpar_uuid);

    if (dom)
        dom->id = lpar_id;

    VIR_FREE(lpar_name);
    return dom;

  err:
    VIR_FREE(lpar_name);
    return NULL;
}

static char *
phypDomainDumpXML(virDomainPtr dom, int flags)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
1323
    phyp_driverPtr phyp_driver = dom->conn->privateData;
1324
    LIBSSH2_SESSION *session = connection_data->session;
1325
    virDomainDef def;
1326
    char *managed_system = phyp_driver->managed_system;
1327

1328
    memset(&def, 0, sizeof(virDomainDef));
1329

1330 1331
    def.virtType = VIR_DOMAIN_VIRT_PHYP;
    def.id = dom->id;
1332

1333
    char *lpar_name = phypGetLparNAME(session, managed_system, def.id,
1334 1335 1336
                                      dom->conn);

    if (lpar_name == NULL) {
1337
        VIR_ERROR0(_("Unable to determine domain's name."));
1338 1339 1340
        goto err;
    }

1341
    if (phypGetLparUUID(def.uuid, dom->id, dom->conn) == -1) {
1342
        VIR_ERROR0(_("Unable to generate random uuid."));
1343 1344 1345
        goto err;
    }

1346
    if ((def.maxmem =
1347
         phypGetLparMem(dom->conn, managed_system, dom->id, 0)) == 0) {
1348
        VIR_ERROR0(_("Unable to determine domain's max memory."));
1349 1350 1351
        goto err;
    }

1352
    if ((def.memory =
1353
         phypGetLparMem(dom->conn, managed_system, dom->id, 1)) == 0) {
1354
        VIR_ERROR0(_("Unable to determine domain's memory."));
1355 1356 1357
        goto err;
    }

1358
    if ((def.vcpus =
1359
         phypGetLparCPU(dom->conn, managed_system, dom->id)) == 0) {
1360
        VIR_ERROR0(_("Unable to determine domain's CPU."));
1361 1362 1363
        goto err;
    }

1364
    return virDomainDefFormat(&def, flags);
1365 1366 1367

  err:
    return NULL;
1368 1369 1370 1371 1372 1373
}

static int
phypDomainResume(virDomainPtr dom)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
1374
    phyp_driverPtr phyp_driver = dom->conn->privateData;
1375
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1376
    int system_type = phyp_driver->system_type;
1377
    char *managed_system = phyp_driver->managed_system;
1378
    int exit_status = 0;
1379 1380
    char *cmd = NULL;
    char *ret = NULL;
E
Eduardo Otubo 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "chsysstate");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -r lpar -o on --id %d -f %s",
                      dom->id, dom->name);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1390
        virReportOOMError();
E
Eduardo Otubo 已提交
1391
        return -1;
1392
    }
E
Eduardo Otubo 已提交
1393
    cmd = virBufferContentAndReset(&buf);
1394

1395
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1396

1397 1398 1399
    if (exit_status < 0)
        goto err;

1400 1401 1402 1403
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

1404 1405 1406 1407
  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return -1;
1408 1409 1410 1411 1412 1413
}

static int
phypDomainShutdown(virDomainPtr dom)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
E
Eduardo Otubo 已提交
1414
    virConnectPtr conn = dom->conn;
1415
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1416 1417
    phyp_driverPtr phyp_driver = conn->privateData;
    int system_type = phyp_driver->system_type;
1418
    char *managed_system = phyp_driver->managed_system;
1419
    int exit_status = 0;
1420 1421
    char *cmd = NULL;
    char *ret = NULL;
E
Eduardo Otubo 已提交
1422 1423 1424 1425 1426 1427 1428 1429
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "chsysstate");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -r lpar -o shutdown --id %d", dom->id);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1430
        virReportOOMError();
E
Eduardo Otubo 已提交
1431
        return 0;
1432
    }
E
Eduardo Otubo 已提交
1433
    cmd = virBufferContentAndReset(&buf);
1434

1435
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1436

1437 1438 1439
    if (exit_status < 0)
        goto err;

1440 1441 1442 1443
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

1444 1445 1446 1447
  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;
1448 1449 1450 1451 1452
}

static int
phypDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
1453 1454
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    char *managed_system = phyp_driver->managed_system;
1455 1456 1457 1458 1459

    info->state = phypGetLparState(dom->conn, dom->id);

    if ((info->maxMem =
         phypGetLparMem(dom->conn, managed_system, dom->id, 0)) == 0)
1460
        VIR_WARN0("Unable to determine domain's max memory.");
1461 1462 1463

    if ((info->memory =
         phypGetLparMem(dom->conn, managed_system, dom->id, 1)) == 0)
1464
        VIR_WARN0("Unable to determine domain's memory.");
1465 1466 1467

    if ((info->nrVirtCpu =
         phypGetLparCPU(dom->conn, managed_system, dom->id)) == 0)
1468
        VIR_WARN0("Unable to determine domain's CPU.");
1469 1470 1471 1472

    return 0;
}

1473 1474 1475 1476 1477 1478
static int
phypDomainDestroy(virDomainPtr dom)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1479
    int system_type = phyp_driver->system_type;
1480 1481
    char *managed_system = phyp_driver->managed_system;
    int exit_status = 0;
1482 1483
    char *cmd = NULL;
    char *ret = NULL;
E
Eduardo Otubo 已提交
1484 1485 1486 1487 1488 1489 1490 1491
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "rmsyscfg");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -r lpar --id %d", dom->id);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1492
        virReportOOMError();
E
Eduardo Otubo 已提交
1493
        return -1;
1494
    }
E
Eduardo Otubo 已提交
1495
    cmd = virBufferContentAndReset(&buf);
1496

1497
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517

    if (exit_status < 0)
        goto err;

    if (phypUUIDTable_RemLpar(dom->conn, dom->id) == -1)
        goto err;

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return -1;

}

static virDomainPtr
phypDomainCreateAndStart(virConnectPtr conn,
E
Eduardo Otubo 已提交
1518
                         const char *xml, unsigned int flags)
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
{

    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    virDomainDefPtr def = NULL;
    virDomainPtr dom = NULL;
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    lparPtr *lpars = uuid_table->lpars;
    unsigned int i = 0;
    char *managed_system = phyp_driver->managed_system;

1531 1532
    virCheckFlags(0, NULL);

1533
    if (!(def = virDomainDefParseString(phyp_driver->caps, xml,
1534 1535 1536 1537 1538
                                        VIR_DOMAIN_XML_SECURE)))
        goto err;

    /* checking if this name already exists on this system */
    if (phypGetLparID(session, managed_system, def->name, conn) == -1) {
1539
        VIR_WARN0("LPAR name already exists.");
1540 1541 1542 1543 1544 1545
        goto err;
    }

    /* checking if ID or UUID already exists on this system */
    for (i = 0; i < uuid_table->nlpars; i++) {
        if (lpars[i]->id == def->id || lpars[i]->uuid == def->uuid) {
1546
            VIR_WARN0("LPAR ID or UUID already exists.");
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
            goto err;
        }
    }

    if ((dom = virGetDomain(conn, def->name, def->uuid)) == NULL)
        goto err;

    if (phypBuildLpar(conn, def) == -1)
        goto err;

    if (phypDomainResume(dom) == -1)
        goto err;

    return dom;

  err:
    virDomainDefFree(def);
1564 1565
    if (dom)
        virUnrefDomain(dom);
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
    return NULL;
}

static char *
phypConnectGetCapabilities(virConnectPtr conn)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    char *xml;

    if ((xml = virCapabilitiesFormatXML(phyp_driver->caps)) == NULL)
1576
        virReportOOMError();
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630

    return xml;
}

virCapsPtr
phypCapsInit(void)
{
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

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

    /* Some machines have problematic NUMA toplogy causing
     * unexpected failures. We don't want to break the QEMU
     * driver in this scenario, so log errors & carry on
     */
    if (nodeCapsInitNUMA(caps) < 0) {
        virCapabilitiesFreeNUMAInfo(caps);
        VIR_WARN0
            ("Failed to query host NUMA topology, disabling NUMA capabilities");
    }

    /* XXX shouldn't 'borrow' KVM's prefix */
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]) {
                                0x52, 0x54, 0x00});

    if ((guest = virCapabilitiesAddGuest(caps,
                                         "linux",
                                         utsname.machine,
                                         sizeof(int) == 4 ? 32 : 8,
                                         NULL, NULL, 0, NULL)) == NULL)
        goto no_memory;

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

    return caps;

  no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}

static int
phypDomainSetCPU(virDomainPtr dom, unsigned int nvcpus)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1631
    int system_type = phyp_driver->system_type;
1632 1633
    char *managed_system = phyp_driver->managed_system;
    int exit_status = 0;
1634 1635
    char *cmd = NULL;
    char *ret = NULL;
1636 1637 1638
    char operation;
    unsigned long ncpus = 0;
    unsigned int amount = 0;
E
Eduardo Otubo 已提交
1639
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1640 1641

    if ((ncpus = phypGetLparCPU(dom->conn, managed_system, dom->id)) == 0)
E
Eduardo Otubo 已提交
1642
        return 0;
1643 1644

    if (nvcpus > phypGetLparCPUMAX(dom)) {
1645
        VIR_ERROR0(_("You are trying to set a number of CPUs bigger than "
E
Eduardo Otubo 已提交
1646 1647
                     "the max possible."));
        return 0;
1648 1649 1650 1651 1652 1653 1654 1655 1656
    }

    if (ncpus > nvcpus) {
        operation = 'r';
        amount = nvcpus - ncpus;
    } else if (ncpus < nvcpus) {
        operation = 'a';
        amount = nvcpus - ncpus;
    } else
E
Eduardo Otubo 已提交
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
        return 0;

    virBufferAddLit(&buf, "chhwres -r proc");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " --id %d -o %c --procunits %d 2>&1 |sed "
                      "-e 's/^.*\\([0-9][0-9]*.[0-9][0-9]*\\).*$/\\1/'",
                      dom->id, operation, amount);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1667
        virReportOOMError();
E
Eduardo Otubo 已提交
1668
        return 0;
1669
    }
E
Eduardo Otubo 已提交
1670
    cmd = virBufferContentAndReset(&buf);
1671

1672
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1673 1674

    if (exit_status < 0) {
E
Eduardo Otubo 已提交
1675 1676 1677
        VIR_ERROR0(_
                   ("Possibly you don't have IBM Tools installed in your LPAR."
                    " Contact your support to enable this feature."));
1678 1679 1680 1681 1682 1683 1684 1685 1686
    }

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

}

virDriver phypDriver = {
E
Eduardo Otubo 已提交
1687
    VIR_DRV_PHYP, "PHYP", phypOpen,     /* open */
1688 1689 1690 1691
    phypClose,                  /* close */
    NULL,                       /* supports_feature */
    NULL,                       /* type */
    NULL,                       /* version */
1692
    NULL,                       /* libvirtVersion (impl. in libvirt.c) */
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    NULL,                       /* getHostname */
    NULL,                       /* getMaxVcpus */
    NULL,                       /* nodeGetInfo */
    phypConnectGetCapabilities, /* getCapabilities */
    phypListDomains,            /* listDomains */
    phypNumDomains,             /* numOfDomains */
    phypDomainCreateAndStart,   /* domainCreateXML */
    phypDomainLookupByID,       /* domainLookupByID */
    NULL,                       /* domainLookupByUUID */
    phypDomainLookupByName,     /* domainLookupByName */
    NULL,                       /* domainSuspend */
    phypDomainResume,           /* domainResume */
    phypDomainShutdown,         /* domainShutdown */
    NULL,                       /* domainReboot */
    phypDomainDestroy,          /* domainDestroy */
    NULL,                       /* domainGetOSType */
    NULL,                       /* domainGetMaxMemory */
    NULL,                       /* domainSetMaxMemory */
    NULL,                       /* domainSetMemory */
1712 1713 1714 1715
    phypDomainGetInfo,          /* domainGetInfo */
    NULL,                       /* domainSave */
    NULL,                       /* domainRestore */
    NULL,                       /* domainCoreDump */
1716
    phypDomainSetCPU,           /* domainSetVcpus */
1717 1718
    NULL,                       /* domainPinVcpu */
    NULL,                       /* domainGetVcpus */
1719
    phypGetLparCPUMAX,          /* domainGetMaxVcpus */
1720 1721 1722
    NULL,                       /* domainGetSecurityLabel */
    NULL,                       /* nodeGetSecurityModel */
    phypDomainDumpXML,          /* domainDumpXML */
1723 1724
    NULL,                       /* domainXMLFromNative */
    NULL,                       /* domainXMLToNative */
1725 1726 1727
    phypListDefinedDomains,     /* listDefinedDomains */
    phypNumDefinedDomains,      /* numOfDefinedDomains */
    NULL,                       /* domainCreate */
1728
    NULL,                       /* domainCreateWithFlags */
1729 1730 1731
    NULL,                       /* domainDefineXML */
    NULL,                       /* domainUndefine */
    NULL,                       /* domainAttachDevice */
1732
    NULL,                       /* domainAttachDeviceFlags */
1733
    NULL,                       /* domainDetachDevice */
1734
    NULL,                       /* domainDetachDeviceFlags */
1735
    NULL,                       /* domainUpdateDeviceFlags */
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
    NULL,                       /* domainGetAutostart */
    NULL,                       /* domainSetAutostart */
    NULL,                       /* domainGetSchedulerType */
    NULL,                       /* domainGetSchedulerParameters */
    NULL,                       /* domainSetSchedulerParameters */
    NULL,                       /* domainMigratePrepare */
    NULL,                       /* domainMigratePerform */
    NULL,                       /* domainMigrateFinish */
    NULL,                       /* domainBlockStats */
    NULL,                       /* domainInterfaceStats */
1746
    NULL,                       /* domainMemoryStats */
1747 1748
    NULL,                       /* domainBlockPeek */
    NULL,                       /* domainMemoryPeek */
1749
    NULL,                       /* domainGetBlockInfo */
1750 1751 1752 1753 1754 1755 1756 1757 1758
    NULL,                       /* nodeGetCellsFreeMemory */
    NULL,                       /* getFreeMemory */
    NULL,                       /* domainEventRegister */
    NULL,                       /* domainEventDeregister */
    NULL,                       /* domainMigratePrepare2 */
    NULL,                       /* domainMigrateFinish2 */
    NULL,                       /* nodeDeviceDettach */
    NULL,                       /* nodeDeviceReAttach */
    NULL,                       /* nodeDeviceReset */
C
Chris Lalancette 已提交
1759
    NULL,                       /* domainMigratePrepareTunnel */
1760 1761
    phypIsEncrypted,            /* isEncrypted */
    phypIsSecure,               /* isSecure */
1762 1763
    NULL,                       /* domainIsActive */
    NULL,                       /* domainIsPersistent */
J
Jiri Denemark 已提交
1764
    NULL,                       /* cpuCompare */
1765
    NULL,                       /* cpuBaseline */
E
Eduardo Otubo 已提交
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
    NULL,                       /* domainGetJobInfo */
    NULL,                       /* domainAbortJob */
    NULL,                       /* domainMigrateSetMaxDowntime */
    NULL,                       /* domainEventRegisterAny */
    NULL,                       /* domainEventDeregisterAny */
    NULL,                       /* domainManagedSave */
    NULL,                       /* domainHasManagedSaveImage */
    NULL,                       /* domainManagedSaveRemove */
    NULL,                       /* domainSnapshotCreateXML */
    NULL,                       /* domainSnapshotDumpXML */
    NULL,                       /* domainSnapshotNum */
    NULL,                       /* domainSnapshotListNames */
    NULL,                       /* domainSnapshotLookupByName */
    NULL,                       /* domainHasCurrentSnapshot */
    NULL,                       /* domainSnapshotCurrent */
    NULL,                       /* domainRevertToSnapshot */
    NULL,                       /* domainSnapshotDelete */
1783 1784 1785
};

int
1786
phypBuildLpar(virConnectPtr conn, virDomainDefPtr def)
1787
{
1788 1789 1790
    ConnectionData *connection_data = conn->networkPrivateData;
    phyp_driverPtr phyp_driver = conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
E
Eduardo Otubo 已提交
1791
    int system_type = phyp_driver->system_type;
1792
    char *managed_system = phyp_driver->managed_system;
1793 1794
    char *cmd = NULL;
    char *ret = NULL;
1795
    int exit_status = 0;
E
Eduardo Otubo 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virBufferAddLit(&buf, "mksyscfg");
    if (system_type == HMC)
        virBufferVSprintf(&buf, " -m %s", managed_system);
    virBufferVSprintf(&buf, " -r lpar -p %s -i min_mem=%d,desired_mem=%d,"
                      "max_mem=%d,desired_procs=%d,virtual_scsi_adapters=%s",
                      def->name, (int) def->memory, (int) def->memory,
                      (int) def->maxmem, (int) def->vcpus, def->disks[0]->src);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
1807
        virReportOOMError();
E
Eduardo Otubo 已提交
1808
        return -1;
1809
    }
E
Eduardo Otubo 已提交
1810
    cmd = virBufferContentAndReset(&buf);
1811

1812
    ret = phypExec(session, cmd, &exit_status, conn);
1813 1814

    if (exit_status < 0) {
1815
        VIR_ERROR(_("Unable to create LPAR. Reason: '%s'"), ret);
1816 1817 1818 1819
        goto err;
    }

    if (phypUUIDTable_AddLpar(conn, def->uuid, def->id) == -1) {
1820
        VIR_ERROR0(_("Unable to add LPAR to the table"));
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
        goto err;
    }

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return -1;
}

int
phypUUIDTable_RemLpar(virConnectPtr conn, int id)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    unsigned int i = 0;

    for (i = 0; i <= uuid_table->nlpars; i++) {
        if (uuid_table->lpars[i]->id == id) {
            uuid_table->lpars[i]->id = -1;
1844
            memset(uuid_table->lpars[i]->uuid, 0, VIR_UUID_BUFLEN);
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
        }
    }

    if (phypUUIDTable_WriteFile(conn) == -1)
        goto err;

    if (phypUUIDTable_Push(conn) == -1)
        goto err;

    return 0;

  err:
    return -1;
}

int
phypUUIDTable_AddLpar(virConnectPtr conn, unsigned char *uuid, int id)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;

    uuid_table->nlpars++;
    unsigned int i = uuid_table->nlpars;
    i--;

    if (VIR_REALLOC_N(uuid_table->lpars, uuid_table->nlpars) < 0) {
1871
        virReportOOMError();
1872 1873 1874 1875
        goto err;
    }

    if (VIR_ALLOC(uuid_table->lpars[i]) < 0) {
1876
        virReportOOMError();
1877 1878 1879 1880
        goto err;
    }

    uuid_table->lpars[i]->id = id;
1881
    memmove(uuid_table->lpars[i]->uuid, uuid, VIR_UUID_BUFLEN);
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903

    if (phypUUIDTable_WriteFile(conn) == -1)
        goto err;

    if (phypUUIDTable_Push(conn) == -1)
        goto err;

    return 0;

  err:
    return -1;
}

int
phypUUIDTable_ReadFile(virConnectPtr conn)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    unsigned int i = 0;
    int fd = -1;
    char local_file[] = "./uuid_table";
    int rc = 0;
1904
    int id;
1905 1906

    if ((fd = open(local_file, O_RDONLY)) == -1) {
1907
        VIR_WARN0("Unable to write information to local file.");
1908 1909 1910 1911 1912 1913 1914
        goto err;
    }

    /* Creating a new data base and writing to local file */
    if (VIR_ALLOC_N(uuid_table->lpars, uuid_table->nlpars) >= 0) {
        for (i = 0; i < uuid_table->nlpars; i++) {

1915
            rc = read(fd, &id, sizeof(int));
1916
            if (rc == sizeof(int)) {
1917
                if (VIR_ALLOC(uuid_table->lpars[i]) < 0) {
1918
                    virReportOOMError();
1919 1920
                    goto err;
                }
1921
                uuid_table->lpars[i]->id = id;
1922
            } else {
E
Eduardo Otubo 已提交
1923 1924
                VIR_WARN0
                    ("Unable to read from information to local file.");
1925 1926 1927 1928 1929
                goto err;
            }

            rc = read(fd, uuid_table->lpars[i]->uuid, VIR_UUID_BUFLEN);
            if (rc != VIR_UUID_BUFLEN) {
1930
                VIR_WARN0("Unable to read information to local file.");
1931 1932 1933
                goto err;
            }
        }
1934
    } else
1935
        virReportOOMError();
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958

    close(fd);
    return 0;

  err:
    close(fd);
    return -1;
}

int
phypUUIDTable_WriteFile(virConnectPtr conn)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    unsigned int i = 0;
    int fd = -1;
    char local_file[] = "./uuid_table";

    if ((fd = creat(local_file, 0755)) == -1)
        goto err;

    for (i = 0; i < uuid_table->nlpars; i++) {
        if (safewrite(fd, &uuid_table->lpars[i]->id,
1959
                      sizeof(uuid_table->lpars[i]->id)) !=
1960
            sizeof(uuid_table->lpars[i]->id)) {
1961
            VIR_ERROR0(_("Unable to write information to local file."));
1962 1963 1964 1965 1966
            goto err;
        }

        if (safewrite(fd, uuid_table->lpars[i]->uuid, VIR_UUID_BUFLEN) !=
            VIR_UUID_BUFLEN) {
1967
            VIR_ERROR0(_("Unable to write information to local file."));
1968 1969 1970 1971 1972
            goto err;
        }
    }

    close(fd);
1973
    return 0;
1974 1975 1976 1977

  err:
    close(fd);
    return -1;
1978 1979
}

1980 1981
int
phypUUIDTable_Init(virConnectPtr conn)
1982
{
1983 1984
    uuid_tablePtr uuid_table;
    phyp_driverPtr phyp_driver;
1985 1986
    int nids_numdomains = 0;
    int nids_listdomains = 0;
1987 1988 1989
    int *ids = NULL;
    unsigned int i = 0;

1990
    if ((nids_numdomains = phypNumDomainsGeneric(conn, 2)) < 0)
1991
        goto err;
1992

1993
    if (VIR_ALLOC_N(ids, nids_numdomains) < 0) {
1994
        virReportOOMError();
1995 1996
        goto err;
    }
1997

1998 1999
    if ((nids_listdomains =
         phypListDomainsGeneric(conn, ids, nids_numdomains, 1)) < 0)
2000 2001
        goto err;

2002
    /* exit early if there are no domains */
2003 2004 2005 2006 2007
    if (nids_numdomains == 0 && nids_listdomains == 0)
        goto exit;
    else if (nids_numdomains != nids_listdomains) {
        VIR_ERROR0(_("Unable to determine number of domains."));
        goto err;
2008 2009
    }

2010 2011
    phyp_driver = conn->privateData;
    uuid_table = phyp_driver->uuid_table;
2012
    uuid_table->nlpars = nids_listdomains;
2013 2014 2015 2016 2017 2018 2019

    /* try to get the table from server */
    if (phypUUIDTable_Pull(conn) == -1) {
        /* file not found in the server, creating a new one */
        if (VIR_ALLOC_N(uuid_table->lpars, uuid_table->nlpars) >= 0) {
            for (i = 0; i < uuid_table->nlpars; i++) {
                if (VIR_ALLOC(uuid_table->lpars[i]) < 0) {
2020
                    virReportOOMError();
2021 2022 2023 2024 2025
                    goto err;
                }
                uuid_table->lpars[i]->id = ids[i];

                if (virUUIDGenerate(uuid_table->lpars[i]->uuid) < 0)
2026 2027
                    VIR_WARN("Unable to generate UUID for domain %d",
                             ids[i]);
2028
            }
2029
        } else {
2030
            virReportOOMError();
2031
            goto err;
2032
        }
2033 2034 2035 2036 2037 2038 2039 2040 2041

        if (phypUUIDTable_WriteFile(conn) == -1)
            goto err;

        if (phypUUIDTable_Push(conn) == -1)
            goto err;
    } else {
        if (phypUUIDTable_ReadFile(conn) == -1)
            goto err;
2042
        goto exit;
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    }

  exit:
    VIR_FREE(ids);
    return 0;

  err:
    VIR_FREE(ids);
    return -1;
}

2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
void
phypUUIDTable_Free(uuid_tablePtr uuid_table)
{
    int i;

    if (uuid_table == NULL)
        return;

    for (i = 0; i < uuid_table->nlpars; i++)
        VIR_FREE(uuid_table->lpars[i]);

    VIR_FREE(uuid_table->lpars);
    VIR_FREE(uuid_table);
}

2069 2070 2071 2072 2073 2074
int
phypUUIDTable_Push(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    LIBSSH2_CHANNEL *channel = NULL;
E
Eduardo Otubo 已提交
2075
    virBuffer username = VIR_BUFFER_INITIALIZER;
2076 2077 2078 2079 2080 2081 2082
    struct stat local_fileinfo;
    char buffer[1024];
    int rc = 0;
    FILE *fd;
    size_t nread, sent;
    char *ptr;
    char local_file[] = "./uuid_table";
E
Eduardo Otubo 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    char *remote_file = NULL;

    if (conn->uri->user != NULL) {
        virBufferVSprintf(&username, "%s", conn->uri->user);

        if (virBufferError(&username)) {
            virBufferFreeAndReset(&username);
            virReportOOMError();
            goto err;
        }
    }

    if (virAsprintf
        (&remote_file, "/home/%s/libvirt_uuid_table",
         virBufferContentAndReset(&username))
        < 0) {
        virReportOOMError();
        goto err;
    }
2102 2103 2104 2105 2106

    if (stat(local_file, &local_fileinfo) == -1) {
        VIR_WARN0("Unable to stat local file.");
        goto err;
    }
2107

2108 2109 2110 2111
    if (!(fd = fopen(local_file, "rb"))) {
        VIR_WARN0("Unable to open local file.");
        goto err;
    }
2112

2113 2114 2115 2116 2117
    do {
        channel =
            libssh2_scp_send(session, remote_file,
                             0x1FF & local_fileinfo.st_mode,
                             (unsigned long) local_fileinfo.st_size);
2118

2119 2120 2121 2122 2123 2124 2125 2126
        if ((!channel) && (libssh2_session_last_errno(session) !=
                           LIBSSH2_ERROR_EAGAIN))
            goto err;
    } while (!channel);

    do {
        nread = fread(buffer, 1, sizeof(buffer), fd);
        if (nread <= 0) {
2127 2128 2129 2130
            if (feof(fd)) {
                /* end of file */
                break;
            } else {
2131
                VIR_ERROR(_("Failed to read from %s"), local_file);
2132 2133
                goto err;
            }
2134
        }
2135 2136 2137 2138 2139 2140 2141 2142
        ptr = buffer;
        sent = 0;

        do {
            /* write the same data over and over, until error or completion */
            rc = libssh2_channel_write(channel, ptr, nread);
            if (LIBSSH2_ERROR_EAGAIN == rc) {   /* must loop around */
                continue;
2143
            } else if (rc > 0) {
2144 2145 2146
                /* rc indicates how many bytes were written this time */
                sent += rc;
            }
2147 2148
            ptr += sent;
            nread -= sent;
2149 2150 2151 2152 2153 2154 2155 2156 2157
        } while (rc > 0 && sent < nread);
    } while (1);

    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
2158
    }
E
Eduardo Otubo 已提交
2159
    virBufferFreeAndReset(&username);
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
    return 0;

  err:
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
    }
    return -1;
}

int
phypUUIDTable_Pull(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    LIBSSH2_CHANNEL *channel = NULL;
E
Eduardo Otubo 已提交
2179
    virBuffer username = VIR_BUFFER_INITIALIZER;
2180 2181 2182 2183 2184 2185 2186 2187 2188
    struct stat fileinfo;
    char buffer[1024];
    int rc = 0;
    int fd;
    int got = 0;
    int amount = 0;
    int total = 0;
    int sock = 0;
    char local_file[] = "./uuid_table";
E
Eduardo Otubo 已提交
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    char *remote_file = NULL;

    if (conn->uri->user != NULL) {
        virBufferVSprintf(&username, "%s", conn->uri->user);

        if (virBufferError(&username)) {
            virBufferFreeAndReset(&username);
            virReportOOMError();
            goto err;
        }
    }

    if (virAsprintf
        (&remote_file, "/home/%s/libvirt_uuid_table",
         virBufferContentAndReset(&username))
        < 0) {
        virReportOOMError();
        goto err;
    }
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238

    /* Trying to stat the remote file. */
    do {
        channel = libssh2_scp_recv(session, remote_file, &fileinfo);

        if (!channel) {
            if (libssh2_session_last_errno(session) !=
                LIBSSH2_ERROR_EAGAIN) {
                goto err;;
            } else {
                waitsocket(sock, session);
            }
        }
    } while (!channel);

    /* Creating a new data base based on remote file */
    if ((fd = creat(local_file, 0755)) == -1)
        goto err;

    /* Request a file via SCP */
    while (got < fileinfo.st_size) {
        do {
            amount = sizeof(buffer);

            if ((fileinfo.st_size - got) < amount) {
                amount = fileinfo.st_size - got;
            }

            rc = libssh2_channel_read(channel, buffer, amount);
            if (rc > 0) {
                if (safewrite(fd, buffer, rc) != rc)
E
Eduardo Otubo 已提交
2239 2240
                    VIR_WARN0
                        ("Unable to write information to local file.");
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259

                got += rc;
                total += rc;
            }
        } while (rc > 0);

        if ((rc == LIBSSH2_ERROR_EAGAIN)
            && (got < fileinfo.st_size)) {
            /* this is due to blocking that would occur otherwise
             * so we loop on this condition */

            waitsocket(sock, session);  /* now we wait */
            continue;
        }
        break;
    }
    close(fd);
    goto exit;

2260
  exit:
2261 2262 2263 2264 2265 2266 2267
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
    }
E
Eduardo Otubo 已提交
2268
    virBufferFreeAndReset(&username);
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
    return 0;

  err:
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
    }
    return -1;
2280 2281
}

2282
int
2283
escape_specialcharacters(char *src, char *dst, size_t dstlen)
2284 2285 2286 2287 2288 2289 2290 2291 2292
{
    size_t len = strlen(src);
    char temp_buffer[len];
    unsigned int i = 0, j = 0;
    if (len == 0)
        return -1;

    for (i = 0; i < len; i++) {
        switch (src[i]) {
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
            case '&':
            case ';':
            case '`':
            case '@':
            case '"':
            case '|':
            case '*':
            case '?':
            case '~':
            case '<':
            case '>':
            case '^':
            case '(':
            case ')':
            case '[':
            case ']':
            case '{':
            case '}':
            case '$':
            case '%':
            case '#':
            case '\\':
            case '\n':
            case '\r':
2317 2318 2319 2320 2321 2322 2323 2324 2325
            case '\t':
                continue;
            default:
                temp_buffer[j] = src[i];
                j++;
        }
    }
    temp_buffer[j] = '\0';

C
Chris Lalancette 已提交
2326
    if (virStrcpy(dst, temp_buffer, dstlen) == NULL)
2327 2328 2329 2330
        return -1;

    return 0;
}
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341

int
waitsocket(int socket_fd, LIBSSH2_SESSION * session)
{
    struct timeval timeout;
    int rc;
    fd_set fd;
    fd_set *writefd = NULL;
    fd_set *readfd = NULL;
    int dir;

2342 2343
    timeout.tv_sec = 0;
    timeout.tv_usec = 1000;
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361

    FD_ZERO(&fd);

    FD_SET(socket_fd, &fd);

    /* now make sure we wait in the correct direction */
    dir = libssh2_session_block_directions(session);

    if (dir & LIBSSH2_SESSION_BLOCK_INBOUND)
        readfd = &fd;

    if (dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
        writefd = &fd;

    rc = select(socket_fd + 1, readfd, writefd, NULL, &timeout);

    return rc;
}
2362 2363 2364 2365 2366 2367 2368

int
phypRegister(void)
{
    virRegisterDriver(&phypDriver);
    return 0;
}