~fwereade/pyjuju/cobbler-zk-connect-error-messages

« back to all changes in this revision

Viewing changes to ensemble/providers/ec2/connect.py

  • Committer: William Reade
  • Date: 2011-08-15 09:29:20 UTC
  • mfrom: (314.1.3 spike-catchup)
  • Revision ID: fwereade@gmail.com-20110815092920-amun4ufsutm7d938
merge parent

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import datetime
 
2
from datetime import timedelta
 
3
 
 
4
from twisted.internet.defer import inlineCallbacks, returnValue
 
5
 
 
6
from ensemble.errors import EnvironmentPending, NoConnection
 
7
from ensemble.state.sshclient import SSHClient
 
8
 
 
9
from .utils import log
 
10
 
 
11
 
 
12
class EC2Connect(object):
 
13
 
 
14
    def __init__(self, provider):
 
15
        self._provider = provider
 
16
 
 
17
    def run(self, share=False):
 
18
        client_deferred = self._provider.get_zookeeper_machines()
 
19
        client_deferred.addCallback(self._connect_to_machine, share)
 
20
        client_deferred.addCallback(self._wait_for_initialization)
 
21
        return client_deferred
 
22
 
 
23
    def _connect_to_machine(self, machines, share):
 
24
        # TODO Should we pick a random entry from the nodes list?
 
25
        log.info("Connecting to environment.")
 
26
        machine = machines[0]
 
27
        if not machine.dns_name:
 
28
            raise EnvironmentPending("machine %s has no address assigned yet"
 
29
                                     % machine.instance_id)
 
30
        client = SSHClient()
 
31
        result = client.connect(machine.dns_name + ":2181",
 
32
                                timeout=30, share=share)
 
33
        result.addErrback(self._check_machine_age, machine)
 
34
        return result
 
35
 
 
36
    def _check_machine_age(self, failure, machine):
 
37
        failure.trap(NoConnection)
 
38
        five_minutes_ago = datetime.datetime.now() - timedelta(minutes=5)
 
39
        if machine.launch_time > five_minutes_ago:
 
40
            raise NoConnection("Can't yet connect to started machine: %s" %
 
41
                               str(failure.value))
 
42
        return failure
 
43
 
 
44
    @inlineCallbacks
 
45
    def _wait_for_initialization(self, client):
 
46
        exists_d, watch_d = client.exists_and_watch("/initialized")
 
47
        exists = yield exists_d
 
48
        if not exists:
 
49
            log.info("Environment still initializing.  Will wait.")
 
50
            yield watch_d
 
51
        else:
 
52
            log.debug("Environment already initialized.")
 
53
        returnValue(client)