code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
__docformat__ = "reStructuredText" from zope import interface, schema class LinkNotFoundError(ValueError): """Exception raised if a link could not be found for the given parameter.""" class IBrowser(interface.Interface): """A Programmatic Web Browser.""" url = schema.URI( title=u"URL", description=u"The URL the browser is currently showing.", required=True) headers = schema.Field( title=u"Headers", description=(u"Headers of the HTTP response; a " "``httplib.HTTPMessage``."), required=True) contents = schema.Text( title=u"Contents", description=u"The complete response body of the HTTP request.", required=True) isHtml = schema.Bool( title=u"Is HTML", description=u"Tells whether the output is HTML or not.", required=True) title = schema.TextLine( title=u"Base", description=u"Base URL for opening relative paths", required=False) title = schema.TextLine( title=u"Title", description=u"Title of the displayed page", required=False) handleErrors = schema.Bool( title=u"Handle Errors", description=(u"Describes whether server-side errors will be handled " u"by the publisher. If set to ``False``, the error will " u"progress all the way to the test, which is good for " u"debugging."), default=True, required=True) def addHeader(key, value): """Adds a header to each HTTP request. Adding additional headers can be useful in many ways, from setting the credentials token to specifying the browser identification string. """ def open(url, data=None): """Open a URL in the browser. The URL must be fully qualified unless a ``base`` has been provided. The ``data`` argument describes the data that will be sent as the body of the request. """ def reload(): """Reload the current page. Like a browser reload, if the past request included a form submission, the form data will be resubmitted.""" def goBack(count=1): """Go back in history by a certain amount of visisted pages. The ``count`` argument specifies how far to go back. It is set to 1 by default. """ def getLink(text=None, url=None, id=None): """Return an ILink from the page. The link is found by the arguments of the method. One or more may be used together. o ``text`` -- A regular expression trying to match the link's text, in other words everything between <a> and </a> or the value of the submit button. o ``url`` -- The URL the link is going to. This is either the ``href`` attribute of an anchor tag or the action of a form. o ``id`` -- The id attribute of the anchor tag submit button. """ lastRequestSeconds = schema.Field( title=u"Seconds to Process Last Request", description=( u"""Return how many seconds (or fractions) the last request took. The values returned have the same resolution as the results from ``time.clock``. """), required=True, readonly=True) lastRequestPystones = schema.Field( title= u"Approximate System-Independent Effort of Last Request (Pystones)", description=( u"""Return how many pystones the last request took. This number is found by multiplying the number of pystones/second at which this system benchmarks and the result of ``lastRequestSeconds``. """), required=True, readonly=True) def getControl(label=None, name=None, index=None): """Get a control from the page. Only one of ``label`` and ``name`` may be provided. ``label`` searches form labels (including submit button values, per the HTML 4.0 spec), and ``name`` searches form field names. Label value is searched as case-sensitive whole words within the labels for each control--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline. If no values are found, the code raises a LookupError. If ``index`` is None (the default) and more than one field matches the search, the code raises an AmbiguityError. If an index is provided, it is used to choose the index from the ambiguous choices. If the index does not exist, the code raises a LookupError. """ def getForm(id=None, name=None, action=None, index=None): """Get a form from the page. Zero or one of ``id``, ``name``, and ``action`` may be provided. If none are provided the index alone is used to determine the return value. If no values are found, the code raises a LookupError. If ``index`` is None (the default) and more than one form matches the search, the code raises an AmbiguityError. If an index is provided, it is used to choose the index from the ambiguous choices. If the index does not exist, the code raises a LookupError. """ class ExpiredError(Exception): """The browser page to which this was attached is no longer active""" class IControl(interface.Interface): """A control (input field) of a page.""" name = schema.TextLine( title=u"Name", description=u"The name of the control.", required=True) value = schema.Field( title=u"Value", description=u"The value of the control", default=None, required=True) type = schema.Choice( title=u"Type", description=u"The type of the control", values=['text', 'password', 'hidden', 'submit', 'checkbox', 'select', 'radio', 'image', 'file'], required=True) disabled = schema.Bool( title=u"Disabled", description=u"Describes whether a control is disabled.", default=False, required=False) multiple = schema.Bool( title=u"Multiple", description=u"Describes whether this control can hold multiple values.", default=False, required=False) def clear(): """Clear the value of the control.""" class IListControl(IControl): """A radio button, checkbox, or select control""" options = schema.List( title=u"Options", description=u"""\ A list of possible values for the control.""", required=True) displayOptions = schema.List( # TODO: currently only implemented for select by ClientForm title=u"Options", description=u"""\ A list of possible display values for the control.""", required=True) displayValue = schema.Field( # TODO: currently only implemented for select by ClientForm title=u"Value", description=u"The value of the control, as rendered by the display", default=None, required=True) def getControl(label=None, value=None, index=None): """return subcontrol for given label or value, disambiguated by index if given. Label value is searched as case-sensitive whole words within the labels for each item--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline.""" controls = interface.Attribute( """a list of subcontrols for the control. mutating list has no effect on control (although subcontrols may be changed as usual).""") class ISubmitControl(IControl): def click(): "click the submit button" class IImageSubmitControl(ISubmitControl): def click(coord=(1,1,)): "click the submit button with optional coordinates" class IItemControl(interface.Interface): """a radio button or checkbox within a larger multiple-choice control""" control = schema.Object( title=u"Control", description=(u"The parent control element."), schema=IControl, required=True) disabled = schema.Bool( title=u"Disabled", description=u"Describes whether a subcontrol is disabled.", default=False, required=False) selected = schema.Bool( title=u"Selected", description=u"Whether the subcontrol is selected", default=None, required=True) optionValue = schema.TextLine( title=u"Value", description=u"The value of the subcontrol", default=None, required=False) class ILink(interface.Interface): def click(): """click the link, going to the URL referenced""" url = schema.TextLine( title=u"URL", description=u"The normalized URL of the link", required=False) text = schema.TextLine( title=u'Text', description=u'The contained text of the link', required=False) class IForm(interface.Interface): """An HTML form of the page.""" action = schema.TextLine( title=u"Action", description=u"The action (or URI) that is opened upon submittance.", required=True) name = schema.TextLine( title=u"Name", description=u"The value of the `name` attribute in the form tag, " u"if specified.", required=True) id = schema.TextLine( title=u"Id", description=u"The value of the `id` attribute in the form tag, " u"if specified.", required=True) def getControl(label=None, name=None, index=None): """Get a control in the page. Only one of ``label`` and ``name`` may be provided. ``label`` searches form labels (including submit button values, per the HTML 4.0 spec), and ``name`` searches form field names. Label value is searched as case-sensitive whole words within the labels for each control--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline. If no values are found, the code raises a LookupError. If ``index`` is None (the default) and more than one field matches the search, the code raises an AmbiguityError. If an index is provided, it is used to choose the index from the ambiguous choices. If the index does not exist, the code raises a LookupError. """ def submit(label=None, name=None, index=None, coord=(1,1)): """Submit this form. The `label`, `name`, and `index` arguments select the submit button to use to submit the form. You may label or name, with index to disambiguate. Label value is searched as case-sensitive whole words within the labels for each control--that is, a search for 'Add' will match 'Add a contact' but not 'Address'. A word is defined as one or more alphanumeric characters or the underline. The control code works identically to 'get' except that searches are filtered to find only submit and image controls. """ class ITextAreaControl(IControl): """An HTML text area. Mostly just a marker."""
zc.testbrowser
/zc.testbrowser-1.0a1.tar.gz/zc.testbrowser-1.0a1/src/zc/testbrowser/interfaces.py
interfaces.py
import os.path import re import simplejson import socket import telnetlib import time import urlparse import zc.testbrowser.browser import zc.testbrowser.interfaces import zope.interface PROMPT = re.compile('repl\d?> ') class BrowserStateError(RuntimeError): pass class AmbiguityError(ValueError): pass def disambiguate(intermediate, msg, index): if intermediate: if index is None: if len(intermediate) > 1: raise AmbiguityError(msg) else: return intermediate[0] else: try: return intermediate[index] except KeyError: msg = '%s index %d' % (msg, index) raise LookupError(msg) def controlFactory(token, browser, selectionItem=False): tagName = browser.execute('tb_tokens[%s].tagName' % token).lower() if tagName == 'select': return ListControl(token, browser) elif tagName == 'option': return ItemControl(token, browser) inputType = browser.execute('tb_tokens[%s].getAttribute("type")' % token) if inputType is not None: inputType = inputType.lower() if inputType in ('checkbox', 'radio'): if selectionItem: return ItemControl(token, browser) return ListControl(token, browser) elif inputType in ('submit', 'button'): return SubmitControl(token, browser) elif inputType == 'image': return ImageControl(token, browser) return Control(token, browser) class JSFunctionProxy(object): def __init__(self, executor, name): self.executor = executor self.js_name = name def __call__(self, *args): js_args = [simplejson.dumps(a) for a in args] js = '[%s(%s)].toSource()' % ( self.js_name, ', '.join(js_args)) res = self.executor(js) # JS has 'null' and 'undefined', python only has 'None'. # This hack is sufficient for now. if res == '[undefined]': return None return simplejson.loads(res)[0] class JSProxy(object): def __init__(self, executor): self.executor = executor def __getattr__(self, attr): return JSFunctionProxy(self, attr) def __call__(self, js): js = js.strip() if js: return self.executor(js) class Browser(zc.testbrowser.browser.SetattrErrorsMixin): zope.interface.implements(zc.testbrowser.interfaces.IBrowser) base = None raiseHttpErrors = True _counter = 0 timeout = 5 # XXX debug only, change back to 60 def __init__(self, url=None, host='localhost', port=4242): self.js = JSProxy(self.execute) self.timer = zc.testbrowser.browser.PystoneTimer() self.init_repl(host, port) self._enable_setattr_errors = True if url is not None: self.open(url) def init_repl(self, host, port): dir = os.path.dirname(__file__) js_path = os.path.join(dir, 'real.js') try: self.telnet = telnetlib.Telnet(host, port) except socket.error, e: raise RuntimeError('Error connecting to Firefox at %s:%s.' ' Is MozRepl running?' % (host, port)) self.telnet.write(open(js_path, 'rt').read()) self.expect() def execute(self, js): if not js.strip(): return self.telnet.write("'MARKER'") self.telnet.read_until('MARKER', self.timeout) self.expect() self.telnet.write(js) i, match, text = self.expect() if '!!!' in text: import pdb;pdb.set_trace() # XXX debug only, remove #if '!!!' in text: raise Exception('FAILED: ' + js) result = text.rsplit('\n', 1) if len(result) == 1: return None else: return result[0] def executeLines(self, js): lines = js.split('\n') for line in lines: self.execute(line) def getAttribute(self, token, attr_name): return self.getAttributes([token], attr_name)[0] def getAttributes(self, tokens, attr_name): return self.js.tb_extract_token_attrs(tokens, attr_name) def expect(self): i, match, text = self.telnet.expect([PROMPT], self.timeout) if match is None: raise RuntimeError('unexpected result from MozRepl') return i, match, text def _changed(self): self._counter += 1 @property def url(self): return self.execute('content.location') def waitForPageLoad(self): start = time.time() while self.execute('tb_page_loaded') == 'false': time.sleep(0.001) if time.time() - start > self.timeout: raise RuntimeError('timed out waiting for page load') self.execute('tb_page_loaded = false;') def open(self, url, data=None): if self.base is not None: url = urlparse.urljoin(self.base, url) assert data is None self.start_timer() try: self.execute('content.location = ' + simplejson.dumps(url)) self.waitForPageLoad() finally: self.stop_timer() self._changed() # TODO raise non-200 errors @property def isHtml(self): return self.execute('content.document.contentType') == 'text/html' @property def title(self): if not self.isHtml: raise BrowserStateError('not viewing HTML') result = self.execute('content.document.title') if result is '': result = None return result @property def contents(self): return self.execute('content.document.documentElement.innerHTML') @property def headers(self): raise NotImplementedError @apply def handleErrors(): def get(self): raise NotImplementedError def set(self, value): raise NotImplementedError return property(get, set) def start_timer(self): self.timer.start() def stop_timer(self): self.timer.stop() @property def lastRequestPystones(self): return self.timer.elapsedPystones @property def lastRequestSeconds(self): return self.timer.elapsedSeconds def reload(self): self.start_timer() self.execute('content.document.location = content.document.location') self.waitForPageLoad() self.stop_timer() def goBack(self, count=1): self.start_timer() self.execute('content.back()') # Our method of knowing when the page finishes loading doesn't work # for "back", so for now just sleep a little, and hope it is enough. time.sleep(1) self.stop_timer() self._changed() def addHeader(self, key, value): raise NotImplementedError def getLink(self, text=None, url=None, id=None, index=0): zc.testbrowser.browser.onlyOne((text, url, id), 'text, url, or id') js_index = simplejson.dumps(index) if text is not None: msg = 'text %r' % text token = self.js.tb_get_link_by_text(text, index) elif url is not None: msg = 'url %r' % url token = self.js.tb_get_link_by_url(url, index) elif id is not None: msg = 'id %r' % id token = self.js.tb_get_link_by_id(id, index) if token is False: raise zc.testbrowser.interfaces.LinkNotFoundError elif token == 'ambiguity error': raise AmbiguityError(msg) return Link(token, self) def _follow_link(self, token): self.js.tb_follow_link(token) def getControlToken(self, label=None, name=None, index=None, context_token=None, xpath=None): js_index = simplejson.dumps(index) token = None if label is not None: msg = 'label %r' % label token = self.js.tb_get_control_by_label( label, index, context_token, xpath) elif name is not None: msg = 'name %r' % name token = self.js.tb_get_control_by_name( name, index, context_token, xpath) else: raise NotImplementedError if token is False: raise LookupError(msg) elif token == 'ambiguity error': raise AmbiguityError(msg) return token def getControl(self, label=None, name=None, index=None, context_token=None, xpath=None): zc.testbrowser.browser.onlyOne([label, name], '"label" and "name"') token = self.getControlToken(label, name, index, context_token, xpath) selectionItem = False if label is not None: inputType = self.execute( 'tb_tokens[%s].getAttribute("type")' % token) if inputType and inputType.lower() in ('radio', 'checkbox'): selectionItem = True return controlFactory(token, self, selectionItem) def getForm(self, id=None, name=None, action=None, index=None): xpath = '//form' if id is not None: xpath += '[@id=%s]' % repr(id) if name is not None: xpath += '[@name=%s]' % repr(name) matching_tokens = self.js.tb_xpath_tokens(xpath) if index is None and not any([id, name, action]): if len(matching_tokens) == 1: index = 0 else: raise ValueError( 'if no other arguments are given, index is required.') if action is not None: form_actions = self.getAttributes(matching_tokens, 'action') matching_tokens = [tok for tok, form_act in zip(matching_tokens, form_actions) if re.search(action, form_act)] form_token = disambiguate(matching_tokens, '', index) return Form(self, form_token) class Link(zc.testbrowser.browser.SetattrErrorsMixin): zope.interface.implements(zc.testbrowser.interfaces.ILink) def __init__(self, token, browser): self.token = token self.browser = browser self._browser_counter = self.browser._counter self._enable_setattr_errors = True def click(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser.start_timer() self.browser._follow_link(self.token) self.browser.stop_timer() self.browser._changed() @property def url(self): return self.browser.execute('tb_tokens[%s].href' % self.token) @property def text(self): return str(self.browser.js.tb_get_link_text(self.token)) def __repr__(self): return "<%s text=%r url=%r>" % ( self.__class__.__name__, self.text, self.url) class Control(zc.testbrowser.browser.SetattrErrorsMixin): """A control of a form.""" zope.interface.implements(zc.testbrowser.interfaces.IControl) _enable_setattr_errors = False def __init__(self, token, browser): self.token = token self.browser = browser self._browser_counter = self.browser._counter self._file = None # disable addition of further attributes self._enable_setattr_errors = True @property def disabled(self): return self.browser.execute( 'tb_tokens[%s].hasAttribute("disabled")' % self.token) == 'true' @property def type(self): if self.browser.execute('tb_tokens[%s].tagName' % self.token).lower() == 'textarea': return 'textarea' return self.browser.execute( 'tb_tokens[%s].getAttribute("type")' % self.token) @property def name(self): return self.browser.execute( 'tb_tokens[%s].getAttribute("name")' % self.token) @property def multiple(self): if self.type == 'file': return False return self.browser.execute( 'tb_tokens[%s].hasAttribute("multiple")' % self.token) == 'true' @apply def value(): def fget(self): if self.type == 'textarea': return self.browser.execute('tb_tokens[%s].innerHTML' % self.token) return self.browser.execute( 'tb_tokens[%s].getAttribute("value")' % self.token) def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError if self.type == 'file': self.add_file(value, content_type=self.content_type, filename=self.filename) elif self.type == 'textarea': self.browser.execute('tb_tokens[%s].innerHTML = %r' % (self.token, value)) elif self.type == 'checkbox' and len(self.mech_control.items) == 1: self.mech_control.items[0].selected = bool(value) else: self.browser.execute( 'tb_tokens[%s].setAttribute("value", %s)' %( self.token, simplejson.dumps(value))) return property(fget, fset) def add_file(self, file, content_type, filename): if not self.type == 'file': raise TypeError("Can't call add_file on %s controls" % self.type) if isinstance(file, str): file = StringIO(file) # HTML only supports ever setting one file for one input control self._file = (file, content_type, filename) @property def filename(self): return self._file[2] @property def content_type(self): return self._file[1] def clear(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.mech_control.clear() def __repr__(self): return "<%s name=%r type=%r>" % ( self.__class__.__name__, self.name, self.type) class ListControl(Control): zope.interface.implements(zc.testbrowser.interfaces.IListControl) @property def type(self): tagName = self.browser.execute( 'tb_tokens[%s].tagName' % self.token).lower() if tagName == 'input': return super(ListControl, self).type return tagName @property def multiple(self): return self.browser.js.tb_is_listcontrol_multiple(self.token) @apply def displayValue(): # not implemented for anything other than select; # would be nice if ClientForm implemented for checkbox and radio. # attribute error for all others. def fget(self): return [str(option) for option in self.browser.js.tb_get_listcontrol_displayValue(self.token)] def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser.js.tb_set_listcontrol_displayValue(self.token, value) return property(fget, fset) @property def acts_as_single(self): return self.browser.js.tb_act_as_single(self.token) @apply def value(): def fget(self): values = self.browser.js.tb_get_listcontrol_value(self.token) if self.acts_as_single: return values[0] return values def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError if self.acts_as_single: # expects a single value self.browser.js.tb_set_checked(self.token, bool(value)) else: # expects a list of control ids self.browser.js.tb_set_listcontrol_value(self.token, value) return property(fget, fset) @property def displayOptions(self): return [str(option) for option in self.browser.js.tb_get_listcontrol_displayOptions(self.token)] @property def options(self): return self.browser.js.tb_get_listcontrol_options(self.token) @property def controls(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError res = [] tokens = self.browser.js.tb_get_listcontrol_item_tokens(self.token) return [ItemControl(token, self.browser) for token in tokens] def getControl(self, label=None, value=None, index=None): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError # XXX: this method is broken and isn't tested return self.browser.getControl( label, value, index, self.token, ".//input | .//option") class SubmitControl(Control): zope.interface.implements(zc.testbrowser.interfaces.ISubmitControl) def click(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser.js.tb_click_token(self.token) self.browser._changed() class ImageControl(Control): zope.interface.implements(zc.testbrowser.interfaces.IImageSubmitControl) def click(self, coord=(1,1)): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser.js.tb_click_token(self.token, *coord) self.browser._changed() @property def value(self): return '' @property def multiple(self): return False class TextAreaControl(Control): zope.interface.implements(zc.testbrowser.interfaces.ITextAreaControl) class ItemControl(zc.testbrowser.browser.SetattrErrorsMixin): zope.interface.implements(zc.testbrowser.interfaces.IItemControl) def __init__(self, token, browser): self.token = token self.browser = browser self._browser_counter = self.browser._counter # disable addition of further attributes self._enable_setattr_errors = True @property def control(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError return controlFactory(self.token, self.browser) @property def disabled(self): return self.browser.execute( 'tb_tokens[%s].hasAttribute("disabled")' % self.token) == 'true' @apply def selected(): def fget(self): return self.browser.js.tb_get_checked(self.token) def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser.js.tb_set_checked(self.token, bool(value)) return property(fget, fset) @property def optionValue(self): v = self.browser.execute( 'tb_tokens[%s].getAttribute("value")' % self.token) if not v and self.selected: v = 'on' return v def click(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.mech_item.selected = not self.mech_item.selected def __repr__(self): tagName = self.browser.execute('tb_tokens[%s].tagName' % self.token) if tagName.lower() == 'option': type = 'select' name = self.browser.execute( 'tb_tokens[%s].parentNode.getAttribute("name")' % self.token) else: type = self.browser.execute( 'tb_tokens[%s].getAttribute("type")' % self.token) name = self.browser.execute( 'tb_tokens[%s].getAttribute("name")' % self.token) return "<%s name=%r type=%r optionValue=%r selected=%r>" % ( self.__class__.__name__, name, type, self.optionValue, self.selected) class Form(zc.testbrowser.browser.SetattrErrorsMixin): """HTML Form""" zope.interface.implements(zc.testbrowser.interfaces.IForm) def __init__(self, browser, token): self.token = token self.browser = browser self._browser_counter = self.browser._counter self._enable_setattr_errors = True @property def action(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError action = self.browser.getAttribute(self.token, 'action') if action: return urlparse.urljoin(self.browser.base, action) return self.browser.url @property def method(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError return self.browser.getAttribute(self.token, 'method').upper() @property def enctype(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError enc = self.browser.execute('tb_tokens[%s].encoding' % self.token) return enc or 'application/x-www-form-urlencoded' @property def name(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError return self.browser.getAttribute(self.token, 'name') @property def id(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError return self.browser.getAttribute(self.token, 'id') def submit(self, label=None, name=None, index=None, coord=(1,1)): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser.start_timer() if (label is None and name is None): self.browser.execute('tb_tokens[%s].submit()' % self.token) else: button = self.browser.getControlToken( label, name, index, self.token) self.browser.js.tb_click_token(button, *coord) self.browser.stop_timer() self.browser._changed() def getControl(self, label=None, name=None, index=None): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError return self.browser.getControl( label, name, index, self.token)
zc.testbrowser
/zc.testbrowser-1.0a1.tar.gz/zc.testbrowser-1.0a1/src/zc/testbrowser/real.py
real.py
__docformat__ = "reStructuredText" from cStringIO import StringIO import ClientForm import mechanize import operator import re import sys import time import urllib2 import urlparse import zc.testbrowser.interfaces import zope.interface RegexType = type(re.compile('')) _compress_re = re.compile(r"\s+") compressText = lambda text: _compress_re.sub(' ', text.strip()) def disambiguate(intermediate, msg, index): if intermediate: if index is None: if len(intermediate) > 1: raise ClientForm.AmbiguityError(msg) else: return intermediate[0] else: try: return intermediate[index] except KeyError: msg = '%s index %d' % (msg, index) raise LookupError(msg) def controlFactory(control, form, browser): if isinstance(control, ClientForm.Item): # it is a subcontrol return ItemControl(control, form, browser) else: t = control.type if t in ('checkbox', 'select', 'radio'): return ListControl(control, form, browser) elif t in ('submit', 'submitbutton'): return SubmitControl(control, form, browser) elif t=='image': return ImageControl(control, form, browser) else: return Control(control, form, browser) def any(items): return bool(sum([bool(i) for i in items])) def onlyOne(items, description): total = sum([bool(i) for i in items]) if total == 0 or total > 1: raise ValueError( "Supply one and only one of %s as arguments" % description) def zeroOrOne(items, description): if sum([bool(i) for i in items]) > 1: raise ValueError( "Supply no more than one of %s as arguments" % description) class SetattrErrorsMixin(object): _enable_setattr_errors = False def __setattr__(self, name, value): if self._enable_setattr_errors: # cause an attribute error if the attribute doesn't already exist getattr(self, name) # set the value object.__setattr__(self, name, value) class PystoneTimer(object): start_time = 0 end_time = 0 _pystones_per_second = None @property def pystonesPerSecond(self): """How many pystones are equivalent to one second on this machine""" # deferred import as workaround for Zope 2 testrunner issue: # http://www.zope.org/Collectors/Zope/2268 from test import pystone if self._pystones_per_second == None: self._pystones_per_second = pystone.pystones(pystone.LOOPS/10)[1] return self._pystones_per_second def _getTime(self): if sys.platform.startswith('win'): # Windows' time.clock gives us high-resolution wall-time return time.clock() else: # everyone else uses time.time return time.time() def start(self): """Begin a timing period""" self.start_time = self._getTime() self.end_time = None def stop(self): """End a timing period""" self.end_time = self._getTime() @property def elapsedSeconds(self): """Elapsed time from calling `start` to calling `stop` or present time If `stop` has been called, the timing period stopped then, otherwise the end is the current time. """ if self.end_time is None: end_time = self._getTime() else: end_time = self.end_time return end_time - self.start_time @property def elapsedPystones(self): """Elapsed pystones in timing period See elapsed_seconds for definition of timing period. """ return self.elapsedSeconds * self.pystonesPerSecond class Browser(SetattrErrorsMixin): """A web user agent.""" zope.interface.implements(zc.testbrowser.interfaces.IBrowser) base = None _contents = None _counter = 0 def __init__(self, url=None, mech_browser=None): if mech_browser is None: mech_browser = mechanize.Browser() self.mech_browser = mech_browser self.timer = PystoneTimer() self.raiseHttpErrors = True self._enable_setattr_errors = True if url is not None: self.open(url) @property def url(self): return self.mech_browser.geturl() @property def isHtml(self): return self.mech_browser.viewing_html() @property def title(self): return self.mech_browser.title() @property def contents(self): if self._contents is not None: return self._contents response = self.mech_browser.response() old_location = response.tell() response.seek(0) self._contents = response.read() response.seek(old_location) return self._contents @property def headers(self): return self.mech_browser.response().info() @apply def handleErrors(): header_key = 'X-zope-handle-errors' def get(self): headers = self.mech_browser.addheaders return dict(headers).get(header_key, True) def set(self, value): headers = self.mech_browser.addheaders current_value = get(self) if current_value == value: return if header_key in dict(headers): headers.remove((header_key, current_value)) headers.append((header_key, value)) return property(get, set) def open(self, url, data=None): if self.base is not None: url = urlparse.urljoin(self.base, url) self._start_timer() try: try: self.mech_browser.open(url, data) except urllib2.HTTPError, e: if e.code >= 200 and e.code <= 299: # 200s aren't really errors pass elif self.raiseHttpErrors: raise finally: self._stop_timer() self._changed() # if the headers don't have a status, I suppose there can't be an error if 'Status' in self.headers: code, msg = self.headers['Status'].split(' ', 1) code = int(code) if self.raiseHttpErrors and code >= 400: raise urllib2.HTTPError(url, code, msg, self.headers, fp=None) def _start_timer(self): self.timer.start() def _stop_timer(self): self.timer.stop() @property def lastRequestPystones(self): return self.timer.elapsedPystones @property def lastRequestSeconds(self): return self.timer.elapsedSeconds def reload(self): self._start_timer() self.mech_browser.reload() self._stop_timer() self._changed() def goBack(self, count=1): self._start_timer() self.mech_browser.back(count) self._stop_timer() self._changed() def addHeader(self, key, value): self.mech_browser.addheaders.append( (key, value) ) def getLink(self, text=None, url=None, id=None, index=0): if id is not None: def predicate(link): return dict(link.attrs).get('id') == id args = {'predicate': predicate} else: if isinstance(text, RegexType): text_regex = text elif text is not None: text_regex = re.compile(re.escape(text), re.DOTALL) else: text_regex = None if isinstance(url, RegexType): url_regex = url elif url is not None: url_regex = re.compile(re.escape(url), re.DOTALL) else: url_regex = None args = {'text_regex': text_regex, 'url_regex': url_regex} args['nr'] = index return Link(self.mech_browser.find_link(**args), self) def _findByLabel(self, label, forms, include_subcontrols=False): # forms are iterable of mech_forms matches = re.compile(r'(^|\b|\W)%s(\b|\W|$)' % re.escape(compressText(label))).search found = [] for f in forms: for control in f.controls: phantom = control.type in ('radio', 'checkbox') if not phantom: for l in control.get_labels(): if matches(l.text): found.append((control, f)) break if include_subcontrols and ( phantom or control.type=='select'): for i in control.items: for l in i.get_labels(): if matches(l.text): found.append((i, f)) found_one = True break return found def _findByName(self, name, forms): found = [] for f in forms: for control in f.controls: if control.name==name: found.append((control, f)) return found def getControl(self, label=None, name=None, index=None): intermediate, msg = self._get_all_controls( label, name, self.mech_browser.forms(), include_subcontrols=True) control, form = disambiguate(intermediate, msg, index) return controlFactory(control, form, self) def _get_all_controls(self, label, name, forms, include_subcontrols=False): onlyOne([label, name], '"label" and "name"') if label is not None: res = self._findByLabel(label, forms, include_subcontrols) msg = 'label %r' % label elif name is not None: res = self._findByName(name, forms) msg = 'name %r' % name return res, msg def getForm(self, id=None, name=None, action=None, index=None): zeroOrOne([id, name, action], '"id", "name", and "action"') matching_forms = [] for form in self.mech_browser.forms(): if ((id is not None and form.attrs.get('id') == id) or (name is not None and form.name == name) or (action is not None and re.search(action, str(form.action))) or id == name == action == None): matching_forms.append(form) if index is None and not any([id, name, action]): if len(matching_forms) == 1: index = 0 else: raise ValueError( 'if no other arguments are given, index is required.') form = disambiguate(matching_forms, '', index) self.mech_browser.form = form return Form(self, form) def _clickSubmit(self, form, control, coord): labels = control.get_labels() if labels: label = labels[0].text else: label = None self._start_timer() self.mech_browser.open(form.click( id=control.id, name=control.name, label=label, coord=coord)) self._stop_timer() def _changed(self): self._counter += 1 self._contents = None class Link(SetattrErrorsMixin): zope.interface.implements(zc.testbrowser.interfaces.ILink) def __init__(self, link, browser): self.mech_link = link self.browser = browser self._browser_counter = self.browser._counter self._enable_setattr_errors = True def click(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser._start_timer() self.browser.mech_browser.follow_link(self.mech_link) self.browser._stop_timer() self.browser._changed() @property def url(self): return self.mech_link.absolute_url @property def text(self): return self.mech_link.text @property def tag(self): return self.mech_link.tag @property def attrs(self): return dict(self.mech_link.attrs) def __repr__(self): return "<%s text=%r url=%r>" % ( self.__class__.__name__, self.text, self.url) class Control(SetattrErrorsMixin): """A control of a form.""" zope.interface.implements(zc.testbrowser.interfaces.IControl) _enable_setattr_errors = False def __init__(self, control, form, browser): self.mech_control = control self.mech_form = form self.browser = browser self._browser_counter = self.browser._counter if self.mech_control.type == 'file': self.filename = None self.content_type = None # for some reason ClientForm thinks we shouldn't be able to modify # hidden fields, but while testing it is sometimes very important if self.mech_control.type == 'hidden': self.mech_control.readonly = False # disable addition of further attributes self._enable_setattr_errors = True @property def disabled(self): return bool(getattr(self.mech_control, 'disabled', False)) @property def type(self): return getattr(self.mech_control, 'type', None) @property def name(self): return getattr(self.mech_control, 'name', None) @property def multiple(self): return bool(getattr(self.mech_control, 'multiple', False)) @apply def value(): def fget(self): if (self.type == 'checkbox' and len(self.mech_control.items) == 1 and self.mech_control.items[0].name == 'on'): return self.mech_control.items[0].selected return self.mech_control.value def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError if self.mech_control.type == 'file': self.mech_control.add_file(value, content_type=self.content_type, filename=self.filename) elif self.type == 'checkbox' and len(self.mech_control.items) == 1: self.mech_control.items[0].selected = bool(value) else: self.mech_control.value = value return property(fget, fset) def add_file(self, file, content_type, filename): if not self.mech_control.type == 'file': raise TypeError("Can't call add_file on %s controls" % self.mech_control.type) if isinstance(file, str): file = StringIO(file) self.mech_control.add_file(file, content_type, filename) def clear(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.mech_control.clear() def __repr__(self): return "<%s name=%r type=%r>" % ( self.__class__.__name__, self.name, self.type) class ListControl(Control): zope.interface.implements(zc.testbrowser.interfaces.IListControl) @apply def displayValue(): # not implemented for anything other than select; # would be nice if ClientForm implemented for checkbox and radio. # attribute error for all others. def fget(self): return self.mech_control.get_value_by_label() def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.mech_control.set_value_by_label(value) return property(fget, fset) @property def displayOptions(self): res = [] for item in self.mech_control.items: if not item.disabled: for label in item.get_labels(): if label.text: res.append(label.text) break else: res.append(None) return res @property def options(self): if (self.type == 'checkbox' and len(self.mech_control.items) == 1 and self.mech_control.items[0].name == 'on'): return [True] return [i.name for i in self.mech_control.items if not i.disabled] @property def disabled(self): if self.type == 'checkbox' and len(self.mech_control.items) == 1: return bool(getattr(self.mech_control.items[0], 'disabled', False)) return bool(getattr(self.mech_control, 'disabled', False)) @property def controls(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError res = [controlFactory(i, self.mech_form, self.browser) for i in self.mech_control.items] for s in res: s.__dict__['control'] = self return res def getControl(self, label=None, value=None, index=None): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError onlyOne([label, value], '"label" and "value"') if label is not None: options = self.mech_control.get_items(label=label) msg = 'label %r' % label elif value is not None: options = self.mech_control.get_items(name=value) msg = 'value %r' % value res = controlFactory( disambiguate(options, msg, index), self.mech_form, self.browser) res.__dict__['control'] = self return res class SubmitControl(Control): zope.interface.implements(zc.testbrowser.interfaces.ISubmitControl) def click(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser._clickSubmit(self.mech_form, self.mech_control, (1,1)) self.browser._changed() class ImageControl(Control): zope.interface.implements(zc.testbrowser.interfaces.IImageSubmitControl) def click(self, coord=(1,1)): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.browser._clickSubmit(self.mech_form, self.mech_control, coord) self.browser._changed() class ItemControl(SetattrErrorsMixin): zope.interface.implements(zc.testbrowser.interfaces.IItemControl) def __init__(self, item, form, browser): self.mech_item = item self.mech_form = form self.browser = browser self._browser_counter = self.browser._counter self._enable_setattr_errors = True @property def control(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError res = controlFactory( self.mech_item._control, self.mech_form, self.browser) self.__dict__['control'] = res return res @property def disabled(self): return self.mech_item.disabled @apply def selected(): def fget(self): return self.mech_item.selected def fset(self, value): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.mech_item.selected = value return property(fget, fset) @property def optionValue(self): return self.mech_item.attrs.get('value') def click(self): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError self.mech_item.selected = not self.mech_item.selected def __repr__(self): return "<%s name=%r type=%r optionValue=%r selected=%r>" % ( self.__class__.__name__, self.mech_item._control.name, self.mech_item._control.type, self.optionValue, self.mech_item.selected) class Form(SetattrErrorsMixin): """HTML Form""" zope.interface.implements(zc.testbrowser.interfaces.IForm) def __init__(self, browser, form): """Initialize the Form browser - a Browser instance form - a ClientForm instance """ self.browser = browser self.mech_form = form self._browser_counter = self.browser._counter self._enable_setattr_errors = True @property def action(self): return self.mech_form.action @property def method(self): return self.mech_form.method @property def enctype(self): return self.mech_form.enctype @property def name(self): return self.mech_form.name @property def id(self): return self.mech_form.attrs.get('id') def submit(self, label=None, name=None, index=None, coord=(1,1)): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError form = self.mech_form if label is not None or name is not None: intermediate, msg = self.browser._get_all_controls( label, name, (form,)) intermediate = [ (control, form) for (control, form) in intermediate if control.type in ('submit', 'submitbutton', 'image')] control, form = disambiguate(intermediate, msg, index) self.browser._clickSubmit(form, control, coord) else: # JavaScript sort of submit if index is not None or coord != (1,1): raise ValueError( 'May not use index or coord without a control') request = self.mech_form._switch_click("request", urllib2.Request) self.browser._start_timer() self.browser.mech_browser.open(request) self.browser._stop_timer() self.browser._changed() def getControl(self, label=None, name=None, index=None): if self._browser_counter != self.browser._counter: raise zc.testbrowser.interfaces.ExpiredError intermediate, msg = self.browser._get_all_controls( label, name, (self.mech_form,), include_subcontrols=True) control, form = disambiguate(intermediate, msg, index) return controlFactory(control, form, self.browser)
zc.testbrowser
/zc.testbrowser-1.0a1.tar.gz/zc.testbrowser-1.0a1/src/zc/testbrowser/browser.py
browser.py
Detailed Documentation ====================== Before being of much interest, we need to open a web page. ``Browser`` instances have a ``base`` attribute that sets the URL from which ``open``-ed URLs are relative. This lets you target tests at servers running in various, or even variable locations (like using randomly chosen ports). >>> browser = Browser() >>> browser.base = 'http://localhost:%s/' % TEST_PORT >>> browser.open('index.html') >>> browser.url 'http://localhost:.../index.html' Once you have opened a web page initially, best practice for writing testbrowser doctests suggests using 'click' to navigate further (as discussed below), except in unusual circumstances. The test browser complies with the IBrowser interface; see ``zc.testbrowser.interfaces`` for full details on the interface. >>> import zc.testbrowser.interfaces >>> from zope.interface.verify import verifyObject >>> zc.testbrowser.interfaces.IBrowser.providedBy(browser) True Page Contents ------------- The contents of the current page are available: >>> browser.contents '...<h1>Simple Page</h1>...' Note: Unfortunately, ellipsis (...) cannot be used at the beginning of the output (this is a limitation of doctest). Making assertions about page contents is easy. >>> '<h1>Simple Page</h1>' in browser.contents True Checking for HTML ----------------- Not all URLs return HTML. Of course our simple page does: >>> browser.isHtml True But if we load an image (or other binary file), we do not get HTML: >>> browser.open('zope3logo.gif') >>> browser.isHtml False HTML Page Title ---------------- Another useful helper property is the title: >>> browser.open('index.html') >>> browser.title 'Simple Page' If a page does not provide a title, it is simply ``None``: >>> browser.open('notitle.html') >>> browser.title However, if the output is not HTML, then an error will occur trying to access the title: >>> browser.open('zope3logo.gif') >>> browser.title Traceback (most recent call last): ... BrowserStateError: not viewing HTML Navigation and Link Objects --------------------------- If you want to simulate clicking on a link, get the link and call its `click` method. In the `navigate.html` file there are several links set up to demonstrate the capabilities of the link objects and their `click` method. The simplest way to get a link is via the anchor text. In other words the text you would see in a browser: >>> browser.open('navigate.html') >>> browser.contents '...<a href="target.html">Link Text</a>...' >>> link = browser.getLink('Link Text') >>> link <Link text='Link Text' url='http://localhost:.../target.html'> Link objects comply with the ILink interface. >>> verifyObject(zc.testbrowser.interfaces.ILink, link) True Links expose several attributes for easy access. >>> link.text 'Link Text' Links can be "clicked" and the browser will navigate to the referenced URL. >>> link.click() >>> browser.url 'http://localhost:.../target.html' >>> browser.contents '...This page is the target of a link...' When finding a link by its text, whitespace is normalized. >>> browser.open('navigate.html') >>> browser.contents '...> Link Text \n with Whitespace\tNormalization (and parens) </...' >>> link = browser.getLink('Link Text with Whitespace Normalization ' ... '(and parens)') >>> link <Link text='Link Text with Whitespace Normalization (and parens)'...> >>> link.text 'Link Text with Whitespace Normalization (and parens)' >>> link.click() >>> browser.url 'http://localhost:.../target.html' When a link text matches more than one link, by default the first one is chosen. You can, however, specify the index of the link and thus retrieve a later matching link: >>> browser.open('navigate.html') >>> browser.getLink('Link Text') <Link text='Link Text' ...> >>> browser.getLink('Link Text', index=1) <Link text='Link Text with Whitespace Normalization (and parens)' ...> Note that clicking a link object after its browser page has expired will generate an error. >>> link.click() Traceback (most recent call last): ... ExpiredError You can also find links by URL, >>> browser.open('navigate.html') >>> browser.getLink(url='target.html').click() >>> browser.url 'http://localhost:.../target.html' or its id: >>> browser.open('navigate.html') >>> browser.contents '...<a href="target.html" id="anchorid">By Anchor Id</a>...' >>> browser.getLink(id='anchorid').click() >>> browser.url 'http://localhost:.../target.html' You thought we were done here? Not so quickly. The `getLink` method also supports image maps, though not by specifying the coordinates, but using the area's id: >>> browser.open('navigate.html') >>> link = browser.getLink(id='zope3') >>> link.click() >>> browser.url 'http://localhost:.../target.html' Getting a nonexistent link raises an exception. >>> browser.open('navigate.html') >>> browser.getLink('This does not exist') Traceback (most recent call last): ... LinkNotFoundError Other Navigation ---------------- Like in any normal browser, you can reload a page: >>> browser.open('index.html') >>> browser.url 'http://localhost:.../index.html' >>> browser.reload() >>> browser.url 'http://localhost:.../index.html' You can also go back: >>> browser.open('notitle.html') >>> browser.url 'http://localhost:.../notitle.html' >>> browser.goBack() >>> browser.url 'http://localhost:.../index.html' Controls -------- One of the most important features of the browser is the ability to inspect and fill in values for the controls of input forms. To do so, let's first open a page that has a bunch of controls: >>> browser.open('controls.html') Obtaining a Control ~~~~~~~~~~~~~~~~~~~ You look up browser controls with the 'getControl' method. The default first argument is 'label', and looks up the form on the basis of any associated label. >>> control = browser.getControl('Text Control') >>> control <Control name='text-value' type='text'> >>> browser.getControl(label='Text Control') # equivalent <Control name='text-value' type='text'> If you request a control that doesn't exist, the code raises a LookupError: >>> browser.getControl('Does Not Exist') Traceback (most recent call last): ... LookupError: label 'Does Not Exist' If you request a control with an ambiguous lookup, the code raises an AmbiguityError. >>> browser.getControl('Ambiguous Control') Traceback (most recent call last): ... AmbiguityError: label 'Ambiguous Control' This is also true if an option in a control is ambiguous in relation to the control itself. >>> browser.getControl('Sub-control Ambiguity') Traceback (most recent call last): ... AmbiguityError: label 'Sub-control Ambiguity' Ambiguous controls may be specified using an index value. We use the control's value attribute to show the two controls; this attribute is properly introduced below. >>> browser.getControl('Ambiguous Control', index=0) <Control name='ambiguous-control-name' type='text'> >>> browser.getControl('Ambiguous Control', index=0).value 'First' >>> browser.getControl('Ambiguous Control', index=1).value 'Second' >>> browser.getControl('Sub-control Ambiguity', index=0) <ListControl name='ambiguous-subcontrol' type='select'> >>> browser.getControl('Sub-control Ambiguity', index=1).optionValue 'ambiguous' Label searches are against stripped, whitespace-normalized, no-tag versions of the text. Text applied to searches is also stripped and whitespace normalized. The search finds results if the text search finds the whole words of your text in a label. Thus, for instance, a search for 'Add' will match the label 'Add a Client' but not 'Address'. Case is honored. >>> browser.getControl('Label Needs Whitespace Normalization') <Control name='label-needs-normalization' type='text'> >>> browser.getControl('label needs whitespace normalization') Traceback (most recent call last): ... LookupError: label 'label needs whitespace normalization' >>> browser.getControl(' Label Needs Whitespace ') <Control name='label-needs-normalization' type='text'> >>> browser.getControl('Whitespace') <Control name='label-needs-normalization' type='text'> >>> browser.getControl('hitespace') Traceback (most recent call last): ... LookupError: label 'hitespace' >>> browser.getControl('[non word characters should not confuse]') <Control name='non-word-characters' type='text'> Multiple labels can refer to the same control (simply because that is possible in the HTML 4.0 spec). >>> browser.getControl('Multiple labels really') <Control name='two-labels' type='text'> >>> browser.getControl('really are possible') <Control name='two-labels' type='text'> >>> browser.getControl('really') # OK: ambiguous labels, but not ambiguous control <Control name='two-labels' type='text'> A label can be connected with a control using the 'for' attribute and also by containing a control. >>> browser.getControl( ... 'Labels can be connected by containing their respective fields') <Control name='contained-in-label' type='text'> Get also accepts one other search argument, 'name'. Only one of 'label' and 'name' may be used at a time. The 'name' keyword searches form field names. >>> browser.getControl(name='text-value') <Control name='text-value' type='text'> >>> browser.getControl(name='ambiguous-control-name') Traceback (most recent call last): ... AmbiguityError: name 'ambiguous-control-name' >>> browser.getControl(name='does-not-exist') Traceback (most recent call last): ... LookupError: name 'does-not-exist' >>> browser.getControl(name='ambiguous-control-name', index=1).value 'Second' Combining 'label' and 'name' raises a ValueError, as does supplying neither of them. >>> browser.getControl(label='Ambiguous Control', name='ambiguous-control-name') Traceback (most recent call last): ... ValueError: Supply one and only one of "label" and "name" as arguments >>> browser.getControl() Traceback (most recent call last): ... ValueError: Supply one and only one of "label" and "name" as arguments Radio and checkbox fields are unusual in that their labels and names may point to different objects: names point to logical collections of radio buttons or checkboxes, but labels may only be used for individual choices within the logical collection. This means that obtaining a radio button by label gets a different object than obtaining the radio collection by name. Select options may also be searched by label. >>> browser.getControl(name='radio-value') <ListControl name='radio-value' type='radio'> >>> browser.getControl('Zwei') <ItemControl name='radio-value' type='radio' optionValue='2' selected=True> >>> browser.getControl('One') <ItemControl name='multi-checkbox-value' type='checkbox' optionValue='1' selected=True> >>> browser.getControl('Tres') <ItemControl name='single-select-value' type='select' optionValue='3' selected=False> Characteristics of controls and subcontrols are discussed below. Control Objects ~~~~~~~~~~~~~~~ Controls provide IControl. >>> ctrl = browser.getControl('Text Control') >>> ctrl <Control name='text-value' type='text'> >>> verifyObject(zc.testbrowser.interfaces.IControl, ctrl) True They have several useful attributes: - the name as which the control is known to the form: >>> ctrl.name 'text-value' - the value of the control, which may also be set: >>> ctrl.value 'Some Text' >>> ctrl.value = 'More Text' >>> ctrl.value 'More Text' - the type of the control: >>> ctrl.type 'text' - a flag describing whether the control is disabled: >>> ctrl.disabled False - and a flag to tell us whether the control can have multiple values: >>> ctrl.multiple False Additionally, controllers for select, radio, and checkbox provide IListControl. These fields have four other attributes and an additional method: >>> ctrl = browser.getControl('Multiple Select Control') >>> ctrl <ListControl name='multi-select-value' type='select'> >>> ctrl.disabled False >>> ctrl.multiple True >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True - 'options' lists all available value options. >>> [unicode(o) for o in ctrl.options] [u'1', u'2', u'3'] - 'displayOptions' lists all available options by label. The 'label' attribute on an option has precedence over its contents, which is why our last option is 'Third' in the display. >>> ctrl.displayOptions ['Un', 'Deux', 'Third'] - 'displayValue' lets you get and set the displayed values of the control of the select box, rather than the actual values. >>> ctrl.value [] >>> ctrl.displayValue [] >>> ctrl.displayValue = ['Un', 'Deux'] >>> ctrl.displayValue ['Un', 'Deux'] >>> [unicode(v) for v in ctrl.value] [u'1', u'2'] - 'controls' gives you a list of the subcontrol objects in the control (subcontrols are discussed below). >>> ctrl.controls [<ItemControl name='multi-select-value' type='select' optionValue='1' selected=True>, <ItemControl name='multi-select-value' type='select' optionValue='2' selected=True>, <ItemControl name='multi-select-value' type='select' optionValue='3' selected=False>] - The 'getControl' method lets you get subcontrols by their label or their value. >>> ctrl.getControl('Un') <ItemControl name='multi-select-value' type='select' optionValue='1' selected=True> >>> ctrl.getControl('Deux') <ItemControl name='multi-select-value' type='select' optionValue='2' selected=True> >>> ctrl.getControl('Trois') # label attribute <ItemControl name='multi-select-value' type='select' optionValue='3' selected=False> >>> ctrl.getControl('Third') # contents <ItemControl name='multi-select-value' type='select' optionValue='3' selected=False> >>> browser.getControl('Third') # ambiguous in the browser, so useful Traceback (most recent call last): ... AmbiguityError: label 'Third' Finally, submit controls provide ISubmitControl, and image controls provide IImageSubmitControl, which extents ISubmitControl. These both simply add a 'click' method. For image submit controls, you may also provide a coordinates argument, which is a tuple of (x, y). These submit the forms, and are demonstrated below as we examine each control individually. ItemControl Objects ~~~~~~~~~~~~~~~~~~~ As introduced briefly above, using labels to obtain elements of a logical radio button or checkbox collection returns item controls, which are parents. Manipulating the value of these controls affects the parent control. >>> [unicode(v) for v in browser.getControl(name='radio-value').value] [u'2'] >>> browser.getControl('Zwei').optionValue # read-only. '2' >>> browser.getControl('Zwei').selected True >>> verifyObject(zc.testbrowser.interfaces.IItemControl, ... browser.getControl('Zwei')) True >>> browser.getControl('Ein').selected False >>> browser.getControl('Ein').selected = True >>> browser.getControl('Ein').selected True Of course at this point the previously selected "Zwei" will be unselected since only one radio button can be selected. >>> browser.getControl('Zwei').selected False >>> browser.getControl('Zwei').selected False >>> [unicode(v) for v in browser.getControl(name='radio-value').value] [u'1'] This test is not valid because it is impossible (with the browser) to unselect a radio box ... one radio box (must always remain selected). This used to be a test for mechanize and used to pass because mechanize didn't realize. And by running the level 3 tests we are running these tests under both mechanize and the "real" browser testing. :: browser.getControl('Ein').selected = False browser.getControl('Ein').selected False browser.getControl(name='radio-value').value [] >>> browser.getControl('Zwei').selected = True Checkbox collections behave similarly, as shown below. Controls with subcontrols-- Various Controls ~~~~~~~~~~~~~~~~ The various types of controls are demonstrated here. - Text Control The text control we already introduced above. - Password Control >>> ctrl = browser.getControl('Password Control') >>> ctrl <Control name='password-value' type='password'> >>> verifyObject(zc.testbrowser.interfaces.IControl, ctrl) True >>> ctrl.value 'Password' >>> ctrl.value = 'pass now' >>> ctrl.value 'pass now' >>> ctrl.disabled False >>> ctrl.multiple False - Hidden Control >>> ctrl = browser.getControl(name='hidden-value') >>> ctrl <Control name='hidden-value' type='hidden'> >>> verifyObject(zc.testbrowser.interfaces.IControl, ctrl) True >>> ctrl.value 'Hidden' >>> ctrl.value = 'More Hidden' >>> ctrl.disabled False >>> ctrl.multiple False - Text Area Control >>> ctrl = browser.getControl('Text Area Control') >>> ctrl <Control name='textarea-value' type='textarea'> >>> verifyObject(zc.testbrowser.interfaces.IControl, ctrl) True >>> ctrl.value ' Text inside\n area!\n ' >>> ctrl.value = 'A lot of\n text.' >>> ctrl.value 'A lot of\n text.' >>> ctrl.disabled False >>> ctrl.multiple False - File Control File controls are used when a form has a file-upload field. To specify data, call the add_file method, passing: - A file-like object - a content type, and - a file name >>> ctrl = browser.getControl('File Control') >>> ctrl <Control name='file-value' type='file'> >>> verifyObject(zc.testbrowser.interfaces.IControl, ctrl) True >>> ctrl.value is None True >>> import cStringIO >>> ctrl.add_file(cStringIO.StringIO('File contents'), ... 'text/plain', 'test.txt') The file control (like the other controls) also knows if it is disabled or if it can have multiple values. >>> ctrl.disabled False >>> ctrl.multiple False - Selection Control (Single-Valued) >>> ctrl = browser.getControl('Single Select Control') >>> ctrl <ListControl name='single-select-value' type='select'> >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True >>> [unicode(v) for v in ctrl.value] [u'1'] >>> ctrl.value = ['2'] >>> ctrl.disabled False >>> ctrl.multiple False >>> [unicode(o) for o in ctrl.options] [u'1', u'2', u'3'] >>> ctrl.displayOptions ['Uno', 'Dos', 'Third'] >>> ctrl.displayValue ['Dos'] >>> ctrl.displayValue = ['Tres'] >>> ctrl.displayValue ['Third'] >>> ctrl.displayValue = ['Dos'] >>> ctrl.displayValue ['Dos'] >>> ctrl.displayValue = ['Third'] >>> ctrl.displayValue ['Third'] >>> [unicode(v) for v in ctrl.value] [u'3'] - Selection Control (Multi-Valued) >>> ctrl = browser.getControl('Multiple Select Control') >>> ctrl <ListControl name='multi-select-value' type='select'> >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True >>> [unicode(v) for v in ctrl.value] [u'1', u'2'] >>> ctrl.value = ['1', '3'] >>> [unicode(v) for v in ctrl.displayValue] [u'Un', u'Third'] - Checkbox Control (Single-Valued; Unvalued) >>> ctrl = browser.getControl(name='single-unvalued-checkbox-value') >>> ctrl <ListControl name='single-unvalued-checkbox-value' type='checkbox'> >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True >>> ctrl.value True >>> ctrl.value = False >>> ctrl.disabled False >>> ctrl.multiple True >>> ctrl.options [True] >>> ctrl.displayOptions ['Single Unvalued Checkbox'] >>> ctrl.displayValue [] >>> verifyObject( ... zc.testbrowser.interfaces.IItemControl, ... browser.getControl('Single Unvalued Checkbox')) True >>> browser.getControl('Single Unvalued Checkbox').optionValue 'on' >>> browser.getControl('Single Unvalued Checkbox').selected False >>> ctrl.displayValue = ['Single Unvalued Checkbox'] >>> ctrl.displayValue ['Single Unvalued Checkbox'] >>> browser.getControl('Single Unvalued Checkbox').selected True >>> browser.getControl('Single Unvalued Checkbox').selected = False >>> browser.getControl('Single Unvalued Checkbox').selected False >>> ctrl.displayValue [] >>> browser.getControl( ... name='single-disabled-unvalued-checkbox-value').disabled True - Checkbox Control (Single-Valued, Valued) >>> ctrl = browser.getControl(name='single-valued-checkbox-value') >>> ctrl <ListControl name='single-valued-checkbox-value' type='checkbox'> >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True >>> [unicode(v) for v in ctrl.value] [u'1'] >>> ctrl.value = [] >>> ctrl.disabled False >>> ctrl.multiple True >>> [unicode(o) for o in ctrl.options] [u'1'] >>> ctrl.displayOptions ['Single Valued Checkbox'] >>> ctrl.displayValue [] >>> verifyObject( ... zc.testbrowser.interfaces.IItemControl, ... browser.getControl('Single Valued Checkbox')) True >>> browser.getControl('Single Valued Checkbox').selected False >>> browser.getControl('Single Valued Checkbox').optionValue '1' >>> ctrl.displayValue = ['Single Valued Checkbox'] >>> ctrl.displayValue ['Single Valued Checkbox'] >>> browser.getControl('Single Valued Checkbox').selected True >>> browser.getControl('Single Valued Checkbox').selected = False >>> browser.getControl('Single Valued Checkbox').selected False >>> ctrl.displayValue [] - Checkbox Control (Multi-Valued) >>> ctrl = browser.getControl(name='multi-checkbox-value') >>> ctrl <ListControl name='multi-checkbox-value' type='checkbox'> >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True >>> [unicode(v) for v in ctrl.value] [u'1', u'3'] >>> ctrl.value = ['1', '2'] >>> ctrl.disabled False >>> ctrl.multiple True >>> [unicode(o) for o in ctrl.options] [u'1', u'2', u'3'] >>> ctrl.displayOptions ['One', 'Two', 'Three'] >>> ctrl.displayValue ['One', 'Two'] >>> ctrl.displayValue = ['Two'] >>> [unicode(v) for v in ctrl.value] [u'2'] >>> browser.getControl('Two').optionValue '2' >>> browser.getControl('Two').selected True >>> verifyObject(zc.testbrowser.interfaces.IItemControl, ... browser.getControl('Two')) True >>> browser.getControl('Three').selected = True >>> browser.getControl('Three').selected True >>> browser.getControl('Two').selected True >>> [unicode(v) for v in ctrl.value] [u'2', u'3'] >>> browser.getControl('Two').selected = False >>> [unicode(v) for v in ctrl.value] [u'3'] >>> browser.getControl('Three').selected = False >>> ctrl.value [] - Radio Control This is how you get a radio button based control: >>> ctrl = browser.getControl(name='radio-value') This shows the existing value of the control, as it was in the HTML received from the server: >>> [unicode(v) for v in ctrl.value] [u'2'] We can then unselect it: >>> ctrl.value = [] >>> ctrl.value [] We can also reselect it: >>> ctrl.value = ['2'] >>> [unicode(v) for v in ctrl.value] [u'2'] displayValue shows the text the user would see next to the control: >>> ctrl.displayValue ['Zwei'] This is just unit testing: >>> ctrl <ListControl name='radio-value' type='radio'> >>> verifyObject(zc.testbrowser.interfaces.IListControl, ctrl) True >>> ctrl.disabled False >>> ctrl.multiple False >>> [unicode(o) for o in ctrl.options] [u'1', u'2', u'3'] >>> ctrl.displayOptions ['Ein', 'Zwei', 'Drei'] >>> ctrl.displayValue = ['Ein'] >>> [unicode(v) for v in ctrl.value] [u'1'] >>> ctrl.displayValue ['Ein'] The radio control subcontrols were illustrated above. - Image Control >>> ctrl = browser.getControl(name='image-value') >>> ctrl <ImageControl name='image-value' type='image'> >>> verifyObject(zc.testbrowser.interfaces.IImageSubmitControl, ctrl) True >>> ctrl.value '' >>> ctrl.disabled False >>> ctrl.multiple False - Submit Control >>> ctrl = browser.getControl(name='submit-value') >>> ctrl <SubmitControl name='submit-value' type='submit'> >>> browser.getControl('Submit This') # value of submit button is a label <SubmitControl name='submit-value' type='submit'> >>> browser.getControl('Standard Submit Control') # label tag is legal <SubmitControl name='submit-value' type='submit'> >>> browser.getControl('Submit') # multiple labels, but same control <SubmitControl name='submit-value' type='submit'> >>> verifyObject(zc.testbrowser.interfaces.ISubmitControl, ctrl) True >>> ctrl.value 'Submit This' >>> ctrl.disabled False >>> ctrl.multiple False Using Submitting Controls ~~~~~~~~~~~~~~~~~~~~~~~~~ Both the submit and image type should be clickable and submit the form: >>> browser.getControl('Text Control').value = 'Other Text' >>> browser.getControl('Submit').click() >>> browser.contents "...'text-value': ['Other Text']..." Note that if you click a submit object after the associated page has expired, you will get an error. >>> browser.open('controls.html') >>> ctrl = browser.getControl('Submit') >>> ctrl.click() >>> ctrl.click() Traceback (most recent call last): ... ExpiredError All the above also holds true for the image control: >>> browser.open('controls.html') >>> browser.getControl('Text Control').value = 'Other Text' >>> browser.getControl(name='image-value').click() >>> browser.contents "...'text-value': ['Other Text']..." >>> browser.open('controls.html') >>> ctrl = browser.getControl(name='image-value') >>> ctrl.click() >>> ctrl.click() Traceback (most recent call last): ... ExpiredError But when sending an image, you can also specify the coordinate you clicked: # >>> browser.open('controls.html') # >>> browser.getControl(name='image-value').click((50,25)) # >>> browser.contents # "...'image-value.x': ['50']...'image-value.y': ['25']..." Forms ----- Because pages can have multiple forms with like-named controls, it is sometimes necessary to access forms by name or id. The browser's `forms` attribute can be used to do so. The key value is the form's name or id. If more than one form has the same name or id, the first one will be returned. >>> browser.open('forms.html') >>> form = browser.getForm(name='one') Form instances conform to the IForm interface. >>> verifyObject(zc.testbrowser.interfaces.IForm, form) True The form exposes several attributes related to forms: - The name of the form: >>> unicode(form.name) u'one' - The id of the form: >>> unicode(form.id) u'1' - The action (target URL) when the form is submitted: >>> unicode(form.action) u'http://localhost:.../forms.html' - The method (HTTP verb) used to transmit the form data: >>> unicode(form.method) u'POST' - The encoding type of the form data: >>> unicode(form.enctype) u'application/x-www-form-urlencoded' Besides those attributes, you have also a couple of methods. Like for the browser, you can get control objects, but limited to the current form... >>> form.getControl(name='text-value') <Control name='text-value' type='text'> ...and submit the form. >>> form.submit('Submit') >>> browser.contents "...'text-value': ['First Text']..." Submitting also works without specifying a control, as shown below, which is it's primary reason for existing in competition with the control submission discussed above. Now let me show you briefly that looking up forms is sometimes important. In the `forms.html` template, we have four forms all having a text control named `text-value`. Now, if I use the browser's `get` method, >>> browser.open('forms.html') >>> browser.getControl(name='text-value') Traceback (most recent call last): ... AmbiguityError: name 'text-value' >>> browser.getControl('Text Control') Traceback (most recent call last): ... AmbiguityError: label 'Text Control' I'll always get an ambiguous form field. I can use the index argument, or with the `getForm` method I can disambiguate by searching only within a given form: >>> form = browser.getForm('2') >>> form.getControl(name='text-value').value 'Second Text' >>> form.submit('Submit') >>> browser.contents "...'text-value': ['Second Text']..." >>> browser.open('forms.html') >>> form = browser.getForm('2') >>> form.getControl('Submit').click() >>> browser.contents "...'text-value': ['Second Text']..." >>> browser.open('forms.html') >>> browser.getForm('3').getControl('Text Control').value 'Third Text' The last form on the page does not have a name, an id, or a submit button. Working with it is still easy, thanks to a index attribute that guarantees order. (Forms without submit buttons are sometimes useful for JavaScript.) >>> form = browser.getForm(index=3) >>> form.submit() >>> browser.contents "...'text-value': ['Fourth Text']..." If a form is requested that does not exists, an exception will be raised. >>> browser.open('forms.html') >>> form = browser.getForm('does-not-exist') Traceback (most recent call last): LookupError If the HTML page contains only one form, no arguments to `getForm` are needed: >>> browser.open('oneform.html') >>> browser.getForm() <zc.testbrowser...Form object at ...> If the HTML page contains more than one form, `index` is needed to disambiguate if no other arguments are provided: >>> browser.open('forms.html') >>> browser.getForm() Traceback (most recent call last): ValueError: if no other arguments are given, index is required. Performance Testing ------------------- Browser objects keep up with how much time each request takes. This can be used to ensure a particular request's performance is within a tolerable range. Be very careful using raw seconds, cross-machine differences can be huge, pystones is usually a better choice. >>> browser.open('index.html') >>> browser.lastRequestSeconds < 10 # really big number for safety True >>> browser.lastRequestPystones < 100000 # really big number for safety True Hand-Holding ------------ Instances of the various objects ensure that users don't set incorrect instance attributes accidentally. >>> browser.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Browser' object has no attribute 'nonexistant' >>> form.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Form' object has no attribute 'nonexistant' >>> control.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Control' object has no attribute 'nonexistant' >>> link.nonexistant = None Traceback (most recent call last): ... AttributeError: 'Link' object has no attribute 'nonexistant' Fixed Bugs ---------- This section includes tests for bugs that were found and then fixed that don't fit into the more documentation-centric sections above. Spaces in URL ~~~~~~~~~~~~~ When URLs have spaces in them, they're handled correctly (before the bug was fixed, you'd get "ValueError: too many values to unpack"): >>> browser.open('navigate.html') >>> browser.getLink('Spaces in the URL').click() .goBack() Truncation ~~~~~~~~~~~~~~~~~~~~ The .goBack() method used to truncate the .contents. >>> browser.open('navigate.html') >>> actual_length = len(browser.contents) >>> browser.open('navigate.html') >>> browser.open('index.html') >>> browser.goBack() >>> len(browser.contents) == actual_length True Authors ------- Benji York created testbrowser (originally zope.testbrowser) in 2005 with Gary Poster and Stephan Richter making large contributions. The zc.testbrowser.real version was conceptualized by Benji York in 2007 and after an initial implementation sketch, brought to fruition by Stephan Richter, Rocky Burt, Justas Sadzevicius, and others at the Foliage Zope 3 sprint in Boston, MA during the week of September 24, 2007. There have been many other contributions from users of testbrowser that are greatly appreciated.
zc.testbrowser
/zc.testbrowser-1.0a1.tar.gz/zc.testbrowser-1.0a1/src/zc/testbrowser/README.txt
README.txt
var tb_tokens = {}; var tb_next_token = 0; tb_page_loaded = false; document.getElementById("appcontent" ).addEventListener("load", function() { tb_page_loaded = true; }, true); function tb_xpath(pattern, context) { if (context == null) context = content.document; return content.document.evaluate( pattern, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); } function tb_xpath_tokens(pattern, contextToken) { var tokens = new Array(); var context = null; if (contextToken != null) { context = tb_tokens[contextToken] } var result = tb_xpath(pattern, context); var debug_tokens = new Array(); for (var c = 0; c < result.snapshotLength; c++) { tb_tokens[tb_next_token] = result.snapshotItem(c); debug_tokens.push(tb_tokens[tb_next_token].tagName); tokens.push(tb_next_token++); } return tokens; } function tb_extract_token_attrs(tokens, attr) { var attrs = new Array(); for (var i in tokens) { attrs.push(tb_tokens[tokens[i]].getAttribute(attr)); } return attrs; } function tb_get_link_by_predicate(predicate, index) { var anchors = content.document.getElementsByTagName('a'); var i=0; var found = null; if (index == undefined) index = null; for (var x=0; x < anchors.length; x++) { a = anchors[x]; if (!predicate(a)) { continue; } // this anchor matches // if we weren't given an index, but we found more than // one match, we have an ambiguity if (index == null && i > 0) { return 'ambiguity error'; } found = x; // if we were given an index and we just found it, stop if (index != null && i == index) { break } i++; } if (found != null) { tb_tokens[tb_next_token] = anchors[found]; return tb_next_token++; } return false; // link not found } function tb_normalize_whitespace(text) { text = text.replace(/[\n\r]+/g, ' '); text = text.replace(/\s+/g, ' '); text = text.replace(/ +$/g, ''); text = text.replace(/^ +/g, ''); return text; } function tb_get_link_by_text(text, index) { text = tb_normalize_whitespace(text); return tb_get_link_by_predicate( function (a) { return tb_normalize_whitespace(a.textContent).indexOf(text) != -1; }, index) } function tb_get_link_by_url(url, index) { return tb_get_link_by_predicate( function (a) { return a.href.indexOf(url) != -1; }, index) } function tb_get_link_by_id(id, index) { var found = content.document.getElementById(id); if (found != null) { tb_tokens[tb_next_token] = found; return tb_next_token++; } return false; // link not found } function tb_take_screen_shot(out_path) { // The `subject` is what we want to take a screen shot of. var subject = content.document; var canvas = content.document.createElement('canvas'); canvas.width = subject.width; canvas.height = subject.height; var ctx = canvas.getContext('2d'); ctx.drawWindow(content, 0, 0, subject.width, subject.height, 'rgb(0,0,0)'); tb_save_canvas(canvas, out_path); } function tb_save_canvas(canvas, out_path) { var io = Components.classes['@mozilla.org/network/io-service;1' ].getService(Components.interfaces.nsIIOService); var source = io.newURI(canvas.toDataURL('image/png', ''), 'UTF8', null); var persist = Components.classes[ '@mozilla.org/embedding/browser/nsWebBrowserPersist;1' ].createInstance(Components.interfaces.nsIWebBrowserPersist); var file = Components.classes['@mozilla.org/file/local;1' ].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(out_path); persist.saveURI(source, null, null, null, null, file); } function tb_click_token(token, client_x, client_y) { var a = tb_tokens[token]; var evt = a.ownerDocument.createEvent('MouseEvents'); if (client_x == null) client_x = 0; if (client_y == null) client_y = 0; evt.initMouseEvent('click', true, true, a.ownerDocument.defaultView, 1, 0, 0, client_x, client_y, false, false, false, false, 0, null); a.dispatchEvent(evt); } function tb_follow_link(token) { tb_click_token(token); // empty the tokens data structure, they're all expired now // XXX: justas: really? what about links which do not lead from the page // and are only used for javascript onclick event? tb_tokens = {}; } function tb_set_checked(token, checked) { var input = tb_tokens[token]; // XXX: yes, it would be nice to handle checkbox checking via mouse events, but // sometimes tests run too fast, and Firefox misses the mouse clicks // var changed = false; // if ((input.checked && !checked) || (!input.checked && checked)) // changed = true; // if (changed) { // var evt = input.ownerDocument.createEvent('MouseEvents'); // evt.initMouseEvent('click', true, true, // input.ownerDocument.defaultView, // 1, 0, 0, 0, 0, false, false, false, false, // 0, null); // input.dispatchEvent(evt); // } input.checked = checked; type = input.getAttribute('type'); value = input.getAttribute('value') if (type == 'checkbox' && value == null) { input.setAttribute('value', 'on'); } } function tb_get_checked(token) { var input = tb_tokens[token]; var tagName = input.tagName; if (tagName == 'OPTION') { return input.selected; } return input.checked; } function tb_get_link_text(token) { return tb_normalize_whitespace(tb_tokens[token].textContent); } function tb_get_control_by_predicate( predicate, index, allowDuplicate, context, xpath) { if (xpath == null) { var xpath = './/input | .//select | .//option | .//textarea'; } var res = tb_xpath(xpath, context) var i=0; var found = null; if (index == undefined) index = null; for (var x = 0; x < res.snapshotLength; x++) { elem = res.snapshotItem(x); if (!predicate(elem)) { continue; } // if we weren't given an index, but we found more than // one match, we have an ambiguity if (index == null && i > 0) { return 'ambiguity error'; } found = elem; // if we were given an index and we just found it, stop if (index != null && i == index) { break; } // One exception is when the name of a radio or checkbox input is // found twice if (allowDuplicate) { inputType = elem.getAttribute('type'); if (inputType == 'radio' || inputType == 'checkbox') { break; } } i++; } if (found != null) { tb_tokens[tb_next_token] = found; return tb_next_token++; } return false; // control not found } function tb_get_control_by_label(text, index, contextToken, xpath) { context = null; if (contextToken != null) { context = tb_tokens[contextToken]; } text = tb_normalize_whitespace(text); return tb_get_control_by_predicate( function (control) { var tag = control.tagName; var labelText = null; if (tag == 'OPTION') { labelText = control.textContent; if (control.hasAttribute('label')) { labelText += ' ' + control.getAttribute('label'); } } else if (tag == 'SUBMIT' || tag == 'BUTTON') { labelText = control.getAttribute('value'); } else { if (tag == 'INPUT' && control.getAttribute('type').toUpperCase() == 'SUBMIT') { labelText = control.getAttribute('value'); } var id = control.getAttribute('id'); var name = control.getAttribute('name'); // The label encloses the input element var res = tb_xpath("ancestor::label", control); // The label element references the control id if (res.snapshotLength == 0) { var res = tb_xpath("//label[@for='" + id + "']") } // Collect all text content, since HTML allows multiple labels // for the same input. if (res.snapshotLength > 0) { if (!labelText) { labelText = ''; } for (var c = 0; c < res.snapshotLength; c++) { labelText += ' ' + tb_normalize_whitespace( res.snapshotItem(c).textContent); } } } // We can only match whole words! Sigh! if (labelText == null) return false; var expr = ('(^| )\\W*' + text.replace(/(\W)/gi, '\\$1') + '\\W*($| [^a-zA-Z]*)'); if (labelText.search(expr) == -1) return false; return true; }, index, false, context, xpath) } function tb_get_control_by_name(name, index, contextToken, xpath) { return tb_get_control_by_predicate( function (control) { var controlName = control.getAttribute('name'); return controlName != null && controlName.indexOf(name) != -1; }, index, true, tb_tokens[contextToken], xpath) } function tb_get_listcontrol_options(token) { var elem = tb_tokens[token]; var tagName = elem.tagName; var options = new Array(); if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem) for (var c = 0; c < res.snapshotLength; c++) { options.push(res.snapshotItem(c).getAttribute('value')); } } else if (tagName == 'INPUT') { var elemName = elem.getAttribute('name'); var typeName = elem.getAttribute('type'); var res = tb_xpath("//input[@name='" + elemName + "'][@type='"+typeName+"']", elem); for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); var value = item.getAttribute('value'); if (value != null && value != 'on') { options.push(item.getAttribute('value')); } else { options.push(true); } } } return options; } function tb_get_listcontrol_displayOptions(token) { var elem = tb_tokens[token]; var tagName = elem.tagName; var options = new Array(); if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem) for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c) if (item.hasAttribute('label')) options.push(item.getAttribute('label')) else options.push(item.textContent); } } else if (tagName == 'INPUT') { var elemName = elem.getAttribute('name'); var typeName = elem.getAttribute('type'); var res = tb_xpath("//input[@name='" + elemName + "'][@type='"+typeName+"']", elem); for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); labels = tb_find_labels(item); for (var i = 0; i < labels.length; i++) { options.push(labels[i]); } } } return options; } function tb_act_as_single(token) { elem = tb_tokens[token] tagName = elem.tagName if (tagName == 'INPUT') { typeName = elem.getAttribute('type'); var elem = tb_tokens[token]; var res = tb_xpath("//input[@name='" + elem.getAttribute('name') + "'][@type='"+typeName+"']", elem); if (res.snapshotLength > 1) { return false; } else if (res.snapshotLength == 1) { item = res.snapshotItem(0); return !item.hasAttribute('value'); } return true; } return false; } function tb_is_listcontrol_multiple(token) { elem = tb_tokens[token] tagName = elem.tagName if (tagName == 'SELECT') { multiple = elem.getAttribute('multiple') return (multiple && multiple.toUpperCase() == 'MULTIPLE') ? true : false } else if (tagName == 'INPUT') { var typeName = elem.getAttribute('type'); if (typeName == 'radio') { return false; } else if (typeName == 'checkbox'){ var elem = tb_tokens[token]; var res = tb_xpath("//input[@name='" + elem.getAttribute('name') + "'][@type='"+typeName+"']", elem); return res.snapshotLength > 0; } } return false; } function tb_get_listcontrol_value(token) { var elem = tb_tokens[token]; var tagName = elem.tagName; var values = new Array(); if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem) for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); if (item.selected) values.push(item.getAttribute('value')); } } else if (tagName == 'INPUT') { var elemName = elem.getAttribute('name'); var typeName = elem.getAttribute('type'); var res = tb_xpath("//input[@name='" + elemName + "'][@type='"+typeName+"']", elem); for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); if (item.checked) { if (!item.hasAttribute('value')) values.push(true); else values.push(item.getAttribute('value')); } } } return values; } function tb_find_labels(elem) { var elem_id = elem.id; var labels = new Array(); // The label encloses the input element var res = tb_xpath("ancestor::label", elem); // The label element references the control id if (res.snapshotLength == 0) { var res = tb_xpath("//label[@for='" + elem_id + "']") } // Collect all text content, since HTML allows multiple labels // for the same input. if (res.snapshotLength > 0) { for (var c = 0; c < res.snapshotLength; c++) { labels.push(tb_normalize_whitespace( res.snapshotItem(c).textContent)); } } return labels; } function tb_get_listcontrol_displayValue(token) { var elem = tb_tokens[token]; var tagName = elem.tagName; var options = new Array(); if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem) for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); if (item.selected) { if (item.hasAttribute('label')) options.push(item.getAttribute('label')); else options.push(item.textContent); } } } else if (tagName == 'INPUT') { var elemName = elem.getAttribute('name'); var typeName = elem.getAttribute('type'); var res = tb_xpath("//input[@name='" + elemName + "'][@type='"+typeName+"']", elem); for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); if (item.checked) { labels = tb_find_labels(item); for (var i = 0; i < labels.length; i++) { options.push(labels[i]); } } } } return options; } function tb_find_listcontrol_elements(token) { var elem = tb_tokens[token]; var tagName = elem.tagName; var elements = new Array(); if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem); for (var c = 0; c < res.snapshotLength; c++) { elements.push(res.snapshotItem(c)); } } else if (tagName == 'INPUT') { var elemName = elem.getAttribute('name'); var typeName = elem.getAttribute('type'); var res = tb_xpath("//input[@name='" + elemName + "'][@type='"+ typeName +"']"); for (var c = 0; c < res.snapshotLength; c++) { elements.push(res.snapshotItem(c)); } } return elements; } function tb_set_listcontrol_displayValue(token, value) { var elem = tb_tokens[token]; var tagName = elem.tagName; if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem) for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); if (value.indexOf(item.textContent) != -1 || value.indexOf(item.getAttribute('label')) > -1) item.selected = true; else item.selected = false; } } else if (tagName == 'INPUT') { elements = tb_find_listcontrol_elements(token); for (var c = 0; c < elements.length; c++ ) { element = elements[c]; var check = false; labels = tb_find_labels(element); for (var li = 0; li < labels.length; li++ ) { if(value.indexOf(labels[li]) > -1 || value == labels[li]) { check = true; } } element.checked = check; } } } function tb_set_listcontrol_value(token, value) { var elem = tb_tokens[token]; var tagName = elem.tagName; if (tagName == 'SELECT') { var res = tb_xpath('child::option', elem) for (var c = 0; c < res.snapshotLength; c++) { var item = res.snapshotItem(c); if (value.indexOf(item.getAttribute('value')) != -1) item.selected = true; else item.selected = false; } } else if (tagName == 'INPUT'){ var elements = tb_find_listcontrol_elements(token); for (var c = 0; c < elements.length; c++ ) { var element = elements[c]; var elemValue = element.getAttribute('value'); if (elemValue != null && (elemValue == value || value.indexOf(elemValue) > -1)) { element.checked = true; } else { element.checked = false; } } } } function tb_get_listcontrol_item_tokens(token) { var tokens = new Array(); var elements = tb_find_listcontrol_elements(token); for (var c = 0; c < elements.length; c++) { tb_tokens[tb_next_token] = elements[c]; tokens.push(tb_next_token++); } return tokens; }
zc.testbrowser
/zc.testbrowser-1.0a1.tar.gz/zc.testbrowser-1.0a1/src/zc/testbrowser/real.js
real.js
Thread-creation helper ********************** The thread-creation API provided by the Python ``threading`` module is annoying. :) This package provides a very simple thread-creation API that: - Makes threads daemonic and allows daemonicity to be passed to the constructor. For example:: zc.thread.Thread(mythreadfunc) Starts a daemonic thread named ``'mythreadfunc'`` running ``mythreadfunc``. - Allows threads to be defined via decorators, as in:: import zc.thread @zc.thread.Thread def mythread(): ... In the example above, a daemonic thread named ``mythread`` is created and started. The thread is also assigned to the variable ``mythread``. You can control whether threads are daemonic and wether they are started by default:: import zc.thread @zc.thread.Thread(daemon=False, start=False) def mythread(): ... - After a thread finishes, you can get the return value of the target function from the thread's ``value`` attribute, or, if the function raises an exception, you can get the exception object from the thread's ``exception`` attribute. (This feature was inspired by the same feature in gevent greenlets.) - If a thread raises an exception (subclass of Exception), the exception is logged and a traceback is printed to standard error. - A restart argument can be used to rerun a thread target function if there's an uncaught exception. Value passed to the restart argument is passed to time.sleep before restarting the function. There's also a Process constructor/decorator that works like Thread, but with multi-processing processes, and without the ``value`` and ``exception`` attributes. Changes ******* 1.0.0 (2015-06-17) ================== - Python 3 support - Thread names now include a function's module name. - Unhandled exceptions in thread and process targets are now logged and printed with tracebacks. - A restart argument can be used to automatically restart thread targets after a rest. 0.1.0 (2011-11-27) ================== Initial release
zc.thread
/zc.thread-1.0.0.tar.gz/zc.thread-1.0.0/README.txt
README.txt
import atexit exiting = False @atexit.register def set_exiting(): global exiting exiting = True def _options(daemon=True, start=True, args=(), kwargs=None, restart=False): return daemon, start, args, kwargs or {}, restart def _Thread(class_, func, options): daemon, start, args, kwargs, restart = _options(**options) name = "%s.%s" % (getattr(func, '__module__', None), getattr(func, '__name__', None)) def run(*args, **kw): while 1: try: v = func(*args, **kw) thread.value = v return except Exception as v: thread.exception = v if exiting: return import logging logging.getLogger(name).exception( 'Exception in %s', class_.__name__) import traceback traceback.print_exc() if not restart: return import time time.sleep(restart) thread = class_(target=run, name=name, args=args, kwargs=kwargs) if hasattr(thread, 'setDaemon'): thread.setDaemon(daemon) else: thread.daemon = daemon thread.value = thread.exception = None if start: thread.start() return thread def Thread(func=None, **options): """Create and (typically) start a thread If no function is passed, then a decorator function is returned. Typical usage is:: @zc.thread.Thread def mythreadfunc(): ... ... mythread.join() Options: deamon=True Thread daemon flag. Set to false to cause process exit to block until the thread has exited. start=True True to automatically start the thread. args=() Positional arguments to pass to the thread function. kwargs={} keyword arguments to pass to the thread function. """ if func is None: return lambda f: Thread(f, **options) import threading return _Thread(threading.Thread, func, options) def Process(func=None, **options): """Create and (typically) start a multiprocessing process If no function is passed, then a decorator function is returned. Typical usage is:: @zc.thread.Process def mythreadfunc(): ... ... mythread.join() Options: deamon=True Process daemon flag. Set to false to cause process exit to block until the process has exited. start=True True to automatically start the process. args=() Positional arguments to pass to the process function. kwargs={} keyword arguments to pass to the process function. """ if func is None: return lambda f: Process(f, **options) import multiprocessing return _Thread(multiprocessing.Process, func, options)
zc.thread
/zc.thread-1.0.0.tar.gz/zc.thread-1.0.0/src/zc/thread/__init__.py
__init__.py
======= zc.time ======= zc.time provides a single point of creating datetime objects with the current time. It is easily swappable with a test method without having to monkeypatch the standard datetime classes. >>> import time >>> import zc.time >>> now = zc.time.now() >>> type(now) <type 'datetime.datetime'> It also defaults to UTC, which the vanilla datetime does not. >>> now.tzinfo <UTC> There's also a ``utcnow()`` function, which returns the naive UTC time corresponding to the ``now()`` function's return value. This provides a utcnow() implementation that's similarly affected by replacing the ``now()`` function: >>> now = zc.time.utcnow() >>> type(now) <type 'datetime.datetime'> >>> now.tzinfo This relationship holds even if ``now()`` is replaced (not recommended): >>> import datetime >>> import pytz >>> t = datetime.datetime(2010, 4, 1, 10, 50, 30, 2345, pytz.UTC) >>> old_now = zc.time.now >>> zc.time.now = lambda: t >>> zc.time.now() datetime.datetime(2010, 4, 1, 10, 50, 30, 2345, tzinfo=<UTC>) >>> zc.time.utcnow() datetime.datetime(2010, 4, 1, 10, 50, 30, 2345) The ``reset()`` function provided cleans up modifications made to control the time: >>> zc.time.reset() >>> zc.time.now is old_now True A ``set_now()`` function is provided that takes a datetime, and causes ``now()`` and ``utcnow()`` to pretend that's the real time. The time passed in can be in any time zone; naive times are converted to UTC using ``pytz.UTC.localize``: >>> zc.time.set_now(t) >>> zc.time.now() datetime.datetime(2010, 4, 1, 10, 50, 30, 2345, tzinfo=<UTC>) >>> zc.time.utcnow() datetime.datetime(2010, 4, 1, 10, 50, 30, 2345) >>> time.time() 1270137030.002345 >>> naive = datetime.datetime(2010, 4, 1, 12, 27, 3, 5432) >>> zc.time.set_now(naive) >>> zc.time.now() datetime.datetime(2010, 4, 1, 12, 27, 3, 5432, tzinfo=<UTC>) >>> zc.time.utcnow() datetime.datetime(2010, 4, 1, 12, 27, 3, 5432) >>> time.time() 1270142823.005432 >>> t = datetime.datetime(2010, 4, 1, 11, 17, 3, 5432, ... pytz.timezone("US/Eastern")) >>> zc.time.set_now(t) >>> zc.time.now() datetime.datetime(2010, 4, 1, 16, 17, 3, 5432, tzinfo=<UTC>) >>> zc.time.utcnow() datetime.datetime(2010, 4, 1, 16, 17, 3, 5432) >>> time.time() 1270156623.005432 To move forward in time, simply use ``set_now()`` again: >>> zc.time.set_now(t + datetime.timedelta(hours=1)) >>> zc.time.now() datetime.datetime(2010, 4, 1, 17, 17, 3, 5432, tzinfo=<UTC>) >>> zc.time.utcnow() datetime.datetime(2010, 4, 1, 17, 17, 3, 5432) >>> time.time() 1270160223.005432 If an application sleeps using ``time.sleep``, that'll be reflected in the times reported: >>> import time >>> time.sleep(0.25) >>> zc.time.now() datetime.datetime(2010, 4, 1, 17, 17, 3, 255432, tzinfo=<UTC>) >>> zc.time.utcnow() datetime.datetime(2010, 4, 1, 17, 17, 3, 255432) >>> time.time() 1270160223.255432 The reported time will be updated by the exact delay requested of the ``time.sleep`` call, rather than by the actual delay. The ``reset()`` function is used to clean up after this as well: >>> zc.time.reset() The ``reset()`` is registered as a general cleanup handler if ``zope.testing`` is available. This is generally not sufficient for functional tests, which will need to call ``reset`` themselves. Changes ======= 1.0.2 (2015-04-20) ------------------ - Fix packaging bug. 1.0.0 (2015-04-20) ------------------ - Include ``time.time`` in what's controlled by ``zc.time.set_now``. 0.3 (2010-07-23) ---------------- - Added time.sleep() support. 0.2 (2010-04-01) ---------------- - Added utcnow(). - Added set_now(), reset(). 0.1 --- Initial release.
zc.time
/zc.time-1.0.2.tar.gz/zc.time-1.0.2/src/zc/time/README.txt
README.txt
=================================================== Twist: Talking to the ZODB in Twisted Reactor Calls =================================================== The twist package contains a few functions and classes, but primarily a helper for having a deferred call on a callable persistent object, or on a method on a persistent object. This lets you have a Twisted reactor call or a Twisted deferred callback affect the ZODB. Everything can be done within the main thread, so it can be full-bore Twisted usage, without threads. There are a few important "gotchas": see the Gotchas_ section below for details. The main API is `Partial`. You can pass it a callable persistent object, a method of a persistent object, or a normal non-persistent callable, and any arguments or keyword arguments of the same sort. DO NOT use non-persistent data structures (such as lists) of persistent objects with a database connection as arguments. This is your responsibility. If nothing is persistent, the partial will not bother to get a connection, and will behave normally. >>> from zc.twist import Partial >>> def demo(): ... return 42 ... >>> Partial(demo)() 42 Now let's imagine a demo object that is persistent and part of a database connection. It has a `count` attribute that starts at 0, a `__call__` method that increments count by an `amount` that defaults to 1, and an `decrement` method that reduces count by an `amount` that defaults to 1 [#set_up]_. Everything returns the current value of count. >>> demo.count 0 >>> demo() 1 >>> demo(2) 3 >>> demo.decrement() 2 >>> demo.decrement(2) 0 >>> import transaction >>> transaction.commit() Now we can make some deferred calls with these examples. We will use `transaction.begin()` to sync our connection with what happened in the deferred call. Note that we need to have some adapters set up for this to work. The twist module includes implementations of them that we will also assume have been installed [#adapters]_. >>> call = Partial(demo) >>> demo.count # hasn't been called yet 0 >>> deferred = call() >>> demo.count # we haven't synced yet 0 >>> t = transaction.begin() # sync the connection >>> demo.count # ah-ha! 1 We can use the deferred returned from the call to do something with the return value. In this case, the deferred is already completed, so adding a callback gets instant execution. >>> def show_value(res): ... print res ... >>> ignore = deferred.addCallback(show_value) 1 We can also pass the method. >>> call = Partial(demo.decrement) >>> deferred = call() >>> demo.count 1 >>> t = transaction.begin() >>> demo.count 0 This also works for slot methods. >>> import BTrees >>> tree = root['tree'] = BTrees.family32.OO.BTree() >>> transaction.commit() >>> call = Partial(tree.__setitem__, 'foo', 'bar') >>> deferred = call() >>> len(tree) 0 >>> t = transaction.begin() >>> tree['foo'] 'bar' Arguments are passed through. >>> call = Partial(demo) >>> deferred = call(2) >>> t = transaction.begin() >>> demo.count 2 >>> call = Partial(demo.decrement) >>> deferred = call(amount=2) >>> t = transaction.begin() >>> demo.count 0 They can also be set during instantiation. >>> call = Partial(demo, 3) >>> deferred = call() >>> t = transaction.begin() >>> demo.count 3 >>> call = Partial(demo.decrement, amount=3) >>> deferred = call() >>> t = transaction.begin() >>> demo.count 0 Arguments themselves can be persistent objects. Let's assume a new demo2 object as well. >>> demo2.count 0 >>> def mass_increment(d1, d2, value=1): ... d1(value) ... d2(value) ... >>> call = Partial(mass_increment, demo, demo2, value=4) >>> deferred = call() >>> t = transaction.begin() >>> demo.count 4 >>> demo2.count 4 >>> demo.count = demo2.count = 0 # cleanup >>> transaction.commit() ConflictErrors make it retry. In order to have a chance to simulate a ConflictError, this time imagine we have a runner that can switch execution from the call to our code using `pause`, `retry` and `resume` (this is just for tests--remember, calls used in non-threaded Twisted should be non-blocking!) [#conflict_error_setup]_. >>> import sys >>> demo.count 0 >>> call = Partial(demo) >>> runner = Runner(call) # it starts paused in the middle of an attempt >>> call.attempt_count 1 >>> demo.count = 5 # now we will make a conflicting transaction... >>> transaction.commit() >>> runner.retry() >>> call.attempt_count # so it has to retry 2 >>> t = transaction.begin() >>> demo.count # our value hasn't changed... 5 >>> runner.resume() # but now call will be successful on the second attempt >>> call.attempt_count 2 >>> t = transaction.begin() >>> demo.count 6 By default, after five ConflictError retries, the partial fails, raising the last ConflictError. This is returned to the deferred. The failure put on the deferred will have a sanitized traceback. Here, imagine we have a deferred (named `deferred`) created from such a an event [#conflict_error_failure]_. >>> res = None >>> def get_result(r): ... global res ... res = r # we return None to quiet Twisted down on the command line ... >>> d = deferred.addErrback(get_result) >>> print res.getTraceback() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ZODB.POSException.ConflictError: database conflict error... You can control how many ConflictError (and other transaction error) retries should be performed by setting the ``max_transaction_errors`` attribute [#max_transaction_errors]_. ZEO ClientDisconnected errors are always retried, with a backoff that, by default begins at 5 seconds and is never greater than 60 seconds [#relies_on_twisted_reactor]_ [#use_original_demo]_ [#client_disconnected]_. Other errors are returned to the deferred, like a transaction error that has exceeded its available retries, as sanitized failures. >>> call = Partial(demo) >>> d = call('I do not add well with integers') >>> d = d.addErrback(get_result) >>> print res.getTraceback() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ...TypeError: unsupported operand type(s) for +=: 'int' and 'str' The failure is sanitized in that the traceback is gone and the frame values are turned in to reprs. If you pickle the failure then it truncates the reprs to a maximum of 20 characters plus "[...]" to indicate the truncation [#show_sanitation]_. The call tries to be a good connection citizen, waiting for a connection if the pool is at its maximum size. This code relies on the twisted reactor; we'll use a `time_flies` function, which takes seconds to move ahead, to simulate time passing in the reactor. We use powers of 2 for the floating-points numbers (e.g. 0.125) to avoid a floating-point additive accumulation error that happened in the tests when values such as 0.1 were used. >>> db.setPoolSize(1) >>> db.getPoolSize() 1 >>> demo.count = 0 >>> transaction.commit() >>> call = Partial(demo) >>> res = None >>> deferred = call() >>> d = deferred.addCallback(get_result) >>> call.attempt_count 0 >>> time_flies(.125) >= 1 # returns number of connection attempts True >>> call.attempt_count 0 >>> res # None >>> db.setPoolSize(2) >>> db.getPoolSize() 2 >>> time_flies(.25) >= 1 True >>> call.attempt_count > 0 True >>> res 1 >>> t = transaction.begin() >>> demo.count 1 If it takes more than a second or two, it will eventually just decide to grab one. This behavior may change. >>> db.setPoolSize(1) >>> db.getPoolSize() 1 >>> call = Partial(demo) >>> res = None >>> deferred = call() >>> d = deferred.addCallback(get_result) >>> call.attempt_count 0 >>> time_flies(.125) >= 1 True >>> call.attempt_count 0 >>> res # None >>> time_flies(2) >= 2 # for a total of at least 3 True >>> res 2 >>> t = transaction.begin() >>> demo.count 2 Without a running reactor, this functionality will not work [#teardown_monkeypatch]_. You can also specify a reactor for the partial using ``setReactor``, if you don't want to use the standard one installed by twisted in ``twisted.internet.reactor``. [#setReactor]_ Gotchas ------- For a certain class of jobs, you won't have to think much about using the twist Partial. For instance, if you are putting a result gathered by work done by deferreds into the ZODB, and that's it, everything should be pretty simple. However, unfortunately, you have to think a bit harder for other common use cases. * As already mentioned, do not use arguments that are non-persistent collections (or even persistent objects without a connection) that hold any persistent objects with connections. * Using persistent objects with connections but that have not been committed to the database will cause problems when used (as callable or argument), perhaps intermittently (if a commit happens before the partial is called, it will work). Don't do this. * Do not return values that are persistent objects tied to a connection. * If you plan on firing off another reactor call on the basis of your work in the callable, realize that the work hasn't really "happened" until you commit the transaction. The partial typically handles commits for you, committing if you return any result and aborting if you raise an error. But if you want to send off a reactor call on the basis of a successful transaction, you'll want to (a) do the work, then (b) commit, then (c) send off the reactor call. If the commit fails, you'll get the standard abort and retry. * If you want to handle your own transactions, do not use the thread transaction manager that you get from importing transaction. This will cause intermittent, hard-to-debug, unexpected problems. Instead, adapt any persistent object you get to transaction.interfaces.ITransactionManager, and use that manager for commits and aborts. ========= Footnotes ========= .. [#set_up] We'll actually create the state that the text describes here. >>> import persistent >>> class Demo(persistent.Persistent): ... count = 0 ... def __call__(self, amount=1): ... self._p_deactivate() # to be able to trigger ClientDisconnected ... self.count += amount ... return self.count ... def decrement(self, amount=1): ... self.count -= amount ... return self.count ... >>> from ZODB.tests.util import DB >>> db = DB() >>> conn = db.open() >>> root = conn.root() >>> demo = root['demo'] = Demo() >>> demo2 = root['demo2'] = Demo() >>> import transaction >>> transaction.commit() .. [#adapters] You must have two adapter registrations: IConnection to ITransactionManager, and IPersistent to IConnection. We will also register IPersistent to ITransactionManager because the adapter is designed for it. >>> from zc.twist import transactionManager, connection >>> import zope.component >>> zope.component.provideAdapter(transactionManager) >>> zope.component.provideAdapter(connection) >>> import ZODB.interfaces >>> zope.component.provideAdapter( ... transactionManager, adapts=(ZODB.interfaces.IConnection,)) This quickly tests the adapters: >>> ZODB.interfaces.IConnection(demo) is conn True >>> import transaction.interfaces >>> transaction.interfaces.ITransactionManager(demo) is transaction.manager True >>> transaction.interfaces.ITransactionManager(conn) is transaction.manager True .. [#conflict_error_setup] We also use this runner in the footnote below. >>> import threading >>> _main = threading.Lock() >>> _thread = threading.Lock() >>> class AltDemo(persistent.Persistent): ... count = 0 ... def __call__(self, amount=1): ... self.count += amount ... assert _main.locked() ... _main.release() ... _thread.acquire() ... return self.count ... >>> demo = root['altdemo'] = AltDemo() >>> transaction.commit() >>> class Runner(object): ... def __init__(self, call): ... self.call = call ... self.thread = threading.Thread(target=self.run) ... self.thread.setDaemon(True) ... _thread.acquire() ... _main.acquire() ... self.thread.start() ... _main.acquire() ... def run(self): ... self.running = True ... self.result = self.call() ... assert _main.locked() ... assert _thread.locked() ... _thread.release() ... self.running = False ... _main.release() ... def retry(self): ... assert _thread.locked() ... _thread.release() ... _main.acquire() ... def resume(self): ... while self.running: ... self.retry() ... self.thread.join() ... assert not _thread.locked() ... assert _main.locked() ... _main.release() .. [#conflict_error_failure] Here we create five consecutive conflict errors, which causes the call to give up. >>> call = Partial(demo) >>> runner = Runner(call) >>> for i in range(5): ... demo.count = i ... transaction.commit() # creates a write conflict ... runner.retry() ... >>> demo.count 4 When we resume without a conflict error, it is too late: the result is a ConflictError. The ConflictError is actually shown in the main text. >>> runner.resume() >>> demo.count 4 >>> call.attempt_count 5 >>> deferred = runner.result .. [#max_transaction_errors] As the main text mentions, the ``max_transaction_errors`` attribute lets you set how many conflict errors should be retried. >>> call = Partial(demo) >>> call.max_transaction_errors 5 >>> call.max_transaction_errors = 10 >>> call.max_transaction_errors 10 >>> runner = Runner(call) >>> for i in range(10): ... demo.count = i ... transaction.commit() ... runner.retry() ... When we resume without a conflict error, it is too late: the result is a ConflictError. >>> runner.resume() >>> demo.count 9 >>> call.attempt_count 10 >>> deferred = runner.result >>> res = None >>> def get_result(r): ... global res ... res = r # we return None to quiet Twisted down on the command line ... >>> d = deferred.addErrback(get_result) >>> print res.getTraceback() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ZODB.POSException.ConflictError: database conflict error... Setting ``None`` means to retry conflict errors forever. For our example, we will arbitrarily choose 50 iterations to show "forever". >>> call = Partial(demo) >>> call.max_transaction_errors 5 >>> call.max_transaction_errors = None >>> print call.max_transaction_errors None >>> runner = Runner(call) >>> for i in range(50): ... demo.count = i ... transaction.commit() ... runner.retry() ... Now when we resume without a conflict error, we get a successful result: it never gave up. >>> runner.resume() >>> runner.result # doctest: +ELLIPSIS <Deferred at ... current result: 50> >>> _ = transaction.begin() # we need to sync to get changes >>> demo.count # notice, 49 + 1 50 .. [#relies_on_twisted_reactor] We monkeypatch twisted.internet.reactor (and revert it in another footnote below). >>> import twisted.internet.reactor >>> oldCallLater = twisted.internet.reactor.callLater >>> import bisect >>> class FauxReactor(object): ... def __init__(self): ... self.time = 0 ... self.calls = [] ... def callLater(self, delay, callable, *args, **kw): ... res = (delay + self.time, callable, args, kw) ... bisect.insort(self.calls, res) ... # normally we're supposed to return something but not needed ... def time_flies(self, time): ... end = self.time + time ... ct = 0 ... while self.calls and self.calls[0][0] <= end: ... self.time, callable, args, kw = self.calls.pop(0) ... callable(*args, **kw) # normally this would get try...except ... ct += 1 ... self.time = end ... return ct ... >>> faux = FauxReactor() >>> twisted.internet.reactor.callLater = faux.callLater >>> time_flies = faux.time_flies .. [#use_original_demo] The second demo has too much thread code in it: we'll use the old demo for the rest of the discussion. >>> demo = root['demo'] .. [#client_disconnected] As the main text describes, ZEO.Exceptions.ClientDisconnected errors will always be retried, but with a backoff. First we'll mimic a disconnected ZEO at the start of a transaction. >>> from ZEO.Exceptions import ClientDisconnected >>> raise_error = [1] >>> storage_class = db._storage.__class__ >>> original_load = storage_class.load >>> def load(self, oid, version): ... if raise_error: ... raise_error.pop() ... raise ClientDisconnected() ... else: ... return original_load(self, oid, version) ... >>> _ = transaction.begin() >>> demo.count 0 >>> call = Partial(demo) >>> storage_class.load = load We rely on a reactor to implement delayed calls. We have a fake reactor called ``faux`` for these examples. It has a list of pending calls, and we can call ``time_flies`` to make time appear to pass. >>> len(faux.calls) 0 When we first call the partial, it will fail, and reschedule for later. >>> len(faux.calls) 0 >>> deferred = call() >>> deferred.called 0 >>> len(faux.calls) 1 The rescheduling is initially for five seconds later, by default. In this first example, after the first retry, the call will succeed. >>> faux.calls[0][0] - faux.time 5 >>> time_flies(1) # 1 second 0 >>> deferred.called 0 >>> time_flies(1) # 1 second 0 >>> deferred.called 0 >>> time_flies(1) # 1 second 0 >>> deferred.called 0 >>> time_flies(1) # 1 second 0 >>> deferred.called 0 >>> time_flies(1) # 1 second 1 >>> deferred.called True >>> deferred.result 1 >>> len(faux.calls) 0 By default, the rescheduling backoff increases by five seconds for every retry, to a maximum of a 60 second backoff. >>> call = Partial(demo) >>> raise_error.extend([1] * 30) >>> len(faux.calls) 0 >>> deferred = call() >>> deferred.called 0 >>> len(faux.calls) 1 >>> def run(deferred): ... sleeps = [] ... for i in range(31): ... if deferred.called: ... break ... else: ... sleep = faux.calls[0][0] - faux.time ... sleeps.append(sleep) ... time_flies(sleep) ... else: ... print 'oops' ... return sleeps ... >>> sleeps = run(deferred) >>> deferred.result 2 >>> len(sleeps) 30 >>> sleeps # doctest: +ELLIPSIS [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 60, 60,..., 60, 60, 60, 60] The default backoff values can be changed by setting the instance attributes ``initial_backoff``, ``backoff_increment``, and ``max_backoff``. >>> call = Partial(demo) >>> call.initial_backoff 5 >>> call.backoff_increment 5 >>> call.max_backoff 60 >>> call.initial_backoff = 4 >>> call.backoff_increment = 2 >>> call.max_backoff = 21 >>> raise_error.extend([1] * 30) >>> len(faux.calls) 0 >>> deferred = call() >>> deferred.called 0 >>> len(faux.calls) 1 >>> sleeps = run(deferred) >>> deferred.result 3 >>> len(sleeps) 30 >>> sleeps # doctest: +ELLIPSIS [4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 21, 21, 21, 21, 21,..., 21, 21, 21] A ClientDisconnected error can also occur during transaction commit. >>> storage_class.load = original_load >>> from transaction import TransactionManager >>> old_commit = TransactionManager.commit >>> commit_count = 0 >>> error = None >>> max = 2 >>> raise_error = [1] # change state to active >>> def new_commit(self): ... if raise_error: ... raise_error.pop() ... raise ClientDisconnected() ... else: ... old_commit(self) # changing state to "active" or similar ... >>> TransactionManager.commit = new_commit >>> call = Partial(demo) >>> len(faux.calls) 0 >>> deferred = call() >>> deferred.called 0 >>> len(faux.calls) 1 >>> faux.calls[0][0] - faux.time 5 >>> time_flies(4) # 4 seconds 0 >>> deferred.called 0 >>> time_flies(1) # 1 second 1 >>> deferred.called True >>> deferred.result 4 >>> len(faux.calls) 0 >>> TransactionManager.commit = old_commit >>> _ = transaction.begin() .. [#show_sanitation] Before pickling, the failure includes full information about before and after the exception was caught, as well as locals and globals. Everything has been repr'd, though, and the traceback object removed. >>> print res.getTraceback() # doctest: +ELLIPSIS Traceback (most recent call last): File ".../zc/twist/__init__.py", line ..., in __call__... File ".../twisted/internet/defer.py", line ..., in addCallback... --- <exception caught here> --- File ".../zc/twist/__init__.py", line ..., in _call... File "<doctest README.txt[...]>", line ..., in __call__... exceptions.TypeError: unsupported operand type(s) for +=: 'int' and 'str' <BLANKLINE> (The failure traceback at "verbose" detail is wildly verbose--this example takes out more than 90% of the text, just so you know.) >>> print res.getTraceback(detail='verbose') # doctest: +ELLIPSIS *--- Failure #... (pickled) --- .../zc/twist/__init__.py:...: __call__(...) [ Locals ]... args : "('I do not add well with integers',)... ( Globals )... Partial : "<class 'zc.twist.Partial'>... .../twisted/internet/defer.py:...: addCallback(...) [ Locals ]... args : '(<Deferred at ... ( Globals )... Deferred : '<class twisted.internet.defer.Deferred at ... --- <exception caught here> --- .../zc/twist/__init__.py:...: _call(...) [ Locals ]... args : "['I do not add well with integers']... ( Globals )... Partial : "<class 'zc.twist.Partial'>... <doctest README.txt[...]>:...: __call__(...) [ Locals ]... amount : "'I do not add well with integers'... ( Globals )... Partial : "<class 'zc.twist.Partial'>... exceptions.TypeError: unsupported operand type(s) for +=: 'int' and 'str' *--- End of Failure #... --- <BLANKLINE> After pickling, the failure only includes information for when the exception was caught and beyond (after the "--- <exception caught here> ---" lines above), does not have globals, and has local reprs truncated to a maximum of 20 characters plus "[...]" to indicate the truncation. This addresses past problems of large pickle size for failures, which can cause performance problems. >>> import pickle >>> print pickle.loads(pickle.dumps(res)).getTraceback() ... # doctest: +ELLIPSIS Traceback (most recent call last): File ".../zc/twist/__init__.py", line ..., in _call res = call(*args, **kwargs) File "<doctest README.txt[...]>", line ..., in __call__ self.count += amount exceptions.TypeError: unsupported operand type(s) for +=: 'int' and 'str' <BLANKLINE> >>> print pickle.loads(pickle.dumps(res)).getTraceback(detail='verbose') ... # doctest: +ELLIPSIS *--- Failure #... (pickled) --- .../src/zc/twist/__init__.py:...: _call(...) [ Locals... self : '<zc.twist.Partial obj[...]... ( Globals ) <doctest README.txt[...]>:...: __call__(...) [ Locals... amount : "'I do not add well wi[...]... ( Globals ) exceptions.TypeError: unsupported operand type(s) for +=: 'int' and 'str' *--- End of Failure #... --- <BLANKLINE> In some cases, it is possible that a Failure object may include references to itself, for example, indirectly through a zc.async job whose result is a Failure. Failure's __getstate__ method used to use deepcopy, which in cases like this could result in infinite recursion. >>> import zc.twist >>> class Kaboom(Exception): ... pass >>> class Foo(object): ... failure = None ... def fail(self): ... raise Kaboom, self >>> foo = Foo() >>> try: ... foo.fail() ... except Kaboom: ... foo.failure = zc.twist.Failure() >>> ignored = foo.failure.__getstate__() # used to cause RunTimeError. .. [#teardown_monkeypatch] >>> twisted.internet.reactor.callLater = oldCallLater .. [#setReactor] >>> db.setPoolSize(1) >>> db.getPoolSize() 1 >>> demo.count = 0 >>> transaction.commit() >>> call = Partial(demo).setReactor(faux) >>> res = None >>> deferred = call() >>> d = deferred.addCallback(get_result) >>> call.attempt_count 0 >>> time_flies(.125) >= 1 # returns number of connection attempts True >>> call.attempt_count 0 >>> res # None >>> db.setPoolSize(2) >>> db.getPoolSize() 2 >>> time_flies(.25) >= 1 True >>> call.attempt_count > 0 True >>> res 1 >>> t = transaction.begin() >>> demo.count 1 If it takes more than a second or two, it will eventually just decide to grab one. This behavior may change. >>> db.setPoolSize(1) >>> db.getPoolSize() 1 >>> call = Partial(demo).setReactor(faux) >>> res = None >>> deferred = call() >>> d = deferred.addCallback(get_result) >>> call.attempt_count 0 >>> time_flies(.125) >= 1 True >>> call.attempt_count 0 >>> res # None >>> time_flies(2) >= 2 # for a total of at least 3 True >>> res 2 >>> t = transaction.begin() >>> demo.count 2
zc.twist
/zc.twist-1.3.1.tar.gz/zc.twist-1.3.1/src/zc/twist/README.txt
README.txt
import random, types, warnings import ZODB.interfaces import ZODB.POSException import ZEO.Exceptions import transaction import transaction.interfaces import persistent import persistent.interfaces import twisted.internet.defer import twisted.internet.reactor import twisted.python.failure import zope.component import zope.interface import zc.twist._methodwrapper METHOD_WRAPPER_TYPE = type({}.__setitem__) def get_self(wrapper): if not isinstance(wrapper, METHOD_WRAPPER_TYPE): raise TypeError('unsupported type') # includes dict.__getitem__ :-/ return zc.twist._methodwrapper._get_self(wrapper) EXPLOSIVE_ERRORS = [SystemExit, KeyboardInterrupt, ZODB.POSException.POSError] # this is currently internal, though maybe we'll expose it later class IDeferredReference(zope.interface.Interface): def __call__(self, connection): """return the actual object to be used.""" db = zope.interface.Attribute(""" The associated database, or None""") class DeferredReferenceToPersistent(object): zope.interface.implements(IDeferredReference) name = None def __init__(self, obj): if isinstance(obj, types.MethodType): self.name = obj.__name__ obj = obj.im_self elif isinstance(obj, METHOD_WRAPPER_TYPE): self.name = obj.__name__ obj = get_self(obj) conn = ZODB.interfaces.IConnection(obj) self.db = conn.db() self.id = obj._p_oid def __call__(self, conn): if conn.db().database_name != self.db.database_name: conn = conn.get_connection(self.db.database_name) obj = conn.get(self.id) if self.name is not None: obj = getattr(obj, self.name) return obj def Reference(obj): if isinstance(obj, types.MethodType): if (persistent.interfaces.IPersistent.providedBy(obj.im_self) and obj.im_self._p_jar is not None): return DeferredReferenceToPersistent(obj) else: return obj if isinstance(obj, METHOD_WRAPPER_TYPE): obj_self = get_self(obj) if (persistent.interfaces.IPersistent.providedBy(obj_self) and obj_self._p_jar is not None): return DeferredReferenceToPersistent(obj) else: return obj if (persistent.interfaces.IPersistent.providedBy(obj) and obj._p_jar is not None): return DeferredReferenceToPersistent(obj) return obj def availableConnectionCount(db): try: # ZODB 3.9 and newer pool = db.pool except AttributeError: # ZODB 3.8 and older pools = db._pools pool = pools.get('') # version = '' if pool is None: return True size = db.getPoolSize() all = len(pool.all) available = len(pool.available) + (size - all) return available missing = object() def get_connection(db, deferred=None, backoff=0, reactor=None): if deferred is None: deferred = twisted.internet.defer.Deferred() backoff += random.random() / 20.0 + .0625 # 1/16 second (USE POWERS OF 2!) # if this is taking too long (i.e., the cumulative backoff is taking # more than half a second) then we'll just take one. This might be # a bad idea: we'll have to see in practice. Otherwise, if the # backoff isn't too long and we don't have a connection within our # limit, try again later. if backoff < .5 and not availableConnectionCount(db): if reactor is None: reactor = twisted.internet.reactor reactor.callLater( backoff, get_connection, db, deferred, backoff, reactor) return deferred deferred.callback(db.open( transaction_manager=transaction.TransactionManager())) return deferred def truncate(str): if len(str) > 21: # 64 bit int or so str = str[:21]+"[...]" return str class Failure(twisted.python.failure.Failure): sanitized = False def __init__(self, exc_value=None, exc_type=None, exc_tb=None): twisted.python.failure.Failure.__init__( self, exc_value, exc_type, exc_tb) self.__dict__ = twisted.python.failure.Failure.__getstate__(self) def cleanFailure(self): pass # already done def __getstate__(self): res = self.__dict__.copy() if not self.sanitized: res['stack'] = [] res['frames'] = [ [ v[0], v[1], v[2], [(j[0], truncate(j[1])) for j in v[3]], [] # [(j[0], truncate(j[1])) for j in v[4]] ] for v in self.frames ] res['sanitized'] = True return res def printTraceback( self, file=None, elideFrameworkCode=0, detail='default'): return twisted.python.failure.Failure.printTraceback( self, file, elideFrameworkCode or self.sanitized, detail) class _Dummy: # twisted.python.failure.Failure is an old-style class pass # so we use old-style hacks instead of __new__ def sanitize(failure): # failures may have some bad things in the traceback frames. This # converts everything to strings if not isinstance(failure, Failure): res = _Dummy() res.__class__ = Failure res.__dict__ = failure.__getstate__() else: res = failure return res class Partial(object): # for TransactionErrors, such as ConflictErrors transaction_error_count = 0 max_transaction_errors = 5 # for ClientDisconnected errors backoff = None initial_backoff = 5 # seconds backoff_increment = 5 # seconds max_backoff = 60 # seconds # more general values attempt_count = 0 _reactor = None def __init__(self, call, *args, **kwargs): self.call = Reference(call) self.args = list(Reference(a) for a in args) self.kwargs = dict((k, Reference(v)) for k, v in kwargs.iteritems()) def __call__(self, *args, **kwargs): self.args.extend(args) self.kwargs.update(kwargs) db = None for src in ((self.call,), self.args, self.kwargs.itervalues()): for item in src: if IDeferredReference.providedBy(item) and item.db is not None: db = item.db break else: continue break else: # no persistent bits call, args, kwargs = self._resolve(None) return call(*args, **kwargs) d = twisted.internet.defer.Deferred() get_connection(db, reactor=self.getReactor()).addCallback( self._call, d) return d def setReactor(self, value): self._reactor = value return self def getReactor(self): if self._reactor is None: return twisted.internet.reactor return self._reactor def _resolve(self, conn): if IDeferredReference.providedBy(self.call): call = self.call(conn) else: call = self.call args = [] for a in self.args: if IDeferredReference.providedBy(a): a = a(conn) args.append(a) kwargs = {} for k, v in self.kwargs.items(): if IDeferredReference.providedBy(v): v = v(conn) kwargs[k] = v return call, args, kwargs def _call(self, conn, d): self.attempt_count += 1 tm = transaction.interfaces.ITransactionManager(conn) try: tm.begin() # syncs; inside try:except because of ClientDisconnected call, args, kwargs = self._resolve(conn) res = call(*args, **kwargs) tm.commit() except ZODB.POSException.TransactionError: self.transaction_error_count += 1 tm.abort() db = conn.db() conn.close() if (self.max_transaction_errors is not None and self.transaction_error_count >= self.max_transaction_errors): res = Failure() d.errback(res) else: get_connection(db, reactor=self.getReactor()).addCallback( self._call, d) except ZEO.Exceptions.ClientDisconnected: tm.abort() db = conn.db() conn.close() if self.backoff is None: backoff = self.backoff = self.initial_backoff else: backoff = self.backoff = min( self.backoff + self.backoff_increment, self.max_backoff) reactor = self.getReactor() reactor.callLater( backoff, lambda: get_connection(db, reactor=reactor).addCallback( self._call, d)) except EXPLOSIVE_ERRORS: tm.abort() conn.close() res = Failure() d.errback(res) raise except: tm.abort() conn.close() res = Failure() d.errback(res) else: conn.close() if isinstance(res, twisted.python.failure.Failure): d.errback(sanitize(res)) elif isinstance(res, twisted.internet.defer.Deferred): res.chainDeferred(d) else: # the caller must not return any persistent objects! d.callback(res) # also register this for adapting from IConnection @zope.component.adapter(persistent.interfaces.IPersistent) @zope.interface.implementer(transaction.interfaces.ITransactionManager) def transactionManager(obj): conn = ZODB.interfaces.IConnection(obj) # typically this will be # zope.app.keyreference.persistent.connectionOfPersistent try: return conn.transaction_manager except AttributeError: return conn._txn_mgr # or else we give up; who knows. transaction_manager is the more # recent spelling. # very slightly modified from # zope.app.keyreference.persistent.connectionOfPersistent; included to # reduce dependencies @zope.component.adapter(persistent.interfaces.IPersistent) @zope.interface.implementer(ZODB.interfaces.IConnection) def connection(ob): """An adapter which gets a ZODB connection of a persistent object. We are assuming the object has a parent if it has been created in this transaction. Returns None if it is impossible to get a connection. """ cur = ob while getattr(cur, '_p_jar', None) is None: cur = getattr(cur, '__parent__', None) if cur is None: return None return cur._p_jar # The Twisted Failure __getstate__, which we use in our sanitize function # arguably out of paranoia, does a repr of globals and locals. If the repr # raises an error, they handle it gracefully. However, if the repr has side # effects, they can't know. xmlrpclib unfortunately has this problem as of # this writing. This is a monkey patch to turn off this behavior, graciously # provided by Florent Guillaume of Nuxeo. # XXX see if this can be submitted somewhere as a bug/patch for xmlrpclib import xmlrpclib def xmlrpc_method_repr(self): return '<xmlrpc._Method %s>' % self._Method__name xmlrpclib._Method.__repr__ = xmlrpc_method_repr del xmlrpclib
zc.twist
/zc.twist-1.3.1.tar.gz/zc.twist-1.3.1/src/zc/twist/__init__.py
__init__.py
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zc.twist
/zc.twist-1.3.1.tar.gz/zc.twist-1.3.1/bootstrap/bootstrap.py
bootstrap.py
import sys import persistent import zope.interface import zope.component import zope.location import zc.vault.vault import zope.publisher.browser import zope.publisher.interfaces import zope.publisher.interfaces.browser import zope.traversing.interfaces class IReadVersions(zope.interface.Interface): """abstract: see IVersions""" vault = zope.interface.Attribute( """the vault that this collection of versions uses.""") factory = zope.interface.Attribute( """the (persistable) callable that gets an inventory and returns the persistable wrapper object that has the desired API.""") def __getitem__(ix): """return version for given index, or raise KeyError if no such index exists.""" def __len__(): """return number of versions""" class IWriteVersions(zope.interface.Interface): """abstract: see IVersions""" def commit(version): """commit version""" def commitFrom(version): """commit from previous version""" def create(): """create and return an editable version of the most recently committed.""" class IVersions(IReadVersions, IWriteVersions): """a collection of versions""" class IWrapperAware(zope.interface.Interface): """A manifest that has a wrapper attribute pointing to it's desired wrapper""" wrapper = zope.interface.Attribute( """the desired wrapper""") class Versions(persistent.Persistent, zope.location.Location): """Sequence of capability family versions. Used to implement CapabilityFamily.versions """ zope.interface.implements(IVersions) def __init__(self, vault, factory, parent=None, name=None, initialize=None): self.vault = vault self.factory = factory if vault.__parent__ is None: zope.location.locate(self.vault, self, 'vault') elif parent is None: raise RuntimeError( "programmer error: Locate the vault, or pass a parent in, " "or both") if parent is not None: if name is not None: zope.location.locate(self, parent, name) else: self.__parent__ = parent for ix in range(len(vault)): i = vault.getInventory(ix) assert not IWrapperAware.providedBy(i.manifest), ( 'programmer error: manifests in vault have already been placed ' 'in a Versions container') i.__parent__ = self wrapper = self.factory(i) i.manifest.wrapper = wrapper zope.interface.directlyProvides(i.manifest, IWrapperAware) if zope.location.interfaces.ILocation.providedBy(wrapper): zope.location.locate(wrapper, self, str(i.manifest.vault_index)) if initialize is not None: res = self.create() initialize(res) self.commit(res) def __len__(self): return len(self.vault) def __getitem__(self, idx): manifest = self.vault[idx] return manifest.wrapper def __iter__(self): for m in self.vault: yield m.wrapper def commit(self, wrapper): manifest = wrapper.inventory.manifest # XXX currently .inventory is # undocumented, hard requirement of wrapper... assert manifest.wrapper is wrapper, ( 'programmer error: manifest should have back reference to ' 'version') self.vault.commit(manifest) if zope.location.interfaces.ILocation.providedBy(wrapper): zope.location.locate(wrapper, self, str(manifest.vault_index)) def commitFrom(self, wrapper): manifest = wrapper.inventory.manifest assert manifest.wrapper is wrapper, ( 'programmer error: manifest should have back reference to ' 'version') self.vault.commitFrom(manifest) i = self.vault.getInventory(-1) wrapper = self.factory(i) i.manifest.wrapper = wrapper zope.interface.directlyProvides(i.manifest, IWrapperAware) if zope.location.interfaces.ILocation.providedBy(wrapper): zope.location.locate(wrapper, self, str(i.manifest.vault_index)) def create(self): inventory = zc.vault.vault.Inventory(vault=self.vault, mutable=True) inventory.__parent__ = self res = self.factory(inventory) inventory.manifest.wrapper = res zope.interface.directlyProvides( inventory.manifest, IWrapperAware) res.__parent__ = self return res class deferredProperty(object): def __init__(self, name, initialize): self.name = name sys._getframe(1).f_locals[name] = self self.initialize = initialize def __get__(self, obj, typ=None): if obj is not None: self.initialize(obj) return obj.__dict__[self.name] return self class Traverser(zope.publisher.browser.BrowserView): zope.component.adapts( IVersions, zope.publisher.interfaces.browser.IBrowserRequest) zope.interface.implements( zope.publisher.interfaces.browser.IBrowserPublisher) _default = 'index.html' def browserDefault(self, request): return self.context, (self._default, ) def publishTraverse(self, request, name): try: ix = int(name) except ValueError: pass else: try: v = self.context[ix] except IndexError: name = self._default else: return v view = zope.component.queryMultiAdapter( (self.context, request), name=name) if view is not None: return view raise zope.publisher.interfaces.NotFound(self.context, name, request) _marker = object() class Traversable(object): """Traverses containers via `getattr` and `get`.""" zope.component.adapts(IVersions) zope.interface.implements(zope.traversing.interfaces.ITraversable) def __init__(self, context): self.context = context def traverse(self, name, furtherPath): try: ix = int(name) except ValueError: pass else: try: return self.context[ix] except IndexError: pass res = getattr(self, name, _marker) if res is _marker: raise zope.traversing.interfaces.TraversalError(name) return res
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/versions.py
versions.py
from zope import interface import zope.interface.common.mapping import zope.interface.common.sequence import zope.app.container.interfaces import zope.component.interfaces #### CONSTANTS #### # see IManifest.getType for definitions LOCAL = 'local' BASE = 'base' UPDATED = 'updated' SUGGESTED = 'suggested' MODIFIED = 'modified' MERGED = 'merged' #### EXCEPTIONS #### class OutOfDateError(ValueError): """Manifest to be committed is not based on the currently committed version """ class NoChangesError(ValueError): """Manifest to be committed has no changes from the currently committed version""" class ConflictError(ValueError): """Manifest to be committed has unresolved conflicts""" #### EVENTS #### class IMappingEvent(zope.component.interfaces.IObjectEvent): # abstract mapping = interface.Attribute( 'the affected mapping; __parent__ is relationship') key = interface.Attribute('the key affected') class IObjectRemoved(IMappingEvent): """Object was removed from mapping""" class IObjectAdded(IMappingEvent): """Object was added to mapping""" class IOrderChanged(zope.component.interfaces.IObjectEvent): """Object order changed; object is mapping""" old_keys = interface.Attribute('A tuple of the old key order') class IManifestCommitted(zope.component.interfaces.IObjectEvent): """Object is manifest.""" class ILocalRelationshipAdded(zope.component.interfaces.IObjectEvent): """Relationship added to manifest as a local version. Relationship.__parent__ must be manifest.""" class IModifiedRelationshipAdded(zope.component.interfaces.IObjectEvent): """Relationship added to manifest as a modified version. Relationship.__parent__ must be manifest.""" class ISuggestedRelationshipAdded(zope.component.interfaces.IObjectEvent): """Relationship added to manifest as a suggested version. Relationship.__parent__ must be manifest.""" class IUpdateEvent(zope.component.interfaces.IObjectEvent): source = interface.Attribute( '''source manifest (from beginUpdate) or collection (from beginCollectionUpdate)''') base = interface.Attribute( '''the base manifest from which the update proceeds, or None.''') class IUpdateBegun(IUpdateEvent): '''fired from beginUpdate or beginCollectionUpdate''' class IUpdateCompleted(IUpdateEvent): '' class IUpdateAborted(IUpdateEvent): '' class IObjectChanged(zope.component.interfaces.IObjectEvent): previous = interface.Attribute('the previous object') class IVaultChanged(zope.component.interfaces.IObjectEvent): previous = interface.Attribute('the previous vault') class IRelationshipSelected(zope.component.interfaces.IObjectEvent): """relationship was selected""" manifest = interface.Attribute( 'the manifest in which this relationship was selected') class IRelationshipDeselected(zope.component.interfaces.IObjectEvent): """relationship was deselected""" manifest = interface.Attribute( 'the manifest in which this relationship was deselected') class ObjectRemoved(zope.component.interfaces.ObjectEvent): interface.implements(IObjectRemoved) def __init__(self, obj, mapping, key): super(ObjectRemoved, self).__init__(obj) self.mapping = mapping self.key = key class ObjectAdded(zope.component.interfaces.ObjectEvent): interface.implements(IObjectAdded) def __init__(self, obj, mapping, key): super(ObjectAdded, self).__init__(obj) self.mapping = mapping self.key = key class OrderChanged(zope.component.interfaces.ObjectEvent): interface.implements(IOrderChanged) def __init__(self, obj, old_keys): super(OrderChanged, self).__init__(obj) self.old_keys = old_keys class ManifestCommitted(zope.component.interfaces.ObjectEvent): interface.implements(IManifestCommitted) class LocalRelationshipAdded(zope.component.interfaces.ObjectEvent): interface.implements(ILocalRelationshipAdded) class ModifiedRelationshipAdded(zope.component.interfaces.ObjectEvent): interface.implements(IModifiedRelationshipAdded) class SuggestedRelationshipAdded(zope.component.interfaces.ObjectEvent): interface.implements(ISuggestedRelationshipAdded) class AbstractUpdateEvent(zope.component.interfaces.ObjectEvent): def __init__(self, obj, source, base): super(AbstractUpdateEvent, self).__init__(obj) self.source = source self.base = base class UpdateBegun(AbstractUpdateEvent): interface.implements(IUpdateBegun) class UpdateCompleted(AbstractUpdateEvent): interface.implements(IUpdateCompleted) class UpdateAborted(AbstractUpdateEvent): interface.implements(IUpdateAborted) class VaultChanged(zope.component.interfaces.ObjectEvent): interface.implements(IVaultChanged) def __init__(self, obj, previous): super(VaultChanged, self).__init__(obj) self.previous = previous class ObjectChanged(zope.component.interfaces.ObjectEvent): interface.implements(IObjectChanged) def __init__(self, obj, previous): super(ObjectChanged, self).__init__(obj) self.previous = previous class RelationshipSelected(zope.component.interfaces.ObjectEvent): interface.implements(IRelationshipSelected) def __init__(self, obj, manifest): super(RelationshipSelected, self).__init__(obj) self.manifest = manifest class RelationshipDeselected(zope.component.interfaces.ObjectEvent): interface.implements(IRelationshipDeselected) def __init__(self, obj, manifest): super(RelationshipDeselected, self).__init__(obj) self.manifest = manifest #### EXCEPTIONS #### class ParentConflictError(StandardError): """the item has more than one selected parent""" class UpdateError(StandardError): """Update-related operation cannot proceed""" #### BASIC INTERFACES #### class IVersionFactory(interface.Interface): """looked up as a adapter of vault""" def __call__(object, manifest): """return the object to be stored""" class IConflictResolver(interface.Interface): """looked up as a adapter of vault.""" def __call__(manifest, local, update, base): """React to conflict between local and update as desired.""" class IUniqueReference(interface.Interface): identifiers = interface.Attribute( """An iterable of identifiers for this object. From most general to most specific. Combination uniquely identifies the object.""") def __hash__(): """return a hash of the full set of identifiers.""" def __cmp__(other): """Compare against other objects that provide IUniqueReference, using the identifiers.""" # note that btrees do not support rich comps class IToken(IUniqueReference): """An object used as a token for a manifest relationship""" class IBidirectionalNameMapping(zope.interface.common.mapping.IMapping): """all keys are unicode, all values are adaptable to IKeyReference. all values must be unique (no two keys may have the same value). items, values, keys, and __iter__ returns in the specified order.""" def getKey(value, default=None): """return key for value, or None""" def updateOrder(order): """Revise the order of keys, replacing the current ordering. order is an iterable containing the set of existing keys in the new order. `order` must contain ``len(keys())`` items and cannot contain duplicate keys. Raises ``TypeError`` if order is not iterable or any key is not hashable. Raises ``ValueError`` if order contains an invalid set of keys. """ class IRelationshipContainment(IBidirectionalNameMapping): """If __parent__.__parent__ (manifest) exists, must call manifest.approveRelationshipChange before making any changes, and should call manifest.reindex after all changes except order changes. """ __parent__ = interface.Attribute( """The IRelationship of this containment before versioning (may be reused for other relationships after versioning).""") class IRelationship(IUniqueReference): """The relationship for mapping a token to its contents and its object. Not mutable if can_modify is False.""" token = interface.Attribute( """The token that this relationship maps""") __parent__ = interface.Attribute( """The manifest of this relationship before versioning (may be reused for other manifests after being versioned)""") object = interface.Attribute( """the object that the token represents for this relationship. if __parent__ exists (manifest), should call manifest.approveRelationshipChange before making any changes, and call manifest.reindex after change.""") containment = interface.Attribute( """The IRelationshipContainment, mapping names to contained tokens, for this relationship.""") children = interface.Attribute( """readonly: the containment.values(). modify with the containment.""" ) class IContained(IBidirectionalNameMapping): """Abstract interface.""" previous = interface.Attribute( """The IContained in the vault's previous inventory, or None if it has no previous version. May be equal to (have the same relationship as) this IContained.""") next = interface.Attribute( """The IContained in the vault's next inventory, or None if it has no next version. May be equal to (have the same relationship as) this IContained.""") previous_version = interface.Attribute( """The previous version of the IContained in the vault, or None if it has no previous version. Will never be equal to (have the same relationship as) this IContained.""") next_version = interface.Attribute( """The next version of the IContained in the vault, or None if it has no next version. Will never be equal to (have the same relationship as) this IContained.""") __parent__ = interface.Attribute( """the inventory to which this IContained belongs; same as inventory. """) inventory = interface.Attribute( """the inventory to which this IContained belongs; same as __parent__. """) relationship = interface.Attribute( """The relationship that models the containment and object information for the token.""") token = interface.Attribute( """The token assigned to this IContained's relationship. Synonym for .relationship.token""") def __call__(name): """return an IContained for the name, or raise Key Error""" def makeMutable(): """convert this item to a mutable version if possible. XXX""" type = interface.Attribute( '''readonly; one of LOCAL, BASE, MERGED, UPDATED, SUGGESTED, MODIFIED. see IManifest.getType (below) for definitions.''') selected = interface.Attribute( '''readonly boolean; whether this item is selected. Only one item (relationship) may be selected at a time for a given token in a given inventory''') selected_item = interface.Attribute( '''the selected version of this item''') def select(): '''select this item, deselecting any other items for the same token''' is_update_conflict = interface.Attribute( '''whether this is an unresolved update conflict''') def resolveUpdateConflict(): '''select this item and mark the update conflict as resolved.''' has_base = interface.Attribute("whether item has a base version") has_local = interface.Attribute("whether item has a local version") has_updated = interface.Attribute("whether item has an updated version") has_suggested = interface.Attribute( "whether item has any suggested versions") has_modified = interface.Attribute( "whether item has any modified versions") has_merged = interface.Attribute( "whether item has any merged versions") base_item = interface.Attribute('''the base item, or None''') local_item = interface.Attribute('''the local item, or None''') updated_item = interface.Attribute('''the updated item, or None''') def iterSuggestedItems(): """iterate over suggested items""" def iterModifiedItems(): """iterate over modified items""" def iterMergedItems(): """iterate over merged items""" def updateOrderFromTokens(order): """Revise the order of keys, replacing the current ordering. order is an iterable containing the set of tokens in the new order. `order` must contain ``len(keys())`` items and cannot contain duplicate values. XXX what exceptions does this raise? """ class IInventoryContents(IContained): """The top node of an inventory's hierarchy""" class IInventoryItem(IContained): is_orphan = interface.Attribute( '''whether this item cannot be reached from the top of the inventory's hierarchy via selected relationships/items''') is_orphan_conflict = interface.Attribute( '''whether this is an orphan (see is_orphan) that is not BASE or MERGED and not resolved.''') def resolveOrphanConflict(): '''resolve the orphan conflict so that it no longer stops committing or completing an update''' is_parent_conflict = interface.Attribute( '''whether this object has more than one selected parent''') parent = interface.Attribute( """The effective parent of the IContained. Always another IContained, or None (for an IInventoryContents). Will raise ParentConflictError if multiple selected parents.""") name = interface.Attribute( """The effective name of the IContained. Always another IContained, or None (for an IInventoryContents). Will raise ParentConflictError if multiple selected parents.""") def iterSelectedParents(): '''iterate over all selected parents''' def iterParents(): '''iterate over all parents''' object = interface.Attribute( """the object to which this IContained's token maps. The vault_contents for the vault's top_token""") def copyTo(location, name=None): """make a clone of this node and below in location. Does not copy actual object(s): just puts the same object(s) in an additional location. Location must be an IContained. Copying to another inventory is currently undefined. """ def moveTo(location=None, name=None): """move this object's tree to location. Location must be an IMutableContained from the same vault_contents. Not specifying location indicates the current location (merely a rename).""" copy_source = interface.Attribute( '''the item representing the relationship and inventory from which this item's relationship was created.''') class IInventory(interface.Interface): """IMPORTANT: the top token in an IInventory (and IManifest) is always zc.vault.keyref.top_token.""" manifest = interface.Attribute( """The IManifest used by this inventory""") def iterUpdateConflicts(): '''iterate over the unresolved items that have update conflicts''' def iterUpdateResolutions(): '''iterate over the resolved items that have update conflicts''' def iterOrphanConflicts(): '''iterate over the current unresolved orphan conflicts''' def iterOrphanResolutions(): '''iterate over the current resolved orphan conflicts''' def iterUnchangedOrphans(): '''iterate over the orphans that do not cause conflicts--the ones that were not changed, so are either in the base or a merged inventory.''' def iterParentConflicts(): '''iterate over the items that have multiple parents. The only way to resolve these is by deleting the item in one of the parents.''' def __iter__(): '''iterates over all selected items, whether or not they are orphans. ''' updating = interface.Attribute( '''readonly boolean: whether inventory is updating''') merged_sources = interface.Attribute( '''a tuple of the merged sources for this item.''') update_source = interface.Attribute( '''the source currently used for an update, or None if not updating''') def beginUpdate(inventory=None, previous=None): """begin update. Fails if already updating. if inventory is None, uses the current vault's most recent checkin. if previous is None, calculates most recent shared base. """ def completeUpdate(): """complete update, moving update to merged. Fails if any update, orphan, or parent conflicts.""" def abortUpdate(): """returns to state before update, discarding all changes made during the update.""" def beginCollectionUpdate(items): """start an update based on just a collection of items""" def iterChangedItems(source=None): '''iterate over items that have changed from source. if source is None, use previous.''' def getItemFromToken(token, default=None): """get an item for the token in this inventory, or return default.""" previous = interface.Attribute('the previous inventory in the vault') next = interface.Attribute('the next inventory in the vault') class IVault(zope.app.container.interfaces.IContained, zope.interface.common.sequence.IFiniteSequence): """A read sequence of historical manifests. The oldest is 0, and the most recent is -1.""" manifest = interface.Attribute( """The most recent committed manifest (self[-1])""") def getPrevious(relationship): '''return the previous version of the relationship (based on token) or None''' def getNext(relationship): '''return the next version of the relationship (based on token) or None''' def commit(manifest): """XXX""" def commitFrom(manifest): """XXX""" class IInventoryVault(IVault): """commit and commitFrom also take inventories""" inventory = interface.Attribute( """The most recent committed inventory (self.getInventory(-1))""") def getInventory(self, ix): """return IInventory for relationship set at index ix""" class IManifest(interface.Interface): """IMPORTANT: the top token in an IManifest (and IInventory) is always zc.vault.keyref.top_token.""" # should manifests know all of the manifests # they have generated (working copies)? Maybe worth keeping track of? vault_index = interface.Attribute( 'the index of the manifest in its vault') held = interface.Attribute( """Container of any related objects held because they were nowhere else. """) def getBaseSources(): '''iterate over all bases (per vault)''' def getBaseSource(vault): '''get the base for the vault''' base_source = interface.Attribute('''the base of the set''') vault = interface.Attribute('the vault for this relationship set') vault_index = interface.Attribute('the index of this set in the vault') merged_sources = interface.Attribute( '''a tuple of the non-base merged sources, as found in getBase.''') update_source = interface.Attribute( '''the manifest used for the upate''') update_base = interface.Attribute( '''the manifest for the shared ancestor that the two manifests share''' ) updating = interface.Attribute( '''boolean. whether in middle of update.''') base_source = interface.Attribute( """the manifest used as a base for this one.""") def addLocal(relationship): '''add local copy except during update. If no other relationship exists for the token, select it. If no relationship already exists for the child tokens, disallow, raising ValueError.''' def addModified(relationship): '''add modified copies during update If no other relationship exists for the token, select it. If no relationship already exists for the child tokens, disallow, raising ValueError.''' def addSuggested(relationship): '''add suggested copies during update. Another relationship must already exist in the manifest for the relationship's token.''' def checkRelationshipChange(relationship): """raise errors if the relationship may not be changed. UpdateError if the manifest is updating and the relationship is LOCAL; TypeError (XXX?) if the relationship is SUGGESTED or UPDATED""" def beginUpdate(source=None, base=None): '''begin an update. Calculates update conflicts, tries to resolve. If source is None, uses vault's most recent manifest. If base is None, uses the most recent shared base between this manifest and the source, if any. if already updating, raise UpdateError. update conflicts (different changes from the base both locally and in the source) are given to an interfaces.IConflictResolver, if an adapter to this interface is provided by the vault, to do with as it will (typically including making suggestions and resolving).''' def beginCollectionUpdate(source): '''cherry-pick update interface: CURRENTLY IN FLUX''' def completeUpdate(): '''moves update source to bases; turns off updating; discards unused suggested, modified, and local relationships. Newer versions of the bases of the update source will replace the bases of this manifest. if a BASE or MERGED relationship (see getType for definitions) is selected and its source is no longer a part of the bases after the bases are replaced, a new (mutable) copy is created as a local relationship.''' def abortUpdate(): '''return manifest to state before beginUpdate.''' def iterChanges(base=None): ''''iterate over all selected relationships that differ from the base. if base is not given, uses self.base_source''' def reindex(relationship): '''reindex the relationship after a change: used by relationships.''' def get(token, default=None): '''return the currently selected relationship for the token''' def getType(relationship): '''return type of relationship: one of BASE, LOCAL, UPDATED, SUGGESTED, MODIFIED, MERGED (see constants in this file, above). BASE relationships are those in the base_source (which is the manifest from the current vault on which this manifest was based). There will only be zero or one BASE relationship for any given token in a manifest. LOCAL relationships are new relationships added (replacing or in addition to BASE) when not updating. They may not be modified while the manifest is updating. There will only be zero or one LOCAL relationship for any given token in a manifest. UPDATED relationships only are available in this manifest while updating, and are relationships changed from the BASE of the same token. They may not be modified, even if they have not been versioned (e.g., added via `beginCollectionUpdate`). There will only be zero or one UPDATED relationship for any given token in a manifest. SUGGESTED relationships only exist while updating, and are intended to be relationships that an IConflictResolver created (although the resolvers have free reign). They may not be modified, even if they have not been versioned. There will be zero or more (unbounded) SUGGESTED relationships for any given token in a manifest. All MODIFIED relationships are discarded after an `abortUpdate`. MODIFIED relationships only exist while updating, and are the only relationships that may be modified while updating. There will be zero or more (unbounded) MODIFIED relationships for any given token in a manifest. Unselected MODIFIED relationships are discarded after an `completeUpdate`, and all MODIFIED relationships are discarded after an `abortUpdate`. MERGED relationships are those in the manifests returned by `getBaseSources` that are not the `base_source`: that is, typically those in manifests that have been merged into this one. There will be zero or more MERGED relationships--no more than `len(self.getBaseSources()) -1`--in a manifest for a given token. ''' def isSelected(relationship): '''bool whether relationship is selected''' def select(relationship): '''select the relationship for the given token. There should always be one and only one selected relationship for any given token known about by the manifest.''' def getBase(token, default=None): '''Get the base relationship for the token, or default if None''' def getLocal(token, default=None): '''Get the local relationship for the token, or default if None''' def getUpdated(token, default=None): '''Get the updated relationship for the token, or default if None''' def iterSuggested(token): '''Iterate over suggested relationships for the token.''' def iterModified(token): '''Iterate over modified relationships for the token.''' def iterMerged(token): '''Iterate over merged relationships for the token.''' def iterSelectedParents(token): '''Iterate over selected parent for the token. If there is more than one, it is a parent conflict; if there are none and the token is not the zc.vault.keyref.top_token, it is an orphan.''' def iterParents(token): '''iterate over all possible parents, selected and unselected, for the token''' def isLinked(token, child): '''returns boolean, whether child token is transitively linked beneath token using only selected relationships.''' def iterUpdateConflicts(): '''iterate over unresolved update conflicts.''' def iterUpdateResolutions(): '''iterate over resolved update conflicts.''' def isUpdateConflict(token): '''returns boolean, whether token is an unresolved update conflict.''' def resolveUpdateConflict(token): '''resolve the update conflict ("stop complaining, and use whatever is selected")''' def iterOrphanConflicts(): '''iterate over unresolved orphan conflicts--selected relationships changed from the BASE and MERGED relationships.''' def iterOrphanResolutions(): '''iterate over resolved orphan conflicts.''' def isOrphan(token): '''Whether token is an orphan.''' def isOrphanConflict(token): '''Whether token is an unresolved orphan token, as found in iterOrphanConflicts''' def resolveOrphanConflict(token): '''resolve the orphan conflict''' def undoOrphanConflictResolution(token): '''undo orphan conflict resolution''' def iterParentConflicts(): '''iterate over all selected relationships that have more than one parent.''' def iterAll(): '''iterate over all relationships known (of all types)''' def iterSelections(): '''iterate over all selected relationships.''' def __iter__(): '''iterate over linked, selected relationships: selected non-orphans. ''' def iterUnchangedOrphans(): '''iterate over BASE and MERGED orphans (that do not cause conflicts) ''' next = interface.Attribute('the next manifest in the vault') previous = interface.Attribute( "the previous manifest in the vault, or from a branch's source") def isOption(relationship): """boolean, whether relationship is known (in iterAll)"""
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/interfaces.py
interfaces.py
from ZODB.interfaces import IConnection from BTrees import IOBTree, OIBTree, OOBTree, IFBTree, Length import persistent from zope import interface, component, event import zope.lifecycleevent import zope.location import zope.location.interfaces import zope.app.container.contained from zope.app.container.interfaces import INameChooser import zope.app.intid import zope.app.intid.interfaces from zc.relationship import index import zc.freeze import zc.freeze.interfaces import zope.app.keyreference.interfaces import rwproperty from zc.vault import interfaces, keyref # vault -> relationships -> relationship -> mapping # -> held # XXX Missing relationships (child token without matching selected # relationship) is handled but not very gracefully. Especially a problem with # beginCollectionUpdate. Other situations are addressed in reindex. class approvalmethod(object): def __init__(self, reindex=False): self.reindex = reindex def __call__(self, func): self.func = func return self.wrapper def wrapper(self, wself, *args, **kwargs): manifest = None rel = wself.__parent__ if rel is not None: manifest = rel.__parent__ if manifest is not None: if rel.token is None: raise ValueError( 'cannot change containment without token on ' 'relationship') manifest.checkRelationshipChange(rel) self.func(wself, *args, **kwargs) if self.reindex and manifest is not None: manifest.reindex(rel) class Mapping(persistent.Persistent, zc.freeze.Freezing): interface.implements(interfaces.IRelationshipContainment) __parent__ = None def __init__(self, data=None): self._forward = OIBTree.OIBTree() self._reverse = IOBTree.IOBTree() self._length = Length.Length() self._order = () if data is not None: self.update(data) def __len__(self): return self._length.value def __getitem__(self, key): return self._forward[key] def get(self, key, default=None): return self._forward.get(key, default) def items(self): return [(k, self._forward[k]) for k in self._order] def keys(self): return self._order def values(self): return [self._forward[k] for k in self._order] @property def valuesBTree(self): # for optimization return self._reverse @property def keysBTree(self): # for symmetry :-) return self._forward def __iter__(self): return iter(self._order) def __contains__(self, key): return key in self._forward has_key = __contains__ def getKey(self, value, default=None): if not isinstance(value, int): return default return self._reverse.get(value, default) @zc.freeze.method @approvalmethod(reindex=True) def __delitem__(self, key): self._delitem(key) def _delitem(self, key): old = self._forward.pop(key) order = list(self._order) order.remove(key) self._order = tuple(order) self._reverse.pop(old) self._length.change(-1) event.notify(interfaces.ObjectRemoved(old, self, key)) @zc.freeze.method @approvalmethod(reindex=True) def __setitem__(self, key, value): self._setitem(key, value) def _setitem(self, key, value): bad = False if isinstance(key, basestring): try: unicode(key) except UnicodeError: bad = True else: bad = True if bad: raise TypeError("'%s' is invalid, the key must be an " "ascii or unicode string" % key) if len(key) == 0: raise ValueError("The key cannot be an empty string") if not isinstance(value, int): raise ValueError("The value must be an integer") old_key = self._reverse.get(value) if old_key is not None: if old_key != key: raise ValueError( 'name mapping can only contain unique values') # else noop else: old_value = self._forward.get(key) if old_value is None: self._order += (key,) self._length.change(1) else: old_old_key = self._reverse.pop(old_value) assert old_old_key == key self._forward[key] = value self._reverse[value] = key if old_value is not None: event.notify(interfaces.ObjectRemoved(old_value, self, key)) event.notify(interfaces.ObjectAdded(value, self, key)) @zc.freeze.method @approvalmethod(reindex=True) def update(self, data): if getattr(data, 'keys', None) is not None: data = [(k, data[k]) for k in data.keys()] if len(self): # since duplication of values is disallowed, we need to remove # any current overlapped values so we don't get spurious errors. keys = set() probs = [] for k, v in data: keys.add(k) old_k = self._reverse.get(v) if old_k is not None and old_k != k: probs.append((old_k, v)) for k, v in probs: if k not in keys: raise ValueError( 'name mapping can only contain unique values', v) for k, v in probs: self._delitem[k] for k, v in data: self._setitem(k, v) @zc.freeze.method @approvalmethod(reindex=False) def updateOrder(self, order): order = tuple(order) if self._order != order: if len(order) != len(self): raise ValueError('Incompatible key set.') for k in order: if k not in self._forward: raise ValueError('Incompatible key set.') old_order = self._order self._order = order event.notify(interfaces.OrderChanged(self, old_order)) def __eq__(self, other): return self is other or ( (interfaces.IBidirectionalNameMapping.providedBy(other) and self.keys() == other.keys() and self.values() == other.values())) def __ne__(self, other): return not (self == other) class Relationship(keyref.Token, zc.freeze.Freezing): interface.implements(interfaces.IRelationship) _token = _copy_source = None def __init__(self, token=None, object=None, containment=None, relationship=None, source_manifest=None): if source_manifest is not None: if relationship is None: raise ValueError( 'source_inventory must be accompanied with relationship') if relationship is not None: if (source_manifest is None and relationship.__parent__ is not None): tmp = getattr( relationship.__parent__, '__parent__', None) if interfaces.IManifest.providedBy(tmp): source_manifest = tmp if source_manifest is not None: self._copy_source = (relationship, source_manifest) if object is not None or containment is not None: raise ValueError( 'cannot specify relationship with object or containment') object = relationship.object containment = relationship.containment if token is not None: if not isinstance(token, int): raise ValueError('token must be int') self._token = token self._object = object self._containment = Mapping(containment) self._containment.__parent__ = self @property def copy_source(self): # None or tuple of (relationship, inventory) return self._copy_source @zc.freeze.method def _z_freeze(self): if self.token is None: raise zc.freeze.interfaces.FreezingError( 'Cannot version without a token') vault = self.__parent__.vault if not self.containment._z_frozen: prev = vault.getPrevious(self) if prev is not None: if prev.containment == self.containment: assert prev.containment._z_frozen self._containment = prev.containment if not self._containment._z_frozen: self.containment._z_freeze() if self._object is not None: obj_v = zc.freeze.interfaces.IFreezing(self.object) if not obj_v._z_frozen: factory = interfaces.IVersionFactory(vault, None) if factory is not None: res = factory(self.object, self.__parent__) if res is not self.object: self.object = res obj_v = zc.freeze.interfaces.IFreezing(res) if not obj_v._z_frozen: obj_v._z_freeze() super(Relationship, self)._z_freeze() @property def token(self): return self._token @rwproperty.setproperty def token(self, value): if self._token is None: self._token = value elif not isinstance(value, int): raise ValueError('token must be int') else: self._token = value @property def object(self): return self._object @zc.freeze.setproperty def object(self, value): if self.token is None and self.__parent__ is not None: raise ValueError('cannot change object without token') if self.token == self.__parent__.vault.top_token: raise ValueError('cannot set object of top token') if (value is not None and not zc.freeze.interfaces.IFreezable.providedBy(value)): raise ValueError( 'can only place freezable objects in vault, or None') if self.__parent__ is not None: self.__parent__.checkRelationshipChange(self) if value is not self._object: old = self._object self._object = value if (self.__parent__ is not None and self.__parent__.getType(self) is not None): self.__parent__.reindex(self) event.notify(interfaces.ObjectChanged(self, old)) @property def containment(self): return self._containment @property def children(self): return self.containment.valuesBTree def localDump(obj, index, cache): # NOTE: a reference to this function is persisted! return index.__parent__.vault.intids.register(obj) def localLoad(token, index, cache): # NOTE: a reference to this function is persisted! return index.__parent__.vault.intids.getObject(token) class Manifest(persistent.Persistent, zc.freeze.Freezing, zope.app.container.contained.Contained): interface.implements(interfaces.IManifest) _updateSource = _updateBase = None def __init__(self, base=None, vault=None): if vault is None: if base is None: raise ValueError('must provide base or vault') vault = base.vault elif base is not None: if base.vault is not vault and base.getBaseSource(vault) is None: raise ValueError( "explicitly passed vault must have a base in base_source.") else: # vault but not base base = vault.manifest if base is not None and not base._z_frozen: raise ValueError('base must be versioned') self.__parent__ = self._vault = vault self._index = index.Index( ({'element':interfaces.IRelationship['token'], 'dump': None, 'load': None, 'btree': IOBTree}, interfaces.IRelationship['object'], {'element':interfaces.IRelationship['children'], 'multiple': True, 'dump': None, 'load': None, 'name': 'child', 'btree': IOBTree}), index.TransposingTransitiveQueriesFactory('token', 'child'), localDump, localLoad) self._index.__parent__ = self self._selections = IFBTree.IFTreeSet() self._oldSelections = IFBTree.IFTreeSet() self._conflicts = IFBTree.IFTreeSet() self._resolutions = IFBTree.IFTreeSet() self._orphanResolutions = IFBTree.IFTreeSet() self._oldOrphanResolutions = IFBTree.IFTreeSet() self._updated = IFBTree.IFTreeSet() self._local = IFBTree.IFTreeSet() self._suggested = IFBTree.IFTreeSet() self._modified = IFBTree.IFTreeSet() self._bases = IOBTree.IOBTree() if base: self._indexBases(base.getBaseSources(), base, True) if vault.held is None: self._held = HeldContainer() zope.location.locate(self._held, self, "held") else: self._held = vault.held @property def held(self): return self._held def _indexBases(self, bases, base=None, select=False): intids = component.getUtility(zope.app.intid.interfaces.IIntIds) bases = dict((intids.register(b.vault), b) for b in bases) if base is not None: bid = intids.register(base.vault) bases[bid] = base else: bid = None assert not self._bases, ( 'programmer error: _indexBases should not be called with ' 'populated _bases') for iid, b in bases.items(): select_this = select and iid==bid base_set = IFBTree.IFTreeSet() data = (base_set, b) register = self.vault.intids.register for rel in b: rid = register(rel) base_set.insert(rid) if select_this: self._selections.insert(rid) event.notify(interfaces.RelationshipSelected(rel, self)) self._index.index_doc(rid, rel) self._bases[iid] = data zc.freeze.makeProperty('vault_index') def getBaseSources(self): return tuple(data[1] for data in self._bases.values()) def getBaseSource(self, vault): intids = component.getUtility(zope.app.intid.interfaces.IIntIds) iid = intids.queryId(vault) if iid is not None: data = self._bases.get(iid) if data is not None: return data[1] @property def base_source(self): return self.getBaseSource(self.vault) _vault = None @property def vault(self): return self._vault @zc.freeze.setproperty def vault(self, value): if self.updating: raise interfaces.UpdateError('Cannot change vault while updating') if value is not self._vault: old = self._vault s = set(old.intids.getObject(t) for t in self._selections) bases = tuple(self.getBaseSources()) self._selections.clear() l = set(old.intids.getObject(t) for t in self._local) self._local.clear() self._index.clear() self._bases.clear() self._vault = value self._indexBases(bases) for r in l: self._add(r, self._local, True) self._selections.update(value.intids.register(r) for r in s) event.notify(interfaces.VaultChanged(self, old)) @property def merged_sources(self): v = self.vault return tuple(b for b in self.getBaseSources() if b.vault is not v) @property def update_source(self): return self._updateSource @property def update_base(self): return self._updateBase @property def updating(self): return self._updateSource is not None @zc.freeze.method def _z_freeze(self): if self.updating: raise zc.freeze.interfaces.FreezingError( 'cannot version during update') if (list(self.iterParentConflicts()) or list(self.iterOrphanConflicts())): raise zc.freeze.interfaces.FreezingError( 'cannot version with conflicts') selections = set(self._iterLinked()) b = base = self.base_source for r in list(self._local): if r not in selections: self._local.remove(r) self._index.unindex_doc(r) else: rel = self.vault.intids.getObject(r) if base is not None: b = base.get(rel.token) if (b is None or b.object is not rel.object or b.containment != rel.containment): if not rel._z_frozen: rel._z_freeze() else: selections.remove(r) self._local.remove(r) selections.add(self.vault.intids.getId(b)) self._index.unindex_doc(r) self._selections.clear() self._selections.update(selections) super(Manifest, self)._z_freeze() def _locateObject(self, relationship, force=False): if not force: for child in relationship.children: if self.get(child) is None: raise ValueError( 'child tokens must have selected relationships') if relationship.token == self.vault.top_token: assert relationship.object is None return obj = relationship.object if obj is not None and getattr(obj, '__parent__', None) is None: if zope.location.interfaces.ILocation.providedBy(obj): dest = self.held dest[INameChooser(dest).chooseName('', obj)] = obj else: obj.__parent__ = self.vault def _add(self, relationship, set, force=False): self._locateObject(relationship, force) if relationship.__parent__ is not self: if relationship.__parent__ is None: relationship.__parent__ = self else: raise ValueError( 'cannot add relationship already in another set') iid = self.vault.intids.register(relationship) set.insert(iid) self._index.index_doc(iid, relationship) @zc.freeze.method def addLocal(self, relationship): if self.updating: raise interfaces.UpdateError( 'cannot add local relationships during update') if self.getLocal(relationship.token) is not None: raise ValueError( 'cannot add a second local relationship for the same token') self._add(relationship, self._local) event.notify(interfaces.LocalRelationshipAdded(relationship)) if len(self._index.findRelationshipTokenSet( self._index.tokenizeQuery({'token': relationship.token}))) == 1: self.select(relationship) @zc.freeze.method def addModified(self, relationship): if not self.updating: raise interfaces.UpdateError( 'can only add modified relationships during update') self._add(relationship, self._modified) event.notify(interfaces.ModifiedRelationshipAdded(relationship)) if len(self._index.findRelationshipTokenSet( self._index.tokenizeQuery({'token': relationship.token}))) == 1: self.select(relationship) @zc.freeze.method def addSuggested(self, relationship): if not self.updating: raise interfaces.UpdateError( 'can only add suggested relationships during update') if len(self._index.findRelationshipTokenSet( {'token': relationship.token})) == 0: raise ValueError('cannot add suggested relationship for new token') self._add(relationship, self._suggested) event.notify(interfaces.SuggestedRelationshipAdded(relationship)) @zc.freeze.method def beginUpdate(self, source=None, base=None): if self.updating: raise interfaces.UpdateError( 'cannot begin another update while updating') if source is None: source = self.vault.manifest if not interfaces.IManifest.providedBy(source): raise ValueError('source must be manifest') if source.vault.intids is not self.vault.intids: raise ValueError('source must share intids') if base is None: if self.base_source is None or source.vault != self.vault: myBase = self.getBaseSource(source.vault) otherBase = source.getBaseSource(self.vault) if myBase is None: if otherBase is None: # argh. Need to walk over all bases and find any # shared ones. Then pick the most recent one. for b in self.getBaseSources(): if b.vault == self.vault: continue o = source.getBaseSource(b.vault) if o is not None: # we found one! if (o._z_freeze_timestamp > b._z_freeze_timestamp): b = o if base is None or ( b._z_freeze_timestamp > base._z_freeze_timestamp): base = b if base is None: raise ValueError('no shared previous manifest') else: base = otherBase elif (otherBase is None or otherBase._z_freeze_timestamp <= myBase._z_freeze_timestamp): base = myBase else: base = otherBase else: base = self.base_source if base is source: raise ValueError('base is source') elif base._z_freeze_timestamp > source._z_freeze_timestamp: raise NotImplementedError( "don't know how to merge to older source") if not interfaces.IManifest.providedBy(base): raise ValueError('base must be manifest') if not source._z_frozen or not base._z_frozen: raise ValueError('manifests must be versioned') intids = self.vault.intids self._oldSelections.update(self._selections) self._oldOrphanResolutions.update(self._orphanResolutions) self._updateSource = source self._updateBase = base to_be_resolved = [] for s in source: b = base.get(s.token) source_changed = (b is None or s.object is not b.object or s.containment != b.containment) l = self.get(s.token) if l is None: # even if base is non-None, that change is elsewhere local_changed = False elif b is None: local_changed = True else: local_changed = l is not b and ( l.object is not b.object or l.containment != b.containment) if source_changed: iid = intids.register(s) self._updated.insert(iid) self._index.index_doc(iid, s) if local_changed: self._conflicts.insert(s.token) if l is not s and (l.object is not s.object or l.containment != s.containment): # material difference. Give resolver a chance. to_be_resolved.append((l, s, b)) else: # we'll use the merged version by default self.select(s) self._resolutions.insert(s.token) else: self.select(s) if to_be_resolved: resolver = interfaces.IConflictResolver(self.vault, None) if resolver is not None: for l, s, b in to_be_resolved: resolver(self, l, s, b) event.notify(interfaces.UpdateBegun(self, source, base)) @zc.freeze.method def beginCollectionUpdate(self, source): if self.updating: raise interfaces.UpdateError( 'cannot begin another update while updating') source = set(source) token_to_source = dict((r.token, r) for r in source) if len(token_to_source) < len(source): raise ValueError( 'cannot provide more than one update relationship for the ' 'same source') for rel in source: if rel.__parent__.vault.intids is not self.vault.intids: raise ValueError('sources must share intids') for child in rel.children: if (token_to_source.get(child) is None and self.get(child) is None): raise ValueError( 'cannot update from a set that includes children ' 'tokens without matching relationships in which the ' 'child is the token') intids = self.vault.intids self._oldSelections.update(self._selections) self._oldOrphanResolutions.update(self._orphanResolutions) tmp_source = set() for rel in source: if not rel._z_frozen: if rel.__parent__ is not None and rel.__parent__ is not self: rel = Relationship(rel.token, relationship=rel) rel.__parent__ = self event.notify( zope.lifecycleevent.ObjectCreatedEvent(rel)) self._add(rel, self._updated, force=True) else: iid = intids.register(rel) self._updated.insert(iid) self._locateObject(rel, force=True) self._index.index_doc(iid, rel) tmp_source.add(rel) local = self.getLocal(rel.token) if local is not None: self._conflicts.insert(rel.token) if (local.object is rel.object and local.containment == rel.containment): self._resolutions.insert(rel.token) else: resolver = component.queryMultiAdapter( (local, rel, None), interfaces.IConflictResolver) if resolver is not None: resolver(self) else: self.select(rel) self._updateSource = frozenset(tmp_source) assert not self._getChildErrors() event.notify(interfaces.UpdateBegun(self, source, None)) def _selectionsFilter(self, relchain, query, index, cache): return relchain[-1] in self._selections def _iterLinked(self): for p in self._index.findRelationshipTokenChains( {'token': self.vault.top_token}, filter=self._selectionsFilter): yield p[-1] def completeUpdate(self): source = self._updateSource if source is None: raise interfaces.UpdateError('not updating') if (list(self.iterUpdateConflicts()) or list(self.iterParentConflicts()) or list(self.iterOrphanConflicts())): raise interfaces.UpdateError( 'cannot complete update with conflicts') assert not self._getChildErrors(), 'children without relationships!' manifest = interfaces.IManifest.providedBy(source) # assemble the contents of what will be the new bases intids = self.vault.intids selected = set(self._iterLinked()) base = self._updateBase self._updateSource = self._updateBase = None self._selections.clear() self._selections.update(selected) self._local.clear() self._index.clear() self._updated.clear() self._modified.clear() self._suggested.clear() self._conflicts.clear() self._resolutions.clear() self._orphanResolutions.clear() self._oldOrphanResolutions.clear() self._oldSelections.clear() bases = self.getBaseSources() self._bases.clear() if manifest: global_intids = component.getUtility( zope.app.intid.interfaces.IIntIds) bases = dict((global_intids.register(b.vault), b) for b in bases) for b in source.getBaseSources(): iid = global_intids.register(b.vault) o = bases.get(iid) if o is None or o._z_freeze_timestamp < b._z_freeze_timestamp: bases[iid] = b self._indexBases(bases.values(), source) existing = IFBTree.multiunion( [data[0] for data in self._bases.values()]) for i in selected: orig = rel = intids.getObject(i) if rel._z_frozen: create_local = False source_rel = source.get(rel.token) if source_rel is rel: create_local = True elif source_rel is not None: base_rel = base.get(rel.token) if (base_rel is None or source_rel._z_freeze_timestamp > base_rel._z_freeze_timestamp): create_local = True if create_local: rel = Relationship( rel.token, relationship=rel, source_manifest=self) rel.__parent__ = self event.notify( zope.lifecycleevent.ObjectCreatedEvent(rel)) else: continue self._add(rel, self._local, True) event.notify(interfaces.LocalRelationshipAdded(rel)) if orig is not rel: self._selections.remove(i) self.select(rel) else: self._indexBases(bases) existing = IFBTree.multiunion( [data[0] for data in self._bases.values()]) for i in selected: if i not in existing: rel = intids.getObject(i) if rel._z_frozen: rel = Relationship( rel.token, relationship=rel, source_manifest=self) rel.__parent__ = self event.notify( zope.lifecycleevent.ObjectCreatedEvent(rel)) self._add(rel, self._local, True) event.notify(interfaces.LocalRelationshipAdded(rel)) assert not (list(self.iterUpdateConflicts()) or list(self.iterParentConflicts()) or list(self.iterOrphanConflicts()) or self._getChildErrors()) event.notify(interfaces.UpdateCompleted(self, source, base)) def checkRelationshipChange(self, relationship): reltype = self.getType(relationship) if self.updating and reltype == interfaces.LOCAL: raise interfaces.UpdateError( 'cannot change local relationships while updating') if reltype in (interfaces.SUGGESTED, interfaces.UPDATED): assert self.updating, ( 'internal state error: the system should not allow suggested ' 'or updated relationships when not updating') raise TypeError( 'cannot change relationships when used as suggested or ' 'updated values') def abortUpdate(self): if self._updateSource is None: raise interfaces.UpdateError('not updating') source = self._updateSource base = self._updateBase self._updateSource = self._updateBase = None for s in (self._updated, self._modified, self._suggested): for t in s: self._index.unindex_doc(t) s.clear() self._conflicts.clear() self._resolutions.clear() self._orphanResolutions.clear() self._orphanResolutions.update(self._oldOrphanResolutions) self._oldOrphanResolutions.clear() self._selections.clear() self._selections.update(self._oldSelections) self._oldSelections.clear() event.notify(interfaces.UpdateAborted(self, source, base)) def iterChanges(self, base=None): get = self.vault.intids.getObject if base is None: base = self.base_source for t in self._selections: rel = get(t) if base is None: yield rel else: b = base.get(rel.token) if (b is None or b.object is not rel.object or b.containment != rel.containment): yield rel @zc.freeze.method def reindex(self, relationship): t = self.vault.intids.queryId(relationship) if t is not None and (t in self._local or t in self._suggested or t in self._modified or t in self._updated): self._locateObject(relationship) self._index.index_doc(t, relationship) def _getFromSet(self, token, set, default): res = list(self._yieldFromSet(token, set)) if not res: return default assert len(res) == 1, 'internal error: too many in the same category' return res[0] def _yieldFromSet(self, token, set): get = self.vault.intids.getObject for t in self._index.findRelationshipTokenSet({'token': token}): if t in set: yield get(t) def get(self, token, default=None): # return the selected relationship return self._getFromSet(token, self._selections, default) def getType(self, relationship): t = self.vault.intids.queryId(relationship) if t is not None: if t in self._local: return interfaces.LOCAL elif t in self._updated: return interfaces.UPDATED elif t in self._suggested: return interfaces.SUGGESTED elif t in self._modified: return interfaces.MODIFIED else: intids = component.getUtility( zope.app.intid.interfaces.IIntIds) iid = intids.queryId(relationship.__parent__.vault) if iid is not None and iid in self._bases: iiset, rel_set = self._bases[iid] if t in iiset: return interfaces.BASE for bid, (iiset, rel_set) in self._bases.items(): if bid == iid: continue if t in iiset: return interfaces.MERGED return None def isSelected(self, relationship): t = self.vault.intids.queryId(relationship) return t is not None and t in self._selections @zc.freeze.method def select(self, relationship): t = self.vault.intids.queryId(relationship) if t is None or self.getType(relationship) is None: raise ValueError('unknown relationship') if t in self._selections: return rel_tokens = self._index.findRelationshipTokenSet( self._index.tokenizeQuery({'token': relationship.token})) for rel_t in rel_tokens: if rel_t in self._selections: self._selections.remove(rel_t) event.notify(interfaces.RelationshipDeselected( self.vault.intids.getObject(rel_t), self)) break self._selections.insert(t) event.notify(interfaces.RelationshipSelected(relationship, self)) def getBase(self, token, default=None): vault = self.base_source for iiset, rel_set in self._bases.values(): if rel_set is vault: return self._getFromSet(token, iiset, default) def getLocal(self, token, default=None): return self._getFromSet(token, self._local, default) def getUpdated(self, token, default=None): return self._getFromSet(token, self._updated, default) def iterSuggested(self, token): return self._yieldFromSet(token, self._suggested) def iterModified(self, token): return self._yieldFromSet(token, self._modified) def iterMerged(self, token): vault = self.vault seen = set() for iiset, rel_set in self._bases.values(): if rel_set is not vault: for r in self._yieldFromSet(token, iiset): if r not in seen: yield r seen.add(r) def _parents(self, token): return self._index.findRelationshipTokenSet({'child': token}) def iterSelectedParents(self, token): get = self.vault.intids.getObject for iid in self._parents(token): if iid in self._selections: yield get(iid) def iterParents(self, token): get = self.vault.intids.getObject return (get(iid) for iid in self._parents(token)) def getParent(self, token): good = set() orphaned = set() unselected = set() orphaned_unselected = set() for iid in self._parents(token): is_orphaned = self.isOrphan(iid) if iid in self._selections: if is_orphaned: orphaned.add(iid) else: good.add(iid) else: if is_orphaned: orphaned_unselected.add(iid) else: unselected.add(iid) for s in (good, orphaned, unselected, orphaned_unselected): if s: if len(s) > 1: raise interfaces.ParentConflictError return self.vault.intids.getObject(s.pop()) def isLinked(self, token, child): return self._index.isLinked( self._index.tokenizeQuery({'token': token}), filter=self._selectionsFilter, targetQuery=self._index.tokenizeQuery({'child': child})) def iterUpdateConflicts(self): # any proposed (not accepted) relationship that has both update and # local for its token if self._updateSource is None: raise StopIteration get = self.vault.intids.getObject for t in self._conflicts: if t not in self._resolutions: rs = list(self._index.findRelationshipTokenSet({'token': t})) for r in rs: if r in self._selections: yield get(r) break else: assert 0, ( 'programmer error: no selected relationship found for ' 'conflicted token') def iterUpdateResolutions(self): if self._updateSource is None: raise StopIteration get = self.vault.intids.getObject for t in self._resolutions: assert t in self._conflicts rs = list(self._index.findRelationshipTokenSet({'token': t})) for r in rs: if r in self._selections: yield get(r) break else: assert 0, ( 'programmer error: no selected relationship found for ' 'resolved token') def isUpdateConflict(self, token): return (token in self._conflicts and token not in self._resolutions) @zc.freeze.method def resolveUpdateConflict(self, token): if not self.updating: raise interfaces.UpdateError( 'can only resolve merge conflicts during update') if token not in self._conflicts: raise ValueError('token does not have merge conflict') self._resolutions.insert(token) def _iterOrphans(self, condition): get = self.vault.intids.getObject res = set(self._selections) res.difference_update(self._iterLinked()) bases = IFBTree.multiunion([d[0] for d in self._bases.values()]) res.difference_update(bases) for t in res: tids = self._index.findValueTokenSet(t, 'token') assert len(tids) == 1 tid = iter(tids).next() if not condition(tid): continue yield get(t) def iterOrphanConflicts(self): return self._iterOrphans(lambda t: t not in self._orphanResolutions) def iterOrphanResolutions(self): return self._iterOrphans(lambda t: t in self._orphanResolutions) def isOrphan(self, token): return not (token == self.vault.top_token or self.isLinked(self.vault.top_token, token)) def isOrphanConflict(self, token): return (self.isOrphan(token) and self.getType(token) not in (interfaces.BASE, interfaces.MERGED) and token not in self._orphanResolutions) @zc.freeze.method def resolveOrphanConflict(self, token): self._orphanResolutions.insert(token) @zc.freeze.method def undoOrphanConflictResolution(self, token): self._orphanResolutions.remove(token) def iterParentConflicts(self): get = self.vault.intids.getObject seen = set() for r in self._iterLinked(): if r in seen: continue seen.add(r) ts = self._index.findValueTokenSet(r, 'token') assert len(ts) == 1 t = iter(ts).next() paths = list(self._index.findRelationshipTokenChains( {'child': t}, filter=self._selectionsFilter, targetQuery={'token': self.vault.top_token})) if len(paths) > 1: yield get(r) def _getChildErrors(self): parents = set() children = set() for rid in self._iterLinked(): parents.update(self._index.findValueTokenSet(rid, 'token')) children.update(self._index.findValueTokenSet(rid, 'child')) children.difference_update(parents) return children # these are token ids def iterAll(self): # XXX __iter__? get = self.vault.intids.getObject seen = set() for s in (self._local, self._updated, self._suggested, self._modified): for t in s: if t not in seen: yield get(t) seen.add(t) for iidset, rel_set in self._bases.values(): for t in iidset: if t not in seen: yield get(t) seen.add(t) def iterSelections(self): # XXX __iter__? get = self.vault.intids.getObject return (get(t) for t in self._selections) def __iter__(self): # XXX iterLinked? get = self.vault.intids.getObject return (get(t) for t in self._iterLinked()) def iterUnchangedOrphans(self): get = self.vault.intids.getObject res = set(self._selections) res.difference_update(self._iterLinked()) bases = IFBTree.multiunion([d[0] for d in self._bases.values()]) res.intersection_update(bases) return (get(t) for t in res) @property def previous(self): i = self.vault_index if i is not None and len(self.vault)-1 >= i and self.vault[i] is self: if i > 0: return self.vault[i-1] return None return self.base_source @property def next(self): i = self.vault_index if i is not None and len(self.vault) > i+1 and self.vault[i] is self: return self.vault[i+1] return None def isOption(self, relationship): # XXX __contains__? for rel in self._index.findRelationships( self._index.tokenizeQuery( {'token': relationship.token, 'object': relationship.object})): if rel is relationship: return True return False class HeldContainer(zope.app.container.btree.BTreeContainer): pass class Vault(persistent.Persistent, zope.app.container.contained.Contained): interface.implements(interfaces.IVault) def __init__(self, intids=None, held=None): self._data = IOBTree.IOBTree() if intids is None: intids = zope.app.intid.IntIds() self.intids = intids if intids.__parent__ is None: zope.location.locate(intids, self, 'intids') self._next = OOBTree.OOBTree() self.top_token = intids.register(keyref.top_token) self._held = held @property def held(self): return self._held def createBranch(self, ix=-1, held=None): # ...shugah, shugah... # uh, that means that this is sugar for the "make sure you share the # intids when you make a branch" issue. if not isinstance(ix, int): raise ValueError('ix must be int') if held is None: held = self.held res = self.__class__(self.intids, held) res.commit(Manifest(self[ix])) return res def getPrevious(self, relationship): manifest = relationship.__parent__ # first one with this relationship ix = manifest.vault_index if ix > 0: return manifest.vault[ix-1].get(relationship.token) return None def getNext(self, relationship): return self._next.get(self.intids.getId(relationship)) def __len__(self): if self._data: return self._data.maxKey() + 1 else: return 0 def __getitem__(self, key): if isinstance(key, slice): start, stop, stride = key.indices(len(self)) if stride==1: return self._data.values(start, stop, excludemax=True) else: pos = start res = [] while pos < stop: res.append(self._data[pos]) pos += stride return res elif key < 0: effective_key = len(self) + key if effective_key < 0: raise IndexError(key) return self._data[effective_key] elif key >= len(self): raise IndexError(key) else: return self._data[key] def __iter__(self): return iter(self._data.values()) @property def manifest(self): if self._data: return self._data[self._data.maxKey()] return None def commit(self, manifest): if not interfaces.IManifest.providedBy(manifest): raise ValueError('may only commit an IManifest') current = self.manifest if current is not None: current_vaults = set(id(b.vault) for b in current.getBaseSources()) current_vaults.add(id(current.vault)) new_vaults = set(id(b.vault) for b in manifest.getBaseSources()) new_vaults.add(id(manifest.vault)) if not current_vaults & new_vaults: raise ValueError( 'may only commit a manifest with at least one shared base') elif manifest.getBaseSource(self) is not current and ( not manifest.updating or ( manifest.updating and manifest.update_source is not current)): raise interfaces.OutOfDateError(manifest) self._commit(manifest) def _commit(self, manifest): if manifest._z_frozen: raise zc.freeze.interfaces.FrozenError(manifest) if manifest.get(self.top_token) is None: raise ValueError( 'cannot commit a manifest without a top_token relationship') if (self.manifest is not None and not len(tuple(manifest.iterChanges(self.manifest)))): raise interfaces.NoChangesError(manifest) if manifest.updating: manifest.completeUpdate() elif (list(manifest.iterUpdateConflicts()) or list(manifest.iterOrphanConflicts()) or list(manifest.iterParentConflicts())): raise interfaces.ConflictError(manifest) manifest.vault = self ix = len(self) self._data[ix] = manifest manifest.vault_index = ix manifest._z_freeze() for r in manifest: if manifest.getLocal(r.token) is r: p = self.getPrevious(r) if p is not None and p.__parent__.vault is self: pid = self.intids.getId(p) self._next[pid] = r if (manifest.__parent__ is None or manifest.__name__ is None): # so absoluteURL on objects in held "works" (needs traversers to # really work) zope.location.locate(manifest, self, unicode(manifest.vault_index)) event.notify(interfaces.ManifestCommitted(manifest)) def commitFrom(self, source): if not interfaces.IManifest.providedBy(source): raise ValueError('source must be manifest') if source.vault.intids is not self.intids: raise ValueError('source must share intids') if not source._z_frozen: raise ValueError('source must already be versioned') res = Manifest(self.manifest) base_rels = dict((r.token, r) for r in res.base_source) for rel in source: base_rel = base_rels.pop(rel.token, None) if base_rel is not None and base_rel == rel: res.select(rel) else: rel = Relationship( rel.token, relationship=rel, source_manifest=res) rel.__parent__ = res event.notify( zope.lifecycleevent.ObjectCreatedEvent(rel)) res._add(rel, res._local, True) res.select(rel) event.notify(interfaces.LocalRelationshipAdded(rel)) for rel in base_rels.values(): res.select(rel) # to make sure that any hidden local changes are # ignored. We don't need to resolve the orphans because base # orphans are not regarded as conflicts self._commit(res)
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/core.py
core.py
from BTrees import IOBTree, IFBTree from zc.vault import interfaces, keyref from zope import component, interface import persistent import zope.app.container.interfaces import zope.app.intid.interfaces import zope.component.interfaces import zope.event import zope.lifecycleevent import zope.lifecycleevent.interfaces import zope.location # from a site, to get to the default package, the incantation is # site.getSiteManager()['default'] def addLocalUtility(package, utility, interface=None, name='', name_in_container='', comment=u''): chooser = zope.app.container.interfaces.INameChooser(package) name_in_container = chooser.chooseName(name_in_container, utility) zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(utility)) package[name_in_container] = utility # really want IComponentRegistry, but that is not set up in Zope 3 ATM registry = zope.component.interfaces.IComponentLookup(package) registry.registerUtility(utility, interface, name, comment) HISTORICAL = 'zc.vault.historical' CURRENT = 'zc.vault.current' WORKING = 'zc.vault.working' # the following constant is not API REVERSE = 'zc.vault.working_reverse' class IRevisionReferences(interface.Interface): historical = interface.Attribute( '''an object with a standard mapping get method: stores object intid -> set of historical manifest intids''') current = interface.Attribute( '''an object with a standard mapping get method: stores object intid -> set of historical manifest intids''') working = interface.Attribute( '''an object with a standard mapping get method: stores object intid -> set of historical manifest intids''') class RevisionReferencesMappings(persistent.Persistent): def __init__(self): self.references = IOBTree.IOBTree() def _getrefs(self, key): refs = self.references.get(key) if refs is None: refs = self.references[key] = IFBTree.IFTreeSet() return refs def add(self, key, value): self._getrefs(key).insert(value) def update(self, key, values): self._getrefs(key).update(values) def remove(self, key, value): refs = self.references.get(key) if refs is not None: refs.remove(value) # raises KeyError when we desire if not refs: del self.references[key] else: raise KeyError("key and value pair does not exist") def discard(self, key, value): try: self.remove(key, value) except KeyError: pass def contains(self, key, value): refs = self.references.get(key) if refs is not None: return value in refs return False def set(self, key, values): refs = self.references.get(key) vals = tuple(values) if not vals: if refs is not None: # del del self.references[key] else: if refs is None: refs = self.references[key] = IFBTree.IFTreeSet() else: refs.clear() refs.update(vals) def get(self, key): return self.references.get(key, ()) class RevisionReferences(persistent.Persistent, zope.location.Location): interface.implements(IRevisionReferences) __parent__ = __name__ = None def __init__(self): self.historical = RevisionReferencesMappings() self.current = RevisionReferencesMappings() self.working = RevisionReferencesMappings() self.reverse = RevisionReferencesMappings() def createRevisionReferences(package): utility = RevisionReferences() chooser = zope.app.container.interfaces.INameChooser(package) name = chooser.chooseName('zc_vault_revision_references', utility) zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(utility)) package[name] = utility # really want IComponentRegistry, but that is not set up in Zope 3 ATM registry = zope.component.interfaces.IComponentLookup(package) registry.registerUtility(utility, IRevisionReferences, '', '') @component.adapter(interfaces.IManifestCommitted) def makeReferences(ev): refs = component.getUtility(IRevisionReferences) intids = component.getUtility(zope.app.intid.interfaces.IIntIds) man = ev.object man_id = intids.register(man) prev = man.previous if prev is not None: prev_id = intids.register(prev) for rel in prev: if rel.token is not man.vault.top_token: o_id = intids.register(rel.object) refs.current.discard(o_id, prev_id) refs.historical.add(o_id, prev_id) for o_id in refs.reverse.get(man_id): refs.working.remove(o_id, man_id) refs.reverse.set(man_id, ()) for rel in man: if rel.token is not man.vault.top_token: refs.current.add(intids.register(rel.object), man_id) @component.adapter(interfaces.IUpdateCompleted) def updateCompleted(ev): refs = component.getUtility(IRevisionReferences) intids = component.getUtility(zope.app.intid.interfaces.IIntIds) man = ev.object man_id = intids.register(man) for o_id in refs.reverse.get(man_id): refs.working.remove(o_id, man_id) refs.reverse.set(man_id, ()) for rel in man.iterSelections(): if rel.token is not man.vault.top_token: o_id = intids.register(rel.object) refs.working.add(o_id, man_id) refs.reverse.add(man_id, o_id) @component.adapter(interfaces.IUpdateAborted) def updateAborted(ev): updateCompleted(ev) @component.adapter( interfaces.IManifest, zope.lifecycleevent.interfaces.IObjectCreatedEvent) def manifestCreated(man, ev): refs = component.getUtility(IRevisionReferences) intids = component.getUtility(zope.app.intid.interfaces.IIntIds) man = ev.object man_id = intids.register(man) for rel in man: if rel.token is not man.vault.top_token: o_id = intids.register(rel.object) refs.working.add(o_id, man_id) refs.reverse.add(man_id, o_id) @component.adapter(interfaces.IRelationshipSelected) def relationshipSelected(ev): rel = ev.object if rel.token is not rel.__parent__.vault.top_token: man = ev.manifest refs = component.getUtility(IRevisionReferences) intids = component.getUtility(zope.app.intid.interfaces.IIntIds) man_id = intids.register(man) o_id = intids.register(rel.object) refs.working.add(o_id, man_id) refs.reverse.add(man_id, o_id) @component.adapter(interfaces.IRelationshipDeselected) def relationshipDeselected(ev): rel = ev.object if rel.token is not rel.__parent__.vault.top_token: man = ev.manifest for other in man: if other.object is rel.object: break else: refs = component.getUtility(IRevisionReferences) intids = component.getUtility(zope.app.intid.interfaces.IIntIds) man_id = intids.register(man) o_id = intids.register(rel.object) refs.working.remove(o_id, man_id) refs.reverse.remove(man_id, o_id) @component.adapter(interfaces.IObjectChanged) def objectChanged(ev): rel = ev.object if rel.token is not rel.__parent__.vault.top_token: man = rel.__parent__ if man is not None and man.isSelected(rel): refs = component.getUtility(IRevisionReferences) intids = component.getUtility(zope.app.intid.interfaces.IIntIds) man_id = intids.register(man) o_id = intids.register(rel.object) previous = ev.previous if previous is not None: for other in man: if other.object is previous: break else: p_id = intids.register(previous) refs.working.remove(p_id, man_id) refs.reverse.remove(man_id, p_id) refs.working.add(o_id, man_id) refs.reverse.add(man_id, o_id)
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/catalog.py
catalog.py
import persistent # Not sure from zope import interface, component, event import zope.app.container.contained import zope.lifecycleevent import zope.proxy import rwproperty import zc.freeze.interfaces from zc.vault import interfaces, core def makeItem(rel, inventory): if rel.token == inventory.vault.top_token: return InventoryContents(inventory, relationship=rel) else: return InventoryItem(inventory, relationship=rel) class InventoryContents(object): interface.implements(interfaces.IInventoryContents) def __init__(self, inventory, relationship=None): self.__parent__ = self.inventory = inventory if relationship is not None: if relationship.token != self.inventory.vault.top_token: raise ValueError('contents must use top_token') if not inventory.manifest.isOption(relationship): raise ValueError('relationship is not in manifest') self._relationship = relationship else: rel = inventory.manifest.get(self.inventory.vault.top_token) if rel is None: rel = core.Relationship(self.inventory.vault.top_token) rel.__parent__ = inventory.manifest event.notify( zope.lifecycleevent.ObjectCreatedEvent(rel)) inventory.manifest.addLocal(rel) self._relationship = rel def __getstate__(self): raise RuntimeError('This should not be persisted.') # negotiable def __eq__(self, other): return (interfaces.IInventoryContents.providedBy(other) and self.relationship is other.relationship and self.inventory.manifest is other.inventory.manifest) def __ne__(self, other): return not (self == other) @property def relationship(self): return self._relationship def _getRelationshipFromKey(self, key, default=None): token = self.relationship.containment.get(key) if token is None: return default return self.inventory.manifest.get(token) def __len__(self): return len(self.relationship.containment) def __getitem__(self, key): rel = self._getRelationshipFromKey(key) if rel is None: raise KeyError(key) return rel.object def get(self, key, default=None): rel = self._getRelationshipFromKey(key) if rel is None: return default return rel.object def items(self): get = self.inventory.manifest.get return [(k, get(t).object) for k, t in self.relationship.containment.items()] def keys(self): return self.relationship.containment.keys() def values(self): get = self.inventory.manifest.get return [get(t).object for t in self.relationship.containment.values()] def __iter__(self): return iter(self.relationship.containment) def __contains__(self, key): return key in self.relationship.containment has_key = __contains__ def getKey(self, item, default=None): if interfaces.IInventoryItem.providedBy(item): item = item.relationship return self.relationships.containment.getKey(item.token, default) def makeMutable(self): # local is mutable normally; modified is mutable while updating if self.inventory.manifest._z_frozen: raise zc.freeze.interfaces.FrozenError typ = self.type if not self.inventory.manifest.updating: if typ == interfaces.LOCAL: return typ elif self.has_local: raise ValueError('Local revision already created') elif typ == interfaces.MODIFIED: return typ selected = self.selected rel = core.Relationship( self.relationship.token, relationship=self.relationship, source_manifest=self.inventory.manifest) rel.__parent__ = self.inventory.manifest event.notify(zope.lifecycleevent.ObjectCreatedEvent(rel)) if not self.inventory.manifest.updating: self.inventory.manifest.addLocal(rel) if selected: self.inventory.manifest.select(rel) res = interfaces.LOCAL else: self.inventory.manifest.addModified(rel) if selected: self.inventory.manifest.select(rel) res = interfaces.MODIFIED self._relationship = rel return res def __delitem__(self, key): self.makeMutable() old = self.relationship.containment[key] del self.relationship.containment[key] def __setitem__(self, key, value): relset = self.inventory.manifest token = self.relationship.containment.get(key) if token is None: self.makeMutable() sub_rel = core.Relationship() sub_rel.__parent__ = self.inventory.manifest sub_rel.token = self.inventory.vault.intids.register(sub_rel) event.notify( zope.lifecycleevent.ObjectCreatedEvent(sub_rel)) sub_rel.object = value if self.inventory.updating: relset.addModified(sub_rel) else: relset.addLocal(sub_rel) self.relationship.containment[key] = sub_rel.token else: sub_rel = self.inventory.manifest.get(token) assert sub_rel is not None if relset.getType(sub_rel) not in ( interfaces.LOCAL, interfaces.SUGGESTED, interfaces.MODIFIED): item = makeItem(sub_rel, self.inventory) item.makeMutable() sub_rel = item.relationship sub_rel.object = value def updateOrder(self, order): self.makeMutable() self.relationship.containment.updateOrder(order) def updateOrderFromTokens(self, order): self.makeMutable() c = self.relationship.containment c.updateOrder(c.getKey(t) for t in order) @property def token(self): return self.relationship.token def __call__(self, name, *args): if args: if len(args) > 1: raise TypeError( '__call__() takes at most 2 arguments (%d given)' % len(args) + 1) rel = self.relationship.containment.get(name) if rel is None: return args[0] else: rel = self.relationship.containment[name] return InventoryItem(self.inventory, rel) @property def previous(self): previous = self.inventory.manifest.previous if previous is None: return None previous_relationship = previous.get(self.relationship.token) if previous_relationship is None: return None return makeItem(previous_relationship, Inventory(previous)) @property def next(self): next = self.inventory.manifest.next if next is None: return None next_relationship = next.get(self.relationship.token) if next_relationship is None: return None return makeItem(next_relationship, Inventory(next)) @property def previous_version(self): rel = self.inventory.vault.getPrevious(self.relationship) if rel is not None: return makeItem(rel, Inventory(rel.__parent__)) @property def next_version(self): rel = self.inventory.vault.getNext(self.relationship) if rel is not None: return makeItem(rel, Inventory(rel.__parent__)) @property def type(self): return self.inventory.manifest.getType(self.relationship) @property def selected(self): return self.inventory.manifest.isSelected(self.relationship) def select(self): self.inventory.manifest.select(self.relationship) @property def is_update_conflict(self): return self.inventory.manifest.isUpdateConflict( self.relationship.token) def resolveUpdateConflict(self): if not self.inventory.manifest.updating: raise RuntimeError('can only resolve merges while updating') if not self.is_update_conflict: raise RuntimeError('Not a conflict') self.select() # XXX is this good behavior? self.inventory.manifest.resolveUpdateConflict( self.relationship.token) @property def has_base(self): return bool(self.inventory.manifest.getBase( self.relationship.token)) @property def has_local(self): return bool(self.inventory.manifest.getLocal( self.relationship.token)) @property def has_updated(self): return bool(self.inventory.manifest.getUpdated( self.relationship.token)) @property def has_suggested(self): return bool(list( self.inventory.manifest.iterSuggested( self.relationship.token))) @property def has_modified(self): return bool(list( self.inventory.manifest.iterModified( self.relationship.token))) @property def has_merged(self): return bool(list( self.inventory.manifest.iterMerged( self.relationship.token))) @property def base_item(self): rel = self.inventory.manifest.getBase( self.relationship.token) if rel is not None: return makeItem(rel, self.inventory) @property def local_item(self): rel = self.inventory.manifest.getLocal( self.relationship.token) if rel is not None: return makeItem(rel, self.inventory) @property def updated_item(self): rel = self.inventory.manifest.getUpdated( self.relationship.token) if rel is not None: return makeItem(rel, self.inventory) def iterSuggestedItems(self): for rel in self.inventory.manifest.iterSuggested( self.relationship.token): yield makeItem(rel, self.inventory) def iterModifiedItems(self): for rel in self.inventory.manifest.iterModified( self.relationship.token): yield makeItem(rel, self.inventory) def iterMergedItems(self): for rel in self.inventory.manifest.iterMerged( self.relationship.token): yield makeItem(rel, self.inventory) @property def copy_source(self): if self.relationship.copy_source is not None: return makeItem( self.relationship.copy_source[0], Inventory(self.relationship.copy_source[1])) @property def selected_item(self): if self.selected: return self return makeItem( self.inventory.manifest.get(self.relationship.token), self.inventory) class InventoryItem(InventoryContents): interface.implements(interfaces.IInventoryItem) def __init__(self, inventory, token=None, relationship=None): if token is inventory.vault.top_token: raise ValueError('Cannot create inventory item with top_token') self.__parent__ = self.inventory = inventory if relationship is None: if token is None: raise ValueError('must provide one of relationship or token') relationship = inventory.manifest.get(token) if relationship is None: raise ValueError('token is not used in this inventory') elif not inventory.manifest.isOption(relationship): raise ValueError('relationship is not in inventory') self._relationship = relationship def resolveOrphanConflict(self): self.inventory.manifest.resolveOrphanConflict( self.relationship.token) @property def is_orphan(self): return self.inventory.manifest.isOrphan(self.relationship.token) @property def is_orphan_conflict(self): return self.inventory.manifest.isOrphanConflict( self.relationship.token) @property def is_parent_conflict(self): return len(list( self.inventory.manifest.iterSelectedParents( self.relationship.token))) > 1 @property def parent(self): res = self.inventory.manifest.getParent(self.relationship.token) if res is not None: return makeItem(res, self.inventory) @property def name(self): res = self.inventory.manifest.getParent(self.relationship.token) if res is not None: return res.containment.getKey(self.relationship.token) def iterSelectedParents(self): return (makeItem(rel, self.inventory) for rel in self.inventory.manifest.iterSelectedParents( self.relationship.token)) def iterParents(self): return (makeItem(rel, self.inventory) for rel in self.inventory.manifest.iterParents( self.relationship.token)) @property def object(self): return self.relationship.object @rwproperty.setproperty def object(self, value): self.relationship.object = value # may raise VersionedError def moveTo(self, location=None, name=None): clean_location = zope.proxy.removeAllProxies(location) if clean_location.inventory.manifest is not self.inventory.manifest: self.copyTo(location, name) if self.name: del self.parent[self.name] # go down & resolve all orphan conflicts: too much of a heuristic? stack = [(lambda x: self, iter(('',)))] while stack: s, i = stack[-1] try: key = i.next() except StopIteration: stack.pop() else: val = s(key) if val.is_orphan_conflict: val.resolveOrphanConflict() stack.append((val, iter(val))) return if location is None: location = self.parent if location is None: raise ValueError('location must be supplied for orphans') old_name = self.name if name is None: name = old_name if name is None: raise ValueError('Must specify name') if name in location: if zope.proxy.removeAllProxies( location(name).relationship) is self.relationship: return raise ValueError( 'Object with same name already exists in new location') if (self.selected and location.selected and self.inventory.manifest.isLinked( self.relationship.token, location.relationship.token)): # location is in self raise ValueError('May not move item to within itself') parent = self.parent if old_name: del parent[old_name] if (parent is None or clean_location.relationship.token != parent.relationship.token): location.makeMutable() else: location = parent location.relationship.containment[name] = self.relationship.token if location.selected and not self.selected: self.select() def copyTo(self, location, name=None): if name is None: name = self.name if name in location: raise ValueError( 'Object with same name already exists in new location') location.makeMutable() # to get around error-checking constraints in the core, we go from # bottom-to-top. # this also prevents the possibility of infinite recursion in the copy. stack = [ (location.relationship, iter((name,)), lambda x: self, {})] if location.inventory.updating: add = location.inventory.manifest.addModified else: add = location.inventory.manifest.addLocal clean_location = zope.proxy.removeAllProxies(location) while stack: relationship, keys, src, queued = stack[-1] try: key = keys.next() except StopIteration: stack.pop() for k, v in queued.items(): relationship.containment[k] = v if (zope.proxy.removeAllProxies(relationship) is not clean_location.relationship): add(relationship) else: value = src(key) rel = core.Relationship( relationship=value.relationship, source_manifest=value.inventory.manifest) rel.__parent__ = clean_location.inventory.manifest rel.token = location.inventory.vault.intids.register(rel) event.notify( zope.lifecycleevent.ObjectCreatedEvent(rel)) queued[key] = rel.token stack.append((rel, iter(value), value, {})) class Inventory(persistent.Persistent, zope.app.container.contained.Contained): interface.implements(interfaces.IInventory) def __init__( self, manifest=None, inventory=None, vault=None, mutable=False): if manifest is None: if vault is None: if inventory is None: raise ValueError( 'must provide manifest, inventory, or vault') manifest = inventory.manifest else: # vault exists if inventory is None: manifest = vault.manifest if manifest is None: manifest = core.Manifest(vault=vault) event.notify( zope.lifecycleevent.ObjectCreatedEvent( manifest)) else: manifest = inventory.manifest elif inventory is not None: raise ValueError('cannot pass both manifest and inventory') if mutable and manifest._z_frozen: manifest = core.Manifest(manifest, vault) event.notify( zope.lifecycleevent.ObjectCreatedEvent(manifest)) self._manifest = manifest self.__parent__ = manifest.vault def __eq__(self, other): return (interfaces.IInventory.providedBy(other) and self.manifest is other.manifest) def __ne__(self, other): return not (self == other) @property def vault(self): return self._manifest.vault @rwproperty.setproperty def vault(self, value): self._manifest.vault = value @property def contents(self): return InventoryContents( self, self.manifest.get(self.vault.top_token)) @property def manifest(self): return self._manifest def iterUpdateConflicts(self): return (makeItem(r, self) for r in self.manifest.iterUpdateConflicts()) def iterUpdateResolutions(self): return (makeItem(r, self) for r in self.manifest.iterUpdateResolutions()) def iterOrphanConflicts(self): return (makeItem(r, self) for r in self.manifest.iterOrphanConflicts()) def iterOrphanResolutions(self): return (makeItem(r, self) for r in self.manifest.iterOrphanResolutions()) def iterUnchangedOrphans(self): return (makeItem(r, self) for r in self.manifest.iterUnchangedOrphans()) def iterParentConflicts(self): return (makeItem(r, self) for r in self.manifest.iterParentConflicts()) def __iter__(self): # selected items return (makeItem(r, self) for r in self.manifest) @property def updating(self): return self.manifest.updating @property def merged_sources(self): return tuple(Inventory(r) for r in self.manifest.merged_sources) @property def update_source(self): res = self.manifest.update_source if res is not None: return Inventory(res) def beginUpdate(self, source=None, previous=None): if interfaces.IInventory.providedBy(source): source = source.manifest if interfaces.IInventory.providedBy(previous): previous = previous.manifest self.manifest.beginUpdate(source, previous) def completeUpdate(self): self.manifest.completeUpdate() def abortUpdate(self): self.manifest.abortUpdate() def beginCollectionUpdate(self, items): self.manifest.beginCollectionUpdate( frozenset(i.relationship for i in items)) def iterChangedItems(self, source=None): if interfaces.IInventory.providedBy(source): source = source.manifest return (makeItem(r, self) for r in self.manifest.iterChanges(source)) def getItemFromToken(self, token, default=None): rel = self.manifest.get(token) if rel is None: return default return makeItem(rel, self) @property def previous(self): p = self.manifest.previous if p is not None: return Inventory(p) return None @property def next(self): p = self.manifest.next if p is not None: return Inventory(p) return None class Vault(core.Vault): interface.implements(interfaces.IInventoryVault) def getInventory(self, ix): return Inventory(self[ix]) @property def inventory(self): if self._data: return Inventory(self._data[self._data.maxKey()]) return None def commit(self, value): if interfaces.IInventory.providedBy(value): value = value.manifest super(Vault, self).commit(value) def commitFrom(self, value): if interfaces.IInventory.providedBy(value): value = value.manifest super(Vault, self).commitFrom(value)
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/vault.py
vault.py
===== Vault ===== Vaults model versioned containers. A single revision of a vault is typically viewed and (if not yet frozen) manipulated as an "inventory". Inventories actually manipulate lower-level objects called manifests that are only touched on in this document. Inventories are the primary API. Inventories *model* containers, but are not traditional mappings: containment is external to the actual objects in the inventory. You must query the inventory to discover the hierarchy, rather than the objects themselves. For instance, if you put an object in an inventory and want to treat it as a versioned folder, you don't put children in the object, but in the inventory node that wraps the object. This will be demonstrated repeatedly and in-depth below. Vaults only contain versioned, frozen manifests, accessed as inventories. Working inventories can be made from any inventory in a vault. They can then be modified, and committed themselves in the vault. Committing an inventory freezes it and all objects it "contains". Let's look at an example. Vaults store manifests, so when you first create one it is empty. Vaults have a basic sequence API, so a `len` will return `0`. >>> from zc.vault.vault import Vault, Inventory >>> from zc.vault.core import Manifest >>> from zc.vault import interfaces >>> from zope.interface.verify import verifyObject >>> v = Vault() >>> len(v) 0 >>> verifyObject(interfaces.IVault, v) True The last inventory--the -1 index--is the current one. A shorthand to this inventory is the inventory attribute. >>> v.inventory # None Vaults and inventories must have a database connection in order to store their data. We'll assume we have a ZODB folder named "app" in which we can store our information. This is set up in tests.py when this file is run as a test. >>> app['vault'] = v Creating an initial working inventory requires us to merely instantiate it. Usually we pass a versioned inventory on which to base the new inventory, but without that we at least pass the vault. >>> i = Inventory(vault=v) >>> verifyObject(interfaces.IInventory, i) True Technically, what we have done is create a manifest--the core API for managing the contents--and wrapped an inventory API around it. >>> verifyObject(interfaces.IManifest, i.manifest) True We could have created the manifest explicitly instead. >>> manifest = Manifest(vault=v) >>> verifyObject(interfaces.IManifest, manifest) True >>> i = Inventory(manifest) >>> verifyObject(interfaces.IInventory, i) True Inventories--or at least the manifests on which they rely--must be stored somewhere in the database before being committed. They provide zope.app.location.interfaces.ILocation so that they can be stored in standard Zope containers as they are being developed. >>> app['inventory'] = i Inventories have contents that can seem to directly contain objects. They have a mapping API, and follow the IInventoryContents interface. >>> verifyObject(interfaces.IInventoryContents, i.contents) True >>> len(i.contents.keys()) 0 >>> len(i.contents.values()) 0 >>> len(i.contents.items()) 0 >>> list(i.contents) [] >>> i.contents.get('mydemo') # None >>> 'mydemo' in i False >>> i.contents['mydemo'] Traceback (most recent call last): ... KeyError: 'mydemo' >>> del i.contents['mydemo'] Traceback (most recent call last): ... KeyError: 'mydemo' (ADVANCED SIDE NOTE: feel free to ignore) The contents object is an API convenience to wrap a relationship. Relationships connect a token to various pieces of information. The token for all inventory contents (the top node) is stored on the vault as the top_token attribute, and lower levels get unique tokens that represent a given location in a vault across inventories. Contents and items (seen below) essentially get all their data from the relationships and the associated manifest that holds them. >>> verifyObject(interfaces.IRelationship, i.contents.relationship) True >>> i.contents.relationship.token == i.vault.top_token True >>> verifyObject(interfaces.IRelationshipContainment, ... i.contents.relationship.containment) True >>> i.contents.relationship.object # None, because contents. (end ADVANCED SIDE NOTE) Because it is often convenient to use tokens as a globally unique identifier of a particular object, all inventory items have a "token" attribute. >>> i.contents.token 1234567 Unlike typical Zope 3 containment as defined in zope.app.container, this containment does not affect the __parent__ or __name__ of the object. All objects stored in an inventory must be None, or be adaptable to zope.app.keyreference.interfaces.IKeyReference. In standard Zope 3, this includes any instance of a class that extends persistent.Persistent. All non-None objects must also be adaptable to zc.freeze.interfaces.IFreezable. Here, we create an object, add it to the application, and try to add it to an inventory. >>> import persistent >>> from zope.app.container.contained import Contained >>> class Demo(persistent.Persistent, Contained): ... def __repr__(self): ... return "<%s %r>" % (self.__class__.__name__, self.__name__) ... >>> app['d1'] = Demo() >>> i.contents['mydemo'] = app['d1'] Traceback (most recent call last): ... ValueError: can only place freezable objects in vault, or None This error occurs because committing an inventory must freeze itself and freeze all of its contained objects, so that looking at an historical inventory displays the objects as they were at the time of commit. Here's a simple demo adapter for the Demo objects. We also declare that Demo is IFreezable, an important marker. >>> import pytz >>> import datetime >>> from zope import interface, component, event >>> from zc.freeze.interfaces import ( ... IFreezing, ObjectFrozenEvent, IFreezable) >>> from zc.freeze import method >>> class DemoFreezingAdapter(object): ... interface.implements(IFreezing) ... component.adapts(Demo) ... def __init__(self, context): ... self.context = context ... @property ... def _z_frozen(self): ... return (getattr(self.context, '_z__freeze_timestamp', None) ... is not None) ... @property ... def _z_freeze_timestamp(self): ... return getattr(self.context, '_z__freeze_timestamp', None) ... @method ... def _z_freeze(self): ... self.context._z__freeze_timestamp = datetime.datetime.now( ... pytz.utc) ... event.notify(ObjectFrozenEvent(self)) ... >>> component.provideAdapter(DemoFreezingAdapter) >>> interface.classImplements(Demo, IFreezable) As an aside, it's worth noting that the manifest objects provide IFreezing natively, so they can already be queried for the freezing status and timestamp without adaptation. When a manifest is frozen, all "contained" objects should be frozen as well. It's not frozen now--and neither is our demo instance. >>> manifest._z_frozen False >>> IFreezing(app['d1'])._z_frozen False Now that Demo instances are freezable we can add the object to the inventory. That means adding and removing objects. Here we add one. >>> i.contents['mydemo'] = app['d1'] >>> i.contents['mydemo'] <Demo u'd1'> >>> i.__parent__ is app True >>> i.contents.__parent__ is i True >>> i.contents.get('mydemo') <Demo u'd1'> >>> list(i.contents.keys()) ['mydemo'] >>> i.contents.values() [<Demo u'd1'>] >>> i.contents.items() [('mydemo', <Demo u'd1'>)] >>> list(i.contents) ['mydemo'] >>> 'mydemo' in i.contents True Now our effective hierarchy simply looks like this:: (top node) | 'mydemo' (<Demo u'd1'>) We will update this hierarchy as we proceed. Adding an object fires a (special to the package!) IObjectAdded event. This event is not from the standard lifecycleevents package because that one has a different connotation--for instance, as noted before, putting an object in an inventory does not set the __parent__ or __name__ (unless it does not already have a location, in which case it is put in a possibly temporary "held" container, discussed below). >>> interfaces.IObjectAdded.providedBy(events[-1]) True >>> isinstance(events[-1].object, int) True >>> i.manifest.get(events[-1].object).object is app['d1'] True >>> events[-1].mapping is i.contents.relationship.containment True >>> events[-1].key 'mydemo' Now we remove the object. >>> del i.contents['mydemo'] >>> len(i.contents.keys()) 0 >>> len(i.contents.values()) 0 >>> len(i.contents.items()) 0 >>> list(i.contents) [] >>> i.contents.get('mydemo') # None >>> 'mydemo' in i.contents False >>> i.contents['mydemo'] Traceback (most recent call last): ... KeyError: 'mydemo' >>> del i.contents['mydemo'] Traceback (most recent call last): ... KeyError: 'mydemo' Removing an object fires a special IObjectRemoved event (again, not from lifecycleevents). >>> interfaces.IObjectRemoved.providedBy(events[-1]) True >>> isinstance(events[-1].object, int) True >>> i.manifest.get(events[-1].object).object is app['d1'] True >>> events[-1].mapping is i.contents.relationship.containment True >>> events[-1].key 'mydemo' In addition to a mapping API, the inventory contents support an ordered container API very similar to the ordered container in zope.app.container.ordered. The ordered nature of the contents mean that iterating is on the basis of the order in which objects were added, by default (earliest first); and that the inventory supports an "updateOrder" method. The method takes an iterable of names in the container: the new order will be the given order. If the set of given names differs at all with the current set of keys, the method will raise ValueError. >>> i.contents.updateOrder(()) >>> i.contents.updateOrder(('foo',)) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> i.contents['donald'] = app['d1'] >>> app['b1'] = Demo() >>> i.contents['barbara'] = app['b1'] >>> app['c1'] = Demo() >>> app['a1'] = Demo() >>> i.contents['cathy'] = app['c1'] >>> i.contents['abe'] = app['a1'] >>> list(i.contents.keys()) ['donald', 'barbara', 'cathy', 'abe'] >>> i.contents.values() [<Demo u'd1'>, <Demo u'b1'>, <Demo u'c1'>, <Demo u'a1'>] >>> i.contents.items() # doctest: +NORMALIZE_WHITESPACE [('donald', <Demo u'd1'>), ('barbara', <Demo u'b1'>), ('cathy', <Demo u'c1'>), ('abe', <Demo u'a1'>)] >>> list(i.contents) ['donald', 'barbara', 'cathy', 'abe'] >>> 'cathy' in i.contents True >>> i.contents.updateOrder(()) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> i.contents.updateOrder(('foo',)) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> i.contents.updateOrder(iter(('abe', 'barbara', 'cathy', 'donald'))) >>> list(i.contents.keys()) ['abe', 'barbara', 'cathy', 'donald'] >>> i.contents.values() [<Demo u'a1'>, <Demo u'b1'>, <Demo u'c1'>, <Demo u'd1'>] >>> i.contents.items() # doctest: +NORMALIZE_WHITESPACE [('abe', <Demo u'a1'>), ('barbara', <Demo u'b1'>), ('cathy', <Demo u'c1'>), ('donald', <Demo u'd1'>)] >>> list(i.contents) ['abe', 'barbara', 'cathy', 'donald'] >>> i.contents.updateOrder(('abe', 'cathy', 'donald', 'barbara', 'edward')) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> list(i.contents) ['abe', 'barbara', 'cathy', 'donald'] >>> del i.contents['cathy'] >>> list(i.contents.keys()) ['abe', 'barbara', 'donald'] >>> i.contents.values() [<Demo u'a1'>, <Demo u'b1'>, <Demo u'd1'>] >>> i.contents.items() # doctest: +NORMALIZE_WHITESPACE [('abe', <Demo u'a1'>), ('barbara', <Demo u'b1'>), ('donald', <Demo u'd1'>)] >>> list(i.contents) ['abe', 'barbara', 'donald'] >>> i.contents.updateOrder(('barbara', 'abe', 'donald')) >>> list(i.contents.keys()) ['barbara', 'abe', 'donald'] >>> i.contents.values() [<Demo u'b1'>, <Demo u'a1'>, <Demo u'd1'>] Now our _`hierarchy` looks like this:: (top node) / | \ / | \ 'barbara' 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> Reordering a container fires an event. >>> interfaces.IOrderChanged.providedBy(events[-1]) True >>> events[-1].object is i.contents.relationship.containment True >>> events[-1].old_keys ('abe', 'barbara', 'donald') In some circumstances it's easier to set the new order from a set of tokens. In that case the "updateOrderFromTokens" method is useful. >>> def getToken(key): ... return i.contents(k).token >>> new_order = [getToken(k) for k in ('abe', 'donald', 'barbara')] >>> i.contents.updateOrderFromTokens(new_order) >>> list(i.contents.keys()) ['abe', 'donald', 'barbara'] Just like "updateOrder", an event is fired. >>> interfaces.IOrderChanged.providedBy(events[-1]) True >>> events[-1].object is i.contents.relationship.containment True >>> events[-1].old_keys ('barbara', 'abe', 'donald') It's just as easy to put them back so that the `hierarchy`_ still looks the same as it did at the end of the previous example. >>> new_order = [getToken(k) for k in ('barbara', 'abe', 'donald')] >>> i.contents.updateOrderFromTokens(new_order) >>> list(i.contents.keys()) ['barbara', 'abe', 'donald'] As noted in the introduction to this document, the versioned hierarchy is kept external from the objects themselves. This means that objects that are not containers themselves can still be branch nodes--containers, of a sort--within an inventory. In fact, until a reasonable use case emerges for the pattern, the author discourages the use of true containers within a vault as branch nodes: two dimensions of "containerish" behavior is too confusing. In order to get an object that can act as a container for one of the objects in the inventory, one calls the inventory contents: "i.contents('abe')". This returns an IInventoryItem, if the key exists. It raises a KeyError for a missing key by default, but can take a default. >>> i.contents['abe'] <Demo u'a1'> >>> item = i.contents('abe') >>> verifyObject(interfaces.IInventoryItem, item) True >>> i.contents('foo') Traceback (most recent call last): ... KeyError: 'foo' >>> i.contents('foo', None) # None IInventoryItems extend IInventoryContents to add an 'object' attribute, which is the object they represent. Like IInventoryContents, a mapping interface allows one to manipulate the hierarchy beneath the top level. For instance, here we effectively put the 'cathy' demo object in the container space of the 'abe' demo object. >>> item.object <Demo u'a1'> >>> item.name 'abe' >>> item.parent.relationship is i.contents.relationship True >>> item.__parent__ is item.inventory True >>> list(item.values()) [] >>> list(item.keys()) [] >>> list(item.items()) [] >>> list(item) [] >>> item.get('foo') # None >>> item['foo'] Traceback (most recent call last): ... KeyError: 'foo' >>> item('foo') Traceback (most recent call last): ... KeyError: 'foo' >>> item['catherine'] = app['c1'] >>> item['catherine'] <Demo u'c1'> >>> item.get('catherine') <Demo u'c1'> >>> list(item.keys()) ['catherine'] >>> list(item.values()) [<Demo u'c1'>] >>> list(item.items()) [('catherine', <Demo u'c1'>)] >>> catherine = item('catherine') >>> catherine.object <Demo u'c1'> >>> catherine.name 'catherine' >>> catherine.parent.name 'abe' >>> catherine.parent.object <Demo u'a1'> >>> list(catherine.keys()) [] Now our hierarchy looks like this:: (top node) / | \ / | \ 'barbara' 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> | | 'catherine' <Demo u'c1'> It's worthwhile noting that the same object can be in multiple places in an inventory. This does not duplicate the hierarchy, or keep changes in sync. If desired, this policy should be performed in code that uses the vault; similarly if a vault should only contain an object in one location at a time, this should be enforced in code that uses a vault. >>> i.contents('abe')('catherine')['anna'] = app['a1'] >>> i.contents('abe')('catherine').items() [('anna', <Demo u'a1'>)] >>> i.contents('abe')('catherine')('anna').parent.parent.object <Demo u'a1'> Now our hierarchy looks like this:: (top node) / | \ / | \ 'barbara' 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> | | 'catherine' <Demo u'c1'> | | 'anna' <Demo u'a1'> Even though a1 contains c1 contains a1, this does not constitute a cycle: the hierarchy is separate from the objects. InventoryItems and InventoryContents are currently created on the fly, and not persisted. They should be compared with "==", not "is". They represent a persistent core data object that provides zc.vault.interfaces.IRelationship. The IRelationship itself is hidden from the majority of this discussion and only introduced at the end of the document. But in any case... >>> i.contents('abe') is i.contents('abe') False >>> i.contents('abe') == i.contents('abe') True >>> i.contents is i.contents False >>> i.contents == i.contents True >>> i.contents == None False >>> i.contents('abe') == None False Comparing inventories will also compare their contents: >>> i == None False >>> i == i True >>> i != i False Another important characteristic of inventory items is that they continue to have the right information even as objects around them are changed--for instance, if an object's parent is changed from one part of the hierarchy to another (see `moveTo`, below), an item generated before the move will still reflect the change correctly. It's worth noting that, thanks to the wonder of the zc.shortcut code, views can exist for the object and also, from a proxy, have access to the InventoryItem's information: this needs to be elaborated (TODO). Now we'll try to commit. >>> v.commit(i) # doctest: +ELLIPSIS Traceback (most recent call last): ... ConflictError: <zc.vault.core.Manifest object at ...> Conflicts? We don't need no stinking conflicts! We didn't even merge! Where did this come from? The default vault takes a very strict approach to keeping track of conflicts: for instance, if you add something and then delete it in the same inventory, it will regard this as an "orphan conflict": a change that happened in this inventory that will not be committed. You must explicitly say that it is OK for these orphaned changes to be lost. Let's look at the orphans. >>> orphans = list(i.iterOrphanConflicts()) >>> sorted(repr(item.object) for item in orphans) ["<Demo u'c1'>", "<Demo u'd1'>"] >>> orphans[0].parent # None >>> orphans[0].name # None Ah yes--you can see that we deleted these objects above: we deleted "mydemo" (d1) and cathy (c1). We'll just tell the inventory that it is ok to not include them. If vault clients want to have more automation so that deletions automatically resolve, then they have the tools to do so. After the resolution, iterOrphanConflicts will then be empty, and iterOrphanResolutions will include the objects. >>> for o in orphans: ... o.resolveOrphanConflict() ... >>> len(list(i.iterOrphanConflicts())) 0 >>> sorted(repr(item.object) for item in i.iterOrphanResolutions()) ["<Demo u'c1'>", "<Demo u'd1'>"] Now when we commit, all objects will be versioned, and we will receive events for the freezing and the committing. The events list represents recent events; when this document is run as a test, it is populated by listening for all events and attaching them to the list. >>> v.commit(i) >>> interfaces.IManifestCommitted.providedBy(events[-1]) True >>> events[-1].object is manifest True >>> manifest.__parent__ is v True >>> IFreezing(app['a1'])._z_frozen True >>> IFreezing(app['b1'])._z_frozen True >>> IFreezing(app['c1'])._z_frozen True >>> IFreezing(app['d1'])._z_frozen True >>> manifest._z_frozen True >>> v.manifest is manifest True >>> len(v) 1 After the committing, the inventory enforces the freeze: no more changes can be made. >>> i.contents['foo'] = Demo() Traceback (most recent call last): ... FrozenError >>> i.contents.updateOrder(()) Traceback (most recent call last): ... FrozenError >>> i.contents('abe')('catherine')['foo'] = Demo() Traceback (most recent call last): ... FrozenError >>> v.manifest._z_frozen True Enforcing the freezing of the inventory's objects is the responsibility of other code or configuration, not the vault package. The manifest now has an __name__ which is the string of its index. This is of very limited usefulness, but with the right traverser might still allow items in the held container to be traversed to. >>> i.manifest.__name__ u'0' After every commit, the vault should be able to determine the previous and next versions of every relationship. Since this is the first commit, previous will be None, but we'll check it now anyway, building a function that checks the most recent manifest of the vault. >>> def checkManifest(m): ... v = m.vault ... for r in m: ... p = v.getPrevious(r) ... assert (p is None or ... r.__parent__.vault is not v or ... p.__parent__.vault is not v or ... v.getNext(p) is r) ... >>> checkManifest(v.manifest) Creating a new working inventory requires a new manifest, based on the old manifest. For better or worse, the package offers four approaches to this. We can create a new working inventory by specifying a vault, from which the most recent manifest will be selected, and "mutable=True"; >>> i = Inventory(vault=v, mutable=True) >>> manifest = i.manifest >>> manifest._z_frozen False by specifying an inventory, from which its manifest will be extracted, and "mutable=True"; >>> i = Inventory(inventory=v.inventory, mutable=True) >>> manifest = i.manifest >>> manifest._z_frozen False by specifying a versioned manifest and "mutable=True"; >>> i = Inventory(v.manifest, mutable=True) >>> manifest = i.manifest >>> manifest._z_frozen False or by specifying a mutable manifest. >>> i = Inventory(Manifest(v.manifest)) >>> i.manifest._z_frozen False These multiple spellings should be reexamined at a later date, and may have a deprecation period. The last spelling--an explicit pasing of a manifest to an inventory--is the most likely to remain stable, because it clearly allows instantiation of the inventory wrapper for a working manifest or a versioned manifest. Note that, as mentioned above, the inventory is just an API wrapper around the manifest: therefore, changes to inventories that share a manifest will be shared among them. >>> i_extra = Inventory(i.manifest) >>> manifest._z_frozen False In any case, we now have an inventory that has the same contents as the original. >>> i.contents.keys() == v.inventory.contents.keys() True >>> i.contents['barbara'] is v.inventory.contents['barbara'] True >>> i.contents['abe'] is v.inventory.contents['abe'] True >>> i.contents['donald'] is v.inventory.contents['donald'] True >>> i.contents('abe')['catherine'] is v.inventory.contents('abe')['catherine'] True >>> i.contents('abe')('catherine')['anna'] is \ ... v.inventory.contents('abe')('catherine')['anna'] True We can now manipulate the new inventory as we did the old one. >>> app['d2'] = Demo() >>> i.contents['donald'] = app['d2'] >>> i.contents['donald'] is v.inventory.contents['donald'] False Now our hierarchy looks like this:: (top node) / | \ / | \ 'barbara' 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd2'> | | 'catherine' <Demo u'c1'> | | 'anna' <Demo u'a1'> Now we can observe our local changes. One way to do this is to examine the results of iterChangedItems. >>> len(list(i.iterChangedItems())) 1 >>> iter(i.iterChangedItems()).next() == i.contents('donald') True Another is to look at each inventory item. The items specify the type of information in the item: whether it is from the 'base', the 'local' changes, or a few other options we'll see when we examine merges. >>> i.contents('abe').type 'base' >>> i.contents('donald').type 'local' This will be true whether or not the change is returned to the original value by hand. >>> i.contents['donald'] = app['d1'] >>> v.inventory.contents['donald'] is i.contents['donald'] True However, unchanged local copies are not included in the iterChangedItems results; they are also discarded on commit, as we will see below. >>> len(list(i.iterChangedItems())) 0 Now our hierarchy looks like this again:: (top node) / | \ / | \ 'barbara' 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> | | 'catherine' <Demo u'c1'> | | 'anna' <Demo u'a1'> Each inventory item represents a single collection of data that stores an object and its effective hierarchy. Therefore, changing either (or both) will generate a local inventory item. >>> app['e1'] = Demo() >>> i.contents('barbara').type 'base' >>> i.contents('barbara')['edna'] = app['e1'] >>> i.contents('barbara').type 'local' >>> i.contents['barbara'] is v.inventory.contents['barbara'] True >>> len(list(i.iterChangedItems())) 2 Those are two changes: one new node (edna) and one changed node (barbara got a new child). Now our hierarchy looks like this ("*" indicates a changed node):: (top node) / | \ / | \ 'barbara'* 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> / | / | 'edna'* 'catherine' <Demo u'e1'> <Demo u'c1'> | | 'anna' <Demo u'a1'> Modifying the collection of the top level contents means that we have a change as well: even though the inventory does not keep track of a single object at the top of the hierarchy, it does keep track of containment at the top level. >>> i.contents.type 'base' >>> app['f1'] = Demo() >>> i.contents['fred'] = app['f1'] >>> i.contents.type 'local' >>> len(list(i.iterChangedItems())) 4 That's four changes: edna, barbara, fred, and the top node. Now our hierarchy looks like this ("*" indicates a changed or new node):: (top node)* / / \ \ ---- / \ --------- / | | \ 'barbara'* 'abe' 'donald' 'fred'* <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> <Demo u'f1'> / | / | 'edna'* 'catherine' <Demo u'e1'> <Demo u'c1'> | | 'anna' <Demo u'a1'> You can actually examine the base from the changed item--and even switch back. The `base_item` attribute always returns an item with the original object and containment. The `local_item` returns an item with local changes, or None if no changes have been made. A `select` method allows you to switch the given item to look at one or the other by default. The readonly `selected` attribute allows introspection. >>> list(i.contents.keys()) ['barbara', 'abe', 'donald', 'fred'] >>> i.contents == i.contents.local_item True >>> list(i.contents('barbara').keys()) ['edna'] >>> i.contents('barbara') == i.contents('barbara').local_item True >>> i.contents('barbara').local_item.selected True >>> i.contents('barbara').base_item.selected False >>> len(i.contents('barbara').base_item.keys()) 0 >>> list(i.contents.base_item.keys()) ['barbara', 'abe', 'donald'] >>> i.contents('barbara').base_item.select() >>> len(list(i.iterChangedItems())) 3 That's fred, the top level, /and/ edna: edna still is a change, even though she is inaccessible with the old version of barbara. If we were to commit now, we would have to resolve the orphan, as shown above. >>> v.commit(i) # doctest: +ELLIPSIS Traceback (most recent call last): ... ConflictError: <zc.vault.core.Manifest object at ...> >>> list(item.object for item in i.iterOrphanConflicts()) [<Demo u'e1'>] Let's look around a little more and switch things back: >>> i.contents('barbara').local_item.selected False >>> i.contents('barbara').base_item.selected True >>> len(i.contents('barbara').keys()) 0 >>> i.contents('barbara') == i.contents('barbara').local_item False >>> i.contents('barbara') == i.contents('barbara').base_item True >>> i.contents('barbara').local_item.select() >>> len(list(i.iterChangedItems())) 4 >>> i.contents('barbara').local_item.selected True >>> i.contents('barbara').base_item.selected False >>> list(i.contents('barbara').keys()) ['edna'] The inventory has booleans to examine whether a base item or local item exists, as a convenience (and optimization opportunity). >>> i.contents('fred').has_local True >>> i.contents('fred').has_base False >>> i.contents('abe')('catherine').has_local False >>> i.contents('abe')('catherine').has_base True >>> i.contents('barbara').has_local True >>> i.contents('barbara').has_base True It also has four other similar properties, `has_updated`, `has_suggested`, `has_modified`, and `has_merged`, which we will examine later. Before we commit we are going to make one more change to the inventory. We'll make a change to "anna". Notice how we spell this in the code: it this is the first object we have put in an inventory that does not already have a location in app. When an inventory is asked to version an object without an ILocation, it stores it in a special folder on the manifest named "held". Held objects are assigned names using the standard Zope 3 name chooser pattern and can be moved out even after being versioned. In this case we will need to register a name chooser for our demo objects. We'll use the standard one. >>> from zope.app.container.contained import NameChooser >>> from zope.app.container.interfaces import IWriteContainer >>> component.provideAdapter(NameChooser, adapts=(IWriteContainer,)) >>> len(i.manifest.held) 0 >>> i.contents('abe')('catherine')['anna'] = Demo() >>> len(i.manifest.held) 1 >>> i.manifest.held.values()[0] is i.contents('abe')('catherine')['anna'] True Now our hierarchy looks like this ("*" indicates a changed or new node):: (top node)* / / \ \ ---- / \ --------- / | | \ 'barbara'* 'abe' 'donald' 'fred'* <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> <Demo u'f1'> / | / | 'edna'* 'catherine' <Demo u'e1'> <Demo u'c1'> | | 'anna'* <Demo ...> In our previous inventory commit, objects were versioned in place. The vault code provides a hook to generate objects for committing to vault: it tries to adapt objects it wants to version to zc.vault.interfaces.IVersionFactory. This interface specifies any callable object. Let's provide an example. The policy here is that if the object is in the inventories' held container, just return it, but otherwise "make a copy"--which for our demo just makes a new instance and slams the old one's name on it as an attribute. >>> @interface.implementer(interfaces.IVersionFactory) ... @component.adapter(interfaces.IVault) ... def versionFactory(vault): ... def makeVersion(obj, manifest): ... if obj.__parent__ is manifest.held: ... return obj ... res = Demo() ... res.source_name = obj.__name__ ... return res ... return makeVersion ... >>> component.provideAdapter(versionFactory) Let's commit now, to show the results. We'll discard the change to barbara. >>> len(list(i.iterChangedItems())) 5 >>> i.contents('barbara')('edna').resolveOrphanConflict() >>> i.contents('barbara').base_item.select() >>> len(list(i.iterChangedItems())) 4 Edna is included even though she is resolved. Now our hierarchy looks like this ("*" indicates a changed or new node):: (top node)* / / \ \ ---- / \ --------- / | | \ 'barbara' 'abe' 'donald' 'fred'* <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> <Demo u'f1'> | | 'catherine' <Demo u'c1'> | | 'anna'* <Demo ...> >>> changed = dict( ... (getattr(item, 'name', None), item) ... for item in i.iterChangedItems()) >>> changed['anna'].parent.name 'catherine' >>> changed['fred'].object <Demo u'f1'> >>> changed['edna'].object <Demo u'e1'> >>> list(changed[None].keys()) ['barbara', 'abe', 'donald', 'fred'] >>> old_objects = dict( ... (k, i.object) for k, i in changed.items() if k is not None) >>> v.commit(i) >>> checkManifest(v.manifest) >>> len(v) 2 >>> v.manifest is i.manifest True >>> v.inventory == i True We committed the addition of fred, but not the addition of edna. Once an inventory is committed, unselected changes are discarded. Also, as mentioned above, the data for local item for `donald` has been discarded, since it did not include any changes. >>> i.contents.local_item == i.contents True >>> i.contents.type 'local' >>> i.contents('barbara').local_item # None >>> i.contents('barbara').type 'base' >>> i.contents('donald').local_item # None >>> i.contents('donald').type 'base' >>> IFreezing(app['e1'])._z_frozen False Our changes are a bit different than what we had when we began the commit, because of the version Factory. The f1 is not versioned, because we have made a copy instead. >>> IFreezing(app['f1'])._z_frozen False >>> new_changed = dict( ... (getattr(item, 'name', None), item) ... for item in i.iterChangedItems()) >>> new_changed['anna'].parent.name 'catherine' >>> new_changed['anna'].object is old_objects['anna'] True >>> new_changed['fred'].object is old_objects['fred'] False >>> new_changed['fred'].object is app['f1'] False >>> new_changed['fred'].object.source_name u'f1' >>> IFreezing(new_changed['anna'].object)._z_frozen True >>> IFreezing(new_changed['fred'].object)._z_frozen True Now that we have two versions in the vault, we can introduce two additional attributes of the inventories, contents, and items: `next` and `previous`. These attributes let you time travel in the vault's history. We also look at similar attributes on the manifest, and at the vault's `getInventory` method. For instance, the current inventory's `previous` attribute points to the original inventory, and vice versa. >>> i.previous == v.getInventory(0) True >>> i.manifest.previous is v[0] True >>> v.getInventory(0).next == i == v.inventory True >>> v[0].next is i.manifest is v.manifest True >>> i.next # None >>> manifest.next # None >>> v.getInventory(0).previous # None >>> v[0].previous # None The same is true for inventory items. >>> list(v.inventory.contents.previous.keys()) ['barbara', 'abe', 'donald'] >>> list(v.getInventory(0).contents.next.keys()) ['barbara', 'abe', 'donald', 'fred'] >>> v.inventory.contents.previous.next == v.inventory.contents True >>> v.inventory.contents('abe')('catherine')('anna').previous.object <Demo u'a1'> >>> (v.inventory.contents('abe').relationship is ... v.inventory.contents.previous('abe').relationship) True Once you step to a previous or next item, further steps from the item remain in the previous or next inventory. >>> v.inventory.contents('abe')('catherine')['anna'].__name__ == 'a1' False >>> v.inventory.contents.previous('abe')('catherine')['anna'] <Demo u'a1'> In addition, inventory items support `previous_version` and `next_version`. The difference between these and `previous` and `next` is that the `*_version` variants skip to the item that was different than the current item. For instance, while the previous_version of the 'anna' is the old 'a1' object, just like the `previous` value, the previous_version of 'abe' is None, because it has no previous version. >>> v.inventory.contents( ... 'abe')('catherine')('anna').previous_version.object <Demo u'a1'> >>> v.inventory.contents('abe').previous_version # None These leverage the `getPrevious` and `getNext` methods on the vault, which work with relationships. The previous and next tools are even more interesting when tokens move: you can see positions change within the hierarchy. Inventories have a `moveTo` method that can let the inventory follow the moves to maintain history. We'll create a new inventory copy and demonstrate. As we do, notice that inventory items obtained before the move correctly reflect the move, as described above. >>> manifest = Manifest(v.manifest) >>> del app['inventory'] >>> i = app['inventory'] = Inventory(manifest) >>> item = i.contents('abe')('catherine') >>> item.parent.name 'abe' >>> i.contents('abe')('catherine').moveTo(i.contents('fred')) >>> item.parent.name 'fred' >>> len(i.contents('abe').keys()) 0 >>> list(i.contents('fred').keys()) ['catherine'] The change actually only affects the source and target of the move. >>> changes = dict((getattr(item, 'name'), item) ... for item in i.iterChangedItems()) >>> len(changes) 2 >>> changes['fred'].values() [<Demo u'c1'>] >>> len(changes['abe'].keys()) 0 So now our hierarchy looks like this ("*" indicates a changed node):: (top node) / / \ \ ---- / \ --------- / | | \ 'barbara' 'abe'* 'donald' 'fred'* <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> <Demo u'f1'> | | 'catherine' <Demo u'c1'> | | 'anna' <Demo ...> If you try to move parts of the hierarchy to someplace that has the same name, you will receive a ValueError unless you specify a name that does not conflict. >>> i.contents('abe')['donald'] = app['d2'] >>> i.contents('donald').moveTo(i.contents('abe')) Traceback (most recent call last): ... ValueError: Object with same name already exists in new location >>> i.contents('donald').moveTo(i.contents('abe'), 'old_donald') >>> i.contents('abe').items() [('donald', <Demo u'd2'>), ('old_donald', <Demo u'd1'>)] Now our hierarchy looks like this ("*" indicates a changed or new node):: (top node)* / | \ ---- | ---- / | \ 'barbara' 'abe'* 'fred'* <Demo u'b1'> <Demo u'a1'> <Demo u'f1'> / \ | / \ | 'donald'* 'old_donald' 'catherine' <Demo u'd2'> <Demo u'd1'> <Demo u'c1'> | | 'anna' <Demo ...> If you try to move part of the hierarchy to someplace within itself, you will also receive a ValueError. >>> i.contents('fred').moveTo(i.contents('fred')('catherine')('anna')) Traceback (most recent call last): ... ValueError: May not move item to within itself It is for this reason that the contents does not support the moveTo operation. >>> hasattr(i.contents, 'moveTo') False If you move an object to the same folder it is a silent noop, unless you are using the move as a rename operation and the new name conflicts. >>> i.contents('abe')('old_donald').moveTo(i.contents('abe')) >>> i.contents('abe').items() [('donald', <Demo u'd2'>), ('old_donald', <Demo u'd1'>)] >>> i.contents('abe')('old_donald').moveTo(i.contents('abe'), 'donald') Traceback (most recent call last): ... ValueError: Object with same name already exists in new location >>> i.contents('abe').items() [('donald', <Demo u'd2'>), ('old_donald', <Demo u'd1'>)] >>> i.contents('abe')('donald').moveTo(i.contents('abe'), ... 'new_donald') >>> i.contents('abe').items() [('old_donald', <Demo u'd1'>), ('new_donald', <Demo u'd2'>)] Notice in the last part of the example above that the move within the folder also changed the order. It's also interesting to note that, with all these changes, we only have two additional changed items: the addition of new_donald, and the changed containment of the contents. old_donald, for instance, is not considered to be changed; only its containers were. >>> changes = dict((getattr(item, 'name', None), item) ... for item in i.iterChangedItems()) >>> len(changes) 4 >>> changes['fred'].items() [('catherine', <Demo u'c1'>)] >>> changes['abe'].items() [('old_donald', <Demo u'd1'>), ('new_donald', <Demo u'd2'>)] >>> changes['new_donald'].object <Demo u'd2'> >>> list(changes[None].keys()) ['barbara', 'abe', 'fred'] Now that we have moved some objects that existed in previous inventories-- catherine (containing anna) was moved from abe to fred, and donald was moved from the root contents to abe and renamed to 'old_donald'--we can examine the previous and previous_version pointers. >>> i.contents('abe')('old_donald').previous.parent == i.previous.contents True >>> i.contents('abe')('old_donald').previous_version # None The previous_version is None because, as seen in the iterChangedItems example, donald didn't actually change--only its containers did. previous_version does work for both local changes and changes in earlier inventories, though. >>> list(i.contents('abe').keys()) ['old_donald', 'new_donald'] >>> list(i.contents('abe').previous.keys()) ['catherine'] >>> (i.contents('fred')('catherine')('anna').previous.inventory == ... v.inventory) True >>> (i.contents('fred')('catherine')('anna').previous_version.inventory == ... v.getInventory(0)) True The previous_version of anna is the first one that was committed in the initial inventory--it didn't change in this version, but in the most recently committed inventory, so the previous version is the very first one committed. By the way, notice that, while previous and previous_version point to the inventories from which the given item came, the historical, versioned inventories in the vault don't point to this working inventory in next or next_version because this inventory has not been committed yet. >>> v.inventory.contents('abe').next # None >>> v.inventory.contents('abe').next_version # None As mentioned above, only inventory items support `moveTo`, not the top-node inventory contents. Both contents and inventory items support a `copyTo` method. This is similar to moveTo but it creates new additional locations in the inventory for the same objects; the new locations don't maintain any history. It is largely a short hand for doing "location1['foo'] = location2['foo']" for all objects in a part of the inventory. The only difference is when copying between inventories, as we will see below. The basic `copyTo` machinery is very similar to `moveTo`. We'll first copy catherine and anna to within the contents. >>> i.contents('fred')('catherine').copyTo(i.contents) >>> list(i.contents.keys()) ['barbara', 'abe', 'fred', 'catherine'] >>> list(i.contents('catherine').keys()) ['anna'] >>> i.contents['catherine'] is i.contents('fred')['catherine'] True >>> (i.contents('catherine')('anna').object is ... i.contents('fred')('catherine')('anna').object) True Now our hierarchy looks like this ("*" indicates a changed or new node):: (top node)* --------/ / \ \----------- / / \ \ / / \ \ 'barbara' 'abe'* 'fred'* 'catherine'* <Demo u'b1'> <Demo u'a1'> <Demo u'f1'> <Demo u'c1'> / \ | | / \ | | 'new_donald'* 'old_donald' 'catherine' 'anna'* <Demo u'd2'> <Demo u'd1'> <Demo u'c1'> <Demo ...> | | 'anna' <Demo ...> Now we have copied objects from one location to another. The copies are unlike the originals because they do not have any history. >>> i.contents('fred')('catherine')('anna').previous is None False >>> i.contents('catherine')('anna').previous is None True However, they do know their copy source. >>> (i.contents('catherine')('anna').copy_source == ... i.contents('fred')('catherine')('anna')) True As with `moveTo`, you may not override a name, but you may explicitly provide one. >>> i.contents['anna'] = Demo() >>> i.contents('catherine')('anna').copyTo(i.contents) Traceback (most recent call last): ... ValueError: Object with same name already exists in new location >>> i.contents('catherine')('anna').copyTo(i.contents, 'old_anna') >>> list(i.contents.keys()) ['barbara', 'abe', 'fred', 'catherine', 'anna', 'old_anna'] >>> del i.contents['anna'] >>> del i.contents['old_anna'] Unlike with `moveTo`, if you try to copy a part of the hierarchy on top of itself (same location, same name), the inventory will raise an error. >>> i.contents('catherine')('anna').copyTo(i.contents('catherine')) Traceback (most recent call last): ... ValueError: Object with same name already exists in new location You can actually copyTo a location in a completely different inventory, even from a separate vault. >>> another = app['another'] = Vault() >>> another_i = app['another_i'] = Inventory(vault=another) >>> len(another_i.contents) 0 >>> i.contents('abe').copyTo(another_i.contents) >>> another_i.contents['abe'] <Demo u'a1'> >>> another_i.contents('abe')['new_donald'] <Demo u'd2'> >>> another_i.contents('abe')['old_donald'] <Demo u'd1'> We haven't committed for awhile, so let's commit this third revision. We did a lot of deletes, so let's just accept all of the orphan conflicts. >>> for item in i.iterOrphanConflicts(): ... item.resolveOrphanConflict() ... >>> v.commit(i) >>> checkManifest(v.manifest) In a future revision of the zc.vault package, it may be possible to move and copy between inventories. At the time of writing, this use case is unnecessary, and doing so will have unspecified behavior. .. topic:: A test for a subtle bug in revision <= 78553 One important case, at least for the regression testing is an attempt to rename an item after the vault has been frozen. Since we have just committed, this is the right time to try that. Let's create a local copy of an inventory and try to rename some items on it. >>> v.manifest._z_frozen True >>> l = Inventory(Manifest(v.manifest)) >>> l.manifest._z_frozen False >>> l.contents('abe').items() [('old_donald', <Demo u'd1'>), ('new_donald', <Demo u'Demo-2'>)] >>> l.contents('abe')('old_donald').moveTo(l.contents('abe'), 'bob') >>> l.contents('abe')('new_donald').moveTo(l.contents('abe'), 'donald') >>> l.contents('abe').items() [('bob', <Demo u'd1'>), ('donald', <Demo u'Demo-2'>)] We have now discussed the core API for the vault system for basic use. A number of other use cases are important, however: - revert to an older inventory; - merge concurrent changes; - track an object in a vault; and - traverse through a vault using URL or TALES paths. Reverting to an older inventory is fairly simple: use the 'commitFrom' method to copy and commit an older version into a new copy. The same works with manifests. >>> v.commitFrom(v[0]) The data is now as it was in the old version. >>> list(v.inventory.contents.keys()) ['barbara', 'abe', 'donald'] Now our hierarchy looks like this again:: (top node) / | \ / | \ 'barbara' 'abe' 'donald' <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> | | 'catherine' <Demo u'c1'> | | 'anna' <Demo u'a1'> The `commitFrom` method will take any committed manifest from a vault that shares the same intids utility. It creates a new manifest that duplicates the provided one. >>> v.inventory.contents('abe')('catherine').previous.parent.name 'fred' >>> v.manifest.previous is v[-2] True >>> v.manifest.base_source is v[-2] True >>> v.manifest.base_source is v[0] False >>> v[-2].base_source is v[-3] True Note that this approach will cause an error: >>> v.commit(Manifest(v[0])) # doctest: +ELLIPSIS Traceback (most recent call last): ... OutOfDateError: <zc.vault.core.Manifest object at ...> Again, use `commitFrom` to revert. Now we come to the most complex vault use case: concurrent changes to a vault, merging inventories. The vault design supports a number of features for these sorts of use cases. The basic merge story is that if one or more commits happen to a vault while an inventory from the vault is being worked on, so that the base of a working inventory is no longer the most recent committed inventory, and thus cannot be committed normally... >>> long_running = Inventory(Manifest(v.manifest)) >>> short_running = Inventory(Manifest(v.manifest)) >>> long_running.manifest.base_source is v.manifest True >>> short_running.contents['donald'] = app['d2'] >>> short_running.contents.items() [('barbara', <Demo u'b1'>), ('abe', <Demo u'a1'>), ('donald', <Demo u'd2'>)] >>> v.commit(short_running) >>> checkManifest(v.manifest) >>> short_running = Inventory(Manifest(v.manifest)) >>> short_running.contents('barbara')['fred'] = app['f1'] >>> v.commit(short_running) >>> checkManifest(v.manifest) >>> long_running.manifest.base_source is v.manifest False >>> long_running.manifest.base_source is v.manifest.previous.previous True >>> long_running.contents['edna'] = app['e1'] >>> long_running.contents.items() # doctest: +NORMALIZE_WHITESPACE [('barbara', <Demo u'b1'>), ('abe', <Demo u'a1'>), ('donald', <Demo u'd1'>), ('edna', <Demo u'e1'>)] >>> v.commit(long_running) # doctest: +ELLIPSIS Traceback (most recent call last): ... OutOfDateError: <zc.vault.core.Manifest object at ...> ...then the inventory can be updated; and, if there are no problems with the update, then the inventory can be committed. short_running, and the head of the vault, looks like this now ("*" indicates a change from the previous version):: (top node) / | \ / | \ 'barbara'* 'abe' 'donald'* <Demo u'b1'> <Demo u'a1'> <Demo u'd2'> | | | | 'fred'* 'catherine' <Demo u'f1'> <Demo u'c1'> | | 'anna' <Demo u'a1'> long_running looks like this:: (top node)* ------/ / \ \---------- / / \ \ 'barbara' 'abe' 'donald' 'edna'* <Demo u'b1'> <Demo u'a1'> <Demo u'd1'> <Demo u'e1'> | | 'catherine' <Demo u'c1'> | | 'anna' <Demo u'a1'> The contents node changed and 'edna' was added. By default, an update is to the current inventory of the inventory base's vault. Here's the update. It will produce no conflicts, because the node changes do not overlap (review diagrams above). >>> long_running.beginUpdate() >>> long_running.updating True Post-merge, long_running looks like this ('M' indicates a merged node):: (top node)* ------/ / \ \---------- / / \ \ 'barbara'M 'abe' 'donald'M 'edna'* <Demo u'b1'> <Demo u'a1'> <Demo u'd2'> <Demo u'e1'> | | | | 'fred'M 'catherine' <Demo u'f1'> <Demo u'c1'> | | 'anna' <Demo u'a1'> (ADVANCED) During an update, the local relationships may not be changed, even though they are not versioned. >>> long_running.contents('edna').type 'local' >>> long_running.contents('edna').relationship.object = Demo() Traceback (most recent call last): ... UpdateError: cannot change local relationships while updating >>> long_running.contents('edna').relationship.object <Demo u'e1'> >>> long_running.contents('edna').relationship._z_frozen False >>> long_running.manifest.getType(long_running.contents.relationship) 'local' >>> long_running.contents.relationship.containment.updateOrder( ... ('abe', 'barbara', 'edna', 'donald')) Traceback (most recent call last): ... UpdateError: cannot change local relationships while updating >>> long_running.contents.relationship.containment.keys() ('barbara', 'abe', 'donald', 'edna') When you change an item or contents, this is hidden by switching to a MODIFIED relationship, as seen below. (end ADVANCED) Now that we have updated, our `update_source` on the inventory shows the inventory used to do the update. >>> long_running.manifest.base_source is v[-3] True >>> long_running.manifest.update_source is short_running.manifest True What changes should the update reflect? iterChangedItems takes an optional argument which can use an alternate base to calculate changes, so we can use that with the long_running.base to see the effective merges. >>> changed = dict((getattr(item, 'name', None), item) for item in ... short_running.iterChangedItems( ... long_running.manifest.base_source)) >>> changed['donald'].object.source_name u'd2' >>> changed['fred'].object.source_name u'f1' >>> list(changed['barbara'].keys()) ['fred'] Our contents show these merged results. >>> list(long_running.contents.keys()) ['barbara', 'abe', 'donald', 'edna'] >>> long_running.contents['donald'].source_name u'd2' >>> long_running.contents('barbara')['fred'].source_name u'f1' You cannot update to another inventory until you `abortUpdate` or `completeUpdate`, as we discuss far below. >>> long_running.beginUpdate(v[-2]) Traceback (most recent call last): ... UpdateError: cannot begin another update while updating We'll show `abortUpdate`, then redo the update. A characteristic of abortUpdate is that it should revert all changes you made while updating. For instance, we'll select another version of the contents and even add an item. The changes will all go away when we abort. >>> len(list(long_running.iterChangedItems())) 5 >>> long_running.contents['fred'] = app['f1'] >>> list(long_running.contents.keys()) ['barbara', 'abe', 'donald', 'edna', 'fred'] >>> len(list(long_running.iterChangedItems())) 6 >>> long_running.abortUpdate() >>> long_running.manifest.update_source # None >>> long_running.contents.items() # doctest: +NORMALIZE_WHITESPACE [('barbara', <Demo u'b1'>), ('abe', <Demo u'a1'>), ('donald', <Demo u'd1'>), ('edna', <Demo u'e1'>)] >>> len(list(long_running.iterChangedItems())) 2 >>> long_running.beginUpdate() >>> list(long_running.contents.keys()) ['barbara', 'abe', 'donald', 'edna'] >>> long_running.contents['donald'].source_name u'd2' >>> long_running.contents('barbara')['fred'].source_name u'f1' Now we'll look around more at the state of things. We can use iterChangedItems to get a list of all changed and updated. As already seen in the examples, `update_source` on the inventory shows the inventory used to do the update. >>> updated = {} >>> changed = {} >>> for item in long_running.iterChangedItems(): ... name = getattr(item, 'name', None) ... if item.type == interfaces.LOCAL: ... changed[name] = item ... else: ... assert item.type == interfaces.UPDATED ... updated[name] = item ... >>> len(updated) 3 >>> updated['donald'].object.source_name u'd2' >>> updated['fred'].object.source_name u'f1' >>> list(updated['barbara'].keys()) ['fred'] >>> len(changed) 2 >>> list(changed[None].keys()) ['barbara', 'abe', 'donald', 'edna'] >>> changed['edna'].object <Demo u'e1'> The `has_updated` and `updated_item` attributes, which only come into effect when an inventory is in the middle of an update, let you examine the changes from a more local perspective. >>> long_running.contents('donald').has_local False >>> long_running.contents('donald').has_updated True >>> (long_running.contents('donald').updated_item.relationship is ... long_running.contents('donald').relationship) True There are three kinds of problems that can prevent a post-merge commit: item conflicts, orphans, and parent conflicts. Item conflicts are item updates that conflicted with local changes and that the system could not merge (more on that below). Orphans are accepted item changes (local or updated) that are not accessible from the top contents, and so will be lost. Parent conflicts are items that were moved to one location in the source and another location in the local changes, and so now have two parents: an illegal state because it makes future merges and sane historical analysis difficult. These three kinds of problem can be analyzed with `iterUpdateConflicts`, `iterOrphanConflicts`, and `iterParentConflicts`, respectively. We have already seen iterOrphanConflicts. In our current merge, we have none of these problems, and we can commit (or completeUpdate) successfully. >>> list(long_running.iterUpdateConflicts()) [] >>> list(long_running.iterOrphanConflicts()) [] >>> list(long_running.iterParentConflicts()) [] >>> v.commit(long_running) >>> checkManifest(v.manifest) We had a lot of discussion between the most important points here, so to review, all we had to do in the simple case was this:: long_running.beginUpdate() v.commit(long_running) We could have rejected some of the updates and local changes, which might have made things more interesting; and the two steps let you analyze the update changes to tweak things as desired. But the simplest case allows a simple spelling. Now let's explore the possible merging problems. The first, and arguably most complex, is item conflict. An item conflict is easy to provoke. We can do it by manipulating the containment or the object of an item. Here we'll manipulate the containment order of the root. >>> list(v.inventory.contents.keys()) ['barbara', 'abe', 'donald', 'edna'] >>> short_running = Inventory(Manifest(v.manifest)) >>> long_running = Inventory(Manifest(v.manifest)) >>> short_running.contents.updateOrder( ... ('abe', 'barbara', 'edna', 'donald')) >>> long_running.contents.updateOrder( ... ('abe', 'barbara', 'donald', 'edna')) >>> v.commit(short_running) >>> checkManifest(v.manifest) >>> long_running.beginUpdate() >>> v.commit(long_running) Traceback (most recent call last): ... UpdateError: cannot complete update with conflicts >>> conflicts = list(long_running.iterUpdateConflicts()) >>> len(conflicts) 1 >>> conflict = conflicts[0] >>> conflict.type 'local' >>> list(conflict.keys()) ['abe', 'barbara', 'donald', 'edna'] >>> conflict.is_update_conflict True >>> conflict.selected True >>> conflict.has_updated True >>> list(conflict.updated_item.keys()) ['abe', 'barbara', 'edna', 'donald'] As you can see, we have the tools to find out the conflicts and examine them. To resolve this conflict, we merely need to use the `resolveUpdateConflict` method. We can select the desired one we want, or even create a new one and modify it, before or after marking it resolved. Let's create a new one. All you have to do is start changing the item, and a new one is created. You are not allowed to directly modify local changes when you are updating, so that the system can revert to them; but you may create 'modified' versions (that will be discarded if the update is aborted). >>> len(list(conflict.iterModifiedItems())) 0 >>> conflict.has_modified False >>> conflict.selected True >>> conflict.type 'local' >>> list(conflict.keys()) ['abe', 'barbara', 'donald', 'edna'] >>> conflict.updateOrder(['abe', 'donald', 'barbara', 'edna']) >>> len(list(conflict.iterModifiedItems())) 1 >>> conflict.has_modified True >>> conflict.selected True >>> conflict.type 'modified' >>> conflict.copy_source.type 'local' >>> conflict.copy_source == conflict.local_item True >>> conflict == list(conflict.iterModifiedItems())[0] True >>> list(conflict.local_item.keys()) ['abe', 'barbara', 'donald', 'edna'] >>> list(conflict.keys()) ['abe', 'donald', 'barbara', 'edna'] >>> list(conflict.updated_item.keys()) ['abe', 'barbara', 'edna', 'donald'] Now we're going to resolve it. >>> conflict.resolveUpdateConflict() >>> conflict.is_update_conflict False >>> len(list(long_running.iterUpdateConflicts())) 0 >>> resolved = list(long_running.iterUpdateResolutions()) >>> len(resolved) 1 >>> resolved[0] == conflict True Now if we called abortUpdate, the local_item would look the way it did before the update, because we modified a separate object. Let's commit, though. >>> v.commit(long_running) >>> checkManifest(v.manifest) Our hierarchy looks like this now:: (top node)* ----------/ / \ \---------- / / \ \ 'abe' 'donald'M 'barbara'M 'edna'* <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | | | 'catherine' 'fred'M <Demo u'c1'> <Demo u'f1'> | | 'anna' <Demo u'a1'> The vault code allows for adapters to try and suggest merges. For instance, a simple merge might have a policy that one version with an object change and another version with a containment change can be merged simply. This uses some APIs we haven't talked about yet: if there is a core.txt in this directory, you're in luck; otherwise, hope for help in interfaces.py and bother Gary for docs (sorry). >>> from zc.vault.core import Relationship >>> @component.adapter(interfaces.IVault) ... @interface.implementer(interfaces.IConflictResolver) ... def factory(vault): ... def resolver(manifest, local, updated, base): ... if local.object is not base.object: ... if updated.object is base.object: ... object = local.object ... else: ... return ... else: ... object = updated.object ... if local.containment != base.containment: ... if updated.containment != base.containment: ... return ... else: ... containment = local.containment ... else: ... containment = updated.containment ... suggested = Relationship(local.token, object, containment) ... manifest.addSuggested(suggested) ... manifest.select(suggested) ... manifest.resolveUpdateConflict(local.token) ... return resolver ... >>> component.provideAdapter(factory) Now if we merge changes that this policy can handle, we'll have smooth updates. >>> short_running = Inventory(Manifest(v.manifest)) >>> long_running = Inventory(Manifest(v.manifest)) >>> app['c2'] = Demo() >>> short_running.contents('abe')['catherine'] = app['c2'] >>> v.commit(short_running) >>> checkManifest(v.manifest) >>> long_running.contents('abe')('catherine')['fred'] = app['f1'] >>> long_running.beginUpdate() >>> cath = long_running.contents('abe')('catherine') >>> cath.has_suggested True >>> cath.type 'suggested' >>> cath.has_updated True >>> cath.selected True >>> cath.has_local True >>> suggestedItems = list(cath.iterSuggestedItems()) >>> len(suggestedItems) 1 >>> suggestedItems[0] == cath True >>> cath.object.source_name u'c2' >>> list(cath.keys()) ['anna', 'fred'] >>> cath.local_item.object <Demo u'c1'> >>> v.commit(long_running) >>> checkManifest(v.manifest) This means we automatically merged this... :: (top node) ----------/ / \ \---------- / / \ \ 'abe' 'donald' 'barbara' 'edna' <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | | | 'catherine'* 'fred' <Demo u'c2'> <Demo u'f1'> | | 'anna' <Demo u'a1'> ...with this (that would normally produce a conflict with the 'catherine' node)... :: (top node) ----------/ / \ \---------- / / \ \ 'abe' 'donald' 'barbara' 'edna' <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | | | 'catherine'* 'fred' <Demo u'c1'> <Demo u'f1'> / \ / \ 'anna' 'fred'* <Demo u'a1'> <Demo u'f1'> ...to produce this:: (top node) ----------/ / \ \---------- / / \ \ 'abe' 'donald' 'barbara' 'edna' <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | | | 'catherine'* 'fred' <Demo u'c2'> <Demo u'f1'> / \ / \ 'anna' 'fred'* <Demo u'a1'> <Demo u'f1'> This concludes our tour of item conflicts. We are left with orphans and parent conflicts. As mentioned above, orphans are accepted, changed items, typically from the update or local changes, that are inaccessible from the root of the inventory. For example, consider the following. >>> short_running = Inventory(Manifest(v.manifest)) >>> long_running = Inventory(Manifest(v.manifest)) >>> list(short_running.contents('abe').keys()) ['catherine'] >>> list(short_running.contents('abe')('catherine').keys()) ['anna', 'fred'] >>> del short_running.contents('abe')['catherine'] >>> v.commit(short_running) >>> checkManifest(v.manifest) >>> long_running.contents('abe')('catherine')['anna'] = Demo() >>> long_running.beginUpdate() >>> v.commit(long_running) Traceback (most recent call last): ... UpdateError: cannot complete update with conflicts >>> orphans =list(long_running.iterOrphanConflicts()) >>> len(orphans) 1 >>> orphan = orphans[0] >>> orphan.parent.name 'catherine' >>> orphan.selected True >>> orphan.type 'local' >>> orphan.parent.selected True >>> orphan.parent.type 'base' >>> orphan.parent.parent.type 'base' >>> orphan.parent.parent.selected False >>> orphan.parent.parent.selected_item.type 'updated' To reiterate in a diagram, the short_running inventory deleted the 'catherine' branch:: (top node) ----------/ / \ \---------- / / \ \ 'abe' 'donald' 'barbara' 'edna' <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | 'fred' <Demo u'f1'> However, the long running branch made a change to an object that had been removed ('anna'):: (top node) ----------/ / \ \---------- / / \ \ 'abe' 'donald' 'barbara' 'edna' <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | | | 'catherine' 'fred' <Demo u'c2'> <Demo u'f1'> / \ / \ 'anna'* 'fred' <Demo ...> <Demo u'f1'> So, given the orphan, you can discover the old version of the node that let the change occur, and thus the change that hid the orphan. To resolve an orphan, as seen before, you can `resolveOrphanConflict`, or somehow change the tree so that the orphan is within the tree again (using `moveTo`). We'll just resolve it. Note that resolving keeps it selected: it just stops the complaining. >>> orphan.selected True >>> orphan.resolveOrphanConflict() >>> orphan.selected True >>> len(list(long_running.iterOrphanConflicts())) 0 >>> v.commit(long_running) >>> checkManifest(v.manifest) The same happens if the change occurs because of a reversal--the long_running inventory performs the delete. It also can happen if the user explicitly selects a choice that eliminates an accepted change, even outside of a merge, as we have seen above. Parent conflicts are the last sort of conflict. Our hierarchy now looks like this:: (top node) ----------/ / \ \---------- / / \ \ 'abe' 'donald' 'barbara' 'edna' <Demo u'a1'> <Demo u'd2'> <Demo u'b1'> <Demo u'e1'> | | 'fred' <Demo u'f1'> The short_running version will be changed to look like this:: (top node) ------/ | \------- / | \ 'abe' 'barbara'* 'edna' <Demo u'a1'> <Demo u'b1'> <Demo u'e1'> / \ / \ 'fred' 'donald' <Demo u'f1'> <Demo u'd2'> The long_running version will look like this. :: (top node) ------/ | \------- / | \ 'abe' 'barbara' 'edna' <Demo u'a1'> <Demo u'b1'> <Demo u'e1'> | | 'fred'* <Demo u'f1'> | | 'donald' <Demo u'd2'> Post-merge the tree looks like this:: (top node) ------/ | \------- / | \ 'abe' 'barbara'* 'edna' <Demo u'a1'> <Demo u'b1'> <Demo u'e1'> / \ / \ 'fred'* 'donald' <Demo u'f1'> <Demo u'd2'> | | 'donald' <Demo u'd2'> The problem is Donald. It is one token in two or more places: a parent conflict. >>> short_running = Inventory(Manifest(v.manifest)) >>> long_running = Inventory(Manifest(v.manifest)) >>> short_running.contents('donald').moveTo( ... short_running.contents('barbara')) >>> v.commit(short_running) >>> checkManifest(v.manifest) >>> long_running.contents('donald').moveTo( ... long_running.contents('barbara')('fred')) >>> long_running.beginUpdate() >>> conflicts = list(long_running.iterParentConflicts()) >>> v.commit(long_running) Traceback (most recent call last): ... UpdateError: cannot complete update with conflicts >>> conflicts = list(long_running.iterParentConflicts()) >>> len(conflicts) 1 >>> conflict = conflicts[0] >>> conflict.name Traceback (most recent call last): ... ParentConflictError >>> conflict.parent Traceback (most recent call last): ... ParentConflictError >>> selected = list(conflict.iterSelectedParents()) >>> len(selected) 2 >>> sorted((s.type, s.name) for s in selected) [('local', 'fred'), ('updated', 'barbara')] >>> all = dict((s.type, s) for s in conflict.iterParents()) >>> len(all) 3 >>> sorted(all) ['base', 'local', 'updated'] You can provoke these just by accepting a previous version, outside of merges. For instance, we can now make a three-way parent conflict by selecting the root node. >>> all['base'].select() >>> selected = list(conflict.iterSelectedParents()) >>> len(selected) 3 Now if we resolve the original problem by rejecting the local change, we'll still have a problem, because of accepting the baseParent. >>> all['local'].base_item.select() >>> selected = list(conflict.iterSelectedParents()) >>> len(selected) 2 >>> v.commit(long_running) Traceback (most recent call last): ... UpdateError: cannot complete update with conflicts >>> all['base'].local_item.select() >>> len(list(long_running.iterParentConflicts())) 0 Now our hierarchy looks like short_running again:: (top node) ------/ | \------- / | \ 'abe' 'barbara' 'edna' <Demo u'a1'> <Demo u'b1'> <Demo u'e1'> / \ / \ 'fred' 'donald' <Demo u'f1'> <Demo u'd2'> We can't check this in because there are no effective changes between this and the last checkin. >>> v.commit(long_running) # doctest: +ELLIPSIS Traceback (most recent call last): ... NoChangesError: <zc.vault.core.Manifest object at ...> So actually, we'll reinstate the local change, reject the short_running change (the placement within barbara), and commit. >>> all['local'].select() >>> all['updated'].base_item.select() >>> v.commit(long_running) >>> checkManifest(v.manifest) Note that even though we selected the base_item, the relationship generated by completing the update is actually local because it is a change from the previous updated source. >>> v.inventory.contents('barbara').type 'local' There is actually a fourth kind of error: having child nodes in selected relationships for which there are no selected relationships. The code tries to disallow this, so it should not be encountered. Next, we will talk about using vaults to create and manage branches. The simple basics of this are that you can commit an inventory based on one vault into a fresh vault, and you can then update across the two vaults. To create a vault that can have merged manifests, you must share the internal 'intids' attribute. The `createBranch` method is sugar for doing that and then (by default) committing the most recent manifest of the current vault as the first revision of the branch. >>> branch = app['branch'] = v.createBranch() >>> bi = Inventory(Manifest(branch.manifest)) >>> branch_start_inventory = v.inventory >>> bi.contents['george'] = Demo() >>> branch.commit(bi) >>> checkManifest(branch.manifest) >>> i = Inventory(Manifest(v.manifest)) >>> i.contents['barbara'] = app['b2'] = Demo() >>> v.commit(i) >>> checkManifest(v.manifest) >>> i.contents['barbara'].source_name u'b2' >>> bi = Inventory(Manifest(branch.manifest)) >>> bi.contents('barbara')['henry'] = app['h1'] = Demo() >>> branch.commit(bi) >>> checkManifest(branch.manifest) Now we want to merge the mainline changes with the branch. >>> bi = Inventory(Manifest(branch.manifest)) >>> (bi.manifest.base_source is bi.manifest.getBaseSource(branch) is ... branch.manifest) True >>> (bi.manifest.getBaseSource(v) is branch_start_inventory.manifest is ... v[-2]) True >>> bi.beginUpdate(v.inventory) >>> bi.contents['barbara'].source_name u'b2' >>> bi.contents('barbara')['henry'].source_name u'h1' A smooth update. But what happens if meanwhile someone changes the branch, before this is committed? We use `completeUpdate`, and then update again on the branch. `completeUpdate` moves all selected changes to be `local`, whatever the source, the same way commit does (in fact, commit uses completeUpdate). >>> bi2 = Inventory(Manifest(branch.manifest)) >>> bi2.contents['edna'] = app['e2'] = Demo() >>> branch.commit(bi2) >>> checkManifest(branch.manifest) >>> branch.commit(bi) # doctest: +ELLIPSIS Traceback (most recent call last): ... OutOfDateError: <zc.vault.core.Manifest object at ...> >>> bi.completeUpdate() >>> bi.beginUpdate() >>> branch.commit(bi) >>> checkManifest(branch.manifest) Once we have done this, the head of the branch is based on the head of the original vault, so we can immediately check in a branch inventory in the trunk inventory. >>> v.commit(Inventory(Manifest(branch.manifest))) >>> checkManifest(v.manifest) Finally, cherry-picking changes is possible as well, though it can cause normal updates to be confused. `beginCollectionUpdate` takes an iterable of items (such as is produced by iterChangedItems) and applies the update with the usual conflict and examination approaches we've seen above. `completeUpdate` can then accept the changes for additional updates. >>> long_running = Inventory(Manifest(v.manifest)) >>> discarded = Inventory(Manifest(v.manifest)) >>> discarded.contents['ignatius'] = app['i1'] = Demo() >>> discarded.contents['jacobus'] = app['j1'] = Demo() >>> long_running.beginCollectionUpdate((discarded.contents('ignatius'),)) >>> len(list(long_running.iterOrphanConflicts())) 1 >>> o = iter(long_running.iterOrphanConflicts()).next() >>> o.selected True >>> o.name # None >>> o.parent # None >>> o.object <Demo u'i1'> >>> o.moveTo(long_running.contents, 'ignatius') >>> len(list(long_running.iterOrphanConflicts())) 0 >>> long_running.contents['ignatius'] <Demo u'i1'> >>> long_running.contents('ignatius')['jacobus'] = app['j1'] >>> list(long_running.contents('ignatius').keys()) ['jacobus'] >>> long_running.contents('ignatius')('jacobus').selected True >>> list(discarded.contents('ignatius').keys()) [] >>> v.commit(long_running) >>> checkManifest(v.manifest) The code will stop you if you try to add a set of relationships that result in the manifest having keys that don't map to values--or more precisely, child tokens that don't have matching selected relationships. For instance, consider this. >>> long_running = Inventory(Manifest(v.manifest)) >>> discarded = Inventory(Manifest(v.manifest)) >>> discarded.contents['katrina'] = app['k1'] = Demo() >>> discarded.contents('katrina')['loyola'] = app['l1'] = Demo() >>> long_running.beginCollectionUpdate((discarded.contents('katrina'),)) ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: cannot update from a set that includes children tokens... It is disallowed because the katrina node includes the 'loyola' node, but we didn't include the matching 'loyola' item. If you include both, the merge will proceed as usual. >>> long_running.beginCollectionUpdate( ... (discarded.contents('katrina'), ... discarded.contents('katrina')('loyola'))) >>> long_running.updating True >>> len(list((long_running.iterOrphanConflicts()))) 2 >>> orphans = dict((o.name, o) for o in long_running.iterOrphanConflicts()) >>> orphans[None].moveTo(long_running.contents, 'katrina') >>> long_running.contents['katrina'] <Demo u'k1'> >>> long_running.contents('katrina')['loyola'] <Demo u'l1'> The combination of `beginCollectionUpdate` and `iterChangedItems` can provide a powerful way to apply arbitrary changesets to a revision. Storing None ============ Sometimes you want to just make an empty node for organizational purposes. While normally stored objects must be versionable and adaptable to IKeyReference, None is a special case. We can store None in any node. Let's make a quick example. >>> v = app['v'] = Vault() >>> i = Inventory(vault=v) >>> i.contents['foo'] = None >>> i.contents('foo')['bar'] = None >>> i.contents('foo')('bar')['baz'] = app['d1'] >>> i.contents['foo'] # None >>> i.contents('foo')['bar'] # None >>> i.contents('foo')('bar')['baz'] is app['d1'] True >>> i.contents['bing'] = app['a1'] >>> i.contents['bing'] is app['a1'] True >>> v.commit(i) >>> i = Inventory(vault=v, mutable=True) >>> i.contents['bing'] = None >>> del i.contents('foo')['bar'] >>> i.contents['foo'] = app['d1'] >>> v.commit(i) >>> v.inventory.contents.previous['bing'] is app['a1'] True >>> v.inventory.contents.previous['foo'] is None True Special "held" Containers ========================= It is sometimes useful to specify a "held" container for all objects stored in a vault, overriding the "held" containers for each manifest as described above. Vaults can be instantiated with specifying a held container. >>> from zc.vault.core import HeldContainer >>> held = app['held'] = HeldContainer() >>> v = app['vault_held'] = Vault(held=held) >>> i = Inventory(vault=v) >>> o = i.contents['foo'] = Demo() >>> o.__parent__ is held True >>> held[o.__name__] is o True If you create a branch, by default it will use the same held container. >>> v.commit(i) >>> v2 = app['vault_held2'] = v.createBranch() >>> i2 = Inventory(vault=v2, mutable=True) >>> o2 = i2.contents['bar'] = Demo() >>> o2.__parent__ is held True >>> held[o2.__name__] is o2 True You can also specify another held container when you create a branch. >>> another_held = app['another_held'] = HeldContainer() >>> v3 = app['vault_held3'] = v.createBranch(held=another_held) >>> i3 = Inventory(vault=v3, mutable=True) >>> o3 = i3.contents['baz'] = Demo() >>> o3.__parent__ is another_held True >>> another_held[o3.__name__] is o3 True Committing the transaction ========================== We'll make sure that all these changes can in fact be committed to the ZODB. >>> import transaction >>> transaction.commit() ----------- .. Other topics. ...commit messages? Could be added to event, so object log could use. Need commit datetime stamp, users. Handled now by objectlog. Show traversal adapters that use zc.shortcut code... Talk about tokens. Then talk about use case of having a reference be updated to a given object within a vault... ...a vault mirror that also keeps track of hierarchy? A special reference that knows both vault and token?
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/README.txt
README.txt
import itertools import persistent from ZODB.interfaces import IConnection from zope import interface from zope.cachedescriptors.property import Lazy import zope.app.keyreference.interfaces import zope.app.container.contained from zc.vault import interfaces class AbstractUniqueReference(object): interface.implements( zope.app.keyreference.interfaces.IKeyReference, interfaces.IUniqueReference) __slots__ = () # must define identifiers and key_type_id def __call__(self): return self def __hash__(self): return hash(tuple(self.identifiers)) def __cmp__(self, other): if interfaces.IUniqueReference.providedBy(other): return cmp(tuple(self.identifiers), tuple(other.identifiers)) if zope.app.keyreference.interfaces.IKeyReference.providedBy(other): assert self.key_type_id != other.key_type_id return cmp(self.key_type_id, other.key_type_id) raise ValueError( "Can only compare against IUniqueIdentity and " "IKeyReference objects") # XXX this is API; need to highlight in tests... def getPersistentIdentifiers(obj): if obj._p_oid is None: connection = IConnection(obj, None) if connection is None: raise zope.app.keyreference.interfaces.NotYet(obj) connection.add(obj) return (obj._p_jar.db().database_name, obj._p_oid) class Token(AbstractUniqueReference, persistent.Persistent, zope.app.container.contained.Contained): interface.implements(interfaces.IToken) __slots__ = () key_type_id = 'zc.vault.keyref.Token' @Lazy def identifiers(self): return (self.key_type_id,) + getPersistentIdentifiers(self) class _top_token_(AbstractUniqueReference): # creates singleton interface.implements(interfaces.IToken) __slots__ = () key_type_id = 'zc.vault.keyref.TopToken' identifiers = (key_type_id,) def __reduce__(self): return _top_token, () top_token = _top_token_() def _top_token(): return top_token _top_token.__safe_for_unpickling__ = True
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/keyref.py
keyref.py
import zope.component import zope.interface import zope.interface.common.mapping import zope.location import zope.proxy import zope.copypastemove.interfaces import zope.app.container.interfaces import zope.app.container.constraints import zc.copy import zc.freeze.interfaces import zc.shortcut import zc.shortcut.proxy import zc.shortcut.interfaces # interfaces class IInventoryItemAware(zope.interface.Interface): _z_inventory_node = zope.interface.Attribute( """a zc.vault.interfaces.IContained (an IInventoryItem or an IInventoryContents.""") class IInventoryItemAwareFactory(zope.interface.Interface): def __call__(item, parent, name): """returns an object that provudes IInventoryItemAware""" class IProxy( IInventoryItemAware, zc.shortcut.interfaces.ITraversalProxy): """these proxies have _z_inventory_node, __traversed_parent__, and __traversed_name__""" class IData(zope.interface.Interface): """A marker interface that indicates that this object should be adapted to IInventoryItemAwareFactory, and then the factory should be called with the object's item, its parent, and its name within the parent.""" # the proxy class Proxy(zc.shortcut.proxy.ProxyBase): zc.shortcut.proxy.implements(IProxy) __slots__ = '_z_inventory_node', def __new__(self, ob, parent, name, item): return zc.shortcut.proxy.ProxyBase.__new__(self, ob, parent, name) def __init__(self, ob, parent, name, item): zc.shortcut.proxy.ProxyBase.__init__(self, ob, parent, name) self._z_inventory_node = item # the containers class ReadContainer(zope.location.Location): zope.interface.classProvides(IInventoryItemAwareFactory) zope.interface.implements( IInventoryItemAware, zope.interface.common.mapping.IEnumerableMapping) def __init__(self, item, parent=None, name=None): self.__parent__ = parent self.__name__ = name self._z_inventory_node = item def __len__(self): return len(self._z_inventory_node) def __iter__(self): return iter(self._z_inventory_node) def __contains__(self, key): return key in self._z_inventory_node def __getitem__(self, key): item = self._z_inventory_node(key) if item.object is None: factory = zope.component.getUtility(IInventoryItemAwareFactory) return factory(item, self, key) elif IData.providedBy(item.object): factory = IInventoryItemAwareFactory(item.object) return factory(item, self, key) else: return Proxy(item.object, self, key, item) def keys(self): return self._z_inventory_node.keys() def values(self): return [self[key] for key in self] def items(self): return [(key, self[key]) for key in self] def get(self, key, default=None): try: return self[key] except KeyError: return default def __getstate__(self): raise RuntimeError('This should not be persisted.') class Container(ReadContainer): zope.interface.implements(zope.interface.common.mapping.IMapping) def __setitem__(self, key, value): self._z_inventory_node[key] = value def __delitem__(self, key): del self._z_inventory_node[key] def updateOrder(self, order): self._z_inventory_node.updateOrder(order) # the movers and shakers # Unfortunately we have to duplicate the standard checkObject so we can # weed out the IContainer check, which is not pertinent here. def checkObject(container, name, object): """Check containment constraints for an object and container """ # check __setitem__ precondition containerProvided = zope.interface.providedBy(container) __setitem__ = containerProvided.get('__setitem__') if __setitem__ is not None: precondition = __setitem__.queryTaggedValue('precondition') if precondition is not None: precondition(container, name, object) # check the constraint on __parent__ __parent__ = zope.interface.providedBy(object).get('__parent__') if __parent__ is not None: try: validate = __parent__.validate except AttributeError: pass else: validate(container) def isInventoryObject(obj): return obj._z_inventory_node.object is zope.proxy.removeAllProxies(obj) class ObjectMover(object): """can only move objects within and among manifests; moving elsewhere has reparenting connotations that are inappropriate, since inventory membership and parentage are unrelated.""" zope.interface.implements(zope.copypastemove.interfaces.IObjectMover) zope.component.adapts(IInventoryItemAware) def __init__(self, context): self.context = context self.__parent__ = context def moveTo(self, target, new_name=None): if not IInventoryItemAware.providedBy(target): raise ValueError('target must be IInventoryItemAware') node = self.context._z_inventory_node if new_name is None: new_name = node.name if node == target._z_inventory_node and new_name == node.name: return # noop manifest = node.inventory.manifest if manifest._z_frozen: raise zc.freeze.interfaces.FrozenError(manifest) if target._z_inventory_node.inventory.manifest._z_frozen: raise zc.freeze.interfaces.FrozenError( target._z_inventory_node.inventory.manifest) checkObject(target, new_name, self.context) chooser = zope.app.container.interfaces.INameChooser(target) new_name = chooser.chooseName(new_name, node.object) node.moveTo(target._z_inventory_node, new_name) return new_name def moveable(self): manifest = self.context._z_inventory_node.inventory.manifest return not manifest._z_frozen def moveableTo(self, target, new_name=None): node = self.context._z_inventory_node manifest = node.inventory.manifest if (not manifest._z_frozen and IInventoryItemAware.providedBy(target) and not target._z_inventory_node.inventory.manifest._z_frozen): if new_name is None: new_name = node.name try: checkObject(target, new_name, self.context) except zope.interface.Invalid: pass else: return True return False class ObjectCopier(object): """Generally, make new copies of objects. If target is from a non-versioned manifest, use copyTo and then copy all of the non-None data objects in the tree. otherwise if the object is a proxied leaf node, do a normal copy; otherwise puke (can't copy a vault-specific object out of a vault). """ zope.interface.implements(zope.copypastemove.interfaces.IObjectCopier) zope.component.adapts(IInventoryItemAware) def __init__(self, context): self.context = context self.__parent__ = context def copyTo(self, target, new_name=None): if IInventoryItemAware.providedBy(target): if target._z_inventory_node.inventory.manifest._z_frozen: raise zc.freeze.interfaces.FrozenError( target._z_inventory_node.inventory.manifest) else: if not isInventoryObject(self.context): raise ValueError # TODO better error return zope.copypastemove.interfaces.IObjectCopier( zc.shortcut.proxy.removeProxy(self.context)).copyTo( target, new_name) node = self.context._z_inventory_node manifest = node.inventory.manifest if new_name is None: new_name = node.name checkObject(target, new_name, self.context) chooser = zope.app.container.interfaces.INameChooser(target) new_name = chooser.chooseName(new_name, node.object) node.copyTo(target._z_inventory_node, new_name) new_node = zope.proxy.removeAllProxies( target._z_inventory_node(new_name)) stack = [(lambda x: new_node, iter(('',)))] while stack: node, i = stack[-1] try: key = i.next() except StopIteration: stack.pop() else: next = node(key) original = next.object next.object = zc.copy.copy(original) stack.append((next, iter(next))) return new_name def copyable(self): return True def copyableTo(self, target, new_name=None): if not self.copyable(): return False if IInventoryItemAware.providedBy(target): if target._z_inventory_node.inventory.manifest._z_frozen: return False check = checkObject else: if not isInventoryObject(self.context): return False check = zope.app.container.constraints.checkObject node = self.context._z_inventory_node manifest = node.inventory.manifest if new_name is None: new_name = node.name try: check(target, new_name, self.context) except zope.interface.Invalid: return False else: return True class ObjectLinker(object): zope.component.adapts(IInventoryItemAware) zope.interface.implements(zc.shortcut.interfaces.IObjectLinker) def __init__(self, context): self.context = context self.__parent__ = context def linkTo(self, target, new_name=None): if IInventoryItemAware.providedBy(target): if target._z_inventory_node.inventory.manifest._z_frozen: raise zc.freeze.interfaces.FrozenError( target._z_inventory_node.inventory.manifest) else: if not isInventoryObject(self.context): raise ValueError # TODO better error return zc.shortcut.interfaces.IObjectLinker( zc.shortcut.proxy.removeProxy(self.context)).linkTo( target, new_name) node = self.context._z_inventory_node manifest = node.inventory.manifest if new_name is None: new_name = node.name checkObject(target, new_name, self.context) chooser = zope.app.container.interfaces.INameChooser(target) new_name = chooser.chooseName(new_name, node.object) node.copyTo(target._z_inventory_node, new_name) return new_name def linkable(self): return True def linkableTo(self, target, new_name=None): if IInventoryItemAware.providedBy(target): if target._z_inventory_node.inventory.manifest._z_frozen: return False obj = self.context check = checkObject else: if not isInventoryObject(self.context): return False obj = self._createShortcut( zc.shortcut.proxy.removeProxy(self.context)) check = zope.app.container.constraints.checkObject node = self.context._z_inventory_node manifest = node.inventory.manifest if new_name is None: new_name = node.name try: check(target, new_name, obj) except zope.interface.Invalid: return False else: return True def _createShortcut(self, target): return zc.shortcut.Shortcut(target)
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/traversal.py
traversal.py
from zope import interface, component, schema import zope.app.intid.interfaces import zope.lifecycleevent.interfaces import zope.location import zc.objectlog.interfaces from zc import objectlog import zc.freeze.interfaces from zc.vault.i18n import _ from zc.vault import interfaces class IManifestChangeset(interface.Interface): update_source_intid = schema.Int( title=_('Update Source'), description=_('Will be None for collection update'), required=False) update_base_intid = schema.Int( title=_('Update Base'), description=_('Will be None for collection update'), required=False) vault_intid = schema.Int( title=_('Vault'), required=True) class ManifestChangesetAdapter(object): interface.implements(IManifestChangeset) component.adapts(interfaces.IManifest) def __init__(self, man): intids = component.getUtility(zope.app.intid.interfaces.IIntIds) self.vault_intid = intids.register(man.vault) self.update_source_intid = self.update_base_intid = None if interfaces.IManifest.providedBy(man.update_source): self.update_source_intid = intids.register(man.update_source) if interfaces.IManifest.providedBy(man.update_base): self.update_base_intid = intids.register(man.update_base) class IRelationshipChangeset(interface.Interface): items = schema.Tuple( title=_('Items'), required=True) object_intid = schema.Int(title=_('Object'), required=False) class RelationshipChangesetAdapter(object): interface.implements(IRelationshipChangeset) component.adapts(interfaces.IRelationship) def __init__(self, relationship): self.items = tuple((k, v) for k, v in relationship.containment.items()) if relationship.object is None: self.object_intid = None else: intids = component.getUtility(zope.app.intid.interfaces.IIntIds) self.object_intid = intids.register(relationship.object) @component.adapter( interfaces.IManifest, zope.lifecycleevent.interfaces.IObjectCreatedEvent) def createManifestLog(man, ev): if not zc.objectlog.interfaces.ILogging.providedBy(man): man.log = objectlog.Log(IManifestChangeset) zope.location.locate(man.log, man, 'log') interface.directlyProvides(man, zc.objectlog.interfaces.ILogging) man.log(_('Created')) @component.adapter( interfaces.IRelationship, zope.lifecycleevent.interfaces.IObjectCreatedEvent) def createRelationshipLog(rel, ev): if not zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log = objectlog.Log(IRelationshipChangeset) zope.location.locate(rel.log, rel, 'log') interface.directlyProvides(rel, zc.objectlog.interfaces.ILogging) rel.log(_('Created')) rel.log(_('Created (end of transaction)'), defer=True, if_changed=True) @component.adapter(interfaces.IObjectRemoved) def logRemoval(ev): rel = ev.mapping.__parent__ if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Child removed')) @component.adapter(interfaces.IObjectAdded) def logAddition(ev): rel = ev.mapping.__parent__ if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Child added')) @component.adapter(interfaces.IOrderChanged) def logOrderChanged(ev): rel = ev.object.__parent__ if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Child order changed')) @component.adapter(interfaces.IManifestCommitted) def logCommit(ev): man = ev.object if zc.objectlog.interfaces.ILogging.providedBy(man): man.log(_('Committed')) @component.adapter( interfaces.IRelationship, zc.freeze.interfaces.IObjectFrozenEvent) def logVersioning(rel, ev): if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Versioned')) @component.adapter(interfaces.ILocalRelationshipAdded) def logNewLocal(ev): rel = ev.object if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Added as local relationship')) @component.adapter(interfaces.IModifiedRelationshipAdded) def logNewModified(ev): rel = ev.object if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Added as modified relationship')) @component.adapter(interfaces.ISuggestedRelationshipAdded) def logNewSuggested(ev): rel = ev.object if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Added as suggested relationship')) @component.adapter(interfaces.IUpdateBegun) def logUpdateBegun(ev): man = ev.object if zc.objectlog.interfaces.ILogging.providedBy(man): man.log(_('Update begun')) @component.adapter(interfaces.IUpdateAborted) def logUpdateAborted(ev): man = ev.object if zc.objectlog.interfaces.ILogging.providedBy(man): man.log(_('Update aborted')) @component.adapter(interfaces.IUpdateCompleted) def logUpdateCompleted(ev): man = ev.object if zc.objectlog.interfaces.ILogging.providedBy(man): man.log(_('Update completed')) @component.adapter(interfaces.IVaultChanged) def logVaultChanged(ev): man = ev.object if zc.objectlog.interfaces.ILogging.providedBy(man): man.log(_('Vault changed')) # ADDITIONAL_SELECTION = _('Selected in additional manifest (${intid})') @component.adapter(interfaces.IRelationshipSelected) def logSelection(ev): rel = ev.object if zc.objectlog.interfaces.ILogging.providedBy(rel): if ev.manifest is rel.__parent__: rel.log(_('Selected')) # else: # intids = component.getUtility(zope.app.intid.interfaces.IIntIds) # msg = i18n.Message(ADDITIONAL_SELECTION, # mapping={'intid': intids.register( # ev.manifest)}) # rel.log(msg) # ADDITIONAL_DESELECTION = _('Deselected from additional manifest (${intid})') @component.adapter(interfaces.IRelationshipDeselected) def logDeselection(ev): rel = ev.object if zc.objectlog.interfaces.ILogging.providedBy(rel): if ev.manifest is rel.__parent__: rel.log(_('Deselected')) # else: # intids = component.getUtility(zope.app.intid.interfaces.IIntIds) # msg = i18n.Message(ADDITIONAL_DESELECTION, # mapping={'intid': intids.register( # ev.manifest)}) # rel.log(msg) @component.adapter(interfaces.IObjectChanged) def logObjectChanged(ev): rel = ev.object if zc.objectlog.interfaces.ILogging.providedBy(rel): rel.log(_('Object changed'))
zc.vault
/zc.vault-0.11.tar.gz/zc.vault-0.11/src/zc/vault/objectlog.py
objectlog.py
WSGI+Webdriver for testing Javascript (and optionally WSGI) UIs *************************************************************** This package provides some helpers for testing Javascript (and optionally WSGI) applications using Python, Selenium Webdriver, Manuel, and WSGI. The package provides the following functions: ``setUp(test, app)`` a doctest ``setUp`` function that: - Sets up a webdriver, available as a ``browser`` variable. By default, a Chrome browser driver is used. You can override this in two ways: 1. Define a driver in a ``SELENIUM_DRIVER`` environment variable, or 2. In your test script, call the function ``get_factory_argument`` to parse arguments for a ``-b`` option, typically before calling whatever logic normally parses arguments. The value of this option is a driver definition. The function definition: ``get_factory_argument(argv=sys.argv, option='-b')`` Parse arguments for a browser definition. A driver definition can be one of the driver names, ``chrome`` ``firefox``, ``ie``, ``opera``, or ``phantomjs``. It can also be a remote driver specification. A remote driver specification is of the form:: browserName,version,platform,command_executor For example: internet explorer,10,Windows 8 Items on the right can be omitted. In the example above, we've left off the command executor. If the command executor isn't provided as part of the option, it must be provided via the ``SELENIUM_REMOTE_COMMAND_EXECUTOR`` environment variable. Note that to use firefox as a remote browser without specifying anything else, you'll need to supply a trailing comma to prevent it from being treated as a name. - Sets up a server to serve a WSGI application. - Sets up 2 flavors of Javascript doctest examples: ``js>`` examples for evaluating Javascript expressions in the browser. IMPORTANT NOTE This should only be used with expressions. Using with multiple statements is likely to produce errors or strange results. This works by simply taking the source provides, jamming a ``return`` on the front of it and calling the Webdriver ``execute_script`` method. ``js!`` examples for executing Javascript code in the browser without returning anything. This works find with blocks of code. The source given is passed to the Webdriver ``execute_script`` method. IMPORTANT NOTE Functions defined in the source using ``function`` statements aren't in the Javascript global scope. To define global functions, use something like:: global_name = function () {...} You can also execute Javascript code from Python examples using the Webdriver (``browser``) ``execute_script`` method. When invoking Javascript this way, be aware of the following oddities: - Functions defined via ``function`` statements can be used within the block of code, but aren't global. To define a global function, assign an anonymous function to a global variable. - No value is returned unless the block of code includes a return statement. - Includes the ``wait`` function ``from zope.testing.wait`` that waits for a condition. The function takes an additional argument (after the test argument), named ``app`` that provides a WSGI application object. ``start_server(app, port=0, daemon=True)`` A function that can be used to run the test server without running tests. Arguments: ``app`` A WSGI application object ``port`` The port to listen on. If 0, the default, then the port is allocated dynamically and returned. ``daemon`` The daemon mode. This can be ``True``, ``False``, or ``None``. If ``None``, then the server is run in the foreground and blocks the caller. If ``True`` or ``False``, the server is run in a thread, whose daemon mode is set to the value of this parameter. ``html(css=(), scripts=(), title="test", body="<body></body>")`` Return an HTML page with CSS links, script tags, and the given title and body tags. This is handy when you want a mostly empty HTML page that loads Javascript to be tested. ``css`` An iterable of CSS URLs. ``scripts`` An iterable of script definitions. Each definition is one of: - script URL - script tag (starting wth '<') - script Javascript source (containing at least one newline character) ``title`` The contents of the page title ``body`` The body of the document. ``manuels(optionflags=0, checker=None)`` Return a ``manuel`` parser for Python, Javascript and capture. ``TestSuite(*tests, **options)`` A function that takes one or more doctest/manuel file names and Test flags, such as ``setUp``, ``tearDown``, ``optionflags``, and ``checker``, and returns a doctest test suite. You can pass an ``app`` keyword argument, rather than passing ``setUp`` and ``tearDown``. See the example test included with the package. Changes ******* 0.1.0 (2013-08-31) ================== Initial release
zc.wsgidriver
/zc.wsgidriver-0.1.0.tar.gz/zc.wsgidriver-0.1.0/README.rst
README.rst
This is a somewhat silly sample test that goes with the somewhat silly test app. It gives a simple example of using the testing infrastructure:: >>> browser.get(server) >>> print browser.page_source # doctest: +ELLIPSIS <!DOCTYPE html>... <title>test title</title> <BLANKLINE> <link...href="/test.css"... <BLANKLINE> <BLANKLINE> <script type="text/javascript"> <BLANKLINE> wsgidriver_x = 1; <BLANKLINE> </script> <BLANKLINE> <script src="/test.js"></script> <script type="text/javascript"> wsgidriver_y = 2; </script> <BLANKLINE> </head><body>test content </body></html> js> [wsgidriver_x, wsgidriver_y, wsgidriver_z] [1, 2, 3] Use js! when you don't want to return a value. And when doing a block of JS code:: js! wsgidriver_f = function() { ... return 4; ... } Note that we defined a (global) variable here, rather than using a function statement. This is due to some selenium details. Now we can evaluate the function defined above:: js> wsgidriver_f() 4 We can also use ``browser.execute_script`` function to execute a block of Javascript code from Python:: wsgidriver_g = function() { return 5; } .. -> src With the above block in ``src``:: >>> browser.execute_script(src) js> wsgidriver_g() 5
zc.wsgidriver
/zc.wsgidriver-0.1.0.tar.gz/zc.wsgidriver-0.1.0/src/zc/wsgidriver/example.rst
example.rst
import bobo import boboserver import doctest import manuel.testing import manuel.capture import manuel.doctest import os import re import selenium.webdriver import socket import sys import threading import time import wsgiref.simple_server import zc.customdoctests.js import zope.testing.setupstack import zope.testing.wait here = os.path.dirname(__file__) remote_name = 'bobodriver' driver_factory = None basic_factories = dict( chrome = selenium.webdriver.Chrome, ie = selenium.webdriver.Ie, opera = selenium.webdriver.Opera, phantomjs = selenium.webdriver.PhantomJS, firefox = selenium.webdriver.Firefox, ) def remote(platform, browserName, version, executor): def factory(): return selenium.webdriver.Remote( desired_capabilities = dict( browserName=browserName, platform=platform, version=version, javascriptEnabled=True, name=remote_name, ), command_executor=executor, ) return factory def driver_factory_from_string(browser): global driver_factory driver_factory = basic_factories.get(browser) if driver_factory is None: browser = browser.split(',') browserName = browser.pop(0) version = '' platform = 'ANY' executor = None if browser: version = browser.pop(0) if browser: platform = browser.pop() if browser: [executor] = browser if not executor: executor = os.environ['SELENIUM_REMOTE_COMMAND_EXECUTOR'] driver_factory = remote( platform, browserName, version, executor) def get_factory_argument(argv=sys.argv, option='-b'): global driver_factory i = 1 while i < len(argv): if argv[i].startswith(option): browser = argv.pop(i)[len(option):] if not browser: browser = argv.pop(i) driver_factory_from_string(browser) break i += 1 def setUp(test, app): global driver_factory if driver_factory is None: browser = os.environ.get("SELENIUM_DRIVER") if browser: driver_factory_from_string(browser) else: driver_factory = selenium.webdriver.Chrome browser = driver_factory() zope.testing.setupstack.register(test, browser.quit) port = start_server(app) server = 'http://localhost:%s/' % port zope.testing.setupstack.register( test, lambda : browser.get(server + 'stop-testing-server')) test.globs.update( port = port, server = server, browser = browser ) test.globs['JS_'] = browser.execute_script def JS(src): return browser.execute_script('return '+src.strip()) test.globs['JS'] = JS test.globs['wait'] = zope.testing.wait.wait tearDown = zope.testing.setupstack.tearDown class RequestHandler(wsgiref.simple_server.WSGIRequestHandler): def log_request(self, *args): pass def start_server(app, port=0, daemon=True): def app_wrapper(environ, start_response): if environ.get('PATH_INFO') == '/stop-testing-server': thread = threading.Thread(target=server.shutdown) thread.setDaemon(True) thread.start() start_response( "200 OK", [('Content-Type', 'text/plain'), ('Content-Length', '0'), ]) return '' else: return app(environ, start_response) if port == 0: for port in range(8000, 9000): # We don't use ephemeral ports because windows clients, at # least in sauce labs, can't seem to use them, so we have # to do this the hard way. try: server = wsgiref.simple_server.make_server( '', port, app_wrapper, handler_class=RequestHandler) except socket.error: if port == 8999: raise # dang, ran out of ports else: break if daemon is None: import logging logging.basicConfig() server.serve_forever() else: thread = threading.Thread(target=server.serve_forever) thread.setDaemon(daemon) thread.start() return port def html(css=(), scripts=(), title="test", body="<body></body>"): return blank_html_template % dict( title=title, body=body, links = ''.join(link_template % link for link in css), scripts = ''.join( (script if script.startswith('<') else (script_template % script if '\n' in script else script_src_template % script) ) for script in scripts), ) blank_html_template = """ <!doctype html> <html><head> <title>%(title)s</title> %(links)s %(scripts)s </head>%(body)s</html> """ link_template = """ <link rel="stylesheet" type="text/css" href="%s" > """ script_src_template = """ <script src="%s" ></script> """ script_template = """ <script type="text/javascript"> %s </script> """ def manuels(optionflags=0, checker=None): return ( manuel.doctest.Manuel(parser=zc.customdoctests.js.parser, optionflags=optionflags) + manuel.doctest.Manuel(parser=zc.customdoctests.js.eq_parser, optionflags=optionflags) + manuel.doctest.Manuel(optionflags=optionflags, checker=checker) + manuel.capture.Manuel() ) def _manuels(optionflags=0, checker=None, **kw): return manuels(optionflags, checker), kw def TestSuite(*test_names, **kw): manuels, kw = _manuels(**kw) if 'app' in kw: if 'setUp' in kw or 'tearDown' in kw: raise TypeError("Can't pass setUp or tearDown if you pass app") app = kw.pop('app') kw['setUp'] = lambda test: setUp(test, app) kw['tearDown'] = tearDown base = os.path.dirname(sys._getframe(1).f_globals['__file__']) return manuel.testing.TestSuite( manuels, *[os.path.join(base, name) for name in test_names], **kw)
zc.wsgidriver
/zc.wsgidriver-0.1.0.tar.gz/zc.wsgidriver-0.1.0/src/zc/wsgidriver/__init__.py
__init__.py
Run WSGI applications defined by paste.deploy configurations ************************************************************ .. contents:: A script, ``run-wsgi`` is provided that runs WSGI applications defined in `Paste Deployment <http://pythonpaste.org/deploy/>`_ configuration files. For example, given a configuration file, ``paste.ini``:: [app:main] use = egg:bobo bobo_resources = myapp [pipeline:debug] pipeline = debug reload main [filter:reload] use = egg:bobo#reload modules = zc.wsgirunner.tests [filter:debug] use = egg:bobo#debug [server:main] use = egg:waitress host = localhost port = 8080 [configure:main] use = call:myapp:config key = 42 [logging:main] log = INFO We can run the applicaton with:: run-wsgi paste.ini If we want to run the debug pipeline:: run-wsgi -a debug paste.ini Logging and configuration ========================= ``zc.wsgirunner`` extends the Paste Deploy vocabulary of sections with ``logging`` and ``configuration`` sections. As with the other sections, you can have multiple sections and select which one you want with command-line options. Logging sections ---------------- Logging sections come in 2 flavors, ZConfig, and basic. If a logging section has a ``config`` option, its value is passed `ZConfig's <https://pypi.python.org/pypi/ZConfig>`_ [#zconfig]_ ``configureLoggers`` method. Otherwise, the options in the logging section are passed to ``logging.basicConfig``. Configuration sections ---------------------- Configuration sections identify a configuration function with a ``use`` option, as with other Paste Deploy sections. The configuration object is called with global defaults and with options from the configuration section. Changes ******* 0.1.0 (2014-04-12) ================== Initial release .. [#zconfig] ZConfig provides the easiest way to create non-trivial logger configurations. Note, however, that ZConfig isn't a dependency of ``zc.wsgirunner``, so if you want to use ZConfig to configure logging, you need to install it separately.
zc.wsgirunner
/zc.wsgirunner-0.1.0.tar.gz/zc.wsgirunner-0.1.0/README.rst
README.rst
import argparse import paste.deploy try: import configparser except ImportError: import ConfigParser as configparser import os import sys parser = argparse.ArgumentParser(description='Run WSGI applications') parser.add_argument( 'config', metavar="CONFIG", help="Paste deploy configuratopm") parser.add_argument( '--application', '-a', default='main', help='application name in the configuration file') parser.add_argument( '--server', '-s', default='main', help='server name in the configuration file') parser.add_argument( '--configuration', '-c', default='main', help='configuration name in the configuration file') parser.add_argument( '--logging', '-l', default='main', help='logging configuration name in the configuration file') def main(args=None): if args is None: args = sys.argv[1:] args = parser.parse_args(args) config = os.path.abspath(args.config) cp = configparser.RawConfigParser() cp.read(config) def items(section): if cp.has_section(section): return dict( (k, v) for (k, v) in cp.items(section) if k not in cp.defaults() ) log = items('logging:'+args.logging) if log: if 'config' in log: import ZConfig ZConfig.configureLoggers(log['config']) else: import logging if 'level' in log: log['level'] = logging.getLevelName(log['level']) logging.basicConfig(**log) configuration = items('configuration:' + args.configuration) if configuration: use = configuration.pop('use') if use.startswith('egg:'): use = use[4:].split('#', 1) if len(use) == 2: use, rname = use else: use = use[0] rname = 'default' import pkg_resources use = pkg_resources.load_entry_point(use, 'configuration', rname) elif use.startswith('call:'): use, expr = use[5:].split(':', 1) mod = __import__(use, {}, {}, ['*']) use = eval(expr, mod.__dict__) else: raise ValueError(use) use(cp.defaults(), **configuration) app = paste.deploy.loadapp('config:'+config, args.application) server = paste.deploy.loadserver('config:'+config, args.server) sys.setcheckinterval(1000) server(app)
zc.wsgirunner
/zc.wsgirunner-0.1.0.tar.gz/zc.wsgirunner-0.1.0/src/zc/wsgirunner/__init__.py
__init__.py
**************** ZC WSGI Sessions **************** This is an implementation of persistent sessions as a WSGI middleware using `zope.session` as an underlying mechanism. To use it: 1. Add `zc.wsgisessions` to `install_requires` list in `setup.py` of your application (e.g., `myapp`) 2. Add the following to `myapp.ini`:: [filter:sessions] use = egg:zc.wsgisessions You can add to configuration:: secure = true or:: http-only = off Valid words are: `true`, `false`, `on`, `off`, `yes`, `no`, 1, and 0. You can also specify a database name for session storage:: db-name = appdb 3. Add `sessions` to the pipeline *after* database middleware, but *before* the application. 4. Add to a function that is listed as `initializer` for the database middleware:: zc.wsgisessions.sessions.initialize_database(database) You can also pass keyword arguments for: `db_name`, `namespace`, `secret`, `timeout`, and `resolution`. 5. Add to a function that is listed as `bobo.configure` (initializer of your WSGI application):: zope.component.provideAdapter(zc.wsgisessions.sessions.get_session) 6. You can use some helpers in your authentication code:: PKG_KEY = __name__ # e.g., myapp.auth def get_user(request): return zc.wsgisessions.sessions.get(request, PKG_KEY, 'user') def save_user(request, user): zc.wsgisession.sessions.store(request, PKG_KEY, 'user', user) def forget_user(request): return zc.wsgisessions.sessions.remove(request, PKG_KEY, 'user') 7. When running `Selenium` tests, `HttpOnly` cookies cannot be used. Set the option ``'http-only': False`` in the `global_conf` dictionary of your testing application. .. See ``src/zc/wsgisessions/sessions.txt`` for details.
zc.wsgisessions
/zc.wsgisessions-0.5.1.tar.gz/zc.wsgisessions-0.5.1/README.txt
README.txt
__docformat__ = 'reStructuredText' import binascii import hashlib import hmac import os import string import time import transaction import webob import zope.component import zope.interface import zope.session.interfaces import zope.session.session from zc.wsgisessions.utils import boolean def store(request, pkg_id, key, value): session = zope.session.interfaces.ISession(request)[pkg_id] session[key] = value def get(request, pkg_id, key=None): adapter = zope.session.interfaces.ISession(request) if key is None: return adapter[pkg_id] return adapter.get(pkg_id, {}).get(key) def remove(request, pkg_id, key): adapter = zope.session.interfaces.ISession(request) return adapter.get(pkg_id, {}).pop(key, None) def rand(n=20): return binascii.hexlify(os.urandom(n)) class Session(zope.session.session.Session): def __init__(self, client_id, sdc): self.client_id = client_id self._data_container = sdc def _sdc(self, pkg_id): return self._data_container def __iter__(self): raise NotImplementedError class BrowserIdFilter(object): db_name = 'sessions' http_only = True secure = False def __new__(cls, global_conf, **kw): def create(app): self = object.__new__(cls) self.app = app # db-name is passed in kw from a setting in .ini file self.db_name = kw.get('db-name', self.db_name) for setting in ('http-only', 'secure'): attr = setting.replace('-', '_') if setting in kw: setattr(self, attr, boolean(kw[setting])) # for selenium testing set http_only in global_conf if setting in global_conf: setattr(self, attr, boolean(global_conf[setting])) return self return create def __call__(self, environ, start_response): start_response = self.prepare(environ, start_response) return self.app(environ, start_response) def prepare(self, environ, start_response): # Look in the db for the cookie name and the secret: conn = environ['zodb.connection'].get_connection(self.db_name) root = conn.root() namespace, secret = root['browserid_info'] added_headers = [] sid = webob.Request(environ).cookies.get(namespace) if sid is not None: sid = self.verify(secret, sid) if sid is None: sid = self.generate(secret) cookie = '%s=%s; path=/' % (namespace, sid) if self.http_only: cookie += '; HttpOnly' if self.secure or environ['wsgi.url_scheme'] == 'https': cookie += '; secure' # XXX need to set expiration added_headers = [('Set-Cookie', cookie)] original_start_response = start_response def my_start_response(status, headers, exc_info=None): return original_start_response( status, list(headers) + added_headers, exc_info) start_response = my_start_response environ['zc.wsgisessions.browserid'] = sid environ['zc.wsgisessions.session'] = Session(sid, root['sessions']) return start_response def generate(self, secret): data = '%s%.20f%.20f' % (rand(), time.time(), time.clock()) digest = hashlib.sha1(data).digest() s = digestEncode(digest) # we store an HMAC of the random value together with it, which makes # our session ids unforgeable. mac = hmac.new(secret, s, digestmod=hashlib.sha1).digest() return s + digestEncode(mac) def verify(self, secret, sid): if (not sid) or len(sid) != 54: return None s, mac = sid[:27], sid[27:] if (digestEncode(hmac.new( secret, s.encode(), digestmod=hashlib.sha1 ).digest()) != mac): return None else: return sid cookieSafeTrans = string.maketrans('+/', '-.') def digestEncode(s): """Encode SHA digest for cookie.""" return s.encode('base64')[:-2].translate(cookieSafeTrans) def initialize_database(database, *args, **kw): conn = database.open() db_name = kw.get('db_name', BrowserIdFilter.db_name) root = conn.get_connection(db_name).root() if 'browserid_info' not in root: if 'namespace' in kw: namespace = kw['namespace'] else: namespace = 'browserid_%x' % (int(time.time()) - 1000000000) if 'secret' in kw: secret = kw['secret'] else: secret = rand() root['browserid_info'] = (namespace, secret) if 'sessions' not in root: sdc = zope.session.session.PersistentSessionDataContainer() if 'timeout' in kw: sdc.timeout = kw['timeout'] else: sdc.timeout = 24 * 60 * 60 # 1 day if 'resolution' in kw: sdc.resolution = kw['resolution'] else: sdc.resolution = 1 * 60 * 60 # 1 hour root['sessions'] = sdc transaction.commit() conn.close() @zope.interface.implementer(zope.session.interfaces.ISession) @zope.component.adapter(webob.Request) def get_session(request): return request.environ['zc.wsgisessions.session']
zc.wsgisessions
/zc.wsgisessions-0.5.1.tar.gz/zc.wsgisessions-0.5.1/src/zc/wsgisessions/sessions.py
sessions.py
============== Known Good Set ============== This is a known good set of packages used by Zope Corporation applications. The file ``versions.cfg`` contains a complete list. It extends the known good set of ZTK (Zope Toolkit) packages. It uses tagged releases of ZTK version files. Applications can extend this file in their ``versions.cfg`` to add or override the packages. Applications ============ The following applications use (some version of) this KGS:: CCCP Checkout (SCO) PCI Admin ZAAM Dashboard Zope Ads zc.openidprovider zc.rsainputfilter zridp Packages ======== The following packages use (some version of) this KGS:: zc.dojoform zc.wsgisessions zc.zaam
zc.wsgisessions
/zc.wsgisessions-0.5.1.tar.gz/zc.wsgisessions-0.5.1/zc.kgs/README.txt
README.txt
.. This document contains release-specific information about the Zope Toolkit. It is intended for automatic inclusion by the ZTK sphinx-based documentation. Introduction ------------ The Zope Toolkit 1.0 release is the first release of the Zope Toolkit. The Zope Toolkit really is just a collection of libraries managed together by the Zope developers. We typically treat each library independently, so you would like to look at the CHANGES.txt in each library for updates. Here we note larger changes, especially ones that affect multiple libraries. Installation ------------ The Zope Toolkit cannot be installed directly except as individual libraries (such as ``zope.component``). To install it you typically would install a framework or application that makes use of these libraries. Examples of such projects are BlueBream, Grok and Zope 2. If you want to use the Zope Toolkit KGS, you can use the buildout extends mechanism (replace 1.0 by the desired version):: [buildout] extends = http://download.zope.org/zopetoolkit/index/1.0/ztk-versions.cfg You can also copy the file locally or additionally extend the zopeapp-versions.cfg file from the same location. Frameworks and applications have their own set of install instructions. You should follow these in most cases. Python versions --------------- The ZTK 1.0 release series supports Python 2.4 up to Python 2.6. Neither Python 2.7 nor any Python 3.x series is supported. News ---- The 1.0 release of the Zope Toolkit contains a number of refactorings that are aimed to clean up dependencies between pieces of code. Many packages in ``zope.app`` have had their code moved to existing or newly created packages in the ``zope`` namespace. These new packages do generally not contain user interface code (typically what's in ``.browser``), and have much clearer dependency relationships as a result. Backwards compatibility imports have been left in place so that your existing code should still work. In some cases you will have to explicitly add dependencies to a ``zope.app.`` to your code, as due to the cleanup they might not come in automatically anymore due to indirect dependencies; if you see an import error this is probably the case. We recommend you update your existing code to import from the new packages if possible. The transition support and ``zope.app.*`` support is limited: the legacy support will be officially retired from the ZTK in subsequent releases. Migration issues ---------------- zope.app.keyreference -> zope.keyreference ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This package was renamed to ``zope.keyreference`` and all its functionality was moved to the new one. The new package contains a little workaround for making old persistent keyreferences loadable without ``zope.app.keyreference`` installed, so the latter one is not needed at all anymore. Still review your code for any imports coming from ``zope.app.keyreference`` and modify it to use ``zope.keyreference`` instead. zope.app.intid -> zope.intid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The non-UI functionality of these packages was moved to ``zope.intid`` with backwards compatibility imports left in place. Review your imports from ``zope.app.intid`` to see whether they cannot come directly from ``zope.intid`` instead. zope.app.catalog -> zope.catalog ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The non-UI functionality of these packages was moved to ``zope.catalog``. Review your imports from ``zope.app.catalog`` to see whether they cannot come directly from ``zope.catalog`` instead. zope.app.container -> zope.container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The non-UI functionality of these packages was moved to ``zope.container``. Review your imports from ``zope.app.container`` to see whether they cannot come directly from ``zope.container`` instead. In addition, the exceptions used by ``zope.container`` were changed, so if your code catches them, you need to review it: * The ``DuplicationError`` in ``setitem`` was changed to ``KeyError``. * The ``UserError`` in ``NameChooser`` was changed to ``ValueError``. zope.app.component -> zope.security, zope.site ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The implementation of the ``<class>`` ZCML directive moved from this package to ``zope.security``. Packages that relied on ``zope.app.component`` to obtain this directive should declare a direct dependency on ``zope.security``, and it may be possible to lose the dependency on ``zope.app.component`` altogether. Non-UI site related functionality has been moved to the ``zope.site`` package. with backwards compatibility imports left in place. Review your imports from ``zope.app.component`` to see whether they cannot come directly from ``zope.site`` instead. zope.app.folder -> zope.site, zope.container ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The implementation of the ``zope.app.folder.Folder`` class has moved to ``zope.site.folder`` instead, with backwards compatibility imports left in place. Review your imports from ``zope.app.folder`` to see whether they cannot come directly from ``zope.site`` instead. In addition, ``Folder`` is an ``IContainer`` implementation that also mixes in site management functionality. If such site management support is not necessary, in some cases your code does not need ``Folder`` but may be able to rely on a ``Container`` implementation from ``zope.container`` instead. A base class with the implementation of the container-like behavior of ``Folder`` has moved to ``zope.container`` (and ``zope.site`` uses this for its implementation of ``Folder``). This is not normally something you should need to retain backwards compatibility. zc.copy -> zope.copy, zope.copypastemove, zope.location ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The pluggable object copying mechanism once developed in the ``zc.copy`` package was merged back into ``zope.location``, ``zope.copypastemove`` and the new ``zope.copy`` package. The ``zope.copy`` package now provides a pluggable mechanism for copying objects from ``zc.copy`` and doesn't depend on anything but ``zope.interface``. The ``zope.copypastemove`` uses the ``copy`` function from ``zope.copy`` in its ``ObjectCopier``. The ``zope.location`` now provides an ``ICopyHook`` adapter that implements conditional copy functionality based on object locations, that old ``zope.location.pickling.CopyPersistent`` used to provide. Note, that if you don't use ZCML configuration of ``zope.location``, you may need to register ``zope.location.pickling.LocationCopyHook`` yourself. The ``zope.location.pickling.locationCopy`` and ``zope.location.pickling.CopyPersistent`` are now deprecated in favor of ``zope.copy`` and were replaced by backward-compatibility imports. See ``zope.copy`` package documentation for information on how to use the new mechanism. The new version of the ``zc.copy`` package now only contains backward-compatibility imports and is deprecated. ``zope.copy`` should be preferred for new developments. zope.app.security refactoring ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``zope.app.security`` package was finally refactored into a few small parts with less dependencies and more clear purpose. The implementation of the ``<module>`` ZCML directive moved from this package to ``zope.security``. Packages that relied on ``zope.app.security`` to obtain this directive should declare a direct dependency on ``zope.security``, and it may be possible to lose the dependency on ``zope.app.security`` altogether. The ``protectclass`` module in this package has moved to ``zope.security``, with backwards compatibility imports left in place. Review your imports from ``zope.app.security`` to see whether they cannot come directly from ``zope.security`` instead. All interfaces (`IAuthentication`, `IUnauthenticatedPrincipal`, `ILoginPassword` and so on.) were moved into a new ``zope.authentication`` package, as well as several utility things, like `PrincipalSource` and `checkPrincipal` function. The new package has much less dependencies and defines an abstract contract for implementing authentication policies. While backward compatibility imports are left in place, it's strongly recommended to update your imports to the ``zope.authentication``. The `global principal registry` and its ZCML directives are moved into a new ``zope.principalregistry`` package with backward-compatibility imports left in place. If your application uses global principals, review your code and ZCML configuration to update it to the new place. The `local permission` functionality was moved into a new ``zope.app.localpermission`` package. This functionality is a part of Through-The-Web development pattern that seems not to be used and supported much by Zope Toolkit and Application anymore, so it can be considered deprecated. However, it can serve as a great example of TTW-related component. The `Permission vocabularies` and standard protections for Message objects and `__name__`, `__parent__` attributes as well as some common permissions, like `zope.View` and `zope.ManageContent` were merged into `zope.security`. The adapters from ``zope.publisher``'s `IHTTPCredentials` and `IFTPCredentials` to the `ILoginPassword` were moved into ``zope.publisher``, thus making ``zope.authentication`` a dependency for ``zope.publisher``. The original ``zope.app.security`` package now only contains several deprecated or application-specific permission definitions, python module protections, that are only likely to be needed with deprecated Through-The-Web development pattern, and ZMI-related browser views (login.html, zope.app.form view for PrincipalSource and so on), as well as backward-compatibility imports. So, if you're not using TTW and/or standard ZMI browser views, you probably should review update your imports to a new places and drop dependency on ``zope.app.security`` to reduce package dependencies count. Other packages, that used ``zope.app.security``, like ``zope.securitypolicy`` are either already adapted to the changes or will be adapted soon. zope.app.publisher refactoring ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``zope.app.publisher`` package was also refactored into smaller parts with less dependencies and clearer purpose. The browser resources mechanism (mostly used for serving static files and directories) was factored out to the new ``zope.browserresource`` package. It was also made more pluggable, so you can register specific resource classes for some file extensions, if you need special processing. One of the example is the new ``zope.ptresource`` package, where the PageTemplateResource was moved, another example is ``z3c.zrtresource`` package that was adapted to automatically use ZRT resource class for files with ``.zrt`` extensions. Browser menu mechanism was moved into a new ``zope.browsermenu`` package with no further changes. ZCML directives for easy creation of browser views (the ``browser:page`` directive and friends) was moved into a new small package, ``zope.browserpage``. Also, the directives don't depend the menu mechanism now and will simply ignore "menu" and "title" arguments if ``zope.browsermenu`` package is not installed. The ``IModifiableBrowserLanguages`` adapter was moved into ``zope.publisher`` along with several ZCML security declarations for ``zope.publisher`` classes that used to be in ``zope.app.publisher``. ZCML registrations for ``IXMLRPCPublisher`` adapter for containers was moved into the ``zope.container``, because the actual adapters code were already in ``zope.container`` and registered there as ``IBrowserPublisher`` adapters. However, both adapters and their ZCML registrations will probably move elsewhere when we'll be refactoring ``zope.container``. Several parts are left in ``zope.app.publisher`` untouched: * ``Browser Skins`` vocabulary. * ``date`` field converter for ``zope.publisher``'s form values conversion mechanism. * ``ManagementViewSelector`` browser view (ZMI-related part). * ``xmlrpc:view`` directive for publishing XML-RPC methods. The latter, ``xmlrpc:view`` directive is generally useful, so it may be moved into a separate package in future, however there are no clear decision about how to move XML-RPC and FTP-related things currently. Password managers extracted from zope.app.authentication ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The `IPasswordManager` interface and its implementations were extracted from ``zope.app.authentication`` into a new ``zope.password`` package to make them usable with other authentication systems, like ``z3c.authenticator`` or ``zope.principalregistry`` or any custom one. It basically depends only on ``zope.interface``, so it can be really useful even in non-Zope environments, like ``Pylons``, for example. The `Password Manager Names` vocabulary is also moved into ``zope.password``, however, it's only useful with ``zope.schema`` and ``zope.component``, so you need them installed to work with them. They're listed in the "vocabulary" extra requirement specification. ZODB 3.9 FileStorage native blob support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The FileStorage component of ZODB 3.9 used in Zope Toolkit 1.0 now supports blobs natively, so you don't need to use BlobStorage proxy for it anymore. Thus, you can specify blob directory directly to FileStorage. If you use ZConfig, that means something like this:: <filestorage> path var/Data.fs blob-dir var/blobs </filestorage> instead of:: <blobstorage> blob-dir var/blobs <filestorage> path var/Data.fs </filestorage> </blobstorage> If you creating a storage from python, that means something like this: .. code-block:: python storage = FileStorage('var/Data.fs', blob_dir='var/blobs') instead of: .. code-block:: python storage = BlobStorage('var/blobs', FileStorage('var/Data.fs')) zope.dublincore permission renaming ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``zope.app.dublincore.*`` permissions have been renamed to ``zope.dublincore.*``. Applications using these permissions have to fix up grants based on the old permissions.
zc.wsgisessions
/zc.wsgisessions-0.5.1.tar.gz/zc.wsgisessions-0.5.1/zc.kgs/ztk/index.rst
index.rst
================ The Zope Toolkit ================ The Zope Toolkit is a set of libraries maintained by the Zope project for building web applications, web frameworks and application servers. This directory contains the definition of the Zope Toolkit in the file ``ztk.cfg``. It specifies the list of packages included in the ZTK and packages which are under review for inclusion. Also, specific versions have been tested together (including their dependencies) and can directly be used with a buildout by specifying the ``ztk-versions.cfg`` file via the ``extends`` mechanism. To test the ZTK, run ``bin/test-ztk``. To generate dependency graphs for the ZTK, run ``bin/depgraph``. The resulting SVN graphs will be in ``parts/depgraph``. For details about the ZTK, please see http://docs.zope.org/zopetoolkit. Transition support ------------------ For a limited period of time, we maintain a second set of versions in the ``zopeapp.cfg`` set. This transition support should help existing applications to move to the Zope Toolkit. You can extend from the ``zopeapp-versions.cfg`` via the buildout extends mechanism. To test the Zope App set, run ``bin/test-zopeapp``. For more details read the ZTK 1.0 release notes.
zc.wsgisessions
/zc.wsgisessions-0.5.1.tar.gz/zc.wsgisessions-0.5.1/zc.kgs/ztk/README.txt
README.txt
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser( 'This is a custom version of the zc.buildout %prog script. It is ' 'intended to meet a temporary need if you encounter problems with ' 'the zc.buildout 1.5 release.') parser.add_option("-v", "--version", dest="version", default='1.4.4', help='Use a specific zc.buildout version. *This ' 'bootstrap script defaults to ' '1.4.4, unlike usual buildpout bootstrap scripts.*') parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' env = dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(tmpeggs)] if 'bootstrap-testing-find-links' in os.environ: cmd.extend(['-f', os.environ['bootstrap-testing-find-links']]) cmd.append('zc.buildout' + VERSION) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) assert exitcode == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zc.wsgisessions
/zc.wsgisessions-0.5.1.tar.gz/zc.wsgisessions-0.5.1/zc.kgs/ztk/bootstrap.py
bootstrap.py
===================== Zope 3 Monitor Server ===================== The Zope 3 monitor server is a server that runs in a Zope 3 process and that provides a command-line interface to request various bits of information. It is based on zc.monitor, which is itself based on zc.ngi, so we can use the zc.ngi testing infrastructure to demonstrate it. This package provides several Zope 3 and ZODB monitoring and introspection tools that work within the zc.monitor server. These are demonstrated below. Please see the zc.monitor documentation for details on how the server works. This package also supports starting a monitor using ZConfig, and provides a default configure.zcml for registering plugins. The ZConfig setup is not demonstrated in this documentation, but the usage is simple. In your ZConfig file, provide a "product-config" stanza for zc.z3monitor that specifies the port on which the zc.monitor server should listen. For instance, this stanza will start a monitor server on port 8888:: <product-config zc.z3monitor> bind 8888 </product-config> To bind to a specific address:: <product-config zc.z3monitor> bind 127.0.0.1:8888 </product-config> To bind to a unix domain socket:: <product-config zc.z3monitor> bind /var/socket </product-config> To include the default commands of zc.monitor and zc.z3monitor, simply include the configure.zcml from this package:: <include package="zc.z3monitor" /> Now let's look at the commands that this package provides. We'll get a test connection to the monitor server and register the plugins that zc.monitor and zc.z3monitor provide. >>> import zc.ngi.testing >>> import zc.monitor >>> import zc.monitor.interfaces >>> import zc.z3monitor >>> import zc.z3monitor.interfaces >>> import zope.component >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> zope.component.provideUtility(zc.monitor.help, ... zc.monitor.interfaces.IMonitorPlugin, 'help') >>> zope.component.provideUtility(zc.monitor.interactive, ... zc.monitor.interfaces.IMonitorPlugin, 'interactive') >>> zope.component.provideUtility(zc.monitor.quit, ... zc.monitor.interfaces.IMonitorPlugin, 'quit') >>> zope.component.provideUtility(zc.z3monitor.monitor, ... zc.z3monitor.interfaces.IZ3MonitorPlugin, 'monitor') >>> zope.component.provideUtility(zc.z3monitor.dbinfo, ... zc.z3monitor.interfaces.IZ3MonitorPlugin, 'dbinfo') >>> zope.component.provideUtility(zc.z3monitor.zeocache, ... zc.z3monitor.interfaces.IZ3MonitorPlugin, 'zeocache') >>> zope.component.provideUtility(zc.z3monitor.zeostatus, ... zc.z3monitor.interfaces.IZ3MonitorPlugin, 'zeostatus') We'll use the zc.monitor ``help`` command to see the list of available commands: >>> connection.test_input('help\n') Supported commands: dbinfo -- Get database statistics help -- Get help about server commands interactive -- Turn on monitor's interactive mode monitor -- Get general process info quit -- Quit the monitor zeocache -- Get ZEO client cache statistics zeostatus -- Get ZEO client status information -> CLOSE The commands that come with the zc.z3monitor package use database information. They access databases as utilities. Let's create some test databases and register them as utilities. >>> from ZODB.tests.util import DB >>> main = DB() >>> from zope import component >>> import ZODB.interfaces >>> component.provideUtility(main, ZODB.interfaces.IDatabase) >>> other = DB() >>> component.provideUtility(other, ZODB.interfaces.IDatabase, 'other') We also need to enable activity monitoring in the databases: >>> import ZODB.ActivityMonitor >>> main.setActivityMonitor(ZODB.ActivityMonitor.ActivityMonitor()) >>> other.setActivityMonitor(ZODB.ActivityMonitor.ActivityMonitor()) Process Information =================== To get information about the process overall, use the monitor command: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('help monitor\n') Help for monitor: <BLANKLINE> Get general process info <BLANKLINE> The minimal output has: <BLANKLINE> - The number of open database connections to the main database, which is the database registered without a name. - The virtual memory size, and - The resident memory size. <BLANKLINE> If there are old database connections, they will be listed. By default, connections are considered old if they are greater than 100 seconds old. You can pass a minimum old connection age in seconds. If you pass a value of 0, you'll see all connections. <BLANKLINE> If you pass a name after the integer, this is used as the database name. The database name defaults to the empty string (''). <BLANKLINE> -> CLOSE >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('monitor\n') #doctest: +NORMALIZE_WHITESPACE 0 VmSize: 35284 kB VmRSS: 28764 kB -> CLOSE >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('monitor 100 other\n') #doctest: +NORMALIZE_WHITESPACE 0 VmSize: 35284 kB VmRSS: 28764 kB -> CLOSE Note that, as of this writing, the VmSize and VmRSS lines will only be present on a system with procfs. This generally includes many varieties of Linux, and excludes OS X and Windows. Let's create a couple of connections and then call z3monitor again with a value of 0: >>> conn1 = main.open() >>> conn2 = main.open() >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('monitor 0\n') #doctest: +NORMALIZE_WHITESPACE 2 VmSize: 36560 kB VmRSS: 28704 kB 0.0 (0) 0.0 (0) -> CLOSE The extra line of output gives connection debug info. If we set some additional input, we'll see it: >>> conn1.setDebugInfo('/foo') >>> conn2.setDebugInfo('/bar') >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('monitor 0\n') #doctest: +NORMALIZE_WHITESPACE 2 VmSize: 13048 kB VmRSS: 10084 kB 0.0 /bar (0) 0.0 /foo (0) -> CLOSE >>> conn1.close() >>> conn2.close() Database Information ==================== To get information about a database, use the dbinfo command: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('help dbinfo\n') Help for dbinfo: <BLANKLINE> Get database statistics <BLANKLINE> By default statistics are returned for the main database. The statistics are returned as a single line consisting of the: <BLANKLINE> - number of database loads <BLANKLINE> - number of database stores <BLANKLINE> - number of connections in the last five minutes <BLANKLINE> - number of objects in the object caches (combined) <BLANKLINE> - number of non-ghost objects in the object caches (combined) <BLANKLINE> You can pass a database name, where "-" is an alias for the main database. <BLANKLINE> By default, the statistics are for a sampling interval of 5 minutes. You can request another sampling interval, up to an hour, by passing a sampling interval in seconds after the database name. <BLANKLINE> -> CLOSE >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('dbinfo\n') #doctest: +NORMALIZE_WHITESPACE 0 0 2 0 0 -> CLOSE Let's open a connection and do some work: >>> conn = main.open() >>> conn.root()['a'] = 1 >>> import transaction >>> transaction.commit() >>> conn.root()['a'] = 1 >>> transaction.commit() >>> conn.close() >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('dbinfo\n') #doctest: +NORMALIZE_WHITESPACE 1 2 3 1 1 -> CLOSE You can specify a database name. So, to get statistics for the other database, we'll specify the name it was registered with: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('dbinfo other\n') #doctest: +NORMALIZE_WHITESPACE 0 0 0 0 0 -> CLOSE You can use '-' to name the main database: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('dbinfo -\n') #doctest: +NORMALIZE_WHITESPACE 1 2 3 1 1 -> CLOSE You can specify a number of seconds to sample. For example, to get data for the last 10 seconds: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('dbinfo - 10\n') #doctest: +NORMALIZE_WHITESPACE 1 2 3 1 1 -> CLOSE .. Edge case to make sure that ``deltat`` is used: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('dbinfo - 0\n') #doctest: +NORMALIZE_WHITESPACE 0 0 0 1 1 -> CLOSE ZEO Cache Statistics ==================== You can get ZEO cache statistics using the zeocache command. >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('help zeocache\n') Help for zeocache: <BLANKLINE> Get ZEO client cache statistics <BLANKLINE> The command returns data in a single line: <BLANKLINE> - the number of records added to the cache, <BLANKLINE> - the number of bytes added to the cache, <BLANKLINE> - the number of records evicted from the cache, <BLANKLINE> - the number of bytes evicted from the cache, <BLANKLINE> - the number of cache accesses. <BLANKLINE> By default, data for the main database are returned. To return information for another database, pass the database name. <BLANKLINE> -> CLOSE >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('zeocache\n') #doctest: +NORMALIZE_WHITESPACE 42 4200 23 2300 1000 -> CLOSE You can specify a database name: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('zeocache other\n') #doctest: +NORMALIZE_WHITESPACE 42 4200 23 2300 1000 -> CLOSE ZEO Connection Status ===================== The zeostatus command lets you get information about ZEO connection status: >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('help zeostatus\n') Help for zeostatus: <BLANKLINE> Get ZEO client status information <BLANKLINE> The command returns True if the client is connected and False otherwise. <BLANKLINE> By default, data for the main database are returned. To return information for another database, pass the database name. <BLANKLINE> -> CLOSE >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('zeostatus\n') #doctest: +NORMALIZE_WHITESPACE True -> CLOSE >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('zeostatus other\n') #doctest: +NORMALIZE_WHITESPACE True -> CLOSE In this example, we're using a faux ZEO connection. It has an attribute that determines whether it is connected or not. Id we change it, then the zeocache output will change: >>> main._storage._is_connected = False >>> connection = zc.ngi.testing.TextConnection() >>> server = zc.monitor.Server(connection) >>> connection.test_input('zeostatus\n') #doctest: +NORMALIZE_WHITESPACE False -> CLOSE
zc.z3monitor
/zc.z3monitor-0.8.0.tar.gz/zc.z3monitor-0.8.0/src/zc/z3monitor/README.txt
README.txt
import os, re, time import ZODB.ActivityMonitor import ZODB.interfaces import zc.monitor import zope.component import zope.interface import zope.publisher.browser import zope.publisher.interfaces.browser import zope.security.proxy import zope.traversing.interfaces import zope.app.appsetup.interfaces import zope.app.appsetup.product import zope.app.publication.interfaces opened_time_search = re.compile('[(](\d+[.]\d*)s[)]').search def monitor(connection, long=100, database=''): # this order of arguments is often inconvenient, but supports legacy usage # in which ``database`` was not an option. """Get general process info The minimal output has: - The number of open database connections to the main database, which is the database registered without a name. - The virtual memory size, and - The resident memory size. If there are old database connections, they will be listed. By default, connections are considered old if they are greater than 100 seconds old. You can pass a minimum old connection age in seconds. If you pass a value of 0, you'll see all connections. If you pass a name after the integer, this is used as the database name. The database name defaults to the empty string (''). """ min = float(long) db = zope.component.getUtility(ZODB.interfaces.IDatabase, database) result = [] nconnections = 0 for data in db.connectionDebugInfo(): opened = data['opened'] if not opened: continue nconnections += 1 match = opened_time_search(opened) # XXX the code originally didn't make sure a there was really a # match; which caused exceptions in some (unknown) circumstances # that we weren't able to reproduce; this hack keeps that from # happening if not match: continue age = float(match.group(1)) if age < min: continue result.append((age, data['info'])) result.sort() print >>connection, str(nconnections) for status in getStatus(): print >>connection, status for age, info in result: print >>connection, age, info.encode('utf-8') def dbinfo(connection, database='', deltat=300): """Get database statistics By default statistics are returned for the main database. The statistics are returned as a single line consisting of the: - number of database loads - number of database stores - number of connections in the last five minutes - number of objects in the object caches (combined) - number of non-ghost objects in the object caches (combined) You can pass a database name, where "-" is an alias for the main database. By default, the statistics are for a sampling interval of 5 minutes. You can request another sampling interval, up to an hour, by passing a sampling interval in seconds after the database name. """ if database == '-': database = '' db = zope.component.getUtility(ZODB.interfaces.IDatabase, database) am = db.getActivityMonitor() if am is None: data = -1, -1, -1 else: now = time.time() analysis = am.getActivityAnalysis(now-int(deltat), now, 1)[0] data = (analysis['loads'], analysis['stores'], analysis['connections'], ) ng = s = 0 for detail in db.cacheDetailSize(): ng += detail['ngsize'] s += detail['size'] print >> connection, data[0], data[1], data[2], s, ng def zeocache(connection, database=''): """Get ZEO client cache statistics The command returns data in a single line: - the number of records added to the cache, - the number of bytes added to the cache, - the number of records evicted from the cache, - the number of bytes evicted from the cache, - the number of cache accesses. By default, data for the main database are returned. To return information for another database, pass the database name. """ db = zope.component.getUtility(ZODB.interfaces.IDatabase, database) print >> connection, ' '.join(map(str, db._storage._cache.fc.getStats())) def zeostatus(connection, database=''): """Get ZEO client status information The command returns True if the client is connected and False otherwise. By default, data for the main database are returned. To return information for another database, pass the database name. """ db = zope.component.getUtility(ZODB.interfaces.IDatabase, database) print >> connection, db._storage.is_connected() @zope.component.adapter(zope.app.appsetup.interfaces.IDatabaseOpenedEvent) def initialize(opened_event): config = zope.app.appsetup.product.getProductConfiguration(__name__) if config is None: return for name, db in zope.component.getUtilitiesFor(ZODB.interfaces.IDatabase): if db.getActivityMonitor() is None: db.setActivityMonitor(ZODB.ActivityMonitor.ActivityMonitor()) try: #being backwards compatible here and not passing address if not given port = int(config['port']) zc.monitor.start(port) except KeyError: #new style bind try: bind = config['bind'] bind = bind.strip() m = re.match(r'^(?P<addr>\S+):(?P<port>\d+)$', bind) if m: #we have an address:port zc.monitor.start((m.group('addr'), int(m.group('port')))) return m = re.match(r'^(?P<port>\d+)$', bind) if m: #we have a port zc.monitor.start(int(m.group('port'))) return #we'll consider everything else as a domain socket zc.monitor.start(bind) except KeyError: #no bind config no server pass @zope.component.adapter( zope.traversing.interfaces.IContainmentRoot, zope.app.publication.interfaces.IBeforeTraverseEvent, ) def save_request_in_connection_info(object, event): object = zope.security.proxy.getObject(object) connection = getattr(object, '_p_jar', None) if connection is None: return path = event.request.get('PATH_INFO') if path is not None: connection.setDebugInfo(path) class Test(zope.publisher.browser.BrowserPage): zope.component.adapts(zope.interface.Interface, zope.publisher.interfaces.browser.IBrowserRequest) def __call__(self): time.sleep(30) return 'OK' pid = os.getpid() def getStatus(want=('VmSize', 'VmRSS')): if not os.path.exists('/proc/%s/status' % pid): return for line in open('/proc/%s/status' % pid): if (line.split(':')[0] in want): yield line.strip()
zc.z3monitor
/zc.z3monitor-0.8.0.tar.gz/zc.z3monitor-0.8.0/src/zc/z3monitor/__init__.py
__init__.py
import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
zc.z3monitor
/zc.z3monitor-0.8.0.tar.gz/zc.z3monitor-0.8.0/bootstrap/bootstrap.py
bootstrap.py
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--setuptools-version", help="use a specific setuptools version") options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zc.zdaemonrecipe
/zc.zdaemonrecipe-1.0.0.tar.gz/zc.zdaemonrecipe-1.0.0/bootstrap.py
bootstrap.py
zdaemon recipe ============== zc.zdaemonrecipe provides a recipe that can be used to create zdaemon run-control scripts. It can be used directly in buildouts and by other recipes. It accepts 2 options: program The anme of the program and, optionally, command-line arguments. (Note that, due to limitations in zdaemon, the command-line options cannot have embedded spaces.) zdaemon.conf Optionally, you can provide extra configuration in ZConfig format. What's provided will be augmented by the zdaemon recipe, as needed. deployment The name of a zc.recipe.deployment deployment. If specified, then: - The configuration, log, and run-time files will be put in deployment-defined directories. - A logrotate configuration will be generated for the zdaemon transacript log. Let's look at an example: >>> write('buildout.cfg', ... ''' ... [buildout] ... parts = run ... ... [run] ... recipe = zc.zdaemonrecipe ... program = sleep 1 ... ''') If we run the buildout, we'll get a run part that contains the zdaemon configuration file and a run script in the bin directory: >>> from six import print_ >>> print_(system(buildout), end='') Installing run. Generated script '/sample-buildout/bin/zdaemon'. Generated script '/sample-buildout/bin/run'. >>> cat('parts', 'run', 'zdaemon.conf') <runner> daemon on directory /sample-buildout/parts/run program sleep 1 socket-name /sample-buildout/parts/run/zdaemon.sock transcript /sample-buildout/parts/run/transcript.log </runner> <BLANKLINE> <eventlog> <logfile> path /sample-buildout/parts/run/transcript.log </logfile> </eventlog> >>> cat('bin', 'run') # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ ... '/sample-buildout/eggs/zdaemon-2.0-py2.4.egg', '/sample-buildout/eggs/ZConfig-2.4-py2.4.egg', ] <BLANKLINE> import zdaemon.zdctl <BLANKLINE> if __name__ == '__main__': sys.exit(zdaemon.zdctl.main([ '-C', '/sample-buildout/parts/run/zdaemon.conf', ]+sys.argv[1:] )) zdaemon will also be installed: >>> ls('eggs') d ZConfig-2.4-py2.4.egg d setuptools-0.6-py2.4.egg d zc.buildout-1.0.0b27-py2.4.egg d zc.recipe.egg-1.0.0-py2.4.egg d zdaemon-2.0-py2.4.egg d zope.testing-3.4-py2.4.egg You can use an eggs option to specify a zdaemon version. If we specify a deployment, then the files will be placed in deployment-defined locations: >>> mkdir('etc') >>> mkdir('init.d') >>> mkdir('logrotate') >>> write('buildout.cfg', ... ''' ... [buildout] ... parts = run ... ... [run] ... recipe = zc.zdaemonrecipe ... program = sleep 1 ... deployment = deploy ... ... [deploy] ... name = test-deploy ... etc-directory = etc ... rc-directory = init.d ... log-directory = logs ... run-directory = run ... logrotate-directory = logrotate ... user = bob ... ''') >>> print_(system(buildout), end='') Uninstalling run. Installing run. Generated script '/sample-buildout/init.d/test-deploy-run'. >>> import os >>> os.path.exists('parts/run') False >>> os.path.exists('bin/run') False >>> cat('etc', 'run-zdaemon.conf') <runner> daemon on directory run program sleep 1 socket-name run/run-zdaemon.sock transcript logs/run.log user bob </runner> <BLANKLINE> <eventlog> <logfile> path logs/run.log </logfile> </eventlog> >>> cat('init.d', 'test-deploy-run') # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ ... '/sample-buildout/eggs/zdaemon-2.0a6-py2.4.egg', '/sample-buildout/eggs/ZConfig-2.4a6-py2.4.egg', ] <BLANKLINE> import zdaemon.zdctl <BLANKLINE> if __name__ == '__main__': sys.exit(zdaemon.zdctl.main([ '-C', 'etc/run-zdaemon.conf', ]+sys.argv[1:] )) >>> cat('logrotate', 'test-deploy-run') logs/run.log { rotate 5 weekly postrotate init.d/test-deploy-run -C etc/run-zdaemon.conf reopen_transcript endscript } If you want to override any part of the generated zdaemon configuration, simply provide a zdaemon.conf option in your instance section: >>> write('buildout.cfg', ... ''' ... [buildout] ... parts = run ... ... [run] ... recipe = zc.zdaemonrecipe ... program = sleep 1 ... deployment = deploy ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... [deploy] ... etc-directory = etc ... rc-directory = init.d ... log-directory = logs ... run-directory = run ... logrotate-directory = logrotate ... user = bob ... ''') >>> print_(system(buildout), end='') Uninstalling run. Installing run. Generated script '/sample-buildout/init.d/deploy-run'. >>> cat('etc', 'run-zdaemon.conf') <runner> daemon off directory run program sleep 1 socket-name /sample-buildout/parts/instance/sock transcript /dev/null user bob </runner> <BLANKLINE> <eventlog> </eventlog> Creating shell start scripts ---------------------------- By default, the startup scripts are generated Python scripts that use the zdaemon module. Sometimes, this is inconvenient. In particular, when deploying software, generated Python scripts may break after a software update because they contain paths to software eggs. We can request shell scripts that invoke a generic zdaemon script. The shell script only depends on the path to the zdaemon script, which generally doesn't change when updating softawre. To request a shell script, add a shell-script option with a true value: >>> write('buildout.cfg', ... ''' ... [buildout] ... parts = run ... ... [run] ... recipe = zc.zdaemonrecipe ... program = sleep 1 ... shell-script = true ... deployment = deploy ... ... [deploy] ... name = test-deploy ... etc-directory = etc ... rc-directory = init.d ... log-directory = logs ... run-directory = run ... logrotate-directory = logrotate ... user = alice ... ''') >>> print_(system(buildout), end='') # doctest: +NORMALIZE_WHITESPACE Uninstalling run. Installing run. zc.zdaemonrecipe: Generated shell script '/sample-buildout/init.d/test-deploy-run'. >>> cat('init.d', 'test-deploy-run') # doctest: +NORMALIZE_WHITESPACE #!/bin/sh su alice -c \ "/sample-buildout/bin/zdaemon -C '/sample-buildout/etc/run-zdaemon.conf' $*" >>> ls('etc') - run-zdaemon.conf Using the zdaemon recipe from other recipes ------------------------------------------- To use the daemon recipe from other recipes, simply instantiate an instance in your recipe __init__, passing your __init__ arguments, and then calling the instance's install in your install method.
zc.zdaemonrecipe
/zc.zdaemonrecipe-1.0.0.tar.gz/zc.zdaemonrecipe-1.0.0/zc/zdaemonrecipe/README.txt
README.txt
"""zdaemon -- a package to manage a daemon application.""" import ZConfig.schemaless import logging import os import sys import zc.buildout.easy_install import zc.recipe.egg if sys.version_info >= (3,): from io import StringIO else: from cStringIO import StringIO logger = logging.getLogger("zc.zdaemonrecipe") class Recipe: def __init__(self, buildout, name, options): self.name, self.options = name, options self.buildout = buildout deployment = self.deployment = options.get('deployment') if deployment: # Note we use get below to work with old zc.recipe.deployment eggs. self.deployment = buildout[deployment].get('name', deployment) options['rc-directory'] = buildout[deployment]['rc-directory'] options['run-directory'] = buildout[deployment]['run-directory'] options['log-directory'] = buildout[deployment]['log-directory'] options['etc-directory'] = buildout[deployment]['etc-directory'] options['logrotate'] = os.path.join( buildout[deployment]['logrotate-directory'], self.deployment + '-' + name) options['user'] = buildout[deployment]['user'] else: options['rc-directory'] = buildout['buildout']['bin-directory'] options['run-directory'] = os.path.join( buildout['buildout']['parts-directory'], self.name, ) options['eggs'] = options.get('eggs', 'zdaemon') self.egg = zc.recipe.egg.Egg(buildout, name, options) shell_script = options.get('shell-script', '') if shell_script in ('false', ''): self.shell_script = False elif shell_script == 'true': self.shell_script = True options['zdaemon'] = os.path.join( buildout['buildout']['bin-directory'], options.get('zdaemon', 'zdaemon'), ) else: raise zc.buildout.UserError( 'The shell-script option value must be "true", "false" or "".') def install(self): options = self.options run_directory = options['run-directory'] deployment = self.deployment if deployment: zdaemon_conf_path = os.path.join(options['etc-directory'], self.name+'-zdaemon.conf') event_log_path = os.path.join( options['log-directory'], self.name+'.log', ) socket_path = os.path.join(run_directory, self.name+'-zdaemon.sock') rc = deployment + '-' + self.name rc=os.path.join(options['rc-directory'], rc) logrotate = options['logrotate'] options.created(logrotate) open(logrotate, 'w').write(logrotate_template % dict( logfile=event_log_path, rc=rc, conf=zdaemon_conf_path, )) else: zdaemon_conf_path = os.path.join(run_directory, 'zdaemon.conf') event_log_path = os.path.join( run_directory, 'transcript.log', ) socket_path = os.path.join(run_directory, 'zdaemon.sock') rc = os.path.join(options['rc-directory'], self.name) options.created(run_directory) if not os.path.exists(run_directory): os.mkdir(run_directory) zdaemon_conf = options.get('zdaemon.conf', '')+'\n' zdaemon_conf = ZConfig.schemaless.loadConfigFile( StringIO(zdaemon_conf)) defaults = { 'program': "%s" % ' '.join(options['program'].split()), 'daemon': 'on', 'transcript': event_log_path, 'socket-name': socket_path, 'directory' : run_directory, } if deployment: defaults['user'] = options['user'] runner = [s for s in zdaemon_conf.sections if s.type == 'runner'] if runner: runner = runner[0] else: runner = ZConfig.schemaless.Section('runner') zdaemon_conf.sections.insert(0, runner) for name, value in defaults.items(): if name not in runner: runner[name] = [value] if not [s for s in zdaemon_conf.sections if s.type == 'eventlog']: zdaemon_conf.sections.append(event_log(event_log_path)) options.created(zdaemon_conf_path) open(zdaemon_conf_path, 'w').write(str(zdaemon_conf)) self.egg.install() requirements, ws = self.egg.working_set() rc = os.path.abspath(rc) options.created(rc) if self.shell_script: if not os.path.exists(options['zdaemon']): logger.warn(no_zdaemon % options['zdaemon']) contents = "%(zdaemon)s -C '%(conf)s' $*" % dict( zdaemon=options['zdaemon'], conf=os.path.join(self.buildout['buildout']['directory'], zdaemon_conf_path), ) if options.get('user'): contents = 'su %(user)s -c \\\n "%(contents)s"' % dict( user=options['user'], contents=contents, ) contents = "#!/bin/sh\n%s\n" % contents dest = os.path.join(options['rc-directory'], rc) if not (os.path.exists(dest) and open(dest).read() == contents): open(dest, 'w').write(contents) os.chmod(dest, 0o755) logger.info("Generated shell script %r.", dest) else: zc.buildout.easy_install.scripts( [(rc, 'zdaemon.zdctl', 'main')], ws, options['executable'], options['rc-directory'], arguments = ('[' '\n %r, %r,' '\n ]+sys.argv[1:]' '\n ' % ('-C', zdaemon_conf_path, ) ), ) return options.created() update = install def event_log(path, *data): return ZConfig.schemaless.Section( 'eventlog', '', None, [ZConfig.schemaless.Section('logfile', '', dict(path=[path]))]) event_log_template = """ <eventlog> <logfile> path %s formatter zope.exceptions.log.Formatter </logfile> </eventlog> """ logrotate_template = """%(logfile)s { rotate 5 weekly postrotate %(rc)s -C %(conf)s reopen_transcript endscript } """
zc.zdaemonrecipe
/zc.zdaemonrecipe-1.0.0.tar.gz/zc.zdaemonrecipe-1.0.0/zc/zdaemonrecipe/__init__.py
__init__.py
================================================= Service registration and discovery with ZooKeeper ================================================= The zc.zk package provides support for registering and discovering services with ZooKeeper. It also provides support for defining services with a tree-based model and syncing the model with ZooKeeper. The use cases are: - Register a server providing a service. - Get the addresses of servers providing a service. - Get and set service configuration data. - Model system architecture as a tree. Important note for zc.zk 1.x users Version 2 is mostly. but not entirely backward compatible. Although the goal of version 1 was primarily service registration and discovery, it also provided a high-level ZooKeeper API. `Kazoo <https://pypi.python.org/pypi/kazoo/>`_ is a much better high-level interface for ZooKeeper because: - It isn't based on the buggy ZooKeeper C interface and Python extension. - It doesn't assume that ephemeral nodes should be reestablished when a session expires and is recreated. zc.zk 2 uses Kazoo. This package makes no effort to support Windows. (Patches to support Windows might be accepted if they don't add much complexity.) .. contents:: Installation ============ You can install this as you would any other distribution. It requires the kazoo Python ZooKeeper interface. Instantiating a ZooKeeper helper ================================ To use the helper API, create a ZooKeeper instance:: >>> import zc.zk >>> zk = zc.zk.ZooKeeper('zookeeper.example.com:2181') The ZooKeeper constructor takes a ZooKeeper connection string, which is a comma-separated list of addresses of the form *HOST:PORT*. It defaults to the value of the ``ZC_ZK_CONNECTION_STRING`` environment variable, if set, or ``'127.0.0.1:2181'`` if not, which is convenient during development. You can also pass a kazoo client object, instead of a connection string. Register a server providing a service ===================================== To register a server, use the ``register`` method, which takes a service path and the address a server is listing on:: >>> zk.register('/fooservice/providers', ('192.168.0.42', 8080)) .. test >>> import os >>> zk.get_properties('/fooservice/providers/192.168.0.42:8080' ... ) == dict(pid=os.getpid()) True ``register`` creates a read-only ephemeral ZooKeeper node as a child of the given service path. The name of the new node is (a string representation of) the given address. This allows clients to get the list of addresses by just getting the list of the names of children of the service path. Ephemeral nodes have the useful property that they're automatically removed when a ZooKeeper session is closed or when the process containing it dies. De-registration is automatic. When registering a server, you can optionally provide server (node) data as additional keyword arguments to register. By default, the process id is set as the ``pid`` property. This is useful to tracking down the server process. In addition, an event is generated, providing subscribers to add properties as a server is being registered. (See `Server-registration events`_.) Get the addresses of service providers ====================================== Getting the addresses providing a service is accomplished by getting the children of a service node:: >>> addresses = zk.children('/fooservice/providers') >>> sorted(addresses) ['192.168.0.42:8080'] The ``children`` method returns an iterable of names of child nodes of the node specified by the given path. The iterable is automatically updated when new providers are registered:: >>> zk.register('/fooservice/providers', ('192.168.0.42', 8081)) >>> sorted(addresses) ['192.168.0.42:8080', '192.168.0.42:8081'] You can also get the number of children with ``len``:: >>> len(addresses) 2 You can call the iterable with a callback function that is called whenever the list of children changes:: >>> @zk.children('/fooservice/providers') ... def addresses_updated(addresses): ... print 'addresses changed' ... print sorted(addresses) addresses changed ['192.168.0.42:8080', '192.168.0.42:8081'] The callback is called immediately with the children. When we add another child, it'll be called again:: >>> zk.register('/fooservice/providers', ('192.168.0.42', 8082)) addresses changed ['192.168.0.42:8080', '192.168.0.42:8081', '192.168.0.42:8082'] Get service configuration data ============================== You get service configuration data by getting properties associated with a ZooKeeper node. The interface for getting properties is similar to the interface for getting children:: >>> data = zk.properties('/fooservice') >>> data['database'] u'/databases/foomain' >>> data['threads'] 1 The ``properties`` method returns a mapping object that provides access to node data. (ZooKeeper only stores string data for nodes. ``zc.zk`` provides a higher-level data interface by storing JSON strings.) The properties objects can be called with callback functions and used as function decorators to get update notification:: >>> @zk.properties('/fooservice') ... def data_updated(data): ... print 'data updated' ... for item in sorted(data.items()): ... print '%s: %r' % item data updated database: u'/databases/foomain' favorite_color: u'red' threads: 1 The callback is called immediately. It'll also be called when data are updated. Updating node properties ======================== You can update properties by calling the ``update`` method:: >>> thread_info = {'threads': 2} >>> data.update(thread_info, secret='123') data updated database: u'/databases/foomain' favorite_color: u'red' secret: u'123' threads: 2 You can also set individual properties: >>> data['threads'] = 1 data updated database: u'/databases/foomain' favorite_color: u'red' secret: u'123' threads: 1 If you call the ``set`` method, keys not listed are removed: >>> data.set(threads= 3, secret='1234') data updated secret: u'1234' threads: 3 Both ``update`` and ``set`` can take data from a positional data argument, or from keyword parameters. Keyword parameters take precedent over the positional data argument. Getting property data without tracking changes ============================================== Sometimes, you want to get service data, but don't want to watch for changes. If you pass ``watch=False`` to ``properties``, Then properties won't track changes. In this case, you can't set callback functions, but you can still update data. .. test >>> p2 = zk.properties('/fooservice', watch=False) >>> sorted(p2) [u'secret', u'threads'] >>> p2(lambda data: None) Traceback (most recent call last): ... TypeError: Can't set callbacks without watching. >>> p2['threads'] = 2 # doctest: +ELLIPSIS data updated ... threads: 2 >>> p2.update(threads=3) # doctest: +ELLIPSIS data updated ... threads: 3 Tree-definition format, import, and export ========================================== You can describe a ZooKeeper tree using a textual tree representation. You can then populate the tree by importing the representation. Heres an example:: /lb : ipvs /pools /cms # The address is fixed because it's # exposed externally address = '1.2.3.4:80' providers -> /cms/providers /retail address = '1.2.3.5:80' providers -> /cms/providers /cms : z4m cms threads = 3 /providers /databases /main /providers /retail : z4m retail threads = 1 /providers /databases main -> /cms/databases/main /ugc /providers .. -> tree_text This example defines a tree with 3 top nodes, ``lb`` and ``cms``, and ``retail``. The ``retail`` node has two sub-nodes, ``providers`` and ``databases`` and a property ``threads``. The ``/retail/databases`` node has symbolic link, ``main`` and a ``ugc`` sub-node. The symbolic link is implemented as a property named `` We'll say more about symbolic links in a later section. The ``lb``, ``cms`` and ``retail`` nodes have *types*. A type is indicated by following a node name with a colon and a string value. The string value is used to populate a ``type`` property. Types are useful to document the kinds of services provided at a node and can be used by deployment tools to deploy service providers. You can import a tree definition with the ``import_tree`` method:: >>> zk.import_tree(tree_text) This imports the tree at the top of the ZooKeeper tree. We can also export a ZooKeeper tree:: >>> print zk.export_tree(), /cms : z4m cms threads = 3 /databases /main /providers /providers /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers /retail address = u'1.2.3.5:80' providers -> /cms/providers /retail : z4m retail threads = 1 /databases main -> /cms/databases/main /ugc /providers /providers Note that when we export a tree: - The special reserved top-level zookeeper node is omitted. - Ephemeral nodes are omitted. - Each node's information is sorted by type (properties, then links, - then sub-nodes) and then by name, You can export just a portion of a tree:: >>> print zk.export_tree('/fooservice'), /fooservice secret = u'1234' threads = 3 /providers You can optionally see ephemeral nodes:: >>> print zk.export_tree('/fooservice', ephemeral=True), /fooservice secret = u'1234' threads = 3 /providers /192.168.0.42:8080 pid = 9999 /192.168.0.42:8081 pid = 9999 /192.168.0.42:8082 pid = 9999 We can import a tree over an existing tree and changes will be applied. Let's update our textual description:: /lb : ipvs /pools /cms # The address is fixed because it's # exposed externally address = '1.2.3.4:80' providers -> /cms/providers /cms : z4m cms threads = 4 /providers /databases /main /providers .. -> tree_text and re-import:: >>> zk.import_tree(tree_text) extra path not trimmed: /lb/pools/retail We got a warning about nodes left over from the old tree. We can see this if we look at the tree:: >>> print zk.export_tree(), /cms : z4m cms threads = 4 /databases /main /providers /providers /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers /retail address = u'1.2.3.5:80' providers -> /cms/providers /retail : z4m retail threads = 1 /databases main -> /cms/databases/main /ugc /providers /providers If we want to trim these, we can add a ``trim`` option. This is a little scary, so we'll use the dry-run option to see what it's going to do:: >>> zk.import_tree(tree_text, trim=True, dry_run=True) would delete /lb/pools/retail. If we know we're not trimming things and want to avoid a warning, we can use trim=False: >>> zk.import_tree(tree_text, trim=False) We can see that this didn't trim by using dry-run again: >>> zk.import_tree(tree_text, trim=True, dry_run=True) would delete /lb/pools/retail. We do want to trim, so we use trim=True: >>> zk.import_tree(tree_text, trim=True) >>> print zk.export_tree(), /cms : z4m cms threads = 4 /databases /main /providers /providers /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers /retail : z4m retail threads = 1 /databases main -> /cms/databases/main /ugc /providers /providers Note that nodes containing (directly or recursively) ephemeral nodes will never be trimmed. Also node that top-level nodes are never automatically trimmed. So we weren't warned about the unreferenced top-level nodes in the import. Recursive deletion ================== ZooKeeper only allows deletion of nodes without children. The ``delete_recursive`` method automates removing a node and all of it's children. If we want to remove the ``retail`` top-level node, we can use delete_recursive:: >>> zk.delete_recursive('/retail') >>> print zk.export_tree(), /cms : z4m cms threads = 4 /databases /main /providers /providers /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers Bt default, ``delete_recursive`` won't delete ephemeral nodes, or nodes that contain them:: >>> zk.delete_recursive('/fooservice') Not deleting /fooservice/providers/192.168.0.42:8080 because it's ephemeral. Not deleting /fooservice/providers/192.168.0.42:8081 because it's ephemeral. Not deleting /fooservice/providers/192.168.0.42:8082 because it's ephemeral. /fooservice/providers not deleted due to ephemeral descendent. /fooservice not deleted due to ephemeral descendent. You can use the ``force`` option to force ephemeral nodes to be deleted. Symbolic links ============== ZooKeeper doesn't have a concept of symbolic links, but ``zc.zk`` provides a convention for dealing with symbolic links. When trying to resolve a path, if a node lacks a child, but has a property with a name ending in ``' ->'``, the child will be found by following the path in the property value. The ``resolve`` method is used to resolve a path to a real path:: >>> zk.resolve('/lb/pools/cms/providers') u'/cms/providers' In this example, the link was at the endpoint of the virtual path, but it could be anywhere:: >>> zk.register('/cms/providers', '1.2.3.4:5') >>> zk.resolve('/lb/pools/cms/providers/1.2.3.4:5') u'/cms/providers/1.2.3.4:5' Note a limitation of symbolic links is that they can be hidden by children. For example, if we added a real node, at ``/lb/pools/cms/provioders``, it would shadow the link. ``children``, ``properties``, and ``register`` will automatically use ``resolve`` to resolve paths. When the ``children`` and ``properties`` are used for a node, the paths they use will be adjusted dynamically when paths are removed. To illustrate this, let's get children of ``/cms/databases/main``:: >>> main_children = zk.children('/cms/databases/main') >>> main_children.path '/cms/databases/main' >>> main_children.real_path '/cms/databases/main' .. test >>> main_properties = zk.properties('/cms/databases/main') >>> main_properties.path '/cms/databases/main' >>> main_properties.real_path '/cms/databases/main' ``Children`` and ``Properties`` objects have a ``path`` attribute that has the value passed to the ``children`` or ``properties`` methods. They have a ``real_path`` attribute that contains the path after resolving symbolic links. Let's suppose we want to move the database node to '/databases/cms'. First we'll export it:: >>> export = zk.export_tree('/cms/databases/main', name='cms') >>> print export, /cms /providers Note that we used the export ``name`` option to specify a new name for the exported tree. Now, we'll create a databases node:: >>> zk.create('/databases') u'/databases' And import the export:: >>> zk.import_tree(export, '/databases') >>> print zk.export_tree('/databases'), /databases /cms /providers Next, we'll create a symbolic link at the old location. We can use the ``ln`` convenience method:: >>> zk.ln('/databases/cms', '/cms/databases/main') >>> zk.get_properties('/cms/databases') {u'main ->': u'/databases/cms'} Now, we can remove ``/cms/databases/main`` and ``main_children`` will be updated:: >>> zk.delete_recursive('/cms/databases/main') >>> main_children.path '/cms/databases/main' >>> main_children.real_path u'/databases/cms' .. test >>> main_properties.path '/cms/databases/main' >>> main_properties.real_path u'/databases/cms' If we update ``/databases/cms``, ``main_children`` will see the updates:: >>> sorted(main_children) ['providers'] >>> _ = zk.delete('/databases/cms/providers') >>> sorted(main_children) [] .. test >>> dict(main_properties) {} >>> zk.properties('/databases/cms').set(a=1) >>> dict(main_properties) {u'a': 1} Symbolic links can be relative. If a link doesn't start with a slash, it's interpreted relative to the node the link occurs in. The special names ``.`` and ``..`` have their usual meanings. So, in:: /a /b l -> c l2 -> ../c /c /c .. -> relative_link_source >>> zk.import_tree(relative_link_source) >>> zk.resolve('/a/b/l') u'/a/b/c' >>> zk.resolve('/a/b/l2') u'/a/c' >>> zk.delete_recursive('/a') The link at ``/a/b/l`` resolves to ``/a/b/c`` and ``/a/b/l2`` resolves to ``/a/c``. Property links ============== In addition to symbolic links between nodes, you can have links between properties. In our earlier example, both the ``/cms`` and ``/fooservice`` nodes had ``threads`` properties:: /cms : z4m cms threads = 4 /databases /main /providers /providers /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers If we wanted ``/cms`` to have the same ``threads`` settings, we could use a property link:: /cms : z4m cms threads => /fooservice threads /databases /main /providers /providers /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers .. -> property_link_source >>> _ = zk.create('/test-propery-links', '', zc.zk.OPEN_ACL_UNSAFE) >>> zk.import_tree(property_link_source, '/test-propery-links') >>> properties = zk.properties('/test-propery-links/cms') >>> properties['threads =>'] u'/fooservice threads' >>> properties['threads'] 3 >>> zk.import_tree('/cms\n threads => /fooservice\n', ... '/test-propery-links') extra path not trimmed: /test-propery-links/cms/databases extra path not trimmed: /test-propery-links/cms/providers >>> properties['threads =>'] u'/fooservice' >>> properties['threads'] 3 >>> zk.delete_recursive('/test-propery-links') Property links are indicated with ``=>``. The value is a node path and optional property name, separated by whitespace. If the name is ommitted, then the refering name is used. For example, the name could be left off of the property link above. Node deletion ============= If a node is deleted and ``Children`` or ``Properties`` instances have been created for it, and the paths they were created with can't be resolved using symbolic links, then the instances' data will be cleared. Attempts to update properties will fail. If callbacks have been registered, they will be called without arguments, if possible. It would be bad, in practice, to remove a node that processes are watching. Registering a server with a blank hostname ========================================== It's common to use an empty string for a host name when calling bind to listen on all IPv4 interfaces. If you pass an address with an empty host to ``register`` and `netifaces <http://alastairs-place.net/projects/netifaces/>`_ is installed, then all of the non-local IPv4 addresses [#ifaces]_ (for the given port) will be registered. If there are no non-local interfaces (not connected to network), then the local IPV4 interface will be registered. If netifaces isn't installed and you pass an empty host name, then the fully-qualified domain name, as returned by ``socket.getfqdn()`` will be used for the host. Server-registration events ========================== When ``register`` is called, a ``zc.zk.RegisteringServer`` event is emmitted with a properties attribute that can be updated by subscribers prior to creating the ZooKeeper ephemeral node. This allows third-party code to record extra server information. Events are emitted by passing them to ``zc.zk.event.notify``. If ``zope.event`` is installed, then ``zc.zk.event.notify`` is an alias for ``zope.event.notify``, otherwise, ``zc.zk.event.notify`` is an empty function that can be replaced by applications. ZooKeeper Session Management ============================ Kazoo takes care of reestablishing ZooKeeper sessions. Watches created with the ``children`` and ``properties`` methods are reestablished when new sessions are established. ``zc.zk`` also recreates ephemeral nodes created via ``register``. zookeeper_export script ======================= The `zc.zk` package provides a utility script for exporting a ZooKeeper tree:: $ zookeeper_export -e zookeeper.example.com:2181 /fooservice /fooservice secret = u'1234' threads = 3 /providers /192.168.0.42:8080 pid = 9999 /192.168.0.42:8081 pid = 9999 /192.168.0.42:8082 pid = 9999 .. -> sh >>> command, expected = sh.strip().split('\n', 1) >>> _, command, args = command.split(None, 2) >>> import pkg_resources >>> export = pkg_resources.load_entry_point( ... 'zc.zk', 'console_scripts', command) >>> import sys, StringIO >>> sys.stdout = f = StringIO.StringIO(); export(args.split()) >>> got = f.getvalue() >>> import zc.zk.tests >>> zc.zk.tests.checker.check_output(expected.strip(), got.strip(), 0) True >>> export(['zookeeper.example.com:2181', '/fooservice']) /fooservice secret = u'1234' threads = 3 /providers >>> export(['zookeeper.example.com:2181']) /cms : z4m cms threads = 4 /databases main -> /databases/cms /providers /databases /cms a = 1 /fooservice secret = u'1234' threads = 3 /providers /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers >>> export(['zookeeper.example.com:2181', '/fooservice', '-oo']) >>> print open('o').read(), /fooservice secret = u'1234' threads = 3 /providers The export script provides the same features as the ``export_tree`` method. Use the ``--help`` option to see how to use it. zookeeper_import script ======================= The `zc.zk` package provides a utility script for importing a ZooKeeper tree. So, for example, given the tree:: /provision /node1 /node2 .. -> file_source >>> with open('mytree.txt', 'w') as f: f.write(file_source) In the file ``mytree.txt``, we can import the file like this:: $ zookeeper_import zookeeper.example.com:2181 mytree.txt /fooservice .. -> sh >>> command = sh.strip() >>> expected = '' >>> _, command, args = command.split(None, 2) >>> import_ = pkg_resources.load_entry_point( ... 'zc.zk', 'console_scripts', command) >>> import_(args.split()) >>> zk.print_tree() /cms : z4m cms threads = 4 /databases main -> /databases/cms /providers /1.2.3.4:5 pid = 9999 /databases /cms a = 1 /fooservice secret = u'1234' threads = 3 /providers /192.168.0.42:8080 pid = 9999 /192.168.0.42:8081 pid = 9999 /192.168.0.42:8082 pid = 9999 /provision /node1 /node2 /lb : ipvs /pools /cms address = u'1.2.3.4:80' providers -> /cms/providers Read from stdin: >>> stdin = sys.stdin >>> sys.stdin = StringIO.StringIO('/x\n/y') >>> import_('-d zookeeper.example.com:2181 - /fooservice'.split()) add /fooservice/x add /fooservice/y >>> sys.stdin = StringIO.StringIO('/x\n/y') >>> import_('-d zookeeper.example.com:2181'.split()) add /x add /y Trim: >>> sys.stdin = StringIO.StringIO('/provision\n/y') >>> import_('-dt zookeeper.example.com:2181 - /fooservice'.split()) would delete /fooservice/provision/node1. would delete /fooservice/provision/node2. add /fooservice/y >>> sys.stdin = stdin The import script provides the same features as the ``import_tree`` method, with the exception that it provides less flexibility for specifing access control lists. Use the ``--help`` option to see how to use it. Propery-update script ===================== The `zc.zk` package provides a utility script for updating individual properties:: zookeeper_set_property zookeeper.example.com:2181 /fooservice \ threads=4 debug=True comment='ok' .. -> example >>> example = example.replace('\\', '') >>> args = example.strip().split() >>> set_property = pkg_resources.load_entry_point( ... 'zc.zk', 'console_scripts', args.pop(0)) >>> set_property(args) data updated comment: u'ok' debug: True secret: u'1234' threads: 4 >>> zk.print_tree('/fooservice') /fooservice comment = u'ok' debug = True secret = u'1234' threads = 4 /providers /192.168.0.42:8080 pid = 9999 /192.168.0.42:8081 pid = 9999 /192.168.0.42:8082 pid = 9999 /provision /node1 /node2 The first argument to the script is the path of the node to be updated. Any number of additional arguments of the form: ``NAME=PYTHONEXPRESSION`` are provided to supply updates. If setting strings, you may have to quote the argument, as in "comment='a comment'". Iterating over a tree ===================== The ``walk`` method can be used to walk over the nodes in a tree:: >>> for path in zk.walk(): ... print path / /cms /cms/databases /cms/providers /cms/providers/1.2.3.4:5 /databases /databases/cms /fooservice /fooservice/providers /fooservice/providers/192.168.0.42:8080 /fooservice/providers/192.168.0.42:8081 /fooservice/providers/192.168.0.42:8082 /fooservice/provision /fooservice/provision/node1 /fooservice/provision/node2 /lb /lb/pools /lb/pools/cms /zookeeper /zookeeper/quota >>> for path in zk.walk('/fooservice'): ... print path /fooservice /fooservice/providers /fooservice/providers/192.168.0.42:8080 /fooservice/providers/192.168.0.42:8081 /fooservice/providers/192.168.0.42:8082 /fooservice/provision /fooservice/provision/node1 /fooservice/provision/node2 You can omit ephemeral nodes: >>> for path in zk.walk('/fooservice', ephemeral=False): ... print path /fooservice /fooservice/providers /fooservice/providers/192.168.0.42:8080 /fooservice/providers/192.168.0.42:8081 /fooservice/providers/192.168.0.42:8082 /fooservice/provision /fooservice/provision/node1 /fooservice/provision/node2 You can also get a mutable list of children, which you can mutate: >>> i = zk.walk('/fooservice', children=True) >>> path, children = i.next() >>> path, children ('/fooservice', [u'providers', u'provision']) >>> del children[0] >>> for path in i: ... print path /fooservice/provision /fooservice/provision/node1 /fooservice/provision/node2 Modifications to nodes are reflected while traversing:: >>> for path in zk.walk('/fooservice'): ... print path ... if 'provision' in zk.get_children(path): ... zk.delete_recursive(path+'/provision') /fooservice /fooservice/providers /fooservice/providers/192.168.0.42:8080 /fooservice/providers/192.168.0.42:8081 /fooservice/providers/192.168.0.42:8082 Graph analysis ============== The textual tree representation can be used to model and analyze a system architecturte. You can get a parsed representation of a tree using ``zc.zk.parse_tree`` to parse a text tree representation generated by hand for import, or using the ``export_tree`` method. :: >>> tree = zc.zk.parse_tree(tree_text) >>> sorted(tree.children) ['cms', 'lb'] >>> tree.children['lb'].properties {'type': 'ipvs'} The demo module, ``zc.zk.graphvis`` shows how you might generate system diagrams from tree models. Reference ========= zc.zk.ZooKeeper --------------- ``zc.zk.ZooKeeper([connection_string[, session_timeout[, wait]]])`` Return a new instance given a ZooKeeper connection string. The connection string defaults to the value of the ``ZC_ZK_CONNECTION_STRING`` environment variable, if set, otherwise '127.0.0.1:2181' will be used. If a session timeout (``session_timeout``) isn't specified, the ZooKeeper server's default session timeout is used. If the connection to ZooKeeper flaps, setting this to a higher value can avoid having clients think a server has gone away, when it hasn't. The downside of setting this to a higher value is that if a server crashes, it will take longer for ZooKeeper to notice that it's gone. The ``wait`` flag indicates whether the constructor should wait for a connection to ZooKeeper. It defaults to False. If a connection can't be made, a ``zc.zk.FailedConnect`` exception is raised. ``children(path)`` Return a `zc.zk.Children`_ for the path. Note that there is a fair bit of machinery in `zc.zk.Children`_ objects to support keeping them up to date, callbacks, and cleaning them up when they are no-longer used. If you only want to get the list of children once, use ``get_children``. ``close()`` Close the ZooKeeper session. This should be called when cleanly shutting down servers to more quickly remove ephemeral nodes. ``delete_recursive(path[, dry_run[, force[, ignore_if_ephemeral]]])`` Delete a node and all of it's sub-nodes. Ephemeral nodes or nodes containing them are not deleted by default. To force deletion of ephemeral nodes, supply the ``force`` option with a true value. Normally, a message is printed if a node can't be deleted because it's ephemeral or has ephemeral sub-nodes. If the ``ignore_if_ephemeral`` option is true, the a message isn't printed if the node's path was passed to ``delete_recursive`` directly. (This is used by ``import_tree`` when the only nodes that would be trimmed are ephemeral nodes.) The dry_run option causes a summary of what would be deleted to be printed without actually deleting anything. ``export_tree(path[, ephemeral[, name]])`` Export a tree to a text representation. path The path to export. ephemeral Boolean, defaulting to false, indicating whether to include ephemeral nodes in the export. Including ephemeral nodes is mainly useful for visualizing the tree state. name The name to use for the top-level node. This is useful when using export and import to copy a tree to a different location and name in the hierarchy. Normally, when exporting the root node, ``/``, the root isn't included, but it is included if a name is given. ``import_tree(text[, path='/'[, trim[, acl[, dry_run]]]])`` Create tree nodes by importing a textual tree representation. text A textual representation of the tree. path The path at which to create the top-level nodes. trim Boolean, defaulting to false, indicating whether nodes not in the textual representation should be removed. acl An access control-list to use for imported nodes. If not specified, then full access is allowed to everyone. dry_run Boolean, defaulting to false, indicating whether to do a dry run of the import, without applying any changes. ``is_ephemeral(path)`` Return ``True`` if the node at ``path`` is ephemeral,``False`` otherwise. ``ln(source, destination)`` Create a symbolic link at the destination path pointing to the source path. If the destination path ends with ``'/'``, then the source name is appended to the destination. ``print_tree(path='/')`` Print the tree at the given path. This is just a short-hand for:: print zk.export_tree(path, ephemeral=True), ``properties(path, watch=True)`` Return a `zc.zk.Properties`_ for the path. Note that there is a fair bit of machinery in `zc.zk.Properties`_ objects to support keeping them up to date, callbacks, and cleaning them up when they are no-longer used. If you don't want to track changes, pass ``watch=False``. ``register(path, address, acl=zc.zk.READ_ACL_UNSAFE, **data)`` Register a server at a path with the address. An ephemeral child node of ``path`` will be created with name equal to the string representation (HOST:PORT) of the given address. ``address`` must be a host and port tuple. ``acl`` is a ZooKeeper access control list. Optional node properties can be provided as keyword arguments. ``resolve(path)`` Find the real path for the given path. ``walk(path)`` Iterate over the nodes of a tree rooted at path. In addition, ``ZooKeeper`` instances provide shortcuts to the following kazoo client methods: ``exists``, ``create``, ``delete``, ``get_children``, ``get``, and ``set``. zc.zk.Children -------------- ``__iter__()`` Return an iterator over the child names. ``__call__(callable)`` Register a callback to be called whenever a child node is added or removed. The callback is passed the children instance when a child node is added or removed. The ``Children`` instance is returned. zc.zk.Properties ---------------- Properties objects provide the usual read-only mapping methods, __getitem__, __len__, etc.. ``set(data=None, **properties)`` Set the properties for the node, replacing existing data. The data argument, if given, must be a dictionary or something that can be passed to the ``dict`` constructor. Items supplied as keywords take precedence over items supplied in the data argument. ``update(data=None, **properties)`` Update the properties for the node. The data argument, if given, must be a dictionary or something that can be passed to a dictionary's ``update`` method. Items supplied as keywords take precedence over items supplied in the data argument. ``__call__(callable)`` Register a callback to be called whenever a node's properties are changed. The callback is passed the properties instance when properties are changed. The ``Properties`` instance is returned. Other module attributes ------------------------ ``zc.zk.ZK`` A convenient aliad for ``zc.zk.ZooKeeper`` for people who hate to type. Testing support --------------- The ``zc.zk.testing`` module provides ``setUp`` and ``tearDown`` functions that can be used to emulate a ZooKeeper server. To find out more, use the help function:: >>> import zc.zk.testing >>> help(zc.zk.testing) .. -> ignore >>> import zc.zk.testing .. cleanup >>> zk.close() Change History ============== 2.1.0 (2014-10-20) ================== - Get the default connection string from ``ZC_ZK_CONNECTION_STRING`` if set. 2.0.1 (2014-08-28) ================== - Fixed: ZooKeeper operations (including closing ZooKeeper connections) hung after network failures if ZooKeeper sessions were lost and ephemeral nodes (for registered services) had to be re-registered. - Fixed: Didn't properly handle None values for node data returned by Kazoo 2.0. 2.0.0 (2014-06-02) ================== Final release (identical to 2.0.0a7). We've used this in production for several months. 2.0.0a7 (2014-02-12) -------------------- Fixed: The release missed a zcml file helpful for registering monitoring components. 2.0.0a6 (2014-02-10) -------------------- This release has a number of backward-compatibility changes made after testing some existing client software with the a5 release. - Restored the ``wait`` constructor flag to keep trying if a connection fails. - Restored the ``recv_timeout`` for test backward compatibility. - Restored the test handle-management mechanism for test backward-compatibility. - Fixed a bug in the way test machinery used internal handles. - Restored the create_recursive method for backward compatibility. 2.0.0a5 (2014-01-30) -------------------- - Log when sessions are lost and ephemeral nodes are restored. Fixed: Kazoo returns node children as Unicode. zc.zk client applications expect children as returned by the children to have bytes values and they use the values to connect sockets. ``Children`` objects returned by zc.zk.children now encode child names using UTF-8. Fixed: zc.zk 2 didn't accept a value of None for session_timeout constructor argument, breaking some old clients. 2.0.0a4 (2014-01-13) -------------------- Fixed: When saving properties in ZooKeeper nodes, empty properties were encoded as empty strings. When Kazoo saves empty strings, it does so in a way that causes the ZooKeeper C client (or at least the Python C binding) to see semi-random data, sometimes including data written previously to other nodes. This can cause havoc when data for one node leaks into another. Now, we save empty properties as ``'{}'``. 2.0.0a3 (2014-01-08) -------------------- - Renamed ``get_raw_properties`` back to ``get_properties``, for backward compatibility, now that we've decided not to have a separate package. - Added ``ensure_path`` to the testing client. - Updated the ``ZooKeeper.close`` method to allow multiple calls. (Calls after the first have no effect.) 2.0.0a2 (2014-01-06) -------------------- Fixed packaging bug. 2.0.0a1 (2014-01-06) -------------------- Initial version forked from zc.zk 1.2.0 ---------------------------------------------------------------------- .. [#ifaces] It's a little more complicated. If there are non-local interfaces, then only non-local addresses are registered. In normal production, there's really no point in registering local addresses, as clients on other machines can't make any sense of them. If *only* local interfaces are found, then local addresses are registered, under the assumption that someone is developing on a disconnected computer.
zc.zk
/zc.zk-2.1.0.tar.gz/zc.zk-2.1.0/src/zc/zk/README.txt
README.txt
import logging import optparse import sys import zc.zk import kazoo.security def world_acl(permission): return kazoo.security.ACL(permission, kazoo.security.ANYONE_ID_UNSAFE) def export(args=None): """Usage: %prog [options] connection [path] """ if args is None: args = sys.argv[1:] parser = optparse.OptionParser(export.__doc__) parser.add_option('-e', '--ephemeral', action='store_true') parser.add_option('-o', '--output') options, args = parser.parse_args(args) connection = args.pop(0) if args: [path] = args else: path = '/' logging.basicConfig(level=logging.WARNING) zk = zc.zk.ZooKeeper(connection) data = zk.export_tree(path, ephemeral=options.ephemeral) if options.output: with open(options.output, 'w') as f: f.write(data) else: print data, zk.close() def import_(args=None): """Usage: %prog [options] connection [import-file [path]] Import a tree definition from a file. If no import-file is provided or if the import file is -, then data are read from standard input. """ if args is None: args = sys.argv[1:] parser = optparse.OptionParser(import_.__doc__) parser.add_option('-d', '--dry-run', action='store_true') parser.add_option('-t', '--trim', action='store_true') parser.add_option( '-p', '--permission', type='int', default=kazoo.security.Permissions.ALL, help='ZooKeeper permission bits as integer,' ' kazoo.security.Permissions.ALL', ) options, args = parser.parse_args(args) if not (1 <= len(args) <= 3): parser.parse_args(['-h']) connection = args.pop(0) if args: import_file = args.pop(0) else: import_file = '-' if args: [path] = args else: path = '/' logging.basicConfig(level=logging.WARNING) zk = zc.zk.ZooKeeper(connection) if import_file == '-': import_file = sys.stdin else: import_file = open(import_file) zk.import_tree( import_file.read(), path, trim=options.trim, dry_run=options.dry_run, acl=[world_acl(options.permission)], ) zk.close() def validate_(args=None): """Usage: %prog connection [file [path]] Validate a tree definition from a file. If no file is provided or if the import file is -, then data are read from standard input. """ if args is None: args = sys.argv[1:] parser = optparse.OptionParser(import_.__doc__) options, args = parser.parse_args(args) if len(args) != 1: parser.parse_args(['-h']) if args: import_file = args.pop(0) else: import_file = '-' if import_file == '-': import_file = sys.stdin else: import_file = open(import_file) zc.zk.parse_tree(import_file.read()) import_file.close() def set_property(args=None): if args is None: args = sys.argv[1:] connection = args.pop(0) path = args.pop(0) zk = zc.zk.ZooKeeper(connection) def _property(arg): name, expr = arg.split('=', 1) return name, eval(expr, {}) zk.properties(path).update(dict(map(_property, args))) zk.close()
zc.zk
/zc.zk-2.1.0.tar.gz/zc.zk-2.1.0/src/zc/zk/scripts.py
scripts.py
import collections import json import logging import os import re import socket import sys import threading import time import weakref import zc.zk.event import zc.thread import kazoo.client import kazoo.exceptions from kazoo.security import OPEN_ACL_UNSAFE, READ_ACL_UNSAFE logger = logging.getLogger(__name__) def parse_addr(addr): host, port = addr.split(':') return host, int(port) def encode(props): if len(props) == 1 and 'string_value' in props: return props['string_value'] return json.dumps(props, separators=(',',':')) def decode(sdata, path='?'): s = sdata and sdata.strip() if not s: data = {} elif s.startswith('{') and s.endswith('}'): try: data = json.loads(s) except: logger.exception('bad json data in node at %r', path) data = dict(string_value = sdata) else: data = dict(string_value = sdata) return data def join(*args): return '/'.join(args) class CancelWatch(Exception): pass class LinkLoop(Exception): pass class FailedConnect(Exception): pass class BadPropertyLink(Exception): pass dot = re.compile(r"/\.(/|$)") dotdot = re.compile(r"/[^/]+/\.\.(/|$)") class Resolving: def resolve(self, path, seen=()): # normalize dots while 1: npath = dotdot.sub(r"\1", dot.sub(r"\1", path)) if npath == path: break path = npath if self.exists(path): return path if path in seen: seen += (path,) raise LinkLoop(seen) try: base, name = path.rsplit('/', 1) base = self.resolve(base, seen) newpath = base + '/' + name if self.exists(newpath): return newpath props = self.get_properties(base) newpath = props.get(name+' ->') if not newpath: raise kazoo.exceptions.NoNodeError(newpath) if not newpath[0] == '/': newpath = base + '/' + newpath seen += (path,) return self.resolve(newpath, seen) except kazoo.exceptions.NoNodeError: raise kazoo.exceptions.NoNodeError(path) aliases = 'exists', 'create', 'delete', 'get_children', 'get' class ZooKeeper(Resolving): def __init__( self, connection_string=None, session_timeout=None, wait = False ): if session_timeout is None: session_timeout = 10.0 self.session_timeout = session_timeout if not connection_string: connection_string = os.environ.get( "ZC_ZK_CONNECTION_STRING", "127.0.0.1:2181") if isinstance(connection_string, basestring): client = kazoo.client.KazooClient( connection_string, session_timeout) started = False else: client = connection_string started = True self.close = lambda : None self.client = client for alias in aliases: setattr(self, alias, getattr(client, alias)) self.ephemeral = {} self.state = None def watch_session(state): restore = False logger.info("watch_session %s" % state) if state == kazoo.protocol.states.KazooState.CONNECTED: restore = self.state == kazoo.protocol.states.KazooState.LOST logger.info('connected') self.state = state if restore: @zc.thread.Thread def restore(): for path, data in list(self.ephemeral.items()): logger.info("restoring ephemeral %s", path) try: self.create( path, data['data'], data['acl'], ephemeral=True) except kazoo.exceptions.NodeExistsError: pass # threads? <shrug> client.add_listener(watch_session) if started: watch_session(client.state) else: while 1: try: client.start() except Exception: logger.critical("Can't connect to ZooKeeper at %r", connection_string) if wait: time.sleep(1) else: raise FailedConnect(connection_string) else: break def get_properties(self, path): return decode(self.get(path)[0], path) def _findallipv4addrs(self, tail): try: import netifaces except ImportError: return [socket.getfqdn()+tail] addrs = set() loopaddrs = set() for iface in netifaces.interfaces(): for info in netifaces.ifaddresses(iface).get(2, ()): addr = info.get('addr') if addr: if addr.startswith('127.'): loopaddrs.add(addr+tail) else: addrs.add(addr+tail) return addrs or loopaddrs def register(self, path, addr, acl=READ_ACL_UNSAFE, **kw): kw['pid'] = os.getpid() if not isinstance(addr, str): addr = '%s:%s' % tuple(addr) if addr[:1] == ':': addrs = self._findallipv4addrs(addr) else: addrs = (addr,) path = self.resolve(path) zc.zk.event.notify(RegisteringServer(addr, path, kw)) if path != '/': path += '/' for addr in addrs: data = encode(kw) apath = path + addr self.create(apath, data, acl, ephemeral=True) self.ephemeral[apath] = dict(data=data, acl=acl) register_server = register # backward compatibility def set(self, path, data, *a, **k): r = self.client.set(path, data, *a, **k) if path in self.ephemeral: self.ephemeral[path]['data'] = data return r def children(self, path): return Children(self, path) def properties(self, path, watch=True): return Properties(self, path, watch) def import_tree(self, text, path='/', trim=None, acl=OPEN_ACL_UNSAFE, dry_run=False): while path.endswith('/'): path = path[:-1] # Mainly to deal w root: / self._import_tree(path, parse_tree(text), acl, trim, dry_run, True) def _import_tree(self, path, node, acl, trim, dry_run, top=False): if not top: new_children = set(node.children) for name in sorted(self.get_children(path)): if name in new_children: continue cpath = join(path, name) if trim: self.delete_recursive(cpath, dry_run, ignore_if_ephemeral=True) elif trim is None: print 'extra path not trimmed:', cpath for name, child in sorted(node.children.iteritems()): cpath = path + '/' + name data = encode(child.properties) if self.exists(cpath): if dry_run: new = child.properties old = self.get_properties(cpath) old = decode(self.get(cpath)[0]) for n, v in sorted(old.items()): if n not in new: if n.endswith(' ->'): print '%s remove link %s %s' % (cpath, n, v) else: print '%s remove property %s = %s' % ( cpath, n, v) elif new[n] != v: if n.endswith(' ->'): print '%s %s link change from %s to %s' % ( cpath, n[:-3], v, new[n]) else: print '%s %s change from %s to %s' % ( cpath, n, v, new[n]) for n, v in sorted(new.items()): if n not in old: if n.endswith(' ->'): print '%s add link %s %s' % (cpath, n, v) else: print '%s add property %s = %s' % ( cpath, n, v) else: self.set(cpath, data) oldacl, meta = self.client.get_acls(cpath) if acl != oldacl: self.client.set_acls(cpath, meta.aversion, acl) else: if dry_run: print 'add', cpath continue else: self.create(cpath, data, acl) self._import_tree(cpath, child, acl, trim, dry_run) def delete_recursive(self, path, dry_run=False, force=False, ignore_if_ephemeral=False): self._delete_recursive(path, dry_run, force, ignore_if_ephemeral) def _delete_recursive(self, path, dry_run, force, ignore_if_ephemeral=False): ephemeral_child = None for name in sorted(self.get_children(path)): ephemeral_child = ( self._delete_recursive(join(path, name), dry_run, force) or ephemeral_child ) if ephemeral_child: print "%s not deleted due to ephemeral descendent." % path return ephemeral_child ephemeral = self.is_ephemeral(path) and not force if ephemeral and ignore_if_ephemeral: return if dry_run: if ephemeral: print "wouldn't delete %s because it's ephemeral." % path else: print "would delete %s." % path else: if ephemeral: print "Not deleting %s because it's ephemeral." % path else: logger.info('deleting %s', path) self.delete(path) return ephemeral def is_ephemeral(self, path): return bool(self.get(path)[1].ephemeralOwner) def export_tree(self, path='/', ephemeral=False, name=None): output = [] out = output.append def export_tree(path, indent, name=None): children = self.get_children(path) if path == '/': path = '' if 'zookeeper' in children: children.remove('zookeeper') if name is not None: out(indent + '/' + name) indent += ' ' else: data, meta = self.get(path) if meta.ephemeralOwner and not ephemeral: return if name is None: name = path.rsplit('/', 1)[1] properties = decode(data) type_ = properties.pop('type', None) if type_: name += ' : '+type_ out(indent + '/' + name) indent += ' ' links = [] for i in sorted(properties.iteritems()): if i[0].endswith(' ->'): links.append(i) else: out(indent+"%s = %r" % i) for i in links: out(indent+"%s %s" % i) for name in sorted(children): export_tree(path+'/'+name, indent) export_tree(path, '', name) return '\n'.join(output)+'\n' def print_tree(self, path='/'): print self.export_tree(path, True), def ln(self, target, source): base, name = source.rsplit('/', 1) if target[-1] == '/': target += name properties = decode(self.get(base)[0]) properties[name+' ->'] = target self.set(base, encode(properties)) def close(self): self.client.stop() self.client.close() self.close = lambda : None def walk(self, path='/', ephemeral=True, children=False): try: if not ephemeral and self.get(path)[1].ephemeralOwner: return _children = sorted(self.get_children(path)) if children: yield path, _children else: yield path except kazoo.exceptions.NoNodeError: return for name in _children: if path != '/': name = '/'+name for p in self.walk(path+name): yield p def create_recursive(self, path, data, acl): self.client.ensure_path(path, acl) self.client.set(path, data) # for test assertions, in a backward-compatible way def recv_timeout(self): return self.session_timeout ZK = ZooKeeper class KazooWatch: def __init__(self, client, children, path, watch): self.watch_ref = weakref.ref(watch) if children: client.ChildrenWatch(path)(self.handle) # Add a data watch so we know when a node is deleted. @client.DataWatch(path) def handle(data, *_): if data is None: self.handle(data) else: client.DataWatch(path)(self.handle) def handle(self, data, *rest): watch = self.watch_ref() if watch is None: return False watch.handle(data, *rest) if data is None: return False class Watch: # Base class for child and data watchers def __init__(self, zk, path, watch=True): self.zk = zk self.path = path self.watch = watch self.callbacks = [] self.register(True) def register(self, reraise): try: real_path = self.zk.resolve(self.path) except Exception: if reraise: raise else: self._deleted() else: self.real_path = real_path if self.watch: KazooWatch(self.zk.client, self.children, real_path, self) else: if self.children: self.setData(self.zk.get_children(real_path)) else: self.setData(self.zk.get(real_path)[0]) def handle(self, data, *rest): if data is None: # The watched node was deleted. # Try to re-resolve the watch path. self.register(False) else: self._notify(data) def setData(self, data): self.data = data deleted = False def _deleted(self): self.deleted = True self.data = {} for callback in self.callbacks: try: callback() except TypeError: pass except: logger.exception('Error %r calling %r', self, callback) def __repr__(self): return "%s%s.%s(%s)" % ( self.deleted and 'DELETED: ' or '', self.__class__.__module__, self.__class__.__name__, self.path) def _notify(self, data): if data is not None: self.setData(data) for callback in list(self.callbacks): try: callback(self) except Exception, v: self.callbacks.remove(callback) if isinstance(v, CancelWatch): logger.debug("cancelled watch(%r, %r)", self, callback) else: logger.exception("watch(%r, %r)", self, callback) def __call__(self, func): if not self.watch: raise TypeError("Can't set callbacks without watching.") func(self) self.callbacks.append(func) return self def __iter__(self): return iter(self.data) class Children(Watch): children = True def setData(self, data): Watch.setData(self, [v.encode('utf8') for v in data]) def __len__(self): return len(self.data) class Properties(Watch, collections.Mapping): children = False def __init__(self, zk, path, watch=True, _linked_properties=None): if _linked_properties is None: # {prop_link_path -> Properties} _linked_properties = {} self._linked_properties = _linked_properties Watch.__init__(self, zk, path, watch) def _setData(self, data, handle_errors=False): # Save a mapping as our data. # Set up watchers for any property links. old = getattr(self, 'data', None) self.data = data try: for name in data: if name.endswith(' =>') and name[:-3] not in data: link = data[name].strip().split() try: if not (1 <= len(link) <= 2): raise ValueError('Bad link data') path = link.pop(0) if path[0] != '/': path = self.path + '/' + path # TODO: why resolve here? Why not store the original # path in the linked properties. path = self.zk.resolve(path) properties = self._setup_link(path) properties[link and link[0] or name[:-3]] except Exception, v: if handle_errors: logger.exception( 'Bad property link %r %r', name, data[name]) else: raise ValueError("Bad property link", name, data[name], v) except: self.data = old # rollback raise def _setup_link(self, path): _linked_properties = self._linked_properties props = _linked_properties.get(path) if props is not None: return props _linked_properties[self.real_path] = self props = Properties(self.zk, path, self.watch, _linked_properties) _linked_properties[path] = props if self.watch: @props.callbacks.append def notify(properties=None): if properties is None: # A node we were watching was deleted. We should # try to re-resolve it. This doesn't happen often, # let's just reset everything. self._setData(self.data, True) elif self._linked_properties.get(path) is properties: # Notify our subscribers that there was a change # that might effect them. (But don't update our data.) self._notify(None) else: # We must not care about it anymore. raise CancelWatch() return props def setData(self, data): self._setData(decode(data, self.path), True) def __getitem__(self, key, seen=()): try: return self.data[key] except KeyError: link = self.data.get(key + ' =>', self) if link is self: raise try: data = link.split() if len(data) > 2: raise ValueError('Invalid property link') path = data.pop(0) if not path[0] == '/': path = self.path + '/' + path path = self.zk.resolve(path) if path in seen: raise LinkLoop(seen+(path,)) seen += (path,) properties = self._linked_properties.get(path) if properties is None: properties = self._setup_link(path) name = data and data[0] or key return properties.__getitem__(name, seen) except Exception, v: raise BadPropertyLink( v, 'in %r: %r' % (key + ' =>', self.data[key + ' =>']) ) def __iter__(self): for key in self.data: if key.endswith(' =>'): key = key[:-3] yield key def __len__(self): return len(self.data) def __contains__(self, key): return key in self.data or (key + ' =>') in self.data def copy(self): return self.data.copy() def _set(self, data): self._linked_properties = {} self._setData(data) self.zk.set(self.path, encode(data)) def set(self, data=None, **properties): data = data and dict(data) or {} data.update(properties) self._set(data) def update(self, data=None, **properties): d = self.data.copy() if data: d.update(data) d.update(properties) self._set(d) def __setitem__(self, key, value): self.update({key: value}) def __hash__(self): # Gaaaa, collections.Mapping return hash(id(self)) _text_is_node = re.compile( r'/(?P<name>\S+)' '(\s*:\s*(?P<type>\S.*))?' '$').match _text_is_property = re.compile( r'(?P<name>\S+)' '\s*=\s*' '(?P<expr>\S.*)' '$' ).match _text_is_link = re.compile( r'(?P<name>\S+)' '\s*->\s*' '(?P<target>\S+)' '$' ).match _text_is_plink = re.compile( r'(?P<name>\S+)' '\s*=>\s*' '(?P<target>\S+(\s+\S+)?)' '(\s+(?P<pname>/\S+))?' '$' ).match class ParseNode: def __init__(self, name='', properties=None, **children): self.name = name self.properties = properties or {} self.children = children for name, child in children.iteritems(): child.name = name def parse_tree(text, node_class=ParseNode): root = node_class() indents = [(-1, root)] # sorted [(indent, node)] lineno = 0 for line in text.split('\n'): lineno += 1 line = line.rstrip() if not line: continue stripped = line.strip() if stripped[0] == '#': continue indent = len(line) - len(stripped) data = None m = _text_is_plink(stripped) if m: data = (m.group('name') + ' =>'), m.group('target') if data is None: m = _text_is_property(stripped) if m: expr = m.group('expr') try: data = eval(expr, {}) except Exception, v: raise ValueError( "Error %s in expression: %r in line %s" % (v, expr, lineno)) data = m.group('name'), data if data is None: m = _text_is_link(stripped) if m: data = (m.group('name') + ' ->'), m.group('target') if data is None: m = _text_is_node(stripped) if m: data = node_class(m.group('name')) if m.group('type'): data.properties['type'] = m.group('type') if data is None: if '->' in stripped: raise ValueError(lineno, stripped, "Bad link format") else: raise ValueError(lineno, stripped, "Unrecognized data") if indent > indents[-1][0]: if not isinstance(indents[-1][1], node_class): raise ValueError( lineno, line, "Can't indent under properties") indents.append((indent, data)) else: while indent < indents[-1][0]: indents.pop() if indent > indents[-1][0]: raise ValueError(lineno, data, "Invalid indentation") if isinstance(data, node_class): children = indents[-2][1].children if data.name in children: raise ValueError(lineno, data, 'duplicate node') children[data.name] = data indents[-1] = indent, data else: if indents[-2][1] is root: raise ValueError( "Can't import properties above imported nodes.") properties = indents[-2][1].properties name, value = data if name in properties: raise ValueError(lineno, data, 'duplicate property') properties[name] = value return root class RegisteringServer: """Event emitted while a server is being registered. Attributes: name The server name (node name) name The service path (node parent path) properties A dictionary of properties to be saved on the ephemeral node. Typeically, subscribers will add properties. """ def __init__(self, name, path, properties): self.name = name self.path = path self.properties = properties def __repr__(self): return "RegisteringServer(%r, %r, %r)" % ( self.name, self.path, self.properties)
zc.zk
/zc.zk-2.1.0.tar.gz/zc.zk-2.1.0/src/zc/zk/__init__.py
__init__.py
============= ZEO ZooKeeper ============= Managing addresses, and especially ports is a drag. ZooKeeper can be used as a service registry. Servers can register themselves and clients can find services there. The ``zc.zkzeo`` package provides support for registering ZEO servers and a ZEO client storage that gets addresses from ZooKeeper. .. contents:: Running ZEO servers =================== To run a ZEO server, and register it with ZooKeeper, first create a ZEO configuration file:: <zeo> address 127.0.0.1 </zeo> <zookeeper> connection zookeeper.example.com:2181 path /databases/demo </zookeeper> <filestorage> path demo.fs </filestorage> .. -> server_conf The ZEO configuration file has the same options as usual, plus a ``zookeeper`` section with two options: ``connection`` A ZooKeeper connection string. This is typically a list of *HOST:PORT* pairs separated by commas. ``path`` The path at which to register the server. The path must already exist. When the server starts, it will register itself by creating a subnode of the path with a name consisting of it's address. (You can also specify a ZooKeeper session timeout, in milliseconds, with a ``session-timeout`` option.) When specifying the ZEO address, you can leave off the port and the operating system will assign it for you. To start the server, use the ``zkrunzeo`` script:: $ bin/zkrunzeo -C FILENAME .. test >>> import zc.zkzeo.runzeo, zc.zk >>> stop = zc.zkzeo.runzeo.test( ... server_conf) >>> zk = zc.zk.ZooKeeper('zookeeper.example.com:2181') >>> zk.print_tree('/databases/demo') /demo /127.0.0.1:56824 pid = 88841 >>> stop().exception >>> zk.print_tree('/databases/demo') /demo where ``FILENAME`` is the name of the configuration file you created. Including a ``zc.monitor`` monitoring server -------------------------------------------- The `zc.monitor <http://pypi.python.org/pypi/zc.monitor>`_ package provides a simple extensible command server for gathering monitoring data or providing run-time control of servers. If ``zc.monitor`` is in the Python path, ``zc.zkzeo`` can start a monitor server and make it's address available as the ``monitor`` property of of a server's ephemeral port. To request this, we use a ``monitor-server`` option in the ``zookeeper`` section:: <zeo> address 127.0.0.1 </zeo> <zookeeper> connection zookeeper.example.com:2181 path /databases/demo monitor-server 127.0.0.1 </zookeeper> <filestorage> path demo.fs </filestorage> .. -> server_conf >>> stop = zc.zkzeo.runzeo.test(server_conf) The value is the address to listen on. With the configuration above, if we started the server and looked at the ZooKeeper tree for '/databases/demo' using the ``zc.zk`` package, we'd see something like the following:: >>> zk.print_tree('/databases/demo') /demo /127.0.0.1:64211 monitor = u'127.0.0.1:11976' pid = 5082 .. verify that we can connect to the monitor: >>> [monitor_addr] = zk.get_children('/databases/demo') >>> host, port = monitor_addr.split(':') >>> import socket, time >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> sock.settimeout(.5) >>> sock.connect((host, int(port))) >>> sock.close() >>> _ = stop() >>> import zc.monitor >>> zc.monitor.last_listener.close() You can also specify a unix-domain socket name:: <zeo> address 127.0.0.1 </zeo> <zookeeper> connection zookeeper.example.com:2181 path /databases/demo monitor-server ./monitor.sock </zookeeper> <filestorage> path demo.fs </filestorage> .. -> server_conf We need to clear the zc.zk monitor data so we have a clean monitoring test below. This is an artifact of running multiple servers in one process. >>> import zc.zk.monitor >>> del zc.zk.monitor._servers[:] >>> stop = zc.zkzeo.runzeo.test(server_conf) When using a unix-domain socket, the monitor address isn't included in the tree: >>> zk.print_tree('/databases/demo') /demo /127.0.0.1:64213 pid = 5082 .. verify that we can connect to the monitor: >>> sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) >>> sock.settimeout(.5) >>> sock.connect('./monitor.sock') Some notes on the monitor server: - A monitor server won't be useful unless you've registered some command plugins. - ``zc.monitor`` isn't a dependency of ``zc.zkzeoc`` and won't be in the Python path unless you install it. Monitoring ---------- The zkzeo package provides a Nagios plugin. The plugin takes a ZooKeeper connection string and path to look up a ZEO server at (using the zc.zk service-registry framework). For example, to monitor the server defined above:: zkzeo-nagios zookeeper.example.com:2181 /databases/demo .. -> src >>> import pkg_resources >>> monitor = pkg_resources.load_entry_point( ... 'zc.zkzeo', 'console_scripts', 'zkzeo-nagios') >>> monitor(src.strip().split()[1:]) Empty storage u'1' 1 The zkzeo nagios monitor supports the same options as the ZEO nagios monitor, so for example to get full metrics:: zkzeo-nagios -m -s statusfile zookeeper.example.com:2181 /databases/demo .. -> src >>> monitor(src.strip().split()[1:]) Empty storage u'1'|active_txns=0 | connections=0 waiting=0 1 >>> monitor(src.strip().split()[1:]) Empty storage u'1'|active_txns=0 | connections=0 waiting=0 aborts=0.0 commits=0.0 conflicts=0.0 conflicts_resolved=0.0 loads=0.0 stores=0.0 1 Sometimes, there may be multiple servers registered at the same path, for example if servers are replicated. When monitoring a single server, you need to know which one to check. If you've a monitor-server for your ZEO process, as we did above, then you can use that to determine which one to use. Just provide the monitor server address:: zkzeo-nagios -m -M ./monitor.sock zookeeper.example.com:2181 /databases/demo .. -> src >>> monitor(src.strip().split()[1:]) Empty storage u'1'|active_txns=0 | connections=0 waiting=0 1 There's also a helper function useful for other monitors: >>> import zc.zkzeo.nagios >>> [zc.zkzeo.nagios.find_server( ... 'zookeeper.example.com:2181', ... '/databases/demo', ... None)] == zk.get_children('/databases/demo') True >>> [zc.zkzeo.nagios.find_server( ... 'zookeeper.example.com:2181', ... '/databases/demo', ... './monitor.sock')] == zk.get_children('/databases/demo') True Defining ZEO clients ==================== You can define a client in two ways, from Python and using a configuration file. Defining ZEO clients with Python -------------------------------- From Python, use ``zc.zkzeo.client``:: >>> import zc.zkzeo >>> client = zc.zkzeo.client( ... 'zookeeper.example.com:2181', '/databases/demo', ... max_disconnect_poll=1) You pass a ZooKeeper connection string and a path. The ``Client`` constructor will create a client storage with addresses found as sub-nodes of the given path and it will adjust the client-storage addresses as nodes are added and removed as children of the path. You can pass all other ``ZEO.ClientStorage.ClientStorage`` arguments, except the address, as additional positional and keyword arguments. Database and connection convenience functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You're usually not really interested in getting a storage object. What you really want is a database object:: >>> db = zc.zkzeo.DB( ... 'zookeeper.example.com:2181', '/databases/demo', ... max_disconnect_poll=1) or often, just a database connection:: >>> conn = zc.zkzeo.connection( ... 'zookeeper.example.com:2181', '/databases/demo', ... max_disconnect_poll=1) .. test >>> exconn = conn Defining ZEO clients in configuration files ------------------------------------------- In configuration files, use a ``zkzeoclient`` storage section:: %import zc.zkzeo <zodb> <zkzeoclient> zookeeper zookeeper.example.com:2181 server /databases/demo max-disconnect-poll 1 </zkzeoclient> </zodb> .. -> conf The options for ``zkzeoclient`` are the same as for the standard ZODB ``zeoclient`` section, except: - There's an extra required ``zookeeper`` option used to provide a ZooKeeper connection string. - There can be only one ``server`` option and it is used to supply the path in ZooKeeper where addresses may be found. .. test Double check the clients are working by opening a connection and making sure we see changes: >>> import ZODB.config >>> db_from_config = ZODB.config.databaseFromString(conf) >>> with db_from_config.transaction() as conn: ... conn.root.x = 1 >>> import ZODB >>> db_from_py = ZODB.DB(client) >>> with db_from_py.transaction() as conn: ... print conn.root() {'x': 1} >>> with db.transaction() as conn: ... print conn.root() {'x': 1} >>> import transaction >>> with transaction.manager: ... print exconn.root() {'x': 1} When we stop the storage server, we'll get warnings from zc.zkzeo, the clients will disconnect and will have no addresses: >>> import zope.testing.loggingsupport >>> handler = zope.testing.loggingsupport.Handler('zc.zkzeo') >>> handler.install() >>> [old_addr] = zk.get_children('/databases/demo') >>> stop().exception >>> zc.monitor.last_listener.close() >>> from zope.testing.wait import wait >>> wait(lambda : not client.is_connected()) >>> wait(lambda : not db_from_config.storage.is_connected()) >>> wait(lambda : not db.storage.is_connected()) >>> wait(lambda : not exconn.db().storage.is_connected()) >>> print handler zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> >>> handler.clear() Looking at the client manager, we see that the address list is now empty: >>> client._rpc_mgr <ConnectionManager for []> Let's sleep for a while to make sure we can wake up. Of course, we won't sleep *that* long, it's a test. >>> import time >>> time.sleep(9) Now, we'll restart the server and clients will reconnect >>> stop = zc.zkzeo.runzeo.test(server_conf) >>> [addr] = zk.get_children('/databases/demo') >>> addr != old_addr True >>> print zk.export_tree('/databases/demo', ephemeral=True), /demo /127.0.0.1:56837 pid = 88841 >>> wait(db_from_config.storage.is_connected) >>> with db_from_config.transaction() as conn: ... conn.root.x = 2 >>> wait(db_from_py.storage.is_connected, timeout=22) >>> time.sleep(.1) >>> with db_from_py.transaction() as conn: ... print conn.root() {'x': 2} >>> wait(db.storage.is_connected, timeout=22) >>> time.sleep(.1) >>> with db.transaction() as conn: ... print conn.root() {'x': 2} >>> wait(exconn.db().storage.is_connected, timeout=22) >>> time.sleep(.1) >>> with transaction.manager: ... print exconn.root() {'x': 2} >>> print handler # doctest: +NORMALIZE_WHITESPACE zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] >>> zk.close() >>> handler.uninstall() >>> db_from_py.close() >>> db_from_config.close() >>> db.close() >>> exconn.close() >>> stop().exception >>> zc.monitor.last_listener.close() Change History ============== 1.0.1 (2015-01-11) ------------------ Fixed packaging problem (of course). 1.0.0 (2015-01-11) ------------------ - Updated to work with ZEO/ZODB rather than ZODB3. - Added a Nagios monitoring plugin, the script zkzeo-nagios 0.3.2 (2012-07-10) ------------------ - Fixed: Didn't work with explicit configuration of port 0, which is recently supported by ZConfig. 0.3.1 (2012-06-26) ------------------ - Fixed: setting a monitor server on a unix-domain socket didn't work. 0.3.0 (2012-02-07) ------------------ - Added a static extra to force a dependency on ``zc-zookeeper-static``. - In test mode, use a shorter asyncore loop timeout to make the server shut down faster. - Fixed: zc.zkzeo depended on ``zc.zk [static]``, which forced installation of ``zc-zookeeper-static``, which should be optional. - Fixed: tests didn't pass with a recent change in handling of registration with empty host names in ``zc.zk``. - Fixed: Packaging: distribute can't install distributions with symlinks, so stopped using symlinks in distribution. 0.2.1 (2011-12-14) ------------------ - Fixed bug: The ``path`` key on the ``zookeeper`` server-configuration section was required, and shouldn't have been. 0.2.0 (2011-12-13) ------------------ - Register the host name from the ZEO address setting with ZooKeeper. (This is often an empty string, which ``zc.zk`` turns into the fully-quelified domain name.) - Fixed bug in handling the monitor-server. The actuall address setting was ignored. 0.1.1 (2011-12-12) ------------------ - Fixed a packaging bug. 0.1.0 (2011-12-11) ------------------ Initial release.
zc.zkzeo
/zc.zkzeo-1.0.1.tar.gz/zc.zkzeo-1.0.1/README.rst
README.rst
============= ZEO ZooKeeper ============= Managing addresses, and especially ports is a drag. ZooKeeper can be used as a service registry. Servers can register themselves and clients can find services there. The ``zc.zkzeo`` package provides support for registering ZEO servers and a ZEO client storage that gets addresses from ZooKeeper. .. contents:: Running ZEO servers =================== To run a ZEO server, and register it with ZooKeeper, first create a ZEO configuration file:: <zeo> address 127.0.0.1 </zeo> <zookeeper> connection zookeeper.example.com:2181 path /databases/demo </zookeeper> <filestorage> path demo.fs </filestorage> .. -> server_conf The ZEO configuration file has the same options as usual, plus a ``zookeeper`` section with two options: ``connection`` A ZooKeeper connection string. This is typically a list of *HOST:PORT* pairs separated by commas. ``path`` The path at which to register the server. The path must already exist. When the server starts, it will register itself by creating a subnode of the path with a name consisting of it's address. (You can also specify a ZooKeeper session timeout, in milliseconds, with a ``session-timeout`` option.) When specifying the ZEO address, you can leave off the port and the operating system will assign it for you. To start the server, use the ``zkrunzeo`` script:: $ bin/zkrunzeo -C FILENAME .. test >>> import zc.zkzeo.runzeo, zc.zk >>> stop = zc.zkzeo.runzeo.test( ... server_conf) >>> zk = zc.zk.ZooKeeper('zookeeper.example.com:2181') >>> zk.print_tree('/databases/demo') /demo /127.0.0.1:56824 pid = 88841 >>> stop().exception >>> zk.print_tree('/databases/demo') /demo where ``FILENAME`` is the name of the configuration file you created. Including a ``zc.monitor`` monitoring server -------------------------------------------- The `zc.monitor <http://pypi.python.org/pypi/zc.monitor>`_ package provides a simple extensible command server for gathering monitoring data or providing run-time control of servers. If ``zc.monitor`` is in the Python path, ``zc.zkzeo`` can start a monitor server and make it's address available as the ``monitor`` property of of a server's ephemeral port. To request this, we use a ``monitor-server`` option in the ``zookeeper`` section:: <zeo> address 127.0.0.1 </zeo> <zookeeper> connection zookeeper.example.com:2181 path /databases/demo monitor-server 127.0.0.1 </zookeeper> <filestorage> path demo.fs </filestorage> .. -> server_conf >>> stop = zc.zkzeo.runzeo.test(server_conf) The value is the address to listen on. With the configuration above, if we started the server and looked at the ZooKeeper tree for '/databases/demo' using the ``zc.zk`` package, we'd see something like the following:: >>> zk.print_tree('/databases/demo') /demo /127.0.0.1:64211 monitor = u'127.0.0.1:11976' pid = 5082 .. verify that we can connect to the monitor: >>> [monitor_addr] = zk.get_children('/databases/demo') >>> host, port = monitor_addr.split(':') >>> import socket, time >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> sock.settimeout(.5) >>> sock.connect((host, int(port))) >>> sock.close() >>> _ = stop() >>> import zc.monitor >>> zc.monitor.last_listener.close() You can also specify a unix-domain socket name:: <zeo> address 127.0.0.1 </zeo> <zookeeper> connection zookeeper.example.com:2181 path /databases/demo monitor-server ./monitor.sock </zookeeper> <filestorage> path demo.fs </filestorage> .. -> server_conf We need to clear the zc.zk monitor data so we have a clean monitoring test below. This is an artifact of running multiple servers in one process. >>> import zc.zk.monitor >>> del zc.zk.monitor._servers[:] >>> stop = zc.zkzeo.runzeo.test(server_conf) When using a unix-domain socket, the monitor address isn't included in the tree: >>> zk.print_tree('/databases/demo') /demo /127.0.0.1:64213 pid = 5082 .. verify that we can connect to the monitor: >>> sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) >>> sock.settimeout(.5) >>> sock.connect('./monitor.sock') Some notes on the monitor server: - A monitor server won't be useful unless you've registered some command plugins. - ``zc.monitor`` isn't a dependency of ``zc.zkzeoc`` and won't be in the Python path unless you install it. Monitoring ---------- The zkzeo package provides a Nagios plugin. The plugin takes a ZooKeeper connection string and path to look up a ZEO server at (using the zc.zk service-registry framework). For example, to monitor the server defined above:: zkzeo-nagios zookeeper.example.com:2181 /databases/demo .. -> src >>> import pkg_resources >>> monitor = pkg_resources.load_entry_point( ... 'zc.zkzeo', 'console_scripts', 'zkzeo-nagios') >>> monitor(src.strip().split()[1:]) Empty storage u'1' 1 The zkzeo nagios monitor supports the same options as the ZEO nagios monitor, so for example to get full metrics:: zkzeo-nagios -m -s statusfile zookeeper.example.com:2181 /databases/demo .. -> src >>> monitor(src.strip().split()[1:]) Empty storage u'1'|active_txns=0 | connections=0 waiting=0 1 >>> monitor(src.strip().split()[1:]) Empty storage u'1'|active_txns=0 | connections=0 waiting=0 aborts=0.0 commits=0.0 conflicts=0.0 conflicts_resolved=0.0 loads=0.0 stores=0.0 1 Sometimes, there may be multiple servers registered at the same path, for example if servers are replicated. When monitoring a single server, you need to know which one to check. If you've a monitor-server for your ZEO process, as we did above, then you can use that to determine which one to use. Just provide the monitor server address:: zkzeo-nagios -m -M ./monitor.sock zookeeper.example.com:2181 /databases/demo .. -> src >>> monitor(src.strip().split()[1:]) Empty storage u'1'|active_txns=0 | connections=0 waiting=0 1 There's also a helper function useful for other monitors: >>> import zc.zkzeo.nagios >>> [zc.zkzeo.nagios.find_server( ... 'zookeeper.example.com:2181', ... '/databases/demo', ... None)] == zk.get_children('/databases/demo') True >>> [zc.zkzeo.nagios.find_server( ... 'zookeeper.example.com:2181', ... '/databases/demo', ... './monitor.sock')] == zk.get_children('/databases/demo') True Defining ZEO clients ==================== You can define a client in two ways, from Python and using a configuration file. Defining ZEO clients with Python -------------------------------- From Python, use ``zc.zkzeo.client``:: >>> import zc.zkzeo >>> client = zc.zkzeo.client( ... 'zookeeper.example.com:2181', '/databases/demo', ... max_disconnect_poll=1) You pass a ZooKeeper connection string and a path. The ``Client`` constructor will create a client storage with addresses found as sub-nodes of the given path and it will adjust the client-storage addresses as nodes are added and removed as children of the path. You can pass all other ``ZEO.ClientStorage.ClientStorage`` arguments, except the address, as additional positional and keyword arguments. Database and connection convenience functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You're usually not really interested in getting a storage object. What you really want is a database object:: >>> db = zc.zkzeo.DB( ... 'zookeeper.example.com:2181', '/databases/demo', ... max_disconnect_poll=1) or often, just a database connection:: >>> conn = zc.zkzeo.connection( ... 'zookeeper.example.com:2181', '/databases/demo', ... max_disconnect_poll=1) .. test >>> exconn = conn Defining ZEO clients in configuration files ------------------------------------------- In configuration files, use a ``zkzeoclient`` storage section:: %import zc.zkzeo <zodb> <zkzeoclient> zookeeper zookeeper.example.com:2181 server /databases/demo max-disconnect-poll 1 </zkzeoclient> </zodb> .. -> conf The options for ``zkzeoclient`` are the same as for the standard ZODB ``zeoclient`` section, except: - There's an extra required ``zookeeper`` option used to provide a ZooKeeper connection string. - There can be only one ``server`` option and it is used to supply the path in ZooKeeper where addresses may be found. .. test Double check the clients are working by opening a connection and making sure we see changes: >>> import ZODB.config >>> db_from_config = ZODB.config.databaseFromString(conf) >>> with db_from_config.transaction() as conn: ... conn.root.x = 1 >>> import ZODB >>> db_from_py = ZODB.DB(client) >>> with db_from_py.transaction() as conn: ... print conn.root() {'x': 1} >>> with db.transaction() as conn: ... print conn.root() {'x': 1} >>> import transaction >>> with transaction.manager: ... print exconn.root() {'x': 1} When we stop the storage server, we'll get warnings from zc.zkzeo, the clients will disconnect and will have no addresses: >>> import zope.testing.loggingsupport >>> handler = zope.testing.loggingsupport.Handler('zc.zkzeo') >>> handler.install() >>> [old_addr] = zk.get_children('/databases/demo') >>> stop().exception >>> zc.monitor.last_listener.close() >>> from zope.testing.wait import wait >>> wait(lambda : not client.is_connected()) >>> wait(lambda : not db_from_config.storage.is_connected()) >>> wait(lambda : not db.storage.is_connected()) >>> wait(lambda : not exconn.db().storage.is_connected()) >>> print handler zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo WARNING No addresses from <zookeeper.example.com:2181/databases/demo> >>> handler.clear() Looking at the client manager, we see that the address list is now empty: >>> client._rpc_mgr <ConnectionManager for []> Let's sleep for a while to make sure we can wake up. Of course, we won't sleep *that* long, it's a test. >>> import time >>> time.sleep(9) Now, we'll restart the server and clients will reconnect >>> stop = zc.zkzeo.runzeo.test(server_conf) >>> [addr] = zk.get_children('/databases/demo') >>> addr != old_addr True >>> print zk.export_tree('/databases/demo', ephemeral=True), /demo /127.0.0.1:56837 pid = 88841 >>> wait(db_from_config.storage.is_connected) >>> with db_from_config.transaction() as conn: ... conn.root.x = 2 >>> wait(db_from_py.storage.is_connected, timeout=22) >>> time.sleep(.1) >>> with db_from_py.transaction() as conn: ... print conn.root() {'x': 2} >>> wait(db.storage.is_connected, timeout=22) >>> time.sleep(.1) >>> with db.transaction() as conn: ... print conn.root() {'x': 2} >>> wait(exconn.db().storage.is_connected, timeout=22) >>> time.sleep(.1) >>> with transaction.manager: ... print exconn.root() {'x': 2} >>> print handler # doctest: +NORMALIZE_WHITESPACE zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] zc.zkzeo WARNING OK: Addresses from <zookeeper.example.com:2181/databases/demo> zc.zkzeo INFO Addresses from <zookeeper.example.com:2181/databases/demo>: ['127.0.0.1:52649'] >>> zk.close() >>> handler.uninstall() >>> db_from_py.close() >>> db_from_config.close() >>> db.close() >>> exconn.close() >>> stop().exception >>> zc.monitor.last_listener.close() Change History ============== 1.0.1 (2015-01-11) ------------------ Fixed packaging problem (of course). 1.0.0 (2015-01-11) ------------------ - Updated to work with ZEO/ZODB rather than ZODB3. - Added a Nagios monitoring plugin, the script zkzeo-nagios 0.3.2 (2012-07-10) ------------------ - Fixed: Didn't work with explicit configuration of port 0, which is recently supported by ZConfig. 0.3.1 (2012-06-26) ------------------ - Fixed: setting a monitor server on a unix-domain socket didn't work. 0.3.0 (2012-02-07) ------------------ - Added a static extra to force a dependency on ``zc-zookeeper-static``. - In test mode, use a shorter asyncore loop timeout to make the server shut down faster. - Fixed: zc.zkzeo depended on ``zc.zk [static]``, which forced installation of ``zc-zookeeper-static``, which should be optional. - Fixed: tests didn't pass with a recent change in handling of registration with empty host names in ``zc.zk``. - Fixed: Packaging: distribute can't install distributions with symlinks, so stopped using symlinks in distribution. 0.2.1 (2011-12-14) ------------------ - Fixed bug: The ``path`` key on the ``zookeeper`` server-configuration section was required, and shouldn't have been. 0.2.0 (2011-12-13) ------------------ - Register the host name from the ZEO address setting with ZooKeeper. (This is often an empty string, which ``zc.zk`` turns into the fully-quelified domain name.) - Fixed bug in handling the monitor-server. The actuall address setting was ignored. 0.1.1 (2011-12-12) ------------------ - Fixed a packaging bug. 0.1.0 (2011-12-11) ------------------ Initial release.
zc.zkzeo
/zc.zkzeo-1.0.1.tar.gz/zc.zkzeo-1.0.1/README.txt
README.txt
from __future__ import print_function ############################################################################## # # Copyright (c) 2011 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """%prog [options] zookeeper path Where: zookeeper A ZooKeeper connection string path A ZooKeeper path at which to look up a ZEO server """ import json import optparse import os import re import socket import struct import sys import time import zc.zk import ZEO.nagios zc_monitor_help = """zc.monitor server address to use to look up a server When multiple servers are are registered at a ZooKeeper path, we need to know which one to monitor. If a zkzeo server was condigured with a monitor server, we can connect to the monitor server to determine the address to monitor. """ def connect(addr): m = re.match(r'\[(\S+)\]:(\d+)$', addr) if m: addr = m.group(1), int(m.group(2)) s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: m = re.match(r'(\S+):(\d+)$', addr) if m: addr = m.group(1), int(m.group(2)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(addr) fp = s.makefile() return fp, s def find_server(zookeeper, path, monitor_address): server = None if monitor_address: try: fp, s = connect(monitor_address) except socket.error as err: return print("Can't connect %s" % err) s.settimeout(1.0) fp.write('servers %s\n' % path) fp.flush() data = fp.read().strip() fp.close(); s.close() if data.lower().startswith("invalid "): return print(data + ' at %r' % monitor_address) servers = list(set(data.split())) # dedup if not servers: return print("No servers at: %r" % monitor_address) if len(servers) > 1: return print("Too many servers, %r, at: %r" % (sorted(servers), monitor_address)) server = servers[0] zk = zc.zk.ZK(zookeeper) children = zk.get_children(path) zk.close() if server: host, port = server.split(':') if host: children = [c for c in children if c == server] else: children = [c for c in children if c.split(':')[1] == port] if len(children) != 1: return print("Couldn't find server in ZooKeeper") addr = children[0] return addr def main(args=None): if args is None: args = sys.argv[1:] parser = optparse.OptionParser(__doc__) parser.add_option( '-m', '--output-metrics', action="store_true", help="Output metrics.", ) parser.add_option( '-s', '--status-path', help="Path to status file, needed to get rate metrics", ) parser.add_option( '-u', '--time-units', type='choice', default='minutes', choices=['seconds', 'minutes', 'hours', 'days'], help="Time unit for rate metrics", ) parser.add_option('-M', '--zc-monitor-address', help=zc_monitor_help) (options, args) = parser.parse_args(args) [zk, path] = args addr = find_server(zk, path, options.zc_monitor_address) if not addr: return 2 return ZEO.nagios.check( addr, options.output_metrics, options.status_path, options.time_units)
zc.zkzeo
/zc.zkzeo-1.0.1.tar.gz/zc.zkzeo-1.0.1/src/zc/zkzeo/nagios.py
nagios.py
import logging import time import zc.zk import ZEO.ClientStorage import threading logger = logging.getLogger('zc.zkzeo') def client(zkaddr, path, *args, **kw): zk = zc.zk.ZooKeeper(zkaddr) addresses = zk.children(path) wait = kw.get('wait', kw.get('wait_for_server_on_startup', True)) client = ZEO.ClientStorage.ClientStorage( _wait_addresses(addresses, parse_addr, zkaddr, path, wait), *args, **kw) return _client(addresses, client, zkaddr, path) def parse_addr(addr): host, port = addr.split(':') return host, int(port) def _client(addresses, client, zkaddr, path): new_addr = getattr(client, 'new_addr', None) if new_addr is None: # Pre 3.11 client. We need to make our own new_addr. # This is ugly. Don't look. :( def new_addr(addr): manager = client._rpc_mgr manager.addrlist = manager._parse_addrs(addr) with manager.cond: if manager.thread is not None: manager.thread.addrlist = manager.addrlist warned = set() @addresses def changed(addresses): addrs = map(parse_addr, addresses) if addrs: if warned: logger.warning('OK: Addresses from <%s%s>', zkaddr, path) warned.clear() logger.info('Addresses from <%s%s>: %r', zkaddr, path, sorted(addresses)) else: logger.warning('No addresses from <%s%s>', zkaddr, path) warned.add(1) new_addr(addrs) client.zookeeper_addresses = addresses return client def _wait_addresses(addresses, transform, zkaddr, path, wait): n = 0 while 1: result = [transform(addr) for addr in addresses] if result: if n: logger.warning("OK: Got addresses from <%s%s>", zkaddr, path) return result if not wait: return result if (n%30000) == 0: # warn every few minutes logger.warning("No addresses from <%s%s>", zkaddr, path) time.sleep(.01) n += 1 class ZConfig: def __init__(self, config): self.config = config self.name = config.getSectionName() def open(self): import ZConfig.datatypes import ZODB.config zkaddr = self.config.zookeeper zk = zc.zk.ZooKeeper(zkaddr) paths = [server.address for server in self.config.server] if len(paths) > 1: raise TypeError("Only one server option is allowed") path = paths[0] if not isinstance(path, basestring) or not path[0] == '/': raise TypeError("server must be a ZooKeeper path, %r" % path) addresses = zk.children(path) self.config.server = _wait_addresses( addresses, ZConfig.datatypes.SocketAddress, zkaddr, path, self.config.wait) client = ZODB.config.ZEOClient(self.config).open() return _client(addresses, client, zkaddr, path)
zc.zkzeo
/zc.zkzeo-1.0.1.tar.gz/zc.zkzeo-1.0.1/src/zc/zkzeo/_client.py
_client.py
import asyncore import os import select import sys import threading import time import zc.thread import zc.zk import ZEO.runzeo class Options(ZEO.runzeo.ZEOOptions): __doc__ = ZEO.runzeo.__doc__ + """ This command supports registering a server with ZooKeeper. """ schemadir = os.path.dirname(__file__) def __init__(self): ZEO.runzeo.ZEOOptions.__init__(self) self.add('zkconnection', 'zookeeper.connection') self.add('zkpath', 'zookeeper.path') self.add('zookeeper_session_timeout', 'zookeeper.session_timeout') self.add('monitor_server', 'zookeeper.monitor_server') class ZKServer(ZEO.runzeo.ZEOServer): __zk = __testing = __using_dynamic_port = None def create_server(self): ZEO.runzeo.ZEOServer.create_server(self) if self.__testing is not None: # Make the loop dies quickly when we close the storage # XXX should find a way to do this wo monkey patching. :/ self.server.loop = ( lambda : asyncore.loop(.1, map=self.server.socket_map)) if not self.options.zkpath: return addr = (self.server.addr[0], self.server.dispatcher.socket.getsockname()[1]) def register(): props = {} if self.options.monitor_server: global zc import zc.monitor, zope.configuration.xmlconfig zope.configuration.xmlconfig.file('monitor.zcml', package=zc.zk) zc.monitor.register_basics() maddr = self.options.monitor_server.address if isinstance(maddr, tuple) and maddr[1] is None: maddr = maddr[0], 0 maddr = zc.monitor.start(maddr) if isinstance(maddr, tuple): props['monitor'] = "%s:%s" % maddr self.__zk.register_server(self.options.zkpath, addr[:2], **props) if self.__testing is not None: self.__testing() if self.__using_dynamic_port: self.__zk = zc.zk.ZooKeeper( self.options.zkconnection, self.options.zookeeper_session_timeout, ) register() return @zc.thread.Thread def zookeeper_registration_thread(): self.__zk = zc.zk.ZooKeeper( self.options.zkconnection, self.options.zookeeper_session_timeout, wait = True, ) register() def clear_socket(self): if self.__zk is not None: self.__zk.close() ZEO.runzeo.ZEOServer.clear_socket(self) def check_socket(self): if not self.options.address[1]: self.options.address = self.options.address[0], 0 self.__using_dynamic_port = True return ZEO.runzeo.ZEOServer.check_socket(self) def setup_signals(self): if self.__testing is not None: return ZEO.runzeo.ZEOServer.setup_signals(self) def setup_default_logging(self): if self.__testing is not None: return ZEO.runzeo.ZEOServer.setup_default_logging(self) def main(args=None, testing=None): if args is None: args = sys.argv[1:] options = Options() options.realize(args) s = ZKServer(options) s._ZKServer__testing = testing if testing is not None: return s s.main() def test(config, storage=None, zookeeper=None, threaded=True): """Run a server in a thread, mainly for testing. """ import tempfile if '\n' not in config: # It's just a path if storage is None: storage = '<mappingstorage>\n</mappingstorage>' elif storage.endswith('.fs'): storage = '<filestorage>\npath %s\n</filestorage>' % storage config = """ <zeo> address 127.0.0.1 </zeo> <zookeeper> connection %s path %s </zookeeper> %s """ % (zookeeper, config, storage) fd, confpath = tempfile.mkstemp() os.write(fd, config) os.close(fd) event = threading.Event() server = main(['-C', confpath], event.set) os.remove(confpath) run_zeo_server_for_testing = None def stop(): server.server.close() assert not server.server.dispatcher._map, server.server.dispatcher._map if run_zeo_server_for_testing is not None: run_zeo_server_for_testing.join(11) assert not run_zeo_server_for_testing.is_alive() return run_zeo_server_for_testing if not threaded: try: return server.main() except: stop() raise @zc.thread.Thread def run_zeo_server_for_testing(): import asyncore try: server.main() except select.error: pass except: import logging logging.getLogger(__name__+'.test').exception( 'wtf %r', sys.exc_info()[1]) stop.server = server # :) event.wait(1) return stop
zc.zkzeo
/zc.zkzeo-1.0.1.tar.gz/zc.zkzeo-1.0.1/src/zc/zkzeo/runzeo.py
runzeo.py
================================================= zope.server wrapper that registers with ZooKeeper ================================================= ``zc.zkzopeserver`` provides a wrapper for the zope.server WSGI runner that registers with ZooKeeper. By registering with ZooKeeper, you can let the operating system assign ports and have clients find your server by looking in ZooKeeper. Basic Usage =========== The wrapper is used in a past-deploy configuration file:: [server:main] use = egg:zc.zkzopeserver zookeeper = zookeeper.example.com:2181 path = /fooservice/providers .. -> server_config The wrapper supports the following options: zookeeper required ZooKeeper connection string path required path at which to register your server Your server is registered by adding a ZooKeeper ephemeral node as a child of the path with the server address as the name. host host name or ip to listen on, defaulting to '' port The port to listen on, defaulting to 0 session_timeout A ZooKeeper session timeout in milliseconds threads The size of the thread pool, defaulting to 1 monitor_server A ``zc.monitor`` server address. The value is an address of the form HOST:PORT. See `Monitor server`_ below. (Host can be empty to listen on all interfaces.) loggers Logging configuration. This can be one of: - A logging level name (CRITICAL, ERROR, WARNING, INFO, or DEBUG), or - A ZConfig loggers-definition string. If the configuration includes format strings, you'll need to use double dollar signs rather than %, as in:: format $$(message)s This is necessary due to the use of string formats in the Paste Deployment configuration syntax. .. test >>> import ConfigParser, StringIO >>> parser = ConfigParser.RawConfigParser() >>> parser.readfp(StringIO.StringIO(server_config)) >>> kw = dict(parser.items('server:main')) >>> import zope.testing.loggingsupport >>> loghandler = zope.testing.loggingsupport.InstalledHandler( ... 'zc.zkzopeserver') >>> import pkg_resources >>> dist = kw.pop('use').split(':')[1] >>> [run] = [v.load() ... for v in pkg_resources.get_entry_map( ... 'zc.zkzopeserver', 'paste.server_runner' ... ).values()] >>> import wsgiref.simple_server, zc.thread >>> @zc.thread.Thread ... def server(): ... run(wsgiref.simple_server.demo_app, {}, **kw) >>> import zc.zkzopeserver >>> zc.zkzopeserver.event_for_testing.wait(1) >>> import urllib, zc.zk >>> zk = zc.zk.ZooKeeper('zookeeper.example.com:2181') >>> [port] = [int(c.split(':')[1]) ... for c in zk.get_children('/fooservice/providers')] >>> print urllib.urlopen('http://127.0.0.1:%s/' % port).read() ... # doctest: +ELLIPSIS Hello world! ... >>> zc.zkzopeserver.stop_for_testing(server) >>> zk.get_children('/fooservice/providers') [] A SIGTERM signal handler is installed: >>> import signal >>> [sig, handler] = signal.signal.call_args[0] >>> sig == signal.SIGTERM True >>> try: handler(sig, None) ... except SystemExit, v: print v 0 >>> signal.getsignal.return_value = handler >>> signal.signal.reset_mock() The fact that a handler was installed is logged, as is the address: >>> print loghandler zc.zkzopeserver INFO Installed SIGTERM handler zc.zkzopeserver INFO Serving on :35177 >>> loghandler.clear() Nothing was done w logging: >>> import logging >>> logging.basicConfig.call_args >>> import ZConfig >>> ZConfig.configureLoggers.call_args Monitor server ============== The `zc.monitor <http://pypi.python.org/pypi/zc.monitor>`_ package provides a simple extensible command server for gathering monitoring data or providing run-time control of servers. If ``zc.monitor`` is in the Python path, ``zc.zkzopeserver`` can start a monitor server and make it's address available as the ``monitor`` property of a server's ephemeral port. To see how this works, let's update the earler example:: [server:main] use = egg:zc.zkzopeserver zookeeper = zookeeper.example.com:2181 path = /fooservice/providers monitor_server = 127.0.0.1:0 .. -> server_config When our web server is running, the ``/fooservice/providers`` node would look something like:: /providers /1.2.3.4:61181 monitor = u'127.0.0.1:61182' pid = 4525 .. -> expected_tree >>> parser = ConfigParser.RawConfigParser() >>> parser.readfp(StringIO.StringIO(server_config)) >>> kw = dict(parser.items('server:main')) >>> del kw['use'] >>> import zope.testing.loggingsupport >>> handler = zope.testing.loggingsupport.InstalledHandler('zc.tracelog') >>> @zc.thread.Thread ... def server(): ... run(wsgiref.simple_server.demo_app, {}, **kw) >>> zc.zkzopeserver.event_for_testing.wait(1) >>> [port] = [int(c.split(':')[1]) ... for c in zk.get_children('/fooservice/providers')] >>> print urllib.urlopen('http://127.0.0.1:%s/' % port).read() ... # doctest: +ELLIPSIS Hello world! ... >>> import re, zope.testing.renormalizing >>> checker = zope.testing.renormalizing.RENormalizing([ ... (re.compile('pid = \d+'), 'pid = 999'), ... (re.compile('1.2.3.4:\d+'), '1.2.3.4:99999'), ... (re.compile('127.0.0.1:\d+'), '1.2.3.4:99999'), ... ]) >>> actual_tree = zk.export_tree('/fooservice/providers', True) >>> checker.check_output(expected_tree.strip(), actual_tree.strip(), 0) True >>> zc.zkzopeserver.stop_for_testing(server) >>> zk.get_children('/fooservice/providers') [] >>> print handler <BLANKLINE> >>> handler.uninstall() The signal handler wasn't set again, as it was already set: >>> signal.signal.call_args >>> print loghandler zc.zkzopeserver INFO Serving on :46834 >>> loghandler.uninstall() Some notes on the monitor server: - A monitor server won't be useful unless you've registered some command plugins. - ``zc.monitor`` isn't a dependency of ``zc.zkzopeserver`` and won't be in the Python path unless you install it. ``zc.zservertracslog`` integration ================================== The package ``zc.zservertracelog`` extends zope.server to provide support for "trace" logs that have multiple log entries per web request as a request goes through various stages. If you want to use ``zc.zservertraeslog`` with ``zc.zkzopeserver``, make sure ``zc.zservertracelog`` is in your Python path and include the ``zservertracelog`` option in your server section:: [server:main] use = egg:zc.zkzopeserver zookeeper = zookeeper.example.com:2181 path = /fooservice/providers monitor_server = 127.0.0.1:0 zservertracelog = true .. -> server_config >>> parser = ConfigParser.RawConfigParser() >>> parser.readfp(StringIO.StringIO(server_config)) >>> kw = dict(parser.items('server:main')) >>> del kw['use'] >>> handler = zope.testing.loggingsupport.InstalledHandler('zc.tracelog') >>> @zc.thread.Thread ... def server(): ... run(wsgiref.simple_server.demo_app, {}, **kw) >>> zc.zkzopeserver.event_for_testing.wait(1) >>> [port] = [int(c.split(':')[1]) ... for c in zk.get_children('/fooservice/providers')] >>> print urllib.urlopen('http://127.0.0.1:%s/' % port).read() ... # doctest: +ELLIPSIS Hello world! ... >>> zc.zkzopeserver.stop_for_testing(server) >>> print handler zc.tracelog INFO B 4358585232 2012-01-18 15:31:31.050680 GET / zc.tracelog INFO I 4358585232 2012-01-18 15:31:31.050887 0 zc.tracelog INFO C 4358585232 2012-01-18 15:31:31.051068 zc.tracelog INFO A 4358585232 2012-01-18 15:31:31.051580 200 ? zc.tracelog INFO E 4358585232 2012-01-18 15:31:31.051692 >>> handler.uninstall() Change History ============== 0.3.0 (2012-02-02) ------------------ - Added logging-configuration support. - Fixed: servers were registered with the host information returned by socket.getsockname(), which was unhelpful. - Fixed: Killing a server (with SIGTERM) didn't shut down the ZooKeeper connection cleanly, causing a delay in removing registered ephemeral nodes. 0.2.0 (2012-01-18) ------------------ Added optional support for using zc.zservertracelog to generate trace logs. 0.1.0 (2011-12-11) ------------------ Initial release .. test cleanup >>> zk.close()
zc.zkzopeserver
/zc.zkzopeserver-1.3.2.tar.gz/zc.zkzopeserver-1.3.2/src/zc/zkzopeserver/README.txt
README.txt
import asyncore import logging import re import signal import sys import threading import zc.zk import zope.server.dualmodechannel import zope.server.taskthreads logger = logging.getLogger(__name__) event_for_testing = threading.Event() server_for_testing = None # Note to the reader and tester # ----------------------------- # zope.server and zc.monitor were, for better or worser, designed to # be used as or in main programs. They expect to be instantiated # exactly once and to be used through the end of the program. Neither # provide a clean shutdown mechanism. In normal usage, this probably # isn't a problem, but it's awkward for testing. # # We've worked around this by providing here a way to shutdown a # running server, assuming there is only one at a time. :/ See the 3 # "_for_testing" variables. We've leveraged a similar mechanism in # zc.monitor. See the use of last_listener below. def stop_for_testing(thread=None): zope.server.dualmodechannel.the_trigger.pull_trigger( server_for_testing.close) event_for_testing.clear() if thread is not None: thread.join(1) def run(wsgi_app, global_conf, zookeeper, path, session_timeout=None, name=__name__, host='', port=0, threads=1, monitor_server=None, zservertracelog=None, loggers=None, ): port = int(port) threads = int(threads) if loggers: if re.match('\w+$', loggers) and hasattr(logging, loggers): logging.basicConfig(level=getattr(logging, loggers)) else: import ZConfig ZConfig.configureLoggers(loggers.replace('$$(', '%(')) task_dispatcher = zope.server.taskthreads.ThreadedTaskDispatcher() task_dispatcher.setThreadCount(threads) if zservertracelog == 'true': from zc.zservertracelog.tracelog import Server else: from zope.server.http.wsgihttpserver import WSGIHTTPServer as Server server = Server(wsgi_app, name, host, port, task_dispatcher=task_dispatcher) props = {} if monitor_server: mhost, mport = monitor_server.rsplit(':', 1) global zc import zc.monitor props['monitor'] = "%s:%s" % zc.monitor.start((mhost, int(mport))) server.ZooKeeper = zc.zk.ZooKeeper( zookeeper, session_timeout and int(session_timeout)) addr = "%s:%s" % (host, server.socket.getsockname()[1]) server.ZooKeeper.register_server(path, addr, **props) map = asyncore.socket_map poll_fun = asyncore.poll global server_for_testing server_for_testing = server event_for_testing.set() if not signal.getsignal(signal.SIGTERM): signal.signal(signal.SIGTERM, lambda *a: sys.exit(0)) logger.info('Installed SIGTERM handler') try: logger.info('Serving on %s', addr) while server.accepting: poll_fun(30.0, map) finally: server.ZooKeeper.close() if monitor_server: zc.monitor.last_listener.close()
zc.zkzopeserver
/zc.zkzopeserver-1.3.2.tar.gz/zc.zkzopeserver-1.3.2/src/zc/zkzopeserver/__init__.py
__init__.py
========= Changes ========= 1.2.0 (2017-01-20) ================== - Add support for Python 3.6 and PyPy. - Test with both ZODB/ZEO 4 and ZODB/ZEO 5. Note that ServerZlibStorage cannot be used in a ZODB 5 Connection (e.g., client-side, which wouldn't make sense :-]). (https://github.com/zopefoundation/zc.zlibstorage/issues/5). - Close the underlying iterator used by the ``iterator`` wrapper when it is closed. (https://github.com/zopefoundation/zc.zlibstorage/issues/4) 1.1.0 (2016-08-03) ================== - Fixed an incompatibility with ZODB5. The previously optional and ignored version argument to the database ``invalidate`` method is now disallowed. - Drop Python 2.6, 3.2, and 3.3 support. Added Python 3.4 and 3.5 support. 1.0.0 (2015-11-11) ================== - Python 3 support contributed by Christian Tismer. 0.1.1 (2010-05-26) ================== - Fixed a packaging bug. 0.1.0 (2010-05-20) ================== Initial release
zc.zlibstorage
/zc.zlibstorage-1.2.0.tar.gz/zc.zlibstorage-1.2.0/CHANGES.rst
CHANGES.rst
============================================================= ZODB storage wrapper for zlib compression of database records ============================================================= The ``zc.zlibstorage`` package provides ZODB storage wrapper implementations that provides compression of database records. See src/zc/zlibstorage/README.txt. .. image:: https://api.travis-ci.org/zopefoundation/zc.zlibstorage.png?branch=master :target: https://travis-ci.org/zopefoundation/zc.zlibstorage :alt: Build Status
zc.zlibstorage
/zc.zlibstorage-1.2.0.tar.gz/zc.zlibstorage-1.2.0/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zc.zlibstorage
/zc.zlibstorage-1.2.0.tar.gz/zc.zlibstorage-1.2.0/bootstrap.py
bootstrap.py
============================================================= ZODB storage wrapper for zlib compression of database records ============================================================= The ``zc.zlibstorage`` package provides ZODB storage wrapper implementations that provides compression of database records. .. contents:: Usage ===== The primary storage is ``zc.zlibstorage.ZlibStorage``. It is used as a wrapper around a lower-level storage. From Python, it is constructed by passing another storage, as in:: import ZODB.FileStorage, zc.zlibstorage storage = zc.zlibstorage.ZlibStorage( ZODB.FileStorage.FileStorage('data.fs')) .. -> src >>> import zlib >>> exec(src) >>> data = b'x'*100 >>> storage.transform_record_data(data) == b'.z'+zlib.compress(data) True >>> storage.close() When using a ZODB configuration file, the zlibstorage tag is used:: %import zc.zlibstorage <zodb> <zlibstorage> <filestorage> path data.fs </filestorage> </zlibstorage> </zodb> .. -> src >>> import ZODB.config >>> db = ZODB.config.databaseFromString(src) >>> db.storage.transform_record_data(data) == b'.z'+zlib.compress(data) True >>> db.close() Note the ``%import`` used to load the definition of the ``zlibstorage`` tag. Use with ZEO ============ When used with a ZEO ClientStorage, you'll need to use a server zlib storage on the storage server. This is necessary so that server operations that need to get at uncompressed record data can do so. This is accomplished using the ``serverzlibstorage`` tag in your ZEO server configuration file:: %import zc.zlibstorage <zeo> address 8100 </zeo> <serverzlibstorage> <filestorage> path data.fs </filestorage> </serverzlibstorage> .. -> src >>> src = src[:src.find('<zeo>')]+src[src.find('</zeo>')+7:] >>> storage = ZODB.config.storageFromString(src) >>> storage.transform_record_data(data) == b'.z'+zlib.compress(data) True >>> storage.__class__.__name__ 'ServerZlibStorage' >>> storage.close() Applying compression on the client this way is attractive because, in addition to reducing the size of stored database records on the server, you also reduce the size of records sent from the server to the client and the size of records stored in the client's ZEO cache. Decompressing only ================== By default, records are compressed when written to the storage and uncompressed when read from the storage. A ``compress`` option can be used to disable compression of records but still uncompress compressed records if they are encountered. Here's an example from in Python:: import ZODB.FileStorage, zc.zlibstorage storage = zc.zlibstorage.ZlibStorage( ZODB.FileStorage.FileStorage('data.fs'), compress=False) .. -> src >>> exec(src) >>> storage.transform_record_data(data) == data True >>> storage.close() and using the configurationb syntax:: %import zc.zlibstorage <zodb> <zlibstorage> compress false <filestorage> path data.fs </filestorage> </zlibstorage> </zodb> .. -> src >>> db = ZODB.config.databaseFromString(src) >>> db.storage.transform_record_data(data) == data True >>> db.close() This option is useful when deploying the storage when there are multiple clients. If you don't want to update all of the clients at once, you can gradually update all of the clients with a zlib storage that doesn't do compression, but recognizes compressed records. Then, in a second phase, you can update the clients to compress records, at which point, all of the clients will be able to read the compressed records produced. Compressing entire databases ============================ One way to compress all of the records in a database is to copy data from an uncompressed database to a compressed one, as in:: import ZODB.FileStorage, zc.zlibstorage orig = ZODB.FileStorage.FileStorage('data.fs') new = zc.zlibstorage.ZlibStorage( ZODB.FileStorage.FileStorage('data.fs-copy')) new.copyTransactionsFrom(orig) orig.close() new.close() .. -> src >>> conn = ZODB.connection('data.fs', create=True) >>> conn.root.a = conn.root().__class__([(i,i) for i in range(1000)]) >>> conn.root.b = conn.root().__class__([(i,i) for i in range(2000)]) >>> import transaction >>> transaction.commit() >>> conn.close() >>> exec(src) >>> new = zc.zlibstorage.ZlibStorage( ... ZODB.FileStorage.FileStorage('data.fs-copy')) >>> conn = ZODB.connection(new) >>> dict(conn.root.a) == dict([(i,i) for i in range(1000)]) True >>> dict(conn.root.b) == dict([(i,i) for i in range(2000)]) True >>> import ZODB.utils >>> for i in range(3): ... if not new.base.load(ZODB.utils.p64(i))[0][:2] == b'.z': ... print('oops {}'.format(i)) >>> len(new) 3 >>> conn.close() Record prefix ============= Compressed records have a prefix of ".z". This allows a database to have a mix of compressed and uncompressed records. Stand-alone Compression and decompression functions =================================================== In anticipation of wanting to plug the compression and decompression logic into other tools without creating storages, the functions used to compress and uncompress data records are available as ``zc.zlibstorage`` module-level functions: ``compress(data)`` Compress the given data if: - it is a string more than 20 characters in length, - it doesn't start with the compressed-record marker, ``b'.z'``, and - the compressed size is less the original. The compressed (or original) data are returned. ``decompress(data)`` Decompress the data if it is compressed. The decompressed (or original) data are returned. .. basic sanity check :) >>> _ = (zc.zlibstorage.compress, zc.zlibstorage.decompress)
zc.zlibstorage
/zc.zlibstorage-1.2.0.tar.gz/zc.zlibstorage-1.2.0/src/zc/zlibstorage/README.txt
README.txt
import zlib import ZODB.interfaces import zope.interface @zope.interface.implementer( ZODB.interfaces.IStorageWrapper, ) class ZlibStorage(object): copied_methods = ( 'close', 'getName', 'getSize', 'history', 'isReadOnly', 'lastTransaction', 'new_oid', 'sortKey', 'tpc_abort', 'tpc_begin', 'tpc_finish', 'tpc_vote', 'loadBlob', 'openCommittedBlobFile', 'temporaryDirectory', 'supportsUndo', 'undo', 'undoLog', 'undoInfo', ) def __init__(self, base, *args, **kw): self.base = base # Sorry for the lambda hijinks below, but I really want to use # the name "compress" for both the module-level function name # and for the argument to this function. :/ if (lambda compress=True: compress)(*args, **kw): self._transform = compress # Refering to module func below! else: self._transform = lambda data: data self._untransform = decompress for name in self.copied_methods: v = getattr(base, name, None) if v is not None: setattr(self, name, v) zope.interface.directlyProvides(self, zope.interface.providedBy(base)) base.registerDB(self) def __getattr__(self, name): return getattr(self.base, name) def __len__(self): return len(self.base) def load(self, oid, version=''): data, serial = self.base.load(oid, version) return self._untransform(data), serial def loadBefore(self, oid, tid): r = self.base.loadBefore(oid, tid) if r is not None: data, serial, after = r return self._untransform(data), serial, after else: return r def loadSerial(self, oid, serial): return self._untransform(self.base.loadSerial(oid, serial)) def pack(self, pack_time, referencesf, gc=None): _untransform = self._untransform def refs(p, oids=None): return referencesf(_untransform(p), oids) if gc is not None: return self.base.pack(pack_time, refs, gc) else: return self.base.pack(pack_time, refs) def registerDB(self, db): self.db = db self._db_transform = db.transform_record_data self._db_untransform = db.untransform_record_data _db_transform = _db_untransform = lambda self, data: data def store(self, oid, serial, data, version, transaction): return self.base.store(oid, serial, self._transform(data), version, transaction) def restore(self, oid, serial, data, version, prev_txn, transaction): return self.base.restore( oid, serial, self._transform(data), version, prev_txn, transaction) def iterator(self, start=None, stop=None): return _Iterator(self.base.iterator(start, stop)) def storeBlob(self, oid, oldserial, data, blobfilename, version, transaction): return self.base.storeBlob( oid, oldserial, self._transform(data), blobfilename, version, transaction) def restoreBlob(self, oid, serial, data, blobfilename, prev_txn, transaction): return self.base.restoreBlob(oid, serial, self._transform(data), blobfilename, prev_txn, transaction) def invalidateCache(self): return self.db.invalidateCache() def invalidate(self, transaction_id, oids, version=''): return self.db.invalidate(transaction_id, oids) def references(self, record, oids=None): return self.db.references(self._untransform(record), oids) def transform_record_data(self, data): return self._transform(self._db_transform(data)) def untransform_record_data(self, data): return self._db_untransform(self._untransform(data)) def record_iternext(self, next=None): oid, tid, data, next = self.base.record_iternext(next) return oid, tid, self._untransform(data), next def copyTransactionsFrom(self, other): ZODB.blob.copyTransactionsFromTo(other, self) def copyTransactionsFrom(self, other): ZODB.blob.copyTransactionsFromTo(other, self) def compress(data): if data and (len(data) > 20) and data[:2] != b'.z': compressed = b'.z'+zlib.compress(data) if len(compressed) < len(data): return compressed return data def decompress(data): return data[:2] == b'.z' and zlib.decompress(data[2:]) or data class ServerZlibStorage(ZlibStorage): """Use on ZEO storage server when ZlibStorage is used on client Don't do conversion as part of load/store, but provide pickle decoding. """ copied_methods = ZlibStorage.copied_methods + ( 'load', 'loadBefore', 'loadSerial', 'store', 'restore', 'iterator', 'storeBlob', 'restoreBlob', 'record_iternext', ) class _Iterator(object): # A class that allows for proper closing of the underlying iterator # as well as avoiding any GC issues. # (https://github.com/zopefoundation/zc.zlibstorage/issues/4) def __init__(self, base_it): self._base_it = base_it def __iter__(self): return self def __next__(self): return Transaction(next(self._base_it)) next = __next__ def close(self): try: base_close = self._base_it.close except AttributeError: pass else: base_close() finally: self._base_it = iter(()) def __getattr__(self, name): return getattr(self._base_it, name) class Transaction(object): def __init__(self, trans): self.__trans = trans def __iter__(self): for r in self.__trans: if r.data: r.data = decompress(r.data) yield r def __getattr__(self, name): return getattr(self.__trans, name) class ZConfig: _factory = ZlibStorage def __init__(self, config): self.config = config self.name = config.getSectionName() def open(self): base = self.config.base.open() compress = self.config.compress if compress is None: compress = True return self._factory(base, compress) class ZConfigServer(ZConfig): _factory = ServerZlibStorage
zc.zlibstorage
/zc.zlibstorage-1.2.0.tar.gz/zc.zlibstorage-1.2.0/src/zc/zlibstorage/__init__.py
__init__.py
*********************** ZODB Activity Log *********************** XXX Need tests! This package provides an activity log that lets you track database activity. Just: - put the package in your path - Add:: <include package="zc.zodbactivitylog" /> to your ZCML - Add a log entry to your zope.conf: :: <logger> name zc.zodbactivitylog propagate false <logfile> path ${buildout:directory}/zodb.log format %(asctime)s %(message)s </logfile> </logger> setting the path option appropriately. There is an output log entry for each connection. Each entry has a time, a number of reads, and a number of writes. XXX The log entries don't contain database names. This package will need to be updated for multiple databases. Maybe I'll do that when I write tests. Changes ******* 0.1 (yyyy-mm-dd) ================ Initial release
zc.zodbactivitylog
/zc.zodbactivitylog-0.1.1.tar.gz/zc.zodbactivitylog-0.1.1/README.txt
README.txt
================ Change History ================ 1.1.0 (2020-09-21) ================== - Add support for Python 3.5, 3.6, 3.7, 3.8 and 3.9. - Drop support for Python for Python 2.6, 3.2, 3.3 and 3.4. - Require ZODB 5.1 or later. See `issue 14 <https://github.com/zopefoundation/zc.zodbdgc/issues/14>`_. 1.0.1 (2015-09-23) ================== - Fix #6: Add support for weak references. - Fixed: If the only references to an object were outside its home database, it would be incorrectly collected, breaking the cross-database references. 1.0.0 (2015-08-28) ================== - Add support for PyPy, Python 2.7, and Python 3. This requires the addition of the ``zodbpickle`` dependency, even on Python 2.6. - Fixed the ``--days`` argument to ``multi-zodb-gc`` with recent versions of ``persistent``. - The return values and arguments of the internal implementation functions ``gc`` and ``gc_command`` have changed for compatibility with Python 3. This will not impact users of the documented scripts and is noted only for developers. 0.6.1 (2012-10-08) ================== - Fixed: GC could fail in special cases with a NameError. 0.6.0 (2010-05-27) ================== - Added support for storages with transformed (e.g. compressed) data records. 0.5.0 (2009-11-10) ================== - Fixed a bug in the delay throttle that made it delete objects way too slowly. 0.4.0 (2009-09-08) ================== - The previous version deleted too many objects at a time, which could put too much load on a heavily loaded storage server. - Add a sleep or allow the storage to rest after a set of deletions. Sleep for twice the time taken to perform the deletions. - Adjust the deletion batch size to take about .5 seconds per batch of deletions, but do at least 10 at a time. 0.3.0 (2009-09-03) ================== - Optimized garbage collection by using a temporary file to store object references rather than loading them from the analysis database when needed. - Added an -f option to specify file-storage files directly. It is wildly faster to iterate over a file storage than over a ZEO connection. Using this option uses a file iterator rather than opening a file storage in read-only mode, which avoids scanning the database to build an index and avoids the memory cost of a file-storage index. 0.2.0 (2009-06-15) ================== - Added an option to ignore references to some databases. - Fixed a bug in handling of the logging level option. 0.1.0 (2009-06-11) ================== Initial release
zc.zodbdgc
/zc.zodbdgc-1.1.0.tar.gz/zc.zodbdgc-1.1.0/CHANGES.rst
CHANGES.rst
===================== ZODB Distributed GC ===================== This package provides 2 scripts, for multi-database garbage collection and database validation. The scripts require that the databases provided to them use 64-bit object ids. The garbage-collection script also assumes that the databases support efficient iteration from transactions near the end of the databases. multi-zodb-gc ============= The multi-zodb-gc script takes one or 2 configuration files. If a single configuration file is given, garbage collection is performed on the databases specified by the configuration files. If garbage is found, then delete records are written to the databases. When the databases are subsequently packed to a time after the delete records are written, the garbage objects will be removed. If a second configuration file is given, then the databases specified in the second configuration file will be used to find garbage. Deleted records are still written to the databases given in the first configuration file. When using replicated-database technology, analysis can be performed using secondary storages, which are usually lightly loaded. This is helpful because finding garbage places a significant load on the databases used to find garbage. If your database uses file-storages, then rather than specifying a second configuration file, you can use the -f option to specify file-storage iterators for finding garbage. Using file storage iterators is much faster than using a ZEO connection and is faster and requires less memory than opening a read-only file storage on the files. Some number of trailing days (1 by default) of database records are considered good, meaning the objects referenced by them are not garbage. This allows the garbage-collection algorithm to work more efficiently and avoids problems when applications (incorrectly) do things that cause objects to be temporarily unreferenced, such as moving objects in 2 transactions. Options can be used to control the number of days of trailing data to be treated as non garbage and to specify the logging level. Use the ``--help`` option to get details. multi-zodb-check-refs ===================== The multi-zodb-check-refs script validates a collection of databases by starting with their roots and traversing the databases to make sure all referenced objects are reachable. Any unreachable objects are reported. If any databases are configured to disallow implicit cross-database references, then invalid references are reported as well. Blob records are checked to make sure their blob files can be loaded. Optionally, a database of reference information can be generated. This database allows you to find objects referencing a given object id in a database. This can be very useful to debugging missing objects. Generation of the references database increases the analysis time substantially. The references database can become quite large, often a substantial percentage of the size of the databases being analyzed. Typically, you'll perform an initial analysis without a references database and only create a references file in a subsequent run if problems are found. You can run the script with the ``--help`` option to get usage information.
zc.zodbdgc
/zc.zodbdgc-1.1.0.tar.gz/zc.zodbdgc-1.1.0/src/zc/zodbdgc/README.txt
README.txt
from __future__ import print_function from io import BytesIO import logging import marshal import optparse import struct import sys import tempfile import time from ZODB.utils import z64 import BTrees.fsBTree import BTrees.OOBTree import BTrees.LLBTree from persistent import TimeStamp import transaction import ZODB.blob import ZODB.config import ZODB.FileStorage import ZODB.fsIndex import ZODB.POSException import ZODB.serialize from ZODB.Connection import TransactionMetaData # For consistency and easy of distribution, always use zodbpickle. On # most platforms, including PyPy, and all CPython >= 2.7 or 3, we need # it because of missing or broken `noload` support. We could get away # without it under CPython 2.6, but there's not really any point. Use # the fastest version we can have access to (PyPy doesn't have # fastpickle) try: from zodbpickle.fastpickle import Unpickler except ImportError: from zodbpickle.pickle import Unpickler # In cases where we might iterate multiple times # over large-ish dictionaries, avoid excessive copies # that tend toward O(n^2) complexity by using the explicit # iteration functions on Python 2 if hasattr(dict(), 'iteritems'): def _iteritems(d): return d.iteritems() def _itervalues(d): return d.itervalues() else: def _iteritems(d): return d.items() def _itervalues(d): return d.values() def p64(v): """Pack an integer or long into a 8-byte string""" return struct.pack(b">q", v) def u64(v): """Unpack an 8-byte string into a 64-bit signed long integer.""" return struct.unpack(b">q", v)[0] logger = logging.getLogger(__name__) log_format = "%(asctime)s %(name)s %(levelname)s: %(message)s" def gc_command(args=None, ptid=None, return_bad=False): # The setuptools entry point for running a garbage collection. # Arguments and keyword arguments are for internal use only and # may change at any time. The return value is only defined when # return_bad is set to True; see :func:`gc` if args is None: args = sys.argv[1:] level = logging.WARNING else: level = None parser = optparse.OptionParser("usage: %prog [options] config1 [config2]") parser.add_option( '-d', '--days', dest='days', type='int', default=1, help='Number of trailing days (defaults to 1) to treat as non-garbage') parser.add_option( '-f', '--file-storage', dest='fs', action='append', help='name=path, use the given file storage path for analysis of the.' 'named database') parser.add_option( '-i', '--ignore-database', dest='ignore', action='append', help='Ignore references to the given database name.') parser.add_option( '-l', '--log-level', dest='level', help='The logging level. The default is WARNING.') parser.add_option( '-u', '--untransform', dest='untransform', help='Function (module:expr) used to untransform data records in' ' files identified using the -file-storage/-f option') options, args = parser.parse_args(args) if not args or len(args) > 2: parser.parse_args(['-h']) elif len(args) == 2: conf2 = args[1] else: conf2 = None if options.level: level = options.level if level: try: level = int(level) except ValueError: level = getattr(logging, level) logging.basicConfig(level=level, format=log_format) untransform = options.untransform if untransform is not None: mod, expr = untransform.split(':', 1) untransform = eval(expr, __import__(mod, {}, {}, ['*']).__dict__) return gc(args[0], options.days, options.ignore or (), conf2=conf2, fs=dict(o.split('=') for o in options.fs or ()), untransform=untransform, ptid=ptid, return_bad=return_bad) def gc(conf, days=1, ignore=(), conf2=None, fs=(), untransform=None, ptid=None, return_bad=False): # The programmatic entry point for running a GC. Internal function # only, all arguments and return values may change at any time. close = [] result = None try: bad = gc_(close, conf, days, ignore, conf2, fs, untransform, ptid) if return_bad: # For tests only, we return a sorted list of the human readable # pairs (dbname, badoid) when requested. Bad will be closed # in the following finally block. result = sorted((name, int(u64(oid))) for (name, oid) in bad.iterator()) return result finally: for thing in close: if hasattr(thing, 'databases'): for db in thing.databases.values(): db.close() elif hasattr(thing, 'close'): thing.close() def gc_(close, conf, days, ignore, conf2, fs, untransform, ptid): FileIterator = ZODB.FileStorage.FileIterator if untransform is not None: def FileIterator(*args): def transit(trans): for record in trans: if record.data: record.data = untransform(record.data) yield record zfsit = ZODB.FileStorage.FileIterator(*args) try: for t in zfsit: yield transit(t) finally: zfsit.close() def iter_storage(name, storage, start=None, stop=None): fsname = name or '' if fsname in fs: it = FileIterator(fs[fsname], start, stop) else: it = storage.iterator(start, stop) # We need to be sure to always close iterators # in case we raise an exception close.append(it) return it with open(conf) as f: db1 = ZODB.config.databaseFromFile(f) close.append(db1) if conf2 is None: db2 = db1 else: logger.info("Using secondary configuration, %s, for analysis", conf2) with open(conf2) as f: db2 = ZODB.config.databaseFromFile(f) close.append(db2) if set(db1.databases) != set(db2.databases): raise ValueError("primary and secondary databases don't match.") databases = db2.databases storages = sorted((name, d.storage) for (name, d) in databases.items()) if ptid is None: ptid = TimeStamp.TimeStamp( *time.gmtime(time.time() - 86400 * days)[:6] ).raw() good = oidset(databases) bad = Bad(databases) close.append(bad) deleted = oidset(databases) for name, storage in storages: fsname = name or '' logger.info("%s: roots", fsname) # Make sure we can get the roots data, s = storage.load(z64, '') good.insert(name, z64) for ref in getrefs(data, name, ignore): good.insert(*ref) n = 0 if days: # All non-deleted new records are good logger.info("%s: recent", name) for trans in iter_storage(name, storage, start=ptid): for record in trans: if n and n % 10000 == 0: logger.info("%s: %s recent", name, n) n += 1 oid = record.oid data = record.data if data: if deleted.has(name, oid): raise AssertionError( "Non-deleted record after deleted") good.insert(name, oid) # and anything they reference for ref_name, ref_oid in getrefs(data, name, ignore): if not deleted.has(ref_name, ref_oid): good.insert(ref_name, ref_oid) bad.remove(ref_name, ref_oid) else: # deleted record deleted.insert(name, oid) good.remove(name, oid) for name, storage in storages: # Now iterate over older records for trans in iter_storage(name, storage, start=None, stop=ptid): for record in trans: if n and n % 10000 == 0: logger.info("%s: %s old", name, n) n += 1 oid = record.oid data = record.data if data: if deleted.has(name, oid): continue if good.has(name, oid): for ref in getrefs(data, name, ignore): if deleted.has(*ref): continue if good.insert(*ref) and bad.has(*ref): to_do = [ref] while to_do: for ref in bad.pop(*to_do.pop()): if good.insert(*ref) and bad.has(*ref): to_do.append(ref) else: bad.insert(name, oid, record.tid, getrefs(data, name, ignore)) else: # deleted record if good.has(name, oid): good.remove(name, oid) elif bad.has(name, oid): bad.remove(name, oid) deleted.insert(name, oid) if conf2 is not None: for db in db2.databases.values(): db.close() close.remove(db2) # Now, we have the garbage in bad. Remove it. batch_size = 100 for name, db in sorted(db1.databases.items()): logger.info("%s: remove garbage", name) storage = db.storage nd = 0 t = transaction.begin() txn_meta = TransactionMetaData() storage.tpc_begin(txn_meta) start = time.time() for oid, tid in bad.iterator(name): try: storage.deleteObject(oid, tid, txn_meta) except (ZODB.POSException.POSKeyError, ZODB.POSException.ConflictError): continue nd += 1 if (nd % batch_size) == 0: storage.tpc_vote(txn_meta) storage.tpc_finish(txn_meta) t.commit() logger.info("%s: deleted %s", name, nd) duration = time.time() - start time.sleep(duration * 2) batch_size = max(10, int(batch_size * .5 / duration)) t = transaction.begin() txn_meta = TransactionMetaData() storage.tpc_begin(txn_meta) start = time.time() logger.info("Removed %s objects from %s", nd, name) if nd: storage.tpc_vote(txn_meta) storage.tpc_finish(txn_meta) t.commit() else: storage.tpc_abort(txn_meta) t.abort() return bad def getrefs(p, rname, ignore): refs = [] u = Unpickler(BytesIO(p)) u.persistent_load = refs.append u.noload() u.noload() for ref in refs: # ref types are documented in ZODB.serialize if isinstance(ref, tuple): # (oid, class meta data) yield rname, ref[0] elif isinstance(ref, str): # oid yield rname, ref elif not ref: # Seen in corrupted databases raise ValueError("Unexpected empty reference") elif ref: assert isinstance(ref, list) # [reference type, args] or [oid] if len(ref) == 1: # Legacy persistent weak ref. Ignored, not a # strong ref. # To treat as strong: yield rname, ref continue # Args is always a tuple, but depending on # the value of the reference type, the order # may be different. Types n and m are in the same # order, type w is different kind, ref = ref if kind in ('n', 'm'): # (dbname, oid, [class meta]) if ref[0] not in ignore: yield ref[:2] elif kind == 'w': # Weak ref, either (oid) for this DB # or (oid, dbname) for other db. Both ignored. # To treat the first as strong: # yield rname, ref[0] # To treat the second as strong: # yield ref[1], ref[0] continue else: raise ValueError('Unknown persistent ref', kind, ref) class oidset(dict): """ {(name, oid)} implemented as: {name-> {oid[:6] -> {oid[-2:]}}} """ def __init__(self, names): for name in names: self[name] = {} def insert(self, name, oid): prefix = oid[:6] suffix = oid[6:] data = self[name].get(prefix) if data is None: data = self[name][prefix] = BTrees.fsBTree.TreeSet() elif suffix in data: return False data.insert(suffix) return True def remove(self, name, oid): prefix = oid[:6] suffix = oid[6:] data = self[name].get(prefix) if data and suffix in data: data.remove(suffix) if not data: del self[name][prefix] def __nonzero__(self): for v in _itervalues(self): if v: return True return False __bool__ = __nonzero__ def pop(self): for name, data in _iteritems(self): if data: break prefix, s = next(iter(_iteritems(data))) suffix = s.maxKey() s.remove(suffix) if not s: del data[prefix] return name, prefix + suffix def has(self, name, oid): try: data = self[name][oid[:6]] except KeyError: return False return oid[6:] in data def iterator(self, name=None): if name is None: for name in self: for oid in self.iterator(name): yield name, oid else: for prefix, data in _iteritems(self[name]): for suffix in data: yield prefix + suffix class Bad(object): def __init__(self, names): self._file = tempfile.TemporaryFile(dir='.', prefix='gcbad') self.close = self._file.close self._pos = 0 self._dbs = {} for name in names: self._dbs[name] = ZODB.fsIndex.fsIndex() def remove(self, name, oid): db = self._dbs[name] if oid in db: del db[oid] def __nonzero__(self): raise SystemError('wtf') return sum(map(bool, _itervalues(self._dbs))) __bool__ = __nonzero__ def has(self, name, oid): db = self._dbs[name] return oid in db def iterator(self, name=None): if name is None: for name in self._dbs: for oid in self._dbs[name]: yield name, oid else: f = self._file for oid, pos in _iteritems(self._dbs[name]): f.seek(pos) yield oid, f.read(8) def insert(self, name, oid, tid, refs): assert len(tid) == 8 f = self._file db = self._dbs[name] pos = db.get(oid) if pos is not None: f.seek(pos) oldtid = f.read(8) oldrefs = set(marshal.load(f)) refs = oldrefs.union(refs) tid = max(tid, oldtid) if refs == oldrefs: if tid != oldtid: f.seek(pos) f.write(tid) return db[oid] = pos = self._pos f.seek(pos) f.write(tid) marshal.dump(list(refs), f) self._pos = f.tell() def pop(self, name, oid): db = self._dbs[name] pos = db.get(oid, None) if pos is None: return () del db[oid] f = self._file f.seek(pos + 8) return marshal.load(f) def check(config, refdb=None): if refdb is None: return check_(config) fs = ZODB.FileStorage.FileStorage(refdb, create=True) conn = ZODB.connection(fs) references = conn.root.references = BTrees.OOBTree.BTree() try: check_(config, references) finally: transaction.commit() conn.close() fs.close() def _insert_ref(references, rname, roid, name, oid): if references is None: return False oid = u64(oid) roid = u64(roid) by_oid = references.get(name) if not by_oid: by_oid = references[name] = BTrees.LOBTree.BTree() # Setting _p_changed is needed when using older versions of # the pure-python BTree package (e.g., under PyPy). This is # a bug documented at https://github.com/zopefoundation/BTrees/pull/11. # Without it, the References example in README.test fails # with a KeyError: the 'db2' key is not found because it wasn't # persisted to disk. references._p_changed = True by_rname = by_oid.get(oid) if not by_rname: references = BTrees.LLBTree.TreeSet() if rname == name: by_oid[oid] = references else: by_oid[oid] = {rname: references} elif isinstance(by_rname, dict): references = by_rname.get(rname) if not references: references = by_rname[rname] = BTrees.LLBTree.TreeSet() # trigger change since dict is not persistent: by_oid[oid] = by_rname elif rname != name: references = BTrees.LLBTree.TreeSet() by_oid[oid] = {name: by_rname, rname: references} else: references = by_rname if roid not in references: references.insert(roid) references._p_changed = True return True return False def _get_referer(references, name, oid): if references is None: return by_oid = references.get(name) if by_oid: oid = u64(oid) by_rname = by_oid.get(oid) if by_rname: if isinstance(by_rname, dict): rname = next(iter(by_rname)) return rname, p64(next(iter(by_rname[rname]))) else: return name, p64(next(iter(by_rname))) def check_(config, references=None): with open(config) as f: db = ZODB.config.databaseFromFile(f) try: databases = db.databases storages = dict((name, db.storage) for (name, db) in databases.items()) roots = oidset(databases) for name in databases: roots.insert(name, z64) seen = oidset(databases) nreferences = 0 while roots: name, oid = roots.pop() try: if not seen.insert(name, oid): continue p, tid = storages[name].load(oid, b'') if (# XXX should be in is_blob_record len(p) < 100 and (b'ZODB.blob' in p) and ZODB.blob.is_blob_record(p) ): storages[name].loadBlob(oid, tid) except: print('!!!', name, u64(oid), end=' ') referer = _get_referer(references, name, oid) if referer: rname, roid = referer print(rname, u64(roid)) else: print('?') t, v = sys.exc_info()[:2] print("%s: %s" % (t.__name__, v)) continue for ref in getrefs(p, name, ()): if (ref[0] != name) and not databases[name].xrefs: print('bad xref', ref[0], u64(ref[1]), name, u64(oid)) nreferences += _insert_ref(references, name, oid, *ref) if nreferences > 400: transaction.commit() nreferences = 0 if ref[0] not in databases: print('!!!', ref[0], u64(ref[1]), name, u64(oid)) print('bad db') continue if seen.has(*ref): continue roots.insert(*ref) finally: for d in db.databases.values(): d.close() def check_command(args=None): if args is None: args = sys.argv[1:] logging.basicConfig(level=logging.WARNING, format=log_format) parser = optparse.OptionParser("usage: %prog [options] config") parser.add_option( '-r', '--references-filestorage', dest='refdb', help='The name of a file-storage to save reference info in.') options, args = parser.parse_args(args) if not args or len(args) > 1: parser.parse_args(['-h']) check(args[0], options.refdb) class References(object): def __init__(self, db): self._conn = ZODB.connection(db) self._refs = self._conn.root.references def close(self): self._conn.close() def __getitem__(self, arg): name, oid = arg if isinstance(oid, (str, bytes)): oid = u64(oid) by_rname = self._refs[name][oid] if isinstance(by_rname, dict): for rname, roids in _iteritems(by_rname): for roid in roids: yield rname, roid else: for roid in by_rname: yield name, roid
zc.zodbdgc
/zc.zodbdgc-1.1.0.tar.gz/zc.zodbdgc-1.1.0/src/zc/zodbdgc/__init__.py
__init__.py
Changes ******* 3.0 (2023-02-07) ================ - Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11. - Drop support for Python < 3.7. 2.0.0 (2014-02-12) ================== This release isn't backward compatible It uses ZODB, rather than ZODB3. - Added Python 3 support - Changed from ZODB3 to ZODB. 0.6.2 (2012-10-31) ================== Bugs Fixed ---------- - Moved 'zope.testing' requirement from install to test requirement. 0.6.1 (2010-05-25) ================== Bugs Fixed ---------- - Pack scripts were incorrectly generated for storages that weren't named in their storage configurations. 0.6.0 (2009-12-03) ================== New Features ------------ - Generation of a logrotate configuration can now be disabled by providing a logrotate option with a value of "false". - Added documentation of the eggs option and why it generally shouldn't be used. - Improved error handling. Bugs Fixed ---------- - The eggs option, when used, wasn't handled properly. 0.5.0 (2008-11-03) ================== New Features ------------ You can now specify a name option in server parts to have installed files use a different name than the section name. Bugs Fixed ---------- Pack crontab files weren't removed when parts were removed or renamed. 0.4 (2008-02-18) ================ New Features ------------ The server recipe now honors the deployment name option. 0.3.1 (2008-01-03) ================== Bugs Fixed ---------- Shell-scripts using su weren't generated correctly. 0.3 (2008-01-03) ================ New Features ------------ - You can now specify an email address in a packing crontab file to control where errors are sent. - If you install a general ZEO script, using a zdaemon part:: [zdaemon] recipe = zc.recipe.egg:script eggs = zdaemon you can request that shell scripts be generated that use the generic zdaemon script. This can make updating software for deployed systems easier since instance-specific scripts don't depend on paths, like egg names, that are likely to change. Bugs Fixed ---------- - ZODB3 and most of its requirements were spurious dependencies of the recipes. This caused ZODB3 to be installed using the Python used to run the buildout, which caused problems in some circumstances. 0.2.1 (2007-04-23) ================== Bugs Fixed ---------- - crontab and logrotate configuration files were being generates incorrectly. 0.2 (2007-04-17) ================ Added handling of %import directives. 0.1 (2007-04-13) ================ Initial release.
zc.zodbrecipes
/zc.zodbrecipes-3.0.tar.gz/zc.zodbrecipes-3.0/CHANGES.rst
CHANGES.rst
import logging import os from io import StringIO import zc.buildout import zc.recipe.egg import ZConfig.schemaless from ZConfig import ConfigurationSyntaxError logger = logging.getLogger('zc.zodbrecipes') class StorageServer: def __init__(self, buildout, name, options): self.name, self.options = options.get('name', name), options deployment = self.deployment = options.get('deployment') if deployment: options['deployment-name'] = buildout[deployment].get( 'name', deployment) options['rc-directory'] = buildout[deployment]['rc-directory'] options['run-directory'] = buildout[deployment]['run-directory'] options['log-directory'] = buildout[deployment]['log-directory'] options['etc-directory'] = buildout[deployment]['etc-directory'] logrotate = options.get('logrotate', buildout[deployment].get('logrotate', '')) if logrotate.lower() == 'false': options['logrotate'] = '' else: options['logrotate'] = os.path.join( buildout[deployment]['logrotate-directory'], options['deployment-name'] + '-' + self.name) options['crontab-directory'] = buildout[ deployment]['crontab-directory'] options['user'] = buildout[deployment]['user'] else: options['rc-directory'] = buildout['buildout']['bin-directory'] options['run-directory'] = os.path.join( buildout['buildout']['parts-directory'], self.name, ) options['scripts'] = '' options['eggs'] = options.get('eggs', '') + '\nzdaemon\nsetuptools' self.egg = zc.recipe.egg.Egg(buildout, name, options) options['runzeo'] = os.path.join( buildout['buildout']['bin-directory'], options.get('runzeo', 'runzeo'), ) options['zdaemon'] = os.path.join( buildout['buildout']['bin-directory'], options.get('zdaemon', 'zdaemon'), ) options['zeopack'] = os.path.join( buildout['buildout']['bin-directory'], options.get('zeopack', 'zeopack'), ) if options.get('shell-script', '') not in ('true', 'false', ''): raise zc.buildout.UserError( 'The shell-script option value must be "true", "false" or "".') def install(self): options = self.options if not os.path.exists(options['runzeo']): logger.warn(no_runzeo % options['runzeo']) run_directory = options['run-directory'] deployment = self.deployment if deployment: zeo_conf_path = os.path.join(options['etc-directory'], self.name + '-zeo.conf') zdaemon_conf_path = os.path.join(options['etc-directory'], self.name + '-zdaemon.conf') event_log_path = os.path.join(options['log-directory'], self.name + '-zeo.log') socket_path = os.path.join(run_directory, self.name + '-zdaemon.sock') rc = options['deployment-name'] + '-' + self.name options.created( zeo_conf_path, zdaemon_conf_path, os.path.join(options['rc-directory'], rc), ) logrotate = options['logrotate'] if logrotate: open(logrotate, 'w').write(logrotate_template % dict( logfile=event_log_path, rc=os.path.join(options['rc-directory'], rc), conf=zdaemon_conf_path, )) options.created(logrotate) pack = options.get('pack') if pack: pack = pack.split() if len(pack) < 5: raise zc.buildout.UserError( 'Too few crontab fields in pack specification') if len(pack) > 7: raise zc.buildout.UserError( 'Too many values in pack option') pack_path = os.path.join( options['crontab-directory'], "pack-{}-{}".format(options['deployment-name'], self.name), ) if not os.path.exists(options['zeopack']): logger.warn("Couln'e find zeopack script, %r", options['zeopack']) else: zeo_conf_path = os.path.join(run_directory, 'zeo.conf') zdaemon_conf_path = os.path.join(run_directory, 'zdaemon.conf') event_log_path = os.path.join(run_directory, 'zeo.log') socket_path = os.path.join(run_directory, 'zdaemon.sock') rc = self.name options.created(run_directory, os.path.join(options['rc-directory'], rc), ) if not os.path.exists(run_directory): os.mkdir(run_directory) pack = pack_path = None zeo_conf = options.get('zeo.conf', '') + '\n' try: zeo_conf = ZConfig.schemaless.loadConfigFile(StringIO(zeo_conf)) except ConfigurationSyntaxError as e: raise zc.buildout.UserError( '{} in:\n{}'.format(e, zeo_conf) ) zeo_section = [s for s in zeo_conf.sections if s.type == 'zeo'] if not zeo_section: raise zc.buildout.UserError('No zeo section was defined.') if len(zeo_section) > 1: raise zc.buildout.UserError('Too many zeo sections.') zeo_section = zeo_section[0] if 'address' not in zeo_section: raise zc.buildout.UserError('No ZEO address was specified.') storages = [s.name or '1' for s in zeo_conf.sections if s.type not in ('zeo', 'eventlog', 'runner') ] if not storages: raise zc.buildout.UserError('No storages were defined.') if not [s for s in zeo_conf.sections if s.type == 'eventlog']: zeo_conf.sections.append(event_log('STDOUT')) zdaemon_conf = options.get('zdaemon.conf', '') + '\n' zdaemon_conf = ZConfig.schemaless.loadConfigFile( StringIO(zdaemon_conf)) defaults = { 'program': "{} -C {}".format(options['runzeo'], zeo_conf_path), 'daemon': 'on', 'transcript': event_log_path, 'socket-name': socket_path, 'directory': run_directory, } if deployment: defaults['user'] = options['user'] runner = [s for s in zdaemon_conf.sections if s.type == 'runner'] if runner: runner = runner[0] else: runner = ZConfig.schemaless.Section('runner') zdaemon_conf.sections.insert(0, runner) for name, value in defaults.items(): if name not in runner: runner[name] = [value] if not [s for s in zdaemon_conf.sections if s.type == 'eventlog']: zdaemon_conf.sections.append(event_log(event_log_path)) zdaemon_conf = str(zdaemon_conf) self.egg.install() requirements, ws = self.egg.working_set() open(zeo_conf_path, 'w').write(str(zeo_conf)) open(zdaemon_conf_path, 'w').write(str(zdaemon_conf)) if options.get('shell-script') == 'true': if not os.path.exists(options['zdaemon']): logger.warn(no_zdaemon % options['zdaemon']) contents = "%(zdaemon)s -C '%(conf)s' $*" % dict( zdaemon=options['zdaemon'], conf=zdaemon_conf_path, ) if options.get('user'): contents = 'su %(user)s -c \\\n "%(contents)s"' % dict( user=options['user'], contents=contents, ) contents = "#!/bin/sh\n%s\n" % contents dest = os.path.join(options['rc-directory'], rc) if not (os.path.exists(dest) and open(dest).read() == contents): open(dest, 'w').write(contents) os.chmod(dest, 0o755) logger.info("Generated shell script %r.", dest) else: self.egg.install() requirements, ws = self.egg.working_set() zc.buildout.easy_install.scripts( [(rc, 'zdaemon.zdctl', 'main')], ws, options['executable'], options['rc-directory'], arguments=('[' '\n %r, %r,' '\n ]+sys.argv[1:]' '\n ' % ('-C', zdaemon_conf_path, ) ), ) if pack: address, = zeo_section['address'] if ':' in address: host, port = address.split(':') address = '-h {} -p {}'.format(host, port) else: try: port = int(address) except ValueError: address = '-U ' + address else: address = '-p ' + address f = open(pack_path, 'w') if len(pack) == 7: assert '@' in pack[6] f.write("MAILTO=%s\n" % pack.pop()) if len(pack) == 6: days = pack.pop() else: days = 1 for storage in storages: f.write("{} {} {} {} -S {} -d {}\n".format( ' '.join(pack), options['user'], options['zeopack'], address, storage, days, )) f.close() options.created(pack_path) return options.created() update = install no_runzeo = """ A runzeo script couldn't be found at: %r You may need to generate a runzeo script using the zc.recipe.eggs:script recipe and the ZEO egg, or you may need to specify the location of a script using the runzeo option. """ no_zdaemon = """ A zdaemon script couldn't be found at: %r You may need to generate a zdaemon script using the zc.recipe.eggs:script recipe and the zdaemon egg. """ def event_log(path, *data): return ZConfig.schemaless.Section( 'eventlog', '', None, [ZConfig.schemaless.Section('logfile', '', dict(path=[path]))]) logrotate_template = """%(logfile)s { rotate 5 weekly postrotate %(rc)s -C %(conf)s reopen_transcript endscript } """
zc.zodbrecipes
/zc.zodbrecipes-3.0.tar.gz/zc.zodbrecipes-3.0/src/zc/zodbrecipes/__init__.py
__init__.py
.. image:: https://travis-ci.org/zopefoundation/zc.zodbwsgi.png?branch=master :target: https://travis-ci.org/zopefoundation/zc.zodbwsgi WSGI Middleware for Managing ZODB Database Connections ====================================================== The zc.zodbwsgi provides middleware for managing connections to a ZODB database. It combines several features into a single middleware component: - database configuration - database initialization - connection management - optional transaction management - optional request retry on conflict errors (using repoze.retry) - optionaly limiting the number of simultaneous database connections - applications can take over connection and transaction management on a case-by-case basis, for example to support the occasional long-running request. It is designed to work with paste deployment and provides a "filter_app_factory" entry point, named "main". A number of configuration options are provided. Option values are strings. configuration A required ZConfig formatted ZODB database configuration If multiple databases are defined, they will define a multi-database. Connections will be to the first defined database. initializer An optional database initialization function of the form ``module:expression`` key An optional name of a WSGI environment key for database connections This defaults to "zodb.connection". transaction_management An optional flag (either "true" or "false") indicating whether the middleware manages transactions. Transaction management is enabled by default. transaction_key An optional name of a WSGI environment key for transaction managers This defaults to "transaction.manager". The key will only be present if transaction management is enabled. thread_transaction_manager An option flag (either "true" or "false") indicating whether the middleware will use a thread-aware transaction mananger (e.g., thread.TransactionManager). Using a thread-aware transaction mananger is convenient if you're using a server that always a request in the same thread, such as servers thaat use thread pools, or that create threads for each request. If you're using a server, such as gevent, that handles multiple requests in the same thread or a server that might handle the same request in different threads, then you should set this option to false. Defaults to True. retry An optional retry count The default is "3", indicating that requests will be retried up to 3 times. Use "0" to disable retries. Note that when retry is not "0", request bodies will be buffered. demostorage_manage_header An optional entry that controls whether the filter will support push/pop support for the underlying demostorage. If a value is provided, it'll check for that header in the request. If found and its value is "push" or "pop" it'll perform the relevant operation. The middleware will return a response indicating the action taken _without_ processing the rest of the pipeline. Also note that this only works if the underlying storage is a DemoStorage. max_connections Maximum number of simultaneous connections. .. contents:: Basic usage ----------- Let's look at some examples. First we define an demonstration "application" that we can pass to our factory:: import transaction, ZODB.POSException from sys import stdout class demo_app: def __init__(self, default): pass def __call__(self, environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) root = environ['zodb.connection'].root() path = environ['PATH_INFO'] if path == '/inc': root['x'] = root.get('x', 0) + 1 if 'transaction.manager' in environ: environ['transaction.manager'].get().note('path: %r' % path) else: transaction.commit() # We have to commit our own! elif path == '/conflict': print >>stdout, 'Conflict!' raise ZODB.POSException.ConflictError elif path == "/tm": tm = environ["transaction.manager"] return ["thread tm: " + str(tm is transaction.manager)] return [repr(root)] .. -> src >>> import zc.zodbwsgi.tests >>> exec(src, zc.zodbwsgi.tests.__dict__) Now, we'll define our application factory using a paste deployment configuration:: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> .. -> src >>> open('paste.ini', 'w').write(src) Here, for demonstration purposes, we used an in-memory demo storage. Now, we'll create an application with paste: >>> import paste.deploy, os >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) The resulting applications has a database attribute (mainly for testing) with the created database. Being newly initialized, the database is empty: >>> conn = app.database.open() >>> conn.root() {} Let's do an "increment" request. >>> import webtest >>> testapp = webtest.TestApp(app) >>> testapp.get('/inc') <200 OK text/html body="{'x': 1}"> Now, if we look at the database, we see that there's now data in the root object: >>> conn.sync() >>> conn.root() {'x': 1} Database initialization ----------------------- We can supply a database initialization function using the initializer option. Let's define an initialization function:: import transaction def initialize_demo_db(db): conn = db.open() conn.root()['x'] = 100 transaction.commit() conn.close() .. -> src >>> exec(src, zc.zodbwsgi.tests.__dict__) and update our paste configuration to use it:: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> initializer = zc.zodbwsgi.tests:initialize_demo_db .. -> src >>> open('paste.ini', 'w').write(src) Now, when we use the application, we see the impact of the initializer: >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> testapp.get('/inc') <200 OK text/html body="{'x': 101}"> .. Our application updated transaction meta data when called under transaction control. >>> print app.database.history(conn.root()._p_oid, 1)[0]['description'] GET /inc path: '/inc' We also see that zodbwsgi added transaction information. Disabling transaction management -------------------------------- Sometimes, you may not want the middleware to control transactions. You might do this if your application used multiple databases, including non-ZODB databases [#multidb]_. You can suppress transaction management by supplying a value of "false" for the transaction_management option:: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> initializer = zc.zodbwsgi.tests:initialize_demo_db transaction_management = false .. -> src >>> open('paste.ini', 'w').write(src) >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> testapp.get('/inc') <200 OK text/html body="{'x': 101}"> >>> app.database.history('\0'*8, 1)[0]['description'] '' Suppressing request retry ------------------------- By default, zc.zodbwsgi adds ``repoze.retry`` middleware to retry requests when there are conflict errors: >>> import ZODB.POSException >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> try: testapp.get('/conflict') ... except ZODB.POSException.ConflictError: pass ... else: print 'oops' Conflict! Conflict! Conflict! Conflict! Here we can see that the request was retried 3 times. We can suppress this by supplying a value of "0" for the retry option:: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> retry = 0 .. -> src >>> open('paste.ini', 'w').write(src) Now, if we run the app, the request won't be retried: >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> try: testapp.get('/conflict') ... except ZODB.POSException.ConflictError: pass ... else: print 'oops' Conflict! Using non-thread-aware (non thread-local) transaction managers -------------------------------------------------------------- By default, the middleware uses a thread-aware transaction manager:: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> initializer = zc.zodbwsgi.tests:initialize_demo_db .. -> src >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> print testapp.get("/tm").body thread tm: True >>> print testapp.get("/tm").body thread tm: True This can be controlled via the ``thread_transaction_manager`` key:: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> initializer = zc.zodbwsgi.tests:initialize_demo_db thread_transaction_manager = false .. -> src >>> open('paste.ini', 'w').write(src) >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> print testapp.get("/tm").body thread tm: False .. Other tests of corner cases: :: class demo_app: def __init__(self, default): pass def __call__(self, environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) root = environ['connection'].root() path = environ['PATH_INFO'] if path == '/inc': root['x'] = root.get('x', 0) + 1 environ['manager'].get().note('path: %r' % path) return [repr(root)] .. -> src >>> exec(src, zc.zodbwsgi.tests.__dict__) :: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> key = connection transaction_key = manager .. -> src >>> open('paste.ini', 'w').write(src) >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> testapp.get('/inc') <200 OK text/html body="{'x': 1}"> demostorage_manage_header ------------------------- Providing an value for this options enables hooks that allow one to push/pop the underlying demostorage. :: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb> <demostorage> </demostorage> </zodb> key = connection transaction_key = manager demostorage_manage_header = X-FOO .. -> src >>> open('paste.ini', 'w').write(src) >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> testapp.get('/inc') <200 OK text/html body="{'x': 1}"> If the push or pop header is provided, the middleware returns a response immediately without sending it to the end of the pipeline. >>> testapp.get('/', {}, headers={'X-FOO': 'push'}).body 'Demostorage pushed\n' >>> testapp.get('/inc') <200 OK text/html body="{'x': 2}"> >>> testapp.get('/', {}, {'X-FOO': 'pop'}).body 'Demostorage popped\n' >>> testapp.get('/') <200 OK text/html body="{'x': 1}"> If you have access to the middleware object, you can accomplish the same thing by calling the push and pop methods, which also return the database. This is useful when you're running the server in the test process and have Python access: >>> db = app.application.push() Note that app is a repoze.retry, so we have to use .application to get the wsgi app. >>> with db.transaction() as conn: ... conn.root.x = 41 >>> testapp.get('/inc') <200 OK text/html body="{'x': 42}"> >>> db = app.application.pop() >>> with db.transaction() as conn: ... print conn.root.x 1 >>> testapp.get('/') <200 OK text/html body="{'x': 1}"> This also works with multiple dbs. :: class demo_app: def __init__(self, default): pass def __call__(self, environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) path = environ['PATH_INFO'] root_one = environ['connection'].get_connection('one').root() root_two = environ['connection'].get_connection('two').root() if path == '/inc': root_one['x'] = root_one.get('x', 0) + 1 root_two['y'] = root_two.get('y', 0) + 1 environ['manager'].get().note('path: %r' % path) data = {'one': root_one, 'two': root_two} return [repr(data)] .. -> src >>> exec(src, zc.zodbwsgi.tests.__dict__) :: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb one> <demostorage> </demostorage> </zodb> <zodb two> <demostorage> </demostorage> </zodb> key = connection transaction_key = manager demostorage_manage_header = X-FOO .. -> src >>> open('paste.ini', 'w').write(src) >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) >>> testapp = webtest.TestApp(app) >>> testapp.get('/inc').body "{'two': {'y': 1}, 'one': {'x': 1}}" >>> testapp.get('/', {}, {'X-FOO': 'push'}).body 'Demostorage pushed\n' >>> testapp.get('/inc').body "{'two': {'y': 2}, 'one': {'x': 2}}" >>> testapp.get('/', {}, {'X-FOO': 'pop'}).body 'Demostorage popped\n' >>> testapp.get('/').body "{'two': {'y': 1}, 'one': {'x': 1}}" If the storage of any of the databases is not a demostorage, an error is returned. :: [app:main] paste.app_factory = zc.zodbwsgi.tests:demo_app filter-with = zodb [filter:zodb] use = egg:zc.zodbwsgi configuration = <zodb one> <demostorage> </demostorage> </zodb> <zodb two> <filestorage> path /tmp/Data.fs </filestorage> </zodb> key = connection transaction_key = manager demostorage_manage_header = foo .. -> src >>> open('paste.ini', 'w').write(src) >>> app = paste.deploy.loadapp('config:'+os.path.abspath('paste.ini')) ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... UserError: Attempting to activate demostorage hooks when one of the storages is not a DemoStorage Limiting the number of connections ---------------------------------- If you're using a threaded server, one that dedicates a thread to each active request, you can limit the number of simultaneous database connections by specifying the number with the ``max_connections`` option. (This only works for threaded servers because it uses threaded semaphores. In the future, support for other locking mechanisms, such as gevent Semaphores, may be added. In the mean time, if you're inclined to monkey patch, you can replace ``zc.zodbwsgi.Semaphore`` with an alternative semaphore implementation, like gevent's.) .. test >>> import threading, zc.thread, time >>> events = [] >>> def app(environ, start_response): ... event = threading.Event() ... events.append(event) ... event.wait(30) ... start_response('200 OK', []) ... return '' >>> f = zc.zodbwsgi.make_filter( ... app, {}, '<zodb>\n<mappingstorage>\n</mappingstorage>\n</zodb>', ... max_connections='1', retry=0) Now, we've said to only allow 1 connection. If we make requests in threads, only one will be active at a time. >>> @zc.thread.Thread ... def t1(): ... webtest.TestApp(f).get('/') >>> @zc.thread.Thread ... def t2(): ... webtest.TestApp(f).get('/') >>> @zc.thread.Thread ... def t3(): ... webtest.TestApp(f).get('/') >>> time.sleep(.01) Even though there are 3 requests out standing, only 1 has made it to the app: >>> len(events) 1 If we complete one, the next will be handled: >>> events.pop().set() >>> time.sleep(.01) >>> len(events) 1 and so on: >>> events.pop().set() >>> time.sleep(.01) >>> len(events) 1 >>> events.pop().set() >>> time.sleep(.01) >>> len(events) 0 >>> t1.join() >>> t2.join() >>> t3.join() Check the no-transaction case: >>> f = zc.zodbwsgi.make_filter( ... app, {}, '<zodb>\n<mappingstorage>\n</mappingstorage>\n</zodb>', ... max_connections='1', retry=0, transaction_management='False') >>> @zc.thread.Thread ... def t1(): ... webtest.TestApp(f).get('/') >>> @zc.thread.Thread ... def t2(): ... webtest.TestApp(f).get('/') >>> @zc.thread.Thread ... def t3(): ... webtest.TestApp(f).get('/') >>> time.sleep(.01) >>> len(events) 1 >>> events.pop().set() >>> time.sleep(.01) >>> len(events) 1 >>> events.pop().set() >>> time.sleep(.01) >>> len(events) 1 >>> events.pop().set() >>> time.sleep(.01) >>> len(events) 0 >>> t1.join() >>> t2.join() >>> t3.join() Verify that we can monkey patch: >>> def app(environ, start_response): ... start_response('200 OK', []) ... return '' >>> import mock >>> with mock.patch("zc.zodbwsgi.Semaphore") as Semaphore: ... f = zc.zodbwsgi.make_filter( ... app, {}, '<zodb>\n<mappingstorage>\n</mappingstorage>\n</zodb>', ... max_connections='99', retry=0, transaction_management='False') ... Semaphore.assert_called_with(99) ... _ = webtest.TestApp(f).get('/') ... Semaphore.return_value.acquire.assert_called_with() ... Semaphore.return_value.release.assert_called_with() Escaping connection and transaction management ---------------------------------------------- Normally, having connections and transactions managed for you is convenient. Sometimes, however, you want to take over transaction management yourself. If you close ``environ['zodb.connection']``, then it won't be closed by ``zc.zodbwsgi``, nor will ``zc.zodbwsgi`` commit or abort the transaction it started. If you're using ``max_connections``, closing ``environ['zodb.connection']`` will make the connection available for other requests immediately, rather than waiting for your request to complete. .. test Normal (no error): >>> import sys >>> def app(environ, start_response): ... print 'about to close' ... environ['zodb.connection'].close() ... print 'closed' ... start_response('200 OK', []) ... return '' >>> with mock.patch('transaction.manager') as manager: ... with mock.patch("zc.zodbwsgi.Semaphore") as Semaphore: ... f = zc.zodbwsgi.make_filter( ... app, {}, ... '<zodb>\n<mappingstorage>\n</mappingstorage>\n</zodb>', ... max_connections='99', retry=0) ... Semaphore.assert_called_with(99) ... Semaphore.return_value.acquire.side_effect = ( ... lambda : sys.stdout.write('acquire\n')) ... Semaphore.return_value.release.side_effect = ( ... lambda : sys.stdout.write('release\n')) ... manager.begin.side_effect = ( ... lambda : sys.stdout.write('begin\n')) ... manager.commit.side_effect = ( ... lambda *a: sys.stdout.write('commit\n')) ... manager.abort.side_effect = ( ... lambda *a: sys.stdout.write('abort\n')) ... _ = webtest.TestApp(f).get('/') acquire begin about to close release closed Error: >>> def app(environ, start_response): ... print 'about to close' ... environ['zodb.connection'].close() ... print 'closed' ... raise ValueError('Fail') >>> with mock.patch('transaction.manager') as manager: ... with mock.patch("zc.zodbwsgi.Semaphore") as Semaphore: ... f = zc.zodbwsgi.make_filter( ... app, {}, ... '<zodb>\n<mappingstorage>\n</mappingstorage>\n</zodb>', ... max_connections='99', retry=0) ... Semaphore.assert_called_with(99) ... Semaphore.return_value.acquire.side_effect = ( ... lambda : sys.stdout.write('acquire\n')) ... Semaphore.return_value.release.side_effect = ( ... lambda : sys.stdout.write('release\n')) ... manager.begin.side_effect = ( ... lambda : sys.stdout.write('begin\n')) ... manager.commit.side_effect = ( ... lambda *a: sys.stdout.write('commit\n')) ... manager.abort.side_effect = ( ... lambda *a: sys.stdout.write('abort\n')) ... try: webtest.TestApp(f).get('/') ... except ValueError: pass acquire begin about to close release closed Dealing with the occasional long-running requests ------------------------------------------------- Database connections can be pretty expensive resources, especially if they have large database caches. For this reason, when using large caches, it's common to limit the number of application threads, to limit the number of connections used. If your application is compute bound, you generally want to use one application thread per process and a process per processor on the host machine. If your application itself makes network requests (e.g calling external service APIs), so it's network/server bound rather than compute bound, you should increase the number of application threads and decrease the size of the connection caches to compensate. If your application is mostly compute bound, but sometimes calls external services, you can take a hybrid approach: - Increase the number of application threads. - Set ``max_connections`` to 1. - In the parts of your application that make external service calls: - Close ``environ['zodb.connection']``, committing first, if necessary. - Make your service calls. - Open and close ZODB connections yourself when you need to use the database. If you're using ZEO or relstorage, you might want to create separate database clients for use in these calls, configured with smaller caches. Changes ======= 1.2.0 (2015-03-08) ------------------ - Record a request summary in transaction meta-data - Added dependencies to reflect imports. 1.1.0 (2014-04-22) ------------------ - Provide Python ``push`` and ``pop`` methods for use when testing and when running the server in the test process. 1.0.0 (2013-09-15) ------------------ - Added support for occasional long-running requests: - You can limit the number of database connections with max_connections. - You can take over connection and transaction management to release connections while blocking (typically when calling external services). - Add an option to use a thread-aware transaction manager, and make it the default. 0.3.0 (2013-03-07) ------------------ - Using the demostorage hook now returns a response immediately without processing the rest of the pipeline. Makes use of this feature less confusing. 0.2.1 (2013-03-06) ------------------ - Fix reference to a file that was renamed. 0.2.0 (2013-03-06) ------------------ - Add hooks to manage (push/pop) underlying demostorage based on headers. - Refactor filter to use instance attributes instead of a closure. 0.1.0 (2010-02-16) ------------------ Initial release .. [#multidb] If you want to use multiple ZODB databases, you can simply define them in your configuration option. Just make sure to give them names. When you want to access a database, use the ``get_connection`` method on the connection in the environment:: foo_conn = environ['zodb.connection'].get_connection('foo')
zc.zodbwsgi
/zc.zodbwsgi-1.2.0.tar.gz/zc.zodbwsgi-1.2.0/README.rst
README.rst
from threading import Semaphore import repoze.retry import transaction import ZODB.DemoStorage import ZODB.config from ZODB.DB import DB from zope.exceptions.interfaces import UserError to_bool = lambda val: {"true": True, "false": False}[val.lower()] class DatabaseFilter(object): def __init__( self, application, default, configuration, initializer=None, key=None, transaction_management=None, transaction_key=None, thread_transaction_manager=None, demostorage_manage_header=None, max_connections=None, ): self.application = application self.database = ZODB.config.databaseFromString(configuration) initializer = initializer or default.get('initializer') if initializer: module, expr = initializer.split(':', 1) if module: d = __import__(module, {}, {}, ['*']).__dict__ else: d={} initializer = eval(expr, d) initializer(self.database) self.key = key or default.get('key', 'zodb.connection') self.transaction_management = to_bool( transaction_management or default.get('transaction_management', 'true')) self.transaction_key = transaction_key or default.get( 'transaction_key', 'transaction.manager') self.thread_transaction_manager = to_bool( thread_transaction_manager or default.get("thread_transaction_manager", "true")) self.demostorage_management = to_bool( transaction_management or default.get('transaction_management', 'true')) header = (demostorage_manage_header or default.get('demostorage_manage_header')) if header is not None: for d in self.database.databases.values(): if not isinstance(d.storage, ZODB.DemoStorage.DemoStorage): raise UserError( "Attempting to activate demostorage hooks when " "one of the storages is not a DemoStorage") self.demostorage_manage_header = header and header.replace('-', '_') if max_connections: sem = Semaphore(int(max_connections)) self.acquire = sem.acquire self.release = sem.release def push(self): databases = {} for name, db in self.database.databases.items(): DB(db.storage.push(), databases=databases, database_name=name) self.database = databases[self.database.database_name] return self.database def pop(self): databases = {} for name, db in self.database.databases.items(): DB(db.storage.pop(), databases=databases, database_name=name) self.database = databases[self.database.database_name] return self.database def __call__(self, environ, start_response): if self.demostorage_manage_header is not None: # XXX See issue #3 regarding current implementation and Jim's # suggestions:: # # https://github.com/zopefoundation/zc.zodbwsgi/issues/3 action = environ.get('HTTP_' + self.demostorage_manage_header) status = '200 OK' response_headers = [('Content-type', 'text/plain')] if action == 'push': self.push() start_response(status, response_headers) return ['Demostorage pushed\n'] elif action == 'pop': self.pop() start_response(status, response_headers) return ['Demostorage popped\n'] closed = [] try: self.acquire() if self.transaction_management: if self.thread_transaction_manager: tm = transaction.manager else: tm = transaction.TransactionManager() environ[self.transaction_key] = tm else: tm = None conn = environ[self.key] = self.database.open(tm) @conn.onCloseCallback def on_close(): closed.append(1) self.release() try: if tm: try: tm.begin() tm.get().note( "%(REQUEST_METHOD)s " "%(SCRIPT_NAME)s %(PATH_INFO)s " "%(QUERY_STRING)s\n" % environ) result = self.application(environ, start_response) except: if not closed: tm.abort() raise else: if not closed: tm.commit() return result else: return self.application(environ, start_response) finally: if not closed: conn.close() environ.pop(self.transaction_key, 0) del environ[self.key] finally: if not closed: self.release() def acquire(self): pass release = acquire def make_filter( app, default, configuration, initializer=None, key=None, transaction_management=None, transaction_key=None, thread_transaction_manager=None, retry=None, max_memory_retry_buffer_size=1<<20, demostorage_manage_header=None, max_connections=None, ): db_app = DatabaseFilter( app, default, configuration, initializer=initializer, key=key, transaction_management=transaction_management, transaction_key=transaction_key, thread_transaction_manager=thread_transaction_manager, demostorage_manage_header=demostorage_manage_header, max_connections=max_connections) retry = int(retry or default.get('retry', '3')) if retry > 0: retry_app = repoze.retry.Retry(db_app, tries=retry+1) retry_app.database = db_app.database return retry_app return db_app
zc.zodbwsgi
/zc.zodbwsgi-1.2.0.tar.gz/zc.zodbwsgi-1.2.0/src/zc/zodbwsgi/__init__.py
__init__.py
******************************** zookeeper-deploy buildout script ******************************** Usage: Create a part in your rpm buildout:: [zookeeper-deploy] recipe = zc.recipe.egg eggs = zc.zookeeper_deploy_buildout arguments = 'APP', 'RECIPE' where APP the name of your application and the name of the directory in ``/etc`` where deployments will be recorded RECIPE the name of the meta-recipe to use In development mode, you can include initlization logic to run the recipe in development mode: [zookeeper-deploy] recipe = zc.recipe.egg eggs = zc.zookeeper_deploy_buildout arguments = 'APP', 'RECIPE' initialization = zc.zookeeper_deploy_buildout.development_mode = True Changes ******* 0.2.0 (2012-09-25) ================== - Allow the application name (APP) to be blank or None, in which case it's determined from the script name. - Added a -r option to specify a recipe entry point to the recipe supplied to main. 0.1.0 (2012-05-31) ================== Initial release
zc.zookeeper_deploy_buildout
/zc.zookeeper_deploy_buildout-0.2.0.tar.gz/zc.zookeeper_deploy_buildout-0.2.0/README.txt
README.txt
================= ZooKeeper Recipes ================= devtree ======= The devtree recipe sets up temporary ZooKeeper tree for a buildout:: [myproject] recipe = zc.zookeeperrecipes:devtree import-file = tree.txt .. -> conf *** Basics, default path, *** >>> def write(name, text): ... with open(name, 'w') as f: f.write(text) >>> write('tree.txt', """ ... x=1 ... type = 'foo' ... /a ... /b ... /c ... """) >>> import ConfigParser, StringIO, os >>> from zc.zookeeperrecipes import DevTree >>> here = os.getcwd() >>> buildoutbuildout = { ... 'directory': here, ... 'parts-directory': os.path.join(here, 'parts'), ... } >>> from pprint import pprint >>> class Raw: ... def __init__(self, parent): ... self.parent = parent ... def __setitem__(self, key, value): ... self.parent[key] = value ... print 'Raw: ', key ... pprint(value) >>> class TestBuildout(dict): ... @property ... def _raw(self): ... return Raw(self) >>> def buildout(): ... parser = ConfigParser.RawConfigParser() ... parser.readfp(StringIO.StringIO(conf)) ... buildout = TestBuildout((name, dict(parser.items(name))) ... for name in parser.sections()) ... [name] = buildout.keys() ... buildout['buildout'] = buildoutbuildout ... options = buildout[name] ... recipe = DevTree(buildout, name, options) ... return recipe, options >>> import zc.zookeeperrecipes, mock >>> with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:14.864772' ... recipe, options = buildout() >>> pprint(options) {'effective-path': '/myproject2012-01-26T14:50:14.864772', 'import-file': 'tree.txt', 'import-text': "\nx=1\ntype = 'foo'\n/a\n /b\n/c\n", 'location': '/testdirectory/parts/myproject', 'path': '/myproject', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> recipe.install() () >>> def cat(*path): ... with open(os.path.join(*path)) as f: ... return f.read() >>> cat('parts', 'myproject') '/myproject2012-01-26T14:50:14.864772' *** Test node name is persistent *** Updating doesn't change the name: >>> recipe, options = buildout() >>> recipe.update() () >>> options['effective-path'] == '/myproject2012-01-26T14:50:14.864772' True >>> cat('parts', 'myproject') '/myproject2012-01-26T14:50:14.864772' >>> import zc.zk >>> zk = zc.zk.ZooKeeper('127.0.0.1:2181') >>> zk.print_tree() /myproject2012-01-26T14:50:14.864772 : foo buildout:location = u'/testdirectory/parts/myproject' x = 1 /a /b /c *** Test updating tree source *** If there are changes, we see them >>> write('tree.txt', """ ... /a ... /d ... /c ... """) >>> buildout()[0].install() () >>> zk.print_tree() /myproject2012-01-26T14:50:14.864772 buildout:location = u'/testdirectory/parts/myproject' /a /d /c Now, if there are ephemeral nodes: >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/myproject2012-01-26T14:50:14.864772/a/d', ... 'x:y') >>> write('tree.txt', """ ... /a ... /b ... /c ... """) >>> buildout()[0].install() # doctest: +NORMALIZE_WHITESPACE Not deleting /myproject2012-01-26T14:50:14.864772/a/d/x:y because it's ephemeral. /myproject2012-01-26T14:50:14.864772/a/d not deleted due to ephemeral descendent. () >>> zk.print_tree() /myproject2012-01-26T14:50:14.864772 buildout:location = u'/testdirectory/parts/myproject' /a /b /d /x:y pid = 42 /c The ephemeral node, and the node containing it is left, but a warning is issued. *** Cleanup w different part name *** Now, let's change out buildout to use a different part name: >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-file = tree.txt ... """ >>> os.remove(os.path.join('parts', 'myproject')) Now, when we rerun the buildout, the old tree will get cleaned up: >>> import signal >>> with mock.patch('os.kill') as kill: ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:15.864772' ... recipe, options = buildout() ... recipe.install() ... kill.assert_called_with(42, signal.SIGTERM) () >>> pprint(options) {'effective-path': '/myproj2012-01-26T14:50:15.864772', 'import-file': 'tree.txt', 'import-text': '\n/a\n /b\n/c\n', 'location': '/testdirectory/parts/myproj', 'path': '/myproj', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/myproj2012-01-26T14:50:15.864772/a/b', ... 'x:y') >>> zk.print_tree() /myproj2012-01-26T14:50:15.864772 buildout:location = u'/testdirectory/parts/myproj' /a /b /x:y pid = 42 /c *** Cleanup w different path and explicit path, and creation of base nodes *** >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-file = tree.txt ... path = /ztest/path ... """ >>> with mock.patch('os.kill') as kill: ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:16.864772' ... recipe, options = buildout() ... recipe.install() ... kill.assert_called_with(42, signal.SIGTERM) () >>> pprint(options) {'effective-path': '/ztest/path2012-01-26T14:50:16.864772', 'import-file': 'tree.txt', 'import-text': '\n/a\n /b\n/c\n', 'location': '/tmp/tmpZ3mohq/testdirectory/parts/myproj', 'path': '/ztest/path', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/ztest/path2012-01-26T14:50:16.864772/a/b', ... 'x:y') >>> zk.print_tree() /ztest /path2012-01-26T14:50:16.864772 buildout:location = u'/tmp/tmpZ3mohq/testdirectory/parts/myproj' /a /b /x:y pid = 42 /c *** explicit effective-path *** We can control the effective-path directly: >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... effective-path = /my/path ... import-file = tree.txt ... """ This time, we'll also check that kill fail handlers are handled properly. >>> with mock.patch('os.kill') as kill: ... def noway(pid, sig): ... raise OSError ... kill.side_effect = noway ... recipe, options = buildout() ... recipe.install() ... kill.assert_called_with(42, signal.SIGTERM) () >>> pprint(options) {'effective-path': '/my/path', 'import-file': 'tree.txt', 'import-text': '\n/a\n /b\n/c\n', 'location': '/testdirectory/parts/myproj', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> zk.print_tree() # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS /my /path buildout:location = u'/tmp/tmpiKIi2U/testdirectory/parts/myproj' /a /b /c /ztest >>> zk.close() *** Non-local zookeeper no cleanup no/explicit import text *** **Note** because of the way zookeeper testing works, there's really only one zookeeper "server", so even though we're using a different connection string, we get the same db. >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... effective-path = /my/path ... zookeeper = zookeeper.example.com:2181 ... """ >>> recipe, options = buildout() >>> recipe.install() () >>> pprint(options) {'effective-path': '/my/path', 'location': '/tmp/tmpUAkJkK/testdirectory/parts/myproj', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': 'zookeeper.example.com:2181'} >>> zk = zc.zk.ZooKeeper('zookeeper.example.com:2181') >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/my/path', 'a:b') >>> zk.print_tree() /my /path buildout:location = u'/tmp/tmp2Qp4qX/testdirectory/parts/myproj' /a:b pid = 42 /ztest >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-text = /a ... zookeeper = zookeeper.example.com:2181 ... path = ... """ >>> with mock.patch('os.kill') as kill: ... def noway(pid, sig): ... print 'wtf killed' ... kill.side_effect = noway ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:24.864772' ... recipe, options = buildout() ... recipe.install() () >>> zk.print_tree() /2012-01-26T14:50:24.864772 buildout:location = u'/tmp/tmpxh1XPP/testdirectory/parts/myproj' /a /my /path buildout:location = u'/tmp/tmpxh1XPP/testdirectory/parts/myproj' /a:b pid = 42 /ztest In this example, we're creating a ZooKeeper tree at the path ``/myprojectYYYY-MM-DDTHH:MM:SS.SSSSSS`` with data imported from the buildout-local file ``tree.txt``, where YYYY-MM-DDTHH:MM:SS.SSSSSS is the ISO date-time when the node was created. The ``devtree`` recipe options are: zookeeper Optional ZooKeeper connection string. It defaults to '127.0.0.1:2181'. path Optional path at which to create the tree. If not provided, the part name is used, with a leading ``/`` added. When a ``devtree`` part is installed, a path is created at a path derived from the given (or implied) path by adding the current date and time to the path in ISO date-time format (YYYY-MM-DDTHH:MM:SS.SSSSSS). The derived path is stored a file in the buildout parts directory with a name equal to the section name. effective-path Optional path to be used as is. This option is normally computed by the recipe and is queryable from other recipes, but it may also be set explicitly. import-file Optional import file. This is the name of a file containing tree-definition text. See the ``zc.zk`` documentation for information on the format of this file. import-text Optional import text. Unfortunately, because of the way buildout parses configuration files, leading whitespace is stripped, making this option hard to specify. helper-scripts Helper-script prefix If provided, 4 helper scripts will be generated with the given prefix: PREFIXexport Export a zookeepeer tree. PREFIXimport Import a zookeepeer tree. PREFIXprint Print a zookeepeer tree. PREFIXport Print the port of the first child of a given path. Where PREFIX is the profix given to the helper-scripts option. .. test >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-text = /a ... zookeeper = zookeeper.example.com:2181 ... helper-scripts = zk- ... """ >>> with mock.patch('os.kill') as kill: ... def noway(pid, sig): ... print 'wtf killed' ... kill.side_effect = noway ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:24.864772' ... recipe, options = buildout() ... recipe.install() # doctest: +NORMALIZE_WHITESPACE Raw: zk-scripts {'arguments': "['zookeeper.example.com:2181/myproj2012-01-26T14:50:24.864772'] + sys.argv[1:]", 'eggs': 'zc.zk [static]', 'recipe': 'zc.recipe.egg', 'scripts': 'zookeeper_export=zk-export zookeeper_import=zk-import'} Raw: zk-print {'arguments': '[\'zookeeper.example.com:2181/myproj2012-01-26T14:50:24.864772\', "-e"] + sys.argv[1:]', 'eggs': 'zc.zk [static]', 'recipe': 'zc.recipe.egg', 'scripts': 'zookeeper_export=zk-print'} Raw: zk-port {'eggs': 'zc.zk [static]', 'entry-points': 'zk-port=time:time', 'initialization': "\nargs = sys.argv[1:]\nimport zc.zk\nzk = zc.zk.ZK('zookeeper.example.com:2181/myproj2012-01-26T14:50:24.864772')\npath = args.pop(0)\nif path[-1:] == '/':\n path += 'providers'\nchild = zk.get_children(path)[0]\nif args:\n [prop] = args\n child = zk.get_properties(path + '/' + child)[prop]\nprint child.split(':')[-1]\nzk.close()\n", 'recipe': 'zc.recipe.egg', 'scripts': 'zk-port'} () Cleanup ------- We don't want trees to accumulate indefinately. When using a local zookeeper (default), when the recipe is run, the entire tree is scanned looking for nodes that have ``buildout:location`` properties with paths that no-longer exist in the local file system paths that contain different ZooKeeper paths. If such nodes are found, then the nodes are removed and, if the nodes had any ephemeral subnodes with pids, those pids are sent a SIGTERM signal. Change History ============== 0.2.0 (2011-02-22) ------------------ Add an option to define buildout-specific helper scripts for working with the buildout's ZooKeeper tree. 0.1.2 (2011-02-13) ------------------ Fixed: default ZooKeeper connection string wasn't set as option and was thus not usable from other parts. 0.1.1 (2011-02-09) ------------------ Fixed a packaging bug. 0.1.0 (2011-02-02) ------------------ Initial release
zc.zookeeperrecipes
/zc.zookeeperrecipes-0.2.0.tar.gz/zc.zookeeperrecipes-0.2.0/README.txt
README.txt
================= ZooKeeper Recipes ================= devtree ======= The devtree recipe sets up temporary ZooKeeper tree for a buildout:: [myproject] recipe = zc.zookeeperrecipes:devtree import-file = tree.txt .. -> conf *** Basics, default path, *** >>> def write(name, text): ... with open(name, 'w') as f: f.write(text) >>> write('tree.txt', """ ... x=1 ... type = 'foo' ... /a ... /b ... /c ... """) >>> import ConfigParser, StringIO, os >>> from zc.zookeeperrecipes import DevTree >>> here = os.getcwd() >>> buildoutbuildout = { ... 'directory': here, ... 'parts-directory': os.path.join(here, 'parts'), ... } >>> from pprint import pprint >>> class Raw: ... def __init__(self, parent): ... self.parent = parent ... def __setitem__(self, key, value): ... self.parent[key] = value ... print 'Raw: ', key ... pprint(value) >>> class TestBuildout(dict): ... @property ... def _raw(self): ... return Raw(self) >>> def buildout(): ... parser = ConfigParser.RawConfigParser() ... parser.readfp(StringIO.StringIO(conf)) ... buildout = TestBuildout((name, dict(parser.items(name))) ... for name in parser.sections()) ... [name] = buildout.keys() ... buildout['buildout'] = buildoutbuildout ... options = buildout[name] ... recipe = DevTree(buildout, name, options) ... return recipe, options >>> import zc.zookeeperrecipes, mock >>> with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:14.864772' ... recipe, options = buildout() >>> pprint(options) {'effective-path': '/myproject2012-01-26T14:50:14.864772', 'import-file': 'tree.txt', 'import-text': "\nx=1\ntype = 'foo'\n/a\n /b\n/c\n", 'location': '/testdirectory/parts/myproject', 'path': '/myproject', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> recipe.install() () >>> def cat(*path): ... with open(os.path.join(*path)) as f: ... return f.read() >>> cat('parts', 'myproject') '/myproject2012-01-26T14:50:14.864772' *** Test node name is persistent *** Updating doesn't change the name: >>> recipe, options = buildout() >>> recipe.update() () >>> options['effective-path'] == '/myproject2012-01-26T14:50:14.864772' True >>> cat('parts', 'myproject') '/myproject2012-01-26T14:50:14.864772' >>> import zc.zk >>> zk = zc.zk.ZooKeeper('127.0.0.1:2181') >>> zk.print_tree() /myproject2012-01-26T14:50:14.864772 : foo buildout:location = u'/testdirectory/parts/myproject' x = 1 /a /b /c *** Test updating tree source *** If there are changes, we see them >>> write('tree.txt', """ ... /a ... /d ... /c ... """) >>> buildout()[0].install() () >>> zk.print_tree() /myproject2012-01-26T14:50:14.864772 buildout:location = u'/testdirectory/parts/myproject' /a /d /c Now, if there are ephemeral nodes: >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/myproject2012-01-26T14:50:14.864772/a/d', ... 'x:y') >>> write('tree.txt', """ ... /a ... /b ... /c ... """) >>> buildout()[0].install() # doctest: +NORMALIZE_WHITESPACE Not deleting /myproject2012-01-26T14:50:14.864772/a/d/x:y because it's ephemeral. /myproject2012-01-26T14:50:14.864772/a/d not deleted due to ephemeral descendent. () >>> zk.print_tree() /myproject2012-01-26T14:50:14.864772 buildout:location = u'/testdirectory/parts/myproject' /a /b /d /x:y pid = 42 /c The ephemeral node, and the node containing it is left, but a warning is issued. *** Cleanup w different part name *** Now, let's change out buildout to use a different part name: >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-file = tree.txt ... """ >>> os.remove(os.path.join('parts', 'myproject')) Now, when we rerun the buildout, the old tree will get cleaned up: >>> import signal >>> with mock.patch('os.kill') as kill: ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:15.864772' ... recipe, options = buildout() ... recipe.install() ... kill.assert_called_with(42, signal.SIGTERM) () >>> pprint(options) {'effective-path': '/myproj2012-01-26T14:50:15.864772', 'import-file': 'tree.txt', 'import-text': '\n/a\n /b\n/c\n', 'location': '/testdirectory/parts/myproj', 'path': '/myproj', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/myproj2012-01-26T14:50:15.864772/a/b', ... 'x:y') >>> zk.print_tree() /myproj2012-01-26T14:50:15.864772 buildout:location = u'/testdirectory/parts/myproj' /a /b /x:y pid = 42 /c *** Cleanup w different path and explicit path, and creation of base nodes *** >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-file = tree.txt ... path = /ztest/path ... """ >>> with mock.patch('os.kill') as kill: ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:16.864772' ... recipe, options = buildout() ... recipe.install() ... kill.assert_called_with(42, signal.SIGTERM) () >>> pprint(options) {'effective-path': '/ztest/path2012-01-26T14:50:16.864772', 'import-file': 'tree.txt', 'import-text': '\n/a\n /b\n/c\n', 'location': '/tmp/tmpZ3mohq/testdirectory/parts/myproj', 'path': '/ztest/path', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/ztest/path2012-01-26T14:50:16.864772/a/b', ... 'x:y') >>> zk.print_tree() /ztest /path2012-01-26T14:50:16.864772 buildout:location = u'/tmp/tmpZ3mohq/testdirectory/parts/myproj' /a /b /x:y pid = 42 /c *** explicit effective-path *** We can control the effective-path directly: >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... effective-path = /my/path ... import-file = tree.txt ... """ This time, we'll also check that kill fail handlers are handled properly. >>> with mock.patch('os.kill') as kill: ... def noway(pid, sig): ... raise OSError ... kill.side_effect = noway ... recipe, options = buildout() ... recipe.install() ... kill.assert_called_with(42, signal.SIGTERM) () >>> pprint(options) {'effective-path': '/my/path', 'import-file': 'tree.txt', 'import-text': '\n/a\n /b\n/c\n', 'location': '/testdirectory/parts/myproj', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': '127.0.0.1:2181'} >>> zk.print_tree() # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS /my /path buildout:location = u'/tmp/tmpiKIi2U/testdirectory/parts/myproj' /a /b /c /ztest >>> zk.close() *** Non-local zookeeper no cleanup no/explicit import text *** **Note** because of the way zookeeper testing works, there's really only one zookeeper "server", so even though we're using a different connection string, we get the same db. >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... effective-path = /my/path ... zookeeper = zookeeper.example.com:2181 ... """ >>> recipe, options = buildout() >>> recipe.install() () >>> pprint(options) {'effective-path': '/my/path', 'location': '/tmp/tmpUAkJkK/testdirectory/parts/myproj', 'recipe': 'zc.zookeeperrecipes:devtree', 'zookeeper': 'zookeeper.example.com:2181'} >>> zk = zc.zk.ZooKeeper('zookeeper.example.com:2181') >>> with mock.patch('os.getpid') as getpid: ... getpid.return_value = 42 ... zk.register_server('/my/path', 'a:b') >>> zk.print_tree() /my /path buildout:location = u'/tmp/tmp2Qp4qX/testdirectory/parts/myproj' /a:b pid = 42 /ztest >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-text = /a ... zookeeper = zookeeper.example.com:2181 ... path = ... """ >>> with mock.patch('os.kill') as kill: ... def noway(pid, sig): ... print 'wtf killed' ... kill.side_effect = noway ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:24.864772' ... recipe, options = buildout() ... recipe.install() () >>> zk.print_tree() /2012-01-26T14:50:24.864772 buildout:location = u'/tmp/tmpxh1XPP/testdirectory/parts/myproj' /a /my /path buildout:location = u'/tmp/tmpxh1XPP/testdirectory/parts/myproj' /a:b pid = 42 /ztest In this example, we're creating a ZooKeeper tree at the path ``/myprojectYYYY-MM-DDTHH:MM:SS.SSSSSS`` with data imported from the buildout-local file ``tree.txt``, where YYYY-MM-DDTHH:MM:SS.SSSSSS is the ISO date-time when the node was created. The ``devtree`` recipe options are: zookeeper Optional ZooKeeper connection string. It defaults to '127.0.0.1:2181'. path Optional path at which to create the tree. If not provided, the part name is used, with a leading ``/`` added. When a ``devtree`` part is installed, a path is created at a path derived from the given (or implied) path by adding the current date and time to the path in ISO date-time format (YYYY-MM-DDTHH:MM:SS.SSSSSS). The derived path is stored a file in the buildout parts directory with a name equal to the section name. effective-path Optional path to be used as is. This option is normally computed by the recipe and is queryable from other recipes, but it may also be set explicitly. import-file Optional import file. This is the name of a file containing tree-definition text. See the ``zc.zk`` documentation for information on the format of this file. import-text Optional import text. Unfortunately, because of the way buildout parses configuration files, leading whitespace is stripped, making this option hard to specify. helper-scripts Helper-script prefix If provided, 4 helper scripts will be generated with the given prefix: PREFIXexport Export a zookeepeer tree. PREFIXimport Import a zookeepeer tree. PREFIXprint Print a zookeepeer tree. PREFIXport Print the port of the first child of a given path. Where PREFIX is the profix given to the helper-scripts option. .. test >>> conf = """ ... [myproj] ... recipe = zc.zookeeperrecipes:devtree ... import-text = /a ... zookeeper = zookeeper.example.com:2181 ... helper-scripts = zk- ... """ >>> with mock.patch('os.kill') as kill: ... def noway(pid, sig): ... print 'wtf killed' ... kill.side_effect = noway ... with mock.patch('zc.zookeeperrecipes.timestamp') as ts: ... ts.return_value = '2012-01-26T14:50:24.864772' ... recipe, options = buildout() ... recipe.install() # doctest: +NORMALIZE_WHITESPACE Raw: zk-scripts {'arguments': "['zookeeper.example.com:2181/myproj2012-01-26T14:50:24.864772'] + sys.argv[1:]", 'eggs': 'zc.zk [static]', 'recipe': 'zc.recipe.egg', 'scripts': 'zookeeper_export=zk-export zookeeper_import=zk-import'} Raw: zk-print {'arguments': '[\'zookeeper.example.com:2181/myproj2012-01-26T14:50:24.864772\', "-e"] + sys.argv[1:]', 'eggs': 'zc.zk [static]', 'recipe': 'zc.recipe.egg', 'scripts': 'zookeeper_export=zk-print'} Raw: zk-port {'eggs': 'zc.zk [static]', 'entry-points': 'zk-port=time:time', 'initialization': "\nargs = sys.argv[1:]\nimport zc.zk\nzk = zc.zk.ZK('zookeeper.example.com:2181/myproj2012-01-26T14:50:24.864772')\npath = args.pop(0)\nif path[-1:] == '/':\n path += 'providers'\nchild = zk.get_children(path)[0]\nif args:\n [prop] = args\n child = zk.get_properties(path + '/' + child)[prop]\nprint child.split(':')[-1]\nzk.close()\n", 'recipe': 'zc.recipe.egg', 'scripts': 'zk-port'} () Cleanup ------- We don't want trees to accumulate indefinately. When using a local zookeeper (default), when the recipe is run, the entire tree is scanned looking for nodes that have ``buildout:location`` properties with paths that no-longer exist in the local file system paths that contain different ZooKeeper paths. If such nodes are found, then the nodes are removed and, if the nodes had any ephemeral subnodes with pids, those pids are sent a SIGTERM signal. Change History ============== 0.2.0 (2011-02-22) ------------------ Add an option to define buildout-specific helper scripts for working with the buildout's ZooKeeper tree. 0.1.2 (2011-02-13) ------------------ Fixed: default ZooKeeper connection string wasn't set as option and was thus not usable from other parts. 0.1.1 (2011-02-09) ------------------ Fixed a packaging bug. 0.1.0 (2011-02-02) ------------------ Initial release
zc.zookeeperrecipes
/zc.zookeeperrecipes-0.2.0.tar.gz/zc.zookeeperrecipes-0.2.0/src/zc/zookeeperrecipes/README.txt
README.txt
import datetime import logging import os import re import signal import textwrap import zc.buildout import zc.zk logger = logging.getLogger(__name__) def timestamp(): return datetime.datetime.now().isoformat() timestamped = re.compile(r'(.+)\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d+$').match class DevTree: def __init__(self, buildout, name, options): self.name, self.options = name, options if 'zookeeper' not in options: options['zookeeper'] = '127.0.0.1:2181' if 'import-file' in options: options['import-text'] = open(os.path.join( buildout['buildout']['directory'], options['import-file'])).read() options['location'] = location = os.path.join( buildout['buildout']['parts-directory'], name) if 'effective-path' not in options: path = options.get('path', name) if not path.startswith('/'): path = '/' + path options['path'] = path if os.path.exists(location): with open(location) as f: epath = f.read() m = timestamped(epath) if m and m.group(1) == path: options['effective-path'] = epath else: options['effective-path'] = path + timestamp() else: options['effective-path'] = path + timestamp() if not options.get('clean', 'auto') in ('auto', 'yes', 'no'): raise zc.buildout.UserError( 'clean must be one of "auto", "yes", or "no"') # helper scripts prefix = options.get('helper-scripts') if prefix: def add_section(name, options): buildout._raw[name] = options buildout[name] zk = options['zookeeper']+options['effective-path'] if prefix+'scripts' not in buildout: add_section(prefix+'scripts', dict( recipe = 'zc.recipe.egg', eggs = 'zc.zk [static]', scripts = ('zookeeper_export=%(prefix)sexport ' 'zookeeper_import=%(prefix)simport' % dict(prefix=prefix) ), arguments = '[%r] + sys.argv[1:]' % zk, )) if prefix+'print' not in buildout: add_section(prefix+'print', dict( recipe = 'zc.recipe.egg', eggs = 'zc.zk [static]', scripts = 'zookeeper_export=%sprint' % prefix, arguments = '[%r, "-e"] + sys.argv[1:]' % zk, )) if prefix+'port' not in buildout: add_section(prefix+'port', dict( recipe = 'zc.recipe.egg', eggs = 'zc.zk [static]', scripts = prefix+'port', initialization=zkport % zk, **{'entry-points': prefix+'port=time:time'} )) def install(self): options = self.options connection = options['zookeeper'] zk = zc.zk.ZooKeeper(connection) location = options['location'] path = options['effective-path'] base, name = path.rsplit('/', 1) if base: zk.create_recursive(base, '', zc.zk.OPEN_ACL_UNSAFE) zk.import_tree( '/'+name+'\n buildout:location = %r\n ' % location + textwrap.dedent( self.options.get('import-text', '') ).replace('\n', '\n '), base, trim=True) with open(location, 'w') as f: f.write(path) clean = options.get('clean', 'auto') if (clean == 'yes' or (clean == 'auto' and ( connection.startswith('localhost:') or connection.startswith('127.') ) ) ): self.clean(zk) return () update = install def clean(self, zk): for name in zk.get_children('/'): if name == 'zookeeper': continue self._clean(zk, '/'+name) def _clean(self, zk, path): location = zk.get_properties(path).get('buildout:location') if location is not None: if not os.path.exists(location) or readfile(location) != path: pids = [] for spath in zk.walk(path): if spath != path: if zk.is_ephemeral(spath): pid = zk.get_properties(spath).get('pid') if pid: pids.append(pid) zk.delete_recursive(path, force=True) for pid in pids: try: os.kill(pid, signal.SIGTERM) except OSError: logger.warn('Failed to kill') else: for name in zk.get_children(path): self._clean(zk, path + '/' + name) def readfile(path): with open(path) as f: return f.read() zkport = """ args = sys.argv[1:] import zc.zk zk = zc.zk.ZK(%r) path = args.pop(0) if path[-1:] == '/': path += 'providers' child = zk.get_children(path)[0] if args: [prop] = args child = zk.get_properties(path + '/' + child)[prop] print child.split(':')[-1] zk.close() """
zc.zookeeperrecipes
/zc.zookeeperrecipes-0.2.0.tar.gz/zc.zookeeperrecipes-0.2.0/src/zc/zookeeperrecipes/__init__.py
__init__.py
=============== Zope3 Recipes =============== The Zope 3 recipes allow one to define Zope applications and instances of those applications. A Zope application is a collection of software and software configuration, expressed as ZCML. A Zope instance invokes the application with a specific instance configuration. A single application may have many instances. Building Zope 3 applications (from eggs) ======================================== The 'application' recipe can be used to define a Zope application. It is designed to work with with Zope solely from eggs. The app recipe causes a part to be created. The part will contain the scripts runzope and debugzope and the application's site.zcml. Both of the scripts will require providing a -C option and the path to a zope.conf file when run. The debugzope script can be run with a script name and arguments, in which case it will run the script, rather than starting an interactive session. The 'application' recipe accepts the following options: site.zcml The contents of site.zcml. eggs The names of one or more eggs, with their dependencies that should be included in the Python path of the generated scripts. Lets define some (bogus) eggs that we can use in our application: >>> mkdir('demo1') >>> write('demo1', 'setup.py', ... ''' ... from setuptools import setup ... setup(name = 'demo1') ... ''') >>> mkdir('demo2') >>> write('demo2', 'setup.py', ... ''' ... from setuptools import setup ... setup(name = 'demo2', install_requires='demo1') ... ''') .. Please note that the "newest=false" option is set in the test SetUp to prevent upgrades We'll create a buildout.cfg file that defines our application: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ''' % globals()) Now, Let's run the buildout and see what we get: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. The runzope script runs the Web server: >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.twisted.main.main()) Here, unlike the above example the location path is not included in ``sys.path``. Similarly debugzope script is also changed: >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/site-packages', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.twisted.main)) The ``initialization`` setting can be used to provide a bit of additional code that will be included in the runzope and debugzope scripts just before the server's main function is called: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo2" /> ... eggs = demo2 ... initialization = ... print("Starting application server.") ... ''') Now, Let's run the buildout and see what we get: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. The runzope and debugzope scripts now include the additional code just before server is started: >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', ] <BLANKLINE> print("Starting application server.") <BLANKLINE> import zope.app.twisted.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.twisted.main.main()) >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/site-packages', ] <BLANKLINE> print("Starting application server.") import zope.app.twisted.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.twisted.main)) If the additional initialization for debugzope needs to be different from that of runzope, the ``debug-initialization`` setting can be used. If set, that is used for debugzope *instead* of the value of ``initialization``. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo2" /> ... eggs = demo2 ... initialization = ... print("Starting application server.") ... debug-initialization = ... print("Starting debugging interaction.") ... ''') Now, Let's run the buildout and see what we get: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/site-packages', ] <BLANKLINE> print("Starting debugging interaction.") import zope.app.twisted.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.twisted.main)) The runzope script still uses the ``initialization`` setting:: >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', ] <BLANKLINE> print("Starting application server.") <BLANKLINE> import zope.app.twisted.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.twisted.main.main()) Setting ``debug-initialization`` to an empty string suppresses the ``initialization`` setting for the debugzope script: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo2" /> ... eggs = demo2 ... initialization = ... print("Starting application server.") ... debug-initialization = ... ''') Now, Let's run the buildout and see what we get: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/site-packages', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.twisted.main)) Relative paths -------------- If requested in a buildout configuration, the scripts will be generated with relative paths instead of absolute. Let's change a buildout configuration to include ``relative-paths``. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... relative-paths = true ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. We get runzope script with relative paths. >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import os <BLANKLINE> join = os.path.join base = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) base = os.path.dirname(base) base = os.path.dirname(base) <BLANKLINE> import sys sys.path[0:0] = [ join(base, 'demo2'), join(base, 'demo1'), ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.twisted.main.main()) Similarly, debugzope script has relative paths. >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import os <BLANKLINE> join = os.path.join base = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) base = os.path.dirname(base) base = os.path.dirname(base) <BLANKLINE> import sys sys.path[0:0] = [ join(base, 'demo2'), join(base, 'demo1'), '/site-packages', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.twisted.main)) Building Zope 3 Applications (from Zope 3 checkouts/tarballs) ============================================================= The 'app' recipe works much like the 'application' recipe. It takes the same configuration options plus the following one: zope3 The name of a section defining a location option that gives the location of a Zope installation. This can be either a checkout or a distribution. If the location has a lib/python subdirectory, it is treated as a distribution, otherwise, it must have a src subdirectory and will be treated as a checkout. This option defaults to "zope3". And if location is empty, the application will run solely from eggs. Let's look at an example. We'll make a faux zope installation: >>> zope3 = tmpdir('zope3') >>> mkdir(zope3, 'src') Now we'll create a buildout.cfg file that defines our application: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ''' % globals()) Note that our site.zcml file is very small. It expect the application zcml to define almost everything. In fact, a site.zcml file will often include just a single include directive. We don't need to include the surrounding configure element, unless we want a namespace other than the zope namespace. A configure directive will be included for us. Let's run the buildout and see what we get: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. A directory is created in the parts directory for our application files. Starting with zc.buildout >= v1.5, and distribute, a "buildout" directory is created in the parts folder. Since the minimum version we support for zc.buildout is lower than v1.5, we use a custom "ls" functional called "ls_optional" to which we pass a list of folders that may be present. These are ignore by the function. >>> from zc.zope3recipes.tests import ls_optional >>> ls_optional('parts', ignore=('buildout',)) d myapp >>> ls('parts', 'myapp') - debugzope - runzope - site.zcml We get 3 files, two scripts and a site.zcml file. The site.zcml file is just what we had in the buildout configuration: >>> cat('parts', 'myapp', 'site.zcml') <configure xmlns='http://namespaces.zope.org/zope' xmlns:meta="http://namespaces.zope.org/meta" > <include package="demo2" /> <principal id="zope.manager" title="Manager" login="jim" password_manager="SHA1" password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" /> <grant role="zope.Manager" principal="zope.manager" /> </configure> Unfortunately, the leading whitespace is stripped from the configuration file lines. This is a consequence of the way ConfigParser works. The runzope script runs the Web server: >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/zope3/src', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.twisted.main.main()) It includes in it's path the eggs we specified in the configuration file, along with their dependencies. Note that we haven't specified a configuration file. When runzope is run, a -C option must be used to provide a configuration file. -X options can also be provided to override configuration file options. The debugzope script provides access to the object system. When debugzope is run, a -C option must be used to provide a configuration file. -X options can also be provided to override configuration file options. If run without any additional arguments, then an interactive interpreter will be started with databases specified in the configuration file opened and with the variable root set to the application root object. The debugger variable is set to a Zope 3 debugger. If additional arguments are provided, then the first argument should be a script name and the remaining arguments are script arguments. The script will be run with the root and debugger variables available as global variables. .. >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/zope3/src', '/site-packages', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.twisted.main)) Note that the runzope shown above uses the default, twisted-based server components. It's possible to specify which set of server components is used: the "servers" setting can be set to either "zserver" or "twisted". For the application, this affects the runzope script; we'll see additional differences when we create instances of the application. Let's continue to use the twisted servers, but make the selection explicit: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... servers = twisted ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Updating myapp. Note that this is recognized as not being a change to the configuration; the messages say that myapp was updated, not uninstalled and then re-installed. The runzope script generated is identical to what we saw before: >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/zope3/src', ] <BLANKLINE> import zope.app.twisted.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.twisted.main.main()) We can also specify the ZServer servers explicitly: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... servers = zserver ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. The part has been re-installed, and the runzope script generated is different now. Note that the main() function is imported from a different package this time: >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/zope3/src', ] <BLANKLINE> import zope.app.server.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.server.main.main()) The debugzope script has also been modified to take this into account. >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/sample-buildout/demo1', '/zope3/src', '/site-packages', ] <BLANKLINE> import zope.app.server.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.server.main)) Relative paths -------------- We can also request relative paths. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... relative-paths = true ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... servers = zserver ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. The runzope script has relative paths. >>> cat('parts', 'myapp', 'runzope') #!/usr/local/bin/python2.4 <BLANKLINE> import os <BLANKLINE> join = os.path.join base = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) base = os.path.dirname(base) base = os.path.dirname(base) <BLANKLINE> import sys sys.path[0:0] = [ join(base, 'demo2'), join(base, 'demo1'), '/zope3/src', ] <BLANKLINE> import zope.app.server.main <BLANKLINE> if __name__ == '__main__': sys.exit(zope.app.server.main.main()) The debugzope script also has relative paths. >>> cat('parts', 'myapp', 'debugzope') #!/usr/local/bin/python2.4 <BLANKLINE> import os <BLANKLINE> join = os.path.join base = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) base = os.path.dirname(base) base = os.path.dirname(base) <BLANKLINE> import sys sys.path[0:0] = [ join(base, 'demo2'), join(base, 'demo1'), '/zope3/src', '/site-packages', ] <BLANKLINE> import zope.app.server.main <BLANKLINE> <BLANKLINE> import zc.zope3recipes.debugzope <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.debugzope.debug(main_module=zope.app.server.main)) Legacy Functional Testing Support --------------------------------- Zope 3's functional testing support is based on zope.testing test layers. There is a default functional test layer that older functional tests use. This layer loads the default configuration for the Zope application server. It exists to provide support for older functional tests that were written before layers were added to the testing infrastructure. The default testing layer has a number of disadvantages: - It loads configurations for a large number of packages. This has the potential to introduce testing dependency on all of these packages. - It required a ftesting.zcml file and makes assumptions about where that file is. In particular, it assumes a location relative to the current working directory when the test is run. Newer software and maintained software should use their own functional testing layers that use test-configuration files defined in packages. To support older packages that use the default layer, a ftesting.zcml option is provided. If it is used, then the contents of the option are written to a ftesting.zcml file in the application. In addition, an ftesting-base.zcml file is written that includes configuration traditionally found in a Zope 3 ftesting-base.zcml excluding reference to package-includes. If we modify our buildout to include an ftesting.zcml option: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = myapp ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... ftesting.zcml = ... <meta:provides feature="devmode" /> ... <include file="ftesting-base.zcml" /> ... <includeOverrides package="demo2" /> ... eggs = demo2 ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. We'll get ftesting.zcml files and ftesting-base.zcml files created in the application: >>> cat('parts', 'myapp', 'ftesting.zcml') <configure xmlns='http://namespaces.zope.org/zope' xmlns:meta="http://namespaces.zope.org/meta" > <BLANKLINE> <meta:provides feature="devmode" /> <include file="ftesting-base.zcml" /> <includeOverrides package="demo2" /> </configure> >>> cat('parts', 'myapp', 'ftesting-base.zcml') <BLANKLINE> <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope" > <include package="zope.app" /> <include package="zope.app" file="ftesting.zcml" /> <include package="zope.app.securitypolicy" file="meta.zcml" /> <include package="zope.app.securitypolicy" /> <securityPolicy component="zope.app.securitypolicy.zopepolicy.ZopeSecurityPolicy" /> <role id="zope.Anonymous" title="Everybody" description="All users have this role implicitly" /> <role id="zope.Manager" title="Site Manager" /> <role id="zope.Member" title="Site Member" /> <grant permission="zope.View" role="zope.Anonymous" /> <grant permission="zope.app.dublincore.view" role="zope.Anonymous" /> <grantAll role="zope.Manager" /> <include package="zope.app.securitypolicy.tests" file="functional.zcml" /> <unauthenticatedPrincipal id="zope.anybody" title="Unauthenticated User" /> <unauthenticatedGroup id="zope.Anybody" title="Unauthenticated Users" /> <authenticatedGroup id="zope.Authenticated" title="Authenticated Users" /> <everybodyGroup id="zope.Everybody" title="All Users" /> <principal id="zope.mgr" title="Manager" login="mgr" password="mgrpw" /> <principal id="zope.globalmgr" title="Manager" login="globalmgr" password="globalmgrpw" /> <grant role="zope.Manager" principal="zope.globalmgr" /> </configure> Defining Zope3 instances ======================== Having defined an application, we can define one or more instances of the application. We do this using the zc.zope3recipes instance recipe. The instance recipe has 2 modes, a development and a production mode. We'll start with the development mode. In development mode, a part directory will be created for each instance containing the instance's configuration files. This directory will also contain run-time files created by the instances, such as log files or zdaemon socket files. When defining an instance, we need to specify a zope.conf file. The recipe can do most of the work for us. Let's look at a a basic example: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) The application option names an application part. The application part will be used to determine the location of the site.zcml file and the name of the control script to run. We specified a zope.conf option which contains a start at our final zope.conf file. The recipe will add some bits we leave out. The one thing we really need to have is a database definition. We simply include the zconfig option from the database section, which we provide as a file storage part using the zc.recipe.filestorage recipe. The filestorage recipe will create a directory to hold our database and compute a zconfig option that we can use in our instance section. Note that we've replaced the myapp part with the instance part. The myapp part will be included by virtue of the reference from the instance part. Let's run the buildout, and see what we get: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling myapp. Installing database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/sample-buildout/bin/instance'. We see that the database and myapp parts were included by virtue of being referenced from the instance part. We get new directories for our database and instance: >>> ls_optional('parts', ignore=('buildout',)) d database d instance d myapp The instance directory contains zdaemon.conf and zope.conf files: >>> ls('parts', 'instance') - zdaemon.conf - zope.conf Let's look at the zope.conf file that was generated: >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8080 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> This uses the twisted server types, since that's the default configuration for Zope 3. If we specify use of the ZServer servers, the names of the server types are adjusted appropriately: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... servers = zserver ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Uninstalling myapp. Updating database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/sample-buildout/bin/instance'. The generated zope.conf file now uses the ZServer server components instead: >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8080 type WSGI-HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> The Twisted-based servers can also be specified explicitly: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... servers = twisted ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Uninstalling myapp. Updating database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/sample-buildout/bin/instance'. The generated zope.conf file now uses the Twisted server components once more: >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8080 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> It includes the database definition that we provided in the zope.conf option. It has a site-definition option that names the site.zcml file from our application directory. We didn't specify any server or logging ZConfig sections, so some were generated for us. Note that, by default, the event-log output goes to standard output. We'll say more about that when we talk about the zdaemon configuration later. If we specify a server section ourselves: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... <server> ... type PostmortemDebuggingHTTP ... address 8080 ... </server> ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. Then the section (or sections) we provide will be used and new ones won't be added: >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8080 type PostmortemDebuggingHTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> If we just want to specify alternate ports or addresses, we can use the address option which accepts zero or more address specifications: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 foo.com:8082 ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8081 type HTTP </server> <BLANKLINE> <server> address foo.com:8082 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> We can specify our own accesslog and eventlog configuration. For example, to send the event-log output to a file and suppress the access log: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... <eventlog> ... <logfile> ... path ${buildout:parts-directory}/instance/event.log ... formatter zope.exceptions.log.Formatter ... </logfile> ... </eventlog> ... <accesslog> ... </accesslog> ... ... address = 8081 ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path /sample-buildout/parts/instance/event.log </logfile> </eventlog> <BLANKLINE> <accesslog> </accesslog> <BLANKLINE> <server> address 8081 type HTTP </server> Let's look at the zdaemon.conf file: >>> cat('parts', 'instance', 'zdaemon.conf') <runner> daemon on directory /sample-buildout/parts/instance program /sample-buildout/parts/myapp/runzope -C /sample-buildout/parts/instance/zope.conf socket-name /sample-buildout/parts/instance/zdaemon.sock transcript /sample-buildout/parts/instance/z3.log </runner> <BLANKLINE> <eventlog> <logfile> path /sample-buildout/parts/instance/z3.log </logfile> </eventlog> Here we see a fairly ordinary zdaemon.conf file. The program option refers to the runzope script in our application directory. The socket file, used for communication between the zdaemon command-line script and the zademon manager is placed in the instance directory. If you want to override any part of the generated zdaemon output, simply provide a zdaemon.conf option in your instance section: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. >>> cat('parts', 'instance', 'zdaemon.conf') <runner> daemon off directory /sample-buildout/parts/instance program /sample-buildout/parts/myapp/runzope -C /sample-buildout/parts/instance/zope.conf socket-name /sample-buildout/parts/instance/sock transcript /dev/null </runner> <BLANKLINE> <eventlog> </eventlog> In addition to the configuration files, a control script is generated in the buildout bin directory: >>> ls('bin') - buildout - instance .. >>> cat('bin', 'instance') #!/usr/local/bin/python2.4 <BLANKLINE> import sys sys.path[0:0] = [ '/site-packages', ] <BLANKLINE> import zc.zope3recipes.ctl <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.ctl.main([ '/sample-buildout/parts/myapp/debugzope', '/sample-buildout/parts/instance/zope.conf', '-C', '/sample-buildout/parts/instance/zdaemon.conf', ]+sys.argv[1:] )) Some configuration sections can include a key multiple times; the ZEO client section works this way. When a key is given multiple times, all values are included in the resulting configuration in the order in which they're give in the input:: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... server 127.0.0.1:8002 ... </zeoclient> ... </zodb> ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Uninstalling database. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <zeoclient> server 127.0.0.1:8001 server 127.0.0.1:8002 </zeoclient> </zodb> <BLANKLINE> <server> address 8081 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> Instance names -------------- The instance recipe generates files or directories based on its name, which defaults to the part name. We can specify a different name using the name option. This doesn't effect which parts directory is used, but it does affect the name of the run script in bin: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... name = server ... application = myapp ... zope.conf = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... server 127.0.0.1:8002 ... </zeoclient> ... </zodb> ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/server'. Specifying an alternate site definition --------------------------------------- Ideally, ZCML is used to configure the software used by an application and zope.conf is used to provide instance-specific configuration. For historical reasons, there are ZCML directives that provide process configuration. A good example of this is the smtpMailer directive provided by the zope.sendmail package. We can override the site-definition option in the zope.conf file to specify an alternate zcml file. Here, we'll update out instance configuration to use an alternate site definition: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ... site-definition ${buildout:directory}/site.zcml ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... server 127.0.0.1:8002 ... </zeoclient> ... </zodb> ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/site.zcml <BLANKLINE> <zodb> <zeoclient> server 127.0.0.1:8001 server 127.0.0.1:8002 </zeoclient> </zodb> <BLANKLINE> <server> address 8081 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/instance/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> (Note that, in practice, you'll often use the zc.recipe.deployment:configuration recipe, http://pypi.python.org/pypi/zc.recipe.deployment#configuration-files, to define a site.zcml file using the buildout.) Log files --------- The log file settings deserver some explanation. The Zope event log only captures output from logging calls. In particular, it doesn't capture startup errors written to standard error. The zdaemon transcript log is very useful for capturing this output. Without it, error written to standard error are lost when running as a daemon. The default Zope 3 configuration in the past was to write the Zope access and event log output to both files and standard output and to define a transcript log. This had the effect that the transcript duplicated the contents of the event log and access logs, in addition to capturing other output. This was space inefficient. This recipe's approach is to combine the zope and zdaemon event-log information as well as Zope error output into a single log file. We do this by directing Zope's event log to standard output, where it is useful when running Zope in foreground mode and where it can be captured by the zdaemon transcript log. Unix Deployments ---------------- The instance recipe provides support for Unix deployments, as provided by the zc.recipe.deployment recipe. A deployment part defines a number of options used by the instance recipe: etc-directory The name of the directory where configuration files should be placed. This defaults to /etc/NAME, where NAME is the deployment name. log-directory The name of the directory where application instances should write their log files. This defaults to /var/log/NAME, where NAME is the deployment name. run-directory The name of the directory where application instances should put their run-time files such as pid files and inter-process communication socket files. This defaults to /var/run/NAME, where NAME is the deployment name. rc-directory The name of the directory where run-control scripts should be installed. logrotate-directory The name of the directory where logrotate configuration files should be installed. user The name of a user that processes should run as. The deployment recipe has to be run as root for various reasons, but we can create a faux deployment by providing a section with the needed data. Let's update our configuration to use a deployment. We'll first create a faux installation root: >>> root = tmpdir('root') >>> mkdir(root, 'etc') >>> mkdir(root, 'etc', 'myapp-run') >>> mkdir(root, 'etc', 'init.d') >>> mkdir(root, 'etc', 'logrotate.d') >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 ... deployment = myapp-deployment ... ... [database] ... recipe = zc.recipe.filestorage ... ... [myapp-deployment] ... name = myapp-run ... etc-directory = %(root)s/etc/myapp-run ... rc-directory = %(root)s/etc/init.d ... logrotate-directory = %(root)s/etc/logrotate.d ... log-directory = %(root)s/var/log/myapp-run ... run-directory = %(root)s/var/run/myapp-run ... user = zope ... ''' % globals()) Here we've added a deployment section, myapp-deployment, and added a deployment option to our instance part telling the instance recipe to use the deployment. If we rerun the buildout: >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Installing database. Updating myapp. Installing instance. Generated script '/root/etc/init.d/myapp-run-instance'. The installer files will move. We'll no-longer have the instance part: >>> ls_optional('parts', ignore=('buildout',)) d database d myapp or the control script: >>> ls('bin') - buildout Rather, we'll get our configuration files in the /etc/myapp-run directory: >>> ls(root, 'etc', 'myapp-run') - instance-zdaemon.conf - instance-zope.conf Note that the instance name was added as a prefix to the file names, since we'll typically have additional instances in the deployment. The control script is in the init.d directory: >>> ls(root, 'etc', 'init.d') - myapp-run-instance Note that the deployment name is added as a prefix of the control script name. The logrotate file is in the logrotate.d directory: >>> ls(root, 'etc', 'logrotate.d') - myapp-run-instance The configuration files have changed to reflect the deployment locations: >>> cat(root, 'etc', 'myapp-run', 'instance-zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8081 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /root/var/log/myapp-run/instance-access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> >>> cat(root, 'etc', 'myapp-run', 'instance-zdaemon.conf') <runner> daemon on directory /root/var/run/myapp-run program /sample-buildout/parts/myapp/runzope -C /root/etc/myapp-run/instance-zope.conf socket-name /root/var/run/myapp-run/instance-zdaemon.sock transcript /root/var/log/myapp-run/instance-z3.log user zope </runner> <BLANKLINE> <eventlog> <logfile> path /root/var/log/myapp-run/instance-z3.log </logfile> </eventlog> >>> cat(root, 'etc', 'logrotate.d', 'myapp-run-instance') /root/var/log/myapp-run/instance-z3.log { rotate 5 weekly postrotate /root/etc/init.d/myapp-run-instance reopen_transcript endscript } If we provide an alternate instance name, that will be reflected in the generated files: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... name = server ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 ... deployment = myapp-deployment ... ... [database] ... recipe = zc.recipe.filestorage ... ... [myapp-deployment] ... name = myapp-run ... etc-directory = %(root)s/etc/myapp-run ... rc-directory = %(root)s/etc/init.d ... logrotate-directory = %(root)s/etc/logrotate.d ... log-directory = %(root)s/var/log/myapp-run ... run-directory = %(root)s/var/run/myapp-run ... user = zope ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/root/etc/init.d/myapp-run-server'. >>> cat(root, 'etc', 'myapp-run', 'server-zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8081 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /root/var/log/myapp-run/server-access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> >>> cat(root, 'etc', 'myapp-run', 'server-zdaemon.conf') <runner> daemon on directory /root/var/run/myapp-run program /sample-buildout/parts/myapp/runzope -C /root/etc/myapp-run/server-zope.conf socket-name /root/var/run/myapp-run/server-zdaemon.sock transcript /root/var/log/myapp-run/server-z3.log user zope </runner> <BLANKLINE> <eventlog> <logfile> path /root/var/log/myapp-run/server-z3.log </logfile> </eventlog> Controlling logrotate configuration ----------------------------------- Some applications control their own log rotation policies. In these cases, we don't want the logrotate configuration to be generated. Setting the logrotate.conf setting affects the configuration. Setting it explicitly controls the content of the logrotate file for the instance; setting it to an empty string causes it not to be generated at all. Let's take a look at setting the content to a non-empty value directly: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 ... deployment = myapp-deployment ... logrotate.conf = ... /root/var/log/myapp-run/instance-z3.log { ... rotate 10 ... daily ... postrotate ... /root/etc/init.d/myapp-run-instance reopen_transcript ... endscript ... } ... ... [database] ... recipe = zc.recipe.filestorage ... ... [myapp-deployment] ... name = myapp-run ... etc-directory = %(root)s/etc/myapp-run ... rc-directory = %(root)s/etc/init.d ... logrotate-directory = %(root)s/etc/logrotate.d ... log-directory = %(root)s/var/log/myapp-run ... run-directory = %(root)s/var/run/myapp-run ... user = zope ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Uninstalling myapp. Updating database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/root/etc/init.d/myapp-run-instance'. >>> cat(root, 'etc', 'logrotate.d', 'myapp-run-instance') /root/var/log/myapp-run/instance-z3.log { rotate 10 daily postrotate /root/etc/init.d/myapp-run-instance reopen_transcript endscript } If we set ``logrotate.conf`` to an empty string, the file is not generated: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 ... deployment = myapp-deployment ... logrotate.conf = ... ... [database] ... recipe = zc.recipe.filestorage ... ... [myapp-deployment] ... name = myapp-run ... etc-directory = %(root)s/etc/myapp-run ... rc-directory = %(root)s/etc/init.d ... logrotate-directory = %(root)s/etc/logrotate.d ... log-directory = %(root)s/var/log/myapp-run ... run-directory = %(root)s/var/run/myapp-run ... user = zope ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/root/etc/init.d/myapp-run-instance'. >>> ls(root, 'etc', 'logrotate.d') Defining multiple similar instances ----------------------------------- Often you want to define multiple instances that differ only by one or two options (e.g. an address). The extends option lets you name a section from which default options should be loaded. Any options in the source section not defined in the extending section are added to the extending section. Let's update our buildout to add a new instance: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance instance2 ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... address = 8081 ... deployment = myapp-deployment ... ... [instance2] ... recipe = zc.zope3recipes:instance ... extends = instance ... address = 8082 ... ... [database] ... recipe = zc.recipe.filestorage ... ... [myapp-deployment] ... name = myapp-run ... etc-directory = %(root)s/etc/myapp-run ... rc-directory = %(root)s/etc/init.d ... logrotate-directory = %(root)s/etc/logrotate.d ... log-directory = %(root)s/var/log/myapp-run ... run-directory = %(root)s/var/run/myapp-run ... user = zope ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Uninstalling myapp. Updating database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/root/etc/init.d/myapp-run-instance'. Installing instance2. Generated script '/root/etc/init.d/myapp-run-instance2'. Now, we have the new instance configuration files: >>> ls(root, 'etc', 'myapp-run') - instance-zdaemon.conf - instance-zope.conf - instance2-zdaemon.conf - instance2-zope.conf >>> cat(root, 'etc', 'myapp-run', 'instance2-zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <server> address 8082 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /root/var/log/myapp-run/instance2-access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> Relative paths -------------- Relative paths will be used in the control script if they are requested in a buildout configuration. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... relative-paths = true ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ${database:zconfig} ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance2. Uninstalling instance. Uninstalling myapp. Updating database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/sample-buildout/bin/instance'. Both ``sys.path`` and arguments to the `ctl` are using relative paths now. >>> cat('bin', 'instance') #!/usr/local/bin/python2.4 <BLANKLINE> import os <BLANKLINE> join = os.path.join base = os.path.dirname(os.path.abspath(os.path.realpath(__file__))) base = os.path.dirname(base) <BLANKLINE> import sys sys.path[0:0] = [ '/site-packages', ] <BLANKLINE> import zc.zope3recipes.ctl <BLANKLINE> if __name__ == '__main__': sys.exit(zc.zope3recipes.ctl.main([ join(base, 'parts/myapp/debugzope'), join(base, 'parts/instance/zope.conf'), '-C', join(base, 'parts/instance/zdaemon.conf'), ]+sys.argv[1:] )) zope.conf recipe ================ The zope.conf recipe handles filling in the implied bits of a zope.conf file that the instance recipe performs, without creating the rest of an instance. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 ... parts = some.conf ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo1" /> ... eggs = demo1 ... ... [some.conf] ... recipe = zc.zope3recipes:zopeconf ... application = myapp ... text = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... </zeoclient> ... </zodb> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Uninstalling instance. Uninstalling myapp. Uninstalling database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing some.conf. >>> cat('parts', 'some.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <zeoclient> server 127.0.0.1:8001 </zeoclient> </zodb> <BLANKLINE> <server> address 8080 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/some-access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> We can specify the location of the access log directly in the part: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 ... parts = some.conf ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo1" /> ... eggs = demo1 ... ... [some.conf] ... recipe = zc.zope3recipes:zopeconf ... application = myapp ... access-log = ${buildout:directory}/access.log ... text = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... </zeoclient> ... </zodb> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/tmp/tmp2eRRw1buildoutSetUp/_TEST_/sample-buildout/demo1' Uninstalling some.conf. Updating myapp. Installing some.conf. >>> cat('parts', 'some.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <zeoclient> server 127.0.0.1:8001 </zeoclient> </zodb> <BLANKLINE> <server> address 8080 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> The address of the server can be set using the "address" setting: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 ... parts = some.conf ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo1" /> ... eggs = demo1 ... ... [some.conf] ... recipe = zc.zope3recipes:zopeconf ... address = 4242 ... application = myapp ... text = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... </zeoclient> ... </zodb> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/tmp/tmp2eRRw1buildoutSetUp/_TEST_/sample-buildout/demo1' Uninstalling some.conf. Updating myapp. Installing some.conf. >>> cat('parts', 'some.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <zeoclient> server 127.0.0.1:8001 </zeoclient> </zodb> <BLANKLINE> <server> address 4242 type HTTP </server> <BLANKLINE> <accesslog> <logfile> path /sample-buildout/parts/some-access.log </logfile> </accesslog> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> The location of the file is made available as the "location" setting. This parallels the zc.recipe.deployment:configuration recipe, making this a possible replacement for that recipe where appropriate. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 ... parts = another.conf ... ... [myapp] ... recipe = zc.zope3recipes:application ... site.zcml = <include package="demo1" /> ... eggs = demo1 ... ... [some.conf] ... recipe = zc.zope3recipes:zopeconf ... application = myapp ... text = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... </zeoclient> ... </zodb> ... ... [another.conf] ... recipe = zc.zope3recipes:zopeconf ... application = myapp ... text = ... ${some.conf:text} ... <product-config reference> ... config ${some.conf:location} ... </product-config> ... ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/tmp/tmp2eRRw1buildoutSetUp/_TEST_/sample-buildout/demo1' Uninstalling some.conf. Updating myapp. Installing some.conf. Installing another.conf. >>> cat('parts', 'another.conf') site-definition /sample-buildout/parts/myapp/site.zcml ... <product-config reference> config /sample-buildout/parts/some.conf </product-config> ... Offline recipe ============== The offline recipe creates a script that in some ways is a syntactic sugar for "bin/instance debug" or "bin/instance run <script>". With the offline script, all you do is "bin/offline" or "bin/offline </script>". This script doesn't create additional folders like the ``Instance`` recipe; it expects two options: "application" and "zope.conf" that must be sections for a Zope3 application and a configuration file (that supports a "location" option) to exist. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance offline ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... name = server ... application = myapp ... zope.conf = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... server 127.0.0.1:8002 ... </zeoclient> ... </zodb> ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... [offline.conf] ... location = %(zope3)s ... ... [offline] ... recipe = zc.zope3recipes:offline ... application = myapp ... zope.conf = offline.conf ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling another.conf. Uninstalling some.conf. Uninstalling myapp. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/sample-buildout/bin/server'. Installing offline. >>> cat('bin', 'offline') #!/usr/local/bin/python2.4 <BLANKLINE> import os import sys import logging <BLANKLINE> argv = list(sys.argv) env = {} restart = False <BLANKLINE> if None: import pwd if pwd.getpwnam(None).pw_uid != os.geteuid(): restart = True argv[:0] = ["sudo", "-u", None] # print("switching to user %s" % None) del pwd <BLANKLINE> for k in env: if os.environ.get(k) != env[k]: os.environ[k] = env[k] restart = True del k <BLANKLINE> if restart: # print("restarting") os.execvpe(argv[0], argv, dict(os.environ)) <BLANKLINE> del argv del env del restart <BLANKLINE> sys.argv[1:1] = [ "-C", '/zope3', <BLANKLINE> ] <BLANKLINE> debugzope = '/sample-buildout/parts/myapp/debugzope' globals()["__file__"] = debugzope <BLANKLINE> zeo_logger = logging.getLogger('ZEO.zrpc') zeo_logger.addHandler(logging.StreamHandler()) <BLANKLINE> <BLANKLINE> # print("starting debugzope...") with open(debugzope) as f: exec(f.read()) initialization option --------------------- The recipe also accepts an "initialization" option: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance offline ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... name = server ... application = myapp ... zope.conf = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... server 127.0.0.1:8002 ... </zeoclient> ... </zodb> ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... [offline.conf] ... location = %(zope3)s ... ... [offline] ... recipe = zc.zope3recipes:offline ... initialization = ... os.environ['ZC_DEBUG_LOGGING'] = 'on' ... application = myapp ... zope.conf = offline.conf ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling offline. Updating myapp. Updating instance. Installing offline. >>> cat('bin', 'offline') <BLANKLINE> import os import sys import logging <BLANKLINE> argv = list(sys.argv) env = {} restart = False <BLANKLINE> if None: import pwd if pwd.getpwnam(None).pw_uid != os.geteuid(): restart = True argv[:0] = ["sudo", "-u", None] # print("switching to user %s" % None) del pwd <BLANKLINE> for k in env: if os.environ.get(k) != env[k]: os.environ[k] = env[k] restart = True del k <BLANKLINE> if restart: # print("restarting") os.execvpe(argv[0], argv, dict(os.environ)) <BLANKLINE> del argv del env del restart <BLANKLINE> sys.argv[1:1] = [ "-C", '/zope3', <BLANKLINE> ] <BLANKLINE> debugzope = '/sample-buildout/parts/myapp/debugzope' globals()["__file__"] = debugzope <BLANKLINE> zeo_logger = logging.getLogger('ZEO.zrpc') zeo_logger.addHandler(logging.StreamHandler()) <BLANKLINE> os.environ['ZC_DEBUG_LOGGING'] = 'on' <BLANKLINE> # print("starting debugzope...") with open(debugzope) as f: exec(f.read()) script option ------------- as well as a "script" option. >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance run-foo ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:app ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... name = server ... application = myapp ... zope.conf = ... <zodb> ... <zeoclient> ... server 127.0.0.1:8001 ... server 127.0.0.1:8002 ... </zeoclient> ... </zodb> ... address = 8081 ... zdaemon.conf = ... <runner> ... daemon off ... socket-name /sample-buildout/parts/instance/sock ... transcript /dev/null ... </runner> ... <eventlog> ... </eventlog> ... ... [offline.conf] ... location = %(zope3)s ... ... [run-foo] ... recipe = zc.zope3recipes:offline ... initialization = ... os.environ['ZC_DEBUG_LOGGING'] = 'on' ... application = myapp ... zope.conf = offline.conf ... script = %(zope3)s/foo.py ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling offline. Updating myapp. Updating instance. Installing run-foo. >>> cat('bin', 'run-foo') <BLANKLINE> import os import sys import logging <BLANKLINE> argv = list(sys.argv) env = {} restart = False <BLANKLINE> if None: import pwd if pwd.getpwnam(None).pw_uid != os.geteuid(): restart = True argv[:0] = ["sudo", "-u", None] # print("switching to user %s" % None) del pwd <BLANKLINE> for k in env: if os.environ.get(k) != env[k]: os.environ[k] = env[k] restart = True del k <BLANKLINE> if restart: # print("restarting") os.execvpe(argv[0], argv, dict(os.environ)) <BLANKLINE> del argv del env del restart <BLANKLINE> sys.argv[1:1] = [ "-C", '/zope3', '/zope3/foo.py' ] <BLANKLINE> debugzope = '/sample-buildout/parts/myapp/debugzope' globals()["__file__"] = debugzope <BLANKLINE> zeo_logger = logging.getLogger('ZEO.zrpc') zeo_logger.addHandler(logging.StreamHandler()) <BLANKLINE> os.environ['ZC_DEBUG_LOGGING'] = 'on' <BLANKLINE> # print("starting debugzope...") with open(debugzope) as f: exec(f.read()) Paste-deployment support ======================== You can use paste-deployment to control WSGI servers and middleware. You indicate this by specifying ``paste`` in the ``servers`` option: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:application ... servers = paste ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ... threads 1 ... ${database:zconfig} ... ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) When we run the buildout, we'll get a paste-based runzope script and paste-based instance start scripts. .. test >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling run-foo. Uninstalling instance. Uninstalling myapp. Installing database. Installing myapp. Generated script '/sample-buildout/parts/myapp/runzope'. Generated script '/sample-buildout/parts/myapp/debugzope'. Installing instance. Generated script '/sample-buildout/bin/instance'. >>> cat('parts', 'myapp', 'runzope') #!/usr/local/python/2.6/bin/python2.6 <BLANKLINE> import sys sys.path[0:0] = [ '/sample-buildout/demo2', '/site-packages', '/sample-buildout/demo1', ] <BLANKLINE> import paste.script.command <BLANKLINE> if __name__ == '__main__': sys.exit(paste.script.command.run(['serve']+sys.argv[1:])) >>> cat('parts', 'instance', 'zope.conf') site-definition /sample-buildout/parts/myapp/site.zcml <BLANKLINE> <zodb> <filestorage> path /sample-buildout/parts/database/Data.fs </filestorage> </zodb> <BLANKLINE> <logger accesslog> level info name accesslog propagate false <BLANKLINE> <logfile> format %(message)s path /sample-buildout/parts/instance/access.log </logfile> </logger> <BLANKLINE> <eventlog> <logfile> formatter zope.exceptions.log.Formatter path STDOUT </logfile> </eventlog> >>> cat('parts', 'instance', 'zdaemon.conf') <runner> daemon on directory /sample-buildout/parts/instance program /sample-buildout/parts/myapp/runzope /sample-buildout/parts/instance/paste.ini socket-name /sample-buildout/parts/instance/zdaemon.sock transcript /sample-buildout/parts/instance/z3.log </runner> <BLANKLINE> <eventlog> <logfile> path /sample-buildout/parts/instance/z3.log </logfile> </eventlog> We also get a paste.ini file in the instance directory, which defines the application and server and is used when running paste:: >>> cat('parts', 'instance', 'paste.ini') [app:main] use = egg:zope.app.wsgi config_file = /sample-buildout/parts/instance/zope.conf filter-with = translogger <BLANKLINE> [filter:translogger] use = egg:Paste#translogger setup_console_handler = False logger_name = accesslog <BLANKLINE> [server:main] use = egg:zope.server host = port = 8080 threads = 1 Note that the threads setting made in zope.conf was moved to paste.ini Note too that past:translogger was used to provide an access log. If you don't want to use zope.server, or if you want to control the server configuration yourself, you can provide a paste.init option:: >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = demo1 demo2 ... parts = instance ... ... [zope3] ... location = %(zope3)s ... ... [myapp] ... recipe = zc.zope3recipes:application ... servers = paste ... site.zcml = <include package="demo2" /> ... <principal ... id="zope.manager" ... title="Manager" ... login="jim" ... password_manager="SHA1" ... password="40bd001563085fc35165329ea1ff5c5ecbdbbeef" ... /> ... <grant ... role="zope.Manager" ... principal="zope.manager" ... /> ... eggs = demo2 ... ... [instance] ... recipe = zc.zope3recipes:instance ... application = myapp ... zope.conf = ... threads 1 ... ${database:zconfig} ... paste.ini = test and not working :) ... ... ... [database] ... recipe = zc.recipe.filestorage ... ''' % globals()) .. test >>> print(system(join('bin', 'buildout'))) Develop: '/sample-buildout/demo1' Develop: '/sample-buildout/demo2' Uninstalling instance. Updating database. Updating myapp. Installing instance. Generated script '/sample-buildout/bin/instance'. In this example, we gave useless text in the paste.ini option and we got a nonsense paste.ini file:: >>> cat('parts', 'instance', 'paste.ini') [app:main] use = egg:zope.app.wsgi config_file = /sample-buildout/parts/instance/zope.conf <BLANKLINE> test and not working :) This illustrates that the recipe doesn't care what you provide. It uses it with the application definition instead of supplying zope.server and paste.translogger definition.
zc.zope3recipes
/zc.zope3recipes-1.0-py3-none-any.whl/zc/zope3recipes/README.rst
README.rst
import os import sys import traceback import zope.app.appsetup.interfaces import zope.app.appsetup.product import zope.app.debug from zope.event import notify def load_options(args, main_module=None): options = main_module.ZopeOptions() options.schemadir = os.path.dirname(os.path.abspath( main_module.__file__)) options.positional_args_allowed = True options.realize(args) if options.configroot.path: sys.path[:0] = [os.path.abspath(p) for p in options.configroot.path] return options def zglobals(options): zope.app.appsetup.product.setProductConfigurations(options.product_config) zope.app.appsetup.config(options.site_definition) db = zope.app.appsetup.appsetup.multi_database(options.databases)[0][0] notify(zope.app.appsetup.interfaces.DatabaseOpened(db)) globs = {"__name__": "__main__"} startup = os.environ.get("PYTHONSTARTUP") if startup: try: with open(startup) as f: globs["__file__"] = startup exec(f.read(), globs) del globs["__file__"] except OSError: # Not readable or not there, which is allowed. pass app = zope.app.debug.Debugger.fromDatabase(db) globs["app"] = app globs["debugger"] = app globs["root"] = app.root() return globs def debug(args=None, main_module=None): if args is None: args = sys.argv[1:] options = load_options(args, main_module=main_module) if 'ZC_DEBUG_LOGGING' in os.environ: options.configroot.eventlog.startup() try: globs = zglobals(options.configroot) except Exception: if options.args: raise else: traceback.print_exc() import pdb pdb.post_mortem(sys.exc_info()[2]) return args = options.args if args: sys.argv[:] = args globs['__file__'] = sys.argv[0] with open(sys.argv[0]) as f: code = compile(f.read(), sys.argv[0], 'exec') exec(code, globs) sys.exit() else: import code code.interact(banner=banner, local=globs) banner = """Welcome to the Zope 3 "debugger". The application root object is available as the root variable. A Zope debugger instance is available as the debugger (aka app) variable. """
zc.zope3recipes
/zc.zope3recipes-1.0-py3-none-any.whl/zc/zope3recipes/debugzope.py
debugzope.py
import io import logging import os import pprint import re import shutil import sys import pkg_resources import zc.buildout import zc.recipe.egg import ZConfig.schemaless this_loc = pkg_resources.working_set.find( pkg_resources.Requirement.parse('zc.zope3recipes')).location server_types = { # name (module, http-name) 'twisted': ('zope.app.twisted.main', 'HTTP'), 'zserver': ('zope.app.server.main', 'WSGI-HTTP'), 'paste': ('zope.app.server.main', ''), } WIN = False if sys.platform[:3].lower() == "win": WIN = True def get_executable(section): # Support older multi-python buildouts, and newer mono-python buildouts. return section.get("executable") or sys.executable class Application: def __init__(self, buildout, name, options): self.options = options self.name = name options['location'] = os.path.join( buildout['buildout']['parts-directory'], name, ) options['servers'] = options.get('servers', 'twisted') if options['servers'] not in server_types: raise ValueError( 'servers setting must be one of %s' % repr(sorted(server_types))[1:-1] ) if options['servers'] == 'paste': options['eggs'] += '\n PasteScript\n' options['scripts'] = '' self.egg = zc.recipe.egg.Egg(buildout, name, options) def install(self): options = self.options dest = options['location'] if not os.path.exists(dest): os.mkdir(dest) created = True else: created = False try: open(os.path.join(dest, 'site.zcml'), 'w').write( site_zcml_template % self.options['site.zcml'] ) self.egg.install() requirements, ws = self.egg.working_set() server_module = server_types[options['servers']][0] # install subprograms and ctl scripts if options['servers'] == 'paste': reqs = ['PasteScript'] scripts = dict(paster='runzope') arguments = "['serve']+sys.argv[1:]" else: reqs = [('runzope', server_module, 'main')] scripts = None arguments = '' extra_paths = options.get('extra-paths', '') initialization = options.get('initialization') or '' zc.buildout.easy_install.scripts( reqs, ws, get_executable(options), dest, scripts=scripts, extra_paths=extra_paths.split(), arguments=arguments, initialization=initialization, relative_paths=self.egg._relative_paths, ) options['extra-paths'] = extra_paths + '\n' + this_loc initialization = options.get('debug-initialization') if initialization is None: initialization = options.get('initialization') if initialization: initialization += '\n' else: initialization = '' initialization += 'import %s\n' % server_module arguments = 'main_module=%s' % server_module zc.buildout.easy_install.scripts( [('debugzope', 'zc.zope3recipes.debugzope', 'debug')], ws, get_executable(options), dest, extra_paths=options['extra-paths'].split(), initialization=initialization, arguments=arguments, relative_paths=self.egg._relative_paths, ) ftesting_zcml = options.get('ftesting.zcml') if ftesting_zcml: open(os.path.join(dest, 'ftesting.zcml'), 'w' ).write(site_zcml_template % ftesting_zcml) open(os.path.join(dest, 'ftesting-base.zcml'), 'w' ).write(ftesting_base) return dest except Exception: if created: shutil.rmtree(dest) raise return dest def update(self): self.install() class App(Application): def __init__(self, buildout, name, options): super().__init__(buildout, name, options) location = buildout[options.get('zope3', 'zope3')]['location'] if location: options['zope3-location'] = os.path.join( buildout['buildout']['directory'], location, ) def install(self): options = self.options z3path = options.get('zope3-location') logger = logging.getLogger(self.name) if z3path is not None: if not os.path.exists(z3path): logger.error("The directory, %r, doesn't exist." % z3path) raise zc.buildout.UserError("No directory:", z3path) path = os.path.join(z3path, 'lib', 'python') if not os.path.exists(path): path = os.path.join(z3path, 'src') if not os.path.exists(path): logger.error( "The directory, %r, isn't a valid checkout or release." % z3path) raise zc.buildout.UserError( "Invalid Zope 3 installation:", z3path) extra = options.get('extra-paths') if extra: extra += '\n' + path else: extra = path options['extra-paths'] = extra return super().install() site_zcml_template = """\ <configure xmlns='http://namespaces.zope.org/zope' xmlns:meta="http://namespaces.zope.org/meta" > %s </configure> """ class Instance: deployment = None def __init__(self, buildout, name, options): self.name, self.options = options.get('name', name), options for section in options.get('extends', '').split(): options.update( [(k, v) for (k, v) in buildout[section].items() if k not in options ]) options['application-location'] = buildout[options['application'] ]['location'] options['scripts'] = '' options['servers'] = buildout[options['application']]['servers'] options['eggs'] = options.get('eggs', 'zdaemon\nsetuptools') self.egg = zc.recipe.egg.Egg(buildout, name, options) deployment = options.get('deployment') if deployment: # Note we use get below to work with old zc.recipe.deployment eggs. self.deployment = buildout[deployment].get('name', deployment) options['bin-directory'] = buildout[deployment]['rc-directory'] options['run-directory'] = buildout[deployment]['run-directory'] options['log-directory'] = buildout[deployment]['log-directory'] options['etc-directory'] = buildout[deployment]['etc-directory'] options['logrotate-directory'] = buildout[deployment][ 'logrotate-directory'] options['user'] = buildout[deployment]['user'] else: options['bin-directory'] = buildout['buildout']['bin-directory'] options['run-directory'] = os.path.join( buildout['buildout']['parts-directory'], name, ) def install(self): options = self.options run_directory = options['run-directory'] deployment = self.deployment if deployment: zope_conf_path = os.path.join(options['etc-directory'], self.name+'-zope.conf') zdaemon_conf_path = os.path.join(options['etc-directory'], self.name+'-zdaemon.conf') paste_ini_path = os.path.join(options['etc-directory'], self.name+'-paste.ini') event_log_path = os.path.join(options['log-directory'], self.name+'-z3.log') access_log_path = os.path.join(options['log-directory'], self.name+'-access.log') socket_path = os.path.join(run_directory, self.name+'-zdaemon.sock') rc = deployment + '-' + self.name logrotate_path = os.path.join(options['logrotate-directory'], rc) creating = [zope_conf_path, zdaemon_conf_path, os.path.join(options['bin-directory'], rc), ] logrotate_conf = options.get("logrotate.conf") if isinstance(logrotate_conf, str): if logrotate_conf.strip(): creating.append(logrotate_path) else: logrotate_conf = None else: logrotate_conf = logrotate_template % dict( logfile=event_log_path, rc=os.path.join(options['bin-directory'], rc), conf=zdaemon_conf_path, ) creating.append(logrotate_path) else: zope_conf_path = os.path.join(run_directory, 'zope.conf') zdaemon_conf_path = os.path.join(run_directory, 'zdaemon.conf') paste_ini_path = os.path.join(run_directory, 'paste.ini') event_log_path = os.path.join(run_directory, 'z3.log') access_log_path = os.path.join(run_directory, 'access.log') socket_path = os.path.join(run_directory, 'zdaemon.sock') rc = self.name creating = [run_directory, os.path.join(options['bin-directory'], rc), ] if not os.path.exists(run_directory): os.mkdir(run_directory) try: app_loc = options['application-location'] zope_conf = options.get('zope.conf', '')+'\n' zope_conf = ZConfig.schemaless.loadConfigFile( io.StringIO(zope_conf)) if 'site-definition' not in zope_conf: zope_conf['site-definition'] = [ os.path.join(app_loc, 'site.zcml') ] threads = None server_type = server_types[options['servers']][1] if server_type: for address in options.get('address', '').split(): zope_conf.sections.append( ZConfig.schemaless.Section( 'server', data=dict(type=[server_type], address=[address])) ) if not [s for s in zope_conf.sections if ('server' in s.type)]: zope_conf.sections.append( ZConfig.schemaless.Section( 'server', data=dict(type=[server_type], address=['8080'])) ) program_args = '-C '+zope_conf_path else: # paste paste_ini = options.get('paste.ini', '') if not paste_ini: address = options.get('address', '8080').split() if not len(address) == 1: raise zc.buildout.UserError( "If you don't specify a paste.ini option, " "you must specify exactly one address.") [address] = address if ':' in address: host, port = address.rsplit(':', 1) port = int(port) elif re.match(r'\d+$', address): host = '' port = int(address) else: host = address port = 8080 threads = zope_conf.pop('threads', None) threads = threads and threads[0] or 4 paste_ini = ( "filter-with = translogger\n" "\n" "[filter:translogger]\n" "use = egg:Paste#translogger\n" "setup_console_handler = False\n" "logger_name = accesslog\n" "\n" "" "[server:main]\n" "use = egg:zope.server\n" "host = %s\n" "port = %s\n" "threads = %s\n" % (host, port, threads) ) paste_ini = ( "[app:main]\n" "use = egg:zope.app.wsgi\n" "config_file = %s\n" % zope_conf_path) + paste_ini creating.append(paste_ini_path) f = open(paste_ini_path, 'w') f.write(paste_ini) f.close() program_args = paste_ini_path if not [s for s in zope_conf.sections if s.type == 'zodb']: raise zc.buildout.UserError( 'No database sections have been defined.') if not [s for s in zope_conf.sections if s.type == 'accesslog']: zope_conf.sections.append(access_log(access_log_path)) if not server_type: # paste for s in zope_conf.sections: if s.type != 'accesslog': continue s.type = 'logger' s.name = 'accesslog' s['name'] = [s.name] s['level'] = ['info'] s['propagate'] = ['false'] for formatter in s.sections: formatter['format'] = ['%(message)s'] if not [s for s in zope_conf.sections if s.type == 'eventlog']: zope_conf.sections.append(event_log('STDOUT')) zdaemon_conf = options.get('zdaemon.conf', '')+'\n' zdaemon_conf = ZConfig.schemaless.loadConfigFile( io.StringIO(zdaemon_conf)) defaults = { 'program': "{} {}".format(os.path.join(app_loc, 'runzope'), program_args), 'daemon': 'on', 'transcript': event_log_path, 'socket-name': socket_path, 'directory': run_directory, } if deployment: defaults['user'] = options['user'] runner = [s for s in zdaemon_conf.sections if s.type == 'runner'] if runner: runner = runner[0] else: runner = ZConfig.schemaless.Section('runner') zdaemon_conf.sections.insert(0, runner) for name, value in defaults.items(): if name not in runner: runner[name] = [value] if not [s for s in zdaemon_conf.sections if s.type == 'eventlog']: # No database, specify a default one zdaemon_conf.sections.append(event_log2(event_log_path)) zdaemon_conf = str(zdaemon_conf) self.egg.install() requirements, ws = self.egg.working_set() open(zope_conf_path, 'w').write(str(zope_conf)) open(zdaemon_conf_path, 'w').write(str(zdaemon_conf)) if deployment and logrotate_conf: open(logrotate_path, 'w').write(logrotate_conf) # XXX: We are using a private zc.buildout.easy_install # function below. It would be better if self.egg had a # method to install scripts. All recipe options and # relative path information would be available to the egg # instance and the recipe would have no need to call # zc.buildout.easy_install.scripts directly. Since that # requires changes to zc.recipe.egg/zc.buildout we are # fixing our immediate need to generate correct relative # paths by using the private API. # This should be done "right" in the future. if self.egg._relative_paths: arg_paths = ( os.path.join(app_loc, 'debugzope'), zope_conf_path, zdaemon_conf_path, ) spath, x = zc.buildout.easy_install._relative_path_and_setup( os.path.join(options['bin-directory'], 'ctl'), arg_paths, self.egg._relative_paths, ) rpath = spath.split(',\n ') debugzope_loc, zope_conf_path, zdaemon_conf_path = rpath arguments = ('[' '\n %s,' '\n %s,' '\n %r, %s,' '\n ]+sys.argv[1:]' '\n ' % (debugzope_loc, zope_conf_path, '-C', zdaemon_conf_path, ) ) else: arguments = ('[' '\n %r,' '\n %r,' '\n %r, %r,' '\n ]+sys.argv[1:]' '\n ' % (os.path.join(app_loc, 'debugzope'), zope_conf_path, '-C', zdaemon_conf_path, ) ) if WIN: zc.buildout.easy_install.scripts( [(rc, 'zc.zope3recipes.winctl', 'main')], ws, get_executable(options), options['bin-directory'], extra_paths=[this_loc], arguments=arguments, relative_paths=self.egg._relative_paths, ) else: zc.buildout.easy_install.scripts( [(rc, 'zc.zope3recipes.ctl', 'main')], ws, get_executable(options), options['bin-directory'], extra_paths=[this_loc], arguments=arguments, relative_paths=self.egg._relative_paths, ) return creating except Exception: for f in creating: if os.path.isdir(f): shutil.rmtree(f) elif os.path.exists(f): os.remove(f) raise update = install def access_log(path): return ZConfig.schemaless.Section( 'accesslog', '', sections=[ZConfig.schemaless.Section('logfile', '', dict(path=[path]))] ) def event_log(path, *data): return ZConfig.schemaless.Section( 'eventlog', '', None, [ZConfig.schemaless.Section( 'logfile', '', dict(path=[path], formatter=['zope.exceptions.log.Formatter'])), ]) def event_log2(path, *data): return ZConfig.schemaless.Section( 'eventlog', '', None, [ZConfig.schemaless.Section( 'logfile', '', dict(path=[path]))]) logrotate_template = """%(logfile)s { rotate 5 weekly postrotate %(rc)s reopen_transcript endscript } """ ftesting_base = """ <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope" > <include package="zope.app" /> <include package="zope.app" file="ftesting.zcml" /> <include package="zope.app.securitypolicy" file="meta.zcml" /> <include package="zope.app.securitypolicy" /> <securityPolicy component="zope.app.securitypolicy.zopepolicy.ZopeSecurityPolicy" /> <role id="zope.Anonymous" title="Everybody" description="All users have this role implicitly" /> <role id="zope.Manager" title="Site Manager" /> <role id="zope.Member" title="Site Member" /> <grant permission="zope.View" role="zope.Anonymous" /> <grant permission="zope.app.dublincore.view" role="zope.Anonymous" /> <grantAll role="zope.Manager" /> <include package="zope.app.securitypolicy.tests" file="functional.zcml" /> <unauthenticatedPrincipal id="zope.anybody" title="Unauthenticated User" /> <unauthenticatedGroup id="zope.Anybody" title="Unauthenticated Users" /> <authenticatedGroup id="zope.Authenticated" title="Authenticated Users" /> <everybodyGroup id="zope.Everybody" title="All Users" /> <principal id="zope.mgr" title="Manager" login="mgr" password="mgrpw" /> <principal id="zope.globalmgr" title="Manager" login="globalmgr" password="globalmgrpw" /> <grant role="zope.Manager" principal="zope.globalmgr" /> </configure> """ class SupportingBase: def __init__(self, buildout, name, options): self.options = options self.name = name deployment = options.get("deployment") if deployment: deployment = buildout[deployment] self.deployment = deployment self.app = buildout[options["application"]] options["application-location"] = self.app["location"] def update(self): self.install() class ZopeConf(SupportingBase): def __init__(self, buildout, name, options): super().__init__(buildout, name, options) if self.deployment: options['run-directory'] = self.deployment['run-directory'] zope_conf_path = os.path.join( self.deployment['etc-directory'], self.name) else: directory = os.path.join( buildout['buildout']['parts-directory']) options['run-directory'] = directory zope_conf_path = os.path.join(directory, self.name) options["location"] = zope_conf_path def install(self): options = self.options run_directory = options['run-directory'] zope_conf = options.get('text', '')+'\n' zope_conf = ZConfig.schemaless.loadConfigFile( io.StringIO(zope_conf)) if "access-log" in options: access_log_name = options["access-log"] access_log_specified = True else: basename = os.path.splitext(self.name)[0] access_log_name = basename+'-access.log' access_log_specified = False # access_log_path depends on whether a given name is an absolute # path; this (and the windows case) are handled specially so the # file can be dumped to /dev/null for offline scripts. if (os.path.isabs(access_log_name) or (WIN and access_log_name.upper() == "NUL")): access_log_path = access_log_name elif self.deployment: access_log_path = os.path.join( self.deployment['log-directory'], access_log_name) else: access_log_path = os.path.join(run_directory, access_log_name) zope_conf_path = options["location"] if 'site-definition' not in zope_conf: app_loc = options["application-location"] zope_conf['site-definition'] = [ os.path.join(app_loc, 'site.zcml') ] server_type = server_types[self.app['servers']][1] for address in options.get('address', '').split(): zope_conf.sections.append( ZConfig.schemaless.Section( 'server', data=dict(type=[server_type], address=[address])) ) if not [s for s in zope_conf.sections if ('server' in s.type)]: zope_conf.sections.append( ZConfig.schemaless.Section( 'server', data=dict(type=[server_type], address=['8080'])) ) if not [s for s in zope_conf.sections if s.type == 'zodb']: raise zc.buildout.UserError( 'No database sections have been defined.') if not [s for s in zope_conf.sections if s.type == 'accesslog']: zope_conf.sections.append(access_log(access_log_path)) elif access_log_specified: # Can't include one and specify the path. raise zc.buildout.UserError( "access log can only be specified once") if not [s for s in zope_conf.sections if s.type == 'eventlog']: zope_conf.sections.append(event_log('STDOUT')) open(zope_conf_path, 'w').write(str(zope_conf)) return [zope_conf_path] class Offline(SupportingBase): def __init__(self, buildout, name, options): super().__init__(buildout, name, options) if "directory" not in options: if self.deployment is None: directory = buildout["buildout"]["bin-directory"] else: directory = self.deployment["etc-directory"] options["directory"] = directory if self.deployment is not None and "user" not in options: options["user"] = self.deployment["user"] options["dest"] = os.path.join(options["directory"], name) env = options.get("environment") if env: self.environment = dict(buildout[env]) else: self.environment = {} options["executable"] = get_executable(self.app) zope_conf = buildout[options["zope.conf"]] options["zope.conf-location"] = zope_conf["location"] script = options.get("script") if script: script = os.path.join(buildout["buildout"]["directory"], script) options["script"] = script def install(self): options = self.options debugzope = os.path.join( options["application-location"], "debugzope") config = options["zope.conf-location"] script = options.get("script") or "" if script: script = repr(script) initialization = options.get("initialization", "").strip() script_content = template % dict( config=config, debugzope=debugzope, executable=options["executable"], environment=pprint.pformat(self.environment), initialization=initialization, script=script, user=options.get("user"), ) dest = options["dest"] f = open(dest, "w") f.write(script_content) f.close() os.chmod(dest, 0o775) return [dest] template = '''\ #!%(executable)s import os import sys import logging argv = list(sys.argv) env = %(environment)s restart = False if %(user)r: import pwd if pwd.getpwnam(%(user)r).pw_uid != os.geteuid(): restart = True argv[:0] = ["sudo", "-u", %(user)r] # print("switching to user %%s" %% %(user)r) del pwd for k in env: if os.environ.get(k) != env[k]: os.environ[k] = env[k] restart = True del k if restart: # print("restarting") os.execvpe(argv[0], argv, dict(os.environ)) del argv del env del restart sys.argv[1:1] = [ "-C", %(config)r, %(script)s ] debugzope = %(debugzope)r globals()["__file__"] = debugzope zeo_logger = logging.getLogger('ZEO.zrpc') zeo_logger.addHandler(logging.StreamHandler()) %(initialization)s # print("starting debugzope...") with open(debugzope) as f: exec(f.read()) '''
zc.zope3recipes
/zc.zope3recipes-1.0-py3-none-any.whl/zc/zope3recipes/recipes.py
recipes.py
import errno import subprocess import sys import zdaemon.zdctl if sys.platform[:3].lower() == "win": import msvcrt import win32api import win32com.client import win32process from win32file import ReadFile from win32file import WriteFile from win32pipe import PeekNamedPipe def getChildrenPidsOfPid(pid): """Returns the children pids of a pid""" wmi = win32com.client.GetObject('winmgmts:') children = wmi.ExecQuery( 'Select * from win32_process where ParentProcessId=%s' % pid ) pids = [] for proc in children: pids.append(proc.Properties_('ProcessId')) return pids def getDaemonProcess(pid): """Returns the daemon proces.""" wmi = win32com.client.GetObject('winmgmts:') children = wmi.ExecQuery( 'Select * from win32_process where ProcessId=%s' % pid) pids = [] for proc in children: pids.append(proc.Properties_('ProcessId')) if len(pids) == 1: return pids[0] return None def getZopeScriptProcess(pid): """Returns the daemon proces.""" wmi = win32com.client.GetObject('winmgmts:') children = wmi.ExecQuery( 'Select * from win32_process where ParentProcessId=%s' % pid ) pids = [] for proc in children: pids.append(proc.Properties_('ProcessId')) if len(pids) == 1: return pids[0] return None def kill(pid): """kill function for Win32""" handle = win32api.OpenProcess(1, 0, pid) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) def killAll(pid): """Kill runzope and the python process started by runzope.""" pids = getChildrenPidsOfPid(pid) for pid in pids: kill(pid) class Popen(subprocess.Popen): def recv(self, maxsize=None): return self._recv('stdout', maxsize) def recv_err(self, maxsize=None): return self._recv('stderr', maxsize) def send_recv(self, input='', maxsize=None): return self.send(input), self.recv(maxsize), self.recv_err(maxsize) def get_conn_maxsize(self, which, maxsize): if maxsize is None: maxsize = 1024 elif maxsize < 1: maxsize = 1 return getattr(self, which), maxsize def _close(self, which): getattr(self, which).close() setattr(self, which, None) def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise return written def _recv(self, which, maxsize): conn, maxsize = self.get_conn_maxsize(which, maxsize) if conn is None: return None try: x = msvcrt.get_osfhandle(conn.fileno()) (read, nAvail, nMessage) = PeekNamedPipe(x, 0) if maxsize < nAvail: nAvail = maxsize if nAvail > 0: (errCode, read) = ReadFile(x, nAvail, None) except ValueError: return self._close(which) except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close(which) raise if self.universal_newlines: read = self._translate_newlines(read) return read # TODO: implement a win service script and add install and remove methods for # the service. # Also implement start and stop methods controlling the windows service daemon # if the service is installed. Use the already defined methods if no service # is installed. # class ZopeCtlOptions(ZDOptions): # """Zope controller options.""" # # def realize(self, *args, **kwds): # ZopeCtlOptions.realize(self, *args, **kwds) # # # Add the path to the zopeservice.py script, which is needed for # # some of the Windows specific commands # servicescript = os.path.join(self.directory, 'bin', 'zopeservice.py') # self.servicescript = '"%s" %s' % (self.python, servicescript) class ZopectlCmd(zdaemon.zdctl.ZDCmd): """Manages Zope start and stop etc. This implementation uses a subprocess for execute the given python script. There is also a windows service daemon which can get installed with the install and remove methods. If a windows service is installed, the controller dispatches the start and stop commands to the service. If no service is installed, we use the subprocess instead. """ zd_up = 0 zd_pid = 0 zd_status = None proc = None def do_install(self, arg): """Install the windows service.""" print("Not implemented right now") def help_install(self): print("install -- Installs Zope3 as a Windows service.") print("Not implemented right now") def do_remove(self, arg): """Remove the windows service.""" print("Not implemented right now") def help_remove(self): print("remove -- Removes the Zope3 Windows service.") print("Not implemented right now") def do_debug(self, arg): # Start the process if self.zd_pid: print("Zope3 already running; pid=%d" % self.zd_pid) return args = " ".join(self.options.args[1:]) cmds = [self._debugzope, '-C', self._zope_conf, args] program = " ".join(cmds) print("Debug Zope3: %s" % program) self.proc = Popen(program) self.zd_pid = self.proc.pid self.zd_up = 1 self.awhile(lambda n: self.zd_pid, "Zope3 started in debug mode, pid=%(zd_pid)d") def help_debug(self): print("debug -- Initialize the Zope application, providing a") print(" debugger object at an interactive Python prompt.") do_run = do_debug def help_run(self): print("run <script> [args] -- run a Python script with the Zope") print(" environment set up. The script has") print(" 'root' exposed as the root container.") def send_action(self, action): """Dispatch actions to subprocess.""" try: self.proc.send(action + "\n") response = "" while 1: data = self.proc.recv(1000) if not data: break response += data return response except (subprocess.pywintypes.error, Exception): return None def get_status(self): if not self.zd_pid: return None proc = getDaemonProcess(self.zd_pid) if proc is not None: self.zd_up = 1 proc = getZopeScriptProcess(self.zd_pid) if proc is not None: self.zd_status = "Zope3 is running" return self.zd_status return None def do_stop(self, arg): # Stop the Windows process if not self.zd_pid: print("Zope3 is not running") return killAll(self.zd_pid) self.zd_up = 0 self.zd_pid = 0 cpid = win32process.GetCurrentProcessId() self.awhile(lambda n: not getChildrenPidsOfPid(cpid), "Zope3 stopped") def do_kill(self, arg): self.do_stop(arg) def do_restart(self, arg): pid = self.zd_pid if self.zd_pid: self.do_stop(arg) self.do_start(arg) else: self.do_start(arg) self.awhile(lambda n: self.zd_pid not in (0, pid), "Zope3 restarted, pid=%(zd_pid)d") def show_options(self): print("winctl options:") print("configfile: %s" % repr(self.options.configfile)) print("python: %s" % repr(self.options.python)) print("program: %s" % repr(self.options.program)) print("user: %s" % repr(self.options.user)) print("directory: %s" % repr(self.options.directory)) print("logfile: %s" % repr(self.options.logfile)) def do_start(self, arg): # Start the process if self.zd_pid: print("Zope3 already running; pid=%d" % self.zd_pid) return program = " ".join(self.options.program) print("Starting Zope3: %s" % program) self.proc = Popen(program) self.zd_pid = self.proc.pid self.zd_up = 1 self.awhile(lambda n: self.zd_pid, "Zope3 started, pid=%(zd_pid)d") def do_fg(self, arg): self.do_foreground(arg) def help_fg(self): self.help_foreground() def do_foreground(self, arg): # Start the process if self.zd_pid: print("To run the Zope3 in the foreground, please stop it first.") return program = self.options.program + self.options.args[1:] program = " ".join(program) sys.stdout.flush() try: subprocess.call(program) print("Zope3 started in forground: %s" % program) except KeyboardInterrupt: print def help_foreground(self): print("foreground -- Run the program in the forground.") print("fg -- an alias for foreground.") print("Not supported on windows will call start") def main(args=None): if args is None: args = sys.argv[1:] class Cmd(ZopectlCmd): _debugzope = args.pop(0) _zope_conf = args.pop(0) zdaemon.zdctl.main(args, None, Cmd)
zc.zope3recipes
/zc.zope3recipes-1.0-py3-none-any.whl/zc/zope3recipes/winctl.py
winctl.py
Release History =============== 2.5.3 2015-02-16 ---------------- - Fixed: monitor got the primary last transaction time before before getting the secondary last transaction time, sometimes leading to spurious reports of the primary being behind the secondary. 2.5.2 2015-02-07 ---------------- Fixed: the nagios monitor only worked if the primary and secondary ran in the same process (as in they did in the tests.) 2.5.1 2015-01-28 ---------------- Include ``src/**/*.rst`` files in sdist. 2.5.0 2015-01-25 ---------------- Added nagios plugins for monitoring replication. 2.4.4 2013-08-17 ---------------- Fixed packaging bug: component.xml was left out. 2.4.3 2013-08-15 ---------------- Packaging update: allow installation without setuptools. 2.4.2 2013-05-27 ---------------- Initial open-source release for ZODB 3.9 or later. 2.4.1 2012-07-10 ---------------- Fixed: When listening for replication on all IPV4 addresses, the registered IP address was 0.0.0.0, rather than the fully-qualified host name. 2.4.0 2012-07-10 ---------------- Added support for registering and looking up replication addresses with ZooKeeper. 2.3.4 2010-10-01 ---------------- - Added support for ZODB 3.10. - Added support for layered storages, e.g., zc.zlibstorage. 2.3.3 (2010-09-29) ================== Added proxying for a new ZODB test method. 2.3.2 (2010-09-03) ================== Added proxying for checkCurrentSerialInTransaction, wich was introduced in ZODB 3.10.0b5. 2.3.1 (2010-05-20) ================== - Fixed some spurious test failures. 2.3.0 (2010-03-01) ================== - Updated tests to work with Python 2.6 and Twisted 9. 2.2.5 2010-09-21 ---------------- - Fixed a bug in support for shared ZEO blob directories. 2.2.4 2009-09-02 ---------------- - Updated tests to reflect ZODB changes. 2.2.3 2009-06-26 ---------------- - Updated to work with older releases that didn’t send checksum data. 2.2.2 2009-06-04 ---------------- - Support for ZODB 3.9 and blobs - Updated the configuration syntax. - Added a replication checksum feature - Added support for unix-domain sockets for replication. 2.0.4 2009-03-09 ---------------- - Updated the configuration syntax. 2.0.3 2008-12-19 ---------------- - Updated the configuration syntax. - Added keep-alive option to deal with VPNs that break TCP connections in non-standard ways. 2.0.2 2007-07-16 ---------------- Initial ZRS 2 release.
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/HISTORY.rst
HISTORY.rst
Recent Changes ============== For earlier changes, see the `HISTORY.rst <HISTORY.rst>`_. 3.1.0 (2017-04-07) ------------------ - Python 3 (3.4 amd 3.5) support. 3.6 support will be added when Twisted supports Python 3.6. (There are worrying test failures under Python 3.6.) - Minor convenience change to API: When instantiating primary or secondary servers, you can pass a file-name instead of a storage instance and a file storage will be created automatically. 3.0.0 (2017-04-04) ------------------ - Add support for ZODB 5 - Drop ZooKeeper support.
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/CHANGES.rst
CHANGES.rst
======================= ZODB Replicated Storage ======================= ZODB replicated storage (ZRS) provides database replication for ZODB. For each database, a primary storage and one or more secondary storages may be defined. The secondary storages will automatically replicate data from the primary storage. Replication is superior to back-ups because as long as secondaries are running, secondary data is kept updated. In the event of a failure of a primary storage, just reconfigure a secondary to be the primary, and it can begin handling application requests. .. contents:: Features ======== - Primary/secondary replication - Support for read-only secondary storages Requirements ============ - ZODB 3.9 or later. Installation ============= ZRS is installed like any other Python package, by installing the ``zc.zrs`` package with `easy_install <http://peak.telecommunity.com/DevCenter/EasyInstall>`_, `zc.buildout <http://pypi.python.org/pypi/zc.buildout>`_, `pip <http://pypi.python.org/pypi/pip>`_, etc. Using ZRS ========= ZRS provides two ZODB storage implementations: a primary storage and a secondary storage. Both storages are used with file storages. - The primary storage is a readable and writable storage. - The secondary storage is read-only. A secondary storage can be used by read-only application clients to reduce server load. Secondary storages replicate from primary storages, or other secondary storages. Theoretically, ZRS storages can be used wherever a ZODB storage would be used. In practice, however, they're used in ZEO servers. Configuration with ZConfig -------------------------- If using an application, like a ZEO server or Zope, that uses `ZConfig <http://pypi.python.org/pypi/ZConfig>`_ to configure ZODB storages, the configuration of a ZRS primary or secondary storage may be included in the configuration file as with any other storage e.g, to configure a primary storage, use something like:: %import zc.zrs <zrs> replicate-to 5000 <filestorage> path /path/to/data/file </filestorage> </zrs> Here is a line-by-line walk through:: %import zc.zrs The import statement is necessary to load the ZConfig schema definitions for ZRS. :: <zrs> The zrs section defines a ZRS storage. A ZRS storage may be a primary storage or a secondary storage. A ZRS storage without a ``replicate-from`` option (as in the example above) is a primary storage. :: replicate-to 5000 The replicate-to option specifies the replication address. Secondary storages will connect to this address to download replication data. This address can be a port number or a host name (interface name) and port number separated by a colon. :: <filestorage> path /path/to/data/file </filestorage> A ZRS storage section must include a filestorage section specifying a file storage to contain the data. Configuring a secondary storage is similar to configuring a primary storage:: %import zc.zrs <zrs> replicate-from primary-host:5000 replicate-to 5000 keep-alive-delay 60 <filestorage> path /path/to/secondary/data/file </filestorage> </zrs> For a secondary storage, a ``replicate-from`` option is used to specify the address to replicate data from. Because primary and secondary storages are generally on separate machines, the host is usually specified in a ``replicate-from`` option. A secondary storage can also specify a ``replicate-to`` option. If this option is used, other secondary storages can then replicate from the secondary, rather than replicating from the primary. Secondary storages also support the following optional option: keep-alive-delay SECONDS In some network configurations, TCP connections are broken after extended periods of inactivity. This may even be done in a way that a client doesn't detect the disconnection. To prevent this, you can use the ``keep-alive-delay`` option to cause the secondary storage to send periodic no-operation messages to the server. Code and contributions ====================== https://github.com/zc/zrs
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/README.rst
README.rst
# system imports import zope.interface # Twisted Imports from twisted.internet import interfaces, protocol, main, defer from twisted.python import failure from twisted.internet.interfaces import IAddress class _LoopbackQueue(object): """ Trivial wrapper around a list to give it an interface like a queue, which the addition of also sending notifications by way of a Deferred whenever the list has something added to it. """ _notificationDeferred = None disconnect = False def __init__(self): self._queue = [] def put(self, v): self._queue.append(v) if self._notificationDeferred is not None: d, self._notificationDeferred = self._notificationDeferred, None d.callback(None) def __bool__(self): return bool(self._queue) __nonzero__ = __bool__ def get(self): return self._queue.pop(0) @zope.interface.implementer(IAddress) class _LoopbackAddress(object): pass @zope.interface.implementer(interfaces.ITransport, interfaces.IConsumer) class _LoopbackTransport(object): disconnecting = False producer = None # ITransport def __init__(self, q, proto): self.q = q self.proto = proto def write(self, bytes): self.q.put(bytes) def writeSequence(self, iovec): self.q.put(b''.join(iovec)) def loseConnection(self): self.q.disconnect = True self.q.put(b'') def getPeer(self): return _LoopbackAddress() def getHost(self): return _LoopbackAddress() # IConsumer def registerProducer(self, producer, streaming): assert self.producer is None self.producer = producer self.streamingProducer = streaming self._pollProducer() def unregisterProducer(self): assert self.producer is not None self.producer = None def _pollProducer(self): if self.producer is not None and not self.streamingProducer: self.producer.resumeProducing() def connectionLost(self, reason): if self.producer is not None: self.producer.stopProducing() self.unregisterProducer() self.proto.connectionLost(reason) class _ClientLoopbackTransport(_LoopbackTransport): connector = None def connectionLost(self, reason): self.proto.connectionLost(reason) if self.connector is not None: self.connector.connectionLost(reason) def loopbackAsync(server, client, connector): serverToClient = _LoopbackTransport(_LoopbackQueue(), server) serverToClient.reactor = connector.reactor clientToServer = _ClientLoopbackTransport(_LoopbackQueue(), client) clientToServer.reactor = connector.reactor clientToServer.connector = connector server.makeConnection(serverToClient) client.makeConnection(clientToServer) _loopbackAsyncBody(serverToClient, clientToServer) def _loopbackAsyncBody(serverToClient, clientToServer): def pump(source, q, target): sent = False while q: sent = True bytes = q.get() if bytes: target.dataReceived(bytes) # A write buffer has now been emptied. Give any producer on that side # an opportunity to produce more data. source.transport._pollProducer() return sent server = serverToClient.proto client = clientToServer.proto while 1: disconnect = clientSent = serverSent = False # Deliver the data which has been written. serverSent = pump(server, serverToClient.q, client) clientSent = pump(client, clientToServer.q, server) if not clientSent and not serverSent: # Neither side wrote any data. Wait for some new data to be added # before trying to do anything further. d = defer.Deferred() clientToServer.q._notificationDeferred = d serverToClient.q._notificationDeferred = d d.addCallback(_loopbackAsyncContinue, serverToClient, clientToServer) break if serverToClient.q.disconnect: # The server wants to drop the connection. Flush any remaining # data it has. disconnect = True pump(server, serverToClient.q, client) elif clientToServer.q.disconnect: # The client wants to drop the connection. Flush any remaining # data it has. disconnect = True pump(client, clientToServer.q, server) if disconnect: # Someone wanted to disconnect, so okay, the connection is gone. serverToClient.connectionLost( failure.Failure(main.CONNECTION_DONE)) clientToServer.connectionLost( failure.Failure(main.CONNECTION_DONE)) break def _loopbackAsyncContinue(ignored, serverToClient, clientToServer): # Clear the Deferred from each message queue, since it has already fired # and cannot be used again. clientToServer.q._notificationDeferred = None serverToClient.q._notificationDeferred = None # Push some more bytes around. _loopbackAsyncBody(serverToClient, clientToServer)
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/loopback.py
loopback.py
from hashlib import md5 from six import BytesIO from six.moves import cPickle import logging import os import sys import threading import time import twisted.internet.interfaces import twisted.internet.protocol import zc.zrs.reactor import zc.zrs.sizedmessage import ZODB.BaseStorage import ZODB.blob import ZODB.FileStorage import ZODB.FileStorage.format import ZODB.interfaces import ZODB.TimeStamp import ZODB.utils import zope.interface try: long except NameError: long = lambda n: n if not hasattr(ZODB.blob.BlobStorage, 'restoreBlob'): import zc.zrs.restoreblob logger = logging.getLogger(__name__) class Base(object): def __init__(self, storage, addr, reactor): if isinstance(storage, str): import ZODB.FileStorage storage = ZODB.FileStorage.FileStorage(storage) if reactor is None: reactor = zc.zrs.reactor.reactor() self._reactor = reactor self._storage = storage try: fn = storage.getExtensionMethods except AttributeError: pass # no extension methods else: self.getExtensionMethods = storage.getExtensionMethods for name in fn(): assert not hasattr(self, name) setattr(self, name, getattr(storage, name)) self._addr = addr def __len__(self): return len(self._storage) class Primary(Base): def __init__(self, storage, addr, reactor=None): Base.__init__(self, storage, addr, reactor) storage = self._storage if ZODB.interfaces.IBlobStorage.providedBy(storage): zope.interface.directlyProvides(self, ZODB.interfaces.IBlobStorage) for name in ('storeBlob', 'loadBlob', 'temporaryDirectory', 'restoreBlob', 'openCommittedBlobFile', 'fshelper'): setattr(self, name, getattr(storage, name)) if not isinstance(storage, (ZODB.blob.BlobStorage, ZODB.FileStorage.FileStorage) ): raise ValueError("Invalid storage", storage) self._changed = threading.Condition() # required methods for name in ( 'getName', 'getSize', 'history', 'isReadOnly', 'lastTransaction', 'load', 'loadBefore', 'loadSerial', 'new_oid', 'pack', 'registerDB', 'sortKey', 'store', 'tpc_abort', 'tpc_begin', 'tpc_vote', ): setattr(self, name, getattr(storage, name)) # Optional methods: for name in ( 'restore', 'iterator', 'cleanup', 'loadEx', 'getSerial', 'supportsTransactionalUndo', 'tpc_transaction', 'getTid', 'lastInvalidations', 'supportsUndo', 'undoLog', 'undoInfo', 'undo', 'supportsVersions', 'abortVersion', 'commitVersion', 'versionEmpty', 'modifiedInVersion', 'versions', 'record_iternext', 'deleteObject', 'checkCurrentSerialInTransaction', ): if hasattr(storage, name): setattr(self, name, getattr(storage, name)) self._factory = PrimaryFactory(storage, self._changed) logger.info("Opening %s %s", self.getName(), addr) self._reactor.callFromThread(self.cfr_listen) # StorageServer accesses _transaction directly. :( @property def _transaction(self): return self._storage._transaction _listener = None def cfr_listen(self): if isinstance(self._addr, str): self._listener = self._reactor.listenUNIX(self._addr, self._factory) else: interface, port = self._addr self._listener = self._reactor.listenTCP( port, self._factory, interface=interface) def cfr_stop_listening(self): if self._listener is not None: self._listener.stopListening() def tpc_finish(self, *args): tid = self._storage.tpc_finish(*args) self._changed.acquire() self._changed.notifyAll() self._changed.release() return tid def close(self): logger.info('Closing %s %s', self.getName(), self._addr) self._reactor.callFromThread(self.cfr_stop_listening) # Close the storage first to prevent more writes and to # give the secondaries more time to catch up. self._storage.close() self._factory.close() class PrimaryFactory(twisted.internet.protocol.Factory): def __init__(self, storage, changed): self.storage = storage self.changed = changed self.instances = [] self.threads = ThreadCounter() def close(self): for instance in list(self.instances): instance.close() self.threads.wait(60) class PrimaryProtocol(twisted.internet.protocol.Protocol): __protocol = None __start = None __producer = None def connectionMade(self): # cfr self.__stream = zc.zrs.sizedmessage.Stream(self.messageReceived, 8) self.__peer = str(self.transport.getPeer()) + ': ' self.factory.instances.append(self) self.info("Connected") def connectionLost(self, reason): # cfr self.info("Disconnected %r", reason) if self.__producer is not None: self.__producer.stopProducing() self.factory.instances.remove(self) def close(self): if self.__producer is not None: self.__producer.close() else: self.transport.reactor.callFromThread( self.transport.loseConnection) self.info('Closed') def _stop(self): # for tests if self.__producer is not None: self.__producer._stop() else: self.transport.reactor.callFromThread( self.transport.loseConnection) def error(self, message, *args): logger.error(self.__peer + message, *args) self.close() def info(self, message, *args): logger.info(self.__peer + message, *args) def dataReceived(self, data): # cfr try: self.__stream(data) except zc.zrs.sizedmessage.LimitExceeded as v: self.error('message too large: '+str(v)) def messageReceived(self, data): # cfr if self.__protocol is None: if data == b'zrs2.0': if ZODB.interfaces.IBlobStorage.providedBy( self.factory.storage): return self.error("Invalid protocol %r. Require >= 2.1", data) elif data != b'zrs2.1': return self.error("Invalid protocol %r", data) self.__protocol = data else: if self.__start is not None: if not data: logger.debug(self.__peer + "keep-alive") return # ignore empty messages return self.error("Too many messages") self.__start = data if len(data) != 8: return self.error("Invalid transaction id, %r", data) self.info("start %r (%s)", data, ZODB.TimeStamp.TimeStamp(data)) self.__producer = PrimaryProducer( (self.factory.storage, self.factory.changed, self.__start), self.transport, self.__peer, self.factory.threads.run) PrimaryFactory.protocol = PrimaryProtocol @zope.interface.implementer(twisted.internet.interfaces.IPushProducer) class PrimaryProducer: # stopped indicates that we should stop sending output to a client stopped = False # closed means that we're closed. This is mainly to deal with a # possible race at startup. When we close a producer, we continue # sending data to the client as long as data are available. closed = False def __init__(self, iterator_args, transport, peer, run=lambda f, *args: f(*args)): self.iterator_scan_control = ScanControl() self.storage = iterator_args[0] self.iterator = None self.iterator_args = iterator_args + (self.iterator_scan_control,) self.start_tid = iterator_args[2] self.transport = transport self.peer = peer transport.registerProducer(self, True) self.callFromThread = transport.reactor.callFromThread self.consumer_event = threading.Event() self.consumer_event.set() thread = threading.Thread(target=run, args=(self.run, ), name='Producer(%s)' % peer) thread.setDaemon(True) thread.start() self.thread = thread def pauseProducing(self): logger.debug(self.peer+" pausing") self.consumer_event.clear() def resumeProducing(self): logger.debug(self.peer+" resuming") self.consumer_event.set() def close(self): # We use the closed flag to handle a race condition in # iterator setup. We set the close flag before checking for # the iterator. If we find the iterator, we tell it to stop. # If not, then when the run method below finishes creating the # iterator, it will find the close flag and not use the iterator. self.closed = True iterator = self.iterator if iterator is not None: iterator.catch_up_then_stop() def _stop(self): # for tests iterator = self.iterator if iterator is not None: iterator.stop() def cfr_close(self): if not self.stopped: self.transport.unregisterProducer() self.stopProducing() self.transport.loseConnection() def stopProducing(self): # cfr self.stopped = True iterator = self.iterator if iterator is not None: iterator.stop() else: self.iterator_scan_control.not_stopped = False self.consumer_event.set() # unblock wait calls def cfr_write(self, data): if not self.stopped: self.transport.writeSequence(data) def write(self, data): data = zc.zrs.sizedmessage.marshals(data) self.md5.update(data[1]) self.consumer_event.wait() self.callFromThread(self.cfr_write, data) def run(self): try: self.iterator = FileStorageIterator(*self.iterator_args) except: logger.exception(self.peer) self.iterator = None self.callFromThread(self.cfr_close) return if self.closed: self.callFromThread(self.cfr_close) return if self.stopped: # make sure our iterator gets stopped, as stopProducing might # have been called while we were creating the iterator. self.iterator.stop() picklerf = BytesIO() pickler = cPickle.Pickler(picklerf, 1) pickler.fast = 1 def dump(data): picklerf.seek(0) picklerf.truncate() pickler.dump(data) return picklerf.getvalue() self.md5 = md5(self.start_tid) blob_block_size = 1 << 16 try: for trans in self.iterator: self.write( dump(('T', (trans.tid, trans.status, trans.user, trans.description, trans._extension)))) for record in trans: if record.data and is_blob_record(record.data): try: fname = self.storage.loadBlob( record.oid, record.tid) f = open(fname, 'rb') except (IOError, ZODB.POSException.POSKeyError): pass else: f.seek(0, 2) blob_size = f.tell() blocks, r = divmod(blob_size, blob_block_size) if r: blocks += 1 self.write( dump(('B', (record.oid, record.tid, record.version, record.data_txn, long(blocks))))) self.write(record.data or '') f.seek(0) while blocks > 0: data = f.read(blob_block_size) if not data: raise AssertionError("Too much blob data") blocks -= 1 self.write(data) f.close() continue self.write( dump(('S', (record.oid, record.tid, record.version, record.data_txn))) ) self.write(record.data or b'') self.write(dump(('C', (self.md5.digest(), )))) except Exception as exc: logger.exception(self.peer) self.iterator = None self.callFromThread(self.cfr_close) class TidTooHigh(Exception): """The last tid for an iterator is higher than any tids in a file. """ class ScanControl: not_stopped = True class FileStorageIterator(ZODB.FileStorage.format.FileStorageFormatter): _file_size = 1 << 64 # To make base class check happy. def __init__(self, fs, condition=None, start=ZODB.utils.z64, scan_control=None): self._ltid = start self._fs = fs self._stop = False if scan_control is None: scan_control = ScanControl() self._scan_control = scan_control self._open() if condition is None: condition = threading.Condition() self._condition = condition self._catch_up_then_stop = False def _open(self): self._old_file = self._fs._file try: file = open(self._fs._file_name, 'rb', 0) except IOError as v: if os.path.exists(self._fs._file_name): raise # The file is gone. It must have been removed -- probably # in a test. We won't die here because we're probably # never going to be used. If we are ever used def _next(): raise v self._next = _next return self._file = file self._pos = 4 ltid = self._ltid if ltid > ZODB.utils.z64: # We aren't starting at the beginning. We need to find the # first transaction after _ltid. We can either search from the # beginning, or from the end. file.seek(4) tid = file.read(8) if len(tid) < 8: raise TidTooHigh(repr(ltid)) t1 = ZODB.TimeStamp.TimeStamp(tid).timeTime() tid = self._fs.lastTransaction() t2 = ZODB.TimeStamp.TimeStamp(tid).timeTime() t = ZODB.TimeStamp.TimeStamp(self._ltid).timeTime() if (t - t1) < (t2 - t1)/2: # search from beginning: self._scan_forward(4, ltid) else: # search from end pos = self._fs._pos - 8 if pos < 27: # strangely small position return self._scan_forward(4, ltid) file.seek(pos) tlen = ZODB.utils.u64(file.read(8)) pos -= tlen if pos <= 4: # strangely small position return self._scan_forward(4, ltid) file.seek(pos) h = self._read_txn_header(pos) if h.tid <= ltid: self._scan_forward(pos, ltid) else: self._scan_backward(pos, ltid) def _scan_forward(self, pos, ltid): file = self._file while self._scan_control.not_stopped: # Read the transaction record try: h = self._read_txn_header(pos) except ZODB.FileStorage.format.CorruptedDataError as err: # If buf is empty, we've reached EOF. if not err.buf: # end of file. self._pos = pos raise TidTooHigh(repr(ltid)) raise if h.status == "c": raise TidTooHigh(repr(ltid)) if h.tid > ltid: # This is the one we want to read next self._pos = pos return pos += h.tlen + 8 if h.tid == ltid: # We just read the one we want to skip past self._pos = pos return def _scan_backward(self, pos, ltid): file = self._file seek = file.seek read = file.read while self._scan_control.not_stopped: pos -= 8 seek(pos) tlen = ZODB.utils.u64(read(8)) pos -= tlen h = self._read_txn_header(pos) if h.tid <= ltid: self._pos = pos + tlen + 8 return def __iter__(self): return self def stop(self): self._condition.acquire() self._stop = True self._condition.notifyAll() self._condition.release() def catch_up_then_stop(self): self._condition.acquire() self._catch_up_then_stop = True self._condition.notifyAll() self._condition.release() def __next__(self): self._condition.acquire() try: while 1: if self._stop: raise StopIteration r = self._next() if r is not None: return r if self._catch_up_then_stop: raise StopIteration self._condition.wait() finally: self._condition.release() next = __next__ def _next(self): if self._old_file is not self._fs._file: # Our file-storage must have been packed. We need to # reopen the file: self._open() file = self._file pos = self._pos while 1: # Read the transaction record try: h = self._read_txn_header(pos) except ZODB.FileStorage.format.CorruptedDataError as err: # If buf is empty, we've reached EOF. if not err.buf: return None raise if h.tid <= self._ltid: logger.warning("%s time-stamp reduction at %s", self._file.name, pos) if h.status == "c": # Assume we've hit the last, in-progress transaction # Wait until there is more data. return None if pos + h.tlen + 8 > self._file_size: # Hm, the data were truncated or the checkpoint flag wasn't # cleared. They may also be corrupted, # in which case, we don't want to totally lose the data. logger.critical("%s truncated, possibly due to" " damaged records at %s", self._file.name, pos) raise ZODB.FileStorage.format.CorruptedDataError(None, '', pos) if h.status not in " up": logger.warning('%s has invalid status,' ' %s, at %s', self._file.name, h.status, pos) if h.tlen < h.headerlen(): logger.critical("%s has invalid transaction header at %s", self._file.name, pos) raise ZODB.FileStorage.format.CorruptedDataError(None, '', pos) tpos = pos tend = tpos + h.tlen # Check the (intentionally redundant) transaction length self._file.seek(tend) rtl = ZODB.utils.u64(self._file.read(8)) if rtl != h.tlen: logger.warning("%s redundant transaction length check" " failed at %s", self._file.name, tend) break self._pos = tend + 8 self._ltid = h.tid if h.status == "u": # Undone trans. It's unlikely to see these anymore continue pos += h.headerlen() if h.elen: e = cPickle.loads(h.ext) else: e = {} result = RecordIterator( h.tid, h.status, h.user, h.descr, e, pos, tend, self._file, tpos) return result def notify(self): self._condition.acquire() self._condition.notifyAll() self._condition.release() class RecordIterator(ZODB.FileStorage.format.FileStorageFormatter): """Iterate over the transactions in a FileStorage file.""" def __init__(self, tid, status, user, desc, ext, pos, tend, file, tpos): self.tid = tid self.status = status self.user = user self.description = desc self._extension = ext self._pos = pos self._tend = tend self._file = file self._tpos = tpos def __iter__(self): return self def __next__(self): pos = self._pos if pos < self._tend: # Read the data records for this transaction h = self._read_data_header(pos) dlen = h.recordlen() if pos + dlen > self._tend or h.tloc != self._tpos: logger.critical("%s data record exceeds transaction" " record at %s", file.name, pos) raise ZODB.FileStorage.format.CorruptedDataError( h.oid, '', pos) self._pos = pos + dlen prev_txn = None if h.plen: data = self._file.read(h.plen) else: if h.back == 0: # If the backpointer is 0, then this transaction # undoes the object creation. It either aborts # the version that created the object or undid the # transaction that created it. Return None # instead of a pickle to indicate this. data = None else: data, tid = self._loadBackTxn(h.oid, h.back, False) # Caution: :ooks like this only goes one link back. # Should it go to the original data like BDBFullStorage? prev_txn = self.getTxnFromData(h.oid, h.back) return Record(h.oid, h.tid, '', data, prev_txn, pos) raise StopIteration next = __next__ class Record: """An abstract database record.""" def __init__(self, oid, tid, version, data, prev, pos): self.oid = oid self.tid = tid self.version = version self.data = data self.data_txn = prev self.pos = pos class ThreadCounter: """Keep track of running threads We use the run method to run the threads and the wait method to wait until they're all done: """ def __init__(self): self.count = 0 self.condition = threading.Condition() def run(self, func, *args): self.condition.acquire() self.count += 1 self.condition.release() try: func(*args) finally: self.condition.acquire() self.count -= 1 self.condition.notifyAll() self.condition.release() def wait(self, timeout): deadline = time.time()+timeout self.condition.acquire() while self.count > 0: w = deadline-time.time() if w <= 0: break self.condition.wait(w) self.condition.release() def is_blob_record(record): try: return cPickle.loads(record) is ZODB.blob.Blob except (MemoryError, KeyboardInterrupt, SystemExit): raise except Exception: return False
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/primary.py
primary.py
=================== ZRS Nagios monitors =================== The ZRS nagios monitor replication status only. The ZEO nagios monitor should be used to monitor ZEO status and metrics for ZRS servers. The monitor accepts the following options: -w/--warn seconds Warn if the lag time between the primary and secondary is more than the given b=number of seconds (and less than the number of seconds given for the -e/--error option. -e/--error seconds Error if the lag time between the primary and secondary is more than the given b=number of seconds. The monitor also errors if the lag time is negative. -m/--metrics Output the lag time in Nagios metric format. The monitor, ``zrs-nagios`` takes the primary and secondary ZRS addresses as positional arguments. .. test Load the monitor: >>> import pkg_resources >>> nagios = pkg_resources.load_entry_point( ... 'zc.zrs', 'console_scripts', 'zrs-nagios') Start some servers: >>> import ZEO >>> addr_old, stop_old = ZEO.server('old.fs') >>> addr_current, stop_current = ZEO.server('current.fs') >>> addrs = ["%s:%s" % addr_current, "%s:%s" % addr_old] Note that old is about 60 seconds behind current. Run monitor w no arguments or no options errors and outputs usage: >>> nagios([]) Usage: zrs-nagios [options] PRIMARY_ADDRESS SECONDARY_ADDRESS <BLANKLINE> 2 >>> nagios(addrs) Usage: zrs-nagios [options] PRIMARY_ADDRESS SECONDARY_ADDRESS <BLANKLINE> 2 Just metrics: >>> nagios('-m' .split()+addrs) Secondary behind primary by 68.5678 seconds|'lag'=68.5678seconds Just warning: >>> nagios('-w99' .split()+addrs) Secondary behind primary by 68.5678 seconds >>> nagios('-w30' .split()+addrs) Secondary behind primary by 68.5678 seconds > 30 1 Just error: >>> nagios('-e99' .split()+addrs) Secondary behind primary by 68.5678 seconds >>> nagios('-e30' .split()+addrs) Secondary behind primary by 68.5678 seconds > 30 2 All: >>> nagios('-w99 -e999 -m' .split()+addrs) Secondary behind primary by 68.5678 seconds|'lag'=68.5678seconds >>> nagios('-w33 -e99 -m' .split()+addrs) Secondary behind primary by 68.5678 seconds > 33|'lag'=68.5678seconds 1 >>> nagios('-w33 -e44 -m' .split()+addrs) Secondary behind primary by 68.5678 seconds > 44|'lag'=68.5678seconds 2 Can't connect >>> stop_current() >>> nagios('-w33 -e44 -m' .split()+addrs) Can't connect to primary at 'localhost:28234': [Errno 111] Connection refused 2 >>> stop_old() >>> nagios('-w33 -e44 -m' .split()+addrs) Can't connect to secondary at 'localhost:25441': [Errno 111] Connection refused 2 Multiple storages (sigh): >>> addr_old, stop_old = ZEO.server( ... storage_conf = """ ... <filestorage first> ... path old.fs ... </filestorage> ... <mappingstorage second> ... </mappingstorage> ... <mappingstorage 1> ... </mappingstorage> ... <mappingstorage thursday> ... </mappingstorage> ... """) >>> addr_current, stop_current = ZEO.server( ... storage_conf = """ ... <filestorage first> ... path current.fs ... </filestorage> ... <mappingstorage second> ... </mappingstorage> ... <mappingstorage 1> ... </mappingstorage> ... <mappingstorage friday> ... </mappingstorage> ... """) >>> addrs = ["%s:%s" % addr_current, "%s:%s" % addr_old] >>> nagios('-w33 -e99 -m' .split()+addrs) Secondary up to date.|'lag'=0.0000seconds Secondary ('first') behind primary by 68.5678 seconds > 33 Storage 'friday' in primary, but not secondary Secondary ('second') up to date. Storage 'thursday' in secondary, but not primary| 'lagfirst'=68.5678seconds 'lagsecond'=0.0000seconds 2 >>> nagios('-w33 -e44' .split()+addrs) Secondary up to date. Secondary ('first') behind primary by 68.5678 seconds > 44 Storage 'friday' in primary, but not secondary Secondary ('second') up to date. Storage 'thursday' in secondary, but not primary 2 >>> stop_old(); stop_current()
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/nagios.rst
nagios.rst
from __future__ import print_function ############################################################################## # # Copyright (c) 2015 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## import binascii import optparse import json import re import socket import struct import sys import ZODB.TimeStamp def connect(addr): if isinstance(addr, tuple): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: m = re.match(r'\[(\S+)\]:(\d+)$', addr) if m: addr = m.group(1), int(m.group(2)) s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: m = re.match(r'(\S+):(\d+)$', addr) if m: addr = m.group(1), int(m.group(2)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(addr) fp = s.makefile('wb') return fp, s def _standard_options(parser): parser.add_option( '-m', '--output-metrics', action="store_true", help="Output replication lag as metric.", ) parser.add_option( '-w', '--warning', type="int", default=0, help="Warning lag, in seconds", ) parser.add_option( '-e', '--error', type="int", default=0, help="Error lag, in seconds", ) def get_ts(addr, name): try: fp, s = connect(addr) except socket.error as err: print("Can't connect to %s at %r: %s" % (name, addr, err)) sys.exit(2) fp = s.makefile('rwb') fp.write(b'\x00\x00\x00\x04ruok') fp.flush() proto = fp.read(struct.unpack(">I", fp.read(4))[0]) datas = fp.read(struct.unpack(">I", fp.read(4))[0]) fp.close() s.close() return dict( (sid, ZODB.TimeStamp.TimeStamp( binascii.a2b_hex(sdata['last-transaction']) ).timeTime()) for (sid, sdata) in json.loads(datas.decode('ascii')).items() ) def check(paddr, saddr, warn, error, output_metrics): try: secondary = get_ts(saddr, 'secondary') primary = get_ts(paddr, 'primary') except SystemExit as e: return e.code output = [] metrics = [] level = 0 if not (primary or secondary): return print("No storages") or 1 for sid, ts in sorted(primary.items()): shown_sid = "" if sid == '1' else " (%r)" % sid sts = secondary.get(sid) if sts is None: output.append("Storage %r in primary, but not secondary" % sid) level = 2 continue delta = ts - sts if output_metrics: metrics.append( "'lag%s'=%.4fseconds" % ('' if sid=='1' else sid, delta)) if delta < 0: output.append( "Primary%s behind secondary by %s seconds" % (shown_sid, delta) ) level = 2 else: if delta > 0: output.append( "Secondary%s behind primary by %.4f seconds" % (shown_sid, delta)) if error and delta > error: output[-1] += ' > %s' % error level = 2 elif warn and delta > warn: output[-1] += ' > %s' % warn level = max(level, 1) else: output.append("Secondary%s up to date." % shown_sid) for sid in sorted(secondary): if sid not in primary: output.append("Storage %r in secondary, but not primary" % sid) level = 2 if metrics: output[0] += '|' + metrics.pop(0) if metrics: if len(output) == 1: output.append('') output[-1] += '| ' + '\n '.join(metrics) print('\n'.join(output)) return level or None def basic(args=None): """zrs-nagios [options] PRIMARY_ADDRESS SECONDARY_ADDRESS """ if args is None: args = sys.argv[1:] parser = optparse.OptionParser(__doc__) _standard_options(parser) (options, args) = parser.parse_args(args) if len(args) != 2 or not (options.output_metrics or options.warning or options.error): return print('Usage: ' + basic.__doc__) or 2 paddr, saddr = args return check( paddr, saddr, options.warning, options.error, options.output_metrics)
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/nagios.py
nagios.py
import ConfigParser import datetime import logging import logging.config import sys import threading import time import ZEO.ClientStorage, ZEO.Exceptions import ZODB.TimeStamp import ZODB.utils event = threading.Event() stop = event.set def main(args=None, testing=False): if args is None: args = sys.argv[1:] [config_path] = args logging.config.fileConfig(config_path) global logger, monitor_logger logger = logging.getLogger(__name__) monitor_logger = logging.getLogger('monitor') parser = ConfigParser.RawConfigParser() parser.read(config_path) data = dict( [(section, dict(parser.items(section))) for section in parser.sections()] ) options = data["monitor"] frequency = float(options.get('frequency', 5)) message = options.get( 'message', '%(hostname)s %(service)s %(comment)s') clusters = [ Cluster(cluster_name, data[cluster_name], frequency, message) for cluster_name in options['clusters'].split() ] if not testing: # This is a round-about way to run forever event.wait() else: return clusters zeo_options = dict(wait= False, read_only=True, min_disconnect_poll=1, max_disconnect_poll=30, ) class Base(object): def __init__(self, name, address_string, service, message): address = tuple(address_string.split(':')) address = address[0], int(address[1]) self.address = address self.name = name self.message = message self.service = name + '-' + service self.storage = ZEO.ClientStorage.ClientStorage(address, **zeo_options) def _report(self, log, severity, comment): return log( self.message % dict( hostname = self.address[0], port = self.address[1], name = self.name, service = self.service, severity = severity, comment = comment, utc = datetime.datetime.utcnow().strftime("%m-%d-%Y %H:%M:%S"), )) def ok(self, comment): self._report(monitor_logger.info, 'INFO', comment) def warning(self, comment): self._report(monitor_logger.warning, 'WARNING', comment) def critical(self, comment): self._report(monitor_logger.critical, 'CRITICAL', comment) class Cluster(Base): def __init__(self, name, options, frequency, message): super(Cluster, self).__init__(name, options['primary'], 'primary', message) self.frequency = frequency self.secondaries = [ Secondary(name, address_string, message) for address_string in options['secondaries'].split() ] thread = self.thread = threading.Thread(target=self.run, name=name) thread.setDaemon(True) thread.start() def run(self): try: delta_seconds = self.frequency * 60 storage = self.storage secondaries = self.secondaries last_connected = 'Never connected' next = time.time() next -= next % delta_seconds ts_seconds = 0 while not event.isSet(): now = time.time() next += delta_seconds wait = next - now while wait < 0.0: next += delta_seconds wait = next - now time.sleep(wait) if event.isSet(): break try: ts = storage._server.lastTransaction() except ZEO.Exceptions.ClientDisconnected: self.critical("Disconnected since: %s" % last_connected) else: last_connected = time.ctime(time.time()) ts_seconds = ZODB.TimeStamp.TimeStamp(ts).timeTime() if ts == ZODB.utils.z64: self.ok("No transactions") else: self.ok("Committed: %s" % time.ctime(ts_seconds)) for secondary in secondaries: secondary.check(ts_seconds, now) except: logger.exception("Error in cluster %s", self.name) monitor_logger.error("Error in cluster %s", self.name) raise class Secondary(Base): def __init__(self, name, address_string, message): super(Secondary, self).__init__(name, address_string, 'secondary', message) self.last_connected = 'Never connected' self.last_seconds = -2208988800.0 def check(self, primary_seconds, primary_start): try: ts = self.storage._server.lastTransaction() except ZEO.Exceptions.ClientDisconnected: self.critical("Disconnected since: %s" % self.last_connected) else: self.last_connected = time.ctime(time.time()) ts_seconds = ZODB.TimeStamp.TimeStamp(ts).timeTime() if (ts_seconds - primary_seconds) > (time.time()-primary_start): if primary_seconds < 0: self.critical( "Secondary has data, %s, but primary doesn't." % time.ctime(ts_seconds) ) else: self.critical( "Secondary is ahead of primary s=%s p=%s" % (time.ctime(ts_seconds), time.ctime(primary_seconds)) ) elif ((primary_seconds - ts_seconds) > 60 or ((primary_seconds > ts_seconds) and (time.time() - primary_seconds) > 60 ) ): # We're out of date. Maybe we're making progress. if ts_seconds > self.last_seconds: meth = self.warning else: meth = self.critical if ts == ZODB.utils.z64: meth("Secondary has no data, but primary does: %s" % (time.ctime(primary_seconds)) ) else: meth("Secondary out of date: s=%s p=%s" % (time.ctime(ts_seconds), time.ctime(primary_seconds)) ) else: if ts == ZODB.utils.z64: self.ok("No data") else: self.ok("Committed: %s" % time.ctime(ts_seconds)) self.last_seconds = ts_seconds
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/monitor.py
monitor.py
from six.moves import cPickle import logging from hashlib import md5 import os import tempfile import threading import twisted.internet.protocol import zc.zrs.primary import zc.zrs.reactor import zc.zrs.sizedmessage import ZODB.blob import ZODB.interfaces import ZODB.POSException import zope.interface logger = logging.getLogger(__name__) class SecondaryProtocol(twisted.internet.protocol.Protocol): _zrs_transaction = None keep_alive_delayed_call = None logger = logger def connectionMade(self): self.__stream = zc.zrs.sizedmessage.Stream(self.messageReceived) self.__peer = str(self.transport.getPeer()) + ': ' self.factory.instance = self self.transport.write(zc.zrs.sizedmessage.marshal( self.factory.zrs_proto)) tid = self.factory.storage.lastTransaction() self._replication_stream_md5 = md5(tid) self.transport.write(zc.zrs.sizedmessage.marshal(tid)) self.info("Connected") if self.factory.keep_alive_delay > 0: self.keep_alive() def connectionLost(self, reason): if (self.keep_alive_delayed_call is not None and self.keep_alive_delayed_call.active()): self.keep_alive_delayed_call.cancel() self.factory.instance = None if self._zrs_transaction is not None: self.factory.storage.tpc_abort(self._zrs_transaction) self._zrs_transaction = None self.info("Disconnected %r", reason) def error(self, message, *args, **kw): self.logger.critical(self.__peer + message, *args, **kw) self.factory.connector.disconnect() def info(self, message, *args): self.logger.info(self.__peer + message, *args) def keep_alive(self): if self.keep_alive_delayed_call is not None: self.transport.write(b"\0\0\0\0") self.keep_alive_delayed_call = self.factory.reactor.callLater( self.factory.keep_alive_delay, self.keep_alive, ) def dataReceived(self, data): try: self.__stream(data) except: self.error("Input data error", exc_info=True) __blob_file_blocks = None __blob_file_handle = None __blob_file_name = None __blob_record = None __record = None def messageReceived(self, message): if self.__record: # store or store blob data record oid, serial, version, data_txn = self.__record self.__record = None data = message or None key = serial, version oids = self.__inval.get(key) if oids is None: oids = self.__inval[key] = {} oids[oid] = 1 if self.__blob_file_blocks: # We have to collect blob data self.__blob_record = oid, serial, data, version, data_txn (self.__blob_file_handle, self.__blob_file_name ) = tempfile.mkstemp('blob', 'secondary', self.factory.storage.temporaryDirectory() ) else: self.factory.storage.restore( oid, serial, data, version, data_txn, self._zrs_transaction) elif self.__blob_record: os.write(self.__blob_file_handle, message) self.__blob_file_blocks -= 1 if self.__blob_file_blocks == 0: # We're done collecting data, we can write the data: os.close(self.__blob_file_handle) oid, serial, data, version, data_txn = self.__blob_record self.__blob_record = None self.factory.storage.restoreBlob( oid, serial, data, self.__blob_file_name, data_txn, self._zrs_transaction) else: # Ordinary message message_type, data = cPickle.loads(message) if message_type == 'T': assert self._zrs_transaction is None assert self.__record is None transaction = Transaction(*data) self.__inval = {} self.factory.storage.tpc_begin( transaction, transaction.id, transaction.status) self._zrs_transaction = transaction elif message_type == 'S': self.__record = data elif message_type == 'B': self.__record = data[:-1] self.__blob_file_blocks = data[-1] elif message_type == 'C': self._check_replication_stream_checksum(data) assert self._zrs_transaction is not None assert self.__record is None self.factory.storage.tpc_vote(self._zrs_transaction) def invalidate(tid): if self.factory.db is not None: for (tid, version), oids in self.__inval.items(): self.factory.db.invalidate(tid, oids) self.factory.storage.tpc_finish( self._zrs_transaction, invalidate) self._zrs_transaction = None else: raise ValueError("Invalid message type, %r" % message_type) self._replication_stream_md5.update(message) def _check_replication_stream_checksum(self, data): if self.factory.check_checksums: checksum = data[0] if checksum != self._replication_stream_md5.digest(): raise AssertionError( "Bad checksum", checksum, self._replication_stream_md5.digest()) class SecondaryFactory(twisted.internet.protocol.ClientFactory): db = None connector = None closed = False protocol = SecondaryProtocol # We'll keep track of the connected instance, if any mainly # for the convenience of some tests that want to force disconnects to # stress the secondaries. instance = None def __init__(self, reactor, storage, reconnect_delay, check_checksums, zrs_proto, keep_alive_delay, secondary): self.reactor = reactor self.storage = storage self.reconnect_delay = reconnect_delay self.check_checksums = check_checksums self.zrs_proto = zrs_proto self.keep_alive_delay = keep_alive_delay self.secondary = secondary def close(self, callback): self.closed = True if self.connector is not None: self.connector.disconnect() callback() def startedConnecting(self, connector): if self.closed: connector.disconnect() else: self.connector = connector def clientConnectionFailed(self, connector, reason): self.connector = None if not self.closed: self.reactor.callLater(self.reconnect_delay, self.connect) def clientConnectionLost(self, connector, reason): self.connector = None if not self.closed: self.reactor.callLater(self.reconnect_delay, self.connect) def connect(self): addr = self.secondary._addr reactor = self.reactor if isinstance(addr, str): reactor.callFromThread(reactor.connectUNIX, addr, self) else: host, port = addr reactor.callFromThread(reactor.connectTCP, host, port, self) class Secondary(zc.zrs.primary.Base): factoryClass = SecondaryFactory logger = logger def __init__(self, storage, addr, reactor=None, reconnect_delay=60, check_checksums=True, keep_alive_delay=0): zc.zrs.primary.Base.__init__(self, storage, addr, reactor) storage = self._storage reactor = self._reactor zrs_proto = self.copyMethods(storage) self._factory = self.factoryClass( reactor, storage, reconnect_delay, check_checksums, zrs_proto, keep_alive_delay, self) self.logger.info("Opening %s %s", self.getName(), addr) if addr: self._factory.connect() def setReplicationAddress(self, addr): old = self._addr self._addr = addr if not old: self._factory.connect() def copyMethods(self, storage): if (ZODB.interfaces.IBlobStorage.providedBy(storage) and hasattr(storage, 'restoreBlob') ): zope.interface.directlyProvides(self, ZODB.interfaces.IBlobStorage) for name in ('loadBlob', 'openCommittedBlobFile', 'temporaryDirectory', 'restoreBlob'): setattr(self, name, getattr(storage, name)) zrs_proto = b'zrs2.1' else: zrs_proto = b'zrs2.0' # required methods for name in ( 'getName', 'getSize', 'history', 'lastTransaction', 'load', 'loadBefore', 'loadSerial', 'pack', 'sortKey', ): setattr(self, name, getattr(storage, name)) # Optional methods: for name in ( 'iterator', 'cleanup', 'loadEx', 'getSerial', 'supportsTransactionalUndo', 'tpc_transaction', 'getTid', 'lastInvalidations', 'supportsUndo', 'undoLog', 'undoInfo', 'supportsVersions', 'versionEmpty', 'modifiedInVersion', 'versions', 'record_iternext', 'checkCurrentSerialInTransaction', ): if hasattr(storage, name): setattr(self, name, getattr(storage, name)) return zrs_proto def isReadOnly(self): return True def write_method(*args, **kw): raise ZODB.POSException.ReadOnlyError() new_oid = tpc_begin = undo = write_method def registerDB(self, db, limit=None): self._factory.db = db def close(self): self.logger.info('Closing %s %s', self.getName(), self._addr) event = threading.Event() self._reactor.callFromThread(self._factory.close, event.set) event.wait() self._storage.close() class Transaction: def __init__(self, tid, status, user, description, extension): self.id = tid self.status = status self.user = user self.description = description self.extension = extension @property def _extension(self): return self.extension
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/secondary.py
secondary.py
import binascii import ZODB.blob import ZODB.interfaces import zope.interface @zope.interface.implementer(ZODB.interfaces.IStorageWrapper) class XformStorage(object): copied_methods = ( 'close', 'getName', 'getSize', 'history', 'isReadOnly', 'lastTransaction', 'new_oid', 'sortKey', 'tpc_abort', 'tpc_begin', 'tpc_finish', 'tpc_vote', 'loadBlob', 'openCommittedBlobFile', 'temporaryDirectory', 'supportsUndo', 'undo', 'undoLog', 'undoInfo', # The following should use base methods when in server mode 'load', 'loadBefore', 'loadSerial', 'store', 'restore', 'iterator', 'storeBlob', 'restoreBlob', 'record_iternext', ) def __init__(self, base, transform, untransform, prefix, server=False): if len(prefix) != 1: raise ValueError("Must give a 1-character prefix", prefix) prefix = b'.' + prefix for name in self.copied_methods: v = getattr(base, name, None) if v is not None: setattr(self, name, v) if transform is not None: def _transform(data): if data and (data[:2] != prefix): transformed = transform(data) if transformed is not data: data = prefix + transformed return data def transform_record_data(data): return _transform(self._db_transform(data)) else: _transform = lambda data: data def transform_record_data(data): return self._db_transform(data) self.transform_record_data = transform_record_data def _untransform(data): if data and (data[:2] == prefix): return untransform(data[2:]) else: return data self._untransform = _untransform def untransform_record_data(data): return self._db_untransform(_untransform(data)) self.untransform_record_data = untransform_record_data if (not server) and (transform is not None): def store(oid, serial, data, version, transaction): return base.store( oid, serial, _transform(data), version, transaction) self.store = store def restore(oid, serial, data, version, prev_txn, transaction): return base.restore(oid, serial, _transform(data), version, prev_txn, transaction) self.restore = restore def storeBlob(oid, oldserial, data, blobfilename, version, transaction): return base.storeBlob(oid, oldserial, _transform(data), blobfilename, version, transaction) self.storeBlob = storeBlob def restoreBlob(oid, serial, data, blobfilename, prev_txn, transaction): return base.restoreBlob(oid, serial, _transform(data), blobfilename, prev_txn, transaction) self.restoreBlob = restoreBlob if not server: def load(oid, version=''): data, serial = base.load(oid, version) return _untransform(data), serial self.load = load def loadBefore(oid, tid): r = base.loadBefore(oid, tid) if r is not None: data, serial, after = r return _untransform(data), serial, after else: return r self.loadBefore = loadBefore def loadSerial(oid, serial): return _untransform(base.loadSerial(oid, serial)) self.loadSerial = loadSerial def iterator(start=None, stop=None): for t in base.iterator(start, stop): yield Transaction(t, _untransform) self.iterator = iterator def record_iternext(next=None): oid, tid, data, next = self.base.record_iternext(next) return oid, tid, binascii.a2b_hex(data[2:]), next self.record_iternext = record_iternext zope.interface.directlyProvides(self, zope.interface.providedBy(base)) self.base = base base.registerDB(self) def __getattr__(self, name): return getattr(self.base, name) def __len__(self): return len(self.base) def registerDB(self, db): self.db = db self._db_transform = db.transform_record_data self._db_untransform = db.untransform_record_data _db_transform = _db_untransform = lambda self, data: data def pack(self, pack_time, referencesf, gc=True): _untransform = self._untransform def refs(p, oids=None): return referencesf(_untransform(p), oids) return self.base.pack(pack_time, refs, gc) def invalidateCache(self): return self.db.invalidateCache() def invalidate(self, transaction_id, oids, version=''): return self.db.invalidate(transaction_id, oids, version) def references(self, record, oids=None): return self.db.references(self._untransform(record), oids) def copyTransactionsFrom(self, other): ZODB.blob.copyTransactionsFromTo(other, self) def xiterator(baseit, untransform, prefix): if len(prefix) != 1: raise ValueError("Most give a 1-character prefix", prefix) prefix = '.' + prefix def _untransform(data): if data and (data[:2] == prefix): return untransform(data[2:]) else: return data def iterator(start=None, stop=None): for t in baseit: yield Transaction(t, _untransform) class Transaction(object): def __init__(self, transaction, untransform): self.__transaction = transaction self.__untransform = untransform def __iter__(self): untransform = self.__untransform for r in self.__transaction: if r.data: r.data = untransform(r.data) yield r def __getattr__(self, name): return getattr(self.__transaction, name) def HexStorage(base, server=False): return XformStorage(base, binascii.b2a_hex, binascii.a2b_hex, b'h', server) class ZConfigHex: def __init__(self, config): self.config = config self.name = config.getSectionName() def open(self): return HexStorage(self.config.base.open()) class ZConfigServerHex(ZConfigHex): def open(self): return HexStorage(self.config.base.open(), True)
zc.zrs
/zc.zrs-3.1.0.tar.gz/zc.zrs-3.1.0/src/zc/zrs/xformstorage/__init__.py
__init__.py
Changes ======= 3.0 (2023-01-23) ---------------- - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Add support for Python 3.8, 3.9, 3.10, 3.11. 2.0.0 (2019-02-26) ------------------ - Fix logic bug in seconds_difference() that could introduce error up to nearly a whole second for any particular event. - Limit number precision in HTML reports to 3 decimal digits. - Drop Python 2.6 support. - Add Python 3.4 through 3.7 support. 1.4.0 (2015-05-06) ------------------ - tracereport can be limited to a date range with --date=YYYY-MM-DD..YYYY-MM-DD 1.3.2 (2012-03-20) ------------------ - Slight refactoring to allow alternative tracelog implementations. 1.3.1 (2012-03-20) ------------------ - Fix KeyError: 'ZODB.interfaces.IConnection' on requests that do not have a ZODB connection in annotations (e.g. GET /++etc++process). 1.3.0 (2010-04-08) ------------------ - Added 'D' records providing database transfer counts. This is somewhat experimental. The tracereport script ignores D records. 1.2.1 (2010-01-27) ------------------ - fix reST headings so PyPI page renders properly - add a warning about the strange logger name 1.2.0 (2009-08-31) ------------------ - tracereport improvements: - fix parsing bugs. - add basic tests. - report time with microsecond resolution. 1.1.5 (2009-04-01) ------------------ - new key for user name in environ (refactoring in zope.app.wsgi) 1.1.4 (2009-03-25) ------------------ - put user names in access log 1.1.3 (2009-03-25) ------------------ - sub-second resolution in timestamps 1.1.1 (2008-11-21) ------------------ - switch back to logger name zc.tracelog to maintain backward compatibility. 1.1.0 (2008-10-31) ------------------ - fixed tracelog extension format so that it doesn't conflict with the Zope2 trace code for server shutdown. - added *summary-only* and *summary-lines* options to tracereport. - added shading of alternating rows in tracereport table output. - fixed a documentation error for loghandler configuration. 0.4 (2008-10-09) ---------------- - added automated tests. - fixed bug where log entries could be split by messages containing newline characters. - added request query strings to log. - added the tracelog to the WSGI environment.
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/CHANGES.rst
CHANGES.rst
======================= Zope 3/ZServer tracelog ======================= .. image:: https://github.com/zopefoundation/zc.zservertracelog/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zc.zservertracelog/actions/workflows/tests.yml This package implements a Zope2-style (extended) tracelog. A tracelog is a kind of access log that records several low-level events for each request. Each log entry starts with a record type, a request identifier and the time. Some log records have additional data. To create a trace log, you need to: - Include the zc.zservertracelog configuration in your site zcml file:: <include package="zc.zservertracelog" /> - Define where messages to the 'zc.tracelog' logger should go. In your zope.conf file, use something like:: <logger> name zc.tracelog propagate false <logfile> format %(message)s path /home/jim/p/zc.zservertracelog/dev/trace.log </logfile> </logger> The analysis script, tracereport, can be used to analyze the trace log. I recommend the html output option. Trace log records ================= - Request begins: B -1214390740 2007-04-27T20:16:55.582940 GET / Includes the request method and path. - Got request input: I -1214390740 2007-04-27T20:16:55.605791 0 Includes the request content length. - Entered application thread: C -1214390740 2007-04-27T20:16:55.703829 - Database activity D -1223774356 2007-04-27T20:16:55.890371 42 0 x 2 1 The data includes objects loaded and saved for each database except databases for which there was no activity. Note that it's common for the main database to be unnamed, and the data often starts with objects loaded and saved for the main database. In the example above, 42 objects were loaded from the unnamed database. Two objects were loaded from and one saved to the database named 'x'. If requests are retried due to conflict errors, then there will be multiple 'D' records. - Application done: A -1223774356 2007-04-27T20:16:55.890371 500 84 Includes the response content length. - Request done: E -1223774356 2007-04-27T20:16:55.913855 In addition, application startup is logged with an 'S' record: S 0 2007-04-27T20:24:29.013922 Tracelog extension records are prefixed with a '-': - -1223774356 2008-09-12T15:51:05.559302 zc.example.extension message
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/README.rst
README.rst
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/LICENSE.rst
LICENSE.rst
================ ZServer TraceLog ================ A tracelog is a kind of access log that records several low-level events for each request. Each log entry starts with a record type, a request identifier and the time. Some log records have additional data. >>> import zc.zservertracelog.tracelog >>> import zope.app.appsetup.interfaces For these examples, we'll add a log handler that outputs to standard out. >>> import logging >>> import sys >>> stdout_handler = logging.StreamHandler(sys.stdout) The logger's name is not the package name, but "zc.tracelog" for backward compatibility. >>> logger = logging.getLogger('zc.tracelog') >>> logger.setLevel(logging.INFO) >>> logger.addHandler(stdout_handler) Server Startup ============== There is an event handler to log when the Z server starts. >>> zc.zservertracelog.tracelog.started( ... zope.app.appsetup.interfaces.ProcessStarting()) S 0 2008-08-26 11:55:00.000000 Tracing Applications ==================== The tracelog machinery is primarily implemented as an extension to the zope.server WSGI server. To test the tracelog machinery, we'll create our own application. >>> faux_app = FauxApplication() Now, let's create an instance of the tracelog server. >>> addr, port = '127.0.0.1', 0 >>> trace_server = zc.zservertracelog.tracelog.Server( ... faux_app, None, addr, port) Let's also define a convenience function for processing requests. >>> def invokeRequest(req): ... channel = trace_server.channel_class(trace_server, None, addr) ... channel.received(req) Process a simple request. >>> req1 = b"""\ ... GET /test-req1 HTTP/1.1 ... Host: www.example.com ... ... """ >>> invokeRequest(req1) B 23423600 2008-08-27 10:54:08.000000 GET /test-req1 I 23423600 2008-08-27 10:54:08.000000 0 C 23423600 2008-08-27 10:54:08.000000 A 23423600 2008-08-27 10:54:08.000000 200 ? E 23423600 2008-08-27 10:54:08.000000 Here we get records for each stage in the request: B The request began I Input was read. C An application thread began processing the request. A The response was computed. E The request ended. Application Errors ================== The tracelog will also log application errors. To show this, we'll set up our test application to raise an error when called. >>> def app_failure(*args, **kwargs): ... raise Exception('oh noes!') >>> faux_app.app_hook = app_failure Invoking the request produces log entries for every trace point, and the application error is written to the *Application End (A)* trace entry. >>> try: ... invokeRequest(req1) ... except: ... pass B 21663984 2008-09-02 11:19:26.000000 GET /test-req1 I 21663984 2008-09-02 11:19:26.000000 0 C 21663984 2008-09-02 11:19:26.000000 A 21663984 2008-09-02 11:19:26.000000 Error: oh noes! E 21663984 2008-09-02 11:19:26.000000 Response Errors =============== The tracelog also handles errors that can be generated when writing to the response. To show this, we'll set up our test application to return a response that produces an error when written to. >>> def response_of_wrong_type(*args, **kwargs): ... def f(): ... if 0: ... yield 1 ... raise ValueError("sample error") ... return f() >>> faux_app.app_hook = response_of_wrong_type Invoking the request produces log entries for every trace point, and the error is written to the *Request End (E)* trace entry. >>> try: ... invokeRequest(req1) ... except: ... pass B 21651664 2008-09-02 13:59:02.000000 GET /test-req1 I 21651664 2008-09-02 13:59:02.000000 0 C 21651664 2008-09-02 13:59:02.000000 A 21651664 2008-09-02 13:59:02.000000 200 ? E 21651664 2008-09-02 13:59:02.000000 Error: sample error Let's clean up before moving on. >>> faux_app.app_hook = None Log Messages Containing Line Breaks =================================== Messages to the tracelog that contain newline characters will not split a log entry into multiple lines. >>> req2 = b"""\ ... GET /test-req2/%0Aohnoes/ HTTP/1.1 ... Host: www.example.com/linebreak ... ... """ >>> invokeRequest(req2) B 21598352 2008-09-12 11:40:27.000000 GET /test-req2/\nohnoes/ I 21598352 2008-09-12 11:40:27.000000 0 C 21598352 2008-09-12 11:40:27.000000 A 21598352 2008-09-12 11:40:27.000000 200 ? E 21598352 2008-09-12 11:40:27.000000 Request Query Strings ===================== The tracelog preserves request query strings. >>> req3 = b"""\ ... GET /test-req3/?creature=unicorn HTTP/1.1 ... Host: www.example.com/query-string ... ... """ >>> invokeRequest(req3) B 21598352 2008-09-12 11:40:27.000000 GET /test-req3/?creature=unicorn I 21598352 2008-09-12 11:40:27.000000 0 C 21598352 2008-09-12 11:40:27.000000 A 21598352 2008-09-12 11:40:27.000000 200 ? E 21598352 2008-09-12 11:40:27.000000 Adding Additional Entries to the Trace Log ========================================== A tracelog object is added to the WSGI environment on each request. This object implements ``ITraceLog`` and provides applications a method to add custom entries to the log. Here is an example application that adds a custom entry to the tracelog. >>> def noisy_app(environ, start_response): ... logger = environ['zc.zservertracelog.interfaces.ITraceLog'] ... logger.log('beep! beep!') >>> faux_app.app_hook = noisy_app >>> invokeRequest(req1) B 21569456 2008-09-12 15:51:05.000000 GET /test-req1 I 21569456 2008-09-12 15:51:05.000000 0 C 21569456 2008-09-12 15:51:05.000000 - 21569456 2008-09-12 15:51:05.000000 beep! beep! A 21569456 2008-09-12 15:51:05.000000 200 ? E 21569456 2008-09-12 15:51:05.000000 Database statistics =================== zc.zservertracelog provides event subscribers that gather statistics about database usage in a request. It assumes that requests have 'ZODB.interfaces.IConnection' annotations that are ZODB database connections. To demonstrate how this works, we'll create a number of stubs: >>> class Connection: ... reads = writes = 0 ... db = lambda self: self ... getTransferCounts = lambda self: (self.reads, self.writes) ... def __init__(self, environ, *names): ... self.get = environ.get ... self.databases = names ... self._connections = dict((name, Connection(environ)) ... for name in names) ... self.get_connection = self._connections.get ... request = property(lambda self: self) ... @property ... def annotations(self): ... return {'ZODB.interfaces.IConnection': self} ... def update(self, name, reads=0, writes=0): ... c = self._connections[name] ... c.reads, c.writes = reads, writes The Connection stub is kind of heinous. :) It actually stubs out zope.app.publisher request events, requests, connections, and databases. We simulate a request that calls the traversal hooks a couple of times, does some database activity and redoes requests due to conflicts. >>> def dbapp1(environ, start_response): ... conn = Connection(environ, '', 'x', 'y') ... conn.update('', 1, 1) ... conn.update('x', 2, 2) ... zc.zservertracelog.tracelog.before_traverse(conn) ... conn.update('', 3, 1) ... zc.zservertracelog.tracelog.before_traverse(conn) ... conn.update('', 5, 3) ... conn.update('y', 1, 0) ... zc.zservertracelog.tracelog.request_ended(conn) ... zc.zservertracelog.tracelog.before_traverse(conn) ... conn.update('', 6, 3) ... zc.zservertracelog.tracelog.before_traverse(conn) ... conn.update('', 7, 4) ... conn.update('y', 3, 0) ... zc.zservertracelog.tracelog.request_ended(conn) >>> faux_app.app_hook = dbapp1 >>> invokeRequest(req1) B 49234448 2010-04-07 17:03:41.229648 GET /test-req1 I 49234448 2010-04-07 17:03:41.229811 0 C 49234448 2010-04-07 17:03:41.229943 D 49234448 2010-04-07 17:03:41.230131 4 2 y 1 0 D 49234448 2010-04-07 17:03:41.230264 2 1 y 2 0 A 49234448 2010-04-07 17:03:41.230364 200 ? E 23418928 2008-08-26 10:55:00.000000 Here we got multiple D records due to (simulated) conflicts. We show database activity for those databases for which there was any. The databases are sorted by name, with the unnamed database coming first. For each database, the number of object's loaded and saved are provided. Since not all requests necessarily have a ZODB connection in their annotations (consider, e.g. ``GET /++etc++process``), let's make sure this works too >>> class Request: ... def __init__(self, environ): ... self.get = environ.get ... self.annotations = {} ... # let this stub pretend to be a RequestEvent too ... request = property(lambda self: self) >>> def dbapp2(environ, start_response): ... req = Request(environ) ... zc.zservertracelog.tracelog.before_traverse(req) ... zc.zservertracelog.tracelog.before_traverse(req) ... zc.zservertracelog.tracelog.request_ended(req) >>> faux_app.app_hook = dbapp2 >>> invokeRequest(req1) B 146419788 2012-01-10 03:10:05.501841 GET /test-req1 I 146419788 2012-01-10 03:10:05.502148 0 C 146419788 2012-01-10 03:10:05.502370 A 146419788 2012-01-10 03:10:05.502579 200 ? E 146419788 2012-01-10 03:10:05.502782
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/src/zc/zservertracelog/README.rst
README.rst
import unittest from io import StringIO def strip(s): return s.strip() def fseek(f, size, search, getkey=strip): # Check first line key = getkey(f.readline()) if key >= search: f.seek(0) return 0 seen = 0 position = 0 seek = chunk = size // 2 while chunk > 0: f.seek(seek) line = f.readline() # maybe incomplete position = f.tell() line = f.readline() # complete key = getkey(line) chunk //= 2 if key >= search: seek -= chunk seen = position else: seek += chunk if seen and key < search: position = seen f.seek(position) return position def _get_btree_args(*lines): content = '\n'.join(lines) f = StringIO(content) size = len(content) return (f, size) def _get_colon_key(line): key, x = line.split(':', 1) return key.strip() class FSeekTest(unittest.TestCase): def test_1(self): f, size = _get_btree_args( '0', '1', '2', '3', '4', ) p = fseek(f, size, '0') self.assertEqual(p, 0) f.seek(0) p = fseek(f, size, '1') self.assertEqual(p, 2) f.seek(0) p = fseek(f, size, '2') self.assertEqual(p, 4) f.seek(0) p = fseek(f, size, '3') self.assertEqual(p, 6) f.seek(0) p = fseek(f, size, '4') self.assertEqual(p, 8) def test_2(self): f, size = _get_btree_args( '0', '0', '0', '1', '1', '1', '2', '2', '2', ) p = fseek(f, size, '0') self.assertEqual(p, 0) f.seek(0) p = fseek(f, size, '1') self.assertEqual(p, 6) f.seek(0) p = fseek(f, size, '2') self.assertEqual(p, 12) def test_3(self): f, size = _get_btree_args( '0: sdf asdfasd ', '1: dffwef', '2: afwefwfaf adfa sdf wef aefasdfa sdfae', '3: afefw', '4:', ) p = fseek(f, size, '0') self.assertEqual(p, 0) f.seek(0) p = fseek(f, size, '1', _get_colon_key) self.assertEqual(p, 16) f.seek(0) p = fseek(f, size, '2', _get_colon_key) self.assertEqual(p, 26) f.seek(0) p = fseek(f, size, '3', _get_colon_key) self.assertEqual(p, 67) f.seek(0) p = fseek(f, size, '4', _get_colon_key) self.assertEqual(p, 76)
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/src/zc/zservertracelog/fseek.py
fseek.py
import datetime import logging import re import zope.app.appsetup.interfaces import zope.component import zope.server.http.httprequestparser import zope.server.http.httpserverchannel from zope.app.server import servertype from zope.app.wsgi import WSGIPublisherApplication from zope.publisher.interfaces import EndRequestEvent from zope.server.http import wsgihttpserver from zope.server.http.commonaccesslogger import CommonAccessLogger from zope.traversing.interfaces import BeforeTraverseEvent import zc.zservertracelog.interfaces tracelog = logging.getLogger('zc.tracelog') def _log(channel_id, trace_code='-', msg=None, timestamp=None): if timestamp is None: timestamp = datetime.datetime.now() entry = '{} {} {}'.format(trace_code, channel_id, timestamp) if msg: entry += ' %s' % repr(msg)[1:-1] tracelog.info(entry) @zope.component.adapter(zope.publisher.interfaces.IRequest) @zope.interface.implementer(zc.zservertracelog.interfaces.ITraceLog) def get(request): return request['zc.zservertracelog.interfaces.ITraceLog'] @zope.interface.implementer(zc.zservertracelog.interfaces.ITraceLog) class TraceLog: def __init__(self, channel_id): self.channel_id = channel_id def log(self, msg=None, code='-'): _log(self.channel_id, code, msg) class Parser(zope.server.http.httprequestparser.HTTPRequestParser): def __init__(self, x): self._Channel__B = datetime.datetime.now() zope.server.http.httprequestparser.HTTPRequestParser.__init__(self, x) class Channel(zope.server.http.httpserverchannel.HTTPServerChannel): parser_class = Parser def handle_request(self, parser): full_path = parser.path # If parser.query == '' we want full_path with a trailing '?' if parser.query is not None: full_path += '?%s' % parser.query cid = id(self) _log(cid, 'B', '{} {}'.format(parser.command, full_path), parser.__B) _log(cid, 'I', str(parser.content_length)) zope.server.http.httpserverchannel.HTTPServerChannel.handle_request( self, parser) status_match = re.compile(r'(\d+) (.*)').match class Server(wsgihttpserver.WSGIHTTPServer): channel_class = Channel def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def executeRequest(self, task): """Overrides HTTPServer.executeRequest().""" cid = id(task.channel) _log(cid, 'C') env = task.getCGIEnvironment() env['wsgi.input'] = task.request_data.getBodyStream() env['zc.zservertracelog.interfaces.ITraceLog'] = TraceLog(cid) def start_response(status, headers): # Prepare the headers for output status, reason = status_match(status).groups() task.setResponseStatus(status, reason) if 'wsgi.logging_info' in env: task.setAuthUserName(env['wsgi.logging_info']) task.appendResponseHeaders(['%s: %s' % i for i in headers]) # Return the write method used to write the response data. return wsgihttpserver.fakeWrite # Call the application to handle the request and write a response try: response = self.application(env, start_response) except Exception as v: _log(cid, 'A', 'Error: %s' % v) _log(cid, 'E') raise else: accumulated_headers = getattr(task, 'accumulated_headers') or () length = [h.split(': ')[1].strip() for h in accumulated_headers if h.lower().startswith('content-length: ')] if length: length = length[0] else: length = '?' _log(cid, 'A', '{} {}'.format( getattr(task, 'status', '?'), length)) try: task.write(response) except Exception as v: _log(cid, 'E', 'Error: %s' % v) raise else: _log(cid, 'E') http = servertype.ServerType( Server, WSGIPublisherApplication, CommonAccessLogger, 8080, True) pmhttp = servertype.ServerType( wsgihttpserver.PMDBWSGIHTTPServer, WSGIPublisherApplication, CommonAccessLogger, 8013, True) @zope.component.adapter(zope.app.appsetup.interfaces.IProcessStartingEvent) def started(event): tracelog.info('S 0 %s', datetime.datetime.now()) @zope.component.adapter(BeforeTraverseEvent) def before_traverse(event): request = event.request tl = request.get('zc.zservertracelog.interfaces.ITraceLog') if tl is None: return if getattr(tl, 'transfer_counts', None) is None: connection = request.annotations.get('ZODB.interfaces.IConnection') # Not all requests have a ZODB connection; consider /++etc++process if connection is None: return tl.transfer_counts = { name: connection.get_connection(name).getTransferCounts() for name in connection.db().databases} @zope.component.adapter(EndRequestEvent) def request_ended(event): request = event.request tl = request.get('zc.zservertracelog.interfaces.ITraceLog') if tl is None: return initial_counts = getattr(tl, 'transfer_counts', None) if not initial_counts: return tl.transfer_counts = None # Reset in case of conflict connection = request.annotations.get('ZODB.interfaces.IConnection') if connection is None: return data = [] for name in connection.db().databases: conn = connection.get_connection(name) r, w = conn.getTransferCounts() ir, iw = initial_counts[name] r -= ir w -= iw if r or w: data.append((name, r, w)) msg = ' '.join(' '.join(map(str, r)) for r in sorted(data)) tl.log(msg.strip(), 'D')
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/src/zc/zservertracelog/tracelog.py
tracelog.py
"""Yet another trace log analysis tool """ import datetime import optparse import os.path import sys from zc.zservertracelog.fseek import fseek # Date format and default offset. DATE_FORMATS = ( ('%Y-%m-%d %H:%M:%S', ''), ('%Y-%m-%d %H:%M', 'seconds=59'), ('%Y-%m-%d %H', 'minutes=59, seconds=59'), ('%Y-%m-%d', 'hours=23, minutes=59, seconds=59'), ('%Y-%m', 'days=31, hours=23, minutes=59, seconds=59'), ) OFFSET_VALID_KEYS = ('days', 'minutes', 'seconds') class Request: output_bytes = '-' def __init__(self, start, method, url): self.method = method self.url = url self.start = start self.state = 'input' def I(self, input_time, input_bytes): # noqa: E743 E741 self.input_time = input_time self.input_bytes = input_bytes self.state = 'wait' def C(self, start_app_time): self.start_app_time = start_app_time self.state = 'app' def A(self, app_time, response, output_bytes): self.app_time = app_time self.response = response self.output_bytes = output_bytes self.state = 'output' def E(self, end): self.end = end @property def app_seconds(self): return seconds_difference(self.app_time, self.start_app_time) @property def total_seconds(self): return seconds_difference(self.end, self.start) class Times: tid = 1 def __init__(self): self.times = [] self.hangs = 0 Times.tid += 1 self.tid = Times.tid # generate a unique id def finished(self, request): self.times.append(request.app_seconds) def hung(self): self.hangs += 1 def impact(self): times = self.times if not times: self.median = self.mean = self.impact = 0 return 0 self.times.sort() n = len(times) if n % 2: m = times[(n+1)//2-1] else: m = .5 * (times[n//2]+times[n//2-1]) self.median = m self.mean = float(sum(times))/n self.impact = self.mean * (n+self.hangs) return self.impact def __str__(self): times = self.times if not times: return " 0 %5d" % ( self.hangs) n = len(times) m = self.median return "%9.1f %5d %6.2f %6.2f %6.2f %6.2f %5d" % ( self.impact, n, times[0], m, self.mean, times[-1], self.hangs) def html(self): times = self.times if not times: impact = '<a name="u%s">&nbsp;</a>' % self.tid print(td( impact, 0, '&nbsp;', '&nbsp;', '&nbsp;', '&nbsp;', self.hangs)) else: impact = '<a name="u{}">{:.1f}</a>'.format(self.tid, self.impact) n = len(times) m = self.median print(td(impact, n, times[0], m, self.mean, times[-1], self.hangs)) def __add__(self, other): result = Times() result.times = self.times + other.times result.hangs = self.hangs + other.hangs return result def seconds_difference(dt1, dt2): delta = dt1 - dt2 return delta.seconds + delta.microseconds * 1e-6 def parse_line(line): parts = line.split(' ', 4) code, rid, rdate, rtime = parts[:4] if len(parts) > 4: msg = parts[4] else: msg = '' return (code, rid, rdate + ' ' + rtime, msg) def parse_datetime(s): # XXX this chokes on tracelogs with the 'T' time separator. date, t = s.split(' ') try: h_m_s, ms = t.split('.') except ValueError: h_m_s = t.strip() ms = '0' args = [int(arg) for arg in (date.split('-') + h_m_s.split(':') + [ms])] return datetime.datetime(*args) def parse_offset(offset): offset = offset.replace(' ', '') if offset: items = [] for item in offset.split(','): key, val = item.split('=') items.append((key, int(val))) kwargs = dict(items) else: kwargs = dict() kwargs['microseconds'] = 999999 return datetime.timedelta(**kwargs) def parse_date_interval(interval_string): # Get offset offset = '' negative_offset = False if ' +' in interval_string: date_string, offset = interval_string.split(' +') elif ' -' in interval_string: date_string, offset = interval_string.split(' -') negative_offset = True else: date_string = interval_string # Get datetime date = None date_string = date_string.strip() for date_format, date_format_offset in DATE_FORMATS: try: date = datetime.datetime.strptime(date_string, date_format) except (ValueError, OverflowError): pass else: break if date is None: raise TypeError("Unknown date format of '%s'." % interval_string) # Return datetime interval tuple offset = offset or date_format_offset offset = parse_offset(offset) if negative_offset: return (date - offset, date) else: return (date, date + offset) def time_from_line(line): x, x, strtime, x = parse_line(line) return parse_datetime(strtime) def iterlog(file, date_interval=None): size = 0 if file == '-': yield from _iterlog(sys.stdin, size, date_interval) else: size = os.path.getsize(file) with open(file) as f: yield from _iterlog(f, size, date_interval) def _iterlog(file, size, date_interval=None): date_from, date_to = date_interval or (None, None) if date_from and size: fseek(file, size, date_from, time_from_line) for line in file: typ, rid, strtime, msg = parse_line(line) dt = parse_datetime(strtime) if date_to and date_to < dt: break elif date_from and date_from > dt: continue else: yield line, dt, typ, rid, strtime, msg def main(args=None): if args is None: args = sys.argv[1:] options, args = parser.parse_args(args) if options.date: date_interval = parse_date_interval(options.date) else: date_interval = None if options.event_log: restarts = find_restarts(options.event_log) else: restarts = [] restarts.append(datetime.datetime.utcnow()+datetime.timedelta(1000)) if options.html: print_app_requests = print_app_requests_html output_minute = output_minute_html output_stats = output_stats_html minutes_header = minutes_header_html minutes_footer = minutes_footer_html print('<html title="trace log statistics"><body>') else: print_app_requests = print_app_requests_text output_minute = output_minute_text output_stats = output_stats_text minutes_header = minutes_header_text minutes_footer = minutes_footer_text if options.summary_only: print_app_requests = output_minute = lambda *a, **kw: None minutes_footer = minutes_header = lambda *a, **kw: None urls = {} [file] = args lmin = ldt = None requests = {} input = apps = output = n = wait = 0 spr = spa = 0.0 restart = restarts.pop(0) minutes_header() remove_prefix = options.remove_prefix dt = None for record, dt, typ, rid, strtime, msg in iterlog(file, date_interval): min = strtime.split('.')[0] min = min[:-3] if dt == restart: continue while dt > restart: print_app_requests(requests, ldt, options.old_requests, options.app_requests, urls, "\nLeft over:") record_hung(urls, requests) requests = {} input = apps = output = n = wait = 0 spr = spa = 0.0 restart = restarts.pop(0) ldt = dt if min != lmin: if lmin is not None: output_minute(lmin, requests, input, wait, apps, output, n, spr, spa) if apps > options.apps: print_app_requests(requests, dt, options.old_requests, options.app_requests, urls, ) lmin = min spr = 0.0 spa = 0.0 n = 0 if typ == 'B': if rid in requests: request = requests[rid] if request.state == 'output': output -= 1 elif request.state == 'app': apps -= 1 else: input -= 1 input += 1 method, url = msg.split(' ', 1) request = Request(dt, method, url.strip()) if remove_prefix and request.url.startswith(remove_prefix): request.url = request.url[len(remove_prefix):] requests[rid] = request times = urls.get(request.url) if times is None: times = urls[request.url] = Times() elif typ == 'I': if rid in requests: input -= 1 wait += 1 requests[rid].I(dt, record[3]) elif typ == 'C': if rid in requests: wait -= 1 apps += 1 requests[rid].C(dt) elif typ == 'A': if rid in requests: apps -= 1 output += 1 try: response_code, bytes_len = msg.split() except ValueError: response_code = '500' bytes_len = len(msg) requests[rid].A(dt, response_code, bytes_len) elif typ == 'E': if rid in requests: output -= 1 request = requests.pop(rid) request.E(dt) spr += request.total_seconds spa += request.app_seconds n += 1 times = urls[request.url] times.finished(request) elif typ in 'SX': print_app_requests(requests, ldt, options.old_requests, options.app_requests, urls, "\nLeft over:") record_hung(urls, requests) requests = {} input = apps = output = n = wait = 0 spr = spa = 0.0 elif typ == 'D': pass # ignore db stats for now else: print('WTF {}'.format(record)) record_hung(urls, requests) if dt: print_app_requests(requests, dt, options.old_requests, options.app_requests, urls, "Left over:") minutes_footer() output_stats(urls, lines=options.summary_lines) if options.html: print('</body></html>') def output_stats_text(urls, lines): print('\nURL statistics:') print(" Impact count min median mean max hangs") print("========= ===== ====== ====== ====== ====== =====") urls = [(times.impact(), url, times) for (url, times) in urls.items() ] urls.sort() urls.reverse() line = 0 for (_, url, times) in urls: if times.impact > 0 or times.hangs: print("{} {}".format(times, url)) line += 1 if line > lines: break def output_stats_html(urls, lines): print('\nURL statistics:') print('<table border="1">') print('<tr><th>Impact</th><th>count</th><th>min</th>') print('<th>median</th><th>mean</th><th>max</th><th>hangs</th></tr>') urls = [(times.impact(), url, times) for (url, times) in urls.items() ] urls.sort() urls.reverse() line = 0 for (_, url, times) in urls: if times.impact > 0 or times.hangs: if line % 2: print('<tr style="background: lightgrey;">') else: print('<tr>') times.html() print(td(url)) print('</tr>') line += 1 if line > lines: break print('</table>') def minutes_header_text(): print("") print(" minute req input wait app output") print("================ ===== ===== ===== ===== ======") def minutes_footer_text(): print("") def minutes_header_html(): print('<table border="2">') print("<tr>") print('<th>Minute</th>') print('<th>Requests</th>') print('<th>Requests inputing</th>') print('<th>Requests waiting</th>') print('<th>Requests executing</th>') print('<th>Requests outputing</th>') print('<th>Requests completed</th>') print('<th>Mean Seconds Per Request Total</th>') print('<th>Mean Seconds Per Request in App</th>') print("</tr>") def minutes_footer_html(): print('</table>') def output_minute_text(lmin, requests, input, wait, apps, output, n, spr, spa): if n: extra = " N=%4d %10.2f %10.2f" % (n, spr/n, spa/n) else: extra = "" print("%s %5d I=%3d W=%3d A=%3d O=%4d%s" % (lmin, len(requests), input, wait, apps, output, extra)) def td(*values): return ''.join( [ "<td>%.3f</td>" % s if isinstance(s, float) else "<td>%s</td>" % s for s in values ] ) output_minute_count = 0 def output_minute_html(lmin, requests, input, wait, apps, output, n, spr, spa): global output_minute_count output_minute_count += 1 if output_minute_count % 2: print('<tr style="background: lightgrey">') else: print('<tr>') apps = '<font size="+2"><strong>%s</strong></font>' % apps print(td(lmin, len(requests), input, wait, apps, output)) if n: print(td(n, "%10.2f" % (spr/n), "%10.2f" % (spa/n))) else: print(td(n, '&nbsp;', '&nbsp;')) print('</tr>') def find_restarts(event_log): result = [] with open(event_log) as f: for line in f: if line.strip().endswith("Zope Ready to handle requests"): result.append(parse_datetime(line.split()[0])) return result def record_hung(urls, requests): for request in requests.values(): times = urls.get(request.url) if times is None: times = urls[request.url] = Times() times.hung() def print_app_requests_text(requests, dt, min_seconds, max_requests, allurls, label=''): requests = [ (seconds_difference(dt, request.start), request) for request in requests.values() if request.state == 'app' ] urls = {} for s, request in requests: urls[request.url] = urls.get(request.url, 0) + 1 requests.sort() requests.reverse() for s, request in requests[:max_requests]: if s < min_seconds: continue if label: print(label) label = '' url = request.url repeat = urls[url] if repeat > 1: print("%s R=%d %s" % (s, repeat, url)) else: print("{} {}".format(s, url)) def print_app_requests_html(requests, dt, min_seconds, max_requests, allurls, label=''): requests = [ ((dt-request.start).seconds, request.url, request) for request in requests.values() if request.state == 'app' ] urls = {} for s, url, request in requests: urls[url] = urls.get(url, 0) + 1 requests.sort() requests.reverse() printed = False for s, url, request in requests[:max_requests]: if s < min_seconds: continue if label: print(label) label = '' if not printed: print('</table>') print('<table border="1">') print('<tr><th>age</th><th>R</th><th>url</th><th>state</th></tr>') printed = True repeat = urls[url] print('<tr>') if repeat <= 1: repeat = '' url = '<a href="#u{}">{}</a>'.format(allurls[url].tid, url) print(td(s, repeat, url, request.state)) print('</tr>') if printed: print('</table>') minutes_header_html() parser = optparse.OptionParser("""%prog [options] trace_log_file Output trace log data showing: - number of active requests, - number of input requests (requests gathering input), - number of application requests, - number of output requests, - number of requests completed in the minute shown, - mean seconds per request and - mean application seconds per request. Note that we don't seem to be logging when a connection to the client is broken, so the number of active requests, and especially the number of outputing requests tends to grow over time. This is spurious. Also, note that, unfortunately, application requests include requests that are running in application threads and requests waiting to get an application thread. When application threads get above the app request threshold, then we show the requests that have been waiting the longest. """) parser.add_option("--app-request-threshold", "-a", dest='apps', type="int", default=10, help="""\ Number of pending application requests at which detailed request information if printed. """) parser.add_option("--app-requests", "-r", dest='app_requests', type="int", default=10, help="""\ How many requests to show when the maximum number of pending apps is exceeded. """) parser.add_option("--old-requests", "-o", dest='old_requests', type="int", default=10, help="""\ Number of seconds beyond which a request is considered old. """) parser.add_option("--event-log", "-e", dest='event_log', help="""\ The name of an event log that goes with the trace log. This is used to determine when the server is restarted, so that the running trace data structures can be reinitialized. """) parser.add_option("--html", dest='html', action='store_true', help="""\ Generate HTML output. """) parser.add_option("--remove-prefix", dest='remove_prefix', help="""\ A prefix to be removed from URLS. """) parser.add_option("--summary-only", dest='summary_only', action='store_true', help="""\ Only output summary lines. """) parser.add_option("--summary-lines", dest='summary_lines', type="int", default=999999999, help="""The number of summary lines to show""") parser.add_option("--date", "-d", dest='date', default=None, metavar='DATESPEC', help="""\ Only consider events in the specified date range. Syntax: "YYYY-MM[-DD [HH[:MM[:SS]]]][ +/-[days=N][, hours=N][, minutes=N][, seconds=N]]". E.g. -d 2015-04 would select the entire month, -d 2015-04-20 would select the entire day, -d "2015-04-20 14" would select one hour, -d "2015-04-20 14:00 +hours=2" would select two hours, and -d "2015-04-20 16:00 -hours=2" would select the same two hours. """) if __name__ == '__main__': main()
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/src/zc/zservertracelog/tracereport.py
tracereport.py
=================== Analyzing Tracelogs =================== `tracereport.py` provides a basic means to analyze a tracelog and generate a report. >>> import os >>> os.environ['COLUMNS'] = '70' >>> import zc.zservertracelog.tracereport >>> import sys >>> sys.argv[0] = 'tracereport' The '--help' option displays the following usage information: >>> try: ... zc.zservertracelog.tracereport.main(['--help']) ... except SystemExit: ... pass ... # doctest: +REPORT_NDIFF, +NORMALIZE_WHITESPACE Usage: tracereport [options] trace_log_file <BLANKLINE> Output trace log data showing: <BLANKLINE> - number of active requests, - number of input requests (requests gathering input), - number of application requests, - number of output requests, - number of requests completed in the minute shown, - mean seconds per request and - mean application seconds per request. <BLANKLINE> Note that we don't seem to be logging when a connection to the client is broken, so the number of active requests, and especially the number of outputing requests tends to grow over time. This is spurious. <BLANKLINE> Also, note that, unfortunately, application requests include requests that are running in application threads and requests waiting to get an application thread. <BLANKLINE> When application threads get above the app request threshold, then we show the requests that have been waiting the longest. <BLANKLINE> <BLANKLINE> <BLANKLINE> Options: -h, --help show this help message and exit -a APPS, --app-request-threshold=APPS Number of pending application requests at which detailed request information if printed. -r APP_REQUESTS, --app-requests=APP_REQUESTS How many requests to show when the maximum number of pending apps is exceeded. -o OLD_REQUESTS, --old-requests=OLD_REQUESTS Number of seconds beyond which a request is considered old. -e EVENT_LOG, --event-log=EVENT_LOG The name of an event log that goes with the trace log. This is used to determine when the server is restarted, so that the running trace data structures can be reinitialized. --html Generate HTML output. --remove-prefix=REMOVE_PREFIX A prefix to be removed from URLS. --summary-only Only output summary lines. --summary-lines=SUMMARY_LINES The number of summary lines to show -d DATESPEC, --date=DATESPEC Only consider events in the specified date range. Syntax: "YYYY-MM[-DD [HH[:MM[:SS]]]][ +/-[days=N][, hours=N][, minutes=N][, seconds=N]]". E.g. -d 2015-04 would select the entire month, -d 2015-04-20 would select the entire day, -d "2015-04-20 14" would select one hour, -d "2015-04-20 14:00 +hours=2" would select two hours, and -d "2015-04-20 16:00 -hours=2" would select the same two hours. Here, we display the summarized report for a sample trace log. >>> zc.zservertracelog.tracereport.main( ... ['--summary-only', '--app-request-threshold', '0', sample_log]) <BLANKLINE> URL statistics: Impact count min median mean max hangs ========= ===== ====== ====== ====== ====== ===== 62.4 1 62.42 62.42 62.42 62.42 0 /constellations/andromeda.html 61.5 1 61.50 61.50 61.50 61.50 0 /stars/alpha-centauri.html 60.3 2 0.13 30.13 30.13 60.13 0 /favicon.png 60.0 2 0.00 30.00 30.00 60.00 0 /space-travel/plans/supplies.txt 9.7 1 9.69 9.69 9.69 9.69 0 /planets/saturn.html 8.3 1 8.30 8.30 8.30 8.30 0 /moons/io.html 7.3 1 7.34 7.34 7.34 7.34 0 /planets/jupiter.html 0.9 1 0.88 0.88 0.88 0.88 0 /stories/aliens-posing-as-humans.html 0.6 1 0.64 0.64 0.64 0.64 0 /columns/t-jansen 0.4 2 0.18 0.19 0.19 0.19 0 /faqs/how-to-recognize-lazer-fire.html 0.4 1 0.35 0.35 0.35 0.35 0 /faqs/how-to-charge-lazers.html 0.3 1 0.32 0.32 0.32 0.32 0 /space-travel/ships/tardis.html 0.3 1 0.25 0.25 0.25 0.25 0 /approve-photo 0.2 1 0.18 0.18 0.18 0.18 0 /ufo-sightings/report 0.1 1 0.14 0.14 0.14 0.14 0 /space-travel/ships/soyuz.html 0.0 3 0.02 0.02 0.02 0.02 0 /space-travelers/famous/kirk.jpg 0.0 1 0.02 0.02 0.02 0.02 0 /space-travelers/famous/spock.jpg 0.0 1 0.02 0.02 0.02 0.02 0 /login 0.0 3 0.00 0.00 0.00 0.00 0 /space-travel/plans/signals.html 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/launchpad.html 0.0 1 0.00 0.00 0.00 0.00 1 /space-travel/plans/orbit.html 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-logs.txt 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/moon-base.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/moon-buggy.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-diary.txt 0.0 1 0.00 0.00 0.00 0.00 0 /js/photo.js 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/visor.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/lunar-cycles.html 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/cryostasis.txt 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-suit.jpg 0 1 /submit-photo This can also be displayed as HTML. >>> zc.zservertracelog.tracereport.main( ... ['--summary-only', '--html', '--app-request-threshold', '0', sample_log]) <html title="trace log statistics"><body> <BLANKLINE> URL statistics: <table border="1"> <tr><th>Impact</th><th>count</th><th>min</th> <th>median</th><th>mean</th><th>max</th><th>hangs</th></tr> <tr> <td><a name="u37">62.4</a></td><td>1</td><td>62.418</td><td>62.418</td><td>62.418</td><td>62.418</td><td>0</td> <td>/constellations/andromeda.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u53">61.5</a></td><td>1</td><td>61.502</td><td>61.502</td><td>61.502</td><td>61.502</td><td>0</td> <td>/stars/alpha-centauri.html</td> </tr> <tr> <td><a name="u44">60.3</a></td><td>2</td><td>0.133</td><td>30.134</td><td>30.134</td><td>60.134</td><td>0</td> <td>/favicon.png</td> </tr> <tr style="background: lightgrey;"> <td><a name="u34">60.0</a></td><td>2</td><td>0.003</td><td>30.003</td><td>30.003</td><td>60.003</td><td>0</td> <td>/space-travel/plans/supplies.txt</td> </tr> <tr> <td><a name="u48">9.7</a></td><td>1</td><td>9.694</td><td>9.694</td><td>9.694</td><td>9.694</td><td>0</td> <td>/planets/saturn.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u51">8.3</a></td><td>1</td><td>8.300</td><td>8.300</td><td>8.300</td><td>8.300</td><td>0</td> <td>/moons/io.html</td> </tr> <tr> <td><a name="u55">7.3</a></td><td>1</td><td>7.340</td><td>7.340</td><td>7.340</td><td>7.340</td><td>0</td> <td>/planets/jupiter.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u60">0.9</a></td><td>1</td><td>0.880</td><td>0.880</td><td>0.880</td><td>0.880</td><td>0</td> <td>/stories/aliens-posing-as-humans.html</td> </tr> <tr> <td><a name="u33">0.6</a></td><td>1</td><td>0.638</td><td>0.638</td><td>0.638</td><td>0.638</td><td>0</td> <td>/columns/t-jansen</td> </tr> <tr style="background: lightgrey;"> <td><a name="u41">0.4</a></td><td>2</td><td>0.184</td><td>0.187</td><td>0.187</td><td>0.190</td><td>0</td> <td>/faqs/how-to-recognize-lazer-fire.html</td> </tr> <tr> <td><a name="u54">0.4</a></td><td>1</td><td>0.351</td><td>0.351</td><td>0.351</td><td>0.351</td><td>0</td> <td>/faqs/how-to-charge-lazers.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u50">0.3</a></td><td>1</td><td>0.320</td><td>0.320</td><td>0.320</td><td>0.320</td><td>0</td> <td>/space-travel/ships/tardis.html</td> </tr> <tr> <td><a name="u39">0.3</a></td><td>1</td><td>0.253</td><td>0.253</td><td>0.253</td><td>0.253</td><td>0</td> <td>/approve-photo</td> </tr> <tr style="background: lightgrey;"> <td><a name="u57">0.2</a></td><td>1</td><td>0.182</td><td>0.182</td><td>0.182</td><td>0.182</td><td>0</td> <td>/ufo-sightings/report</td> </tr> <tr> <td><a name="u61">0.1</a></td><td>1</td><td>0.138</td><td>0.138</td><td>0.138</td><td>0.138</td><td>0</td> <td>/space-travel/ships/soyuz.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u45">0.0</a></td><td>3</td><td>0.015</td><td>0.016</td><td>0.016</td><td>0.018</td><td>0</td> <td>/space-travelers/famous/kirk.jpg</td> </tr> <tr> <td><a name="u59">0.0</a></td><td>1</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0</td> <td>/space-travelers/famous/spock.jpg</td> </tr> <tr style="background: lightgrey;"> <td><a name="u43">0.0</a></td><td>1</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0</td> <td>/login</td> </tr> <tr> <td><a name="u56">0.0</a></td><td>3</td><td>0.003</td><td>0.004</td><td>0.003</td><td>0.004</td><td>0</td> <td>/space-travel/plans/signals.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u36">0.0</a></td><td>2</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/launchpad.html</td> </tr> <tr> <td><a name="u62">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>1</td> <td>/space-travel/plans/orbit.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u38">0.0</a></td><td>2</td><td>0.003</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/space-logs.txt</td> </tr> <tr> <td><a name="u35">0.0</a></td><td>2</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0.004</td><td>0</td> <td>/space-travel/plans/moon-base.jpg</td> </tr> <tr style="background: lightgrey;"> <td><a name="u46">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/moon-buggy.jpg</td> </tr> <tr> <td><a name="u49">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/space-diary.txt</td> </tr> <tr style="background: lightgrey;"> <td><a name="u58">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/js/photo.js</td> </tr> <tr> <td><a name="u63">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/visor.jpg</td> </tr> <tr style="background: lightgrey;"> <td><a name="u52">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/lunar-cycles.html</td> </tr> <tr> <td><a name="u40">0.0</a></td><td>1</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0</td> <td>/space-travel/plans/cryostasis.txt</td> </tr> <tr style="background: lightgrey;"> <td><a name="u47">0.0</a></td><td>1</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0</td> <td>/space-travel/plans/space-suit.jpg</td> </tr> <tr> <td><a name="u42">&nbsp;</a></td><td>0</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>1</td> <td>/submit-photo</td> </tr> </table> </body></html> The full report shows the request activity per minute. >>> zc.zservertracelog.tracereport.main( ... ['--app-request-threshold', '0', sample_log]) <BLANKLINE> minute req input wait app output ================ ===== ===== ===== ===== ====== 2009-07-30 15:47 1 I= 0 W= 0 A= 1 O= 0 N= 1 0.64 0.64 60.004106 /space-travel/plans/supplies.txt 2009-07-30 15:48 2 I= 0 W= 1 A= 1 O= 0 N= 3 20.00 20.00 60.791825 /constellations/andromeda.html 2009-07-30 15:49 0 I= 0 W= 0 A= 0 O= 0 N= 4 31.69 15.67 2009-07-30 15:50 2 I= 0 W= 0 A= 2 O= 0 N= 2 0.34 0.10 60.62335 /submit-photo 60.209388 /favicon.png 2009-07-30 15:51 3 I= 0 W= 1 A= 1 O= 1 N= 5 12.08 12.07 121.301024 /submit-photo 2009-07-30 15:52 3 I= 0 W= 1 A= 2 O= 0 N= 8 20.45 2.29 200.494494 /submit-photo 68.09801 /stars/alpha-centauri.html 2009-07-30 15:53 3 I= 0 W= 2 A= 1 O= 0 N= 11 14.39 6.39 270.622261 /submit-photo Left over: 271.214443 /submit-photo <BLANKLINE> <BLANKLINE> URL statistics: Impact count min median mean max hangs ========= ===== ====== ====== ====== ====== ===== 62.4 1 62.42 62.42 62.42 62.42 0 /constellations/andromeda.html 61.5 1 61.50 61.50 61.50 61.50 0 /stars/alpha-centauri.html 60.3 2 0.13 30.13 30.13 60.13 0 /favicon.png 60.0 2 0.00 30.00 30.00 60.00 0 /space-travel/plans/supplies.txt 9.7 1 9.69 9.69 9.69 9.69 0 /planets/saturn.html 8.3 1 8.30 8.30 8.30 8.30 0 /moons/io.html 7.3 1 7.34 7.34 7.34 7.34 0 /planets/jupiter.html 0.9 1 0.88 0.88 0.88 0.88 0 /stories/aliens-posing-as-humans.html 0.6 1 0.64 0.64 0.64 0.64 0 /columns/t-jansen 0.4 2 0.18 0.19 0.19 0.19 0 /faqs/how-to-recognize-lazer-fire.html 0.4 1 0.35 0.35 0.35 0.35 0 /faqs/how-to-charge-lazers.html 0.3 1 0.32 0.32 0.32 0.32 0 /space-travel/ships/tardis.html 0.3 1 0.25 0.25 0.25 0.25 0 /approve-photo 0.2 1 0.18 0.18 0.18 0.18 0 /ufo-sightings/report 0.1 1 0.14 0.14 0.14 0.14 0 /space-travel/ships/soyuz.html 0.0 3 0.02 0.02 0.02 0.02 0 /space-travelers/famous/kirk.jpg 0.0 1 0.02 0.02 0.02 0.02 0 /space-travelers/famous/spock.jpg 0.0 1 0.02 0.02 0.02 0.02 0 /login 0.0 3 0.00 0.00 0.00 0.00 0 /space-travel/plans/signals.html 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/launchpad.html 0.0 1 0.00 0.00 0.00 0.00 1 /space-travel/plans/orbit.html 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-logs.txt 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/moon-base.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/moon-buggy.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-diary.txt 0.0 1 0.00 0.00 0.00 0.00 0 /js/photo.js 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/visor.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/lunar-cycles.html 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/cryostasis.txt 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-suit.jpg 0 1 /submit-photo Again, this report is also available in HTML form. >>> zc.zservertracelog.tracereport.main( ... ['--html', '--app-request-threshold', '0', sample_log]) <html title="trace log statistics"><body> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> <tr style="background: lightgrey"> <td>2009-07-30 15:47</td><td>1</td><td>0</td><td>0</td><td><font size="+2"><strong>1</strong></font></td><td>0</td> <td>1</td><td> 0.64</td><td> 0.64</td> </tr> </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>60</td><td></td><td><a href="#u96">/space-travel/plans/supplies.txt</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> <tr> <td>2009-07-30 15:48</td><td>2</td><td>0</td><td>1</td><td><font size="+2"><strong>1</strong></font></td><td>0</td> <td>3</td><td> 20.00</td><td> 20.00</td> </tr> </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>60</td><td></td><td><a href="#u99">/constellations/andromeda.html</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> <tr style="background: lightgrey"> <td>2009-07-30 15:49</td><td>0</td><td>0</td><td>0</td><td><font size="+2"><strong>0</strong></font></td><td>0</td> <td>4</td><td> 31.69</td><td> 15.67</td> </tr> <tr> <td>2009-07-30 15:50</td><td>2</td><td>0</td><td>0</td><td><font size="+2"><strong>2</strong></font></td><td>0</td> <td>2</td><td> 0.34</td><td> 0.10</td> </tr> </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>60</td><td></td><td><a href="#u104">/submit-photo</a></td><td>app</td> </tr> <tr> <td>60</td><td></td><td><a href="#u106">/favicon.png</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> <tr style="background: lightgrey"> <td>2009-07-30 15:51</td><td>3</td><td>0</td><td>1</td><td><font size="+2"><strong>1</strong></font></td><td>1</td> <td>5</td><td> 12.08</td><td> 12.07</td> </tr> </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>121</td><td></td><td><a href="#u104">/submit-photo</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> <tr> <td>2009-07-30 15:52</td><td>3</td><td>0</td><td>1</td><td><font size="+2"><strong>2</strong></font></td><td>0</td> <td>8</td><td> 20.45</td><td> 2.29</td> </tr> </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>200</td><td></td><td><a href="#u104">/submit-photo</a></td><td>app</td> </tr> <tr> <td>68</td><td></td><td><a href="#u115">/stars/alpha-centauri.html</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> <tr style="background: lightgrey"> <td>2009-07-30 15:53</td><td>3</td><td>0</td><td>2</td><td><font size="+2"><strong>1</strong></font></td><td>0</td> <td>11</td><td> 14.39</td><td> 6.39</td> </tr> </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>270</td><td></td><td><a href="#u104">/submit-photo</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> Left over: </table> <table border="1"> <tr><th>age</th><th>R</th><th>url</th><th>state</th></tr> <tr> <td>271</td><td></td><td><a href="#u104">/submit-photo</a></td><td>app</td> </tr> </table> <table border="2"> <tr> <th>Minute</th> <th>Requests</th> <th>Requests inputing</th> <th>Requests waiting</th> <th>Requests executing</th> <th>Requests outputing</th> <th>Requests completed</th> <th>Mean Seconds Per Request Total</th> <th>Mean Seconds Per Request in App</th> </tr> </table> <BLANKLINE> URL statistics: <table border="1"> <tr><th>Impact</th><th>count</th><th>min</th> <th>median</th><th>mean</th><th>max</th><th>hangs</th></tr> <tr> <td><a name="u99">62.4</a></td><td>1</td><td>62.418</td><td>62.418</td><td>62.418</td><td>62.418</td><td>0</td> <td>/constellations/andromeda.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u115">61.5</a></td><td>1</td><td>61.502</td><td>61.502</td><td>61.502</td><td>61.502</td><td>0</td> <td>/stars/alpha-centauri.html</td> </tr> <tr> <td><a name="u106">60.3</a></td><td>2</td><td>0.133</td><td>30.134</td><td>30.134</td><td>60.134</td><td>0</td> <td>/favicon.png</td> </tr> <tr style="background: lightgrey;"> <td><a name="u96">60.0</a></td><td>2</td><td>0.003</td><td>30.003</td><td>30.003</td><td>60.003</td><td>0</td> <td>/space-travel/plans/supplies.txt</td> </tr> <tr> <td><a name="u110">9.7</a></td><td>1</td><td>9.694</td><td>9.694</td><td>9.694</td><td>9.694</td><td>0</td> <td>/planets/saturn.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u113">8.3</a></td><td>1</td><td>8.300</td><td>8.300</td><td>8.300</td><td>8.300</td><td>0</td> <td>/moons/io.html</td> </tr> <tr> <td><a name="u117">7.3</a></td><td>1</td><td>7.340</td><td>7.340</td><td>7.340</td><td>7.340</td><td>0</td> <td>/planets/jupiter.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u122">0.9</a></td><td>1</td><td>0.880</td><td>0.880</td><td>0.880</td><td>0.880</td><td>0</td> <td>/stories/aliens-posing-as-humans.html</td> </tr> <tr> <td><a name="u95">0.6</a></td><td>1</td><td>0.638</td><td>0.638</td><td>0.638</td><td>0.638</td><td>0</td> <td>/columns/t-jansen</td> </tr> <tr style="background: lightgrey;"> <td><a name="u103">0.4</a></td><td>2</td><td>0.184</td><td>0.187</td><td>0.187</td><td>0.190</td><td>0</td> <td>/faqs/how-to-recognize-lazer-fire.html</td> </tr> <tr> <td><a name="u116">0.4</a></td><td>1</td><td>0.351</td><td>0.351</td><td>0.351</td><td>0.351</td><td>0</td> <td>/faqs/how-to-charge-lazers.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u112">0.3</a></td><td>1</td><td>0.320</td><td>0.320</td><td>0.320</td><td>0.320</td><td>0</td> <td>/space-travel/ships/tardis.html</td> </tr> <tr> <td><a name="u101">0.3</a></td><td>1</td><td>0.253</td><td>0.253</td><td>0.253</td><td>0.253</td><td>0</td> <td>/approve-photo</td> </tr> <tr style="background: lightgrey;"> <td><a name="u119">0.2</a></td><td>1</td><td>0.182</td><td>0.182</td><td>0.182</td><td>0.182</td><td>0</td> <td>/ufo-sightings/report</td> </tr> <tr> <td><a name="u123">0.1</a></td><td>1</td><td>0.138</td><td>0.138</td><td>0.138</td><td>0.138</td><td>0</td> <td>/space-travel/ships/soyuz.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u107">0.0</a></td><td>3</td><td>0.015</td><td>0.016</td><td>0.016</td><td>0.018</td><td>0</td> <td>/space-travelers/famous/kirk.jpg</td> </tr> <tr> <td><a name="u121">0.0</a></td><td>1</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0</td> <td>/space-travelers/famous/spock.jpg</td> </tr> <tr style="background: lightgrey;"> <td><a name="u105">0.0</a></td><td>1</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0.016</td><td>0</td> <td>/login</td> </tr> <tr> <td><a name="u118">0.0</a></td><td>3</td><td>0.003</td><td>0.004</td><td>0.003</td><td>0.004</td><td>0</td> <td>/space-travel/plans/signals.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u98">0.0</a></td><td>2</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/launchpad.html</td> </tr> <tr> <td><a name="u124">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>1</td> <td>/space-travel/plans/orbit.html</td> </tr> <tr style="background: lightgrey;"> <td><a name="u100">0.0</a></td><td>2</td><td>0.003</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/space-logs.txt</td> </tr> <tr> <td><a name="u97">0.0</a></td><td>2</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0.004</td><td>0</td> <td>/space-travel/plans/moon-base.jpg</td> </tr> <tr style="background: lightgrey;"> <td><a name="u108">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/moon-buggy.jpg</td> </tr> <tr> <td><a name="u111">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/space-diary.txt</td> </tr> <tr style="background: lightgrey;"> <td><a name="u120">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/js/photo.js</td> </tr> <tr> <td><a name="u125">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/visor.jpg</td> </tr> <tr style="background: lightgrey;"> <td><a name="u114">0.0</a></td><td>1</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0.004</td><td>0</td> <td>/space-travel/plans/lunar-cycles.html</td> </tr> <tr> <td><a name="u102">0.0</a></td><td>1</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0</td> <td>/space-travel/plans/cryostasis.txt</td> </tr> <tr style="background: lightgrey;"> <td><a name="u109">0.0</a></td><td>1</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0.003</td><td>0</td> <td>/space-travel/plans/space-suit.jpg</td> </tr> <tr> <td><a name="u104">&nbsp;</a></td><td>0</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>1</td> <td>/submit-photo</td> </tr> </table> </body></html> Report by given time interval. >>> zc.zservertracelog.tracereport.main( ... ['--date', '2009-07-30 15:48 +minutes=5', sample_log]) <BLANKLINE> minute req input wait app output ================ ===== ===== ===== ===== ====== 2009-07-30 15:48 2 I= 0 W= 1 A= 1 O= 0 N= 2 0.00 0.00 2009-07-30 15:49 0 I= 0 W= 0 A= 0 O= 0 N= 4 31.69 15.67 2009-07-30 15:50 2 I= 0 W= 0 A= 2 O= 0 N= 2 0.34 0.10 2009-07-30 15:51 3 I= 0 W= 1 A= 1 O= 1 N= 5 12.08 12.07 Left over: 140.094385 /submit-photo <BLANKLINE> <BLANKLINE> URL statistics: Impact count min median mean max hangs ========= ===== ====== ====== ====== ====== ===== 62.4 1 62.42 62.42 62.42 62.42 0 /constellations/andromeda.html 60.1 1 60.13 60.13 60.13 60.13 0 /favicon.png 9.7 1 9.69 9.69 9.69 9.69 0 /planets/saturn.html 8.3 1 8.30 8.30 8.30 8.30 0 /moons/io.html 0.4 2 0.18 0.19 0.19 0.19 0 /faqs/how-to-recognize-lazer-fire.html 0.3 1 0.32 0.32 0.32 0.32 0 /space-travel/ships/tardis.html 0.3 1 0.25 0.25 0.25 0.25 0 /approve-photo 0.0 1 0.02 0.02 0.02 0.02 0 /space-travelers/famous/kirk.jpg 0.0 1 0.02 0.02 0.02 0.02 0 /login 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/launchpad.html 0.0 2 0.00 0.00 0.00 0.00 0 /space-travel/plans/moon-base.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/moon-buggy.jpg 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-logs.txt 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-diary.txt 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/lunar-cycles.html 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/supplies.txt 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/cryostasis.txt 0.0 1 0.00 0.00 0.00 0.00 0 /space-travel/plans/space-suit.jpg 0 1 /submit-photo 0 1 /stars/alpha-centauri.html 0 1 /faqs/how-to-charge-lazers.html
zc.zservertracelog
/zc.zservertracelog-3.0.tar.gz/zc.zservertracelog-3.0/src/zc/zservertracelog/tracereport.rst
tracereport.rst
=== zca === ZCA whitening in Python with a Scikit-Learn like interface. Usage ----- .. code:: python from zca import ZCA import numpy as np X = np.random.random((10000, 15)) # data array trf = ZCA().fit(X) X_whitened = trf.transform(X) X_reconstructed = trf.inverse_transform(X_whitened) assert(np.allclose(X, X_reconstructed)) # True Installation ------------ .. code:: bash pip install -U zca Licence ------- GPLv3 Authors ------- `zca` was written by `Maarten Versteegh <[email protected]>`_.
zca
/zca-0.1.1.tar.gz/zca-0.1.1/README.rst
README.rst
zca_snippets ======================================== * zca-list * zca-snippets zca-list .. code:: shell $ zca-list pyramid.interfaces pyramid.interfaces:ITranslationDirectories pyramid.interfaces:INewRequest pyramid.interfaces:IRootFactory pyramid.interfaces:IDefaultRootFactory pyramid.interfaces:IViewMapperFactory pyramid.interfaces:IBeforeRender ## ..snip pyramid.interfaces:IExceptionViewClassifier pyramid.interfaces:ILocaleNegotiator pyramid.interfaces:IMultiDict pyramid.interfaces:IAuthenticationPolicy zca-snippets .. code:: shell $ zca-snippets pyramid.interfaces:IAuthenticationPolicy from zope.interface import implementer from pyramid.interfaces import IAuthenticationPolicy ## see: pyramid.interfaces:IAuthenticationPolicy @implementer(IAuthenticationPolicy) class AuthenticationPolicy(object): def remember(self, request, principal, **kw): pass def effective_principals(self, request): pass def forget(self, request): pass def authenticated_userid(self, request): pass def unauthenticated_userid(self, request): pass .. code:: shell $ zca-snippets -q pyramid.interfaces:IAuthorizationPolicy ## see: pyramid.interfaces:IAuthorizationPolicy @implementer(IAuthorizationPolicy) class AuthorizationPolicy(object): def principals_allowed_by_permission(self, context, permission): pass def permits(self, context, principals, permission): pass
zca_snippets
/zca_snippets-0.0.2.tar.gz/zca_snippets-0.0.2/README.rst
README.rst
[![status workflow test](https://github.com/guangrei/PyZcache/actions/workflows/python-app.yml/badge.svg)](https://github.com/guangrei/PyZcache/actions) [![status workflow build](https://github.com/guangrei/PyZcache/actions/workflows/release_to_pypi.yml/badge.svg)](https://github.com/guangrei/PyZcache/actions) [![Downloads](https://static.pepy.tech/badge/zcache)](https://pepy.tech/project/zcache) [![Downloads](https://static.pepy.tech/badge/zcache/month)](https://pepy.tech/project/zcache) [![Downloads](https://static.pepy.tech/badge/zcache/week)](https://pepy.tech/project/zcache) PyZCache is dependency free python key value cache based file storage and json serialize. extra features: - limit able stack cache - option to add ttl (time to life) in cache content - smart request ## Installation ``` pip install zcache ``` # example basic example: ```python from zcache import Cache import time c = Cache(path="/tmp") print("set foo=bar: ", c.set("foo", "bar")) print("c size:", c.size()) print("c has foo: ", c.has("foo")) print("c get foo: ", c.get("foo")) print("c delete foo: ", c.delete("foo")) print("c has foo: ", c.has("foo")) print("c has spam:", c.has("spam")) print("c set spam=eggs, ttl=3: ", c.set("spam", "eggs", ttl=3)) # cache with ttl print("c has spam:", c.has("spam")) print("sleep 3") time.sleep(3) print("c has spam:", c.has("spam")) print("c size:", c.size()) ``` example with limited stack: ```python from zcache import Cache d = Cache(path="/tmp", limit=2) d.reset() # reset cache stack to 0 print(d.set("one", 1)) # True print(d.set("two", 2)) # True print(d.set("three", 3)) # False out of stack limit d.delete("one") # delete one item from stack print(d.set("three", 3)) # True ``` # SmartRequest `SmartRequest` is Simple HTTP Client with smart caching system provide by `zcache`. example usage of `SmartRequest(url, cache_path, cache_time, offline_ttl)`: ```python from zcache import SmartRequest req = SmartRequest("https://www.example.com", cache_path="/tmp/request1.cache") print(req.is_loaded_from_cache) # check is response loaded from cache response_headers = req.response.get('headers') response_body = req.response.get('body') ``` to make advance request you can create costum url object with other library, for example: ```python from zcache import SmartRequest import requests class MyRequest: url = "https://www.example.com" def get(): """ this method called by SmartRequest to retrieve content. you can put request logic get, post etc and return tuple(headers=dict, body=str) """ ret = requests.get(MyRequest.url) return dict(ret.headers), ret.text req = SmartRequest(MyRequest, cache_path="/tmp/request2.cache") ``` note: caching for request media/binary content is possible with `base64` encode. ## License MIT
zcache
/zcache-1.0.1.tar.gz/zcache-1.0.1/README.md
README.md
# zcalc [![Build Status](https://app.travis-ci.com/blackchip-org/zcalc.svg?branch=main)](https://app.travis-ci.com/blackchip-org/zcalc) A fun RPN calculator. If you find it fun too, let me know. This is a constant work in progress. To install and run from PyPI: ```bash python3 -m pip install --upgrade pip pip3 install zcalc zcalc ``` ## Goals - Have fun! - Easy to type. Avoid the shift key in the common case. Prefer the name of `a` for addition over `+` - Use fixed point arithmetic when possible. Prefer `3.3` for `1.1 + 2.2` over `3.3000000000000003` - Auto-completion - Operations should have descriptive names and easily found by auto complete. - Commonly used operations should have easy-to-type aliases. Example: `scientific-notation` and `sn`. - Documentation should also be test cases. ## Usage When running `zcalc` a prompt is presented. When a line is entered at the prompt, it first checked to see if it is the name of an operation. If so, that operation is performed. Otherwise, the line is placed on the stack. An example of adding two numbers: | Input | Stack |------------------|-------------| | `1` | `1` | `2` | `1 ; 2` | `a` | `3` The first line, `1`, does not match an operation so its value is placed on the stack. The next line is a `2` and is also placed on the stack. When `a` is entered, that matches the addition operation. The first two items are popped from the stack, the result is added, and the result is placed back on the stack. When examples are presented in this input/stack table format, each row shows the state of the *stack* after *input* is entered at the prompt. Stack items are separated by semicolons and the top element on the stack is at the right. Operations may have name aliases. The addition operation has a standard long form (`add`), a traditional operator form (`+`) and a short form that is easy to type without the use of the shift key (`a`). The basic math operations are as follows: | Operation | Description |------------------|-----------------| | `add`, `+`, `a` | addition | `sub`, `-`, `s` | subtraction | `mul`, `*`, `m` | multiplication | `div`, `/`, `d` | division More basic math operations can be found in the [math](doc/stdlib/math.md) module documentation. ### Quoting, Multi-lines, and Whitespace Any type of value can be pushed to the stack as long as it isn't the name of an operation. To push the name of an operation to the stack instead of evaluating it, start the line with a single quote (`'`). In the following example, the `len` operation is used to return the length of text: | Input | Stack |----------------------|-------------| | `apples and bananas` | `apples and bananas` | `len` | `18` | `'len` | `18 ; len` | `len` | `18 ; 3` Multiple lines can be submitted on the same line by separating each line with a semicolon (`;`): | Input | Stack |----------------------|-------------| | `'len; len` | `3` Whitespace is significant. Placing a space between the string and semicolon changes the result: | Input | Stack |----------------------|-------------| | `'len ; len` | `4` ### Prefix notation While RPN works great for calculations, sometimes it is more natural to use prefix notation. Using postfix notation, the following can be rounded with: | Input | Stack |------------------|-------------| | `2` | `2` | `3` | `2 ; 3` | `d` | `0.6666666666666667` | `2` | `0.6666666666666667 ; 2` | `round` | `0.67` With prefix notation, this can instead be as follows: | Input | Stack |------------------|-------------| | `2` | `2` | `3` | `2 ; 3` | `d` | `0.6666666666666667` | `[round 2` | `0.67` To use prefix notation the line must start with a `[` and be directly followed by the operation name. Any additional text is treated as arguments to the operation and each argument is separated by whitespace. | Input | Stack |------------------|-------------| | `[a 1 2` | `3` Arguments in prefix notation are always treated as values and never evaluate as operations: | Input | Stack |------------------|-------------| | `[len len` | `3` If the operation needs more arguments than provided, the additional arguments are consumed from the stack. | Input | Stack |------------------|-------------| | `1` | `1` | `[a 2` | `3` If more arguments are provided than needed by the operation, the extra arguments are pushed to the stack. | Input | Stack |------------------|-------------| | `1` | `1` | `[a 2 3 4` | `1 ; 2 ; 7` Leading and trailing whitespace are not significant with arguments. Surround arguments with single quotes if necessary: | Input | Stack |------------------|-------------| | `[len ' len` | `4` | `[len ' len '` | `4 ; 5` ### Macros Define a macro by starting a line with a back quote (`` ` ``) followed by the macro name. All items on the stack are added to the macro. Recall the macro with an equals sign (`=`) followed by the macro name. Example: | Input | Stack |------------------|-------------| | `2` | `2` | `'m` | `2 ; m` | `` `double`` | | `6` | `6` | `=double` | `12` If the macro definition has arguments, those are used instead of the stack. Arguments in this context follow the same rules as arguments in prefix notation: | Input | Stack |------------------|-------------| | `` `double 2 m`` | | `6` | `6` | `=double` | `12` As a shortcut for a common operation, a macro that is defined with the name of `=` can simply be recalled with `=`. | Input | Stack |------------------|-------------| | `` `= 2 m`` | | `6` | `6` | `=` | `12` ### Stack Operations Pop the top item from the stack by entering a blank line: | Input | Stack |------------------|-------------| | `1` | `1` | `2` | `1 ; 2` | | `1` Clear the entire stack with `clear` or `c`: | Input | Stack |------------------|-------------| | `1` | `1` | `2` | `1 ; 2` | `c` | Undo the previous action with `undo` or `u`: | Input | Stack |------------------|-------------| | `1` | `1` | `2` | `1 ; 2` | `a` | `3` | `u` | `1 ; 2` Apply a macro to each item in the stack with `each`: | Input | Stack |------------------|-------------| | `` `double 2 m`` | | `1` | `1` | `2` | `1 ; 2` | `3` | `1 ; 2 ; 3` | `[each double` | `2 ; 4 ; 6` More stack operations can be found in the [builtin](doc/stdlib/builtin.md) module documentation. ### Modules Operations provided by the calculator are grouped into modules. The `builtin` module always has its operations available. Modules that belong to the prelude have their operations available by default when starting the application. Other modules must be explicitly imported with the `use` operation. Example: | Input | Stack |------------------|-------------| | `[use unit` | | `0` | `0` | `C->F` | `32` The `unit` module contains submodules. With `[use unit`, all operations in the submodules are included. To include only a submodule, use the following: | Input | Stack |------------------|-------------| | `[use unit.temp` | | `0` | `0` | `C->F` | `32` The list of modules available are as follows: | Name | Auto? | Description |--------------------------------------|-----------|----------------| | [bit](doc/stdlib/bit.md) | prelude | Bitwise operations | [builtin](doc/stdlib/builtin.md) | always | Builtin operations | [math](doc/stdlib/math.md) | prelude | Basic math operations | [sci](doc/stdlib/sci.md) | prelude | Scientific math operations | [str](doc/stdlib/str.md) | prelude | String operations | [unit.temp](doc/stdlib/unit/temp.md) | | Temperature conversions ## Development Setup In general: ```bash pip3 install -e . zcalc ``` Setup python 3.7 environment on macOS: ```bash brew install [email protected] /usr/local/opt/[email protected]/bin/python3 -m venv venv source venv/bin/activate python -m pip install --upgrade pip pip install -e . ``` Setup environment on Windows: ```powershell python -m venv venv .\venv\Scripts\Activate.ps1 python -m pip install --upgrade pip pip install -e . ``` Running tests: ```bash pip install pytest python -m unittest ``` ## License MIT
zcalc
/zcalc-0.4.0.tar.gz/zcalc-0.4.0/README.md
README.md
from dataclasses import dataclass from typing import Any, Dict, List, Literal from .request_types import User SlideType = Literal['table', 'list', 'images', 'text', 'label'] ButtonType = Literal['+', '-'] ActionType = Literal['invoke.function', 'system.api', 'open.url', 'preview.url'] CardTheme = Literal['default', 'poll', 'modern-inline', 'prompt'] Allignment = Literal['left', 'center', 'right'] BannerStatus = Literal['success', 'failure'] PreviewType = Literal['page', 'audio', 'video', 'image'] FormFieldType = Literal[ 'text', 'checkbox', 'datetime', 'location', 'radio', 'number', 'date', 'textarea', 'file', 'select', 'native_select', 'dynamic_select', 'hidden' ] FormFormat = Literal['email', 'tel', 'url', 'password'] DataSourceType = Literal['channels', 'conversations', 'contacts', 'teams'] MessageType = Literal['text', 'file', 'attachment', 'banner', 'message_edit', 'transient_message'] FormModificationActionType = Literal['remove', 'clear', 'enable', 'disable', 'update', 'add_before', 'add_after'] WidgetButtonEmotion = Literal['positive', 'neutral', 'negative'] WidgetDataType = Literal['sections', 'info'] WidgetElementType = Literal[ 'title', 'text', 'subtext', 'activity', 'user_activity', 'divider', 'buttons', 'table', 'fields'] WidgetEvent = Literal['load', 'refresh', 'tab_click'] WidgetType = Literal['applet'] ChannelOperation = Literal['added', 'removed', 'message_sent', 'message_edited', 'message_deleted'] SystemApiAction = Literal[ 'audiocall/{{id}}', 'videocall/{{id}}', 'startchat/{{id}}', 'invite/{{id}}', 'locationpermission', 'joinchannel/{{id}}'] @dataclass class SuggestionObject: text: str = None icon: str = None @dataclass class SuggestionList: list: List[SuggestionObject] = None @staticmethod def new_suggestion(text: str = None, icon: str = None): return SuggestionObject(text, icon) def add_suggestions(self, *suggestion: SuggestionObject): if not self.list: self.list = list(suggestion) return len(self.list) self.list.extend(suggestion) return len(self.list) @dataclass class ContextParam: name: str = None question: str = None value: Dict[str, str] = None suggestions: SuggestionList = None def set_value(self, val: str): self.value = {'text': val} def add_suggestion(self, text: str, icon: str = None): if not self.suggestions: self.suggestions = SuggestionList() self.suggestions.add_suggestions(self.suggestions.new_suggestion(text, icon)) @dataclass class Context: id: str = None timeout: int = None params: List[ContextParam] = None @staticmethod def new_param(): return ContextParam() def add_params(self, *param: ContextParam): if not self.params: self.params = list(param) return len(self.params) self.params.extend(param) return len(self.params) @dataclass class ActionData: name: str = None owner: str = None web: str = None windows: str = None iOS: str = None android: str = None api: str = None @dataclass class Confirm: title: str = None description: str = None input: str = None button_text: str = None @dataclass class Action: type: ActionType = None data: ActionData = None confirm: Confirm = None @staticmethod def new_action_data_obj(): return ActionData() @staticmethod def new_confirm_object(): return Confirm() @dataclass class ButtonObject: id: str = None button_id: str = None label: str = None name: str = None hint: str = None type: ButtonType = None key: str = None action: Action = None url: str = None @staticmethod def new_action_object(): return Action() @dataclass class Slide: type: SlideType = None title: str = None data: Any = None buttons: List[ButtonObject] = None @staticmethod def new_button_obj(): return ButtonObject() def add_buttons(self, *button: ButtonObject): if not self.buttons: self.buttons = list(button) return len(self.buttons) self.buttons.extend(button) return len(self.buttons) @dataclass class CardDetails: title: str = None icon: str = None thumbnail: str = None theme: CardTheme = None @dataclass class FormAction: type: ActionType = 'invoke.function' name: str = None @dataclass class FormActionsObject: submit: FormAction = None cancel: FormAction = None @staticmethod def new_form_action(name: str = None): return FormAction(name=name) @dataclass class FormValue: label: str = None value: str = None @dataclass class Boundary: latitude: int = None longitude: int = None radius: int = None @dataclass class FormInput: type: FormFieldType = None trigger_on_change: bool = None name: str = None label: str = None hint: str = None placeholder: str = None mandatory: bool = None value: Any = None options: List[FormValue] = None format: FormFormat = None max_length: str = None min_length: str = None max_selections: str = None boundary: Boundary = None max: int = None min: int = None multiple: bool = None data_source: DataSourceType = None auto_search_min_results: int = None min_characters: int = None @staticmethod def new_form_value(label: str = None, value: str = None): return FormValue(label, value) @staticmethod def new_boundary(latitude: int = None, longitude: int = None, radius: int = None): return Boundary(latitude, longitude, radius) def add_options(self, *form_value: FormValue): if not self.options: self.options = list(form_value) return len(self.options) self.options.extend(form_value) return len(self.options) @dataclass class Form: type: str = 'form' title: str = None hint: str = None name: str = None version: int = None button_label: str = None trigger_on_cancel: bool = None actions: FormActionsObject = None action: FormAction = None inputs: List[FormInput] = None @staticmethod def new_form_actions_obj(): return FormActionsObject() @staticmethod def new_form_action(name: str = None): return FormAction(name=name) @staticmethod def new_form_input(): return FormInput() def add_inputs(self, *input: FormInput): if not self.inputs: self.inputs = list(input) return len(self.inputs) self.inputs.extend(input) return len(self.inputs) @dataclass class Mention: name: str = None dname: str = None id: str = None type: str = None @dataclass class File: name: str id: str type: str url: str @dataclass class Message: type: MessageType = None mentions: List[Mention] = None text: str = None file: File = None comment: str = None status: BannerStatus = None @staticmethod def new_mention(): return Mention() def add_mentions(self, *mention: Mention): if not self.mentions: self.mentions = list(mention) return len(self.mentions) self.mentions.extend(mention) return len(self.mentions) @dataclass class CommandSuggestion: title: str = None description: str = None imageurl: str = None @dataclass class FormModificationAction: type: FormModificationActionType = None name: str = None input: FormInput = None @staticmethod def new_form_input(): return FormInput() @dataclass class FormChangeResponse: type: str = 'form_modification' actions: FormModificationAction = None @staticmethod def new_form_modification_action(): return FormModificationAction() def add_actions(self, *action: FormModificationAction): if not self.actions: self.actions = list(action) return len(self.actions) self.actions.extend(action) return len(self.actions) @dataclass class FormDynamicFieldResponse: options: List[FormValue] = None @staticmethod def new_form_value(label: str = None, value: str = None): return FormValue(label, value) def add_options(self, *option: FormValue): if not self.options: self.options = list(option) return len(self.options) self.options.extend(option) return len(self.options) @dataclass class WidgetButton: label: str = None emotion: WidgetButtonEmotion = None disabled: bool = None type: ActionType = None name: str = None url: str = None api: str = None id: str = None def set_api(self, api: SystemApiAction, id: str): self.api = api.replace('{{id}}', id) @dataclass class WidgetElementStyle: widths: List[str] = None alignments: List[Allignment] = None short: bool = None def add_widths(self, *width: str): if not self.widths: self.widths = list(width) return len(self.widths) self.widths.extend(width) return len(self.widths) def add_alignments(self, *alignment: Allignment): if not self.alignments: self.alignments = list(alignment) return len(self.alignments) self.alignments.extend(alignment) return len(self.alignments) @dataclass class WidgetInfo: title: str = None image_url: str = None description: str = None button: WidgetButton = None @staticmethod def new_widget_button(): return WidgetButton() @dataclass class WidgetElement: type: WidgetElementType = None text: str = None description: str = None image_url: str = None buttons: List[WidgetButton] = None button_references: Dict[str, ButtonObject] = None preview_type: PreviewType = None user: User = None headers: List[str] = None rows: List[Dict[str, ButtonObject]] = None style: WidgetElementStyle = None data: List[Dict[str, ButtonObject]] = None @staticmethod def new_widget_button(): return WidgetButton() def add_widget_buttons(self, *button: WidgetButton): if not self.buttons: self.buttons = list(button) return len(self.buttons) self.buttons.extend(button) return len(self.buttons) @staticmethod def new_button_object(): return ButtonObject() def add_button_reference(self, name: str, button: ButtonObject): if not self.button_references: self.button_references = {} self.button_references[name] = button @staticmethod def new_widget_element_style(): return WidgetElementStyle() @dataclass class WidgetSection: id: str = None elements: List[WidgetElement] = None type: str = None @staticmethod def new_widget_element(): return WidgetElement() def add_elements(self, *element: WidgetElement): if not self.elements: self.elements = list(element) return len(self.elements) self.elements.extend(element) return len(self.elements) @dataclass class WidgetTab: id: str = None label: str = None @dataclass class WidgetResponse: type: WidgetType = 'applet' tabs: List[WidgetTab] = None active_tab: str = None data_type: WidgetDataType = None sections: List[WidgetSection] = None info: WidgetInfo = None @staticmethod def new_widget_info(): return WidgetInfo() @staticmethod def new_widget_tab( id: str = None, label: str = None ): return WidgetTab(id, label) @staticmethod def new_widget_section(): return WidgetSection() def add_tab(self, *tab: WidgetTab): if not self.tabs: self.tabs = list(tab) return len(self.tabs) self.tabs.extend(tab) return len(self.tabs) def add_sections(self, *widget_section: WidgetSection): if not self.sections: self.sections = list(widget_section) return len(self.sections) self.sections.extend(widget_section) return len(self.sections) @dataclass class InstallationResponse: status: int = 200 title: str = None message: str = None note: List[str] = None footer: str = None def add_notes(self, *note: str): if not self.notes: self.note = list(note) return len(self.note) self.note.extend(note) return len(self.note)
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/response_types.py
response_types.py
from dataclasses import dataclass from typing import Any, Dict, List, Optional, TypedDict, Literal MessageType = Literal['text', 'file', 'attachment', 'banner', 'message_edit', 'transient_message'] ButtonType = Literal['+', '-'] @dataclass class Access: user_id: int user_agent: str chat_id: str @dataclass class AppInfo: current_version: str existing_version: str type: Literal["install", "upgrade"] @dataclass class Attachment: name: str comment: str id: str url: str contenttype: str @dataclass class BotDetails: name: str image: str @dataclass class ActionData: name: Optional[str] owner: Optional[str] web: Optional[str] windows: Optional[str] iOS: Optional[str] android: Optional[str] api: Optional[str] @dataclass class Confirm: title: Optional[str] description: Optional[str] input: Optional[str] button_text: Optional[str] @dataclass class Action: type: Optional[str] data: Optional[ActionData] confirm: Optional[Confirm] @dataclass class ButtonObject: id: Optional[str] button_id: Optional[str] label: Optional[str] name: Optional[str] hint: Optional[str] type: Optional[ButtonType] key: Optional[str] action: Optional[Action] url: Optional[str] @dataclass class Button: type: Literal['button'] object: ButtonObject @dataclass class ButtonArguments: key: str @dataclass class Member: id: str first_name: str last_name: str email: str status: str @dataclass class Sender: name: str id: str @dataclass class RecentMessage: sender: Sender time: int text: str id: str type: str @dataclass class Chat: owner: int id: str type: str title: str members: List[Member] recent_messages: List[RecentMessage] @dataclass class Dimension: size: int width: int height: int @dataclass class FileContent: name: str id: str type: str dimensions: Dimension @dataclass class Thumbnail: width: str blur_data: str height: str @dataclass class Content: thumbnail: Thumbnail file: FileContent comment: str text: str @dataclass class DateTimeObject: date_time: str time_zone_id: str @dataclass class Environment: data_center: str @dataclass class File: name: str id: str type: str url: str @dataclass class FormRequestParam: name: str action: str values: Any @dataclass class FormValue: label: Optional[str] value: Optional[str] @dataclass class FormTarget: name: str value: FormValue query: str @dataclass class Location: latitude: int longitude: int accuracy: int status: Literal['granted', 'prompt', 'denied', 'failed'] @dataclass class LocationValue: latitude: int longitude: int @dataclass class Mention: name: str dname: str id: str type: str @dataclass class Message: type: str mentions: Optional[List[Mention]] text: Optional[str] file: Optional[File] comment: Optional[str] status: Optional[str] @dataclass class MessageDetails: time: int message: Message; @dataclass class User: id: str first_name: str last_name: str email: str admin: bool organization_id: int timezone: str country: str language: str name: str @dataclass class MessageObject: sender: User time: int type: MessageType text: str is_read: bool ack_key: str id: str content: Content @dataclass class SuggestionObject: text: str icon: str @dataclass class CommandSuggestion: title: Optional[str] description: Optional[str] imageurl: Optional[str] class ICliqReqHandler(TypedDict): type: str name: Optional[str] class ICliqReqBody(TypedDict): name: str unique_name: str handler: ICliqReqHandler response_url: str type: str timestamp: int params: Dict[str, Any] # ######******###### # #new formats starts # SlideType = Literal['table', 'list', 'images', 'text', 'label'] # ButtonType = Literal['+', '-'] # ActionType = Literal['invoke.function', 'system.api', 'open.url', 'preview.url'] # CardTheme = Literal['default', 'poll', 'modern-inline', 'prompt'] # Allignment = Literal['left', 'center', 'right'] # BannerStatus = Literal['success', 'failure'] # PreviewType = Literal['page', 'audio', 'video', 'image'] # FormFieldType = Literal[ # 'text', 'checkbox', 'datetime', 'location', 'radio', 'number', # 'date', 'textarea', 'file', 'select', 'native_select', 'dynamic_select', 'hidden' # ] # FormFormat = Literal['email', 'tel', 'url', 'password'] # DataSourceType = Literal['channels', 'conversations', 'contacts', 'teams'] # MessageType = Literal['text', 'file', 'attachment', 'banner', 'message_edit', 'transient_message'] # FormModificationActionType = Literal['remove', 'clear', 'enable', 'disable', 'update', 'add_before', 'add_after'] # WidgetButtonEmotion = Literal['positive', 'neutral', 'negative'] # WidgetDataType = Literal['sections', 'info'] # WidgetElementType = Literal['title', 'text', 'subtext', 'activity', 'user_activity', 'divider', 'buttons', 'table', 'fields'] # WidgetEvent = Literal['load', 'refresh', 'tab_click'] # WidgetType = Literal['applet'] # ChannelOperation = Literal['added', 'removed', 'message_sent', 'message_edited', 'message_deleted'] # SystemApiAction = Literal['audiocall/{{id}}', 'videocall/{{id}}', 'startchat/{{id}}', 'invite/{{id}}', 'locationpermission', 'joinchannel/{{id}}'] # ##handler response starts # class CardDetails(TypedDict): # title: str # icon: str # thumbnail: str # theme: CardTheme # class ButtonObject(TypedDict): # id: str # button_id: str # label: str # name: str # hint: str # type: ButtonType # key: str # action: Action # url: str # class Slide(TypedDict): # type: SlideType # title: str # data: Any # buttons: List[ButtonObject] # class SuggestionList(TypedDict): # list: List[SuggestionObject] # class ContextParam(TypedDict): # name: str # question: str # value: Dict[str,str] # suggestions: SuggestionList # class Context(TypedDict): # id: str # timeout: int # params: List[ContextParam] # class HandlerResponse(TypedDict): # text: str # context: Context # bot: BotDetails # suggestions: SuggestionList # slides: List[Slide] # buttons: List[ButtonObject] # card: CardDetails # #handler response ends # #handler cs resp starts # class CommandSuggestion(TypedDict): # title: str # description: str # imageurl: str # #handler cs resp ends # #form change response starts # class Boundary(TypedDict): # latitude: int # longitude: int # radius: int # class FormInput(TypedDict): # type: FormFieldType # trigger_on_change: bool # name: str # label: str # hint: str # placeholder: str # mandatory: bool # value: Any # options: List[FormValue] # format: FormFormat # max_length: str # min_length: str # max_selections: str # boundary: Boundary # max: int # min: int # multiple: bool # data_source: DataSourceType # auto_search_min_results: int # min_characters: int # class FormModificationAction(TypedDict): # type: FormModificationActionType # name: str # input: FormInput # class FormChangeResponse(TypedDict): # type: Literal['form_modification'] # actions: FormModificationAction # #form change response ends # #form dynamic response starts # class FormDynamicFieldResponse(TypedDict): # options: List[FormValue] # #form dynamic response ends # #form widget response starts # class WidgetButton(TypedDict): # label: str # emotion: WidgetButtonEmotion # disabled: bool # type: ActionType # name: str # url: str # api: str # id: str # class WidgetElementStyle(TypedDict): # widths: List[str] # alignments: List[Allignment] # short: bool # class WidgetInfo(TypedDict): # title: str # image_url: str # description: str # button: WidgetButton # class WidgetElement(TypedDict): # type: WidgetElementType # text: str # description: str # image_url: str # buttons: List[WidgetButton] # button_references: Dict[str,ButtonObject] # preview_type: PreviewType # user: User # headers: List[str] # rows: List[Dict[str,ButtonObject]] # style: WidgetElementStyle # data: List[Dict[str,ButtonObject]] # class WidgetSection(TypedDict): # elements: List[WidgetElement] # type: str # class WidgetTab(TypedDict): # id: str # label: str # class WidgetResponse(TypedDict): # type: WidgetType # tabs: List[WidgetTab] # active_tab: str # data_type: WidgetDataType # sections: List[WidgetSection] # info: WidgetInfo # #form widget response ends
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/request_types.py
request_types.py
import json from . import _utils from os import path from typing import Union from .request_types import ICliqReqBody from .error import CatalystError from . import _constants as Constants HANDLERS_LIST = [ 'bot_handler', 'command_handler', 'messageaction_handler', 'widget_handler', 'function_handler', 'installation_handler', 'installation_validator' ] class CliqReq: def __init__(self, dict_obj): self.__dict__.update(dict_obj) def get_handler_config(config: Union[str, dict]): if not isinstance(config, (str, dict)): raise CatalystError( 'handler config expected to be dict or a string file path' ) handler_config = parse_config(config) return validate_handler_config(handler_config) def parse_config(config) -> dict: if isinstance(config, dict): return config fn_root = _utils.get_function_root() try: with open(path.normpath(path.join(fn_root, config)), encoding="utf-8") as json_file: json_dict = json.load(json_file) except: raise CatalystError( f'Unable to parse the config json from the file path: {config}' ) from None return json_dict def validate_handler_config(handler_config: dict): if not handler_config: raise CatalystError( 'handler config should not be empty' ) cliq_config = handler_config.get(Constants.CLIQ) if not cliq_config: raise CatalystError( 'integration_config for service ZohoCliq is not found' ) cliq_handlers: dict = cliq_config.get('handlers') if not cliq_handlers: raise CatalystError( 'Handlers is empty' ) fn_root = _utils.get_function_root() for handler in cliq_handlers.keys(): if handler not in HANDLERS_LIST: raise CatalystError( f'Unknown handler: {handler}' ) handler_file = cliq_handlers.get(handler) handler_filepath = path.abspath(path.join(fn_root, handler_file)) if not path.exists(handler_filepath): raise CatalystError( f'Handler file {handler_file} provided for {handler} does not exist' ) cliq_handlers[handler] = handler_filepath return cliq_handlers def process_data(cliq_body: ICliqReqBody) -> CliqReq: params = cliq_body.get('params') req_type = cliq_body.get('type') if not params: raise CatalystError('No params found in request body', 2) if req_type == Constants.BOT: params.update({ 'name': cliq_body.get('name'), 'unique_name': cliq_body.get('unique_name') }) if cliq_body.get('handler').get('type') == Constants.Handlers.BotHandler.ACTION_HANDLER: params.update({ 'action_name': cliq_body.get('handler').get('name') }) elif req_type in [Constants.FUNCTION, Constants.COMMAND, Constants.MESSAGEACTION]: params.update({ 'name': cliq_body.get('name') }) return json.loads(json.dumps(params), object_hook=CliqReq)
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/_handler_util.py
_handler_util.py
from dataclasses import dataclass from typing import Any, Callable, Dict, Optional, TypedDict from ._handler import Handler from . import _constants as Constants from ._constants import Handlers from .handler_response import HandlerResponse from .response_types import ( WidgetResponse, FormChangeResponse, FormDynamicFieldResponse ) from .request_types import ( Access, ButtonObject, Environment, User, Chat, MessageObject, Button, FormRequestParam, FormTarget ) @dataclass class FunctionRequest: name: str user: User chat: Chat message: MessageObject @dataclass class ButtonFunctionRequest(FunctionRequest): arguments: Dict[str, Any] target: Button @dataclass class FormFunctionRequest(FunctionRequest): form: FormRequestParam target: FormTarget @dataclass class WidgetFunctionRequest: name: str user: User target: ButtonObject access: Access environment: Environment def button_function_handler( func: Callable[ [ButtonFunctionRequest, HandlerResponse, tuple], Any ] ): Handler.register_hanlder( Constants.FUNCTION, Handlers.function_handler.BUTTON_HANDLER, func, HandlerResponse ) def form_submit_handler( func: Callable[ [FormFunctionRequest, HandlerResponse, tuple], Any ] ): Handler.register_hanlder( Constants.FUNCTION, Handlers.function_handler.FORM_HANDLER, func, HandlerResponse ) def form_change_handler( func: Callable[ [FormFunctionRequest, FormChangeResponse, tuple], Optional[FormChangeResponse] ] ): Handler.register_hanlder( Constants.FUNCTION, Handlers.function_handler.FORM_CHANGE_HANDLER, func, FormChangeResponse ) def form_dynamic_field_handler( func: Callable[ [FormFunctionRequest, FormDynamicFieldResponse, tuple], Optional[FormDynamicFieldResponse] ] ): Handler.register_hanlder( Constants.FUNCTION, Handlers.function_handler.FORM_VALUES_HANDLER, func, FormDynamicFieldResponse ) def widget_button_handler( func: Callable[ [WidgetFunctionRequest, WidgetResponse, tuple], Any ] ): Handler.register_hanlder( Constants.FUNCTION, Handlers.function_handler.WIDGET_FUNCTION_HANDLER, func, WidgetResponse ) def new_handler_response(): return HandlerResponse() def new_form_change_response(): return FormChangeResponse() def new_form_dynamic_field_response(): return FormDynamicFieldResponse() def new_widget_response(): return WidgetResponse()
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/function_handler.py
function_handler.py
from dataclasses import dataclass from requests import Response from typing import Any, Callable, Dict, List, Optional, Tuple from ._handler import Handler from .error import CatalystError from ._constants import Handlers from ._utils import send_request from .request_types import ( User, Environment, Access, Attachment, MessageDetails, Location, Mention, Chat ) from . import _constants as Constants from .handler_response import HandlerResponse @dataclass class BotHandlerRequest: user: User name: str unique_name: str environment: Optional[Environment] access: Optional[Access] @dataclass class BotWelcomeHandlerRequest(BotHandlerRequest): newuser: bool @dataclass class BotMessageHandlerRequest(BotHandlerRequest): attachments: List[Attachment] links: List[str] message_details: MessageDetails location: Location raw_message: str message: str mentions: List[Mention] chat: Chat @dataclass class BotContextHandlerRequest: user: User name: str unique_name: str chat: Chat context_id: str answers: Any @dataclass class BotMentionHandlerRequest(BotHandlerRequest): location: Location chat: Chat @dataclass class BotMenuActionHandlerRequest(BotHandlerRequest): action_name: str location: Location chat: Chat @dataclass class BotWebHookHandlerRequest(BotHandlerRequest): headers: Dict[str, str] param: Dict[str, str] body: Dict[str, Any] http_method: str @dataclass class BotParticipationHandlerRequest(BotHandlerRequest): operation: str data: Dict[str, Any] chat: Chat def welcome_handler( func: Callable[ [BotWelcomeHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.WELCOME_HANDLER, func, HandlerResponse ) def message_handler( func: Callable[ [BotMessageHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.MESSAGE_HANDLER, func, HandlerResponse ) def context_handler( func: Callable[ [BotContextHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.CONTEXT_HANDLER, func, HandlerResponse ) def mention_handler( func: Callable[ [BotMentionHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.MENTION_HANDLER, func, HandlerResponse ) def menu_action_handler( func: Callable[ [BotMenuActionHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.ACTION_HANDLER, func, HandlerResponse ) def webhook_handler( func: Callable[ [BotWebHookHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.INCOMING_WEBHOOK_HANDLER, func, HandlerResponse ) def participation_handler( func: Callable[ [BotParticipationHandlerRequest, HandlerResponse, Tuple], Any ] ): Handler.register_hanlder( Constants.BOT, Handlers.BotHandler.PARTICIPATION_HANDLER, func, HandlerResponse ) def new_handler_response(): return HandlerResponse() class Util: @staticmethod def get_attached_file(attachments: List[Attachment]): result: list[bytes] = [] try: for attachment in attachments: resp: Response = send_request('GET', attachment.url, stream=True) result.append(resp.content) except Exception as e: raise CatalystError('Error when getting the attached file', 0, e) return result
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/bot_handler.py
bot_handler.py
from io import BufferedReader from typing import List, Union from zcatalyst_sdk._http_client import HttpClient from zcatalyst_sdk.connection import Connector from . import _constants as ApiConstants class ApiUtil: def __init__(self, connector: Connector): self._connection = connector self._requester = HttpClient() def send_request(self, url, **kwargs): resp = self._requester.request( 'POST', url, headers={ 'Authorization': ApiConstants.OAUTH_PREFIX + self._connection.get_access_token(), 'User-Agent': ApiConstants.USER_AGENT }, **kwargs ) return resp class CliqApiService: def __init__(self, connector: Connector): self._api = ApiUtil(connector) def post_to_channel( self, channel_unique_name: str, payload: Union[str, BufferedReader], bot_unique_name: str = None ): file = None message = None url = ApiConstants.POST_TO_CHANNEL_URL + channel_unique_name if isinstance(payload, str): url += ApiConstants.MESSAGE message = { 'text': payload } elif isinstance(payload, BufferedReader): url += ApiConstants.FILES file = { 'file': payload } query_params = {} if bot_unique_name: query_params = { ApiConstants.BOT_UNIQUE_NAME: bot_unique_name } resp = self._api.send_request( url=url, params=query_params, files=file, json=message ) return resp def post_to_channel_as_bot( self, channel_unique_name: str, payload: Union[str, BufferedReader], bot_unique_name: str ): self.post_to_channel( channel_unique_name, payload, bot_unique_name ) def post_to_bot( self, bot_unique_name: str, payload: Union[str, BufferedReader], delivery_info: Union[bool, List[str]] ): file = None message = None url = ApiConstants.POST_TO_BOT_URL + bot_unique_name if isinstance(payload, str): url += ApiConstants.MESSAGE message = { 'text': payload } if isinstance(delivery_info, bool): message[ApiConstants.BROADCAST] = delivery_info elif isinstance(delivery_info, list): message[ApiConstants.BROADCAST] = False message[ApiConstants.USERIDS] = ','.join(delivery_info) elif isinstance(payload, BufferedReader): url += ApiConstants.FILES file = { 'file': payload } resp = self._api.send_request( url=url, files=file, json=message ) return resp def post_to_chat( self, chat_id: str, payload: Union[str, BufferedReader] ): file = None message = None url = ApiConstants.POST_TO_CHAT_URL + chat_id if isinstance(payload, str): url += ApiConstants.MESSAGE message = { 'text': payload } elif isinstance(payload, BufferedReader): url += ApiConstants.FILES file = { 'file': payload } resp = self._api.send_request( url=url, files=file, json=message ) return resp def post_to_user( self, id: str, payload: Union[str, BufferedReader] ): file = None message = None url = ApiConstants.POST_TO_CHAT_URL + id if isinstance(payload, str): url += ApiConstants.MESSAGE message = { 'text': payload } elif isinstance(payload, BufferedReader): url += ApiConstants.FILES file = { 'file': payload } resp = self._api.send_request( url=url, files=file, json=message ) return resp
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/api_service.py
api_service.py
import os from os import path def env_override(env_name: str, default_value: str): env_value = os.getenv(env_name) if not env_value: return default_value return env_value meta_file = path.join(path.dirname(path.abspath(__file__)), '__version__.py') meta = {} with open(meta_file, encoding="utf-8") as fp: exec(fp.read(), meta) # pylint: disable=exec-used # SDK constants SDK_VERSION = meta['__version__'] USER_AGENT = 'zcatalyst-integ-python/' CONFIG_JSON = 'catalyst-config.json' CLIQ = 'ZohoCliq' BOT = 'bot' COMMAND = 'command' MESSAGEACTION = 'messageaction' WIDGET = 'widget' FUNCTION = 'function' INSTALLATION = 'installation_handler' INSTALLATION_VALIDATOR = 'installation_validator' class Handlers: class BotHandler: WELCOME_HANDLER = 'welcome_handler' MESSAGE_HANDLER = 'message_handler' CONTEXT_HANDLER = 'context_handler' MENTION_HANDLER = 'mention_handler' ACTION_HANDLER = 'action_handler' INCOMING_WEBHOOK_HANDLER = 'incomingwebhook_handler' PARTICIPATION_HANDLER = 'participation_handler' class CommandHandler: EXECUTION_HANDLER = 'execution_handler' SUGGESTION_HANDLER = 'suggestion_handler' class MessageActionHandler: EXECUTION_HANDLER = 'execution_handler' class WidgetHandler: VIEW_HANDLER = 'view_handler' class function_handler: BUTTON_HANDLER = 'button_handler' FORM_HANDLER = 'form_handler' FORM_CHANGE_HANDLER = 'form_change_handler' FORM_VALUES_HANDLER = 'form_values_handler' WIDGET_FUNCTION_HANDLER = 'applet_button_handler' installation_handler = 'installation_handler' installation_validator = 'installation_validator' # API Constants DOMAIN = env_override('INTEG_CLIQ_DOMAIN', 'https://cliq.zoho.com') VERSION = '/v2' API = '/api' MESSAGE = '/message' FILES = '/files' OAUTH_PREFIX = 'Zoho-oauthtoken ' BOT_UNIQUE_NAME = 'bot_unique_name' BROADCAST = 'broadcast' USERIDS = 'userids' API_URL = DOMAIN + API + VERSION POST_TO_CHANNEL_URL = API_URL + '/channelsbyname/' POST_TO_BOT_URL = API_URL + '/bots/' POST_TO_CHAT_URL = API_URL + '/chats/' POST_TO_USER_URL = API_URL + '/buddies/'
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/_constants.py
_constants.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ SDK for integrating Zoho Catalyst with Zoho Cliq """ import json import time from importlib.util import module_from_spec, spec_from_file_location from typing import Callable, Union from .error import CatalystError from ._utils import send_request from ._handler_util import get_handler_config, process_data from ._handler import Handler from .request_types import ICliqReqBody def execute( integ_request, config: Union[str, dict], *args ): cliq_body: ICliqReqBody = integ_request.get_request_body() # handling for cli if isinstance(cliq_body, str): cliq_body = json.loads(cliq_body) handler_type = cliq_body.get('handler').get('type') if not handler_type: raise CatalystError('Unknown request body', 2) component_handler_name = cliq_body.get('type') + '_handler' if cliq_body.get('type') else handler_type component_type = cliq_body.get('type') if cliq_body.get('type') else handler_type handler_config = get_handler_config(config) handler_file = handler_config.get(component_handler_name) if not handler_file: raise CatalystError('Handler file missing', 2) if not Handler.handler_map.get(component_type): spec = spec_from_file_location('', handler_file) module = module_from_spec(spec) spec.loader.exec_module(module) if not Handler.handler_map.get(component_type): raise CatalystError( f'No handler function found for {handler_type}', 2 ) cliq_handler = Handler.handler_map.get(component_type).get(handler_type) handler_fn: Callable = cliq_handler.get('func') response = cliq_handler.get('resp') if not handler_fn or handler_fn.__class__.__name__ != 'function': raise CatalystError( f'No handler function found for {handler_type}', 2 ) cliq_params = process_data(cliq_body) handler_resp = handler_fn(cliq_params, response(), *args) try: integ_resp = json.dumps({'output': handler_resp or ''}, default=lambda o: dict((k, v) for k, v in o.__dict__.items() if v)) except: raise CatalystError( f'Unable to process the response for {handler_type} ', 2 ) if (time.time() * 1000 - cliq_body.get('timestamp') >= 15000 and cliq_body.get('response_url')): resp = send_request( 'POST', cliq_body['response_url'], json=integ_resp ) if resp.status_code not in range(200, 300): raise CatalystError( 'Failed to send timeout request' ) return integ_resp
zcatalyst-cliq
/zcatalyst_cliq-0.0.1-py3-none-any.whl/zcatalyst_cliq/__init__.py
__init__.py
import os import sys import time import zipfile import logging import signal from flask import Flask, request, Response, g, current_app from log_handler import LogHandler from init_handler import InitHandler from flavours import FlavourHandler from flavours.utils import send_json_response ZIP_LOCATION: str = '/tmp/code.zip' logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(LogHandler()) # To support user function to import their own modules and prefer # locally installed modules over globally installed modules. sys.path.insert(0, InitHandler.get_code_location().as_posix()) if not InitHandler.is_local(): def init_signal_handler(_sig, _frame): InitHandler.mark_init() signal.signal(signal.SIGPWR, init_signal_handler) app = Flask(__name__) def internal_request_handler(): if request.path == '/init': if InitHandler.is_success(): # Will be caught by uncaught exception handler raise Exception('init already completed') init_start_time = int(time.time() * 1000) with open(ZIP_LOCATION, 'wb') as code_zip: while True: chunk = request.stream.read(1048576) if not chunk: break code_zip.write(chunk) with zipfile.ZipFile(ZIP_LOCATION, 'r') as code_zip: code_zip.extractall(InitHandler.get_code_location()) os.remove(ZIP_LOCATION) if not InitHandler.is_local(): process_group_id = os.getpgid(os.getpid()) os.killpg(process_group_id, signal.SIGPWR) g.response.headers.add('x-catalyst-init-time-ms', f'{int(time.time() * 1000)} - {init_start_time}') send_json_response(200, { 'message': 'success' }) elif request.path == '/ruok': send_json_response(200, { 'message': 'iamok' }) else: raise Exception('unexpected internal path') FLAVOUR_HANDLER: FlavourHandler = None def customer_request_handler(): try: global FLAVOUR_HANDLER if not FLAVOUR_HANDLER: FLAVOUR_HANDLER = FlavourHandler() FLAVOUR_HANDLER.invoke_handler() except Exception as e: logger.exception(repr(e)) FLAVOUR_HANDLER.return_error_response(repr(e)) @app.route('/', methods=['HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE']) @app.route('/<path:_path>', methods=['HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE']) def router(_path = None): g.response = Response() if request.headers.get('x-zoho-catalyst-internal') == 'true': internal_request_handler() else: if not InitHandler.return_on_success(): # Will be caught by uncaught exception handler raise Exception('init not completed') logger.info(f'Execution started at: {int(time.time() * 1000)}') customer_request_handler() return g.response @app.errorhandler(Exception) def error_handler(e): # We caught all customer request exceptions in `customer_request_handler` # itself, so we're marking this exception as an internal failure. with app.app_context(): setattr(current_app, '__internal_failure', True) logger.exception(repr(e)) send_json_response(500, { 'error': repr(e) }) return g.response def run_production_server(): from gunicorn.app.base import BaseApplication # Gunicorn custom application # Refer: https://docs.gunicorn.org/en/stable/custom.html class CatalystApplication(BaseApplication): def __init__(self, app, options = {}): self.app = app self.options = options super().__init__() def init(self, parser, opts, args): return super().init(parser, opts, args) def load(self): return self.app def load_config(self): for k, v in self.options.items(): if k not in self.cfg.settings: print('invalid: ', k) continue try: self.cfg.set(k.lower(), v) except Exception: raise Exception(f'Invalid value for: {k}: {v}') # Gunicorn server hooks # Refer: https://docs.gunicorn.org/en/stable/settings.html#server-hooks # Hook: when_ready def when_ready(_server): """Called just after the server is started.""" if InitHandler.is_local(): return # Updates the status of the function to runtime. # # +---------------------+-----------------+------------------------+-------------------+ # | ENCODING (1 byte) | PATH (1 byte) | CONTENT_LEN (4 byte) | STATUS (1 byte) | # +---------------------+-----------------+------------------------+-------------------+ # # First 1 byte is the encoding, for status it is always 1. # Second 1 byte is the path, for status it is always 0. # Third 4 bytes are the content length. For status(unsigned-8bit) this will always be 1. (big-endian) # Next 1 byte is status. status_frame = bytearray() status_frame[0:1] = (1).to_bytes(1, 'big') status_frame[1:2] = (0).to_bytes(1, 'big') status_frame[2:6] = (1).to_bytes(4, 'big') status_frame[6:7] = (1).to_bytes(1, 'big') status_fd = int(os.getenv('X_ZOHO_SPARKLET_STATUS_FD')) del os.environ['X_ZOHO_SPARKLET_STATUS_FD'] pid = os.getpid() status_fd = open(f'/proc/{pid}/fd/{status_fd}', 'wb', buffering=0) status_fd.write(status_frame) # Hook: post_request def post_request(_worker, _req, _environ, _resp): """Called after a worker processes the request.""" # Since, `error_handler`` marked this as an internal failure, we're exiting # from gunicorn worker process after response is sent. with app.app_context(): if getattr(current_app, '__internal_failure', False): os._exit(signal.SIGUSR1) # Hook: child_exit def child_exit(_server, _worker): """Called just after a worker has been exited, in the master process.""" os._exit(signal.SIGUSR1) options = { 'bind': f'0.0.0.0:{InitHandler.get_listen_port()}', 'workers': InitHandler.get_worker_count(), 'threads': InitHandler.get_thread_count(), 'pythonpath': f'{InitHandler.get_code_location()},', 'preload_app': True, 'loglevel': 'warning', 'timeout': 0, # Server hooks 'when_ready': when_ready, 'child_exit': child_exit, 'post_request': post_request, } CatalystApplication(app, options).run() def run_development_server(): # To disable Flask's server banner and console logs from flask import cli cli.show_server_banner = lambda *args: None logging.getLogger('werkzeug').disabled = True app.run('0.0.0.0', InitHandler.get_listen_port()) if __name__ == "__main__": try: if not InitHandler.is_local(): run_production_server() else: run_development_server() except Exception as e: logger.exception(e) os._exit(signal.SIGUSR1)
zcatalyst-runtime-39
/zcatalyst_runtime_39-0.0.4-py3-none-any.whl/zcatalyst_runtime_39/main.py
main.py
import os import json import threading from importlib.util import spec_from_file_location, module_from_spec from flask import g from init_handler import InitHandler from flavours.utils import get_catalyst_headers, send_json_response CUSTOMER_CODE_ENTRYPOINT = None class FlavourHandler: def __init__(self) -> None: with open(InitHandler.get_code_location().joinpath('catalyst-config.json'), 'r') as config_file: catalyst_config = json.loads(config_file.read()) entry_point = catalyst_config['execution']['main'] or 'main.py' self.__entrypoint = InitHandler.get_code_location().joinpath(entry_point) self.__flavour = os.getenv('CATALYST_FUNCTION_TYPE', catalyst_config['deployment']['type']) def __get_flavour(self): if self.__flavour == 'basicio': from flavours.basicio import BasicIOHandler return BasicIOHandler elif self.__flavour == 'applogic' or self.__flavour == 'advancedio': from flavours.applogic import ApplogicHandler return ApplogicHandler elif self.__flavour == 'cron': from flavours.cron import CronHandler return CronHandler elif self.__flavour == 'event': from flavours.event import EventHandler return EventHandler elif self.__flavour == 'integration': from flavours.integration import IntegrationHandler return IntegrationHandler else: raise Exception(f'unsupported function type: {self.__flavour}') def __construct_function_parameters(self): threading.current_thread().__setattr__('__zc_local', { 'catalyst_headers': get_catalyst_headers() }) return self.__get_flavour().construct_function_parameters() def invoke_handler(self): global CUSTOMER_CODE_ENTRYPOINT if not CUSTOMER_CODE_ENTRYPOINT: spec = spec_from_file_location('', self.__entrypoint) module = module_from_spec(spec) spec.loader.exec_module(module) CUSTOMER_CODE_ENTRYPOINT = module.handler RET = CUSTOMER_CODE_ENTRYPOINT(*(self.__construct_function_parameters())) if self.__flavour == 'basicio': # Refer: !25. Useful when `context.close()`` is not called by user. send_json_response(g.response.status_code, { 'output': g.response.get_data(as_text=True) }) elif RET and (self.__flavour == 'applogic' or self.__flavour == 'advancedio'): # User can return their own response object from applogic functions. g.response = RET def return_error_response(self, error = None): return self.__get_flavour().return_error_response(error)
zcatalyst-runtime-39
/zcatalyst_runtime_39-0.0.4-py3-none-any.whl/zcatalyst_runtime_39/flavours/__init__.py
__init__.py