desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns a dict(instance_id, [security_groups]) to allow obtaining all of the instances and their security groups in one shot.'
def get_instances_security_groups_bindings(self, context):
quantum = quantumv2.get_client(context) ports = quantum.list_ports().get('ports') security_groups = quantum.list_security_groups().get('security_groups') security_group_lookup = {} instances_security_group_bindings = {} for security_group in security_groups: security_group_lookup[securit...
'Returns the security groups that are associated with an instance. If detailed is True then it also returns the full details of the security groups associated with an instance.'
def get_instance_security_groups(self, context, instance_id, instance_uuid=None, detailed=False):
quantum = quantumv2.get_client(context) if instance_uuid: params = {'device_id': instance_uuid} else: params = {'device_id': instance_id} ports = quantum.list_ports(**params) security_groups = quantum.list_security_groups().get('security_groups') security_group_lookup = {} fo...
'Add security group to the instance.'
@wrap_check_security_groups_policy def add_to_instance(self, context, instance, security_group_name):
quantum = quantumv2.get_client(context) try: security_group_id = quantumv20.find_resourceid_by_name_or_id(quantum, 'security_group', security_group_name) except q_exc.QuantumClientException as e: if (e.status_code == 404): msg = ('Security group %s is not found ...
'Remove the security group associated with the instance.'
@wrap_check_security_groups_policy def remove_from_instance(self, context, instance, security_group_name):
quantum = quantumv2.get_client(context) try: security_group_id = quantumv20.find_resourceid_by_name_or_id(quantum, 'security_group', security_group_name) except q_exc.QuantumClientException as e: if (e.status_code == 404): msg = ('Security group %s is not found ...
'Indicates whether the specified rule is already defined in the given security group.'
def rule_exists(self, security_group, new_rule):
for rule in security_group['rules']: is_duplicate = True keys = ('group_id', 'cidr', 'from_port', 'to_port', 'protocol') for key in keys: if (rule.get(key) != new_rule.get(key)): is_duplicate = False break if is_duplicate: retur...
'Called when a rule is added to or removed from a security_group.'
def trigger_rules_refresh(self, context, id):
pass
'Called when a security group gains a new or loses a member. Sends an update request to each compute node for each instance for which this is relevant.'
def trigger_members_refresh(self, context, group_ids):
pass
'Called when populating the database for an instances security groups.'
def populate_security_groups(self, instance, security_groups):
raise NotImplementedError()
'Adds (allocates) a floating ip to a project from a pool.'
@wrap_check_policy def allocate_floating_ip(self, context, pool=None):
return self.floating_manager.allocate_floating_ip(context, context.project_id, False, pool)
'Removes (deallocates) a floating ip with address from a project.'
@wrap_check_policy def release_floating_ip(self, context, address, affect_auto_assigned=False):
return self.floating_manager.deallocate_floating_ip(context, address, affect_auto_assigned)
'Associates a floating ip with a fixed ip. Ensures floating ip is allocated to the project in context. Does not verify ownership of the fixed ip. Caller is assumed to have checked that the instance is properly owned.'
@wrap_check_policy @refresh_cache def associate_floating_ip(self, context, instance, floating_address, fixed_address, affect_auto_assigned=False):
orig_instance_uuid = self.floating_manager.associate_floating_ip(context, floating_address, fixed_address, affect_auto_assigned) if orig_instance_uuid: msg_dict = dict(address=floating_address, instance_id=orig_instance_uuid) LOG.info((_('re-assign floating IP %(address)s from ins...
'Disassociates a floating ip from fixed ip it is associated with.'
@wrap_check_policy @refresh_cache def disassociate_floating_ip(self, context, instance, address, affect_auto_assigned=False):
return self.floating_manager.disassociate_floating_ip(context, address, affect_auto_assigned)
'Allocates all network structures for an instance. TODO(someone): document the rest of these parameters. :param macs: None or a set of MAC addresses that the instance should use. macs is supplied by the hypervisor driver (contrast with requested_networks which is user supplied). :returns: network info as from get_insta...
@wrap_check_policy @refresh_cache def allocate_for_instance(self, context, instance, vpn, requested_networks, macs=None, conductor_api=None, security_groups=None):
instance_type = instance_types.extract_instance_type(instance) args = {} args['vpn'] = vpn args['requested_networks'] = requested_networks args['instance_id'] = instance['uuid'] args['project_id'] = instance['project_id'] args['host'] = instance['host'] args['rxtx_factor'] = instance_typ...
'Deallocates all network structures related to instance.'
@wrap_check_policy def deallocate_for_instance(self, context, instance):
args = {} args['instance_id'] = instance['uuid'] args['project_id'] = instance['project_id'] args['host'] = instance['host'] self.network_rpcapi.deallocate_for_instance(context, **args)
'Adds a fixed ip to instance from specified network.'
@wrap_check_policy @refresh_cache def add_fixed_ip_to_instance(self, context, instance, network_id, conductor_api=None):
instance_type = instance_types.extract_instance_type(instance) args = {'instance_id': instance['uuid'], 'rxtx_factor': instance_type['rxtx_factor'], 'host': instance['host'], 'network_id': network_id} self.network_rpcapi.add_fixed_ip_to_instance(context, **args)
'Removes a fixed ip from instance from specified network.'
@wrap_check_policy @refresh_cache def remove_fixed_ip_from_instance(self, context, instance, address, conductor_api=None):
instance_type = instance_types.extract_instance_type(instance) args = {'instance_id': instance['uuid'], 'rxtx_factor': instance_type['rxtx_factor'], 'host': instance['host'], 'address': address} self.network_rpcapi.remove_fixed_ip_from_instance(context, **args)
'Force adds another network to a project.'
@wrap_check_policy def add_network_to_project(self, context, project_id, network_uuid=None):
self.network_rpcapi.add_network_to_project(context, project_id, network_uuid)
'Associate or disassociate host or project to network.'
@wrap_check_policy def associate(self, context, network_uuid, host=_sentinel, project=_sentinel):
associations = {} network_id = self.get(context, network_uuid)['id'] if (host is not API._sentinel): if (host is None): self.db.network_disassociate(context, network_id, disassociate_host=True, disassociate_project=False) else: self.db.network_set_host(context, networ...
'Returns all network info related to an instance.'
@wrap_check_policy def get_instance_nw_info(self, context, instance, conductor_api=None):
result = self._get_instance_nw_info(context, instance) update_instance_cache_with_nw_info(self, context, instance, result, conductor_api) return result
'Returns all network info related to an instance.'
def _get_instance_nw_info(self, context, instance):
instance_type = instance_types.extract_instance_type(instance) args = {'instance_id': instance['uuid'], 'rxtx_factor': instance_type['rxtx_factor'], 'host': instance['host'], 'project_id': instance['project_id']} nw_info = self.network_rpcapi.get_instance_nw_info(context, **args) return network_model.Ne...
'validate the networks passed at the time of creating the server'
@wrap_check_policy def validate_networks(self, context, requested_networks):
return self.network_rpcapi.validate_networks(context, requested_networks)
'Returns a list of dicts in the form of {\'instance_uuid\': uuid, \'ip\': ip} that matched the ip_filter'
@wrap_check_policy def get_instance_uuids_by_ip_filter(self, context, filters):
return self.network_rpcapi.get_instance_uuids_by_ip_filter(context, filters)
'Returns a list of available dns domains. These can be used to create DNS entries for floating ips.'
@wrap_check_policy def get_dns_domains(self, context):
return self.network_rpcapi.get_dns_domains(context)
'Create specified DNS entry for address.'
@wrap_check_policy def add_dns_entry(self, context, address, name, dns_type, domain):
args = {'address': address, 'name': name, 'dns_type': dns_type, 'domain': domain} return self.network_rpcapi.add_dns_entry(context, **args)
'Create specified DNS entry for address.'
@wrap_check_policy def modify_dns_entry(self, context, name, address, domain):
args = {'address': address, 'name': name, 'domain': domain} return self.network_rpcapi.modify_dns_entry(context, **args)
'Delete the specified dns entry.'
@wrap_check_policy def delete_dns_entry(self, context, name, domain):
args = {'name': name, 'domain': domain} return self.network_rpcapi.delete_dns_entry(context, **args)
'Delete the specified dns domain.'
@wrap_check_policy def delete_dns_domain(self, context, domain):
return self.network_rpcapi.delete_dns_domain(context, domain=domain)
'Get entries for address and domain.'
@wrap_check_policy def get_dns_entries_by_address(self, context, address, domain):
args = {'address': address, 'domain': domain} return self.network_rpcapi.get_dns_entries_by_address(context, **args)
'Get entries for name and domain.'
@wrap_check_policy def get_dns_entries_by_name(self, context, name, domain):
args = {'name': name, 'domain': domain} return self.network_rpcapi.get_dns_entries_by_name(context, **args)
'Create a private DNS domain with nova availability zone.'
@wrap_check_policy def create_private_dns_domain(self, context, domain, availability_zone):
args = {'domain': domain, 'av_zone': availability_zone} return self.network_rpcapi.create_private_dns_domain(context, **args)
'Create a public DNS domain with optional nova project.'
@wrap_check_policy def create_public_dns_domain(self, context, domain, project=None):
args = {'domain': domain, 'project': project} return self.network_rpcapi.create_public_dns_domain(context, **args)
'Setup or teardown the network structures on hosts related to instance'
@wrap_check_policy def setup_networks_on_host(self, context, instance, host=None, teardown=False):
host = (host or instance['host']) args = {'instance_id': instance['id'], 'host': host, 'teardown': teardown} self.network_rpcapi.setup_networks_on_host(context, **args)
'Start to migrate the network of an instance.'
@wrap_check_policy def migrate_instance_start(self, context, instance, migration):
instance_type = instance_types.extract_instance_type(instance) args = dict(instance_uuid=instance['uuid'], rxtx_factor=instance_type['rxtx_factor'], project_id=instance['project_id'], source_compute=migration['source_compute'], dest_compute=migration['dest_compute'], floating_addresses=None) if self._is_mul...
'Finish migrating the network of an instance.'
@wrap_check_policy def migrate_instance_finish(self, context, instance, migration):
instance_type = instance_types.extract_instance_type(instance) args = dict(instance_uuid=instance['uuid'], rxtx_factor=instance_type['rxtx_factor'], project_id=instance['project_id'], source_compute=migration['source_compute'], dest_compute=migration['dest_compute'], floating_addresses=None) if self._is_mul...
'ldap_object is an instance of ldap.LDAPObject. It should already be initialized and bound before getting passed in here.'
def __init__(self, ldap_object):
self.lobj = ldap_object self.ldap_tuple = None self.qualified_domain = None
'Create a new domain entry, and return an object that wraps it.'
@classmethod def create_domain(cls, lobj, domain):
entry = cls._get_tuple_for_domain(lobj, domain) if entry: raise exception.FloatingIpDNSExists(name=domain, domain='') newdn = ('dc=%s,%s' % (domain, CONF.ldap_dns_base_dn)) attrs = {'objectClass': ['domainrelatedobject', 'dnsdomain', 'domain', 'dcobject', 'top'], 'sOARecord': [cls._soa()], 'asso...
'Delete the domain that this entry refers to.'
def delete(self):
entries = self.lobj.search_s(self.dn, ldap.SCOPE_SUBTREE, '(aRecord=*)') for entry in entries: self.lobj.delete_s(entry[0]) self.lobj.delete_s(self.dn)
'Called when a security group is created :param context: the security context. :param group: the new group added. group is a dictionary that contains the following: user_id, project_id, name, description).'
def trigger_security_group_create_refresh(self, context, group):
raise NotImplementedError()
'Called when a security group is deleted :param context: the security context. :param security_group_id: the security group identifier.'
def trigger_security_group_destroy_refresh(self, context, security_group_id):
raise NotImplementedError()
'Called when a rule is added to a security_group. :param context: the security context. :param rule_ids: a list of rule ids that have been affected.'
def trigger_security_group_rule_create_refresh(self, context, rule_ids):
raise NotImplementedError()
'Called when a rule is removed from a security_group. :param context: the security context. :param rule_ids: a list of rule ids that have been affected.'
def trigger_security_group_rule_destroy_refresh(self, context, rule_ids):
raise NotImplementedError()
'Called when a security group gains a new member. :param context: the security context. :param instance: the instance to be associated. :param group_name: the name of the security group to be associated.'
def trigger_instance_add_security_group_refresh(self, context, instance, group_name):
raise NotImplementedError()
'Called when a security group loses a member. :param context: the security context. :param instance: the instance to be associated. :param group_name: the name of the security group to be associated.'
def trigger_instance_remove_security_group_refresh(self, context, instance, group_name):
raise NotImplementedError()
'Called when a security group gains or loses a member. :param context: the security context. :param group_ids: a list of security group identifiers.'
def trigger_security_group_members_refresh(self, context, group_ids):
raise NotImplementedError()
'Called when a rule is added to a security_group. :param context: the security context. :param group: the new group added. group is a dictionary that contains the following: user_id, project_id, name, description).'
def trigger_security_group_create_refresh(self, context, group):
pass
'Called when a rule is added to a security_group. :param context: the security context. :param security_group_id: the security group identifier.'
def trigger_security_group_destroy_refresh(self, context, security_group_id):
pass
'Called when a rule is added to a security_group. :param context: the security context. :param rule_ids: a list of rule ids that have been affected.'
def trigger_security_group_rule_create_refresh(self, context, rule_ids):
pass
'Called when a rule is removed from a security_group. :param context: the security context. :param rule_ids: a list of rule ids that have been affected.'
def trigger_security_group_rule_destroy_refresh(self, context, rule_ids):
pass
'Called when a security group gains a new member. :param context: the security context. :param instance: the instance to be associated. :param group_name: the name of the security group to be associated.'
def trigger_instance_add_security_group_refresh(self, context, instance, group_name):
pass
'Called when a security group loses a member. :param context: the security context. :param instance: the instance to be associated. :param group_name: the name of the security group to be associated.'
def trigger_instance_remove_security_group_refresh(self, context, instance, group_name):
pass
'Called when a security group gains or loses a member. :param context: the security context. :param group_ids: a list of security group identifiers.'
def trigger_security_group_members_refresh(self, context, group_ids):
pass
'Proxy tcp connection from source to dest.'
def one_way_proxy(self, source, dest):
while True: try: d = source.recv(32384) except Exception as e: d = None if ((d is None) or (len(d) == 0)): dest.shutdown(socket.SHUT_WR) break try: dest.sendall(d) except Exception as e: source.close() ...
'Execute hypervisor-specific vnc auth handshaking (if needed).'
def handshake(self, req, connect_info, sockets):
host = connect_info['host'] port = int(connect_info['port']) server = eventlet.connect((host, port)) if connect_info.get('internal_access_path'): server.sendall(('CONNECT %s HTTP/1.1\r\n\r\n' % connect_info['internal_access_path'])) data = '' while True: b = ser...
'Spawn bi-directional vnc proxy.'
def proxy_connection(self, req, connect_info, start_response):
sockets = {} t0 = eventlet.spawn(self.handshake, req, connect_info, sockets) t0.wait() if ((not sockets.get('client')) or (not sockets.get('server'))): LOG.audit(_('Invalid request: %s'), req) start_response('400 Invalid Request', [('content-type', 'text/html')]) retu...
'A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise.'
def supported(cls, stream=sys.stdout):
if (not stream.isatty()): return False try: import curses except ImportError: return False else: try: try: return (curses.tigetnum('colors') > 2) except curses.error: curses.setupterm() return (curses...
'Write the given text to the stream in the given color. @param text: Text to be written to the stream. @param color: A string label for a color. e.g. \'red\', \'white\'.'
def write(self, text, color):
color = self._colors[color] self.stream.write(('\x1b[%s;1m%s\x1b[0m' % (color, text)))
'Overrides normal addError to add support for errorClasses. If the exception is a registered class, the error will be added to the list for that class, not errors.'
def addError(self, test, err):
stream = getattr(self, 'stream', None) (ec, ev, tb) = err try: exc_info = self._exc_info_to_string(err, test) except TypeError: exc_info = self._exc_info_to_string(err) for (cls, (storage, label, isfail)) in self.errorClasses.items(): if (result.isclass(ec) and issubclass(ec,...
'Attempt to ping the specified IP, and give up after 1 second.'
def can_ping(self, ip, command='ping'):
if (sys.platform == 'darwin'): timeout_flag = 't' else: timeout_flag = 'w' (status, output) = commands.getstatusoutput(('%s -c1 -%s1 %s' % (command, timeout_flag, ip))) return (status == 0)
'Wait for instance to be running.'
def wait_for_running(self, instance, tries=60, wait=1):
for x in xrange(tries): instance.update() if instance.state.startswith('running'): return True time.sleep(wait) else: return False
'Wait for instance to be deleted.'
def wait_for_deleted(self, instance, tries=60, wait=1):
for x in xrange(tries): try: instance.update(validate=True) except ValueError: return True time.sleep(wait) else: return False
'Wait for ip to be pingable.'
def wait_for_ping(self, ip, command='ping', tries=120):
for x in xrange(tries): if self.can_ping(ip, command): return True else: return False
'Wait for ip to be sshable.'
def wait_for_ssh(self, ip, key_name, tries=30, wait=5):
for x in xrange(tries): try: conn = self.connect_ssh(ip, key_name) conn.close() except Exception as e: time.sleep(wait) else: return True else: return False
'Returns a boto ec2 connection for the current environment.'
def connection_for_env(self, **kwargs):
access_key = os.getenv('EC2_ACCESS_KEY') secret_key = os.getenv('EC2_SECRET_KEY') clc_url = os.getenv('EC2_URL') if ((not access_key) or (not secret_key) or (not clc_url)): raise Exception('Missing EC2 environment variables. Please source the appropriate novarc file ...
'Splits a cloud controller endpoint url.'
def split_clc_url(self, clc_url):
parts = httplib.urlsplit(clc_url) is_secure = (parts.scheme == 'https') (ip, port) = parts.netloc.split(':') return {'ip': ip, 'port': int(port), 'is_secure': is_secure}
'Retrieve all the instances associated with your account. :type instance_ids: list :param instance_ids: A list of strings of instance IDs :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as t...
def get_all_instances(self, instance_ids=None, filters=None):
params = {} if instance_ids: self.build_list_params(params, instance_ids, 'InstanceId') if filters: self.build_filter_params(params, filters) return self.get_list('DescribeInstancesV6', params, [('item', ReservationV6)])
'Runs an image on EC2. :type image_id: string :param image_id: The ID of the image to run :type min_count: int :param min_count: The minimum number of instances to launch :type max_count: int :param max_count: The maximum number of instances to launch :type key_name: string :param key_name: The name of the key pair wit...
def run_instances(self, image_id, min_count=1, max_count=1, key_name=None, security_groups=None, user_data=None, addressing_type=None, instance_type='m1.small', placement=None, kernel_id=None, ramdisk_id=None, monitoring_enabled=False, subnet_id=None, block_device_map=None):
params = {'ImageId': image_id, 'MinCount': min_count, 'MaxCount': max_count} if key_name: params['KeyName'] = key_name if security_groups: l = [] for group in security_groups: if isinstance(group, securitygroup.SecurityGroup): l.append(group.name) ...
'Called after Websockets server startup (i.e. after daemonize)'
def started(self):
if self.wrap_cmd: dst_string = ("'%s' (port %s)" % (' '.join(self.wrap_cmd), self.target_port)) elif self.unix_target: dst_string = self.unix_target else: dst_string = ('%s:%s' % (self.target_host, self.target_port)) if self.target_cfg: msg = (' - proxy...
'Called after a new WebSocket connection has been established.'
def new_client(self):
if self.target_cfg: (self.target_host, self.target_port) = self.get_target(self.target_cfg, self.path) if self.wrap_cmd: msg = ("connecting to command: '%s' (port %s)" % (' '.join(self.wrap_cmd), self.target_port)) elif self.unix_target: msg = ('connecting to ...
'Parses the path, extracts a token, and looks for a valid target for that token in the configuration file(s). Sets target_host and target_port if successful'
def get_target(self, target_cfg, path):
args = parse_qs(urlparse(path)[4]) if ((not args.has_key('token')) or (not len(args['token']))): raise self.EClose('Token not present') token = args['token'][0].rstrip('\n') if os.path.isdir(target_cfg): cfg_files = [os.path.join(target_cfg, f) for f in os.listdir(target_cfg)] ...
'Proxy client WebSocket to normal target socket.'
def do_proxy(self, target):
cqueue = [] c_pend = 0 tqueue = [] rlist = [self.client, target] while True: wlist = [] if tqueue: wlist.append(target) if (cqueue or c_pend): wlist.append(self.client) (ins, outs, excepts) = select(rlist, wlist, [], 1) if excepts: ...
'Resolve a host (and optional port) to an IPv4 or IPv6 address. Create a socket. Bind to it if listen is set, otherwise connect to it. Return the socket.'
@staticmethod def socket(host, port=None, connect=False, prefer_ipv6=False, unix_socket=None, use_ssl=False):
flags = 0 if (host == ''): host = None if (connect and (not (port or unix_socket))): raise Exception('Connect mode requires a port') if (use_ssl and (not ssl)): raise Exception('SSL socket requested but Python SSL module not loaded.') if ((...
'Encode a HyBi style WebSocket frame. Optional opcode: 0x0 - continuation 0x1 - text frame (base64 encode buf) 0x2 - binary frame (use raw buf) 0x8 - connection close 0x9 - ping 0xA - pong'
@staticmethod def encode_hybi(buf, opcode, base64=False):
if base64: buf = b64encode(buf) b1 = (128 | (opcode & 15)) payload_len = len(buf) if (payload_len <= 125): header = pack('>BB', b1, payload_len) elif ((payload_len > 125) and (payload_len < 65536)): header = pack('>BBH', b1, 126, payload_len) elif (payload_len >= 65536): ...
'Decode HyBi style WebSocket packets. Returns: {\'fin\' : 0_or_1, \'opcode\' : number, \'masked\' : boolean, \'hlen\' : header_bytes_number, \'length\' : payload_bytes_number, \'payload\' : decoded_buffer, \'left\' : bytes_left_number, \'close_code\' : number, \'close_r...
@staticmethod def decode_hybi(buf, base64=False):
f = {'fin': 0, 'opcode': 0, 'masked': False, 'hlen': 2, 'length': 0, 'payload': None, 'left': 0, 'close_code': 1000, 'close_reason': ''} blen = len(buf) f['left'] = blen if (blen < f['hlen']): return f (b1, b2) = unpack_from('>BB', buf) f['opcode'] = (b1 & 15) f['fin'] = ((b1 & 128) ...
'Generate hash value for WebSockets hixie-76.'
@staticmethod def gen_md5(keys):
key1 = keys['Sec-WebSocket-Key1'] key2 = keys['Sec-WebSocket-Key2'] key3 = keys['key3'] spaces1 = key1.count(' ') spaces2 = key2.count(' ') num1 = (int(''.join([c for c in key1 if c.isdigit()])) / spaces1) num2 = (int(''.join([c for c in key2 if c.isdigit()])) / spaces2) return b2s...
'Show traffic flow in verbose mode.'
def traffic(self, token='.'):
if (self.verbose and (not self.daemon)): sys.stdout.write(token) sys.stdout.flush()
'Output message with handler_id prefix.'
def msg(self, msg):
if (not self.daemon): print ('% 3d: %s' % (self.handler_id, msg))
'Same as msg() but only if verbose.'
def vmsg(self, msg):
if self.verbose: self.msg(msg)
'Encode and send WebSocket frames. Any frames already queued will be sent first. If buf is not set then only queued frames will be sent. Returns the number of pending frames that could not be fully sent. If returned pending frames is greater than 0, then the caller should call again when the socket is ready.'
def send_frames(self, bufs=None):
tdelta = (int((time.time() * 1000)) - self.start_time) if bufs: for buf in bufs: if self.version.startswith('hybi'): if self.base64: (encbuf, lenhead, lentail) = self.encode_hybi(buf, opcode=1, base64=True) else: (encbuf...
'Receive and decode WebSocket frames. Returns: (bufs_list, closed_string)'
def recv_frames(self):
closed = False bufs = [] tdelta = (int((time.time() * 1000)) - self.start_time) buf = self.client.recv(self.buffer_size) if (len(buf) == 0): closed = {'code': 1000, 'reason': 'Client closed abruptly'} return (bufs, closed) if self.recv_part: buf = (self.recv_part + ...
'Send a WebSocket orderly close frame.'
def send_close(self, code=1000, reason=''):
if self.version.startswith('hybi'): msg = pack(('>H%ds' % len(reason)), code, reason) (buf, h, t) = self.encode_hybi(msg, opcode=8, base64=False) self.client.send(buf) elif (self.version == 'hixie-76'): buf = s2b('\xff\x00') self.client.send(buf)
'do_handshake does the following: - Peek at the first few bytes from the socket. - If the connection is Flash policy request then answer it, close the socket and return. - If the connection is an HTTPS/SSL/TLS connection then SSL wrap the socket. - Read from the (possibly wrapped) socket. - If we have received a HTTP G...
def do_handshake(self, sock, address):
stype = '' ready = select.select([sock], [], [], 3)[0] if (not ready): raise self.EClose('ignoring socket not ready') handshake = sock.recv(1024, socket.MSG_PEEK) if (handshake == ''): raise self.EClose('ignoring empty handshake') elif handshake.startswith(s2b('<po...
'Called after WebSockets startup'
def started(self):
self.vmsg('WebSockets server started')
'Run periodically while waiting for connections.'
def poll(self):
pass
'Do something with a WebSockets client connection.'
def top_new_client(self, startsock, address):
self.send_parts = [] self.recv_part = None self.base64 = False self.rec = None self.start_time = int((time.time() * 1000)) try: self.client = self.do_handshake(startsock, address) if self.record: fname = ('%s.%s' % (self.record, self.handler_id)) self.msg(...
'Do something with a WebSockets client connection.'
def new_client(self):
raise 'WebSocketServer.new_client() must be overloaded'
'Daemonize if requested. Listen for for connections. Run do_handshake() method for each connection. If the connection is a WebSockets client then call new_client() method (which must be overridden) for each new client connection.'
def start_server(self):
lsock = self.socket(self.listen_host, self.listen_port, False, self.prefer_ipv6) if self.daemon: self.daemonize(keepfd=lsock.fileno(), chdir=self.web) self.started() signal.signal(signal.SIGINT, self.do_SIGINT) if (not multiprocessing): signal.signal(signal.SIGCHLD, self.fallback_SIG...
'Called after Websockets server startup (i.e. after daemonize)'
def started(self):
if self.wrap_cmd: dst_string = ("'%s' (port %s)" % (' '.join(self.wrap_cmd), self.target_port)) elif self.unix_target: dst_string = self.unix_target else: dst_string = ('%s:%s' % (self.target_host, self.target_port)) if self.target_cfg: msg = (' - proxy...
'Called after a new WebSocket connection has been established.'
def new_client(self):
if self.target_cfg: (self.target_host, self.target_port) = self.get_target(self.target_cfg, self.path) if self.wrap_cmd: msg = ("connecting to command: '%s' (port %s)" % (' '.join(self.wrap_cmd), self.target_port)) elif self.unix_target: msg = ('connecting to ...
'Parses the path, extracts a token, and looks for a valid target for that token in the configuration file(s). Sets target_host and target_port if successful'
def get_target(self, target_cfg, path):
args = parse_qs(urlparse(path)[4]) if ((not args.has_key('token')) or (not len(args['token']))): raise self.EClose('Token not present') token = args['token'][0].rstrip('\n') if os.path.isdir(target_cfg): cfg_files = [os.path.join(target_cfg, f) for f in os.listdir(target_cfg)] ...
'Proxy client WebSocket to normal target socket.'
def do_proxy(self, target):
cqueue = [] c_pend = 0 tqueue = [] rlist = [self.client, target] while True: wlist = [] if tqueue: wlist.append(target) if (cqueue or c_pend): wlist.append(self.client) (ins, outs, excepts) = select(rlist, wlist, [], 1) if excepts: ...
'Runs a command in an out-of-process shell. Returns the output of that command. Working directory is self.root.'
def run_command_with_code(self, cmd, redirect_output=True, check_exit_code=True):
if redirect_output: stdout = subprocess.PIPE else: stdout = None proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout) output = proc.communicate()[0] if (check_exit_code and (proc.returncode != 0)): self.die('Command "%s" failed.\n%s', ' '.join(cmd), output) ...
'Creates the virtual environment and installs PIP. Creates the virtual environment and installs PIP only into the virtual environment.'
def create_virtualenv(self, no_site_packages=True):
if (not os.path.isdir(self.venv)): print 'Creating venv...', if no_site_packages: self.run_command(['virtualenv', '-q', '--no-site-packages', self.venv]) else: self.run_command(['virtualenv', '-q', self.venv]) print 'done.' print 'Installing pip ...
'Parses command-line arguments.'
def parse_args(self, argv):
parser = argparse.ArgumentParser() parser.add_argument('-n', '--no-site-packages', action='store_true', help='Do not inherit packages from global Python install') return parser.parse_args(argv[1:])
'Any distribution-specific post-processing gets done here. In particular, this is useful for applying patches to code inside the venv.'
def post_process(self):
pass
'Workaround for a bug in eventlet. This currently affects RHEL6.1, but the fix can safely be applied to all RHEL and Fedora distributions. This can be removed when the fix is applied upstream. Nova: https://bugs.launchpad.net/nova/+bug/884915 Upstream: https://bitbucket.org/which_linden/eventlet/issue/89'
def post_process(self):
if (not self.check_pkg('patch')): self.yum_install('patch') self.apply_patch(os.path.join(self.venv, 'lib', self.py_version, 'site-packages', 'eventlet/green/subprocess.py'), 'contrib/redhat-eventlet.patch')
'A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise.'
def supported(cls, stream=sys.stdout):
if (not stream.isatty()): return False try: import curses except ImportError: return False else: try: try: return (curses.tigetnum('colors') > 2) except curses.error: curses.setupterm() return (curses...
'Write the given text to the stream in the given color. @param text: Text to be written to the stream. @param color: A string label for a color. e.g. \'red\', \'white\'.'
def write(self, text, color):
color = self._colors[color] self.stream.write(('\x1b[%s;1m%s\x1b[0m' % (color, text)))
'Overrides normal addError to add support for errorClasses. If the exception is a registered class, the error will be added to the list for that class, not errors.'
def addError(self, test, err):
stream = getattr(self, 'stream', None) (ec, ev, tb) = err try: exc_info = self._exc_info_to_string(err, test) except TypeError: exc_info = self._exc_info_to_string(err) for (cls, (storage, label, isfail)) in self.errorClasses.items(): if (result.isclass(ec) and issubclass(ec,...
'Notify the agent that is hosting the router'
def _notification_host(self, context, method, payload, host):
LOG.debug(_('Nofity agent at %(host)s the message %(method)s'), {'host': host, 'method': method}) self.cast(context, self.make_msg(method, payload=payload), topic=('%s.%s' % (topics.L3_AGENT, host)))
'Notify changed routers to hosting l3 agents. Adjust routers according to l3 agents\' role and related dhcp agents. Notify dhcp agent to get right subnet\'s gateway ips.'
def _agent_notification(self, context, method, routers, operation, data):
adminContext = ((context.is_admin and context) or context.elevated()) plugin = manager.QuantumManager.get_plugin() for router in routers: l3_agents = plugin.get_l3_agents_hosting_routers(adminContext, [router['id']], admin_state_up=True, active=True) for l3_agent in l3_agents: LO...