desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the number of calls that succeeded.'
def get_num_requests_succeeded(self):
return self._num_requests_succeeded
'Sets the default api instance. When making calls to the api, objects will revert to using the default api if one is not specified when initializing the objects. Args: api_instance: The instance which to set as default.'
@classmethod def set_default_api(cls, api_instance):
cls._default_api = api_instance
'Returns the default api instance.'
@classmethod def get_default_api(cls):
return cls._default_api
'Makes an API call. Args: method: The HTTP method name (e.g. \'GET\'). path: A tuple of path tokens or a full URL string. A tuple will be translated to a url as follows: graph_url/tuple[0]/tuple[1]... It will be assumed that if the path is not a string, it will be iterable. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. headers (optional): A mapping of request headers where a key is the header name and its value is the header value. files (optional): An optional mapping of file names to binary open file objects. These files will be attached to the request. Returns: A FacebookResponse object containing the response body, headers, http status, and summary of the call that was made. Raises: FacebookResponse.error() if the request failed.'
def call(self, method, path, params=None, headers=None, files=None, url_override=None, api_version=None):
if (not params): params = {} if (not headers): headers = {} if (not files): files = {} api_version = (api_version or self._api_version) if (api_version and (not re.search('v[0-9]+\\.[0-9]+', api_version))): raise FacebookBadObjectError(('Please provide the API version in the following format: %s' % self.API_VERSION)) self._num_requests_attempted += 1 if (not isinstance(path, six.string_types)): path = '/'.join(((self._session.GRAPH or url_override), api_version, '/'.join(map(str, path)))) headers = headers.copy() headers.update(FacebookAdsApi.HTTP_DEFAULT_HEADERS) if params: params = _top_level_param_json_encode(params) if (method in ('GET', 'DELETE')): response = self._session.requests.request(method, path, params=params, headers=headers, files=files, timeout=self._session.timeout) else: response = self._session.requests.request(method, path, data=params, headers=headers, files=files, timeout=self._session.timeout) fb_response = FacebookResponse(body=response.text, headers=response.headers, http_status=response.status_code, call={'method': method, 'path': path, 'params': params, 'headers': headers, 'files': files}) if fb_response.is_failure(): raise fb_response.error() self._num_requests_succeeded += 1 return fb_response
'Returns a new FacebookAdsApiBatch, which when executed will go through this api.'
def new_batch(self):
return FacebookAdsApiBatch(api=self)
'Adds a call to the batch. Args: method: The HTTP method name (e.g. \'GET\'). relative_path: A tuple of path tokens or a relative URL string. A tuple will be translated to a url as follows: <graph url>/<tuple[0]>/<tuple[1]>... It will be assumed that if the path is not a string, it will be iterable. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. headers (optional): A mapping of request headers where a key is the header name and its value is the header value. files (optional): An optional mapping of file names to binary open file objects. These files will be attached to the request. success (optional): A callback function which will be called with the FacebookResponse of this call if the call succeeded. failure (optional): A callback function which will be called with the FacebookResponse of this call if the call failed. request (optional): The APIRequest object Returns: A dictionary describing the call.'
def add(self, method, relative_path, params=None, headers=None, files=None, success=None, failure=None, request=None):
if (not isinstance(relative_path, six.string_types)): relative_url = '/'.join(relative_path) else: relative_url = relative_path call = {'method': method, 'relative_url': relative_url} if params: params = _top_level_param_json_encode(params) keyvals = [('%s=%s' % (key, urls.quote_with_encoding(value))) for (key, value) in params.items()] if (method == 'GET'): call['relative_url'] += ('?' + '&'.join(keyvals)) else: call['body'] = '&'.join(keyvals) if files: call['attached_files'] = ','.join(files.keys()) if headers: call['headers'] = [] for header in headers: batch_formatted_header = {} batch_formatted_header['name'] = header batch_formatted_header['value'] = headers[header] call['headers'].append(batch_formatted_header) self._batch.append(call) self._files.append(files) self._success_callbacks.append(success) self._failure_callbacks.append(failure) self._requests.append(request) return call
'Interface to add a APIRequest to the batch. Args: request: The APIRequest object to add success (optional): A callback function which will be called with the FacebookResponse of this call if the call succeeded. failure (optional): A callback function which will be called with the FacebookResponse of this call if the call failed. Returns: A dictionary describing the call.'
def add_request(self, request, success=None, failure=None):
updated_params = copy.deepcopy(request._params) if request._fields: updated_params['fields'] = ','.join(request._fields) return self.add(method=request._method, relative_path=request._path, params=updated_params, files=request._file_params, success=success, failure=failure, request=request)
'Makes a batch call to the api associated with this object. For each individual call response, calls the success or failure callback function if they were specified. Note: Does not explicitly raise exceptions. Individual exceptions won\'t be thrown for each call that fails. The success and failure callback functions corresponding to a call should handle its success or failure. Returns: If some of the calls have failed, returns a new FacebookAdsApiBatch object with those calls. Otherwise, returns None.'
def execute(self):
if (not self._batch): return None method = 'POST' path = tuple() params = {'batch': self._batch} files = {} for call_files in self._files: if call_files: files.update(call_files) fb_response = self._api.call(method, path, params=params, files=files) responses = fb_response.json() retry_indices = [] for (index, response) in enumerate(responses): if response: body = response.get('body') code = response.get('code') headers = response.get('headers') inner_fb_response = FacebookResponse(body=body, headers=headers, http_status=code, call=self._batch[index]) if inner_fb_response.is_success(): if self._success_callbacks[index]: self._success_callbacks[index](inner_fb_response) elif self._failure_callbacks[index]: self._failure_callbacks[index](inner_fb_response) else: retry_indices.append(index) if retry_indices: new_batch = self.__class__(self._api) new_batch._files = [self._files[index] for index in retry_indices] new_batch._batch = [self._batch[index] for index in retry_indices] new_batch._success_callbacks = [self._success_callbacks[index] for index in retry_indices] new_batch._failure_callbacks = [self._failure_callbacks[index] for index in retry_indices] return new_batch else: return None
'Args: node_id: The node id to perform the api call. method: The HTTP method of the call. endpoint: The edge of the api call. api (optional): The FacebookAdsApi object. param_checker (optional): Parameter checker. target_class (optional): The return class of the api call. api_type (optional): NODE or EDGE type of the call. allow_file_upload (optional): Whether the call allows upload. response_parser (optional): An ObjectParser to parse response. include_summary (optional): Include "summary". api_version (optional): API version.'
def __init__(self, node_id, method, endpoint, api=None, param_checker=TypeChecker({}, {}), target_class=None, api_type=None, allow_file_upload=False, response_parser=None, include_summary=True, api_version=None):
self._api = (api or FacebookAdsApi.get_default_api()) self._node_id = node_id self._method = method self._endpoint = endpoint.replace('/', '') self._path = (node_id, endpoint.replace('/', '')) self._param_checker = param_checker self._target_class = target_class self._api_type = api_type self._allow_file_upload = allow_file_upload self._response_parser = response_parser self._include_summary = include_summary self._api_version = api_version self._params = {} self._fields = [] self._file_params = {} self._file_counter = 0 self._accepted_fields = [] if (target_class is not None): self._accepted_fields = target_class.Field.__dict__.values()
'Initializes an cursor over the objects to which there is an edge from source_object. To initialize, you\'ll need to provide either (source_object and target_objects_class) or (api, node_id, endpoint, and object_parser) Args: source_object: An AbstractObject instance from which to inspect an edge. This object should have an id. target_objects_class: Objects traverersed over will be initialized with this AbstractObject class. fields (optional): A list of fields of target_objects_class to automatically read in. params (optional): A mapping of request parameters where a key is the parameter name and its value is a string or an object which can be JSON-encoded. include_summary (optional): Include summary. api (optional): FacebookAdsApi object. node_id (optional): The ID of calling node. endpoint (optional): The edge name. object_parser (optional): The ObjectParser to parse response.'
def __init__(self, source_object=None, target_objects_class=None, fields=None, params=None, include_summary=True, api=None, node_id=None, endpoint=None, object_parser=None):
self.params = dict((params or {})) target_objects_class._assign_fields_to_params(fields, self.params) self._source_object = source_object self._target_objects_class = target_objects_class self._node_id = (node_id or source_object.get_id_assured()) self._endpoint = (endpoint or target_objects_class.get_endpoint()) self._api = (api or source_object.get_api()) self._path = (self._node_id, self._endpoint) self._queue = [] self._finished_iteration = False self._total_count = None self._include_summary = include_summary self._object_parser = (object_parser or ObjectParser(api=self._api, target_class=self._target_objects_class))
'Queries server for more nodes and loads them into the internal queue. Returns: True if successful, else False.'
def load_next_page(self):
if self._finished_iteration: return False if self._include_summary: if ('summary' not in self.params): self.params['summary'] = True response = self._api.call('GET', self._path, params=self.params).json() if (('paging' in response) and ('next' in response['paging'])): self._path = response['paging']['next'] else: self._finished_iteration = True if (self._include_summary and ('summary' in response) and ('total_count' in response['summary'])): self._total_count = response['summary']['total_count'] self._queue = self.build_objects_from_response(response) return (len(self._queue) > 0)
'Tests that bandwidth shaping works. Examines the network speed before, during, and after shaping. Fails if the network speeds do not reflect expected results.'
def test_shapesBandwidth(self):
with Vagrant.ssh('gateway', 'client', 'server') as machines: (gateway, client, server) = machines before = speedBetween(client, server, **IPERF_OPTS) print 'Actual speed before shaping:', before shapedSpeed = (before / 1024) print 'Desired shaping speed:', shapedSpeed shape(gateway, client, shapedSpeed) during = speedBetween(client, server, **IPERF_OPTS) print 'Actual speed during shaping:', during unshape(gateway, client) after = speedBetween(client, server, **IPERF_OPTS) print 'Actual speed after shaping:', after if before.slower(Megabit): self.fail('Actual speed before shaping is too slow for shape testing. (is it already being shaped?)') if during.faster(shapedSpeed): self.fail('Actual speed during shaping exceeded shaping speed.') if after.slower((shapedSpeed * 2)): self.fail('Actual speed after shaping appears to still be shaped.') if after.slower((before * 0.7)): self.fail('Actual speed after shaping did not return to normal value after shaping.')
'Runs the command over ssh. Returns stdout as a string'
def cmd(self, command):
return self.client.exec_command(command)[1].read()
'Runs the command in a pty. Returns a Process object representing the server-side process'
def proc(self, command):
return Process(self, command)
'Initialize Iptables and TC subsystems Only call once as this will FLUSH all current shapings...'
def initialize_shaping_system(self):
self.logger.info('Calling initialize_shaping_system') self._initialize_iptables() self._initialize_tc()
'Initialize IPTables by flushing all rules in FORWARD chain from mangle table.'
def _initialize_iptables(self):
cmd = '{0} -t mangle -F FORWARD'.format(self.iptables) self.run_cmd(cmd)
'Initialize TC on a given interface. If an exception is thrown, it will be forwarded to the main loop unless it can be ignored. Args: eth: the interface to flush TC on. Raises: NetlinkError: An error occured initializing TC subsystem. Exception: Any other exception thrown during initialization.'
def _initialize_tc_for_interface(self, eth):
idx = 65536 eth_name = eth['name'] eth_id = eth['id'] try: self.logger.info('deleting root QDisc on {0}'.format(eth_name)) self.ipr.tc(RTM_DELQDISC, None, eth_id, 0, parent=TC_H_ROOT) except Exception as e: if (isinstance(e, NetlinkError) and (e.code == 2)): self.logger.warning('could not delete root QDisc. There might have been nothing to delete') else: self.logger.exception('Initializing root Qdisc for {0}'.format(eth_name)) raise try: self.logger.info('setting root qdisc on {0}'.format(eth_name)) self.ipr.tc(RTM_NEWQDISC, 'htb', eth_id, idx, default=0) except Exception as e: self.logger.exception('Setting root Qdisc for {0}'.format(eth_name)) raise return TrafficControlRc(code=ReturnCode.OK)
'Initialize TC root qdisc on both LAN and WAN interface.'
def _initialize_tc(self):
for netif in [self.lan, self.wan]: self._initialize_tc_for_interface(netif)
'Given a mark and an interface, unset the HTB class. Args: mark: The mark based on which we delete the class. eth: The interface on which to delete that class id. Returns: A TrafficControlRc containing information on success/failure.'
def _unset_htb_class(self, mark, eth):
ifid = eth['id'] idx = (65536 + mark) try: self.logger.info('deleting class on IFID {0}, classid {1}'.format(eth['name'], int_to_classid(idx))) self.ipr.tc(RTM_DELTCLASS, 'htb', ifid, idx) except NetlinkError as e: return TrafficControlRc(code=ReturnCode.NETLINK_HTB_ERROR, message=str(e)) except Exception as e: self.logger.exception('_unset_htb_class') exc_info = sys.exc_info() return TrafficControlRc(code=ReturnCode.UNKNOWN_HTB_ERROR, message=str(exc_info)) return TrafficControlRc(code=ReturnCode.OK)
'Given a mark, an interface and shaping settings, set the HTB class. Args: mark: The mark based on which we create the class eth: The interface on which to create that class id. shaping: The shaping settings to set. Returns: A TrafficControlRc containing information on success/failure.'
def _set_htb_class(self, mark, eth, shaping):
ifid = eth['id'] idx = (65536 + mark) parent = 65536 self.logger.info('create new HTB class on IFID {0}, classid {1},parent {2}, rate {3}kbits'.format(eth['name'], int_to_classid(idx), int_to_classid(parent), (shaping.rate or ((2 ** 22) - 1)))) try: self.ipr.tc(RTM_NEWTCLASS, 'htb', ifid, idx, parent=parent, rate='{}kbit'.format((shaping.rate or ((2 ** 22) - 1)))) except NetlinkError as e: return TrafficControlRc(code=ReturnCode.NETLINK_HTB_ERROR, message=str(e)) except Exception as e: self.logger.exception('_set_htb_class') exc_info = sys.exc_info() return TrafficControlRc(code=ReturnCode.UNKNOWN_HTB_ERROR, message=str(exc_info)) return TrafficControlRc(code=ReturnCode.OK)
'This is not needed as deleting the HTB class is sufficient to remove the netem qdisc'
def _unset_netem_qdisc(self, mark, eth):
pass
'Given a mark, interface and shaping settings, create the NetEm Qdisc. Args: mark: The mark based on which we create the Qdisc. eth: The interface on which we will create the Qdisc. shaping: The shaping settings for that interface. Returns: A TrafficControlRc containing information on success/failure.'
def _set_netem_qdisc(self, mark, eth, shaping):
ifid = eth['id'] parent = (65536 + mark) idx = 0 self.logger.info('create new Netem qdisc on IFID {0}, parent {1}, loss {2}%, delay {3}'.format(eth['name'], int_to_classid(parent), shaping.loss.percentage, (shaping.delay.delay * 1000))) try: self.ipr.tc(RTM_NEWQDISC, 'netem', ifid, idx, parent=parent, loss=shaping.loss.percentage, delay=(shaping.delay.delay * 1000), jitter=(shaping.delay.jitter * 1000), delay_corr=shaping.delay.correlation, loss_corr=shaping.loss.correlation, prob_reorder=shaping.reorder.percentage, corr_reorder=shaping.reorder.correlation, gap=shaping.reorder.gap, prob_corrupt=shaping.corruption.percentage, corr_corrupt=shaping.corruption.correlation) except NetlinkError as e: return TrafficControlRc(code=ReturnCode.NETLINK_NETEM_ERROR, message=str(e)) except Exception as e: self.logger.exception('_set_netem_qdisc') exc_info = sys.exc_info() return TrafficControlRc(code=ReturnCode.UNKNOWN_NETEM_ERROR, message=str(exc_info)) return TrafficControlRc(code=ReturnCode.OK)
'Given a mark and an interface, delete the filter. Args: mark: The mark based on which we delete the filter. eth: The interface on which we delete the filter. Returns: A TrafficControlRc containing information on success/failure.'
def _unset_filter(self, mark, eth):
ifid = eth['id'] parent = 65536 self.logger.info('deleting filter on IFID {0}, handle {1:X}'.format(eth['name'], mark)) try: self.ipr.tc(RTM_DELTFILTER, 'fw', ifid, mark, parent=parent, protocol=ETH_P_IP, prio=PRIO) except NetlinkError as e: return TrafficControlRc(code=ReturnCode.NETLINK_FW_ERROR, message=str(e)) except Exception as e: self.logger.exception('_unset_filter') exc_info = sys.exc_info() return TrafficControlRc(code=ReturnCode.UNKNOWN_FW_ERROR, message=str(exc_info)) return TrafficControlRc(code=ReturnCode.OK)
'Given a mark, interface and shaping settings, create a TC filter. Args: mark: The mark based on which we create the filter. eth: The interface on which we create the filter. shaping: The shaping associated to this interface. Returns: A TrafficControlRc containing information on success/failure.'
def _set_filter(self, mark, eth, shaping):
ifid = eth['id'] idx = (65536 + mark) parent = 65536 self.logger.info('create new FW filter on IFID {0}, classid {1}, handle {2:X}, rate: {3}kbits'.format(eth['name'], int_to_classid(idx), mark, shaping.rate)) try: extra_args = {} if (not self.dont_drop_packets): extra_args.update({'rate': '{}kbit'.format((shaping.rate or ((2 ** 22) - 1))), 'burst': self.burst_size, 'action': 'drop'}) self.ipr.tc(RTM_NEWTFILTER, 'fw', ifid, mark, parent=parent, protocol=ETH_P_IP, prio=PRIO, classid=idx, **extra_args) except NetlinkError as e: return TrafficControlRc(code=ReturnCode.NETLINK_FW_ERROR, message=str(e)) except Exception as e: self.logger.exception('_set_filter') exc_info = sys.exc_info() return TrafficControlRc(code=ReturnCode.UNKNOWN_FW_ERROR, message=str(exc_info)) return TrafficControlRc(code=ReturnCode.OK)
'Given a mark, interface, IP and options, clear iptables rules. Args: mark: The mark to delete. eth: The interface on which to delete the mark. ip: The IP address to shape. options: An array of iptables options for more specific filtering. Returns: A TrafficControlRc containing information on success/failure.'
def _unset_iptables(self, mark, eth, ip, options=None):
if ((options is None) or (len(options) == 0)): options = [''] for opt in options: cmd = '{0} -t mangle -D FORWARD {1} {2} -i {3} {option} -j MARK --set-mark {4}'.format(self.iptables, ('-s' if (eth['name'] == self.lan['name']) else '-d'), ip, eth['name'], mark, option=opt) self.run_cmd(cmd)
'Given a mark, interface, IP and options, create iptables rules. Those rules will mark packets which will be filtered by TC filter and put in the right shaping bucket. Args: mark: The mark to delete. eth: The interface on which to delete the mark. ip: The IP address to shape. options: An array of iptables options for more specific filtering. Returns: A TrafficControlRc containing information on success/failure.'
def _set_iptables(self, mark, eth, ip, options=None):
if ((options is None) or (len(options) == 0)): options = [''] for opt in options: cmd = '{0} -t mangle -A FORWARD {1} {2} -i {3} {option} -j MARK --set-mark {4}'.format(self.iptables, ('-s' if (eth['name'] == self.lan['name']) else '-d'), ip, eth['name'], mark, option=opt) self.run_cmd(cmd)
'Shape the traffic for a given interface. Shape the traffic for a given IP on a given interface, given the mark and the shaping settings. There is a few steps to shape the traffic of an IP: 1. Create an HTB class that limit the throughput. 2. Create a NetEm QDisc that adds corruption, loss, reordering, loss and delay. 3. Create the TC filter that will bucket packets with a given mark in the right HTB class. 4. Set an iptables rule that mark packets going to/coming from IP Args: mark: The mark to set on IP packets. eth: The network interface. ip: The IP to shape traffic for. shaping: The shaping setting to set. Returns: A TrafficControlRc containing information on success/failure.'
def _shape_interface(self, mark, eth, ip, shaping):
self.logger.info('Shaping ip {0} on interface {1}'.format(ip, eth['name'])) tcrc = self._set_htb_class(mark, eth, shaping) if (tcrc.code != ReturnCode.OK): self.logger.error('adding HTB class on IFID {0}, mark {1}, err: {2}'.format(eth['name'], mark, tcrc.message)) return tcrc tcrc = self._set_netem_qdisc(mark, eth, shaping) if (tcrc.code != ReturnCode.OK): self.logger.error('adding NetEm qdisc on IFID {0}, mark {1}, err: {2}'.format(eth['name'], mark, tcrc.message)) self._unset_htb_class(mark, eth) return tcrc tcrc = self._set_filter(mark, eth, shaping) if (tcrc.code != ReturnCode.OK): self.logger.error('adding filter FW on IFID {0}, mark {1}, err: {2}'.format(eth['name'], mark, tcrc.message)) self._unset_htb_class(mark, eth) return tcrc self._set_iptables(mark, eth, ip, shaping.iptables_options) return TrafficControlRc(code=ReturnCode.OK)
'Unshape the traffic for a given interface. Unshape the traffic for a given IP on a given interface, given the mark and the shaping settings. There is a few steps to unshape the traffic of an IP: 1. Remove the iptables rule. 2. Remove the TC filter. 3. Remove the HTB class. Args: mark: The mark to set on IP packets. eth: The network interface. ip: The IP to shape traffic for. shaping: The shaping setting to set. Returns: A TrafficControlRc containing information on success/failure.'
def _unshape_interface(self, mark, eth, ip, settings):
self.logger.info('Unshaping ip {0} on interface {1}'.format(ip, eth['name'])) self._unset_iptables(mark, eth, ip, settings.iptables_options) tcrc = self._unset_filter(mark, eth) if (tcrc.code != ReturnCode.OK): self.logger.error('deleting FW filter on IFID {0}, mark {1}, err: {2}'.format(eth['name'], mark, tcrc.message)) return tcrc tcrc = self._unset_htb_class(mark, eth) if (tcrc.code != ReturnCode.OK): self.logger.error('deleting HTB class on IFID {0}, mark {1}, err: {2}'.format(eth['name'], mark, tcrc.message)) return tcrc return TrafficControlRc(code=ReturnCode.OK)
'Static method to discover and import the shaper to use. Discover the platform on which Atcd is running and import the shaping backend for this platform. Returns: The shaping backend class Raises: NotImplementedError: the shaping backend class couldn\'t be imported'
@staticmethod def factory():
os_name = os.uname()[0] klass = 'Atcd{0}Shaper'.format(os_name) try: if (klass not in globals()): from_module_import_class('atcd.backends.{0}'.format(os_name.lower()), klass) except AttributeError: raise NotImplementedError('{0} is not implemented!'.format(klass)) except ImportError: raise NotImplementedError('{0} backend is not implemented!'.format(os_name.lower())) return globals()[klass]
'Thrift handler task initialization. Performs the steps needed to initialize the shaping subsystem.'
def initTask(self):
super(AtcdThriftHandlerTask, self).initTask() self.db_task = self.service.tasks.AtcdDBQueueTask self.lan = {'name': self.lan_name} self.wan = {'name': self.wan_name} self._links_lookup() self._ip_to_id_map = {} self._id_to_ip_map = {} self.initialize_id_manager() self.ip_to_pcap_proc_map = {} self.initialize_shaping_system() self._current_shapings = {} self.access_manager = AccessManager(secure=(self.mode != 'unsecure')) if (not self.fresh_start): self.logger.info('Restoring shaped connection from DB') self._restore_saved_shapings()
'Initialize our mapping from network interface name to their device id. Will raise and exception if one of the device is not found'
def _links_lookup(self):
raise NotImplementedError('Subclass should implement this')
'Initialize the Id Manager. This is architecture dependant as the shaping subsystems may have different requirements.'
def initialize_id_manager(self):
self.idmanager = IdManager(first_id=type(self).ID_MANAGER_ID_MIN, max_id=type(self).ID_MANAGER_ID_MAX)
'Restore the shapings from the sqlite3 db.'
def _restore_saved_shapings(self):
names = ['TrafficControlledDevice', 'TrafficControl', 'Shaping', 'TrafficControlSetting', 'Loss', 'Delay', 'Corruption', 'Reorder'] globals = {name: getattr(atc_thrift.ttypes, name) for name in names} results = [] try: results = self.db_task.get_saved_shapings() except OperationalError: self.logger.exception('Unable to perform DB operation') for result in results: tc = eval(result['tc'], globals) timeout = float(result['timeout']) if (timeout > time.time()): tc.timeout = (timeout - time.time()) try: self.startShaping(tc) except TrafficControlException as e: if ((e.code == ReturnCode.ACCESS_DENIED) and (self.mode == 'secure')): self.logger.warn('Shaping Denied in secure mode, passing: {0}'.format(e.message)) continue raise else: self.db_task.queue.put((tc.device.controlledIP, 'remove_shaping'))
'Implements sparts.vtask.VTask.stop() Each shaping platform should implement its own in order to clean its state before shutting down the main loop.'
def stop(self):
raise NotImplementedError('Subclass should implement this')
'Initialize the shaping subsystem. Each shaping platform should implement its own.'
def initialize_shaping_system(self):
raise NotImplementedError('Subclass should implement this')
'Initialize the logging subsystem.'
def set_logger(self):
self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) fmt = logging.Formatter(fmt=logging.BASIC_FORMAT) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(fmt=fmt) self.logger.addHandler(ch) sh = logging.handlers.SysLogHandler(address='/dev/log') sh.setLevel(logging.DEBUG) sh.setFormatter(fmt=fmt) self.logger.addHandler(sh)
'Get the number of devices currently being shaped. Returns: The number of devices currently shaped.'
def getShapedDeviceCount(self):
self.logger.info('Request getShapedDeviceCount') return len(self._ip_to_id_map)
'Start shaping a connection for a given device. Implements the `startShaping` thrift method. If the connection is already being shaped, the shaping will be updated and the old one deleted. Args: A TrafficControl object that contains the device to be shaped, the settings and the timeout. Returns: A TrafficControlRc object with code and message set to reflect success/failure. Raises: A TrafficControlException with code and message set on uncaught exception.'
@AccessCheck def startShaping(self, tc):
self.logger.info('Request startShaping {0}'.format(tc)) try: socket.inet_aton(tc.device.controlledIP) except Exception as e: return TrafficControlRc(code=ReturnCode.INVALID_IP, message='Invalid IP {}'.format(tc.device.controlledIP)) if (tc.timeout < 0): return TrafficControlRc(code=ReturnCode.INVALID_TIMEOUT, message='Invalid Timeout {}'.format(tc.timeout)) new_id = None try: new_id = self.idmanager.new() except Exception as e: return TrafficControlRc(code=ReturnCode.ID_EXHAUST, message='No more session available: {0}'.format(e)) old_id = self._ip_to_id_map.get(tc.device.controlledIP, None) old_settings = self._current_shapings.get(tc.device.controlledIP, {}).get('tc') tcrc = self._shape_interface(new_id, self.wan, tc.device.controlledIP, tc.settings.up) if (tcrc.code != ReturnCode.OK): return tcrc tcrc = self._shape_interface(new_id, self.lan, tc.device.controlledIP, tc.settings.down) if (tcrc.code != ReturnCode.OK): self._unshape_interface(new_id, self.wan, tc.device.controlledIP, tc.settings.up) return tcrc self._add_mapping(new_id, tc) self.db_task.queue.put(((tc, (tc.timeout + time.time())), 'add_shaping')) if (old_id is not None): self._unshape_interface(old_id, self.wan, tc.device.controlledIP, old_settings.settings.up) self._unshape_interface(old_id, self.lan, tc.device.controlledIP, old_settings.settings.down) del self._id_to_ip_map[old_id] self.idmanager.free(old_id) return TrafficControlRc(code=ReturnCode.OK)
'Stop shaping a connection for a given traffic controlled device. Implements the `stopShaping` thrift method. Args: A TrafficControlledDevice object that contains the shaped device. Returns: A TrafficControlRc object with code and message set to reflect success/failure. Raises: A TrafficControlException with code and message set on uncaught exception.'
@AccessCheck def stopShaping(self, dev):
self.logger.info('Request stopShaping for ip {0}'.format(dev.controlledIP)) try: socket.inet_aton(dev.controlledIP) except Exception as e: return TrafficControlRc(code=ReturnCode.INVALID_IP, message='Invalid IP {0}: {1}'.format(dev.controlledIP, e)) id = self._ip_to_id_map.get(dev.controlledIP, None) shaping = self._current_shapings.get(dev.controlledIP, {}).get('tc') if (id is not None): self._unshape_interface(id, self.wan, dev.controlledIP, shaping.settings.up) self._unshape_interface(id, self.lan, dev.controlledIP, shaping.settings.down) self._del_mapping(id, dev.controlledIP) self.db_task.queue.put((dev.controlledIP, 'remove_shaping')) self.idmanager.free(id) else: return TrafficControlRc(code=ReturnCode.UNKNOWN_SESSION, message='No session for IP {} found'.format(dev.controlledIP)) return TrafficControlRc(code=ReturnCode.OK)
'Unshape traffic for a given IP/setting on a network interface'
def _unshape_interface(self, mark, eth, ip, settings):
raise NotImplementedError('Subclass should implement this')
'Shape traffic for a given IP'
def _shape_interface(self, mark, eth, ip, shaping):
raise NotImplementedError('Subclass should implement this')
'Get the TrafficControl object used to shape a TrafficControlledDevice. Args: dev: a TrafficControlledDevice. Returns: A TrafficControl object representing the current shaping for the device. Raises: A TrafficControlException if there is no TC object for that IP'
def getCurrentShaping(self, dev):
self.logger.info('Request getCurrentShaping for ip {0}'.format(dev.controlledIP)) shaping = self._current_shapings.get(dev.controlledIP, {}).get('tc') if (shaping is None): raise TrafficControlException(code=ReturnCode.UNKNOWN_IP, message='This IP ({0}) is not being shaped'.format(dev.controlledIP)) return shaping
'Adds a mapping from id to IP address and vice versa. It also updates the dict mapping IPs to TrafficControl configs. Args: id: the id to map. tc: the TrafficControl object to map.'
def _add_mapping(self, id, tc):
self._id_to_ip_map[id] = tc.device.controlledIP self._ip_to_id_map[tc.device.controlledIP] = id self._current_shapings[tc.device.controlledIP] = {'tc': tc, 'timeout': (time.time() + tc.timeout)}
'Removes mappings from IP to id and id to IP. Also remove the mapping from IP to TrafficControl configs.'
def _del_mapping(self, id, ip):
try: del self._id_to_ip_map[id] del self._ip_to_id_map[ip] del self._current_shapings[ip] except KeyError: self.logger.exception('Unable to remove key from dict')
'Delete finished procs from the map'
def _cleanup_packet_capture_procs(self):
for (ip, p) in self.ip_to_pcap_proc_map.items(): if ((not p) or (p.poll() is not None)): del self.ip_to_pcap_proc_map[ip]
'Start a tcpdump process to capture packets for an ipaddr. The process will run until the timeout expires or stopPacketCapture() is called. Args: dev: a TrafficControlledDevice. timeout: int Max time for tcpdump process to run. Returns: True if process started ok, otherwise False.'
@AccessCheck def startPacketCapture(self, dev, timeout=3600):
self.logger.info('Request startPacketCapture for ip {0}, timeout {1}'.format(dev.controlledIP, timeout)) start_time = time.time() filename = self._pcap_filename(dev.controlledIP, start_time) cmd = 'timeout {timeout!s}\n {tcpdump} -vvv -s0 -i {eth} -w {filepath} host {ip}'.format(timeout=timeout, tcpdump=self.tcpdump, eth=self.lan['name'], filepath=self._pcap_full_path(filename), ip=dev.controlledIP) umask = os.umask(0) p = Popen(shlex.split(cmd)) os.umask(umask) if (p and (p.poll() is None)): p.pcap = PacketCapture(ip=dev.controlledIP, start_time=start_time, file=PacketCaptureFile(name=filename, url=self._pcap_url(filename), bytes=0), pid=p.pid) self.ip_to_pcap_proc_map[dev.controlledIP] = p return p.pcap else: raise PacketCaptureException(message='Failed to start tcpdump process')
'Stop a tcpdump process that was started with startPacketCapture(). Args: dev: a TrafficControlledDevice. Returns: The HTTP URL for the pcap file or empty string.'
@AccessCheck def stopPacketCapture(self, dev):
self.logger.info('Request stopPacketCapture for ip {0}'.format(dev.controlledIP)) self._cleanup_packet_capture_procs() if (dev.controlledIP in self.ip_to_pcap_proc_map): p = self.ip_to_pcap_proc_map[dev.controlledIP] p.terminate() max_secs = 5 start_time = time.time() while ((p.poll() is None) and ((time.time() - start_time) < max_secs)): time.sleep(0.5) if (p.poll() is None): p.kill() p.pcap.file.bytes = self._pcap_file_size(p.pcap.file.name) return p.pcap else: raise PacketCaptureException(message='No capture proc for given ipaddr')
'Stop all running tcpdump procs.'
def stopAllPacketCaptures(self):
self.logger.info('Request stopAllPacketCaptures') self._cleanup_packet_capture_procs() if self.ip_to_pcap_proc_map: for p in self.ip_to_pcap_proc_map.values(): p.terminate() max_secs = 5 start_time = time.time() while (self.ip_to_pcap_proc_map and ((time.time() - start_time) < max_secs)): time.sleep(0.5) self._cleanup_packet_capture_procs() if self.ip_to_pcap_proc_map: for p in self.ip_to_pcap_proc_map.values(): p.kill()
'List the packet captures available for a given device. Args: dev: a TrafficControlledDevice. Returns: A list of PacketCapture ojbects.'
def listPacketCaptures(self, dev):
ip = dev.controlledIP self.logger.info('Request listPacketCaptures for ip {0}'.format(ip)) pcap_list = [] for filename in os.listdir(self.pcap_dir): if (not filename.endswith('.cap')): continue (file_ip, start_time) = self._pcap_parse_filename(filename) if (not (file_ip == ip)): continue pcap = PacketCapture(ip=ip, start_time=start_time, file=PacketCaptureFile(name=filename, url=self._pcap_url(filename), bytes=self._pcap_file_size(filename))) pcap_list.append(pcap) return pcap_list
'List the running packet captures. Returns: A list of PacketCapture ojbects.'
def listRunningPacketCaptures(self):
self.logger.info('Request listRunningPacketCaptures') pcap_list = [] self._cleanup_packet_capture_procs() for (ip, p) in self.ip_to_pcap_proc_map.items(): p.pcap.file.bytes = self._pcap_file_size(p.pcap.file.name) pcap_list.append(p.pcap) return pcap_list
'Stop shaping that have expired.'
def stop_expired_shapings(self):
expired_devs = [attrs['tc'].device for (ip, attrs) in self._current_shapings.iteritems() if (attrs['timeout'] <= time.time())] for dev in expired_devs: self.logger.info('Shaping for Device "{0}" expired'.format(dev)) self.logger.debug('calling stopShaping for "{0}"'.format(dev)) self.stopShaping(dev)
'Returns a unique, random access code. Random token to be given to a host to control the `ip`. The token validity is limited in time. Args: ip: The IP to control. duration: How long the token will be valid for. Returns: An AccessToken.'
def requestToken(self, ip, duration):
self.logger.info('Request requestToken({0}, {1})'.format(ip, duration)) token = self.access_manager.generate_token(ip, duration) return token
'Request to control a remote device. Returns true if the token given is a valid token for the remote IP according to the totp object stored for that IP Args: dev: The TrafficControlledDevice. accessToken: The token to grant access. Returns: True if access is granted, False otherwise.'
def requestRemoteControl(self, dev, accessToken):
self.logger.info('Request requestControl({0}, {1})'.format(dev, accessToken)) access_granted = False try: self.access_manager.validate_token(dev, accessToken) access_granted = True except AccessTokenException: self.logger.exception('Access Denied for request') return access_granted
'Get the devices controlled by a given IP. Args: ip: The IP of the controlling host. Returns: A list of RemoteControlInstance.'
def getDevicesControlledBy(self, ip):
return self.access_manager.get_devices_controlled_by(ip)
'Get the devices controlling a given IP. Args: ip: The IP of the controlled host. Returns: A list of RemoteControlInstance.'
def getDevicesControlling(self, ip):
return self.access_manager.get_devices_controlling(ip)
'Querys the db and returns a list of the TrafficControl objects that are stored there. returns as a list of dicts that have a key for \'tc\' and \'timeout\''
def get_saved_shapings(self):
query = 'SELECT * FROM CurrentShapings' with self._get_conn() as conn: results = conn.execute(query).fetchall() conn.close() shapings = [] for result in results: shapings.append({'tc': result[SQLiteManager.SHAPING_TC_COL], 'timeout': result[SQLiteManager.SHAPING_TIMOUT_COL]}) return shapings
'initialise the id manager class A minimun and maximum ID can be provided at initialisation time.'
def __init__(self, first_id=0, max_id=None):
self.first_id = first_id self.max_id = max_id self.next_available = first_id self.spares = set() self.lock = threading.Lock()
'return an ID to the pool of available IDs'
def free(self, id):
with self.lock: if (id == (self.next_available - 1)): self.next_available -= 1 else: self.spares.add(id)
'claim an ID from the pool of IDs, if no more IDs are available, throw an exception'
def new(self):
with self.lock: try: return self.spares.pop() except: next_avail = self.next_available if ((self.max_id is not None) and (self.next_available > self.max_id)): raise Exception('ID pool exhausted, max id is {0}'.format(self.max_id)) self.next_available += 1 return next_avail
'Returns the time that a code will expire, given a Time object. @param [Time] Time object @return [Time] time the code that would be generated at `for_time` is valid until'
def valid_until(self, for_time):
valid_time = ((self.timecode(for_time) + 1) * self.interval) valid_datetime = datetime.datetime.fromtimestamp(valid_time) return valid_datetime
'takes an ip to generate an AccessToken for and a duration that the remote device will be granted control of the ip once the token is used'
def generate_token(self, ip, duration):
totp_dict = self._ip_to_totp_map.get(ip) if (totp_dict is None): totp = AtcdTOTP(interval=self.ACCESS_TOKEN_INTERVAL, s=pyotp.random_base32()) self._ip_to_totp_map[ip] = {'totp': totp, 'duration': duration} else: totp = totp_dict.get('totp') if (duration != totp_dict.get('duration')): totp_dict['duration'] = duration self._ip_to_totp_map[ip] = totp_dict timestamp = datetime.datetime.now() return AccessToken(token=totp.at(timestamp), interval=self.ACCESS_TOKEN_INTERVAL, valid_until=time.mktime(totp.valid_until(timestamp).timetuple()))
'takes a TrafficControlDevice and an AccessToken and if that device and token are a valid combo, stores the time dev.controllingIP has access internally for lookup later. This either returns None on success or raises an AccessTokenException on failure'
def validate_token(self, dev, access_token):
if (not (dev.controllingIP == dev.controlledIP)): totp_dict = self._ip_to_totp_map.get(dev.controlledIP, {}) totp = totp_dict.get('totp') duration = totp_dict.get('duration') if (not (totp and duration)): raise AccessTokenException("That remote device hasn't generated a code yet") if totp.verify(access_token.token): timeout = (time.time() + duration) self._control_allowed[_dev_to_tuple(dev)] = timeout else: raise AccessTokenException('Access denied for device pair')
'Decides whether or not dev.controllingIP has access to control dev.controlledIP @returns boolean'
def access_allowed(self, dev):
if (not self.secure): return True if (dev.controllingIP == dev.controlledIP): return True dev_tuple = _dev_to_tuple(dev) timeout = self._control_allowed.get(dev_tuple) if timeout: if (timeout > time.time()): return True else: del self._control_allowed[dev_tuple] return False
'Implementation for atcd.getDevicesControlledBy'
def get_devices_controlled_by(self, ip):
now = time.time() def is_valid(key, val): return ((key[0] == ip) and (val > now)) return [_remote_control_instance(key, val) for (key, val) in self._control_allowed.items() if is_valid(key, val)]
'Implementation for atcd.getDevicesControlling'
def get_devices_controlling(self, ip):
now = time.time() def is_valid(key, val): return ((key[1] == ip) and (val > now)) return [_remote_control_instance(key, val) for (key, val) in self._control_allowed.items() if is_valid(key, val)]
'Parameters: - tc'
def startShaping(self, tc):
pass
'Parameters: - device'
def stopShaping(self, device):
pass
'Parameters: - device'
def getCurrentShaping(self, device):
pass
'Parameters: - device'
def isShaped(self, device):
pass
'Parameters: - device - timeout'
def startPacketCapture(self, device, timeout):
pass
'Parameters: - device'
def stopPacketCapture(self, device):
pass
'Parameters: - device'
def listPacketCaptures(self, device):
pass
'Parameters: - ip - duration'
def requestToken(self, ip, duration):
pass
'Parameters: - device - accessToken'
def requestRemoteControl(self, device, accessToken):
pass
'Parameters: - ip'
def getDevicesControlledBy(self, ip):
pass
'Parameters: - ip'
def getDevicesControlling(self, ip):
pass
'Parameters: - tc'
def startShaping(self, tc):
self.send_startShaping(tc) return self.recv_startShaping()
'Parameters: - device'
def stopShaping(self, device):
self.send_stopShaping(device) return self.recv_stopShaping()
'Parameters: - device'
def getCurrentShaping(self, device):
self.send_getCurrentShaping(device) return self.recv_getCurrentShaping()
'Parameters: - device'
def isShaped(self, device):
self.send_isShaped(device) return self.recv_isShaped()
'Parameters: - device - timeout'
def startPacketCapture(self, device, timeout):
self.send_startPacketCapture(device, timeout) return self.recv_startPacketCapture()
'Parameters: - device'
def stopPacketCapture(self, device):
self.send_stopPacketCapture(device) return self.recv_stopPacketCapture()
'Parameters: - device'
def listPacketCaptures(self, device):
self.send_listPacketCaptures(device) return self.recv_listPacketCaptures()
'Parameters: - ip - duration'
def requestToken(self, ip, duration):
self.send_requestToken(ip, duration) return self.recv_requestToken()
'Parameters: - device - accessToken'
def requestRemoteControl(self, device, accessToken):
self.send_requestRemoteControl(device, accessToken) return self.recv_requestRemoteControl()
'Parameters: - ip'
def getDevicesControlledBy(self, ip):
self.send_getDevicesControlledBy(ip) return self.recv_getDevicesControlledBy()
'Parameters: - ip'
def getDevicesControlling(self, ip):
self.send_getDevicesControlling(ip) return self.recv_getDevicesControlling()
'Get the current shaping for an IP. If address is None, defaults to the client IP @return the current shaping applied or 404 if the IP is not being shaped'
@serviced def get(self, request, service, address=None, format=None):
device_serializer = DeviceSerializer(data=request.data, context={'request': request, 'address': address}) if (not device_serializer.is_valid()): raise ParseError(detail=device_serializer.errors) dev = device_serializer.save() try: tc = service.getCurrentShaping(dev) except TrafficControlException as e: return Response({'detail': e.message}, status=status.HTTP_404_NOT_FOUND) serializer = SettingSerializer(tc.settings) return Response(serializer.data, status=status.HTTP_200_OK)
'Set shaping for an IP. If address is None, defaults to the client IP @return the profile that was set on success'
@serviced def post(self, request, service, address=None, format=None):
setting_serializer = SettingSerializer(data=request.data) device_serializer = DeviceSerializer(data=request.data, context={'request': request, 'address': address}) if (not setting_serializer.is_valid()): raise ParseError(detail=setting_serializer.errors) if (not device_serializer.is_valid()): raise ParseError(detail=device_serializer.errors) setting = setting_serializer.save() device = device_serializer.save() tc = TrafficControl(device=device, settings=setting, timeout=atc_api_settings.DEFAULT_TC_TIMEOUT) try: tcrc = service.startShaping(tc) except TrafficControlException as e: return Response(e.message, status=status.HTTP_401_UNAUTHORIZED) result = {'result': tcrc.code, 'message': tcrc.message} if tcrc.code: raise ParseError(detail=result) return Response(setting_serializer.data, status=status.HTTP_201_CREATED)
'Delete the shaping for an IP, if no IP is specified, default to the client IP'
@serviced def delete(self, request, service, address=None, format=None):
device_serializer = DeviceSerializer(data=request.data, context={'request': request, 'address': address}) if (not device_serializer.is_valid()): return Response(device_serializer.errors, status=status.HTTP_400_BAD_REQUEST) device = device_serializer.save() try: tcrc = service.stopShaping(device) except TrafficControlException as e: return Response(e.message, status=status.HTTP_401_UNAUTHORIZED) result = {'result': tcrc.code, 'message': tcrc.message} if tcrc.code: raise ParseError(detail=result) return Response(status=status.HTTP_204_NO_CONTENT)
'Returns the addresses that the provided address is allowed to shape.'
@serviced def get(self, request, service, address=None):
if (address is None): address = get_client_ip(request) controlled_ips = [] for addr in service.getDevicesControlledBy(address): if (addr is None): break controlled_ips.append({'controlled_ip': addr.device.controlledIP, 'valid_until': addr.timeout}) data = {'address': address, 'controlled_ips': controlled_ips} return Response(data, status=status.HTTP_200_OK)
'Authorizes one address to shape another address, based on the provided auth token.'
@serviced def post(self, request, service, address=None):
if (address is None): return Response({'details': 'no address provided'}, status=status.HTTP_400_BAD_REQUEST) controlled_ip = address controlling_ip = get_client_ip(request) if ('token' not in request.data): token = None else: token = AccessToken(token=request.data['token']) dev = TrafficControlledDevice(controlledIP=controlled_ip, controllingIP=controlling_ip) worked = service.requestRemoteControl(dev, token) if (not worked): return Response({'details': 'invalid token provided'}, status=status.HTTP_401_UNAUTHORIZED) print 'Worked:', worked data = {'controlling_ip': controlling_ip, 'controlled_ip': controlled_ip} return Response(data, status=status.HTTP_200_OK)
'Returns the current authorization token for the provided address.'
@serviced def get(self, request, service):
duration = (((3 * 24) * 60) * 60) if ('duration' in request.query_params): duration = int(request.query_params['duration']) address = get_client_ip(request) stuff = service.requestToken(address, duration) data = {'token': stuff.token, 'interval': stuff.interval, 'valid_until': stuff.valid_until, 'address': address} return Response(data, status=status.HTTP_200_OK)
'String representation of the element :param bool pointer: Print pointers :param bool trait: Print traits :param bool frame: Print frames :param int indent: Indention :return: String representation of the element :rtype: str'
def text(self, pointer, trait, frame, indent):
indent_string = (' | ' * indent) return '{}{}\n'.format(indent_string, self.element.summary(pointer=pointer, trait=trait, frame=frame))
'String representation of the hierarchy of elements :param bool pointer: Print pointers :param bool trait: Print traits :param bool frame: Print frames :param int indent: Indention :return: String representation of the hierarchy of elements :rtype: str'
def hierarchy_text(self, pointer=False, trait=False, frame=False, indent=0):
s = self.text(pointer=pointer, trait=trait, frame=frame, indent=indent) for e in self.children: s += e.hierarchy_text(pointer=pointer, trait=trait, frame=frame, indent=(indent + 1)) return s
':param lldb.SBValue element: XCElementSnapshot object :param language: Project language'
def __init__(self, element, language):
super(XCElementSnapshot, self).__init__() self.element = element self.element_value = self.element.GetValue() self.language = language self._type = None self._traits = None self._frame = None self._identifier = None self._value = None self._placeholderValue = None self._label = None self._title = None self._children = None self._enabled = None self._selected = None self._isMainWindow = None self._hasKeyboardFocus = None self._hasFocus = None self._generation = None self._horizontalSizeClass = None self._verticalSizeClass = None
'Checks if element has a label but doesn\'t have an identifier. :return: True if element has a label but doesn\'t have an identifier. :rtype: bool'
@property def is_missing_identifier(self):
return ((len(self.identifier_value) == 0) and (len(self.label_value) > 0))
':return: XCUIElement type / XCUIElementType :rtype: lldb.SBValue'
@property def type(self):
if (self._type is None): name = '_elementType' if (self.element.GetIndexOfChildWithName(name) == NOT_FOUND): self._type = fb.evaluateExpressionValue('(int)[{} elementType]'.format(self.element_value)) else: self._type = self.element.GetChildMemberWithName(name) return self._type
':return: XCUIElementType value :rtype: int'
@property def type_value(self):
return int(self.type.GetValue())
':return: XCUIElementType summary :rtype: str'
@property def type_summary(self):
return self.get_type_value_string(self.type_value)