def action_cancel_order(self, resource, context, form): try: resource.make_transition('open_to_cancel', None) except WorkflowError, excp: log_error(excp.message, domain='ikaaro') context.message = ERROR(unicode(excp.message, 'utf-8')) return
def handle_request(self, soup_message, path): # (1) If path is null => 400 Bad Request if path is None: log_warning('Unexpected HTTP path (null)', domain='itools.web') return set_response(soup_message, 400) # (2) Attach to the soup message and path context = self() context.soup_message = soup_message context.path = path # (3) Get the method that will handle the request method_name = soup_message.get_method() method = getattr(context, 'http_%s' % method_name.lower(), None) # 501 Not Implemented if method is None: log_warning('Unexpected "%s" HTTP method' % method_name, domain='itools.web') return set_response(soup_message, 501) # (4) Go set_context(context) try: method() except StandardError: log_error('Internal error', domain='itools.web') return set_response(soup_message, 500) finally: set_context(None)
def application(environ, start_response): from ikaaro.server import get_server t0 = time() server = get_server() with server.database.init_context(commit_at_exit=False) as context: try: # Init context from wsgi envrion context.init_from_environ(environ) # Handle the request RequestMethod.handle_request(context) t1 = time() # Compute request time context.request_time = t1-t0 # Callback at end of request context.on_request_end() except StandardError: log_error('Internal error', domain='itools.web') context.set_default_response(500) finally: headers = context.header_response if context.content_type: headers.append(('Content-Type', context.content_type)) if context.entity: headers.append(('Content-Length', str(len(context.entity)))) status = context.status or 500 status = '{0} {1}'.format(status, reason_phrases[status]) start_response(str(status), headers) yield context.entity
def action_change_order_state(self, resource, context, form): try: resource.make_transition(form['transition'], form['comments']) except WorkflowError, excp: log_error(excp.message, domain='ikaaro') context.message = ERROR(unicode(excp.message, 'utf-8')) return
def cron_manager(self): database = self.database # Build fake context context = get_fake_context(database, self.root.context_cls) context.server = self context.init_context() context.is_cron = True # Go query = RangeQuery('next_time_event', None, context.timestamp) for brain in database.search(query).get_documents(): payload = pickle.loads(brain.next_time_event_payload) resource = database.get_resource(brain.abspath) try: resource.time_event(payload) except Exception: # Log error log_error('Cron error\n' + format_exc()) context.root.alert_on_internal_server_error(context) # Reindex resource without committing catalog = database.catalog catalog.unindex_document(str(resource.abspath)) catalog.index_document(resource.get_catalog_values()) catalog.save_changes() # Save changes database.save_changes() # Again, and again return self.config.get_value('cron-interval')
def __get__(self, instance, owner): try: value = self.meth(owner) except Exception as e: msg = 'Error on proto property:\n' log_error(msg + str(e), domain='itools.core') raise return value
def cron_manager(self): database = self.database error = False # Build fake context with database.init_context() as context: context.is_cron = True context.git_message = u'[CRON]' # Go t0 = time() catalog = database.catalog query = RangeQuery('next_time_event', None, context.timestamp) search = database.search(query) if not search: return self.config.get_value('cron-interval') nb = len(search) msg = 'Cron launched for {nb} resources'.format(nb=nb) log_info(msg, domain='itools.cron') for brain in search.get_documents(): tcron0 = time() payload = brain.next_time_event_payload if payload: payload = pickle.loads(payload) resource = database.get_resource(brain.abspath) try: resource.time_event(payload) except Exception: # Log error log_error('Cron error\n' + format_exc()) context.root.alert_on_internal_server_error(context) # Abort changes database.abort_changes() # With error error = True break # Reindex resource without committing values = resource.get_catalog_values() catalog.index_document(values) catalog.save_changes() # Log tcron1 = time() msg = 'Done for %s in %s seconds' % (brain.abspath, tcron1-tcron0) log_info(msg, domain='itools.cron') # Save changes if not error: try: database.save_changes() except Exception: log_error('Cron error on save changes\n' + format_exc()) context.root.alert_on_internal_server_error(context) # Message t1 = time() if not error: msg = '[OK] Cron finished for {nb} resources in {s} seconds'.format(nb=nb, s=t1-t0) else: msg = '[ERROR] Cron finished for {nb} resources in {s} seconds'.format(nb=nb, s=t1-t0) log_info(msg, domain='itools.cron') # Again, and again return self.config.get_value('cron-interval')
def action_update(self): """ Launch update methods on every ikaaro instance. """ for ikaaro in config.get_sections_by_type('ikaaro'): if ikaaro.options['pyenv'] == self.name: try: ikaaro.update() except EnvironmentError as e: log_error('[ERROR] ' + str(e))
def __get__(self, instance, owner): name = self.__name__ for cls in owner.__mro__: if name in cls.__dict__: name = self.meth.func_name try: value = self.meth(owner) except Exception as e: msg = 'Error on proto lazy property:\n' log_error(msg + str(e), domain='itools.core') raise setattr(owner, name, value) return value
def get_host(self): user, server, path = self.location if server == 'localhost': return local if config.options.offline: log_error('Error: this action is not available in offline mode') exit(1) server = config.get_section('server', server) host = server.options['host'] shell = bool(int(self.options.get('shell', '0'))) return get_remote_host(host, user, shell)
def save_changes(self): if not self.has_changed: return # Prepare for commit, do here the most you can, if something fails # the transaction will be aborted try: data = self._before_commit() except Exception: log_error('Transaction failed', domain='itools.database') try: self._abort_changes() except Exception: log_error('Aborting failed', domain='itools.database') self._cleanup() raise # Commit try: self._save_changes(data) except Exception: log_error('Transaction failed', domain='itools.database') try: self._abort_changes() except Exception: log_error('Aborting failed', domain='itools.database') raise finally: self._cleanup()
def reset_to_tag(self, tag_name): worktree = self.worktree try: # Reset the tree to the given tag name worktree.git_reset(tag_name) # Remove the tag worktree.git_remove_tag(tag_name) except Exception: log_error('Transaction failed', domain='itools.database') try: self._abort_changes() except Exception: log_error('Aborting failed', domain='itools.database') raise
def action_test(self): """ Test if ikaaro instances of this Python environment are alive""" for ikaaro in config.get_sections_by_type('ikaaro'): if ikaaro.options['pyenv'] == self.name: uri = ikaaro.options['uri'] for i in range(1, 6): try: lfs.open('{}/;_ctrl'.format(uri)) except Exception: log_error('[ERROR {}/5] {}'.format(i, uri)) sleep(0.5) else: log_info('[OK] {}'.format(uri)) break
def save_changes(self, commit_message=None): if not self.has_changed: return # Prepare for commit, do here the most you can, if something fails # the transaction will be aborted try: data = self._before_commit() except Exception: log_error('Transaction failed', domain='itools.database') try: self._abort_changes() except Exception: log_error('Aborting failed', domain='itools.database') self._cleanup() raise # Commit try: self._save_changes(data, commit_message) except Exception as e: log_error('Transaction failed', domain='itools.database') try: self._abort_changes() except Exception: log_error('Aborting failed', domain='itools.database') raise (e) finally: self._cleanup()
def lookup(namespace, name): # Case 1: dict if type(namespace) is dict: if name not in namespace: raise STLError return namespace[name] # Case 2: instance try: value = getattr(namespace, name) except AttributeError: log_error('lookup failed', domain='itools.stl') raise STLError if type(value) is MethodType: value = value() return value
def lookup(namespace, name): # Case 1: dict if type(namespace) is dict: if name not in namespace: err = u"name '{}' not found in the namespace" raise STLError(err.format(name)) return namespace[name] # Case 2: instance try: value = getattr(namespace, name) except AttributeError: log_error('lookup failed', domain='itools.stl') err = "name '{}' not found in the namespace" raise STLError, err.format(name) if type(value) is MethodType: value = value() return value
def path_callback(self, soup_message, path): # (1) Get the class that will handle the request method_name = soup_message.get_method() method = methods.get(method_name) # 501 Not Implemented if method is None: log_warning('Unexpected "%s" HTTP method' % method_name, domain="itools.web") return set_response(soup_message, 501) # (2) Initialize the context context = Context(soup_message, path) self.init_context(context) # (3) Pass control to the Get method class try: method.handle_request(self, context) except Exception: log_error("Failed to handle request", domain="itools.web") set_response(soup_message, 500)
def path_callback(self, soup_message, path): # (1) Get the class that will handle the request method_name = soup_message.get_method() method = methods.get(method_name) # 501 Not Implemented if method is None: log_warning('Unexpected "%s" HTTP method' % method_name, domain='itools.web') return set_response(soup_message, 501) # (2) Initialize the context context = Context(soup_message, path) self.init_context(context) # (3) Pass control to the Get method class try: method.handle_request(self, context) except Exception: log_error('Failed to handle request', domain='itools.web') set_response(soup_message, 500)
def internal_server_error(cls, context): log_error('Internal Server Error', domain='itools.web') context.status = 500 context.set_content_type('text/html', charset='UTF-8') context.entity = context.root.internal_server_error(context)
def smtp_log_error(self): summary = 'Error sending email\n' details = format_exc() log_error(summary + details)
def internal_server_error(cls, server, context): log_error("Internal Server Error", domain="itools.web") context.status = 500 context.entity = server.root.internal_server_error(context)
def internal_server_error(cls, context): log_error('Internal Server Error', domain='itools.web') context.status = 500 context.entity = context.root.internal_server_error(context)