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 param...
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 AP...
'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): ...
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, url...
'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 c...
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 co...
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 ...
'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 c...
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...
'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 ha...
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_cla...
'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'])): ...
'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:', shap...
'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)): ...
'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...
'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....
'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(RT...
'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(...
'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...
'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'], m...
'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 m...
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'], m...
'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. ...
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.me...
'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. et...
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}, m...
'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)) ...
'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...
'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: ...
'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/lo...
'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 obje...
@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 Traffic...
'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 m...
@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_...
'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 sha...
'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} -vv...
'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.ti...
'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()...
'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...
'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(d...
'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') ...
'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]}...
'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))...
'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('dur...
'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 g...
'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_...
'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 TrafficCon...
'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()): ...
'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...
'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': ...
'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['tok...
'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_un...
'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...
'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: 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)