code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
link = FILTER_MAPS['link'][source] html = soup.find_all('link', {link['key']: link['pattern']}) if link['type'] == 'url': for line in html: data['url'] = line.get('href') else: for line in html: data['images'].append({ 'src': urljoin(url, line.get('href')), 'type': link['type'], })
def _filter_link_tag_data(self, source, soup, data, url)
This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS`` :param source: The key of the meta dictionary in ``FILTER_MAPS['link']`` :type source: string :param soup: BeautifulSoup instance to find meta tags :type soup: instance :param data: The response dictionary to manipulate :type data: (dict) :param url: URL used for making an absolute url :type url: string
3.934626
3.084819
1.275481
all_images = soup.find_all('img') for image in all_images: item = normalize_image_data(image, url) data['images'].append(item)
def _find_all_images(self, soup, data, url)
This method finds all images in the web page content :param soup: BeautifulSoup instance to find meta tags :type soup: instance :param data: The response dictionary to manipulate :type data: (dict)
4.137154
4.599367
0.899505
try: headers = decode_header(value) except email.errors.HeaderParseError: return str_decode(str_encode(value, default_charset, 'replace'), default_charset) else: for index, (text, charset) in enumerate(headers): logger.debug("Mail header no. {index}: {data} encoding {charset}".format( index=index, data=str_decode(text, charset or 'utf-8', 'replace'), charset=charset)) try: headers[index] = str_decode(text, charset or default_charset, 'replace') except LookupError: # if the charset is unknown, force default headers[index] = str_decode(text, default_charset, 'replace') return ''.join(headers)
def decode_mail_header(value, default_charset='us-ascii')
Decode a header value into a unicode string.
3.030164
3.067595
0.987798
headers = [h for h in message.get_all(header_name, [])] addresses = email.utils.getaddresses(headers) for index, (address_name, address_email) in enumerate(addresses): addresses[index] = {'name': decode_mail_header(address_name), 'email': address_email} logger.debug("{} Mail address in message: <{}> {}".format( header_name.upper(), address_name, address_email)) return addresses
def get_mail_addresses(message, header_name)
Retrieve all email addresses from one message header.
3.341279
3.350729
0.99718
if len(headers) == 0: return [] if sys.version_info[0] == 3: headers = bytes(headers, "ascii") return list(imaplib.ParseFlags(headers))
def parse_flags(headers)
Copied from https://github.com/girishramnani/gmail/blob/master/gmail/message.py
4.287761
3.245653
1.321078
if self.count >= random.randint(DharmaConst.VARIABLE_MIN, DharmaConst.VARIABLE_MAX): return "%s%d" % (self.var, random.randint(1, self.count)) var = random.choice(self) prefix = self.eval(var[0], state) suffix = self.eval(var[1], state) self.count += 1 element_name = "%s%d" % (self.var, self.count) self.default += "%s%s%s\n" % (prefix, element_name, suffix) return element_name
def generate(self, state)
Return a random variable if any, otherwise create a new default variable.
3.99482
3.727165
1.071812
logging.debug("Using configuration from: %s", settings.name) exec(compile(settings.read(), settings.name, 'exec'), globals(), locals())
def process_settings(self, settings)
A lazy way of feeding Dharma with configuration settings.
6.984201
6.048973
1.154609
out, end = [], 0 token = token.replace("\\n", "\n") for m in re.finditer(self.xref_registry, token, re.VERBOSE | re.DOTALL): if m.start(0) > end: out.append(String(token[end:m.start(0)], self.current_obj)) end = m.end(0) if m.group("type"): xref_type = {"+": ValueXRef, "!": VariableXRef, "@": ElementXRef}[m.group("type")] out.append(xref_type(m.group("xref"), self.current_obj)) elif m.group("uri") is not None: path = m.group("uri") out.append(MetaURI(path, self.current_obj)) elif m.group("repeat") is not None: repeat, separator, nodups = m.group("repeat", "separator", "nodups") if separator is None: separator = "" if nodups is None: nodups = "" out.append(MetaRepeat(self.parse_xrefs(repeat), separator, nodups, self.current_obj)) elif m.group("block") is not None: path = m.group("block") out.append(MetaBlock(path, self.current_obj)) elif m.group("choices") is not None: choices = m.group("choices") out.append(MetaChoice(choices, self.current_obj)) else: startval, endval = m.group("start", "end") out.append(MetaRange(startval, endval, self.current_obj)) if end < len(token): out.append(String(token[end:], self.current_obj)) return out
def parse_xrefs(self, token)
Search token for +value+ and !variable! style references. Be careful to not xref a new variable.
2.438311
2.365331
1.030854
for i, token in enumerate(tokens): if isinstance(token, ElementXRef): variable = token.value break else: logging.error("%s: Variable assignment syntax error", self.id()) sys.exit(-1) if variable != self.current_obj.ident: logging.error("%s: Variable name mismatch", self.id()) sys.exit(-1) if not isinstance(self.current_obj, DharmaVariable): logging.error("%s: Inconsistent object for variable assignment", self.id()) sys.exit(-1) prefix, suffix = tokens[:i], tokens[i + 1:] # pylint: disable=undefined-loop-variable self.current_obj.append((prefix, suffix))
def parse_assign_variable(self, tokens)
Example: tokens dharma.String: 'let ', dharma.ElementXRef: 'GrammarNS:<VarName>', dharma.String: '= new ', dharma.ValueXRef: 'GrammarNS:<ValueName>'
3.845521
3.164486
1.215212
reverse_xref = {} leaves = set() for v in self.value.values(): if v.leaf: leaves.add(v) for xref in v.value_xref: reverse_xref.setdefault(xref, []).append(v.ident) for leaf in leaves: self.calculate_leaf_path(leaf, reverse_xref)
def calculate_leaf_paths(self)
Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
4.058947
3.046192
1.332466
# Setup pre-conditions. if not self.variance: logging.error("%s: No variance information %s", self.id(), self.variance) sys.exit(-1) for var in self.variable.values(): var.clear() # Handle variances variances = [] for _ in range(random.randint(DharmaConst.VARIANCE_MIN, DharmaConst.VARIANCE_MAX)): var = random.choice(list(self.variance.values())) variances.append(DharmaConst.VARIANCE_TEMPLATE % var.generate(GenState())) variances.append("\n") # Handle variables variables = [] for var in self.variable.values(): if var.default: variables.append(DharmaConst.VARIANCE_TEMPLATE % var.default) variables.append("\n") # Build content content = "".join(chain([self.prefix], variables, variances, [self.suffix])) if self.template: return Template(self.template).safe_substitute(testcase_content=content) return content
def generate_content(self)
Generates a test case as a string.
4.272002
3.949264
1.081721
for path in self.default_grammars: grammars.insert(0, open(os.path.relpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.normcase(path))))) for fo in grammars: logging.debug("Processing grammar content of %s", fo.name) self.set_namespace(os.path.splitext(os.path.basename(fo.name))[0]) for line in fo: self.parse_line(line) self.handle_empty_line() self.resolve_xref() self.calculate_leaf_paths()
def process_grammars(self, grammars)
Process provided grammars by parsing them into Python objects.
4.020743
3.910742
1.028128
try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response( 'admin_tools/dashboard/preferences_form.html', {'form': form} )
def set_preferences(request, dashboard_id)
This view serves and validates a preferences form.
1.77044
1.791221
0.988399
if menu is None: menu = get_admin_menu(context) menu.init_with_context(context) has_bookmark_item = False bookmark = None if len([c for c in menu.children if isinstance(c, items.Bookmarks)]) > 0: has_bookmark_item = True url = context['request'].get_full_path() try: bookmark = Bookmark.objects.filter( user=context['request'].user, url=url )[0] except: pass context.update({ 'template': menu.template, 'menu': menu, 'has_bookmark_item': has_bookmark_item, 'bookmark': bookmark, 'admin_url': reverse('%s:index' % get_admin_site_name(context)), }) return context
def admin_tools_render_menu(context, menu=None)
Template tag that renders the menu, it takes an optional ``Menu`` instance as unique argument, if not given, the menu will be retrieved with the ``get_admin_menu`` function.
2.671599
2.693781
0.991765
item.init_with_context(context) context.update({ 'template': item.template, 'item': item, 'index': index, 'selected': item.is_selected(context['request']), 'admin_url': reverse('%s:index' % get_admin_site_name(context)), }) return context
def admin_tools_render_menu_item(context, item, index=None)
Template tag that renders a given menu item, it takes a ``MenuItem`` instance as unique parameter.
3.496988
3.762249
0.929494
if menu is None: menu = get_admin_menu(context) context.update({ 'template': 'admin_tools/menu/css.html', 'css_files': menu.Media.css, }) return context
def admin_tools_render_menu_css(context, menu=None)
Template tag that renders the menu css files,, it takes an optional ``Menu`` instance as unique argument, if not given, the menu will be retrieved with the ``get_admin_menu`` function.
3.732671
3.781599
0.987061
css = getattr(settings, 'ADMIN_TOOLS_THEMING_CSS', False) if not css: css = '/'.join(['admin_tools', 'css', 'theming.css']) return mark_safe( '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % staticfiles_storage.url(css) )
def render_theming_css()
Template tag that renders the needed css files for the theming app.
3.016702
2.870799
1.050823
if request.method == "POST": form = BookmarkForm(user=request.user, data=request.POST) if form.is_valid(): bookmark = form.save() if not request.is_ajax(): messages.success(request, 'Bookmark added') if request.POST.get('next'): return HttpResponseRedirect(request.POST.get('next')) return HttpResponse('Added') return render_to_response( 'admin_tools/menu/remove_bookmark_form.html', {'bookmark': bookmark, 'url': bookmark.url} ) else: form = BookmarkForm(user=request.user) return render_to_response( 'admin_tools/menu/form.html', {'form': form, 'title': 'Add Bookmark'} )
def add_bookmark(request)
This view serves and validates a bookmark form. If requested via ajax it also returns the drop bookmark form to replace the add bookmark form.
2.068084
2.047889
1.009861
bookmark = get_object_or_404(Bookmark, id=id, user=request.user) if request.method == "POST": bookmark.delete() if not request.is_ajax(): messages.success(request, 'Bookmark removed') if request.POST.get('next'): return HttpResponseRedirect(request.POST.get('next')) return HttpResponse('Deleted') return render_to_response( 'admin_tools/menu/add_bookmark_form.html', { 'url': request.POST.get('next'), 'title': '**title**' # replaced on the javascript side } ) return render_to_response( 'admin_tools/menu/delete_confirm.html', {'bookmark': bookmark, 'title': 'Delete Bookmark'} )
def remove_bookmark(request, id)
This view deletes a bookmark. If requested via ajax it also returns the add bookmark form to replace the drop bookmark form.
2.830086
2.775184
1.019783
import imp from django.conf import settings try: from importlib import import_module except ImportError: # Django < 1.9 and Python < 2.7 from django.utils.importlib import import_module blacklist.append('admin_tools.dashboard') blacklist.append('admin_tools.menu') blacklist.append('admin_tools.theming') for app in settings.INSTALLED_APPS: # skip blacklisted apps if app in blacklist: continue # try to import the app try: app_path = import_module(app).__path__ except AttributeError: continue # try to find a app.dashboard module try: imp.find_module('dashboard', app_path) except ImportError: continue # looks like we found it so import it ! import_module('%s.dashboard' % app)
def autodiscover(blacklist=[])
Automagically discover custom dashboards and menus for installed apps. Optionally you can pass a ``blacklist`` of apps that you don't want to provide their own app index dashboard.
2.57117
2.577404
0.997581
ret = ['dashboard-module'] if not self.enabled: ret.append('disabled') if self.draggable: ret.append('draggable') if self.collapsible: ret.append('collapsible') if self.deletable: ret.append('deletable') ret += self.css_classes return ' '.join(ret)
def render_css_classes(self)
Return a string containing the css classes for the module. >>> mod = DashboardModule(enabled=False, draggable=True, ... collapsible=True, deletable=True) >>> mod.render_css_classes() 'dashboard-module disabled draggable collapsible deletable' >>> mod.css_classes.append('foo') >>> mod.render_css_classes() 'dashboard-module disabled draggable collapsible deletable foo' >>> mod.enabled = True >>> mod.render_css_classes() 'dashboard-module draggable collapsible deletable foo'
2.933823
1.917408
1.530099
if super(Group, self).is_empty(): return True for child in self.children: if not child.is_empty(): return False return True
def is_empty(self)
A group of modules is considered empty if it has no children or if all its children are empty. >>> from admin_tools.dashboard.modules import DashboardModule, LinkList >>> mod = Group() >>> mod.is_empty() True >>> mod.children.append(DashboardModule()) >>> mod.is_empty() True >>> mod.children.append(LinkList('links', children=[ ... {'title': 'example1', 'url': 'http://example.com'}, ... {'title': 'example2', 'url': 'http://example.com'}, ... ])) >>> mod.is_empty() False
3.091484
2.960264
1.044327
if location == 'index': return get_index_dashboard(context) elif location == 'app_index': return get_app_index_dashboard(context) raise ValueError('Invalid dashboard location: "%s"' % location)
def get_dashboard(context, location)
Returns the dashboard that match the given ``location`` (index or app_index).
2.967438
2.224669
1.333879
# this is a mess, needs cleanup ! app = context['app_list'][0] model_list = [] app_label = None app_title = app['name'] admin_site = get_admin_site(context=context) for model, model_admin in admin_site._registry.items(): if app['app_label'] == model._meta.app_label: split = model.__module__.find(model._meta.app_label) app_label = model.__module__[0:split] + model._meta.app_label for m in app['models']: if m['name'] == capfirst(model._meta.verbose_name_plural): mod = '%s.%s' % (model.__module__, model.__name__) model_list.append(mod) # if an app has registered its own dashboard, use it if app_label is not None and app_label in Registry.registry: return Registry.registry[app_label](app_title, model_list) # try to discover a general app_index dashboard (with fallback to the # default dashboard) return _get_dashboard_cls(getattr( settings, 'ADMIN_TOOLS_APP_INDEX_DASHBOARD', 'admin_tools.dashboard.dashboards.DefaultAppIndexDashboard' ), context)(app_title, model_list)
def get_app_index_dashboard(context)
Returns the admin dashboard defined by the user or the default one.
3.708616
3.668882
1.01083
models = [] for m in self.models: mod, cls = m.rsplit('.', 1) mod = import_module(mod) models.append(getattr(mod, cls)) return models
def get_app_model_classes(self)
Helper method that returns a list of model classes for the current app.
2.621265
2.469184
1.061592
# Import this here to silence RemovedInDjango19Warning. See #15 from django.contrib.contenttypes.models import ContentType return [ContentType.objects.get_for_model(c) for c in self.get_app_model_classes()]
def get_app_content_types(self)
Return a list of all content_types for this app.
6.035448
5.181947
1.164707
if dashboard is None: dashboard = get_dashboard(context, location) dashboard.init_with_context(context) dashboard._prepare_children() try: preferences = DashboardPreferences.objects.get( user=context['request'].user, dashboard_id=dashboard.get_id() ).data except DashboardPreferences.DoesNotExist: preferences = '{}' try: DashboardPreferences( user=context['request'].user, dashboard_id=dashboard.get_id(), data=preferences ).save() except IntegrityError: # dashboard already was saved for that (user, dashboard) pass context.update({ 'template': dashboard.template, 'dashboard': dashboard, 'dashboard_preferences': preferences, 'split_at': math.ceil( float(len(dashboard.children)) / float(dashboard.columns) ), 'has_disabled_modules': len( [m for m in dashboard.children if not m.enabled] ) > 0, 'admin_url': reverse('%s:index' % get_admin_site_name(context)), }) return context
def admin_tools_render_dashboard(context, location='index', dashboard=None)
Template tag that renders the dashboard, it takes two optional arguments: ``location`` The location of the dashboard, it can be 'index' (for the admin index dashboard) or 'app_index' (for the app index dashboard), the default value is 'index'. ``dashboard`` An instance of ``Dashboard``, if not given, the dashboard is retrieved with the ``get_index_dashboard`` or ``get_app_index_dashboard`` functions, depending on the ``location`` argument.
3.207256
3.399672
0.943401
module.init_with_context(context) context.update({ 'template': module.template, 'module': module, 'admin_url': reverse('%s:index' % get_admin_site_name(context)), }) return context
def admin_tools_render_dashboard_module(context, module)
Template tag that renders a given dashboard module, it takes a ``DashboardModule`` instance as first parameter.
3.732152
4.592712
0.812625
if dashboard is None: dashboard = get_dashboard(context, location) context.update({ 'template': 'admin_tools/dashboard/css.html', 'css_files': dashboard.Media.css, }) return context
def admin_tools_render_dashboard_css( context, location='index', dashboard=None)
Template tag that renders the dashboard css files, it takes two optional arguments: ``location`` The location of the dashboard, it can be 'index' (for the admin index dashboard) or 'app_index' (for the app index dashboard), the default value is 'index'. ``dashboard`` An instance of ``Dashboard``, if not given, the dashboard is retrieved with the ``get_index_dashboard`` or ``get_app_index_dashboard`` functions, depending on the ``location`` argument.
3.532653
5.367438
0.658164
current_url = request.get_full_path() return self.url == current_url or \ len([c for c in self.children if c.is_selected(request)]) > 0
def is_selected(self, request)
Helper method that returns ``True`` if the menu item is active. A menu item is considered as active if it's URL or one of its descendants URL is equals to the current URL.
3.317135
2.93249
1.131167
items = self._visible_models(context['request']) apps = {} for model, perms in items: if not (perms['change'] or perms.get('view', False)): continue app_label = model._meta.app_label if app_label not in apps: apps[app_label] = { 'title': django_apps.get_app_config(app_label).verbose_name, 'url': self._get_admin_app_list_url(model, context), 'models': [] } apps[app_label]['models'].append({ 'title': model._meta.verbose_name_plural, 'url': self._get_admin_change_url(model, context) }) for app in sorted(apps.keys()): app_dict = apps[app] item = MenuItem(title=app_dict['title'], url=app_dict['url']) # sort model list alphabetically apps[app]['models'].sort(key=lambda x: x['title']) for model_dict in apps[app]['models']: item.children.append(MenuItem(**model_dict)) self.children.append(item)
def init_with_context(self, context)
Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class.
2.381603
2.281452
1.043898
items = self._visible_models(context['request']) for model, perms in items: if not (perms['change'] or perms.get('view', False)): continue title = model._meta.verbose_name_plural url = self._get_admin_change_url(model, context) item = MenuItem(title=title, url=url) self.children.append(item)
def init_with_context(self, context)
Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class.
4.037042
3.855882
1.046983
from admin_tools.menu.models import Bookmark for b in Bookmark.objects.filter(user=context['request'].user): self.children.append(MenuItem(mark_safe(b.title), b.url)) if not len(self.children): self.enabled = False
def init_with_context(self, context)
Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class.
4.761484
4.205109
1.132309
if app_name in _cache: return _cache[app_name] template_dir = None for app in apps.get_app_configs(): if app.label == app_name: template_dir = join(app.path, 'templates') break _cache[app_name] = template_dir return template_dir
def get_app_template_dir(app_name)
Get the template directory for an application Uses apps interface available in django 1.7+ Returns a full path, or None if the app was not found.
1.985201
2.183719
0.909092
if ':' not in template_name: return [] app_name, template_name = template_name.split(":", 1) template_dir = get_app_template_dir(app_name) if template_dir: try: from django.template import Origin origin = Origin( name=join(template_dir, template_name), template_name=template_name, loader=self, ) except (ImportError, TypeError): origin = join(template_dir, template_name) return [origin] return []
def get_template_sources(self, template_name, template_dirs=None)
Returns the absolute paths to "template_name" in the specified app. If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take care of the actual loading for us.
2.749252
2.511037
1.094867
id = 1 new_value = value while new_value in seen_values: new_value = "%s%s" % (value, id) id += 1 seen_values.add(new_value) return new_value
def uniquify(value, seen_values)
Adds value to seen_values set and ensures it is unique
1.995579
1.878969
1.06206
items = [] admin_site = get_admin_site(request=request) for model, model_admin in admin_site._registry.items(): perms = model_admin.get_model_perms(request) if True not in perms.values(): continue items.append((model, perms,)) return items
def get_avail_models(request)
Returns (model, perm,) for all models user can possibly see
2.870507
2.590896
1.107921
items = get_avail_models(request) included = [] def full_name(model): return '%s.%s' % (model.__module__, model.__name__) # I beleive that that implemented # O(len(patterns)*len(matched_patterns)*len(all_models)) # algorythm is fine for model lists because they are small and admin # performance is not a bottleneck. If it is not the case then the code # should be optimized. if len(models) == 0: included = items else: for pattern in models: wildcard_models = [] for item in items: model, perms = item model_str = full_name(model) if model_str == pattern: # exact match included.append(item) elif fnmatch(model_str, pattern) and \ item not in wildcard_models: # wildcard match, put item in separate list so it can be # sorted alphabetically later wildcard_models.append(item) if wildcard_models: # sort wildcard matches alphabetically before adding them wildcard_models.sort( key=lambda x: x[0]._meta.verbose_name_plural ) included += wildcard_models result = included[:] for pattern in exclude: for item in included: model, perms = item if fnmatch(full_name(model), pattern): try: result.remove(item) except ValueError: # if the item was already removed skip pass return result
def filter_models(request, models, exclude)
Returns (model, perm,) for all models that match models/exclude patterns and are visible by current user.
4.262907
4.191586
1.017015
app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,))
def _get_admin_app_list_url(self, model, context)
Returns the admin change url.
3.318582
2.993007
1.108779
app_label = model._meta.app_label return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context), app_label, model.__name__.lower()))
def _get_admin_change_url(self, model, context)
Returns the admin change url.
2.90539
2.707503
1.073088
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) self.receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.receiver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.receiver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) self.receiver_socket.bind(('', MCAST_PORT)) mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) self.receiver_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) if not self.socket or not self.receiver_socket: raise exception.ConnectFailedException()
def attempt_connection(self)
Establish a multicast connection - uses 2 sockets (one for sending, the other for receiving)
1.531999
1.444905
1.060277
frame_type = f.cmd.lower() if frame_type in ['disconnect']: return if frame_type == 'send': frame_type = 'message' f.cmd = 'MESSAGE' if frame_type in ['connected', 'message', 'receipt', 'error', 'heartbeat']: if frame_type == 'message': if f.headers['destination'] not in self.subscriptions.values(): return (f.headers, f.body) = self.notify('before_message', f.headers, f.body) self.notify(frame_type, f.headers, f.body) if 'receipt' in f.headers: receipt_frame = Frame('RECEIPT', {'receipt-id': f.headers['receipt']}) lines = convert_frame(receipt_frame) self.send(encode(pack(lines))) log.debug("Received frame: %r, headers=%r, body=%r", f.cmd, f.headers, f.body)
def process_frame(self, f, frame_str)
:param Frame f: Frame object :param bytes frame_str: Raw frame content
4.089363
4.071439
1.004402
self.transport.start()
def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers)
:param str username: :param str passcode: :param bool wait: :param dict headers: :param keyword_headers:
66.003433
74.241013
0.889043
self.transport.subscriptions[id] = destination
def subscribe(self, destination, id, ack='auto', headers=None, **keyword_headers)
:param str destination: :param str id: :param str ack: :param dict headers: :param keyword_headers:
13.034926
22.12302
0.589202
Protocol12.disconnect(self, receipt, headers, **keyword_headers) self.transport.stop()
def disconnect(self, receipt=None, headers=None, **keyword_headers)
:param str receipt: :param dict headers: :param keyword_headers:
7.221163
9.141191
0.789959
if headers is None: headers = {} frame = utils.Frame(cmd, headers, body) if cmd == CMD_BEGIN: trans = headers[HDR_TRANSACTION] if trans in self.transactions: self.notify('error', {}, 'Transaction %s already started' % trans) else: self.transactions[trans] = [] elif cmd == CMD_COMMIT: trans = headers[HDR_TRANSACTION] if trans not in self.transactions: self.notify('error', {}, 'Transaction %s not started' % trans) else: for f in self.transactions[trans]: self.transport.transmit(f) del self.transactions[trans] elif cmd == CMD_ABORT: trans = headers['transaction'] del self.transactions[trans] else: if 'transaction' in headers: trans = headers['transaction'] if trans not in self.transactions: self.transport.notify('error', {}, 'Transaction %s not started' % trans) return else: self.transactions[trans].append(frame) else: self.transport.transmit(frame)
def send_frame(self, cmd, headers=None, body='')
:param str cmd: :param dict headers: :param body:
2.126364
2.176088
0.97715
thread = threading.Thread(None, callback) thread.daemon = True # Don't let thread prevent termination thread.start() return thread
def default_create_thread(callback)
Default thread creation - used to create threads when the client doesn't want to provide their own thread creation. :param function callback: the callback function provided to threading.Thread
4.131225
6.289228
0.656873
headers = {} for header_line in lines[offset:]: header_match = HEADER_LINE_RE.match(header_line) if header_match: key = header_match.group('key') key = re.sub(r'\\.', _unescape_header, key) if key not in headers: value = header_match.group('value') value = re.sub(r'\\.', _unescape_header, value) headers[key] = value return headers
def parse_headers(lines, offset=0)
Parse the headers in a STOMP response :param list(str) lines: the lines received in the message response :param int offset: the starting line number :rtype: dict(str,str)
2.235553
2.365923
0.944897
f = Frame() if frame == b'\x0a': f.cmd = 'heartbeat' return f mat = PREAMBLE_END_RE.search(frame) if mat: preamble_end = mat.start() body_start = mat.end() else: preamble_end = len(frame) body_start = preamble_end preamble = decode(frame[0:preamble_end]) preamble_lines = LINE_END_RE.split(preamble) preamble_len = len(preamble_lines) f.body = frame[body_start:] # Skip any leading newlines first_line = 0 while first_line < preamble_len and len(preamble_lines[first_line]) == 0: first_line += 1 if first_line >= preamble_len: return None # Extract frame type/command f.cmd = preamble_lines[first_line] # Put headers into a key/value map f.headers = parse_headers(preamble_lines, first_line + 1) return f
def parse_frame(frame)
Parse a STOMP frame into a Frame object. :param bytes frame: the frame received from the server (as a byte string) :rtype: Frame
3.031318
3.077531
0.984984
headers = {} for header_map in header_map_list: if header_map: headers.update(header_map) return headers
def merge_headers(header_map_list)
Helper function for combining multiple header maps into one. :param list(dict) header_map_list: list of maps :rtype: dict
2.346391
2.840128
0.826157
(sx, sy) = shb (cx, cy) = chb x = 0 y = 0 if cx != 0 and sy != '0': x = max(cx, int(sy)) if cy != 0 and sx != '0': y = max(cy, int(sx)) return x, y
def calculate_heartbeats(shb, chb)
Given a heartbeat string from the server, and a heartbeat tuple from the client, calculate what the actual heartbeat settings should be. :param (str,str) shb: server heartbeat numbers :param (int,int) chb: client heartbeat numbers :rtype: (int,int)
3.179691
3.156417
1.007374
lines = [] body = None if frame.body: if body_encoding: body = encode(frame.body, body_encoding) else: body = encode(frame.body) if HDR_CONTENT_LENGTH in frame.headers: frame.headers[HDR_CONTENT_LENGTH] = len(body) if frame.cmd: lines.append(encode(frame.cmd)) lines.append(ENC_NEWLINE) for key, vals in sorted(frame.headers.items()): if vals is None: continue if type(vals) != tuple: vals = (vals,) for val in vals: lines.append(encode("%s:%s\n" % (key, val))) lines.append(ENC_NEWLINE) if body: lines.append(body) if frame.cmd: lines.append(ENC_NULL) return lines
def convert_frame(frame, body_encoding=None)
Convert a frame to a list of lines separated by newlines. :param Frame frame: the Frame object to convert :rtype: list(str)
2.594622
2.661939
0.974711
Protocol10.disconnect(self, receipt, headers, **keyword_headers) self.transport.stop()
def disconnect(self, receipt=None, headers=None, **keyword_headers)
Call the protocol disconnection, and then stop the transport itself. :param str receipt: the receipt to use with the disconnect :param dict headers: a map of any additional headers to send with the disconnection :param keyword_headers: any additional headers to send with the disconnection
6.496724
8.828448
0.735885
Protocol11.disconnect(self, receipt, headers, **keyword_headers) self.transport.stop()
def disconnect(self, receipt=None, headers=None, **keyword_headers)
Call the protocol disconnection, and then stop the transport itself. :param str receipt: the receipt to use with the disconnect :param dict headers: a map of any additional headers to send with the disconnection :param keyword_headers: any additional headers to send with the disconnection
6.590714
8.999455
0.732346
if type(char_data) is str: return char_data.encode(encoding, errors='replace') elif type(char_data) is bytes: return char_data else: raise TypeError('message should be a string or bytes, found %s' % type(char_data))
def encode(char_data, encoding='utf-8')
Encode the parameter as a byte string. :param char_data: the data to encode :rtype: bytes
2.426794
2.687092
0.90313
if type(char_data) is unicode: return char_data.encode(encoding, 'replace') else: return char_data
def encode(char_data, encoding='utf-8')
Encode the parameter as a byte string. :param char_data: :rtype: bytes
2.563989
3.062938
0.837101
if 'heart-beat' in headers: self.heartbeats = utils.calculate_heartbeats( headers['heart-beat'].replace(' ', '').split(','), self.heartbeats) if self.heartbeats != (0, 0): self.send_sleep = self.heartbeats[0] / 1000 # by default, receive gets an additional grace of 50% # set a different heart-beat-receive-scale when creating the connection to override that self.receive_sleep = (self.heartbeats[1] / 1000) * self.heart_beat_receive_scale log.debug("Setting receive_sleep to %s", self.receive_sleep) # Give grace of receiving the first heartbeat self.received_heartbeat = monotonic() + self.receive_sleep self.running = True if self.heartbeat_thread is None: self.heartbeat_thread = utils.default_create_thread( self.__heartbeat_loop) self.heartbeat_thread.name = "StompHeartbeat%s" % \ getattr(self.heartbeat_thread, "name", "Thread")
def on_connected(self, headers, body)
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats are not 0, we start up the heartbeat loop accordingly. :param dict headers: headers in the connection message :param body: the message body
5.30266
4.934635
1.07458
if frame.cmd == CMD_CONNECT or frame.cmd == CMD_STOMP: if self.heartbeats != (0, 0): frame.headers[HDR_HEARTBEAT] = '%s,%s' % self.heartbeats if self.next_outbound_heartbeat is not None: self.next_outbound_heartbeat = monotonic() + self.send_sleep
def on_send(self, frame)
Add the heartbeat header to the frame when connecting, and bump next outbound heartbeat timestamp. :param Frame frame: the Frame object
4.985047
4.206603
1.185053
log.info('Starting heartbeat loop') now = monotonic() # Setup the initial due time for the outbound heartbeat if self.send_sleep != 0: self.next_outbound_heartbeat = now + self.send_sleep while self.running: now = monotonic() next_events = [] if self.next_outbound_heartbeat is not None: next_events.append(self.next_outbound_heartbeat - now) if self.receive_sleep != 0: t = self.received_heartbeat + self.receive_sleep - now if t > 0: next_events.append(t) sleep_time = min(next_events) if sleep_time > 0: terminate = self.heartbeat_terminate_event.wait(sleep_time) if terminate: break now = monotonic() if not self.transport.is_connected(): time.sleep(self.send_sleep) continue if self.send_sleep != 0 and now > self.next_outbound_heartbeat: log.debug("Sending a heartbeat message at %s", now) try: self.transport.transmit(utils.Frame(None, {}, None)) except exception.NotConnectedException: log.debug("Lost connection, unable to send heartbeat") except Exception: _, e, _ = sys.exc_info() log.debug("Unable to send heartbeat, due to: %s", e) if self.receive_sleep != 0: diff_receive = now - self.received_heartbeat if diff_receive > self.receive_sleep: # heartbeat timeout log.warning("Heartbeat timeout: diff_receive=%s, time=%s, lastrec=%s", diff_receive, now, self.received_heartbeat) self.transport.set_connected(False) self.transport.disconnect_socket() self.transport.stop() for listener in self.transport.listeners.values(): listener.on_heartbeat_timeout() self.heartbeat_thread = None log.info('Heartbeat loop ended')
def __heartbeat_loop(self)
Main loop for sending (and monitoring received) heartbeats.
3.160058
3.118487
1.013331
if 'receipt-id' in headers and headers['receipt-id'] == self.receipt: with self.receipt_condition: self.received = True self.receipt_condition.notify()
def on_receipt(self, headers, body)
If the receipt id can be found in the headers, then notify the waiting thread. :param dict headers: headers in the message :param body: the message content
3.803776
3.703018
1.02721
with self.receipt_condition: while not self.received: self.receipt_condition.wait() self.received = False
def wait_on_receipt(self)
Wait until we receive a message receipt.
4.283626
3.345509
1.280411
if log.isEnabledFor(logging.DEBUG): log.debug("received an error %s [%s]", body, headers) else: log.info("received an error %s", body) self.errors += 1
def on_error(self, headers, body)
Increment the error count. See :py:meth:`ConnectionListener.on_error` :param dict headers: headers in the message :param body: the message content
3.385314
3.743304
0.904365
log.info("connecting %s %s (x %s)", host_and_port[0], host_and_port[1], self.connections) self.connections += 1
def on_connecting(self, host_and_port)
Increment the connection count. See :py:meth:`ConnectionListener.on_connecting` :param (str,int) host_and_port: the host and port as a tuple
3.994561
4.418553
0.904043
print('on_send %s %s %s' % (frame.cmd, frame.headers, frame.body))
def on_send(self, frame)
:param Frame frame:
5.07326
4.505223
1.126084
frame = utils.Frame(cmd, headers, body) self.transport.transmit(frame)
def send_frame(self, cmd, headers=None, body='')
Encode and send a stomp frame through the underlying transport. :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message
7.510192
9.045649
0.830255
assert transaction is not None, "'transaction' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_TRANSACTION] = transaction self.send_frame(CMD_ABORT, headers)
def abort(self, transaction, headers=None, **keyword_headers)
Abort a transaction. :param str transaction: the identifier of the transaction :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
4.969215
5.442982
0.912958
assert id is not None, "'id' is required" headers = {HDR_MESSAGE_ID: id} if transaction: headers[HDR_TRANSACTION] = transaction if receipt: headers[HDR_RECEIPT] = receipt self.send_frame(CMD_ACK, headers)
def ack(self, id, transaction=None, receipt=None)
Acknowledge 'consumption' of a message by id. :param str id: identifier of the message :param str transaction: include the acknowledgement in the specified transaction
3.061419
3.725553
0.821736
headers = utils.merge_headers([headers, keyword_headers]) if not transaction: transaction = utils.get_uuid() headers[HDR_TRANSACTION] = transaction self.send_frame(CMD_BEGIN, headers) return transaction
def begin(self, transaction=None, headers=None, **keyword_headers)
Begin a transaction. :param str transaction: the identifier for the transaction (optional - if not specified a unique transaction id will be generated) :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires :return: the transaction id :rtype: str
4.762887
4.887878
0.974428
assert transaction is not None, "'transaction' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_TRANSACTION] = transaction self.send_frame(CMD_COMMIT, headers)
def commit(self, transaction=None, headers=None, **keyword_headers)
Commit a transaction. :param str transaction: the identifier for the transaction :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
5.102454
5.402798
0.94441
if not self.transport.is_connected(): log.debug('Not sending disconnect, already disconnected') return headers = utils.merge_headers([headers, keyword_headers]) rec = receipt or utils.get_uuid() headers[HDR_RECEIPT] = rec self.set_receipt(rec, CMD_DISCONNECT) self.send_frame(CMD_DISCONNECT, headers)
def disconnect(self, receipt=None, headers=None, **keyword_headers)
Disconnect from the server. :param str receipt: the receipt to use (once the server acknowledges that receipt, we're officially disconnected; optional - if not specified a unique receipt id will be generated) :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
5.174473
5.479046
0.944411
assert destination is not None, "'destination' is required" assert body is not None, "'body' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_DESTINATION] = destination if content_type: headers[HDR_CONTENT_TYPE] = content_type if self.auto_content_length and body and HDR_CONTENT_LENGTH not in headers: headers[HDR_CONTENT_LENGTH] = len(body) self.send_frame(CMD_SEND, headers, body)
def send(self, destination, body, content_type=None, headers=None, **keyword_headers)
Send a message to a destination. :param str destination: the destination of the message (e.g. queue or topic name) :param body: the content of the message :param str content_type: the content type of the message :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
2.534903
2.699469
0.939038
assert destination is not None, "'destination' is required" headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_DESTINATION] = destination if id: headers[HDR_ID] = id headers[HDR_ACK] = ack self.send_frame(CMD_SUBSCRIBE, headers)
def subscribe(self, destination, id=None, ack='auto', headers=None, **keyword_headers)
Subscribe to a destination. :param str destination: the topic or queue to subscribe to :param str id: a unique id to represent the subscription :param str ack: acknowledgement mode, either auto, client, or client-individual (see http://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_ack_Header) for more information :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
3.023811
3.427271
0.882279
assert id is not None or destination is not None, "'id' or 'destination' is required" headers = utils.merge_headers([headers, keyword_headers]) if id: headers[HDR_ID] = id if destination: headers[HDR_DESTINATION] = destination self.send_frame(CMD_UNSUBSCRIBE, headers)
def unsubscribe(self, destination=None, id=None, headers=None, **keyword_headers)
Unsubscribe from a destination by either id or the destination name. :param str destination: the name of the topic or queue to unsubscribe from :param str id: the unique identifier of the topic or queue to unsubscribe from :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
3.302716
3.330226
0.991739
if cmd != CMD_CONNECT: if headers is None: headers = {} self._escape_headers(headers) frame = utils.Frame(cmd, headers, body) self.transport.transmit(frame)
def send_frame(self, cmd, headers=None, body='')
Encode and send a stomp frame through the underlying transport: :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message
5.636301
6.066148
0.92914
cmd = CMD_STOMP headers = utils.merge_headers([headers, keyword_headers]) headers[HDR_ACCEPT_VERSION] = self.version if self.transport.vhost: headers[HDR_HOST] = self.transport.vhost if username is not None: headers[HDR_LOGIN] = username if passcode is not None: headers[HDR_PASSCODE] = passcode self.send_frame(cmd, headers) if wait: self.transport.wait_for_connection() if self.transport.connection_error: raise ConnectFailedException()
def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers)
Start a connection. :param str username: the username to connect with :param str passcode: the password used to authenticate with :param bool wait: if True, wait for the connection to be established/acknowledged :param dict headers: a map of any additional headers the broker requires :param keyword_headers: any additional headers the broker requires
3.413848
3.496392
0.976392
assert id is not None, "'id' is required" assert subscription is not None, "'subscription' is required" headers = {HDR_MESSAGE_ID: id, HDR_SUBSCRIPTION: subscription} if transaction: headers[HDR_TRANSACTION] = transaction if receipt: headers[HDR_RECEIPT] = receipt self.send_frame(CMD_NACK, headers)
def nack(self, id, subscription, transaction=None, receipt=None)
Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str subscription: the subscription this message is associated with :param str transaction: include this nack in a named transaction
2.430817
2.55023
0.953176
for key, val in headers.items(): try: val = val.replace('\\', '\\\\').replace('\n', '\\n').replace(':', '\\c').replace('\r', '\\r') except: pass headers[key] = val
def _escape_headers(self, headers)
:param dict(str,str) headers:
3.075926
2.807126
1.095756
assert id is not None, "'id' is required" headers = {HDR_ID: id} if transaction: headers[HDR_TRANSACTION] = transaction if receipt: headers[HDR_RECEIPT] = receipt self.send_frame(CMD_NACK, headers)
def nack(self, id, transaction=None, receipt=None)
Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str transaction: include this nack in a named transaction
3.204924
3.624555
0.884226
for res in getaddrinfo(host, port, 0, SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket(af, socktype, proto) if timeout is not None: sock.settimeout(timeout) sock.connect(sa) return sock except error: if sock is not None: sock.close() raise error
def get_socket(host, port, timeout=None)
Return a socket. :param str host: the hostname to connect to :param int port: the port number to connect to :param timeout: if specified, set the socket timeout
1.578835
2.096554
0.753062
self.running = True self.attempt_connection() receiver_thread = self.create_thread_fc(self.__receiver_loop) receiver_thread.name = "StompReceiver%s" % getattr(receiver_thread, "name", "Thread") self.notify('connecting')
def start(self)
Start the connection. This should be called after all listeners have been registered. If this method is not called, no frames will be received by the connection.
10.291236
9.57439
1.074871
with self.__receiver_thread_exit_condition: while not self.__receiver_thread_exited and self.is_connected(): self.__receiver_thread_exit_condition.wait()
def stop(self)
Stop the connection. Performs a clean shutdown by waiting for the receiver thread to exit.
5.275153
3.999221
1.319045
with self.__connect_wait_condition: self.connected = connected if connected: self.__connect_wait_condition.notify()
def set_connected(self, connected)
:param bool connected:
4.622567
4.034128
1.145865
with self.__listeners_change_condition: self.listeners[name] = listener
def set_listener(self, name, listener)
Set a named listener to use with this connection. See :py:class:`stomp.listener.ConnectionListener` :param str name: the name of the listener :param ConnectionListener listener: the listener object
9.302919
56.159794
0.165651
frame_type = f.cmd.lower() if frame_type in ['connected', 'message', 'receipt', 'error', 'heartbeat']: if frame_type == 'message': (f.headers, f.body) = self.notify('before_message', f.headers, f.body) if log.isEnabledFor(logging.DEBUG): log.debug("Received frame: %r, headers=%r, body=%r", f.cmd, f.headers, f.body) else: log.info("Received frame: %r, len(body)=%r", f.cmd, utils.length(f.body)) self.notify(frame_type, f.headers, f.body) else: log.warning("Unknown response frame type: '%s' (frame length was %d)", frame_type, utils.length(frame_str))
def process_frame(self, f, frame_str)
:param Frame f: Frame object :param bytes frame_str: raw frame content
3.32945
3.2148
1.035663
if frame_type == 'receipt': # logic for wait-on-receipt notification receipt = headers['receipt-id'] receipt_value = self.__receipts.get(receipt) with self.__send_wait_condition: self.set_receipt(receipt, None) self.__send_wait_condition.notify() if receipt_value == CMD_DISCONNECT: self.set_connected(False) # received a stomp 1.1+ disconnect receipt if receipt == self.__disconnect_receipt: self.disconnect_socket() self.__disconnect_receipt = None elif frame_type == 'connected': self.set_connected(True) elif frame_type == 'disconnected': self.set_connected(False) with self.__listeners_change_condition: listeners = sorted(self.listeners.items()) for (_, listener) in listeners: if not listener: continue notify_func = getattr(listener, 'on_%s' % frame_type, None) if not notify_func: log.debug("listener %s has no method on_%s", listener, frame_type) continue if frame_type in ('heartbeat', 'disconnected'): notify_func() continue if frame_type == 'connecting': notify_func(self.current_host_and_port) continue if frame_type == 'error' and not self.connected: with self.__connect_wait_condition: self.connection_error = True self.__connect_wait_condition.notify() rtn = notify_func(headers, body) if rtn: (headers, body) = rtn return (headers, body)
def notify(self, frame_type, headers=None, body=None)
Utility function for notifying listeners of incoming and outgoing messages :param str frame_type: the type of message :param dict headers: the map of headers associated with the message :param body: the content of the message
3.586651
3.555908
1.008646
with self.__listeners_change_condition: listeners = sorted(self.listeners.items()) for (_, listener) in listeners: if not listener: continue try: listener.on_send(frame) except AttributeError: continue if frame.cmd == CMD_DISCONNECT and HDR_RECEIPT in frame.headers: self.__disconnect_receipt = frame.headers[HDR_RECEIPT] lines = utils.convert_frame(frame) packed_frame = pack(lines) if log.isEnabledFor(logging.DEBUG): log.debug("Sending frame: %s", lines) else: log.info("Sending frame: %r", frame.cmd or "heartbeat") self.send(packed_frame)
def transmit(self, frame)
Convert a frame object to a frame string and transmit to the server. :param Frame frame: the Frame object to transmit
5.030027
5.354122
0.939468
if timeout is not None: wait_time = timeout / 10.0 else: wait_time = None with self.__connect_wait_condition: while self.running and not self.is_connected() and not self.connection_error: self.__connect_wait_condition.wait(wait_time) if not self.running or not self.is_connected(): raise exception.ConnectFailedException()
def wait_for_connection(self, timeout=None)
Wait until we've established a connection with the server. :param float timeout: how long to wait, in seconds
3.324434
3.510079
0.947111
log.info("Starting receiver loop") notify_disconnected = True try: while self.running: try: while self.running: frames = self.__read() for frame in frames: f = utils.parse_frame(frame) if f is None: continue if self.__auto_decode: f.body = decode(f.body) self.process_frame(f, frame) except exception.ConnectionClosedException: if self.running: # # Clear out any half-received messages after losing connection # self.__recvbuf = b'' self.running = False notify_disconnected = True break finally: self.cleanup() finally: with self.__receiver_thread_exit_condition: self.__receiver_thread_exited = True self.__receiver_thread_exit_condition.notifyAll() log.info("Receiver loop ended") self.notify('receiver_loop_completed') if notify_disconnected: self.notify('disconnected') with self.__connect_wait_condition: self.__connect_wait_condition.notifyAll()
def __receiver_loop(self)
Main loop listening for incoming data.
3.985015
3.978559
1.001623
fastbuf = BytesIO() while self.running: try: try: c = self.receive() except exception.InterruptedException: log.debug("socket read interrupted, restarting") continue except Exception: log.debug("socket read error", exc_info=True) c = b'' if c is None or len(c) == 0: raise exception.ConnectionClosedException() if c == b'\x0a' and not self.__recvbuf and not fastbuf.tell(): # # EOL to an empty receive buffer: treat as heartbeat. # Note that this may misdetect an optional EOL at end of frame as heartbeat in case the # previous receive() got a complete frame whose NUL at end of frame happened to be the # last byte of that read. But that should be harmless in practice. # fastbuf.close() return [c] fastbuf.write(c) if b'\x00' in c: # # Possible end of frame # break self.__recvbuf += fastbuf.getvalue() fastbuf.close() result = [] if self.__recvbuf and self.running: while True: pos = self.__recvbuf.find(b'\x00') if pos >= 0: frame = self.__recvbuf[0:pos] preamble_end_match = utils.PREAMBLE_END_RE.search(frame) if preamble_end_match: preamble_end = preamble_end_match.start() content_length_match = BaseTransport.__content_length_re.search(frame[0:preamble_end]) if content_length_match: content_length = int(content_length_match.group('value')) content_offset = preamble_end_match.end() frame_size = content_offset + content_length if frame_size > len(frame): # # Frame contains NUL bytes, need to read more # if frame_size < len(self.__recvbuf): pos = frame_size frame = self.__recvbuf[0:pos] else: # # Haven't read enough data yet, exit loop and wait for more to arrive # break result.append(frame) pos += 1 # # Ignore optional EOLs at end of frame # while self.__recvbuf[pos:pos + 1] == b'\x0a': pos += 1 self.__recvbuf = self.__recvbuf[pos:] else: break return result
def __read(self)
Read the next frame(s) from the socket. :return: list of frames read :rtype: list(bytes)
3.658151
3.607882
1.013933
try: return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self) except socket.error: return False
def is_connected(self)
Return true if the socket managed by this connection is connected :rtype: bool
3.804403
3.859329
0.985768
self.running = False if self.socket is not None: if self.__need_ssl(): # # Even though we don't want to use the socket, unwrap is the only API method which does a proper SSL # shutdown # try: self.socket = self.socket.unwrap() except Exception: # # unwrap seems flaky on Win with the back-ported ssl mod, so catch any exception and log it # _, e, _ = sys.exc_info() log.warning(e) elif hasattr(socket, 'SHUT_RDWR'): try: self.socket.shutdown(socket.SHUT_RDWR) except socket.error: _, e, _ = sys.exc_info() # ignore when socket already closed if get_errno(e) != errno.ENOTCONN: log.warning("Unable to issue SHUT_RDWR on socket because of error '%s'", e) # # split this into a separate check, because sometimes the socket is nulled between shutdown and this call # if self.socket is not None: try: self.socket.close() except socket.error: _, e, _ = sys.exc_info() log.warning("Unable to close socket because of error '%s'", e) self.current_host_and_port = None self.socket = None self.notify('disconnected')
def disconnect_socket(self)
Disconnect the underlying socket connection
4.203829
4.110526
1.022698
if self.socket is not None: try: with self.__socket_semaphore: self.socket.sendall(encoded_frame) except Exception: _, e, _ = sys.exc_info() log.error("Error sending frame", exc_info=1) raise e else: raise exception.NotConnectedException()
def send(self, encoded_frame)
:param bytes encoded_frame:
3.416809
3.245437
1.052804
try: return self.socket.recv(self.__recv_bytes) except socket.error: _, e, _ = sys.exc_info() if get_errno(e) in (errno.EAGAIN, errno.EINTR): log.debug("socket read interrupted, restarting") raise exception.InterruptedException() if self.is_connected(): raise
def receive(self)
:rtype: bytes
4.495944
4.158549
1.081133
self.connection_error = False sleep_exp = 1 connect_count = 0 while self.running and self.socket is None and ( connect_count < self.__reconnect_attempts_max or self.__reconnect_attempts_max == -1 ): for host_and_port in self.__host_and_ports: try: log.info("Attempting connection to host %s, port %s", host_and_port[0], host_and_port[1]) self.socket = get_socket(host_and_port[0], host_and_port[1], self.__timeout) self.__enable_keepalive() need_ssl = self.__need_ssl(host_and_port) if need_ssl: # wrap socket ssl_params = self.get_ssl(host_and_port) if ssl_params['ca_certs']: cert_validation = ssl.CERT_REQUIRED else: cert_validation = ssl.CERT_NONE try: tls_context = ssl.create_default_context(cafile=ssl_params['ca_certs']) except AttributeError: tls_context = None if tls_context: # Wrap the socket for TLS certfile = ssl_params['cert_file'] keyfile = ssl_params['key_file'] password = ssl_params.get('password') if certfile and not keyfile: keyfile = certfile if certfile: tls_context.load_cert_chain(certfile, keyfile, password) if cert_validation is None or cert_validation == ssl.CERT_NONE: tls_context.check_hostname = False tls_context.verify_mode = cert_validation self.socket = tls_context.wrap_socket(self.socket, server_hostname=host_and_port[0]) else: # Old-style wrap_socket where we don't have a modern SSLContext (so no SNI) self.socket = ssl.wrap_socket( self.socket, keyfile=ssl_params['key_file'], certfile=ssl_params['cert_file'], cert_reqs=cert_validation, ca_certs=ssl_params['ca_certs'], ssl_version=ssl_params['ssl_version']) self.socket.settimeout(self.__timeout) if self.blocking is not None: self.socket.setblocking(self.blocking) # # Validate server cert # if need_ssl and ssl_params['cert_validator']: cert = self.socket.getpeercert() (ok, errmsg) = ssl_params['cert_validator'](cert, host_and_port[0]) if not ok: raise SSLError("Server certificate validation failed: %s", errmsg) self.current_host_and_port = host_and_port log.info("Established connection to host %s, port %s", host_and_port[0], host_and_port[1]) break except socket.error: self.socket = None connect_count += 1 log.warning("Could not connect to host %s, port %s", host_and_port[0], host_and_port[1], exc_info=1) if self.socket is None: sleep_duration = (min(self.__reconnect_sleep_max, ((self.__reconnect_sleep_initial / (1.0 + self.__reconnect_sleep_increase)) * math.pow(1.0 + self.__reconnect_sleep_increase, sleep_exp))) * (1.0 + random.random() * self.__reconnect_sleep_jitter)) sleep_end = monotonic() + sleep_duration log.debug("Sleeping for %.1f seconds before attempting reconnect", sleep_duration) while self.running and monotonic() < sleep_end: time.sleep(0.2) if sleep_duration < self.__reconnect_sleep_max: sleep_exp += 1 if not self.socket: raise exception.ConnectFailedException()
def attempt_connection(self)
Try connecting to the (host, port) tuples specified at construction time.
2.304512
2.278092
1.011597
if not ssl: raise Exception("SSL connection requested, but SSL library not found") for host_port in for_hosts: self.__ssl_params[host_port] = dict(key_file=key_file, cert_file=cert_file, ca_certs=ca_certs, cert_validator=cert_validator, ssl_version=ssl_version, password=password)
def set_ssl(self, for_hosts=[], key_file=None, cert_file=None, ca_certs=None, cert_validator=None, ssl_version=DEFAULT_SSL_VERSION, password=None)
Sets up SSL configuration for the given hosts. This ensures socket is wrapped in a SSL connection, raising an exception if the SSL module can't be found. :param for_hosts: a list of tuples describing hosts this SSL configuration should be applied to :param cert_file: the path to a X509 certificate :param key_file: the path to a X509 key file :param ca_certs: the path to the a file containing CA certificates to validate the server against. If this is not set, server side certificate validation is not done. :param cert_validator: function which performs extra validation on the client certificate, for example checking the returned certificate has a commonName attribute equal to the hostname (to avoid man in the middle attacks). The signature is: (OK, err_msg) = validation_function(cert, hostname) where OK is a boolean, and cert is a certificate structure as returned by ssl.SSLSocket.getpeercert() :param ssl_version: SSL protocol to use for the connection. This should be one of the PROTOCOL_x constants provided by the ssl module. The default is ssl.PROTOCOL_TLSv1
2.430012
3.109711
0.781427
if not host_and_port: host_and_port = self.current_host_and_port return host_and_port in self.__ssl_params
def __need_ssl(self, host_and_port=None)
Whether current host needs SSL or not. :param (str,int) host_and_port: the host/port pair to check, default current_host_and_port
3.381877
3.487208
0.969795
if not host_and_port: host_and_port = self.current_host_and_port return self.__ssl_params.get(host_and_port)
def get_ssl(self, host_and_port=None)
Get SSL params for the given host. :param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port
3.15714
2.61064
1.209336
if self.__quit: return if self.verbose: self.__sysout(frame_type) for k, v in headers.items(): self.__sysout('%s: %s' % (k, v)) else: if 'message-id' in headers: self.__sysout('message-id: %s' % headers['message-id']) if 'subscription' in headers: self.__sysout('subscription: %s' % headers['subscription']) if self.prompt != '': self.__sysout('') self.__sysout(body) if not self.__start: self.__sysout(self.prompt, end='') else: self.__start = False self.stdout.flush()
def __print_async(self, frame_type, headers, body)
Utility function to print a message and setup the command prompt for the next input
2.566287
2.594296
0.989204
self.__sysout('') if 'filename' in headers: content = base64.b64decode(body.encode()) if os.path.exists(headers['filename']): fname = '%s.%s' % (headers['filename'], int(time.time())) else: fname = headers['filename'] with open(fname, 'wb') as f: f.write(content) self.__print_async("MESSAGE", headers, "Saved file: %s" % fname) else: self.__print_async("MESSAGE", headers, body)
def on_message(self, headers, body)
See :py:meth:`ConnectionListener.on_message` Special case: if the header 'filename' is present, the content is written out as a file
3.125573
3.004019
1.040464
text = unicodedata.normalize('NFC', text) if include_punctuation: return [ token.casefold() for token in TOKEN_RE_WITH_PUNCTUATION.findall(text) ] else: return [ token.strip("'").casefold() for token in TOKEN_RE.findall(text) ]
def simple_tokenize(text, include_punctuation=False)
Tokenize the given text using a straightforward, Unicode-aware token expression. The expression mostly implements the rules of Unicode Annex #29 that are contained in the `regex` module's word boundary matching, including the refinement that splits words between apostrophes and vowels in order to separate tokens such as the French article «l'». It makes sure not to split in the middle of a grapheme, so that zero-width joiners and marks on Devanagari words work correctly. Our customizations to the expression are: - It leaves sequences of Chinese or Japanese characters (specifically, Han ideograms and hiragana) relatively untokenized, instead of splitting each character into its own token. - If `include_punctuation` is False (the default), it outputs only the tokens that start with a word-like character, or miscellaneous symbols such as emoji. If `include_punctuation` is True, it outputs all non-space tokens. - It keeps Southeast Asian scripts, such as Thai, glued together. This yields tokens that are much too long, but the alternative is that every grapheme would end up in its own token, which is worse.
2.769818
3.238294
0.855332