python-jenkins-0.2.1/.pep80000644000000000000000000000003212202671451013470 0ustar 00000000000000[pep8] ignore = E221,E501 python-jenkins-0.2.1/COPYING0000644000000000000000000000301312202671451013650 0ustar 00000000000000Software License Agreement (BSD License) Copyright (c) 2010, Willow Garage, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Willow Garage, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS 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 OWNER OR CONTRIBUTORS 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. python-jenkins-0.2.1/Makefile0000644000000000000000000000004312202671451014255 0ustar 00000000000000test: python -m unittest discover python-jenkins-0.2.1/doc/0000755000000000000000000000000012202671451013365 5ustar 00000000000000python-jenkins-0.2.1/jenkins/0000755000000000000000000000000012202671451014261 5ustar 00000000000000python-jenkins-0.2.1/setup.py0000644000000000000000000000051012202671451014326 0ustar 00000000000000#!/usr/bin/env python from distutils.core import setup setup(name='python-jenkins', version='0.2.1', description='Python bindings for the remote Jenkins API', author='Ken Conley', author_email='kwc@willowgarage.com', url='http://launchpad.net/python-jenkins', packages=['jenkins'], ) python-jenkins-0.2.1/tests/0000755000000000000000000000000012202671451013762 5ustar 00000000000000python-jenkins-0.2.1/doc/Makefile0000644000000000000000000001273412202671451015034 0ustar 00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PythonJenkins.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PythonJenkins.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/PythonJenkins" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PythonJenkins" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." python-jenkins-0.2.1/doc/build/0000755000000000000000000000000012202671451014464 5ustar 00000000000000python-jenkins-0.2.1/doc/source/0000755000000000000000000000000012202671451014665 5ustar 00000000000000python-jenkins-0.2.1/doc/source/api.rst0000644000000000000000000000015612202671451016172 0ustar 00000000000000:title: API reference API reference ============= .. automodule:: jenkins :members: :undoc-members: python-jenkins-0.2.1/doc/source/conf.py0000644000000000000000000001627512202671451016177 0ustar 00000000000000# -*- coding: utf-8 -*- # # Python Jenkins documentation build configuration file, created by # sphinx-quickstart on Sat Sep 3 16:24:58 2011. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('../../jenkins')) # -- General configuration ---------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Also document __init__ autoclass_content = 'both' # Change that to 'alphabetical' if you want autodoc_member_order = 'bysource' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Python Jenkins' copyright = u'2010, Willow Garage' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.2' # The full version, including alpha/beta/rc tags. release = '0.2' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PythonJenkinsdoc' # -- Options for LaTeX output ------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]) latex_documents = [ ('index', 'PythonJenkins.tex', u'Python Jenkins Documentation', u'Ken Conley, James Page, Tully Foote, Matthew Gertner', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pythonjenkins', u'Python Jenkins Documentation', [u'Ken Conley, James Page, Tully Foote, Matthew Gertner'], 1) ] python-jenkins-0.2.1/doc/source/example.rst0000644000000000000000000000120212202671451017045 0ustar 00000000000000Example usage ============= Example usage:: j = jenkins.Jenkins('http://your_url_here', 'username', 'password') j.get_jobs() j.create_job('empty', jenkins.EMPTY_CONFIG_XML) j.disable_job('empty') j.copy_job('empty', 'empty_copy') j.enable_job('empty_copy') j.reconfig_job('empty_copy', jenkins.RECONFIG_XML) j.delete_job('empty') j.delete_job('empty_copy') # build a parameterized job j.build_job('api-test', {'param1': 'test value 1', 'param2': 'test value 2'}) build_info = j.get_build_info('build_name', next_build_number) print(build_info) Look at the :doc:`api` for more details. python-jenkins-0.2.1/doc/source/index.rst0000644000000000000000000000101512202671451016523 0ustar 00000000000000Welcome to Python Jenkins's documentation! ========================================== Python Jenkins is a library for the remote API of the `Jenkins `_ continuous integration server. It is useful for creating and managing jobs as well as build nodes. Table of content: .. toctree:: :maxdepth: 2 :glob: * Python Jenkins development is hosted on Launchpad: https://launchpad.net/python-jenkins Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-jenkins-0.2.1/doc/source/install.rst0000644000000000000000000000073312202671451017070 0ustar 00000000000000:title: Installing Installing ========== The module is known to pip and Debian based distribution as ``python-jenkins``. ``pip``:: pip install python-jenkins ``easy_install``:: easy_install python-jenkins The module has been packaged since Ubuntu Oneiric (11.10):: apt-get install python-jenkins For developpement purpose you can get a fake module installed on your system that will point to your working copy. Simply use:: python setup.py develop python-jenkins-0.2.1/jenkins/__init__.py0000644000000000000000000005444212202671451016403 0ustar 00000000000000#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2010, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # 'AS IS' AND ANY EXPRESS 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 OWNER OR CONTRIBUTORS 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. # # Authors: # Ken Conley # James Page # Tully Foote # Matthew Gertner ''' .. module:: jenkins :platform: Unix, Windows :synopsis: Python API to interact with Jenkins See examples at :doc:`example` ''' #import sys import urllib2 import urllib import base64 #import traceback import json import httplib LAUNCHER_SSH = 'hudson.plugins.sshslaves.SSHLauncher' LAUNCHER_COMMAND = 'hudson.slaves.CommandLauncher' LAUNCHER_WINDOWS_SERVICE = 'hudson.os.windows.ManagedWindowsServiceLauncher' INFO = 'api/json' JOB_INFO = 'job/%(name)s/api/json?depth=0' JOB_NAME = 'job/%(name)s/api/json?tree=name' Q_INFO = 'queue/api/json?depth=0' CANCEL_QUEUE = 'queue/item/%(number)s/cancelQueue' CREATE_JOB = 'createItem?name=%(name)s' # also post config.xml CONFIG_JOB = 'job/%(name)s/config.xml' DELETE_JOB = 'job/%(name)s/doDelete' ENABLE_JOB = 'job/%(name)s/enable' DISABLE_JOB = 'job/%(name)s/disable' COPY_JOB = 'createItem?name=%(to_name)s&mode=copy&from=%(from_name)s' RENAME_JOB = 'job/%(name)s/doRename?newName=%(new_name)s' BUILD_JOB = 'job/%(name)s/build' STOP_BUILD = 'job/%(name)s/%(number)s/stop' BUILD_WITH_PARAMS_JOB = 'job/%(name)s/buildWithParameters' BUILD_INFO = 'job/%(name)s/%(number)d/api/json?depth=0' BUILD_CONSOLE_OUTPUT = 'job/%(name)s/%(number)d/consoleText' CREATE_NODE = 'computer/doCreateItem?%s' DELETE_NODE = 'computer/%(name)s/doDelete' NODE_INFO = 'computer/%(name)s/api/json?depth=0' NODE_TYPE = 'hudson.slaves.DumbSlave$DescriptorImpl' TOGGLE_OFFLINE = 'computer/%(name)s/toggleOffline?offlineMessage=%(msg)s' #for testing only EMPTY_CONFIG_XML = ''' false true false false false ''' #for testing only RECONFIG_XML = ''' false true false false false export FOO=bar ''' class JenkinsException(Exception): ''' General exception type for jenkins-API-related failures. ''' pass def auth_headers(username, password): ''' Simple implementation of HTTP Basic Authentication. Returns the 'Authentication' header value. ''' return 'Basic ' + base64.encodestring('%s:%s' % (username, password))[:-1] class Jenkins(object): def __init__(self, url, username=None, password=None): ''' Create handle to Jenkins instance. All methods will raise :class:`JenkinsException` on failure. :param username: Server username, ``str`` :param password: Server password, ``str`` :param url: URL of Jenkins server, ``str`` ''' if url[-1] == '/': self.server = url else: self.server = url + '/' if username is not None and password is not None: self.auth = auth_headers(username, password) else: self.auth = None def get_job_info(self, name): ''' Get job information dictionary. :param name: Job name, ``str`` :returns: dictionary of job information ''' try: response = self.jenkins_open(urllib2.Request( self.server + JOB_INFO % locals())) if response: return json.loads(response) else: raise JenkinsException('job[%s] does not exist' % name) except urllib2.HTTPError: raise JenkinsException('job[%s] does not exist' % name) except ValueError: raise JenkinsException( "Could not parse JSON info for job[%s]" % name) def get_job_name(self, name): ''' Return the name of a job using the API. That is roughly an identity method which can be used to quickly verify a job exist or is accessible without causing too much stress on the server side. :param name: Job name, ``str`` :returns: Name of job or None ''' response = self.jenkins_open( urllib2.Request(self.server + JOB_NAME % locals())) if response: if json.loads(response)['name'] != name: raise JenkinsException( 'Jenkins returned an unexpected job name') return json.loads(response)['name'] else: return None def debug_job_info(self, job_name): ''' Print out job info in more readable format ''' for k, v in self.get_job_info(job_name).iteritems(): print k, v def jenkins_open(self, req): ''' Utility routine for opening an HTTP request to a Jenkins server. This should only be used to extends the :class:`Jenkins` API. ''' try: if self.auth: req.add_header('Authorization', self.auth) return urllib2.urlopen(req).read() except urllib2.HTTPError, e: # Jenkins's funky authentication means its nigh impossible to # distinguish errors. if e.code in [401, 403, 500]: raise JenkinsException( 'Error in request.' + 'Possibly authentication failed [%s]' % (e.code) ) # right now I'm getting 302 infinites on a successful delete def get_build_info(self, name, number): ''' Get build information dictionary. :param name: Job name, ``str`` :param name: Build number, ``int`` :returns: dictionary of build information, ``dict`` Example:: >>> next_build_number = j.get_job_info('build_name')['next_build_number'] >>> output = j.build_job('build_'+kwargs['vcs_server_type'], params) >>> sleep(10) >>> build_info = j.get_build_info('build_name', next_build_number) >>> print(build_info) {u'building': False, u'changeSet': {u'items': [{u'date': u'2011-12-19T18:01:52.540557Z', u'msg': u'test', u'revision': 66, u'user': u'unknown', u'paths': [{u'editType': u'edit', u'file': u'/branches/demo/index.html'}]}], u'kind': u'svn', u'revisions': [{u'module': u'http://eaas-svn01.i3.level3.com/eaas', u'revision': 66}]}, u'builtOn': u'', u'description': None, u'artifacts': [{u'relativePath': u'dist/eaas-87-2011-12-19_18-01-57.war', u'displayPath': u'eaas-87-2011-12-19_18-01-57.war', u'fileName': u'eaas-87-2011-12-19_18-01-57.war'}, {u'relativePath': u'dist/eaas-87-2011-12-19_18-01-57.war.zip', u'displayPath': u'eaas-87-2011-12-19_18-01-57.war.zip', u'fileName': u'eaas-87-2011-12-19_18-01-57.war.zip'}], u'timestamp': 1324317717000, u'number': 87, u'actions': [{u'parameters': [{u'name': u'SERVICE_NAME', u'value': u'eaas'}, {u'name': u'PROJECT_NAME', u'value': u'demo'}]}, {u'causes': [{u'userName': u'anonymous', u'shortDescription': u'Started by user anonymous'}]}, {}, {}, {}], u'id': u'2011-12-19_18-01-57', u'keepLog': False, u'url': u'http://eaas-jenkins01.i3.level3.com:9080/job/build_war/87/', u'culprits': [{u'absoluteUrl': u'http://eaas-jenkins01.i3.level3.com:9080/user/unknown', u'fullName': u'unknown'}], u'result': u'SUCCESS', u'duration': 8826, u'fullDisplayName': u'build_war #87'} ''' try: response = self.jenkins_open(urllib2.Request( self.server + BUILD_INFO % locals())) if response: return json.loads(response) else: raise JenkinsException('job[%s] number[%d] does not exist' % (name, number)) except urllib2.HTTPError: raise JenkinsException('job[%s] number[%d] does not exist' % (name, number)) except ValueError: raise JenkinsException( 'Could not parse JSON info for job[%s] number[%d]' % (name, number) ) def get_queue_info(self): ''' :returns: list of job dictionaries, ``[dict]`` Example:: >>> queue_info = j.get_queue_info() >>> print(queue_info[0]) {u'task': {u'url': u'http://your_url/job/my_job/', u'color': u'aborted_anime', u'name': u'my_job'}, u'stuck': False, u'actions': [{u'causes': [{u'shortDescription': u'Started by timer'}]}], u'buildable': False, u'params': u'', u'buildableStartMilliseconds': 1315087293316, u'why': u'Build #2,532 is already in progress (ETA:10 min)', u'blocked': True} ''' return json.loads(self.jenkins_open( urllib2.Request(self.server + Q_INFO) ))['items'] def cancel_queue(self, number): ''' Cancel a queued build. :param number: Jenkins queue number for the build, ``int`` ''' # Jenkins returns a 302 from this URL, unless Referer is not set, # then you get a 404. self.jenkins_open(urllib2.Request(self.server + CANCEL_QUEUE % locals(), headers={'Referer': self.server})) def get_info(self): """ Get information on this Master. This information includes job list and view information. :returns: dictionary of information about Master, ``dict`` Example:: >>> info = j.get_info() >>> jobs = info['jobs'] >>> print(jobs[0]) {u'url': u'http://your_url_here/job/my_job/', u'color': u'blue', u'name': u'my_job'} """ try: return json.loads(self.jenkins_open( urllib2.Request(self.server + INFO))) except urllib2.HTTPError: raise JenkinsException("Error communicating with server[%s]" % self.server) except httplib.BadStatusLine: raise JenkinsException("Error communicating with server[%s]" % self.server) except ValueError: raise JenkinsException("Could not parse JSON info for server[%s]" % self.server) def get_jobs(self): """ Get list of jobs running. Each job is a dictionary with 'name', 'url', and 'color' keys. :returns: list of jobs, ``[ { str: str} ]`` """ return self.get_info()['jobs'] def copy_job(self, from_name, to_name): ''' Copy a Jenkins job :param from_name: Name of Jenkins job to copy from, ``str`` :param to_name: Name of Jenkins job to copy to, ``str`` ''' self.get_job_info(from_name) self.jenkins_open(urllib2.Request( self.server + COPY_JOB % locals(), '')) if not self.job_exists(to_name): raise JenkinsException('create[%s] failed' % (to_name)) def rename_job(self, name, new_name): ''' Rename an existing Jenkins job :param name: Name of Jenkins job to rename, ``str`` :param new_name: New Jenkins job name, ``str`` ''' self.get_job_info(name) self.jenkins_open(urllib2.Request( self.server + RENAME_JOB % locals(), '')) if not self.job_exists(new_name): raise JenkinsException('rename[%s] failed'%(new_name)) def delete_job(self, name): ''' Delete Jenkins job permanently. :param name: Name of Jenkins job, ``str`` ''' self.get_job_info(name) self.jenkins_open(urllib2.Request( self.server + DELETE_JOB % locals(), '')) if self.job_exists(name): raise JenkinsException('delete[%s] failed' % (name)) def enable_job(self, name): ''' Enable Jenkins job. :param name: Name of Jenkins job, ``str`` ''' self.get_job_info(name) self.jenkins_open(urllib2.Request( self.server + ENABLE_JOB % locals(), '')) def disable_job(self, name): ''' Disable Jenkins job. To re-enable, call :meth:`Jenkins.enable_job`. :param name: Name of Jenkins job, ``str`` ''' self.get_job_info(name) self.jenkins_open(urllib2.Request( self.server + DISABLE_JOB % locals(), '')) def job_exists(self, name): ''' :param name: Name of Jenkins job, ``str`` :returns: ``True`` if Jenkins job exists ''' if self.get_job_name(name) == name: return True def create_job(self, name, config_xml): ''' Create a new Jenkins job :param name: Name of Jenkins job, ``str`` :param config_xml: config file text, ``str`` ''' if self.job_exists(name): raise JenkinsException('job[%s] already exists' % (name)) headers = {'Content-Type': 'text/xml'} self.jenkins_open(urllib2.Request( self.server + CREATE_JOB % locals(), config_xml, headers)) if not self.job_exists(name): raise JenkinsException('create[%s] failed' % (name)) def get_job_config(self, name): ''' Get configuration of existing Jenkins job. :param name: Name of Jenkins job, ``str`` :returns: job configuration (XML format) ''' request = urllib2.Request(self.server + CONFIG_JOB % {"name": urllib.quote(name)}) return self.jenkins_open(request) def reconfig_job(self, name, config_xml): ''' Change configuration of existing Jenkins job. To create a new job, see :meth:`Jenkins.create_job`. :param name: Name of Jenkins job, ``str`` :param config_xml: New XML configuration, ``str`` ''' self.get_job_info(name) headers = {'Content-Type': 'text/xml'} reconfig_url = self.server + CONFIG_JOB % locals() self.jenkins_open(urllib2.Request(reconfig_url, config_xml, headers)) def build_job_url(self, name, parameters=None, token=None): ''' Get URL to trigger build job. Authenticated setups may require configuring a token on the server side. :param parameters: parameters for job, or None., ``dict`` :param token: (optional) token for building job, ``str`` :returns: URL for building job ''' if parameters: if token: parameters['token'] = token return (self.server + BUILD_WITH_PARAMS_JOB % locals() + '?' + urllib.urlencode(parameters)) elif token: return (self.server + BUILD_JOB % locals() + '?' + urllib.urlencode({'token': token})) else: return self.server + BUILD_JOB % locals() def build_job(self, name, parameters=None, token=None): ''' Trigger build job. :param name: name of job :param parameters: parameters for job, or ``None``, ``dict`` :param token: Jenkins API token ''' if not self.job_exists(name): raise JenkinsException('no such job[%s]' % (name)) return self.jenkins_open(urllib2.Request( self.build_job_url(name, parameters, token))) def stop_build(self, name, number): ''' Stop a running Jenkins build. :param name: Name of Jenkins job, ``str`` :param number: Jenkins build number for the job, ``int`` ''' self.jenkins_open(urllib2.Request(self.server + STOP_BUILD % locals())) def get_node_info(self, name): ''' Get node information dictionary :param name: Node name, ``str`` :returns: Dictionary of node info, ``dict`` ''' try: response = self.jenkins_open(urllib2.Request( self.server + NODE_INFO % locals())) if response: return json.loads(response) else: raise JenkinsException('node[%s] does not exist' % name) except urllib2.HTTPError: raise JenkinsException('node[%s] does not exist' % name) except ValueError: raise JenkinsException("Could not parse JSON info for node[%s]" % name) def node_exists(self, name): ''' :param name: Name of Jenkins node, ``str`` :returns: ``True`` if Jenkins node exists ''' try: self.get_node_info(name) return True except JenkinsException: return False def delete_node(self, name): ''' Delete Jenkins node permanently. :param name: Name of Jenkins node, ``str`` ''' self.get_node_info(name) self.jenkins_open(urllib2.Request( self.server + DELETE_NODE % locals(), '')) if self.node_exists(name): raise JenkinsException('delete[%s] failed' % (name)) def disable_node(self, name, msg=''): ''' Disable a node :param name: Jenkins node name, ``str`` :param msg: Offline message, ``str`` ''' info = self.get_node_info(name) if info['offline']: return self.jenkins_open(urllib2.Request( self.server + TOGGLE_OFFLINE % locals())) def enable_node(self, name): ''' Enable a node :param name: Jenkins node name, ``str`` ''' info = self.get_node_info(name) if not info['offline']: return msg = '' self.jenkins_open(urllib2.Request( self.server + TOGGLE_OFFLINE % locals())) def create_node(self, name, numExecutors=2, nodeDescription=None, remoteFS='/var/lib/jenkins', labels=None, exclusive=False, launcher=LAUNCHER_COMMAND, launcher_params={}): ''' :param name: name of node to create, ``str`` :param numExecutors: number of executors for node, ``int`` :param nodeDescription: Description of node, ``str`` :param remoteFS: Remote filesystem location to use, ``str`` :param labels: Labels to associate with node, ``str`` :param exclusive: Use this node for tied jobs only, ``bool`` :param launcher: The launch method for the slave, ``jenkins.LAUNCHER_COMMAND``, ``jenkins.LAUNCHER_SSH``, ``jenkins.LAUNCHER_WINDOWS_SERVICE`` :param launcher_params: Additional parameters for the launcher, ``dict`` ''' if self.node_exists(name): raise JenkinsException('node[%s] already exists' % (name)) mode = 'NORMAL' if exclusive: mode = 'EXCLUSIVE' launcher_params['stapler-class'] = launcher inner_params = { 'name': name, 'nodeDescription': nodeDescription, 'numExecutors': numExecutors, 'remoteFS': remoteFS, 'labelString': labels, 'mode': mode, 'type': NODE_TYPE, 'retentionStrategy': { 'stapler-class': 'hudson.slaves.RetentionStrategy$Always' }, 'nodeProperties': {'stapler-class-bag': 'true'}, 'launcher': launcher_params } params = { 'name': name, 'type': NODE_TYPE, 'json': json.dumps(inner_params) } self.jenkins_open(urllib2.Request( self.server + CREATE_NODE % urllib.urlencode(params))) if not self.node_exists(name): raise JenkinsException('create[%s] failed' % (name)) def get_build_console_output(self, name, number): ''' Get build console text. :param name: Job name, ``str`` :param name: Build number, ``int`` :returns: Build console output, ``str`` ''' try: response = self.jenkins_open(urllib2.Request( self.server + BUILD_CONSOLE_OUTPUT % locals())) if response: return response else: raise JenkinsException('job[%s] number[%d] does not exist' % (name, number)) except urllib2.HTTPError: raise JenkinsException('job[%s] number[%d] does not exist' % (name, number)) except ValueError: raise JenkinsException( 'Could not parse JSON info for job[%s] number[%d]' % (name, number) ) python-jenkins-0.2.1/tests/__init__.py0000644000000000000000000000000012202671451016061 0ustar 00000000000000python-jenkins-0.2.1/tests/helper.py0000644000000000000000000000011712202671451015612 0ustar 00000000000000import os import sys sys.path.insert(0, os.path.abspath('..')) import jenkins python-jenkins-0.2.1/tests/test_jenkins.py0000644000000000000000000000107412202671451017036 0ustar 00000000000000import unittest from mock import patch from helper import jenkins class JenkinsTest(unittest.TestCase): @patch.object(jenkins.Jenkins, 'jenkins_open') def test_get_job_config_encodes_job_name(self, jenkins_mock): """ The job name parameter specified should be urlencoded properly. """ j = jenkins.Jenkins('http://example.com/', 'test', 'test') j.get_job_config(u'Test Job') self.assertEqual(jenkins_mock.call_args[0][0].get_full_url(), u'http://example.com/job/Test%20Job/config.xml')