├── .gitignore
├── COPYING
├── ChangeLog
├── MANIFEST.in
├── README.rst
├── docs
├── api
│ ├── linesman.backends.rst
│ ├── linesman.middleware.rst
│ └── linesman.rst
├── changelog.rst
├── conf.py
├── glossary.rst
├── index.rst
└── narr
│ ├── configuration.rst
│ ├── django_notes.rst
│ └── getting_started.rst
├── examples
├── callgraph.png
├── profile-with-pie-chart.png
├── profile.png
└── session_listing.png
├── ez_setup.py
├── linesman
├── __init__.py
├── backends
│ ├── __init__.py
│ ├── base.py
│ ├── pickle.py
│ └── sqlite.py
├── media
│ ├── css
│ │ ├── list.css
│ │ └── tree.css
│ ├── images
│ │ ├── back_disabled.jpg
│ │ ├── back_enabled.jpg
│ │ ├── closed.gif
│ │ ├── forward_disabled.jpg
│ │ ├── forward_enabled.jpg
│ │ ├── open.gif
│ │ ├── sort_asc.png
│ │ ├── sort_asc_disabled.png
│ │ ├── sort_both.png
│ │ ├── sort_desc.png
│ │ └── sort_desc_disabled.png
│ └── js
│ │ ├── accordian.js
│ │ ├── highcharts.js
│ │ ├── jquery-1.5.2.min.js
│ │ ├── jquery.dataTables.min.js
│ │ └── tables.js
├── middleware.py
├── templates
│ ├── list.tmpl
│ └── tree.tmpl
└── tests
│ ├── __init__.py
│ ├── backends
│ ├── __init__.py
│ ├── test_backend_base.py
│ ├── test_backend_pickle.py
│ └── test_backend_sqlite.py
│ ├── test_graphs.py
│ ├── test_linesman_profiler.py
│ └── test_middleware.py
├── setup.cfg
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.egg
2 | *.pyc
3 | .coverage
4 | build
5 | dist
6 | linesman.egg-info
7 | sessions.db
8 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/ChangeLog:
--------------------------------------------------------------------------------
1 | Please refer to `docs/changelog.rst`.
2 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.rst
2 | recursive-include linesman/templates *
3 | recursive-include linesman/media *
4 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | ``linesman`` is a much needed profiler-for-WSGI applications. It installs as
2 | middleware, can be configured entirely from any ``paster`` config, and aims to
3 | be a jack-of-all-trades when it comes to profiling WSGI apps.
4 |
5 | Since a picture is worth a thousand words, here are a few screenshots of the
6 | interface:
7 |
8 | - `Session listing
9 | `_
10 | - `Profile page
11 | `_
12 | - `Profile page w/ pie chart
13 | `_
14 | - `Generated callgraph
15 | `_
16 |
17 | The changelog can always be viewed `from the source
18 | `_, or `on
19 | PyPi `_. Keep in mind,
20 | PyPi is only updated with each release, and does not include development
21 | documentation.
22 |
23 | Reasoning behind this library
24 | =============================
25 |
26 | One of my team's stories at work was to investigate existing Python profiling
27 | tools for use with some of our new web stacks (all in Pylons). I looked at a
28 | few--``repoze.profile``, ``kea.profile``, and even ``dozer`` (still in
29 | 0.2alpha)--but couldn't find any that suited our use case. We wanted to...
30 |
31 | - visualize the flow of our code
32 | - identify bottlenecks quickly and easily
33 | - have the ability to strip out extraneous calls
34 |
35 | Many of the tools simply outputted the ``pstats`` object from ``cProfile``,
36 | which can be difficult to parse, and even more difficult to identify the call
37 | order. Considering that ``cProfile`` provided all the information needed, I
38 | figured it would be just as easy to write our own middleware.
39 |
40 | ``linesman`` is a name given to people who inspect electrical ``Pylons``, and
41 | was a meek attempt at having a relevant library name.
42 |
43 | Setting up middleware
44 | =====================
45 |
46 | Now, you'll need to tell your WSGI application how to use Linesman. Assuming
47 | you're using Paster, you can do this very easily in your `development.ini` (or
48 | similar) config file. Add a new filter section::
49 |
50 | [filter:linesman]
51 | use = egg:linesman#profiler
52 |
53 | Then, find the section for your specific application. Typically, it will have
54 | a section header that looks like ``[app:main]``. Add the following config
55 | option somewhere within this section::
56 |
57 | filter-with = linesman
58 |
59 | Wallah! Once you start your paster server, you'll be all set. Verify that all
60 | is working correctly by accessing pages on your server. This will also create
61 | profile entries for the next step.
62 |
63 | Accessing the profiles
64 | ======================
65 |
66 | This will assume that your application is mounted at the root directory,
67 | `/`, and that your server is running on `localhost` at port 5000. If
68 | not, make sure you adjust your URLs accordingly.
69 |
70 | Access the URL at http://127.0.0.1:5000/__profiler__, which should present
71 | you with a list of profiles and times, with a link to the `stats` page. If you
72 | can see this (and view the profiles), then you're all set!
73 |
74 | Happy profiling!
75 |
--------------------------------------------------------------------------------
/docs/api/linesman.backends.rst:
--------------------------------------------------------------------------------
1 | :mod:`linesman.backends`
2 | ========================
3 |
4 | .. automodule:: linesman.backends.base
5 | :members:
6 | :undoc-members:
7 |
8 | .. automodule:: linesman.backends.pickle
9 | :members:
10 | :undoc-members:
11 |
12 | .. automodule:: linesman.backends.sqlite
13 | :members:
14 | :undoc-members:
15 |
--------------------------------------------------------------------------------
/docs/api/linesman.middleware.rst:
--------------------------------------------------------------------------------
1 | :mod:`linesman.middleware`
2 | --------------------------
3 |
4 | .. automodule:: linesman.middleware
5 | :members:
6 | :undoc-members:
7 |
--------------------------------------------------------------------------------
/docs/api/linesman.rst:
--------------------------------------------------------------------------------
1 | :mod:`linesman`
2 | ---------------
3 |
4 | .. automodule:: linesman
5 | :members:
6 | :undoc-members:
7 |
--------------------------------------------------------------------------------
/docs/changelog.rst:
--------------------------------------------------------------------------------
1 | 0.3.1 (2013-05-02)
2 | ------------------
3 |
4 | :Contributor: Gert Berger
5 |
6 | * Add delete_many to delete multiple selected sessions at once. (GertBerger)
7 |
8 | 0.3.0 (2013-03-12)
9 | ------------------
10 |
11 | :Contributor: Gert Burger
12 | :Contributor: Sam Kimbrel
13 | :Contributor: J.J. Guy
14 |
15 | * Use pillow instead of PIL. (GertBerger)
16 | * WebOb requires that response.text is a unicode object. (GertBerger)
17 | * Fix a couple resp.text unicode issues (skimbrel)
18 | * Fix timezone-dependent test (skimbrel)
19 | * Assign unicode template to body_unicode (jjguy)
20 |
21 | 0.2.3 (2013-01-16)
22 | ------------------
23 |
24 | :Contributor: Hong Minhee
25 | :Contributor: Sam Kimbrel
26 |
27 | * linesman updated to support webob>=1.2 (dahlia, skimbrel)
28 |
29 | 0.2.2 (2011-09-30)
30 | ------------------
31 | :Contributor: Calen Pennington
32 |
33 | Bugs
34 | ^^^^
35 |
36 | * Date sorting logic was not correct. (cpennington)
37 |
38 | 0.2.1 (2011-08-25)
39 | ------------------
40 |
41 | :Contributor: Luis Peralta
42 |
43 | Bugs
44 | ^^^^
45 |
46 | * os.abspath should have been os.path.abspath (lperalta)
47 | * Updated unittests back to 100% to catch errors, such as the one lperalta
48 | found.
49 |
50 | 0.2 (2011-05-14)
51 | -----------------
52 |
53 | :Contributor: Calen Pennington
54 | :Contributor: Rudd Zwolinski
55 |
56 | .. warning::
57 |
58 | This release will break profile persistence from 0.1. This is because the
59 | default backend has been moved to SQLite, which is a *much* faster storage
60 | mechanism.
61 |
62 | Bugs
63 | ^^^^
64 |
65 | * Requests containing unicode no longer cause errors.
66 | * Row hovering now works in all browsers. (Issue #2)
67 | * Terminology for inlinetime, totaltime changed to match cProfile.
68 |
69 | Documentation
70 | ^^^^^^^^^^^^^
71 |
72 | * Added notes for using Linesman with Django.
73 | * Docstring additions across the board.
74 |
75 | Features
76 | ^^^^^^^^
77 |
78 | * Added ability to enable/disable profiling on-the-fly. (Issue #8)
79 | * All or specific sessions can now be deleted from the session listing. (Issue
80 | #4)
81 | * Introduced modular backends; now possible to store results in either entirely
82 | pickled form or in SQLite.
83 | * Pie charts can be used to visually display time spent in specific packages;
84 | the list of packages is configurable in the middleware. (Issue #1)
85 | * Session history is now displayed in a nice manner (Issue #5)
86 |
87 | 0.1.1 (2011-05-06)
88 | ------------------
89 |
90 | Bugs
91 | ^^^^
92 |
93 | * setuptools will not correctly include data sources unless they live in
94 | MANIFEST.in.
95 |
96 | 0.1 (2011-04-29)
97 | ----------------
98 |
99 | * Initial release
100 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Linesman documentation build configuration file, created by
4 | # sphinx-quickstart on Fri Dec 10 16:32:38 2010.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | # -- General configuration -----------------------------------------------------
22 |
23 | # If your documentation needs a minimal Sphinx version, state it here.
24 | #needs_sphinx = '1.0'
25 |
26 | # Add any Sphinx extension module names here, as strings. They can be extensions
27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode']
29 |
30 | # Add any paths that contain templates here, relative to this directory.
31 | templates_path = ['_templates']
32 |
33 | # The suffix of source filenames.
34 | source_suffix = '.rst'
35 |
36 | # The encoding of source files.
37 | #source_encoding = 'utf-8-sig'
38 |
39 | # The master toctree document.
40 | master_doc = 'index'
41 |
42 | # General information about the project.
43 | project = u'Linesman'
44 | copyright = u'2011, Wireless Generation'
45 |
46 | # The version info for the project you're documenting, acts as replacement for
47 | # |version| and |release|, also used in various other places throughout the
48 | # built documents.
49 | #
50 | # The short X.Y version.
51 | version = '0.2.2'
52 | # The full version, including alpha/beta/rc tags.
53 | release = '0.3.0'
54 |
55 | # The language for content autogenerated by Sphinx. Refer to documentation
56 | # for a list of supported languages.
57 | #language = None
58 |
59 | # There are two options for replacing |today|: either, you set today to some
60 | # non-false value, then it is used:
61 | #today = ''
62 | # Else, today_fmt is used as the format for a strftime call.
63 | #today_fmt = '%B %d, %Y'
64 |
65 | # List of patterns, relative to source directory, that match files and
66 | # directories to ignore when looking for source files.
67 | exclude_patterns = ['_build']
68 |
69 | # The reST default role (used for this markup: `text`) to use for all documents.
70 | #default_role = None
71 |
72 | # If true, '()' will be appended to :func: etc. cross-reference text.
73 | add_function_parentheses = True
74 |
75 | # If true, the current module name will be prepended to all description
76 | # unit titles (such as .. function::).
77 | #add_module_names = True
78 |
79 | # If true, sectionauthor and moduleauthor directives will be shown in the
80 | # output. They are ignored by default.
81 | #show_authors = False
82 |
83 | # The name of the Pygments (syntax highlighting) style to use.
84 | pygments_style = 'sphinx'
85 |
86 | # A list of ignored prefixes for module index sorting.
87 | #modindex_common_prefix = []
88 |
89 |
90 | # -- Options for HTML output ---------------------------------------------------
91 |
92 | # The theme to use for HTML and HTML Help pages. See the documentation for
93 | # a list of builtin themes.
94 | html_theme = 'default'
95 |
96 | # Theme options are theme-specific and customize the look and feel of a theme
97 | # further. For a list of options available for each theme, see the
98 | # documentation.
99 | #html_theme_options = {}
100 |
101 | # Add any paths that contain custom themes here, relative to this directory.
102 | #html_theme_path = []
103 |
104 | # The name for this set of Sphinx documents. If None, it defaults to
105 | # " v documentation".
106 | #html_title = None
107 |
108 | # A shorter title for the navigation bar. Default is the same as html_title.
109 | #html_short_title = None
110 |
111 | # The name of an image file (relative to this directory) to place at the top
112 | # of the sidebar.
113 | #html_logo = None
114 |
115 | # The name of an image file (within the static path) to use as favicon of the
116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
117 | # pixels large.
118 | #html_favicon = None
119 |
120 | # Add any paths that contain custom static files (such as style sheets) here,
121 | # relative to this directory. They are copied after the builtin static files,
122 | # so a file named "default.css" will overwrite the builtin "default.css".
123 | html_static_path = ['_static']
124 |
125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
126 | # using the given strftime format.
127 | #html_last_updated_fmt = '%b %d, %Y'
128 |
129 | # If true, SmartyPants will be used to convert quotes and dashes to
130 | # typographically correct entities.
131 | #html_use_smartypants = True
132 |
133 | # Custom sidebar templates, maps document names to template names.
134 | #html_sidebars = {}
135 |
136 | # Additional templates that should be rendered to pages, maps page names to
137 | # template names.
138 | #html_additional_pages = {}
139 |
140 | # If false, no module index is generated.
141 | html_domain_indices = True
142 |
143 | # If false, no index is generated.
144 | html_use_index = True
145 |
146 | # If true, the index is split into individual pages for each letter.
147 | #html_split_index = False
148 |
149 | # If true, links to the reST sources are added to the pages.
150 | html_show_sourcelink = True
151 |
152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
153 | html_show_sphinx = True
154 |
155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
156 | html_show_copyright = True
157 |
158 | # If true, an OpenSearch description file will be output, and all pages will
159 | # contain a tag referring to it. The value of this option must be the
160 | # base URL from which the finished HTML is served.
161 | #html_use_opensearch = ''
162 |
163 | # This is the file name suffix for HTML files (e.g. ".xhtml").
164 | #html_file_suffix = None
165 |
166 | # Output file base name for HTML help builder.
167 | htmlhelp_basename = 'Linesmandoc'
168 |
169 |
170 | # -- Options for LaTeX output --------------------------------------------------
171 |
172 | # The paper size ('letter' or 'a4').
173 | #latex_paper_size = 'letter'
174 |
175 | # The font size ('10pt', '11pt' or '12pt').
176 | #latex_font_size = '10pt'
177 |
178 | # Grouping the document tree into LaTeX files. List of tuples
179 | # (source start file, target name, title, author, documentclass [howto/manual]).
180 | latex_documents = [
181 | ('index', 'Linesman.tex', u'Linesman',
182 | u'Wireless Generation', 'manual'),
183 | ]
184 |
185 | # The name of an image file (relative to this directory) to place at the top of
186 | # the title page.
187 | #latex_logo = None
188 |
189 | # For "manual" documents, if this is true, then toplevel headings are parts,
190 | # not chapters.
191 | #latex_use_parts = False
192 |
193 | # If true, show page references after internal links.
194 | #latex_show_pagerefs = False
195 |
196 | # If true, show URL addresses after external links.
197 | #latex_show_urls = False
198 |
199 | # Additional stuff for the LaTeX preamble.
200 | #latex_preamble = ''
201 |
202 | # Documents to append as an appendix to all manuals.
203 | #latex_appendices = []
204 |
205 | # If false, no module index is generated.
206 | #latex_domain_indices = True
207 |
208 |
209 | # -- Options for manual page output --------------------------------------------
210 |
211 | # One entry per manual page. List of tuples
212 | # (source start file, name, description, authors, manual section).
213 | man_pages = [
214 | ('index', 'linesman', u'Linesman Documentation',
215 | [u'Wireless Generation'], 1)
216 | ]
217 |
--------------------------------------------------------------------------------
/docs/glossary.rst:
--------------------------------------------------------------------------------
1 | Glossary
2 | ========
3 |
4 | .. glossary::
5 | :sorted:
6 |
7 | session_uuid
8 | Specific implementation of a :term:`uuid` that unique identifies a single, specific request.
9 |
10 | uuid
11 | This is a `universally unique identifier `_
12 | that insures "practically unique" keys.
13 |
14 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | ======================
2 | Linesman Documentation
3 | ======================
4 |
5 | ``linesman`` is a profiler for WSGI applications. It installs as middleware,
6 | can be configured entirely from any ``paster`` config, and aims to be a
7 | jack-of-all-trades when it comes to profiling WSGI apps.
8 |
9 | Unfortunately, there are only a few profilers available for Python, with the
10 | fastest and generally most popular one being `cProfile`. However, the
11 | output can be very difficult to analyze without having substantial knowledge
12 | about what's going on in an application, which makes it difficult to use.
13 |
14 | There are a few select profile wrappers out there--`repoze.profile`,
15 | `keas.profile`, and `dozer` (which is still in alpha) all come to mind, but all
16 | either wrap the output from `cProfile` itself, or show incomplete information.
17 | `Linesman` aims to right this wrong.
18 |
19 | Overview
20 | --------
21 |
22 | This is the central hub for *all* Linesman documentation. It covers:
23 |
24 | - instructions on how to setup middleware
25 | - how to view the on-the-fly graphs and statistics
26 |
27 | Things it *does not cover* are:
28 |
29 | - interpreting profiling data
30 | - memory leaks
31 | - how to improve your application's response time
32 |
33 | To **run unittests**::
34 |
35 | $ python setup.py nosetests
36 |
37 | To **build this documentation**::
38 |
39 | $ easy_install sphinx
40 | [...]
41 | $ python setup.py build_sphinx
42 |
43 | The built documentation is available (by default) in :file:`build/sphinx/html`,
44 | and can be viewed locally on your web browser without the need for a separate
45 | web server.
46 |
47 | Narrative Documentation
48 | =======================
49 |
50 | .. toctree::
51 | :maxdepth: 1
52 | :glob:
53 |
54 | narr/*
55 |
56 | Reference Material
57 | ==================
58 |
59 | .. toctree::
60 | :maxdepth: 2
61 | :glob:
62 |
63 | api/*
64 |
65 | Change Log
66 | ==========
67 |
68 | .. toctree::
69 | :maxdepth: 2
70 |
71 | changelog
72 |
73 | Index and Glossary
74 | ==================
75 |
76 | * :doc:`glossary`
77 | * :ref:`genindex`
78 | * :ref:`search`
79 |
--------------------------------------------------------------------------------
/docs/narr/configuration.rst:
--------------------------------------------------------------------------------
1 | .. _configuration:
2 |
3 | Configuring Linesman
4 | ====================
5 |
6 | Configuration of ``linesman`` is done through the controlling process, such as
7 | Paster. Thus, this assumes that the configuration is similar to the
8 | instructions given in the :ref:`getting started` documentation. ::
9 |
10 | [filter:linesman]
11 | use = egg:linesman#profiler
12 |
13 | All options can be made under this section.
14 |
15 | Configuring the Middleware
16 | --------------------------
17 |
18 | ``profiler_path``
19 | """""""""""""""""
20 |
21 | This is a path relative to the root of your webapp that can be used to access
22 | the profiler. For example, if the host is being run on ``localhost:5000``, and
23 | the application is mounted on the ``/`` context, then specifying a
24 | ``profiler_path`` of ``__profiler__`` will use ``localhost:5000/__profiler__``.
25 |
26 | Consequently, if the same application is NOT mounted under the root context,
27 | and is instead mounted at ``/webapp``, the same ``profiler_path`` would match
28 | ``localhost:5000/webapp/__profiler__``.
29 |
30 | ``backend``
31 | """""""""""
32 |
33 | Takes the form of :samp:`{module}:{class_or_function}`, where
34 | `class_or_function` resolves to a class that implements
35 | :class:`~linesman.backends.Backend`. To see which backends are available, take
36 | a look at the :mod:`~linesman.backends` modules.
37 |
38 | Additionally, you can specify _any_ module, regardless of rather or not its
39 | distributed with Linesman.
40 |
41 | ``chart_packages``
42 | """"""""""""""""""
43 |
44 | Space separated values that indicate which packages should be displayed in pie
45 | graph form. This is extremely useful for getting a high-level view of where
46 | your program is spending most of its time. ::
47 |
48 | chart_packages = paste, repoze.who, webob
49 |
50 | Be very careful when specifying parent and child packages. For example, assume
51 | ``chart_packages = paste, paste.script``. If the time spent in :mod:`paste`
52 | was 10s, and the time spent in :mod:`paste.script` was 3s, then the graphed
53 | times would be 3s in :mod:`paste.script`, and 7s in :mod:`paste`. This is
54 | because child packages "take away" some of the duration for their parent
55 | packages.
56 |
57 | .. warning::
58 |
59 | Subpackages are *always* given priority over their parents. So in the
60 | above example, if :mod:`!linesman` discovers :func:`paste.script.__init__`,
61 | it would add the time to :mod:`pastescript`.
62 |
63 | .. note::
64 |
65 | Unless this configuration variable is specified, the graph is NOT displayed
66 | on the profile page.
67 |
68 | Configuring the Backends
69 | ------------------------
70 |
71 | Whatever ``backend`` is set to, there are new sets of config values that can be
72 | used. This data differs depending on the plug-in, so in order to always keep
73 | the documentation up-to-date, visit the :mod:`linesman.backends` page.
74 | Whatever values :func:`__init__` accepts are values that can be passed in
75 | through the configuration file.
76 |
77 | For example, :class:`~linesman.backends.pickle.PickleBackend` defines a
78 | ``filename`` parameter. Thus, to set the Pickle filename, use the following
79 | config parameter::
80 |
81 | filename = sessions.dat
82 |
83 | Remember, always use the backends page for the most up-to-date info.
84 |
--------------------------------------------------------------------------------
/docs/narr/django_notes.rst:
--------------------------------------------------------------------------------
1 | Django notes
2 | ============
3 |
4 | The Problem
5 | -----------
6 |
7 | Unfortunately, Django uses the term `middleware` incorrect. What it refers to
8 | is, specifically, `Django middleware`. WSGI middleware, on the otherhand, is
9 | defined by :pep:`333` and is warranted as a standard that all WSGI servers
10 | follow.
11 |
12 | Possible Solutions
13 | ------------------
14 |
15 | Currently, `linesman` can *only* be run in a WSGI environment that adheres to
16 | :pep:`333`, as mentioned above. If this is the case, you can wrap the
17 | application call by following the instructions in :ref:`configuration_code`.
18 | For example, the official Django docs refer to using `mod_wsgi and Apache to
19 | host a Django app
20 | `_. In this
21 | case, you would wrap the :meth:`django.core.handlers.wsgi.WSGIHandler()` call
22 | with the middleware, like so::
23 |
24 | import os
25 | import sys
26 |
27 | os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
28 |
29 | import django.core.handlers.wsgi
30 | from linesman.middleware import make_linesman_middleware
31 | application = django.core.handlers.wsgi.WSGIHandler()
32 | application = make_linesman_middleware(application)
33 |
34 | If running a full WSGI server is a little too heavy-weight, there's a very,
35 | very alpha release of `DjangoPaste `_,
36 | which provides the ability to launch Django using Paste.
37 |
38 | The final solution (not yet implemented) is to wrap the middleware so that it is usuable by the
39 | Django middleware. This introduces two big issues. First, when implemented as
40 | WSGI middleware, `linesman` can wrap the *whole* request, from start to finish.
41 | With Django, the profiling will only begin when Django initializes the
42 | middleware. Secondly, because I am not familiar with Django (yet), it may not
43 | be possible to simply jury rig the middleware onto a request. But this may be
44 | changed after future research.
45 |
46 | Conclusion (tl;dr)
47 | ------------------
48 |
49 | If your Django app is being run in a WSGI environment, you do not need to do
50 | any additional work and can wrap the application by following the instructions
51 | on the :ref:`getting started page `. Otherwise, there's no
52 | convenient or easy solution for running `linesman` on Django.
53 |
--------------------------------------------------------------------------------
/docs/narr/getting_started.rst:
--------------------------------------------------------------------------------
1 | .. _getting started:
2 |
3 | Getting Started
4 | ===============
5 |
6 | This document will cover setting up Linesman in your WSGI application.
7 |
8 | Installing Linesman
9 | -------------------
10 |
11 | To install the **latest stable version of Linesman**, you can use::
12 |
13 | $ easy_install -U linesman
14 |
15 | To install Linesman **from source**, you will need to clone the repository and
16 | run::
17 |
18 | $ python setup.py install
19 |
20 | This will install Linesman into `site-packages` and make it available to all
21 | other Python scripts. No other setup is required.
22 |
23 | Setting up middleware
24 | ---------------------
25 |
26 | Via Configuration (Paster)
27 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
28 |
29 | Now, you'll need to tell your WSGI application how to use Linesman. Assuming
30 | you're using Paster, you can do this very easily in your `development.ini` (or
31 | similar) config file. Add a new filter section::
32 |
33 | [filter:linesman]
34 | use = egg:linesman#profiler
35 |
36 | Then, find the section for your specific application. Typically, it will have
37 | a section header that looks like ``[app:main]``. Add the following config
38 | option somewhere within this section::
39 |
40 | filter-with = linesman
41 |
42 | Voila! Once you start your paster server, you'll be all set. Verify that all
43 | is working correctly by accessing pages on your server. This will also create
44 | profile entries for the next step.
45 |
46 | .. _configuration_code:
47 |
48 | Via Code
49 | ^^^^^^^^
50 |
51 | This requires manually wrapping the WSGI calls in the middleware. This is only
52 | recommended if you are unable to setup a filter. Before beginning, please
53 | check your respective WSGI server documentation to see if running your app
54 | through Paster is possible (i.e., `gunicorn
55 | `_), as this requires zero code
56 | changes.
57 |
58 | First off, you'll have to open up the area where your app declares middleware.
59 | Typically, this will just be called `app`, but it is heavily dependant on the
60 | framework. Pylons creates the application in `/config/middleware.py`.
61 |
62 | Then, you can create the middleware by passing in the app to the middleware
63 | constructor, like so::
64 |
65 | from linesman.middleware import make_linesman_middleware
66 |
67 | [...]
68 |
69 | app = make_linesman_middleware(app)
70 | # Or, if you have config options...
71 | # app = make_linesman_middleware(app, profiler_path="/__profiler")
72 |
73 | For a complete list of configurable parameters, please see the
74 | :ref:`configuration` documentation.
75 |
76 | Accessing the profiles
77 | ----------------------
78 |
79 | This will assume that your application is mounted at the root directory,
80 | :file:`/`, and that your server is running on `localhost` at port 5000. If
81 | not, make sure you adjust your URLs accordingly.
82 |
83 | Access the URL at http://127.0.0.1:5000/__profiler__, which should present
84 | you with a list of profiles and times, with a link to the `stats` page. If you
85 | can see this (and view the profiles), then you're all set!
86 |
87 | Happy profiling!
88 |
--------------------------------------------------------------------------------
/examples/callgraph.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/examples/callgraph.png
--------------------------------------------------------------------------------
/examples/profile-with-pie-chart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/examples/profile-with-pie-chart.png
--------------------------------------------------------------------------------
/examples/profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/examples/profile.png
--------------------------------------------------------------------------------
/examples/session_listing.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/examples/session_listing.png
--------------------------------------------------------------------------------
/ez_setup.py:
--------------------------------------------------------------------------------
1 | #!python
2 | """Bootstrap setuptools 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 ez_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 sys
17 | DEFAULT_VERSION = "0.6c9"
18 | DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
19 |
20 | md5_data = {
21 | 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
22 | 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
23 | 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
24 | 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
25 | 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
26 | 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
27 | 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
28 | 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
29 | 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
30 | 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
31 | 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
32 | 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
33 | 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
34 | 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
35 | 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
36 | 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
37 | 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
38 | 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
39 | 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
40 | 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
41 | 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
42 | 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
43 | 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
44 | 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
45 | 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
46 | 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
47 | 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
48 | 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
49 | 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
50 | 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
51 | 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
52 | 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
53 | 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
54 | 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
55 | }
56 |
57 | import sys, os
58 | try: from hashlib import md5
59 | except ImportError: from md5 import md5
60 |
61 | def _validate_md5(egg_name, data):
62 | if egg_name in md5_data:
63 | digest = md5(data).hexdigest()
64 | if digest != md5_data[egg_name]:
65 | print >>sys.stderr, (
66 | "md5 validation of %s failed! (Possible download problem?)"
67 | % egg_name
68 | )
69 | sys.exit(2)
70 | return data
71 |
72 | def use_setuptools(
73 | version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
74 | download_delay=15
75 | ):
76 | """Automatically find/download setuptools and make it available on sys.path
77 |
78 | `version` should be a valid setuptools version number that is available
79 | as an egg for download under the `download_base` URL (which should end with
80 | a '/'). `to_dir` is the directory where setuptools will be downloaded, if
81 | it is not already available. If `download_delay` is specified, it should
82 | be the number of seconds that will be paused before initiating a download,
83 | should one be required. If an older version of setuptools is installed,
84 | this routine will print a message to ``sys.stderr`` and raise SystemExit in
85 | an attempt to abort the calling script.
86 | """
87 | was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
88 | def do_download():
89 | egg = download_setuptools(version, download_base, to_dir, download_delay)
90 | sys.path.insert(0, egg)
91 | import setuptools; setuptools.bootstrap_install_from = egg
92 | try:
93 | import pkg_resources
94 | except ImportError:
95 | return do_download()
96 | try:
97 | pkg_resources.require("setuptools>="+version); return
98 | except pkg_resources.VersionConflict, e:
99 | if was_imported:
100 | print >>sys.stderr, (
101 | "The required version of setuptools (>=%s) is not available, and\n"
102 | "can't be installed while this script is running. Please install\n"
103 | " a more recent version first, using 'easy_install -U setuptools'."
104 | "\n\n(Currently using %r)"
105 | ) % (version, e.args[0])
106 | sys.exit(2)
107 | else:
108 | del pkg_resources, sys.modules['pkg_resources'] # reload ok
109 | return do_download()
110 | except pkg_resources.DistributionNotFound:
111 | return do_download()
112 |
113 | def download_setuptools(
114 | version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
115 | delay = 15
116 | ):
117 | """Download setuptools from a specified location and return its filename
118 |
119 | `version` should be a valid setuptools version number that is available
120 | as an egg for download under the `download_base` URL (which should end
121 | with a '/'). `to_dir` is the directory where the egg will be downloaded.
122 | `delay` is the number of seconds to pause before an actual download attempt.
123 | """
124 | import urllib2, shutil
125 | egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
126 | url = download_base + egg_name
127 | saveto = os.path.join(to_dir, egg_name)
128 | src = dst = None
129 | if not os.path.exists(saveto): # Avoid repeated downloads
130 | try:
131 | from distutils import log
132 | if delay:
133 | log.warn("""
134 | ---------------------------------------------------------------------------
135 | This script requires setuptools version %s to run (even to display
136 | help). I will attempt to download it for you (from
137 | %s), but
138 | you may need to enable firewall access for this script first.
139 | I will start the download in %d seconds.
140 |
141 | (Note: if this machine does not have network access, please obtain the file
142 |
143 | %s
144 |
145 | and place it in this directory before rerunning this script.)
146 | ---------------------------------------------------------------------------""",
147 | version, download_base, delay, url
148 | ); from time import sleep; sleep(delay)
149 | log.warn("Downloading %s", url)
150 | src = urllib2.urlopen(url)
151 | # Read/write all in one block, so we don't create a corrupt file
152 | # if the download is interrupted.
153 | data = _validate_md5(egg_name, src.read())
154 | dst = open(saveto,"wb"); dst.write(data)
155 | finally:
156 | if src: src.close()
157 | if dst: dst.close()
158 | return os.path.realpath(saveto)
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 | def main(argv, version=DEFAULT_VERSION):
196 | """Install or upgrade setuptools and EasyInstall"""
197 | try:
198 | import setuptools
199 | except ImportError:
200 | egg = None
201 | try:
202 | egg = download_setuptools(version, delay=0)
203 | sys.path.insert(0,egg)
204 | from setuptools.command.easy_install import main
205 | return main(list(argv)+[egg]) # we're done here
206 | finally:
207 | if egg and os.path.exists(egg):
208 | os.unlink(egg)
209 | else:
210 | if setuptools.__version__ == '0.0.1':
211 | print >>sys.stderr, (
212 | "You have an obsolete version of setuptools installed. Please\n"
213 | "remove it from your system entirely before rerunning this script."
214 | )
215 | sys.exit(2)
216 |
217 | req = "setuptools>="+version
218 | import pkg_resources
219 | try:
220 | pkg_resources.require(req)
221 | except pkg_resources.VersionConflict:
222 | try:
223 | from setuptools.command.easy_install import main
224 | except ImportError:
225 | from easy_install import main
226 | main(list(argv)+[download_setuptools(delay=0)])
227 | sys.exit(0) # try to force an exit
228 | else:
229 | if argv:
230 | from setuptools.command.easy_install import main
231 | main(argv)
232 | else:
233 | print "Setuptools version",version,"or greater has been installed."
234 | print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
235 |
236 | def update_md5(filenames):
237 | """Update our built-in md5 registry"""
238 |
239 | import re
240 |
241 | for name in filenames:
242 | base = os.path.basename(name)
243 | f = open(name,'rb')
244 | md5_data[base] = md5(f.read()).hexdigest()
245 | f.close()
246 |
247 | data = [" %r: %r,\n" % it for it in md5_data.items()]
248 | data.sort()
249 | repl = "".join(data)
250 |
251 | import inspect
252 | srcfile = inspect.getsourcefile(sys.modules[__name__])
253 | f = open(srcfile, 'rb'); src = f.read(); f.close()
254 |
255 | match = re.search("\nmd5_data = {\n([^}]+)}", src)
256 | if not match:
257 | print >>sys.stderr, "Internal error!"
258 | sys.exit(2)
259 |
260 | src = src[:match.start(1)] + repl + src[match.end(1):]
261 | f = open(srcfile,'w')
262 | f.write(src)
263 | f.close()
264 |
265 |
266 | if __name__=='__main__':
267 | if len(sys.argv)>2 and sys.argv[1]=='--md5update':
268 | update_md5(sys.argv[2:])
269 | else:
270 | main(sys.argv[1:])
271 |
272 |
273 |
274 |
275 |
276 |
277 |
--------------------------------------------------------------------------------
/linesman/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is part of linesman.
2 | #
3 | # linesman is free software: you can redistribute it and/or modify it under
4 | # the terms of the GNU General Public License as published by the Free
5 | # Software Foundation, either version 3 of the License, or (at your option)
6 | # any later version.
7 | #
8 | # linesman is distributed in the hope that it will be useful, but WITHOUT ANY
9 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 | # details.
12 | #
13 | # You should have received a copy of the GNU General Public License along
14 | # with linesman. If not, see .
15 | #
16 | import logging
17 | import uuid
18 | from inspect import getmodule
19 |
20 | import networkx as nx
21 |
22 |
23 | log = logging.getLogger(__name__)
24 |
25 |
26 | def _generate_key(stat):
27 | code = stat.code
28 |
29 | # First, check if its built-in (i.e., code is a string)
30 | if isinstance(code, str):
31 | return code
32 |
33 | # If we have a module, generate the module name (a.b.c, etc..)
34 | module = getmodule(code)
35 | if module:
36 | return ".".join((module.__name__, code.co_name))
37 |
38 | # Otherwise, return a path based on the filename and function name.
39 | return "%s.%s" % (code.co_filename, code.co_name)
40 |
41 |
42 | def draw_graph(graph, output_path):
43 | """
44 | Draws a networkx graph to disk using the `dot` format.
45 |
46 | ``graph``:
47 | networkx graph
48 | ``output_path``:
49 | Location to store the rendered output.
50 | """
51 | nx.to_agraph(graph).draw(output_path, prog="dot")
52 | log.info("Wrote output to `%s'" % output_path)
53 |
54 |
55 | def create_graph(stats):
56 | """
57 | Given an instance of :class:`pstats.Pstats`, this will use the generated
58 | call data to create a graph using the :mod:`networkx` library. Node
59 | and edge information is stored in the graph itself, so that the stats
60 | object itself--which can't be pickled--does not need to be kept around.
61 |
62 | ``stats``:
63 | An instance of :class:`pstats.Pstats`, usually retrieved by calling
64 | :func:`~cProfile.Profile.getstats()` on a cProfile object.
65 |
66 | Returns a :class:`networkx.DiGraph` containing the callgraph.
67 | """
68 |
69 | # Create a graph; dot graphs need names, so just use `G' so that
70 | # pygraphviz doesn't complain when we render it.
71 | g = nx.DiGraph(name="G")
72 |
73 | # Iterate through stats to add the original nodes. The will add ALL
74 | # the nodes, even ones which might be pruned later. This is so that
75 | # the library will always have the original callgraph, which can be
76 | # manipulated for display purposes later.
77 | duration = max([stat.totaltime for stat in stats])
78 |
79 | for stat in stats:
80 | caller_key = _generate_key(stat)
81 |
82 | attrs = {
83 | 'callcount': stat.callcount,
84 | 'inlinetime': stat.inlinetime,
85 | 'reccallcount': stat.reccallcount,
86 | 'totaltime': stat.totaltime,
87 | }
88 | g.add_node(caller_key, attr_dict=attrs)
89 |
90 | # Add all the calls as edges
91 | for call in stat.calls or []:
92 | callee_key = _generate_key(call)
93 |
94 | call_attrs = {
95 | 'callcount': call.callcount,
96 | 'inlinetime': call.inlinetime,
97 | 'reccallcount': call.reccallcount,
98 | 'totaltime': call.totaltime,
99 | }
100 |
101 | # Add the edge using a weight and label
102 | g.add_edge(caller_key, callee_key,
103 | weight=call.totaltime,
104 | label=call.totaltime,
105 | attr_dict=call_attrs)
106 |
107 | return g
108 |
109 |
110 | class ProfilingSession(object):
111 | """
112 | The profiling session is used to store long-term information about the
113 | profiled call, including generating the complete callgraph based on
114 | cProfile's stats output.
115 |
116 | Of special interest is the ``uuid`` that it generates to uniquely track
117 | this request.
118 |
119 | ``stats``:
120 | An instance of :class:`pstats.Pstats`, usually retrieved by calling
121 | :func:`~cProfile.Profile.getstats()` on a cProfile object.
122 | ``environ``:
123 | If specified, this Session will store `environ` data. This should be
124 | the environment setup by the WSGI server (i.e., :mod:`paster`).
125 | ``timestamp``:
126 | If specified, this should mark the beginning of the profiling
127 | session--i.e., when Profile.run() was called. This can be any format
128 | if your choosing; however, the default templates simply invoke
129 | ``timestamp.__repr__``, so whatever object you use should provide at
130 | _least_ that function.
131 | """
132 |
133 | def __init__(self, stats, environ={}, timestamp=None):
134 | self._graph = None
135 | self._uuid = uuid.uuid1()
136 |
137 | # Save some environment variables (if available)
138 | self.path = environ.get('PATH_INFO')
139 |
140 | # Some profiling session attributes need to be calculated
141 | self.duration = max([stat.totaltime for stat in stats])
142 |
143 | self.timestamp = timestamp
144 |
145 | self._graph = create_graph(stats)
146 |
147 | @property
148 | def uuid(self):
149 | """ See :term:`session_uuid`. """
150 | return str(self._uuid)
151 |
--------------------------------------------------------------------------------
/linesman/backends/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is part of linesman.
2 | #
3 | # linesman is free software: you can redistribute it and/or modify it under
4 | # the terms of the GNU General Public License as published by the Free
5 | # Software Foundation, either version 3 of the License, or (at your option)
6 | # any later version.
7 | #
8 | # linesman is distributed in the hope that it will be useful, but WITHOUT ANY
9 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 | # details.
12 | #
13 | # You should have received a copy of the GNU General Public License along
14 | # with linesman. If not, see .
15 | #
16 |
17 | from linesman.backends.sqlite import SqliteBackend
18 | from linesman.backends.pickle import PickleBackend
19 |
--------------------------------------------------------------------------------
/linesman/backends/base.py:
--------------------------------------------------------------------------------
1 | # This file is part of linesman.
2 | #
3 | # linesman is free software: you can redistribute it and/or modify it under
4 | # the terms of the GNU General Public License as published by the Free
5 | # Software Foundation, either version 3 of the License, or (at your option)
6 | # any later version.
7 | #
8 | # linesman is distributed in the hope that it will be useful, but WITHOUT ANY
9 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 | # details.
12 | #
13 | # You should have received a copy of the GNU General Public License along
14 | # with linesman. If not, see .
15 | #
16 |
17 |
18 | class Backend(object):
19 | """
20 | Base class for all backends. Methods that raise a NotImplementedError
21 | exception are required to be overriden by children, while functions that
22 | pass are optional.
23 | """
24 |
25 | def __init__(self, *args, **kwargs):
26 | pass
27 |
28 | def setup(self):
29 | """
30 | Responsible for initializing the backend. for usage. This is run once
31 | on middleware startup.
32 |
33 | Raises a :class:`NotImplementedError` exception.
34 | """
35 | raise NotImplementedError()
36 |
37 | def add(self, session):
38 | """
39 | Store a new session in history.
40 |
41 | Raises a :class:`NotImplementedError` exception.
42 | """
43 | raise NotImplementedError()
44 |
45 | def delete(self, session_uuid):
46 | """
47 | Removes a specific stored session from the history.
48 |
49 | This should return the number of rows removed (0 or 1).
50 |
51 | Raises a :class:`NotImplementedError` exception.
52 | """
53 | raise NotImplementedError()
54 |
55 | def delete_many(self, session_uuids):
56 | """
57 | Removes a list of stored sessions from the history.
58 |
59 | This should return the number of rows removed.
60 |
61 | Raises a :class:`NotImplementedError` exception.
62 | """
63 | raise NotImplementedError()
64 |
65 | def delete_all(self):
66 | """
67 | Removes all stored sessions from the history.
68 |
69 | This should return the number of rows removed.
70 |
71 | Raises a :class:`NotImplementedError` exception.
72 | """
73 | raise NotImplementedError()
74 |
75 | def get(self, session_uuid):
76 | """
77 | Returns the data associated with ``session_uuid``. Should return
78 | `None` if no session can be found with the specified uuid.
79 |
80 | Raises a :class:`NotImplementedError` exception.
81 | """
82 | raise NotImplementedError()
83 |
84 | def get_all(self):
85 | """
86 | Return a dictionary-like object of ALL sessions, where the key is the
87 | `session uuid`.
88 |
89 | Raises a :class:`NotImplementedError` exception.
90 | """
91 | raise NotImplementedError()
92 |
--------------------------------------------------------------------------------
/linesman/backends/pickle.py:
--------------------------------------------------------------------------------
1 | # This file is part of linesman.
2 | #
3 | # linesman is free software: you can redistribute it and/or modify it under
4 | # the terms of the GNU General Public License as published by the Free
5 | # Software Foundation, either version 3 of the License, or (at your option)
6 | # any later version.
7 | #
8 | # linesman is distributed in the hope that it will be useful, but WITHOUT ANY
9 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 | # details.
12 | #
13 | # You should have received a copy of the GNU General Public License along
14 | # with linesman. If not, see .
15 | #
16 | import cPickle
17 | import logging
18 |
19 | from linesman.backends.base import Backend
20 |
21 |
22 | try:
23 | # Python 2.7+
24 | from collections import OrderedDict
25 | except ImportError: #pragma no cover
26 | # Python 2.4+
27 | from ordereddict import OrderedDict
28 |
29 |
30 | log = logging.getLogger(__name__)
31 |
32 |
33 | class PickleBackend(Backend):
34 | """
35 | Stores entire session as a pickled object. This can be extremely slow when
36 | using even smaller sets of sessions--on the order of 30mb, or around 200
37 | requests.
38 | """
39 |
40 | def __init__(self, filename="sessions.dat"):
41 | self.filename = filename
42 |
43 | def _flush(self):
44 | """
45 | Writes the session history to disk, in pickled form.
46 | """
47 | with open(self.filename, "w+b") as pickle_fd:
48 | cPickle.dump(self._session_history,
49 | pickle_fd,
50 | cPickle.HIGHEST_PROTOCOL)
51 |
52 | def setup(self):
53 | """
54 | Reads in pickled data from ``filename``.
55 | """
56 | try:
57 | with open(self.filename, "rb") as pickle_fd:
58 | self._session_history = cPickle.load(pickle_fd)
59 | except IOError:
60 | log.debug(
61 | "`%s' does not exist; creating new dictionary.",
62 | self.filename)
63 | self._session_history = OrderedDict()
64 | except ValueError:
65 | log.error("Could not unpickle `%s`; this is likely not "
66 | "recoverable. Please delete this file and start "
67 | "from scratch.", self.filename)
68 | raise
69 |
70 | def add(self, session):
71 | """
72 | Adds a session to this dictionary and flushes it to disk.
73 | """
74 | self._session_history[session.uuid] = session
75 | self._flush()
76 |
77 | def delete(self, session_uuid):
78 | """
79 | Remove a session from the dictionary and flush it to disk.
80 | """
81 | if self.get(session_uuid):
82 | del self._session_history[session_uuid]
83 | self._flush()
84 | return 1
85 |
86 | return 0
87 |
88 | def delete_many(self, session_uuids):
89 | """
90 | Remove the sessions from the dictionary and flush it to disk.
91 | """
92 | count = 0
93 | for session_uuid in session_uuids:
94 | if session_uuid in self._session_history:
95 | del self._session_history[session_uuid]
96 | count += 1
97 |
98 | self._flush()
99 | return count
100 |
101 | def delete_all(self):
102 | """
103 | Clear the entire session history and flush it to disk.
104 | """
105 | deleted_rows = len(self._session_history)
106 | self._session_history.clear()
107 | self._flush()
108 |
109 | return deleted_rows
110 |
111 | def get(self, session_uuid):
112 | return self._session_history.get(session_uuid)
113 |
114 | def get_all(self):
115 | return self._session_history.copy()
116 |
--------------------------------------------------------------------------------
/linesman/backends/sqlite.py:
--------------------------------------------------------------------------------
1 | # This file is part of linesman.
2 | #
3 | # linesman is free software: you can redistribute it and/or modify it under
4 | # the terms of the GNU General Public License as published by the Free
5 | # Software Foundation, either version 3 of the License, or (at your option)
6 | # any later version.
7 | #
8 | # linesman is distributed in the hope that it will be useful, but WITHOUT ANY
9 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 | # details.
12 | #
13 | # You should have received a copy of the GNU General Public License along
14 | # with linesman. If not, see .
15 | #
16 | import cPickle
17 | import logging
18 | import sqlite3
19 | import time
20 |
21 | from linesman.backends.base import Backend
22 |
23 |
24 | try:
25 | # Python 2.7+
26 | from collections import OrderedDict
27 | except ImportError:
28 | # Python 2.4+
29 | from ordereddict import OrderedDict
30 |
31 |
32 | sqlite3.register_converter("pickle", cPickle.loads)
33 | log = logging.getLogger(__name__)
34 |
35 |
36 | class SqliteBackend(Backend):
37 | """
38 | Stores sessions in a SQLite database.
39 | """
40 |
41 | def __init__(self, filename="sessions.db"):
42 | """
43 | Opens up a connection to a sqlite3 database.
44 |
45 | ``filename``:
46 | filename of the sqlite database. If this file does not exist, it
47 | will be created automatically.
48 |
49 | This can also be set to `:memory:` to store the database in
50 | memory; however, this will not persist across runs.
51 | """
52 | self.filename = filename
53 |
54 | @property
55 | def conn(self):
56 | return sqlite3.connect(self.filename, isolation_level=None,
57 | detect_types=(sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES))
58 |
59 | def setup(self):
60 | """
61 | Creates table for Linesman, if it doesn't already exist.
62 | """
63 | query = """
64 | CREATE TABLE sessions (
65 | uuid PRIMARY KEY,
66 | timestamp FLOAT,
67 | session PICKLE
68 | );
69 | """
70 | try:
71 | c = self.conn.cursor()
72 | c.execute(query)
73 | except sqlite3.OperationalError:
74 | log.debug("Table already exists.")
75 |
76 | def add(self, session):
77 | """
78 | Insert a new session into the database.
79 | """
80 | uuid = session.uuid
81 | if session.timestamp:
82 | timestamp = time.mktime(session.timestamp.timetuple())
83 | else:
84 | timestamp = None
85 | pickled_session = sqlite3.Binary(cPickle.dumps(session, -1))
86 |
87 | query = "INSERT INTO sessions VALUES (?, ?, ?);"
88 | params = (uuid, timestamp, pickled_session)
89 |
90 | c = self.conn.cursor()
91 | c.execute(query, params)
92 |
93 | def delete(self, session_uuid):
94 | """
95 | Remove the session.
96 | """
97 | query = "DELETE FROM sessions WHERE uuid = ?;"
98 | params = (session_uuid,)
99 |
100 | conn = self.conn
101 | curs = conn.cursor()
102 | curs.execute(query, params)
103 |
104 | return conn.total_changes
105 |
106 | def delete_many(self, session_uuids):
107 | """
108 | Remove the sessions.
109 | """
110 | query = "DELETE FROM sessions WHERE uuid IN (%s);" % ", ".join('?' * len(session_uuids))
111 | params = session_uuids
112 |
113 | conn = self.conn
114 | curs = conn.cursor()
115 | curs.execute(query, params)
116 |
117 | return conn.total_changes
118 |
119 | def delete_all(self):
120 | """
121 | Truncate the database.
122 | """
123 | query = "DELETE FROM sessions;"
124 |
125 | conn = self.conn
126 | curs = conn.cursor()
127 | curs.execute(query)
128 |
129 | return conn.total_changes
130 |
131 | def get(self, session_uuid):
132 | """
133 | Retrieves the session from the database.
134 | """
135 | query = "SELECT session FROM sessions WHERE uuid = ?;"
136 | params = (session_uuid,)
137 |
138 | c = self.conn.cursor()
139 | c.execute(query, params)
140 | result = c.fetchone()
141 |
142 | return result[0] if result else None
143 |
144 | def get_all(self):
145 | """
146 | Generates a dictionary of the data based on the contents of the DB.
147 | """
148 | query = "SELECT uuid, session FROM sessions ORDER BY timestamp;"
149 |
150 | c = self.conn.cursor()
151 | c.execute(query)
152 |
153 | return OrderedDict(c.fetchall())
154 |
--------------------------------------------------------------------------------
/linesman/media/css/list.css:
--------------------------------------------------------------------------------
1 | /*
2 | * File: demo_table.css
3 | * CVS: $Id$
4 | * Description: CSS descriptions for DataTables demo pages
5 | * Author: Allan Jardine
6 | * Created: Tue May 12 06:47:22 BST 2009
7 | * Modified: $Date$ by $Author$
8 | * Language: CSS
9 | * Project: DataTables
10 | *
11 | * Copyright 2009 Allan Jardine. All Rights Reserved.
12 | *
13 | * ***************************************************************************
14 | * DESCRIPTION
15 | *
16 | * The styles given here are suitable for the demos that are used with the standard DataTables
17 | * distribution (see www.datatables.net). You will most likely wish to modify these styles to
18 | * meet the layout requirements of your site.
19 | *
20 | * Common issues:
21 | * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is
22 | * no conflict between the two pagination types. If you want to use full_numbers pagination
23 | * ensure that you either have "example_alt_pagination" as a body class name, or better yet,
24 | * modify that selector.
25 | * Note that the path used for Images is relative. All images are by default located in
26 | * ../images/ - relative to this CSS file.
27 | */
28 |
29 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
30 | * DataTables features
31 | */
32 |
33 | #sessions center {
34 | text-align: center;
35 | }
36 |
37 | #profiling-status { margin: 10px 0px; }
38 |
39 | #profiling-status-change {
40 | -moz-border-radius: 7px;
41 | -webkit-border-radius: 7px;
42 | -khtml-border-radius: 7px;
43 | border-radius: 7px;
44 | padding: 5px 10px;
45 | }
46 |
47 | #profiling-status-change.enabled { background: #00ff00; color: #000000; }
48 | #profiling-status-change.disabled { background: #ff0000; color: #000000;}
49 |
50 | .dataTables_wrapper {
51 | position: relative;
52 | min-height: 302px;
53 | clear: both;
54 | _height: 302px;
55 | zoom: 1; /* Feeling sorry for IE */
56 | }
57 |
58 | .dataTables_processing {
59 | position: absolute;
60 | top: 50%;
61 | left: 50%;
62 | width: 250px;
63 | height: 30px;
64 | margin-left: -125px;
65 | margin-top: -15px;
66 | padding: 14px 0 2px 0;
67 | border: 1px solid #ddd;
68 | text-align: center;
69 | color: #999;
70 | font-size: 14px;
71 | background-color: white;
72 | }
73 |
74 | .dataTables_length {
75 | width: 40%;
76 | float: left;
77 | }
78 |
79 | .dataTables_filter {
80 | width: 50%;
81 | float: right;
82 | text-align: right;
83 | }
84 |
85 | .dataTables_info {
86 | width: 60%;
87 | float: left;
88 | }
89 |
90 | .dataTables_paginate {
91 | width: 44px;
92 | * width: 50px;
93 | float: right;
94 | text-align: right;
95 | }
96 |
97 | /* Pagination nested */
98 | .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next {
99 | height: 19px;
100 | width: 19px;
101 | margin-left: 3px;
102 | float: left;
103 | }
104 |
105 | .paginate_disabled_previous {
106 | background-image: url('../images/back_disabled.jpg');
107 | }
108 |
109 | .paginate_enabled_previous {
110 | background-image: url('../images/back_enabled.jpg');
111 | }
112 |
113 | .paginate_disabled_next {
114 | background-image: url('../images/forward_disabled.jpg');
115 | }
116 |
117 | .paginate_enabled_next {
118 | background-image: url('../images/forward_enabled.jpg');
119 | }
120 |
121 |
122 |
123 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
124 | * DataTables display
125 | */
126 | table.display {
127 | margin: 0 auto;
128 | clear: both;
129 | width: 100%;
130 |
131 | /* Note Firefox 3.5 and before have a bug with border-collapse
132 | * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 )
133 | * border-spacing: 0; is one possible option. Conditional-css.com is
134 | * useful for this kind of thing
135 | *
136 | * Further note IE 6/7 has problems when calculating widths with border width.
137 | * It subtracts one px relative to the other browsers from the first column, and
138 | * adds one to the end...
139 | *
140 | * If you want that effect I'd suggest setting a border-top/left on th/td's and
141 | * then filling in the gaps with other borders.
142 | */
143 | }
144 |
145 | table.display thead th {
146 | padding: 3px 18px 3px 10px;
147 | border-bottom: 1px solid black;
148 | font-weight: bold;
149 | cursor: pointer;
150 | * cursor: hand;
151 | }
152 |
153 | table.display tfoot th {
154 | padding: 3px 18px 3px 10px;
155 | border-top: 1px solid black;
156 | font-weight: bold;
157 | }
158 |
159 | table.display tr.heading2 td {
160 | border-bottom: 1px solid #aaa;
161 | }
162 |
163 | table.display td {
164 | padding: 3px 10px;
165 | }
166 |
167 | table.display td.center {
168 | text-align: center;
169 | }
170 |
171 |
172 |
173 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
174 | * DataTables sorting
175 | */
176 |
177 | .sorting_asc {
178 | background: url('../images/sort_asc.png') no-repeat center right;
179 | }
180 |
181 | .sorting_desc {
182 | background: url('../images/sort_desc.png') no-repeat center right;
183 | }
184 |
185 | .sorting {
186 | background: url('../images/sort_both.png') no-repeat center right;
187 | }
188 |
189 | .sorting_asc_disabled {
190 | background: url('../images/sort_asc_disabled.png') no-repeat center right;
191 | }
192 |
193 | .sorting_desc_disabled {
194 | background: url('../images/sort_desc_disabled.png') no-repeat center right;
195 | }
196 |
197 |
198 |
199 |
200 |
201 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
202 | * DataTables row classes
203 | */
204 | table.display tr.odd.gradeA {
205 | background-color: #ddffdd;
206 | }
207 |
208 | table.display tr.even.gradeA {
209 | background-color: #eeffee;
210 | }
211 |
212 | table.display tr.odd.gradeC {
213 | background-color: #ddddff;
214 | }
215 |
216 | table.display tr.even.gradeC {
217 | background-color: #eeeeff;
218 | }
219 |
220 | table.display tr.odd.gradeX {
221 | background-color: #ffdddd;
222 | }
223 |
224 | table.display tr.even.gradeX {
225 | background-color: #ffeeee;
226 | }
227 |
228 | table.display tr.odd.gradeU {
229 | background-color: #ddd;
230 | }
231 |
232 | table.display tr.even.gradeU {
233 | background-color: #eee;
234 | }
235 |
236 |
237 | tr.odd {
238 | background-color: #E2E4FF;
239 | }
240 |
241 | tr.even {
242 | background-color: white;
243 | }
244 |
245 |
246 |
247 |
248 |
249 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
250 | * Misc
251 | */
252 | .dataTables_scroll {
253 | clear: both;
254 | }
255 |
256 | .dataTables_scrollBody {
257 | *margin-top: -1px;
258 | }
259 |
260 | .top, .bottom {
261 | padding: 15px;
262 | background-color: #F5F5F5;
263 | border: 1px solid #CCCCCC;
264 | }
265 |
266 | .top .dataTables_info {
267 | float: none;
268 | }
269 |
270 | .clear {
271 | clear: both;
272 | }
273 |
274 | .dataTables_empty {
275 | text-align: center;
276 | }
277 |
278 | tfoot input {
279 | margin: 0.5em 0;
280 | width: 100%;
281 | color: #444;
282 | }
283 |
284 | tfoot input.search_init {
285 | color: #999;
286 | }
287 |
288 | td.group {
289 | background-color: #d1cfd0;
290 | border-bottom: 2px solid #A19B9E;
291 | border-top: 2px solid #A19B9E;
292 | }
293 |
294 | td.details {
295 | background-color: #d1cfd0;
296 | border: 2px solid #A19B9E;
297 | }
298 |
299 |
300 | .example_alt_pagination div.dataTables_info {
301 | width: 40%;
302 | }
303 |
304 | .paging_full_numbers {
305 | width: 400px;
306 | height: 22px;
307 | line-height: 22px;
308 | }
309 |
310 | .paging_full_numbers span.paginate_button,
311 | .paging_full_numbers span.paginate_active {
312 | border: 1px solid #aaa;
313 | -webkit-border-radius: 5px;
314 | -moz-border-radius: 5px;
315 | padding: 2px 5px;
316 | margin: 0 3px;
317 | cursor: pointer;
318 | *cursor: hand;
319 | }
320 |
321 | .paging_full_numbers span.paginate_button {
322 | background-color: #ddd;
323 | }
324 |
325 | .paging_full_numbers span.paginate_button:hover {
326 | background-color: #ccc;
327 | }
328 |
329 | .paging_full_numbers span.paginate_active {
330 | background-color: #99B3FF;
331 | }
332 |
333 | table.display tr.even.row_selected td {
334 | background-color: #B0BED9;
335 | }
336 |
337 | table.display tr.odd.row_selected td {
338 | background-color: #9FAFD1;
339 | }
340 |
341 |
342 | /*
343 | * Sorting classes for columns
344 | */
345 | /* For the standard odd/even */
346 | tr.odd td.sorting_1 {
347 | background-color: #D3D6FF;
348 | }
349 |
350 | tr.odd td.sorting_2 {
351 | background-color: #DADCFF;
352 | }
353 |
354 | tr.odd td.sorting_3 {
355 | background-color: #E0E2FF;
356 | }
357 |
358 | tr.even td.sorting_1 {
359 | background-color: #EAEBFF;
360 | }
361 |
362 | tr.even td.sorting_2 {
363 | background-color: #F2F3FF;
364 | }
365 |
366 | tr.even td.sorting_3 {
367 | background-color: #F9F9FF;
368 | }
369 |
370 |
371 | /* For the Conditional-CSS grading rows */
372 | /*
373 | Colour calculations (based off the main row colours)
374 | Level 1:
375 | dd > c4
376 | ee > d5
377 | Level 2:
378 | dd > d1
379 | ee > e2
380 | */
381 | tr.odd.gradeA td.sorting_1 {
382 | background-color: #c4ffc4;
383 | }
384 |
385 | tr.odd.gradeA td.sorting_2 {
386 | background-color: #d1ffd1;
387 | }
388 |
389 | tr.odd.gradeA td.sorting_3 {
390 | background-color: #d1ffd1;
391 | }
392 |
393 | tr.even.gradeA td.sorting_1 {
394 | background-color: #d5ffd5;
395 | }
396 |
397 | tr.even.gradeA td.sorting_2 {
398 | background-color: #e2ffe2;
399 | }
400 |
401 | tr.even.gradeA td.sorting_3 {
402 | background-color: #e2ffe2;
403 | }
404 |
405 | tr.odd.gradeC td.sorting_1 {
406 | background-color: #c4c4ff;
407 | }
408 |
409 | tr.odd.gradeC td.sorting_2 {
410 | background-color: #d1d1ff;
411 | }
412 |
413 | tr.odd.gradeC td.sorting_3 {
414 | background-color: #d1d1ff;
415 | }
416 |
417 | tr.even.gradeC td.sorting_1 {
418 | background-color: #d5d5ff;
419 | }
420 |
421 | tr.even.gradeC td.sorting_2 {
422 | background-color: #e2e2ff;
423 | }
424 |
425 | tr.even.gradeC td.sorting_3 {
426 | background-color: #e2e2ff;
427 | }
428 |
429 | tr.odd.gradeX td.sorting_1 {
430 | background-color: #ffc4c4;
431 | }
432 |
433 | tr.odd.gradeX td.sorting_2 {
434 | background-color: #ffd1d1;
435 | }
436 |
437 | tr.odd.gradeX td.sorting_3 {
438 | background-color: #ffd1d1;
439 | }
440 |
441 | tr.even.gradeX td.sorting_1 {
442 | background-color: #ffd5d5;
443 | }
444 |
445 | tr.even.gradeX td.sorting_2 {
446 | background-color: #ffe2e2;
447 | }
448 |
449 | tr.even.gradeX td.sorting_3 {
450 | background-color: #ffe2e2;
451 | }
452 |
453 | tr.odd.gradeU td.sorting_1 {
454 | background-color: #c4c4c4;
455 | }
456 |
457 | tr.odd.gradeU td.sorting_2 {
458 | background-color: #d1d1d1;
459 | }
460 |
461 | tr.odd.gradeU td.sorting_3 {
462 | background-color: #d1d1d1;
463 | }
464 |
465 | tr.even.gradeU td.sorting_1 {
466 | background-color: #d5d5d5;
467 | }
468 |
469 | tr.even.gradeU td.sorting_2 {
470 | background-color: #e2e2e2;
471 | }
472 |
473 | tr.even.gradeU td.sorting_3 {
474 | background-color: #e2e2e2;
475 | }
476 |
477 |
478 | /*
479 | * Row highlighting example
480 | */
481 | .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted {
482 | background-color: #ECFFB3;
483 | }
484 |
485 | .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted {
486 | background-color: #E6FF99;
487 | }
488 |
489 | .ex_highlight_row #example tr.even:hover {
490 | background-color: #ECFFB3;
491 | }
492 |
493 | .ex_highlight_row #example tr.even:hover td.sorting_1 {
494 | background-color: #DDFF75;
495 | }
496 |
497 | .ex_highlight_row #example tr.even:hover td.sorting_2 {
498 | background-color: #E7FF9E;
499 | }
500 |
501 | .ex_highlight_row #example tr.even:hover td.sorting_3 {
502 | background-color: #E2FF89;
503 | }
504 |
505 | .ex_highlight_row #example tr.odd:hover {
506 | background-color: #E6FF99;
507 | }
508 |
509 | .ex_highlight_row #example tr.odd:hover td.sorting_1 {
510 | background-color: #D6FF5C;
511 | }
512 |
513 | .ex_highlight_row #example tr.odd:hover td.sorting_2 {
514 | background-color: #E0FF84;
515 | }
516 |
517 | .ex_highlight_row #example tr.odd:hover td.sorting_3 {
518 | background-color: #DBFF70;
519 | }
520 |
521 |
522 | /*
523 | * KeyTable
524 | */
525 | table.KeyTable td {
526 | border: 3px solid transparent;
527 | }
528 |
529 | table.KeyTable td.focus {
530 | border: 3px solid #3366FF;
531 | }
532 |
533 | table.display tr.gradeA {
534 | background-color: #eeffee;
535 | }
536 |
537 | table.display tr.gradeC {
538 | background-color: #ddddff;
539 | }
540 |
541 | table.display tr.gradeX {
542 | background-color: #ffdddd;
543 | }
544 |
545 | table.display tr.gradeU {
546 | background-color: #ddd;
547 | }
548 |
549 | div.box {
550 | height: 100px;
551 | padding: 10px;
552 | overflow: auto;
553 | border: 1px solid #8080FF;
554 | background-color: #E5E5FF;
555 | }
556 |
--------------------------------------------------------------------------------
/linesman/media/css/tree.css:
--------------------------------------------------------------------------------
1 | #callgraph { border: 1px solid black; padding: 1em; }
2 |
3 | #callhierarchy { font-family: monospace; font-size: small; }
4 | #callhierarchy li { width: 100%; padding-top: 3px; border: 0; }
5 | #callhierarchy li.open { list-style-image: url('../images/open.gif'); }
6 | #callhierarchy li.closed { list-style-image: url('../images/closed.gif'); }
7 | #callhierarchy li.leaf { list-style: square; }
8 | #callhierarchy .header { list-style: none; font-weight: bold; }
9 | #callhierarchy ul { padding-left:5px; }
10 | #callhierarchy span.row { width: 100%; display: inline-block; }
11 | #callhierarchy li.profile-stats span.row:hover { background-color: #dedede; }
12 | #callhierarchy .module { width: 70%; }
13 | #callhierarchy .measurements {
14 | display: inline-block;
15 | float: right;
16 | }
17 | #callhierarchy .count {
18 | width: 100px;
19 | display: inline-block;
20 | }
21 | #callhierarchy .time {
22 | width: 100px;
23 | display: inline-block;
24 | }
25 | #callhierarchy .graph {
26 | width: 200px;
27 | display: inline-block;
28 | }
29 | #callhierarchy span.bar-inlinetime {
30 | background-color: gray;
31 | display: inline-block;
32 | padding: 0;
33 | margin: 0;
34 | }
35 | #callhierarchy span.bar-totaltime {
36 | background-color: black;
37 | display: inline-block;
38 | padding: 0;
39 | margin: 0;
40 | color: white;
41 | }
42 |
43 |
--------------------------------------------------------------------------------
/linesman/media/images/back_disabled.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/back_disabled.jpg
--------------------------------------------------------------------------------
/linesman/media/images/back_enabled.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/back_enabled.jpg
--------------------------------------------------------------------------------
/linesman/media/images/closed.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/closed.gif
--------------------------------------------------------------------------------
/linesman/media/images/forward_disabled.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/forward_disabled.jpg
--------------------------------------------------------------------------------
/linesman/media/images/forward_enabled.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/forward_enabled.jpg
--------------------------------------------------------------------------------
/linesman/media/images/open.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/open.gif
--------------------------------------------------------------------------------
/linesman/media/images/sort_asc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/sort_asc.png
--------------------------------------------------------------------------------
/linesman/media/images/sort_asc_disabled.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/sort_asc_disabled.png
--------------------------------------------------------------------------------
/linesman/media/images/sort_both.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/sort_both.png
--------------------------------------------------------------------------------
/linesman/media/images/sort_desc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/sort_desc.png
--------------------------------------------------------------------------------
/linesman/media/images/sort_desc_disabled.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amcfague/linesman/dbf2f154b17e78469c190fcc5341278d11aa89c1/linesman/media/images/sort_desc_disabled.png
--------------------------------------------------------------------------------
/linesman/media/js/accordian.js:
--------------------------------------------------------------------------------
1 | $(function(){
2 | var slideSpeed = "fast";
3 | $('#callhierarchy .row').click(function() {
4 | // navigate up to the nearest parent list item
5 | var parent_li = $(this).parent('li');
6 | if (parent_li.hasClass('leaf')) {
7 | return false;
8 | }
9 | parent_li.children('ul').toggle(slideSpeed);
10 | parent_li.toggleClass('open closed');
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/linesman/media/js/tables.js:
--------------------------------------------------------------------------------
1 | var asInitVals = new Array();
2 | var oTable;
3 |
4 | $(document).ready(function() {
5 | $("#sessions a.delete").click(function() {
6 | // Get the enclosing row
7 | var parent_tr = $(this).closest("tr");
8 |
9 | // Fade out this row and delete it from the table
10 | $(parent_tr).fadeOut(200, function() {
11 | oTable.fnDeleteRow(parent_tr[0]);
12 | });
13 |
14 | // And of course, delete the row from our database
15 | $.ajax($(this).attr("href"));
16 |
17 | return false;
18 | });
19 |
20 | $("#delete_listed").click(function() {
21 | // Only remove the filtered nodes!
22 | nodes = oTable.fnGetFilteredNodes();
23 |
24 | // Next, confirm that this is what the user really wants!
25 | msg = "You are about to remove " + nodes.length + " saved sessions." +
26 | "\n\nPress OK to delete these sessions.";
27 | if(!confirm(msg))
28 | return false;
29 |
30 | var session_uuids = [];
31 | for(i=0; i < nodes.length; i++) {
32 | // Remove these sessions from the backend
33 | session_uuids.push(nodes[i].id);
34 | // And, of course, remove the rows
35 | oTable.fnDeleteRow(nodes[i]);
36 | }
37 | $.post(PATH+'/delete', {'session_uuids':session_uuids});
38 | // Also clear the search input and manually trigger the keyup event
39 | $("tfoot input").val("").keyup();
40 | // Restore the "Filter by ..." text.
41 | $("tfoot input").blur();
42 |
43 | return false;
44 | });
45 |
46 | // Add the ability to retrieve a list of all filtered rows
47 | $.fn.dataTableExt.oApi.fnGetFilteredNodes = function ( oSettings )
48 | {
49 | var anRows = [];
50 | for ( var i=0, iLen=oSettings.aiDisplay.length ; i 0) {
126 | asInitVals[i] = $("tfoot input")[i].value;
127 | $("tfoot input")[i].value = oSettings.aoPreSearchCols[i].sSearch;
128 | $("tfoot input")[i].className = "";
129 | }
130 | }
131 | },
132 | iDisplayLength: 20,
133 | oLanguage: {
134 | "sSearch": "Search all columns:"
135 | },
136 | sDom: 'lprtip',
137 | sPaginationType: "full_numbers"
138 | } );
139 |
140 | $("tfoot input").keyup( function () {
141 | /* Filter on the column (the index) of this element */
142 | oTable.fnFilter( this.value, $("tfoot input").index(this) );
143 | } );
144 |
145 | } );
146 |
--------------------------------------------------------------------------------
/linesman/middleware.py:
--------------------------------------------------------------------------------
1 | # This file is part of linesman.
2 | #
3 | # linesman is free software: you can redistribute it and/or modify it under
4 | # the terms of the GNU General Public License as published by the Free
5 | # Software Foundation, either version 3 of the License, or (at your option)
6 | # any later version.
7 | #
8 | # linesman is distributed in the hope that it will be useful, but WITHOUT ANY
9 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 | # details.
12 | #
13 | # You should have received a copy of the GNU General Public License along
14 | # with linesman. If not, see .
15 | #
16 | import logging
17 | import os
18 | from cProfile import Profile
19 | from datetime import datetime
20 | from tempfile import gettempdir
21 |
22 | from PIL import Image
23 | import networkx as nx
24 | from mako.lookup import TemplateLookup
25 | from paste.urlparser import StaticURLParser
26 | from pkg_resources import resource_filename
27 | from webob import Request, Response
28 | from webob.exc import HTTPNotFound
29 |
30 | from linesman import ProfilingSession, draw_graph
31 |
32 |
33 | log = logging.getLogger(__name__)
34 |
35 | # Graphs
36 | GRAPH_DIR = os.path.join(gettempdir(), "linesman-graph")
37 | MEDIA_DIR = resource_filename("linesman", "media")
38 | TEMPLATES_DIR = resource_filename("linesman", "templates")
39 | ENABLED_FLAG_FILE = 'linesman-enabled'
40 |
41 | CUTOFF_TIME_UNITS = 1e9 # Nanoseconds per second
42 |
43 |
44 | class ProfilingMiddleware(object):
45 | """
46 | This wraps calls to the WSGI application with cProfile, storing the
47 | output and providing useful graphs for the user to view.
48 |
49 | ``app``:
50 | WSGI application
51 | ``profiler_path``:
52 | Path relative to the root to look up. For example, if your script is
53 | mounted at the context `/someapp` and this variable is set to
54 | `/__profiler__`, `/someapp/__profiler__` will match.
55 | ``backend``:
56 | This should be a full module path, with the function or class name
57 | specified after the trailing `:`. This function or class should return
58 | an implementation of :class:`~linesman.backend.Backend`.
59 | ``chart_packages``:
60 | Space separated list of packages to be charted in the pie graph.
61 | """
62 |
63 | def __init__(self, app,
64 | profiler_path="/__profiler__",
65 | backend="linesman.backends.sqlite:SqliteBackend",
66 | chart_packages="",
67 | **kwargs):
68 | self.app = app
69 | self.profiler_path = profiler_path
70 |
71 | # Always reverse sort these packages, so that child packages of the
72 | # same module will always be picked first.
73 | self.chart_packages = sorted(chart_packages.split(), reverse=True)
74 |
75 | # Setup the backend
76 | module_name, sep, class_name = backend.rpartition(":")
77 | module = __import__(module_name, fromlist=[class_name], level=0)
78 | self._backend = getattr(module, class_name)(**kwargs)
79 |
80 | # Attempt to create the GRAPH_DIR
81 | if not os.path.exists(GRAPH_DIR):
82 | try:
83 | os.makedirs(GRAPH_DIR)
84 | except IOError:
85 | log.error("Could not create directory `%s'", GRAPH_DIR)
86 | raise
87 |
88 | # Setup the Mako template lookup
89 | self.template_lookup = TemplateLookup(directories=[TEMPLATES_DIR])
90 |
91 | # Set it up
92 | self._backend.setup()
93 |
94 | def __call__(self, environ, start_response):
95 | """
96 | This will be called when the application is being run. This can be
97 | either:
98 |
99 | - a request to the __profiler__ framework to display profiled
100 | information, or
101 | - a normal request that will be profiled.
102 |
103 | Returns the WSGI application.
104 | """
105 | # If we're not accessing the profiler, profile the request.
106 | req = Request(environ)
107 |
108 | self.profiling_enabled = os.path.exists(ENABLED_FLAG_FILE)
109 | if req.path_info_peek() != self.profiler_path.strip('/'):
110 | if not self.profiling_enabled:
111 | return self.app(environ, start_response)
112 | _locals = locals()
113 | prof = Profile()
114 | start_timestamp = datetime.now()
115 | prof.runctx(
116 | "app = self.app(environ, start_response)", globals(), _locals)
117 | stats = prof.getstats()
118 | session = ProfilingSession(stats, environ, start_timestamp)
119 | self._backend.add(session)
120 |
121 | return _locals['app']
122 |
123 | req.path_info_pop()
124 |
125 | # We could import `routes` and use something like that here, but since
126 | # not all frameworks use this, it might become an external dependency
127 | # that isn't needed. So parse the URL manually using :class:`webob`.
128 | query_param = req.path_info_pop()
129 | if not query_param:
130 | wsgi_app = self.list_profiles(req)
131 | elif query_param == "graph":
132 | wsgi_app = self.render_graph(req)
133 | elif query_param == "media":
134 | wsgi_app = self.media(req)
135 | elif query_param == "profiles":
136 | wsgi_app = self.show_profile(req)
137 | elif query_param == "delete":
138 | wsgi_app = self.delete_profile(req)
139 | else:
140 | wsgi_app = HTTPNotFound()
141 |
142 | return wsgi_app(environ, start_response)
143 |
144 | def get_template(self, template):
145 | """
146 | Uses mako templating lookups to retrieve the template file. If the
147 | file is ever changed underneath, this function will automatically
148 | retrieve and recompile the new version.
149 |
150 | ``template``:
151 | Filename of the template, relative to the `linesman/templates`
152 | directory.
153 | """
154 | return self.template_lookup.get_template(template)
155 |
156 | def list_profiles(self, req):
157 | """
158 | Displays all available profiles in list format.
159 |
160 | ``req``:
161 | :class:`webob.Request` containing the environment information from
162 | the request itself.
163 |
164 | Returns a WSGI application.
165 | """
166 | if 'enable' in req.params:
167 | try:
168 | if not os.path.exists(ENABLED_FLAG_FILE):
169 | open(ENABLED_FLAG_FILE, 'w').close()
170 | self.profiling_enabled = True
171 | except IOError:
172 | log.error("Unable to create %s to enable profiling",
173 | os.path.abspath(ENABLED_FLAG_FILE))
174 | raise
175 | elif 'disable' in req.params:
176 | try:
177 | if os.path.exists(ENABLED_FLAG_FILE):
178 | os.remove(ENABLED_FLAG_FILE)
179 | self.profiling_enabled = False
180 | except IOError:
181 | log.error("Unable to delete %s to disable profiling",
182 | os.path.abspath(ENABLED_FLAG_FILE))
183 | raise
184 |
185 | resp = Response(charset='utf8')
186 | session_history = self._backend.get_all()
187 | resp.unicode_body = self.get_template('list.tmpl').render_unicode(
188 | history=session_history,
189 | path=req.path,
190 | profiling_enabled=self.profiling_enabled)
191 | return resp
192 |
193 | def media(self, req):
194 | """
195 | Serves up static files relative to ``MEDIA_DIR``.
196 |
197 | ``req``:
198 | :class:`webob.Request` containing the environment information from
199 | the request itself.
200 |
201 | Returns a WSGI application.
202 | """
203 | return StaticURLParser(MEDIA_DIR)
204 |
205 | def render_graph(self, req):
206 | """
207 | Used to display rendered graphs; if the graph that the user is trying
208 | to access does not exist--and the ``session_uuid`` exists in our
209 | history--it will be rendered.
210 |
211 | This also creates a thumbnail image, since some of these graphs can
212 | grow to be extremely large.
213 |
214 | ``req``:
215 | :class:`webob.Request` containing the environment information from
216 | the request itself.
217 |
218 | Returns a WSGI application.
219 | """
220 | path_info = req.path_info_peek()
221 | if '.' not in path_info:
222 | return StaticURLParser(GRAPH_DIR)
223 |
224 | fileid, _, ext = path_info.rpartition('.')
225 | if path_info.startswith("thumb-"):
226 | fileid = fileid[6:]
227 |
228 | if '--' not in fileid:
229 | return StaticURLParser(GRAPH_DIR)
230 |
231 | session_uuid, _, cutoff_time = fileid.rpartition('--')
232 | cutoff_time = int(cutoff_time)
233 |
234 | # We now have the session_uuid
235 | session = self._backend.get(session_uuid)
236 | if session:
237 | force_thumbnail_creation = False
238 |
239 | filename = "%s.png" % fileid
240 | path = os.path.join(GRAPH_DIR, filename)
241 | if not os.path.exists(path):
242 | graph, root_nodes, removed_edges = prepare_graph(
243 | session._graph, cutoff_time, False)
244 | draw_graph(graph, path)
245 | force_thumbnail_creation = True
246 |
247 | thumbnail_filename = "thumb-%s.png" % fileid
248 | thumbnail_path = os.path.join(GRAPH_DIR, thumbnail_filename)
249 | if not os.path.exists(thumbnail_path) or force_thumbnail_creation:
250 | log.debug("Creating thumbnail for %s at %s.", session_uuid,
251 | thumbnail_path)
252 | im = Image.open(path, 'r')
253 | im.thumbnail((600, 600), Image.ANTIALIAS)
254 | im.save(thumbnail_path)
255 |
256 | return StaticURLParser(GRAPH_DIR)
257 |
258 | def delete_profile(self, req):
259 | """
260 | If the current path info refers to a specific ``session_uuid``, this
261 | session will be removed. Otherwise, if it refers to `all`, then all
262 | tracked session info will be removed.
263 |
264 | ``req``:
265 | :class:`webob.Request` containing the environment information from
266 | the request itself.
267 |
268 | Returns a WSGI application.
269 | """
270 | resp = Response(charset='utf8')
271 | session_uuid = req.path_info_pop()
272 | if session_uuid == "all":
273 | deleted_rows = self._backend.delete_all()
274 | elif session_uuid:
275 | deleted_rows = self._backend.delete(session_uuid)
276 | else:
277 | deleted_rows = 0
278 | session_uuids = req.POST.getall('session_uuids[]')
279 | if session_uuids:
280 | deleted_rows = self._backend.delete_many(session_uuids)
281 |
282 | resp.text = u"%d row(s) deleted." % deleted_rows
283 |
284 | return resp
285 |
286 | def show_profile(self, req):
287 | """
288 | Displays specific profile information for the ``session_uuid``
289 | specified in the path.
290 |
291 | ``req``:
292 | :class:`webob.Request` containing the environment information from
293 | the request itself.
294 |
295 | Returns a WSGI application.
296 | """
297 | resp = Response(charset='utf8')
298 | session_uuid = req.path_info_pop()
299 | session = self._backend.get(session_uuid)
300 |
301 | # If the Session doesn't exist, return an appropriate error
302 | if not session:
303 | resp.status = "404 Not Found"
304 | resp.text = u"Session `%s' not found." % session_uuid
305 | else:
306 | # Otherwise, prepare the graph for display!
307 | cutoff_percentage = float(
308 | req.params.get('cutoff_percent', 5) or 5) / 100
309 | cutoff_time = int(
310 | session.duration * cutoff_percentage * CUTOFF_TIME_UNITS)
311 | graph, root_nodes, removed_edges = prepare_graph(
312 | session._graph, cutoff_time, True)
313 | chart_values = time_per_field(session._graph, root_nodes,
314 | self.chart_packages)
315 | resp.unicode_body = self.get_template('tree.tmpl').render_unicode(
316 | session=session,
317 | graph=graph,
318 | root_nodes=root_nodes,
319 | removed_edges=removed_edges,
320 | application_url=self.profiler_path,
321 | cutoff_percentage=cutoff_percentage,
322 | cutoff_time=cutoff_time,
323 | chart_values=chart_values
324 | )
325 | return resp
326 |
327 |
328 | def time_per_field(full_graph, root_nodes, fields):
329 | """
330 | This function generates the fields used by the pie graph jQuery code on the
331 | session profile page. This process is clever about calculating total time,
332 | so that packages and subpackages don't overlap.
333 |
334 | Additionally, if I were to track ``linesman.middleware``, and in that
335 | package an external package is called, say ``re``, the time spent in ``re``
336 | would be added to the total time in package ``linesman.middleware``, unless
337 | ``re`` is one of the fields that are being tracked.
338 |
339 | ``full_graph``:
340 | For best results, this should be an untouched copy of the original
341 | graph. The reasoning is because, if certain packages are pruned, the
342 | graph result could be completely varied and inaccurate.
343 | ``root_nodes``:
344 | The list of starting point for this graph.
345 | ``fields``:
346 | The list of packages to be tracked.
347 |
348 | Returns a dictionary where the keys are the same as the ``fields``, plus an
349 | extra field called `Other` that contains packages that were not tracked.
350 | The values for each field is the total time spent in that package.
351 |
352 | .. warning::
353 |
354 | This will run into issues where separate packages rely on the same core
355 | set of functions. I.e., of `PackageA` and `PackageB` both rely on
356 | ``re``, there's no defined outcome. Whichever one is parsed first will
357 | include the time spent in ``re``.
358 | """
359 | if not fields:
360 | return
361 |
362 | # Keep track of all the nodes we've seen.
363 | seen_nodes = []
364 | values = dict((field, 0.0) for field in fields)
365 | values["Other"] = 0.0
366 |
367 | def is_field(node_name):
368 | """
369 | Returns True if ``node_name`` is part of the ``fields`` that should be
370 | tracked.
371 | """
372 | for field in fields:
373 | if node_name.startswith(field + "."):
374 | return field
375 | return None
376 |
377 | def recursive_parse(node_name, last_seen_field=None):
378 | """
379 | Given a node, follow its descendents and append their runtimes to the
380 | last seen "tracked" field.
381 | """
382 | if node_name in seen_nodes:
383 | return
384 | seen_nodes.append(node_name)
385 |
386 | field = is_field(node_name)
387 | inlinetime = full_graph.node[node_name]['inlinetime']
388 | if field:
389 | last_seen_field = field
390 |
391 | if last_seen_field:
392 | values[last_seen_field] += inlinetime
393 | else:
394 | values["Other"] += inlinetime
395 |
396 | # Parse the successors
397 | for node in full_graph.successors(node_name):
398 | recursive_parse(node, last_seen_field)
399 |
400 | for root_node in root_nodes:
401 | recursive_parse(root_node)
402 |
403 | return values
404 |
405 |
406 | def prepare_graph(source_graph, cutoff_time, break_cycles=False):
407 | """
408 | Prepares a graph for display. This includes:
409 |
410 | - removing subgraphs based on a cutoff time
411 | - breaking cycles
412 |
413 | Returns a tuple of (new_graph, removed_edges)
414 | """
415 | # Always use a copy for destructive changes
416 | graph = source_graph.copy()
417 |
418 | # Some node data could be empty dict
419 | for node, data in graph.nodes(data=True):
420 | if not data:
421 | data['totaltime'] = 0
422 |
423 | max_totaltime = max(data['totaltime']
424 | for node, data in graph.nodes(data=True))
425 | for node, data in graph.nodes(data=True):
426 | data['color'] = "%f 1.0 1.0" % (
427 | (1 - (data['totaltime'] / max_totaltime)) / 3)
428 | data['style'] = 'filled'
429 |
430 | cyclic_breaks = []
431 |
432 | # Remove nodes where the totaltime is greater than the cutoff time
433 | graph.remove_nodes_from([
434 | node
435 | for node, data in graph.nodes(data=True)
436 | if int(data.get('totaltime') * CUTOFF_TIME_UNITS) < cutoff_time])
437 |
438 | # Break cycles
439 | if break_cycles:
440 | for cycle in nx.simple_cycles(graph):
441 | u, v = cycle[0], cycle[1]
442 | if graph.has_edge(u, v):
443 | graph.remove_edge(u, v)
444 | cyclic_breaks.append((u, v))
445 |
446 | root_nodes = [node
447 | for node, degree in graph.in_degree_iter()
448 | if degree == 0]
449 |
450 | return graph, root_nodes, cyclic_breaks
451 |
452 |
453 | def profiler_filter_factory(conf, **kwargs):
454 | """
455 | Factory for creating :mod:`paste` filters. Full documentation can be found
456 | in `the paste docs `_.
457 | """
458 | def filter(app):
459 | return ProfilingMiddleware(app, **kwargs)
460 | return filter
461 |
462 |
463 | def profiler_filter_app_factory(app, conf, **kwargs):
464 | """
465 | Creates a single :mod:`paste` filter. Full documentation can be found in
466 | `the paste docs `_.
467 | """
468 | return ProfilingMiddleware(app, **kwargs)
469 |
470 |
471 | def make_linesman_middleware(app, **kwargs):
472 | """
473 | Helper function for wrapping an application with :mod:`!linesman`. This
474 | can be used when manually wrapping middleware, although its also possible
475 | to simply call :class:`~linesman.middleware.ProfilingMiddleware` directly.
476 | """
477 | return ProfilingMiddleware(app, **kwargs)
478 |
--------------------------------------------------------------------------------
/linesman/templates/list.tmpl:
--------------------------------------------------------------------------------
1 |
2 |
3 | Linesman - Showing all profiles
4 |
5 |
7 |
9 |
11 |
14 |
15 |
16 |
17 |
18 | % if profiling_enabled:
19 | Profiling is enabled
20 | % else:
21 | Profiling is disabled
22 | % endif
23 |