XenServerConnectionPool.java 33.8 KB
1 2 3 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
package com.sitech.ismp.coll.host;

import java.net.SocketException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClientException;

import com.xen.api.APIVersion;
import com.xen.api.Connection;
import com.xen.api.Host;
import com.xen.api.Pool;
import com.xen.api.Session;
import com.xen.api.Types;
import com.xen.api.Types.BadServerResponse;
import com.xen.api.Types.UuidInvalid;
import com.xen.api.Types.XenAPIException;
import com.xen.exception.CloudRuntimeException;

public class XenServerConnectionPool {
    private static final Logger s_logger = Logger.getLogger(XenServerConnectionPool.class);
    protected HashMap<String /* poolUuid */, XenServerConnection> _conns = new HashMap<String, XenServerConnection>();
    protected int _retries;
    protected int _interval;
    protected static boolean s_managePool = true;
    protected static long s_sleepOnError = 10 * 1000; // in ms

    private static final int wait = 3600 * 30;

    protected XenServerConnectionPool() {
        _retries = 3;
        _interval = 3;
    }

    private void addConnect(String poolUuid, XenServerConnection conn) {
        if (poolUuid == null) return;
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Add master connection through " + conn.getIp() + " for pool(" + conn.getPoolUuid() + ")");
        }
        synchronized (_conns) {
            _conns.put(poolUuid, conn);
        }
    }

    protected XenServerConnection getConnect(String poolUuid) {
        if (poolUuid == null) return null;
        synchronized (_conns) {
            return _conns.get(poolUuid);
        }
    }

    private void removeConnect(String poolUuid) {
        if (poolUuid == null) {
            return;
        }
        XenServerConnection conn = null;
        synchronized (_conns) {
            conn = _conns.remove(poolUuid);
        }
        if (conn != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Remove master connection through " + conn.getIp() + " for pool(" + conn.getPoolUuid() + ")");
            }

        }
    }

    static void forceSleep(long sec) {
        long firetime = System.currentTimeMillis() + (sec * 1000);
        long msec = sec * 1000;
        while (true) {
            if (msec < 100)
                break;
            try {
                Thread.sleep(msec);
                return;
            } catch (InterruptedException e) {
                msec = firetime - System.currentTimeMillis();
            }
        }
    }


    private void localLogout(Connection conn) {
        if (conn == null)
            return;
        try {
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("Logging out of the session "
                        + conn.getSessionReference());
            }
            Session.localLogout(conn);
        } catch (Exception e) {
            s_logger.debug("localLogout has problem " + e.getMessage());
        } finally {
            conn.dispose();
            conn = null;
        }
    }

    public Connection slaveConnect(String ip, String username, Queue<String> password) {
        Connection conn = null;
        try {
            conn = new Connection(getURL(ip), 10);
            slaveLocalLoginWithPassword(conn, username, password);
            return conn;
        } catch (Exception e) {
            s_logger.debug("Failed to slave local login to " + ip);
        }
        return null;
    }

    public Connection masterConnect(String ip, String username, Queue<String> password) {
        Connection conn = null;
        try {
            conn = new Connection(getURL(ip), 10);
            s_logger.debug("Logging on as the master to " + ip);
            loginWithPassword(conn, username, password, APIVersion.latest().toString());
            return conn;
        } catch (Exception e) {
            s_logger.debug("Failed to slave local login to " + ip);
        }
        throw new RuntimeException("can not log in to master " + ip);
    }


    public String getMasterIp(String ip, String username, Queue<String> password) throws XenAPIException {
        Connection slaveConn = null;
        try {
            slaveConn = new Connection(getURL(ip), 10);
            slaveLocalLoginWithPassword(slaveConn, username, password);

            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Slave logon to " + ip);
            }
            String masterIp = null;
            Pool.Record pr = getPoolRecord(slaveConn);
            Host master = pr.master;
            masterIp = master.getAddress(slaveConn);
            return masterIp;
        } catch (Types.SessionAuthenticationFailed e) {
            s_logger.debug("Failed to slave local login to " + ip + " due to " + e.toString());
            throw e;
        } catch (Exception e) {
            s_logger.debug("Failed to slave local login to " + ip + " due to " + e.toString());
        } finally {
            localLogout(slaveConn);
            slaveConn = null;
        }
        throw new RuntimeException("can not get master ip");
    }


    void PoolEmergencyTransitionToMaster(String slaveIp, String username, Queue<String> password) {
        if (!s_managePool) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Don't manage pool on error so sleeping for " + s_sleepOnError);
                try {
                    Thread.sleep(s_sleepOnError);
                } catch (InterruptedException ie) {
                }
            }
            return;
        }

        Connection slaveConn = null;
        Connection c = null;
        try {
            s_logger.debug("Trying to transition master to " + slaveIp);
            slaveConn = new Connection(getURL(slaveIp), 10);
            slaveLocalLoginWithPassword(slaveConn, username, password);
            Pool.emergencyTransitionToMaster(slaveConn);
            // restart xapi in 10 sec
            forceSleep(10);
            // check if the master of this host is set correctly.
            c = new Connection(getURL(slaveIp), 10);
            for (int i = 0; i < 30; i++) {
                try {
                    loginWithPassword(c, username, password, APIVersion.latest().toString());
                    s_logger.debug("Succeeded to transition master to " + slaveIp);
                    return;
                } catch (Types.HostIsSlave e) {
                    s_logger.debug("HostIsSlave: Still waiting for the conversion to the master " + slaveIp);
                } catch (Exception e) {
                    s_logger.debug("Exception: Still waiting for the conversion to the master");
                }
                forceSleep(2);
            }
            throw new RuntimeException("EmergencyTransitionToMaster failed after retry 30 times");
        } catch (Exception e) {
            throw new RuntimeException("EmergencyTransitionToMaster failed due to " + e.getMessage());
        } finally {
            localLogout(slaveConn);
            slaveConn = null;
            if (c != null) {
                try {
                    Session.logout(c);
                    c.dispose();
                } catch (Exception e) {
                }
            }
        }

    }

    private void PoolEmergencyResetMaster(String slaveIp, String masterIp, String username, Queue<String> password) {
        if (!s_managePool) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Don't manage pool on error so sleeping for " + s_sleepOnError);
                try {
                    Thread.sleep(s_sleepOnError);
                } catch (InterruptedException ie) {
                }
            }
            return;
        }

        Connection slaveConn = null;
        try {
            s_logger.debug("Trying to reset master of slave " + slaveIp
                    + " to " + masterIp);
            slaveConn = new Connection(getURL(slaveIp), 10);
            slaveLocalLoginWithPassword(slaveConn, username, password);
            Pool.emergencyResetMaster(slaveConn, masterIp);
            forceSleep(10);
            for (int i = 0; i < 30; i++) {
                try {
                    slaveLocalLoginWithPassword(slaveConn, username, password);
                    Pool.Record pr = getPoolRecord(slaveConn);
                    String mIp = pr.master.getAddress(slaveConn);
                    if (mIp.trim().equals(masterIp.trim())) {
                        s_logger.debug("Succeeded to reset master of slave " + slaveIp + " to " + masterIp);
                        return;
                    }
                } catch (Exception e) {
                } finally {
                    localLogout(slaveConn);
                    slaveConn = null;
                }
                // wait 2 second
                forceSleep(2);
            }
            throw new CloudRuntimeException("Unable to reset master of slave " + slaveIp
                    + " to " + masterIp + "after 30 retry");
        } catch (Exception e) {
            throw new CloudRuntimeException("Unable to reset master of slave " + slaveIp
                    + " to " + masterIp + " due to " + e.toString());
        } finally {
            localLogout(slaveConn);
            slaveConn = null;
        }
    }

    protected void ensurePoolIntegrity(Connection conn,
                                       String masterIp, String username, Queue<String> password, int wait) {
        try {
            // try recoverSlave first
            Set<Host> rcSlaves = Pool.recoverSlaves(conn);
            // wait 10 second
            forceSleep(10);
            for (Host slave : rcSlaves) {
                for (int i = 0; i < 30; i++) {
                    Connection slaveConn = null;
                    try {

                        String slaveIp = slave.getAddress(conn);
                        s_logger.debug("Logging on as the slave to " + slaveIp);
                        slaveConn = new Connection(getURL(slaveIp), 10);
                        slaveLocalLoginWithPassword(slaveConn, username, password);
                        Pool.Record pr = getPoolRecord(slaveConn);
                        String mIp = pr.master.getAddress(slaveConn);
                        if (mIp.trim().equals(masterIp.trim())) {
                            break;
                        }
                    } catch (Exception e) {
                    } finally {
                        localLogout(slaveConn);
                        slaveConn = null;
                    }
                    // wait 2 second
                    forceSleep(2);
                }
            }
            // then try emergency reset master
            Set<Host> slaves = Host.getAll(conn);
            for (Host slave : slaves) {
                String slaveIp = slave.getAddress(conn);
                Connection slaveConn = null;
                try {
                    s_logger.debug("Logging on as the slave to " + slaveIp);

                    slaveConn = new Connection(getURL(slaveIp), 10);
                    slaveLocalLoginWithPassword(slaveConn, username, password);
                    Pool.Record slavePoolr = getPoolRecord(slaveConn);
                    String ip = slavePoolr.master.getAddress(slaveConn);
                    if (!masterIp.trim().equals(ip.trim())) {
                        PoolEmergencyResetMaster(slaveIp, masterIp, username, password);
                    }
                } catch (Exception e) {
                    s_logger.debug("Unable to login to slave " + slaveIp + " error " + e.getMessage());
                } finally {
                    localLogout(slaveConn);
                    slaveConn = null;
                }
            }
        } catch (Exception e) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Catch " + e.getClass().getName() + " due to " + e.toString());
            }
        }
    }

    public URL getURL(String ip) {
        try {
            return new URL("http://" + ip);
        } catch (Exception e) {
            String msg = "Unable to convert IP " + ip + " to URL due to " + e.toString();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(msg);
            }
            throw new CloudRuntimeException(msg, e);
        }
    }

    /**
     * 验证操作的host主机是否在指定的链接下
     * <p>Title: connect</p>
     *
     * @return Connection
     * @throws
     * @author: shijincheng;
     */
    public void checkHostBymConn(XenServerConnection mConn, String hostUuid) {
        if (mConn != null && hostUuid != null && !hostUuid.equals("")) {
            try {
                Host.getByUuid(mConn, hostUuid);
            } catch (Types.SessionInvalid e) {
                s_logger.debug("Session thgrough ip " + mConn.getIp() + " is invalid for pool(" + mConn.getPoolUuid() + ") due to " + e.toString());
                try {
                    loginWithPassword(mConn, mConn.getUsername(), mConn.getPassword(), APIVersion.latest().toString());
                } catch (Exception e1) {
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("connect through IP(" + mConn.getIp() + " for pool(" + mConn.getPoolUuid() + ") is broken due to " + e.toString());
                    }
                    removeConnect(mConn.getPoolUuid());
                    mConn = null;
                }
            } catch (UuidInvalid e) {
                String msg = "Host(" + hostUuid + ") doesn't belong to pool(" + mConn.getPoolUuid() + "), please execute 'xe pool-join master-address=" + mConn.getIp()
                        + " master-username=" + mConn.getUsername() + " master-password=" + mConn.getPassword();
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug(msg);
                }
                throw new CloudRuntimeException(msg, e);
            } catch (Exception e) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("connect through IP(" + mConn.getIp() + " for pool(" + mConn.getPoolUuid() + ") is broken due to " + e.toString());
                }
                removeConnect(mConn.getPoolUuid());
                mConn = null;
            }
        }
    }


    /**
     * 验证链接的可用性,初始化链接
     * <p>Title: connect</p>
     *
     * @return Connection
     * @throws
     * @author: shijincheng;
     */
    public Connection connect(String poolUuid, String hostUuid, String ipAddress, String username, Queue<String> password) {
        XenServerConnection mConn = null;
        Connection sConn = null;
        String masterIp = null;
        if (poolUuid == null || ipAddress == null || username == null || password == null) {
            String msg = "Connect some parameter are null  ,poolUuid:" + poolUuid
                    + " ,ipAddress:" + ipAddress;
            s_logger.debug(msg);
            throw new CloudRuntimeException(msg);
        }
        synchronized (poolUuid.intern()) {
            // Let's see if it is an existing connection.
            mConn = getConnect(poolUuid);
            if (mConn == null) {
                try {
                    try {
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Logging on as the slave to " + ipAddress);
                        }
                        sConn = new Connection(getURL(ipAddress), 5);
                        slaveLocalLoginWithPassword(sConn, username, password);
                    } catch (Exception e) {
                        String msg = "Unable to create slave connection to host() due to " + e.toString();
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug(msg);
                        }
                        throw new CloudRuntimeException(msg, e);
                    }
                    Pool.Record pr = null;
                    try {
                        pr = getPoolRecord(sConn);
                    } catch (Exception e) {
                        PoolEmergencyTransitionToMaster(ipAddress, username, password);
                        mConn = new XenServerConnection(getURL(ipAddress), ipAddress, username, password, _retries, _interval, wait);
                        try {
                            loginWithPassword(mConn, username, password, APIVersion.latest().toString());
                            pr = getPoolRecord(mConn);
                        } catch (Exception e1) {
                            String msg = "Unable to create master connection to host() after transition it to master, due to " + e1.toString();
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug(msg);
                            }
                            throw new CloudRuntimeException(msg, e1);
                        }
                        if (!pr.uuid.equals(poolUuid)) {
                            String msg = "host() should be in pool(" + poolUuid + "), but it is actually in pool(" + pr.uuid + ")";
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug(msg);
                            }
                            throw new CloudRuntimeException(msg);
                        } else {
                            if (s_managePool) {
                                ensurePoolIntegrity(mConn, ipAddress, username, password, wait);
                            }
                            addConnect(poolUuid, mConn);
                            return mConn;
                        }
                    }
                    if (!poolUuid.equals("") && !pr.uuid.equals(poolUuid)) {
                        String msg = "host() should be in pool(" + poolUuid + "), but it is actually in pool(" + pr.uuid + ")";
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug(msg);
                        }
                        throw new CloudRuntimeException(msg);
                    }
                    try {
                        masterIp = pr.master.getAddress(sConn);
                        mConn = new XenServerConnection(getURL(masterIp), masterIp, username, password, _retries, _interval, wait);
                        loginWithPassword(mConn, username, password, APIVersion.latest().toString());
                        addConnect(poolUuid, mConn);
                        //链接可用,检查操作主机是否 是此链接内的主机
                        checkHostBymConn(mConn, hostUuid);
                        return mConn;
                    } catch (Exception e) {
                        String msg = "Unable to logon in " + masterIp + " as master in pool(" + poolUuid + ")";
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug(msg);
                        }
                        throw new CloudRuntimeException(msg);
                    }
                } finally {
                    localLogout(sConn);
                    sConn = null;
                }
            }
        }

        return mConn;
    }

    /**
     * 初始化链接
     * <p>Title: connect</p>
     *
     * @return Connection
     * @throws
     * @author: shijincheng;
     */
    public Connection connect(String ipAddress, String username, Queue<String> password) {
        XenServerConnection mConn = null;
        Connection sConn = null;
        String masterIp = null;
        if (ipAddress == null || username == null || password == null) {
            String msg = "Connect some parameter are null  ," + " ,ipAddress:"
                    + ipAddress;
            s_logger.debug(msg);
            throw new CloudRuntimeException(msg);
        }
        try {
            try {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Logging on as the slave to " + ipAddress);
                }
                sConn = new Connection(getURL(ipAddress), 5);
                slaveLocalLoginWithPassword(sConn, username, password);
            } catch (Exception e) {
                e.printStackTrace();
                String msg = "Unable to create slave connection to host() due to "
                        + e.toString();
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug(msg);
                }
                throw new CloudRuntimeException(msg, e);
            }
            Pool.Record pr = null;
            try {
                pr = getPoolRecord(sConn);
            } catch (Exception e) {
                PoolEmergencyTransitionToMaster(ipAddress, username, password);
                mConn = new XenServerConnection(getURL(ipAddress), ipAddress,
                        username, password, _retries, _interval, wait);
                try {
                    loginWithPassword(mConn, username, password, APIVersion
                            .latest().toString());
                    pr = getPoolRecord(mConn);
                } catch (Exception e1) {
                    String msg = "Unable to create master connection to host() after transition it to master, due to "
                            + e1.toString();
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug(msg);
                    }
                    throw new CloudRuntimeException(msg, e1);
                }
            }
            try {
                masterIp = pr.master.getAddress(sConn);
                mConn = new XenServerConnection(getURL(masterIp), masterIp,
                        username, password, _retries, _interval, wait);
                loginWithPassword(mConn, username, password, APIVersion
                        .latest().toString());
                addConnect(pr.uuid, mConn);
            } catch (Exception e) {
                String msg = "Unable to logon in " + masterIp
                        + " as master in pool(" + pr.uuid + ")";
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug(msg);
                }
                throw new CloudRuntimeException(msg);
            }
        } finally {
            localLogout(sConn);
            sConn = null;
        }
        return mConn;
    }

    /**
     * Authenticate locally against a slave in emergency mode. Note the resulting sessions are only good
     * for use on this host.
     * <p>Title: slaveLocalLoginWithPassword</p>
     *
     * @return Session
     * @throws
     * @author: shijincheng;
     */
    protected Session slaveLocalLoginWithPassword(Connection conn, String username, Queue<String> password) throws
            BadServerResponse,
            XenAPIException,
            XmlRpcException {
        Session s = null;
        boolean logged_in = false;
        Exception ex = null;
        while (!logged_in) {
            try {
                s = Session.slaveLocalLoginWithPassword(conn, username, password.peek());
                logged_in = true;
            } catch (BadServerResponse e) {
                logged_in = false;
                ex = e;
            } catch (XenAPIException e) {
                logged_in = false;
                ex = e;
            } catch (XmlRpcException e) {
                logged_in = false;
                ex = e;
            }
            if (logged_in && conn != null) {
                break;
            } else {
                if (password.size() > 1) {
                    password.remove();
                    continue;
                } else {
                    // the last password did not work leave it and flag error
                    if (ex instanceof BadServerResponse) {
                        throw (BadServerResponse) ex;
                    } else if (ex instanceof XmlRpcException) {
                        throw (XmlRpcException) ex;
                    } else if (ex instanceof Types.SessionAuthenticationFailed) {
                        throw (Types.SessionAuthenticationFailed) ex;
                    } else if (ex instanceof XenAPIException) {
                        throw (XenAPIException) ex;
                    }
                    break;
                }
            }
        }
        return s;
    }


    public Session loginWithPassword(Connection conn, String username, Queue<String> password, String version) throws
            BadServerResponse,
            XenAPIException,
            XmlRpcException {
        Session s = null;
        boolean logged_in = false;
        Exception ex = null;
        while (!logged_in) {
            try {
                s = Session.loginWithPassword(conn, username, password.peek(), APIVersion.latest().toString());
                logged_in = true;
            } catch (BadServerResponse e) {
                logged_in = false;
                ex = e;
            } catch (XenAPIException e) {
                logged_in = false;
                ex = e;
            } catch (XmlRpcException e) {
                logged_in = false;
                ex = e;
            }

            if (logged_in && conn != null) {
                break;
            } else {
                if (password.size() > 1) {
                    password.remove();
                    continue;
                } else {
                    // the last password did not work leave it and flag error
                    if (ex instanceof BadServerResponse) {
                        throw (BadServerResponse) ex;
                    } else if (ex instanceof XmlRpcException) {
                        throw (XmlRpcException) ex;
                    } else if (ex instanceof Types.SessionAuthenticationFailed) {
                        throw (Types.SessionAuthenticationFailed) ex;
                    } else if (ex instanceof XenAPIException) {
                        throw (XenAPIException) ex;
                    }
                }
            }
        }
        return s;
    }


    protected void join(Connection conn, String masterIp, String username, Queue<String> password) throws
            BadServerResponse,
            XenAPIException,
            XmlRpcException,
            Types.JoiningHostCannotContainSharedSrs {

        boolean logged_in = false;
        Exception ex = null;
        while (!logged_in) {
            try {
                Pool.join(conn, masterIp, username, password.peek());
                logged_in = true;
            } catch (BadServerResponse e) {
                logged_in = false;
                ex = e;
            } catch (XenAPIException e) {
                logged_in = false;
                ex = e;
            } catch (XmlRpcException e) {
                logged_in = false;
                ex = e;
            }
            if (logged_in && conn != null) {
                break;
            } else {
                if (password.size() > 1) {
                    password.remove();
                    continue;
                } else {
                    // the last password did not work leave it and flag error
                    if (ex instanceof BadServerResponse) {
                        throw (BadServerResponse) ex;
                    } else if (ex instanceof XmlRpcException) {
                        throw (XmlRpcException) ex;
                    } else if (ex instanceof Types.SessionAuthenticationFailed) {
                        throw (Types.SessionAuthenticationFailed) ex;
                    } else if (ex instanceof XenAPIException) {
                        throw (XenAPIException) ex;
                    }
                    break;
                }
            }
        }
    }

    static public Pool.Record getPoolRecord(Connection conn)
            throws XmlRpcException, XenAPIException {
        Map<Pool, Pool.Record> pools = Pool.getAllRecords(conn);
        assert pools.size() == 1 : "Pool size is not one....hmmm....wth? "
                + pools.size();

        return pools.values().iterator().next();
    }

    static public Pool getPool(Connection conn) throws XmlRpcException,
            XenAPIException {
        Set<Pool> pools = Pool.getAll(conn);
        assert pools.size() == 1 : "Pool size is not one....hmmm....wth? "
                + pools.size();

        return pools.iterator().next();
    }

    private static final XenServerConnectionPool s_instance = new XenServerConnectionPool();

    public static XenServerConnectionPool getInstance() {
        return s_instance;
    }


    public class XenServerConnection extends Connection {
        long _interval;
        int _retries;
        String _ip;
        String _username;
        Queue<String> _password;
        String _poolUuid;

        public XenServerConnection(URL url, String ip, String username, Queue<String> password,
                                   int retries, int interval, int wait) {
            super(url, wait);
            _ip = ip;
            _retries = retries;
            _username = username;
            _password = password;
            _interval = (long) interval * 1000;

        }

        public String getPoolUuid() {
            return _poolUuid;
        }

        public String getUsername() {
            return _username;
        }

        public Queue<String> getPassword() {
            return _password;
        }

        public String getIp() {
            return _ip;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected synchronized Map dispatch(String method_call, Object[] method_params) throws XmlRpcException, XenAPIException {
            if (method_call.equals("session.local_logout")
                    || method_call.equals("session.slave_local_login_with_password")
                    || method_call.equals("session.logout")) {
                return super.dispatch(method_call, method_params);
            }

            if (method_call.equals("session.login_with_password")) {
                int retries = 0;
                while (retries++ < _retries) {
                    try {
                        return super.dispatch(method_call, method_params);
                    } catch (XmlRpcException e) {
                        Throwable cause = e.getCause();
                        if (cause == null
                                || !(cause instanceof SocketException)) {
                            throw e;
                        }
                        if (retries >= _retries) {
                            throw e;
                        }
                        s_logger.debug("Unable to login...retrying " + retries);
                    }
                    try {
                        Thread.sleep(_interval);
                    } catch (InterruptedException e) {
                        s_logger
                                .debug("Man....I was just getting comfortable there....who woke me up?");
                    }
                }
            } else {
                int retries = 0;
                while (retries++ < _retries) {
                    try {
                        return super.dispatch(method_call, method_params);
                    } catch (Types.SessionInvalid e) {
                        s_logger.debug("Session is invalid for method: " + method_call + " due to " + e.getMessage() + ".  Reconnecting...retry="
                                + retries);
                        if (retries >= _retries) {
                            removeConnect(_poolUuid);
                            throw e;
                        }
                        loginWithPassword(this, _username, _password, APIVersion.latest().toString());
                        method_params[0] = getSessionReference();
                    } catch (XmlRpcClientException e) {
                        s_logger.debug("XmlRpcClientException for method: " + method_call + " due to " + e.getMessage());
                        removeConnect(_poolUuid);
                        throw e;
                    } catch (XmlRpcException e) {
                        s_logger.debug("XmlRpcException for method: " + method_call + " due to " + e.getMessage() + ".  Reconnecting...retry="
                                + retries);
                        if (retries >= _retries) {
                            removeConnect(_poolUuid);
                            throw e;
                        }
                        Throwable cause = e.getCause();
                        if (cause == null || !(cause instanceof SocketException)) {
                            removeConnect(_poolUuid);
                            throw e;
                        }
                    } catch (Types.HostIsSlave e) {
                        s_logger.debug("HostIsSlave Exception for method: " + method_call + " due to " + e.getMessage() + ".  Reconnecting...retry="
                                + retries);
                        removeConnect(_poolUuid);
                        throw e;
                    }
                    try {
                        Thread.sleep(_interval);
                    } catch (InterruptedException e) {
                        s_logger.info("Who woke me from my slumber?");
                    }
                }
                assert false : "We should never get here";
                removeConnect(_poolUuid);
            }
            throw new CloudRuntimeException("After " + _retries
                    + " retries, we cannot contact the host ");
        }

    }

    public static class TrustAllManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

}