├── .gitignore
├── LICENSE
├── README.md
├── agent.py
└── distribute_setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 |
3 | # C extensions
4 | *.so
5 |
6 | # Packages
7 | *.egg
8 | *.egg-info
9 | dist
10 | build
11 | eggs
12 | parts
13 | bin
14 | var
15 | sdist
16 | develop-eggs
17 | .installed.cfg
18 | lib
19 | lib64
20 |
21 | # Installer logs
22 | pip-log.txt
23 |
24 | # Unit test / coverage reports
25 | .coverage
26 | .tox
27 | nosetests.xml
28 |
29 | # Translations
30 | *.mo
31 |
32 | # Mr Developer
33 | .mr.developer.cfg
34 | .project
35 | .pydevproject
36 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and
10 | distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright
13 | owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all other entities
16 | that control, are controlled by, or are under common control with that entity.
17 | For the purposes of this definition, "control" means (i) the power, direct or
18 | indirect, to cause the direction or management of such entity, whether by
19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 | outstanding shares, or (iii) beneficial ownership of such entity.
21 |
22 | "You" (or "Your") shall mean an individual or Legal Entity exercising
23 | permissions granted by this License.
24 |
25 | "Source" form shall mean the preferred form for making modifications, including
26 | but not limited to software source code, documentation source, and configuration
27 | files.
28 |
29 | "Object" form shall mean any form resulting from mechanical transformation or
30 | translation of a Source form, including but not limited to compiled object code,
31 | generated documentation, and conversions to other media types.
32 |
33 | "Work" shall mean the work of authorship, whether in Source or Object form, made
34 | available under the License, as indicated by a copyright notice that is included
35 | in or attached to the work (an example is provided in the Appendix below).
36 |
37 | "Derivative Works" shall mean any work, whether in Source or Object form, that
38 | is based on (or derived from) the Work and for which the editorial revisions,
39 | annotations, elaborations, or other modifications represent, as a whole, an
40 | original work of authorship. For the purposes of this License, Derivative Works
41 | shall not include works that remain separable from, or merely link (or bind by
42 | name) to the interfaces of, the Work and Derivative Works thereof.
43 |
44 | "Contribution" shall mean any work of authorship, including the original version
45 | of the Work and any modifications or additions to that Work or Derivative Works
46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
47 | by the copyright owner or by an individual or Legal Entity authorized to submit
48 | on behalf of the copyright owner. For the purposes of this definition,
49 | "submitted" means any form of electronic, verbal, or written communication sent
50 | to the Licensor or its representatives, including but not limited to
51 | communication on electronic mailing lists, source code control systems, and
52 | issue tracking systems that are managed by, or on behalf of, the Licensor for
53 | the purpose of discussing and improving the Work, but excluding communication
54 | that is conspicuously marked or otherwise designated in writing by the copyright
55 | owner as "Not a Contribution."
56 |
57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58 | of whom a Contribution has been received by Licensor and subsequently
59 | incorporated within the Work.
60 |
61 | 2. Grant of Copyright License.
62 |
63 | Subject to the terms and conditions of this License, each Contributor hereby
64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65 | irrevocable copyright license to reproduce, prepare Derivative Works of,
66 | publicly display, publicly perform, sublicense, and distribute the Work and such
67 | Derivative Works in Source or Object form.
68 |
69 | 3. Grant of Patent License.
70 |
71 | Subject to the terms and conditions of this License, each Contributor hereby
72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73 | irrevocable (except as stated in this section) patent license to make, have
74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75 | such license applies only to those patent claims licensable by such Contributor
76 | that are necessarily infringed by their Contribution(s) alone or by combination
77 | of their Contribution(s) with the Work to which such Contribution(s) was
78 | submitted. If You institute patent litigation against any entity (including a
79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80 | Contribution incorporated within the Work constitutes direct or contributory
81 | patent infringement, then any patent licenses granted to You under this License
82 | for that Work shall terminate as of the date such litigation is filed.
83 |
84 | 4. Redistribution.
85 |
86 | You may reproduce and distribute copies of the Work or Derivative Works thereof
87 | in any medium, with or without modifications, and in Source or Object form,
88 | provided that You meet the following conditions:
89 |
90 | You must give any other recipients of the Work or Derivative Works a copy of
91 | this License; and
92 | You must cause any modified files to carry prominent notices stating that You
93 | changed the files; and
94 | You must retain, in the Source form of any Derivative Works that You distribute,
95 | all copyright, patent, trademark, and attribution notices from the Source form
96 | of the Work, excluding those notices that do not pertain to any part of the
97 | Derivative Works; and
98 | If the Work includes a "NOTICE" text file as part of its distribution, then any
99 | Derivative Works that You distribute must include a readable copy of the
100 | attribution notices contained within such NOTICE file, excluding those notices
101 | that do not pertain to any part of the Derivative Works, in at least one of the
102 | following places: within a NOTICE text file distributed as part of the
103 | Derivative Works; within the Source form or documentation, if provided along
104 | with the Derivative Works; or, within a display generated by the Derivative
105 | Works, if and wherever such third-party notices normally appear. The contents of
106 | the NOTICE file are for informational purposes only and do not modify the
107 | License. You may add Your own attribution notices within Derivative Works that
108 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
109 | provided that such additional attribution notices cannot be construed as
110 | modifying the License.
111 | You may add Your own copyright statement to Your modifications and may provide
112 | additional or different license terms and conditions for use, reproduction, or
113 | distribution of Your modifications, or for any such Derivative Works as a whole,
114 | provided Your use, reproduction, and distribution of the Work otherwise complies
115 | with the conditions stated in this License.
116 |
117 | 5. Submission of Contributions.
118 |
119 | Unless You explicitly state otherwise, any Contribution intentionally submitted
120 | for inclusion in the Work by You to the Licensor shall be under the terms and
121 | conditions of this License, without any additional terms or conditions.
122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
123 | any separate license agreement you may have executed with Licensor regarding
124 | such Contributions.
125 |
126 | 6. Trademarks.
127 |
128 | This License does not grant permission to use the trade names, trademarks,
129 | service marks, or product names of the Licensor, except as required for
130 | reasonable and customary use in describing the origin of the Work and
131 | reproducing the content of the NOTICE file.
132 |
133 | 7. Disclaimer of Warranty.
134 |
135 | Unless required by applicable law or agreed to in writing, Licensor provides the
136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138 | including, without limitation, any warranties or conditions of TITLE,
139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140 | solely responsible for determining the appropriateness of using or
141 | redistributing the Work and assume any risks associated with Your exercise of
142 | permissions under this License.
143 |
144 | 8. Limitation of Liability.
145 |
146 | In no event and under no legal theory, whether in tort (including negligence),
147 | contract, or otherwise, unless required by applicable law (such as deliberate
148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
149 | liable to You for damages, including any direct, indirect, special, incidental,
150 | or consequential damages of any character arising as a result of this License or
151 | out of the use or inability to use the Work (including but not limited to
152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153 | any and all other commercial damages or losses), even if such Contributor has
154 | been advised of the possibility of such damages.
155 |
156 | 9. Accepting Warranty or Additional Liability.
157 |
158 | While redistributing the Work or Derivative Works thereof, You may choose to
159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160 | other liability obligations and/or rights consistent with this License. However,
161 | in accepting such obligations, You may act only on Your own behalf and on Your
162 | sole responsibility, not on behalf of any other Contributor, and only if You
163 | agree to indemnify, defend, and hold each Contributor harmless for any liability
164 | incurred by, or claims asserted against, such Contributor by reason of your
165 | accepting any such warranty or additional liability.
166 |
167 | END OF TERMS AND CONDITIONS
168 |
169 | APPENDIX: How to apply the Apache License to your work
170 |
171 | To apply the Apache License to your work, attach the following boilerplate
172 | notice, with the fields enclosed by brackets "[]" replaced with your own
173 | identifying information. (Don't include the brackets!) The text should be
174 | enclosed in the appropriate comment syntax for the file format. We also
175 | recommend that a file or class name and description of purpose be included on
176 | the same "printed page" as the copyright notice for easier identification within
177 | third-party archives.
178 |
179 | Copyright [yyyy] [name of copyright owner]
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | http://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
192 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | py_agent
2 | ========
3 |
4 | ### Just getting started w/ Python Agent
5 |
6 | So we're going to try to use Flask for the Python Agent. Flask is a microframework for Python based on Werkzeug and Jinja 2. We'll also be using Flask-RESTful an extension to Flask. Obviously this is all subject to change, but this can be a good start for the Python Agent. Flask depends on two external libraries, Werkzeug and Jinja2. Werkzeug is a toolkit for WSGI, the standard Python interface between web applications and a variety of servers for both development and deployment. Jinja2 renders templates. So how do we get all that installed simply and quickly. There are a couple ways to do this, but probably the best way is to do a virtualenv(virtual environment). Most of the information described can be found on the Flask docs site.
7 |
8 | ###virtualenv and installing Flask
9 |
10 | Virtualenv enables multiple side-by-side installations of Python, one for each project. It doesn’t actually install separate copies of Python, but it does provide a great way to keep different project environments isolated. See below how a virtualenv works.
11 |
12 | If you are on Mac OS X or Linux, chances are that one of the following two commands will work for you:
13 |
14 | ```
15 | $ sudo easy_install virtualenv
16 | ```
17 |
18 | or
19 |
20 | ```
21 | $ sudo pip install virtualenv
22 | ```
23 |
24 | One of these will probably install virtualenv on your system. Maybe it’s even in your package manager. If you use Ubuntu, try:
25 |
26 | ```
27 | $ sudo apt-get install python-virtualenv
28 | ```
29 |
30 | If you are using Windows please scroll down to the Windows Users section to see how to install.
31 |
32 | Once you have the virtualenv installed, open up terminal (aka a shell) and create your own environment. You can create a project folder then a venv folder within that folder:
33 |
34 | ```
35 | $ mkdir myproject
36 | $ cd myproject
37 | $ virtualenv venv
38 | New python executable in venv/bin/python
39 | Installing distribute............done.
40 | ```
41 |
42 | Ok, whenever you want to work on a project, you only have to activate the corresponding environment. On OS X and Linux, do the following:
43 |
44 | ```
45 | $ . venv/bin/activate
46 | ```
47 |
48 | If you are a Windows user, use the following command:
49 |
50 | ```
51 | $ venv\scripts\activate
52 | ```
53 |
54 | Now, you should now be using your virtualenv (notice how the prompt of your shell has changed to show the active environment).
55 |
56 | Now you can just enter the following command to get Flask activated in your virtualenv:
57 |
58 | ```
59 | $ pip install Flask
60 | ```
61 |
62 | And there you go, at least with getting Flask installed. Next we'll need to install Flask-RESTful.
63 |
64 | ###installing Flask-RESTful
65 |
66 | Install Flask-RESTful with pip
67 |
68 | ```
69 | pip install flask-restful
70 | ```
71 |
72 | Flask-RESTful has the following dependencies (which will be automatically installed if you use pip):
73 |
74 | Flask version 0.8 or greater
75 | Flask-RESTful requires Python version 2.6, 2.7, or 3.3.
76 |
77 | Now, after all that is done, we are ready to start the Agent. To do this make sure you are in the project folder that we created above and make sure you have activated your virtual environment. Now run the command below:
78 |
79 | ```
80 | python agent.py
81 | ```
82 |
83 | There you have it! Your agent should be running at 127.0.0.1:5000 (aka http://localhost:5000)
84 |
85 | ###Windows Users
86 |
87 | On Windows, installation of easy_install is a little bit trickier, but still quite easy. The easiest way to do it is to download the distribute_setup.py file and run it. The easiest way to run the file is to open your downloads folder and double-click on the file.
88 |
89 | Next, add the easy_install command and other Python scripts to the command search path, by adding your Python installation’s Scripts folder to the PATH environment variable. To do that, right-click on the “Computer” icon on the Desktop or in the Start menu, and choose “Properties”. Then click on “Advanced System settings” (in Windows XP, click on the “Advanced” tab instead). Then click on the “Environment variables” button. Finally, double-click on the “Path” variable in the “System variables” section, and add the path of your Python interpreter’s Scripts folder. Be sure to delimit it from existing values with a semicolon. Assuming you are using Python 2.7 on the default path, add the following value:
90 |
91 | ```
92 | ;C:\Python27\Scripts
93 | ```
94 |
95 | And you got it! To check that it worked, open the Command Prompt and execute easy_install. If you have User Account Control enabled on Windows Vista or Windows 7, it should prompt you for administrator privileges.
96 |
97 | Now that you have easy_install, you can use it to install pip:
98 |
99 | ```
100 | > easy_install pip
101 | ```
102 |
--------------------------------------------------------------------------------
/agent.py:
--------------------------------------------------------------------------------
1 | # needs: pip install python-simplexml
2 | from simplexml import dumps
3 | from flask import make_response, Flask
4 | from flask.ext.restful import Api, Resource
5 |
6 | def output_xml(data, code, headers=None):
7 | """Makes a Flask response with a XML encoded body"""
8 | resp = make_response(dumps({'response' :data}), code)
9 | resp.headers.extend(headers or {})
10 | return resp
11 |
12 | app = Flask(__name__)
13 | api = Api(app, default_mediatype='application/xml')
14 | api.representations['application/xml'] = output_xml
15 |
16 |
17 | class Hello(Resource):
18 | """
19 | # you need requests
20 | >>> from requests import get
21 | >>> get('http://localhost:5000/me').content # default_mediatype
22 | 'me'
23 | >>> get('http://localhost:5000/me', headers={"accept":"application/json"}).content
24 | '{"hello": "me"}'
25 | >>> get('http://localhost:5000/me', headers={"accept":"application/xml"}).content
26 | 'me'
27 | """
28 | def get(self, entry):
29 | return {'hello': entry}
30 |
31 | api.add_resource(Hello, '/')
32 |
33 | if __name__ == '__main__':
34 | app.run(debug=True)
35 |
--------------------------------------------------------------------------------
/distribute_setup.py:
--------------------------------------------------------------------------------
1 | #!python
2 | """Bootstrap distribute installation
3 |
4 | If you want to use setuptools in your package's setup.py, just include this
5 | file in the same directory with it, and add this to the top of your setup.py::
6 |
7 | from distribute_setup import use_setuptools
8 | use_setuptools()
9 |
10 | If you want to require a specific version of setuptools, set a download
11 | mirror, or use an alternate download directory, you can do so by supplying
12 | the appropriate options to ``use_setuptools()``.
13 |
14 | This file can also be run as a script to install or upgrade setuptools.
15 | """
16 | import os
17 | import shutil
18 | import sys
19 | import time
20 | import fnmatch
21 | import tempfile
22 | import tarfile
23 | import optparse
24 |
25 | from distutils import log
26 |
27 | try:
28 | from site import USER_SITE
29 | except ImportError:
30 | USER_SITE = None
31 |
32 | try:
33 | import subprocess
34 |
35 | def _python_cmd(*args):
36 | args = (sys.executable,) + args
37 | return subprocess.call(args) == 0
38 |
39 | except ImportError:
40 | # will be used for python 2.3
41 | def _python_cmd(*args):
42 | args = (sys.executable,) + args
43 | # quoting arguments if windows
44 | if sys.platform == 'win32':
45 | def quote(arg):
46 | if ' ' in arg:
47 | return '"%s"' % arg
48 | return arg
49 | args = [quote(arg) for arg in args]
50 | return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
51 |
52 | DEFAULT_VERSION = "0.6.49"
53 | DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
54 | SETUPTOOLS_FAKED_VERSION = "0.6c11"
55 |
56 | SETUPTOOLS_PKG_INFO = """\
57 | Metadata-Version: 1.0
58 | Name: setuptools
59 | Version: %s
60 | Summary: xxxx
61 | Home-page: xxx
62 | Author: xxx
63 | Author-email: xxx
64 | License: xxx
65 | Description: xxx
66 | """ % SETUPTOOLS_FAKED_VERSION
67 |
68 |
69 | def _install(tarball, install_args=()):
70 | # extracting the tarball
71 | tmpdir = tempfile.mkdtemp()
72 | log.warn('Extracting in %s', tmpdir)
73 | old_wd = os.getcwd()
74 | try:
75 | os.chdir(tmpdir)
76 | tar = tarfile.open(tarball)
77 | _extractall(tar)
78 | tar.close()
79 |
80 | # going in the directory
81 | subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
82 | os.chdir(subdir)
83 | log.warn('Now working in %s', subdir)
84 |
85 | # installing
86 | log.warn('Installing Distribute')
87 | if not _python_cmd('setup.py', 'install', *install_args):
88 | log.warn('Something went wrong during the installation.')
89 | log.warn('See the error message above.')
90 | # exitcode will be 2
91 | return 2
92 | finally:
93 | os.chdir(old_wd)
94 | shutil.rmtree(tmpdir)
95 |
96 |
97 | def _build_egg(egg, tarball, to_dir):
98 | # extracting the tarball
99 | tmpdir = tempfile.mkdtemp()
100 | log.warn('Extracting in %s', tmpdir)
101 | old_wd = os.getcwd()
102 | try:
103 | os.chdir(tmpdir)
104 | tar = tarfile.open(tarball)
105 | _extractall(tar)
106 | tar.close()
107 |
108 | # going in the directory
109 | subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
110 | os.chdir(subdir)
111 | log.warn('Now working in %s', subdir)
112 |
113 | # building an egg
114 | log.warn('Building a Distribute egg in %s', to_dir)
115 | _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
116 |
117 | finally:
118 | os.chdir(old_wd)
119 | shutil.rmtree(tmpdir)
120 | # returning the result
121 | log.warn(egg)
122 | if not os.path.exists(egg):
123 | raise IOError('Could not build the egg.')
124 |
125 |
126 | def _do_download(version, download_base, to_dir, download_delay):
127 | egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
128 | % (version, sys.version_info[0], sys.version_info[1]))
129 | if not os.path.exists(egg):
130 | tarball = download_setuptools(version, download_base,
131 | to_dir, download_delay)
132 | _build_egg(egg, tarball, to_dir)
133 | sys.path.insert(0, egg)
134 | import setuptools
135 | setuptools.bootstrap_install_from = egg
136 |
137 |
138 | def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
139 | to_dir=os.curdir, download_delay=15, no_fake=True):
140 | # making sure we use the absolute path
141 | to_dir = os.path.abspath(to_dir)
142 | was_imported = 'pkg_resources' in sys.modules or \
143 | 'setuptools' in sys.modules
144 | try:
145 | try:
146 | import pkg_resources
147 |
148 | # Setuptools 0.7b and later is a suitable (and preferable)
149 | # substitute for any Distribute version.
150 | try:
151 | pkg_resources.require("setuptools>=0.7b")
152 | return
153 | except (pkg_resources.DistributionNotFound,
154 | pkg_resources.VersionConflict):
155 | pass
156 |
157 | if not hasattr(pkg_resources, '_distribute'):
158 | if not no_fake:
159 | _fake_setuptools()
160 | raise ImportError
161 | except ImportError:
162 | return _do_download(version, download_base, to_dir, download_delay)
163 | try:
164 | pkg_resources.require("distribute>=" + version)
165 | return
166 | except pkg_resources.VersionConflict:
167 | e = sys.exc_info()[1]
168 | if was_imported:
169 | sys.stderr.write(
170 | "The required version of distribute (>=%s) is not available,\n"
171 | "and can't be installed while this script is running. Please\n"
172 | "install a more recent version first, using\n"
173 | "'easy_install -U distribute'."
174 | "\n\n(Currently using %r)\n" % (version, e.args[0]))
175 | sys.exit(2)
176 | else:
177 | del pkg_resources, sys.modules['pkg_resources'] # reload ok
178 | return _do_download(version, download_base, to_dir,
179 | download_delay)
180 | except pkg_resources.DistributionNotFound:
181 | return _do_download(version, download_base, to_dir,
182 | download_delay)
183 | finally:
184 | if not no_fake:
185 | _create_fake_setuptools_pkg_info(to_dir)
186 |
187 |
188 | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
189 | to_dir=os.curdir, delay=15):
190 | """Download distribute from a specified location and return its filename
191 |
192 | `version` should be a valid distribute version number that is available
193 | as an egg for download under the `download_base` URL (which should end
194 | with a '/'). `to_dir` is the directory where the egg will be downloaded.
195 | `delay` is the number of seconds to pause before an actual download
196 | attempt.
197 | """
198 | # making sure we use the absolute path
199 | to_dir = os.path.abspath(to_dir)
200 | try:
201 | from urllib.request import urlopen
202 | except ImportError:
203 | from urllib2 import urlopen
204 | tgz_name = "distribute-%s.tar.gz" % version
205 | url = download_base + tgz_name
206 | saveto = os.path.join(to_dir, tgz_name)
207 | src = dst = None
208 | if not os.path.exists(saveto): # Avoid repeated downloads
209 | try:
210 | log.warn("Downloading %s", url)
211 | src = urlopen(url)
212 | # Read/write all in one block, so we don't create a corrupt file
213 | # if the download is interrupted.
214 | data = src.read()
215 | dst = open(saveto, "wb")
216 | dst.write(data)
217 | finally:
218 | if src:
219 | src.close()
220 | if dst:
221 | dst.close()
222 | return os.path.realpath(saveto)
223 |
224 |
225 | def _no_sandbox(function):
226 | def __no_sandbox(*args, **kw):
227 | try:
228 | from setuptools.sandbox import DirectorySandbox
229 | if not hasattr(DirectorySandbox, '_old'):
230 | def violation(*args):
231 | pass
232 | DirectorySandbox._old = DirectorySandbox._violation
233 | DirectorySandbox._violation = violation
234 | patched = True
235 | else:
236 | patched = False
237 | except ImportError:
238 | patched = False
239 |
240 | try:
241 | return function(*args, **kw)
242 | finally:
243 | if patched:
244 | DirectorySandbox._violation = DirectorySandbox._old
245 | del DirectorySandbox._old
246 |
247 | return __no_sandbox
248 |
249 |
250 | def _patch_file(path, content):
251 | """Will backup the file then patch it"""
252 | f = open(path)
253 | existing_content = f.read()
254 | f.close()
255 | if existing_content == content:
256 | # already patched
257 | log.warn('Already patched.')
258 | return False
259 | log.warn('Patching...')
260 | _rename_path(path)
261 | f = open(path, 'w')
262 | try:
263 | f.write(content)
264 | finally:
265 | f.close()
266 | return True
267 |
268 | _patch_file = _no_sandbox(_patch_file)
269 |
270 |
271 | def _same_content(path, content):
272 | f = open(path)
273 | existing_content = f.read()
274 | f.close()
275 | return existing_content == content
276 |
277 |
278 | def _rename_path(path):
279 | new_name = path + '.OLD.%s' % time.time()
280 | log.warn('Renaming %s to %s', path, new_name)
281 | os.rename(path, new_name)
282 | return new_name
283 |
284 |
285 | def _remove_flat_installation(placeholder):
286 | if not os.path.isdir(placeholder):
287 | log.warn('Unkown installation at %s', placeholder)
288 | return False
289 | found = False
290 | for file in os.listdir(placeholder):
291 | if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
292 | found = True
293 | break
294 | if not found:
295 | log.warn('Could not locate setuptools*.egg-info')
296 | return
297 |
298 | log.warn('Moving elements out of the way...')
299 | pkg_info = os.path.join(placeholder, file)
300 | if os.path.isdir(pkg_info):
301 | patched = _patch_egg_dir(pkg_info)
302 | else:
303 | patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
304 |
305 | if not patched:
306 | log.warn('%s already patched.', pkg_info)
307 | return False
308 | # now let's move the files out of the way
309 | for element in ('setuptools', 'pkg_resources.py', 'site.py'):
310 | element = os.path.join(placeholder, element)
311 | if os.path.exists(element):
312 | _rename_path(element)
313 | else:
314 | log.warn('Could not find the %s element of the '
315 | 'Setuptools distribution', element)
316 | return True
317 |
318 | _remove_flat_installation = _no_sandbox(_remove_flat_installation)
319 |
320 |
321 | def _after_install(dist):
322 | log.warn('After install bootstrap.')
323 | placeholder = dist.get_command_obj('install').install_purelib
324 | _create_fake_setuptools_pkg_info(placeholder)
325 |
326 |
327 | def _create_fake_setuptools_pkg_info(placeholder):
328 | if not placeholder or not os.path.exists(placeholder):
329 | log.warn('Could not find the install location')
330 | return
331 | pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
332 | setuptools_file = 'setuptools-%s-py%s.egg-info' % \
333 | (SETUPTOOLS_FAKED_VERSION, pyver)
334 | pkg_info = os.path.join(placeholder, setuptools_file)
335 | if os.path.exists(pkg_info):
336 | log.warn('%s already exists', pkg_info)
337 | return
338 |
339 | log.warn('Creating %s', pkg_info)
340 | try:
341 | f = open(pkg_info, 'w')
342 | except EnvironmentError:
343 | log.warn("Don't have permissions to write %s, skipping", pkg_info)
344 | return
345 | try:
346 | f.write(SETUPTOOLS_PKG_INFO)
347 | finally:
348 | f.close()
349 |
350 | pth_file = os.path.join(placeholder, 'setuptools.pth')
351 | log.warn('Creating %s', pth_file)
352 | f = open(pth_file, 'w')
353 | try:
354 | f.write(os.path.join(os.curdir, setuptools_file))
355 | finally:
356 | f.close()
357 |
358 | _create_fake_setuptools_pkg_info = _no_sandbox(
359 | _create_fake_setuptools_pkg_info
360 | )
361 |
362 |
363 | def _patch_egg_dir(path):
364 | # let's check if it's already patched
365 | pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
366 | if os.path.exists(pkg_info):
367 | if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
368 | log.warn('%s already patched.', pkg_info)
369 | return False
370 | _rename_path(path)
371 | os.mkdir(path)
372 | os.mkdir(os.path.join(path, 'EGG-INFO'))
373 | pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
374 | f = open(pkg_info, 'w')
375 | try:
376 | f.write(SETUPTOOLS_PKG_INFO)
377 | finally:
378 | f.close()
379 | return True
380 |
381 | _patch_egg_dir = _no_sandbox(_patch_egg_dir)
382 |
383 |
384 | def _before_install():
385 | log.warn('Before install bootstrap.')
386 | _fake_setuptools()
387 |
388 |
389 | def _under_prefix(location):
390 | if 'install' not in sys.argv:
391 | return True
392 | args = sys.argv[sys.argv.index('install') + 1:]
393 | for index, arg in enumerate(args):
394 | for option in ('--root', '--prefix'):
395 | if arg.startswith('%s=' % option):
396 | top_dir = arg.split('root=')[-1]
397 | return location.startswith(top_dir)
398 | elif arg == option:
399 | if len(args) > index:
400 | top_dir = args[index + 1]
401 | return location.startswith(top_dir)
402 | if arg == '--user' and USER_SITE is not None:
403 | return location.startswith(USER_SITE)
404 | return True
405 |
406 |
407 | def _fake_setuptools():
408 | log.warn('Scanning installed packages')
409 | try:
410 | import pkg_resources
411 | except ImportError:
412 | # we're cool
413 | log.warn('Setuptools or Distribute does not seem to be installed.')
414 | return
415 | ws = pkg_resources.working_set
416 | try:
417 | setuptools_dist = ws.find(
418 | pkg_resources.Requirement.parse('setuptools', replacement=False)
419 | )
420 | except TypeError:
421 | # old distribute API
422 | setuptools_dist = ws.find(
423 | pkg_resources.Requirement.parse('setuptools')
424 | )
425 |
426 | if setuptools_dist is None:
427 | log.warn('No setuptools distribution found')
428 | return
429 | # detecting if it was already faked
430 | setuptools_location = setuptools_dist.location
431 | log.warn('Setuptools installation detected at %s', setuptools_location)
432 |
433 | # if --root or --preix was provided, and if
434 | # setuptools is not located in them, we don't patch it
435 | if not _under_prefix(setuptools_location):
436 | log.warn('Not patching, --root or --prefix is installing Distribute'
437 | ' in another location')
438 | return
439 |
440 | # let's see if its an egg
441 | if not setuptools_location.endswith('.egg'):
442 | log.warn('Non-egg installation')
443 | res = _remove_flat_installation(setuptools_location)
444 | if not res:
445 | return
446 | else:
447 | log.warn('Egg installation')
448 | pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
449 | if (os.path.exists(pkg_info) and
450 | _same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
451 | log.warn('Already patched.')
452 | return
453 | log.warn('Patching...')
454 | # let's create a fake egg replacing setuptools one
455 | res = _patch_egg_dir(setuptools_location)
456 | if not res:
457 | return
458 | log.warn('Patching complete.')
459 | _relaunch()
460 |
461 |
462 | def _relaunch():
463 | log.warn('Relaunching...')
464 | # we have to relaunch the process
465 | # pip marker to avoid a relaunch bug
466 | _cmd1 = ['-c', 'install', '--single-version-externally-managed']
467 | _cmd2 = ['-c', 'install', '--record']
468 | if sys.argv[:3] == _cmd1 or sys.argv[:3] == _cmd2:
469 | sys.argv[0] = 'setup.py'
470 | args = [sys.executable] + sys.argv
471 | sys.exit(subprocess.call(args))
472 |
473 |
474 | def _extractall(self, path=".", members=None):
475 | """Extract all members from the archive to the current working
476 | directory and set owner, modification time and permissions on
477 | directories afterwards. `path' specifies a different directory
478 | to extract to. `members' is optional and must be a subset of the
479 | list returned by getmembers().
480 | """
481 | import copy
482 | import operator
483 | from tarfile import ExtractError
484 | directories = []
485 |
486 | if members is None:
487 | members = self
488 |
489 | for tarinfo in members:
490 | if tarinfo.isdir():
491 | # Extract directories with a safe mode.
492 | directories.append(tarinfo)
493 | tarinfo = copy.copy(tarinfo)
494 | tarinfo.mode = 448 # decimal for oct 0700
495 | self.extract(tarinfo, path)
496 |
497 | # Reverse sort directories.
498 | if sys.version_info < (2, 4):
499 | def sorter(dir1, dir2):
500 | return cmp(dir1.name, dir2.name)
501 | directories.sort(sorter)
502 | directories.reverse()
503 | else:
504 | directories.sort(key=operator.attrgetter('name'), reverse=True)
505 |
506 | # Set correct owner, mtime and filemode on directories.
507 | for tarinfo in directories:
508 | dirpath = os.path.join(path, tarinfo.name)
509 | try:
510 | self.chown(tarinfo, dirpath)
511 | self.utime(tarinfo, dirpath)
512 | self.chmod(tarinfo, dirpath)
513 | except ExtractError:
514 | e = sys.exc_info()[1]
515 | if self.errorlevel > 1:
516 | raise
517 | else:
518 | self._dbg(1, "tarfile: %s" % e)
519 |
520 |
521 | def _build_install_args(options):
522 | """
523 | Build the arguments to 'python setup.py install' on the distribute package
524 | """
525 | install_args = []
526 | if options.user_install:
527 | if sys.version_info < (2, 6):
528 | log.warn("--user requires Python 2.6 or later")
529 | raise SystemExit(1)
530 | install_args.append('--user')
531 | return install_args
532 |
533 | def _parse_args():
534 | """
535 | Parse the command line for options
536 | """
537 | parser = optparse.OptionParser()
538 | parser.add_option(
539 | '--user', dest='user_install', action='store_true', default=False,
540 | help='install in user site package (requires Python 2.6 or later)')
541 | parser.add_option(
542 | '--download-base', dest='download_base', metavar="URL",
543 | default=DEFAULT_URL,
544 | help='alternative URL from where to download the distribute package')
545 | options, args = parser.parse_args()
546 | # positional arguments are ignored
547 | return options
548 |
549 | def main(version=DEFAULT_VERSION):
550 | """Install or upgrade setuptools and EasyInstall"""
551 | options = _parse_args()
552 | tarball = download_setuptools(download_base=options.download_base)
553 | return _install(tarball, _build_install_args(options))
554 |
555 | if __name__ == '__main__':
556 | sys.exit(main())
--------------------------------------------------------------------------------