class representing a single connection stored in the Connection Manager # to-do: may also need some locking to ensure to not connect simultaniously in 2 threads
| 41 | |
| 42 | |
| 43 | class wvmConnection(object): |
| 44 | """ |
| 45 | class representing a single connection stored in the Connection Manager |
| 46 | # to-do: may also need some locking to ensure to not connect simultaniously in 2 threads |
| 47 | """ |
| 48 | |
| 49 | def __init__(self, host, login, passwd, conn): |
| 50 | """ |
| 51 | Sets all class attributes and tries to open the connection |
| 52 | """ |
| 53 | # connection lock is used to lock all changes to the connection state attributes |
| 54 | # (connection and last_error) |
| 55 | self.connection_state_lock = threading.Lock() |
| 56 | self.connection = None |
| 57 | self.last_error = None |
| 58 | |
| 59 | # credentials |
| 60 | self.host = host |
| 61 | self.login = login |
| 62 | self.passwd = passwd |
| 63 | self.type = conn |
| 64 | |
| 65 | # connect |
| 66 | self.connect() |
| 67 | |
| 68 | def connect(self): |
| 69 | self.connection_state_lock.acquire() |
| 70 | try: |
| 71 | # recheck if we have a connection (it may have been |
| 72 | if not self.connected: |
| 73 | if self.type == CONN_TCP: |
| 74 | self.__connect_tcp() |
| 75 | elif self.type == CONN_SSH: |
| 76 | self.__connect_ssh() |
| 77 | elif self.type == CONN_TLS: |
| 78 | self.__connect_tls() |
| 79 | elif self.type == CONN_SOCKET: |
| 80 | self.__connect_socket() |
| 81 | else: |
| 82 | raise ValueError('"{type}" is not a valid connection type'.format(type=self.type)) |
| 83 | |
| 84 | if self.connected: |
| 85 | # do some preprocessing of the connection: |
| 86 | # * set keep alive interval |
| 87 | # * set connection close/fail handler |
| 88 | try: |
| 89 | self.connection.setKeepAlive(connection_manager.keepalive_interval, connection_manager.keepalive_count) |
| 90 | try: |
| 91 | self.connection.registerCloseCallback(self.__connection_close_callback, None) |
| 92 | except: |
| 93 | # Temporary fix for libvirt > libvirt-0.10.2-41 |
| 94 | pass |
| 95 | except libvirtError as e: |
| 96 | # hypervisor driver does not seem to support persistent connections |
| 97 | self.last_error = str(e) |
| 98 | finally: |
| 99 | self.connection_state_lock.release() |
| 100 |