pax_global_header 0000666 0000000 0000000 00000000064 13456064662 0014526 g ustar 00root root 0000000 0000000 52 comment=c92dcb05ca8285c490169fbe9bbfb3869b950f37
fenics-project-dijitso-c92dcb05ca82/ 0000775 0000000 0000000 00000000000 13456064662 0017337 5 ustar 00root root 0000000 0000000 fenics-project-dijitso-c92dcb05ca82/.circleci/ 0000775 0000000 0000000 00000000000 13456064662 0021172 5 ustar 00root root 0000000 0000000 fenics-project-dijitso-c92dcb05ca82/.circleci/config.yml 0000664 0000000 0000000 00000001234 13456064662 0023162 0 ustar 00root root 0000000 0000000 version: 2
jobs:
build:
docker:
- image: circleci/python:3.6
working_directory: ~/dijitso-test
steps:
- checkout
- run:
name: Install dependencies # Install with sudo as tests not run as superuser in circleci/python
command: |
sudo apt-get update && sudo apt-get install python3-mpi4py
sudo pip install flake8 pytest numpy --upgrade
- run:
name: Install dijitso
command: pip install . --user
- run:
name: Run flake8 tests
command: python -m flake8 .
- run:
name: Run unit tests
command: python -m pytest ./test/
fenics-project-dijitso-c92dcb05ca82/COPYING 0000664 0000000 0000000 00000104513 13456064662 0020376 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
fenics-project-dijitso-c92dcb05ca82/COPYING.LESSER 0000664 0000000 0000000 00000016727 13456064662 0021403 0 ustar 00root root 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
fenics-project-dijitso-c92dcb05ca82/ChangeLog.rst 0000664 0000000 0000000 00000002004 13456064662 0021714 0 ustar 00root root 0000000 0000000 Changelog
=========
2019.2.0.dev0
-------------
- No changes so far.
2019.1.0 (2019-04-19)
---------------------
- No changes.
2018.1.0 (2018-06-14)
---------------------
- Very minor cleanups
2017.2.0 (2017-12-05)
---------------------
- Add support for linking external libraries
- Add support for creating a loadable module with __import__ with "lib_loader" parameter (ctypes, module)
2017.1.0.post1 (2017-09-12)
---------------------
- Change PyPI package name to fenics-dijitso.
2017.1.0 (2017-05-09)
---------------------
- Minor fixes
2016.2.0 (2016-11-30)
---------------------
- Introduce commandline script ``dijitso`` with various subcommands to
interact with the cache
- Improve extraction of source files to reproduce compilation failure
during jit
- Implement support for linking between jit modules
- Add optional dependency on ``subprocess32`` to handle fork safety on
infiniband clusters
- Remove ``instant`` dependency
2016.1.0 (2016-06-23)
---------------------
- Initial implementation
fenics-project-dijitso-c92dcb05ca82/MANIFEST.in 0000664 0000000 0000000 00000000213 13456064662 0021071 0 ustar 00root root 0000000 0000000 include COPYING
include COPYING.LESSER
include ChangeLog
recursive-include doc *
recursive-include test *
global-exclude __pycache__ *.pyc
fenics-project-dijitso-c92dcb05ca82/README.rst 0000664 0000000 0000000 00000007103 13456064662 0021027 0 ustar 00root root 0000000 0000000 dijitso
=======
*A Python module for distributed just-in-time shared library building*
Authors:
- Martin Sandve Alnæs (martinal@simula.no)
- Garth N. Wells (gnw20@cam.ac.uk)
- Johannes Ring (johannr@simula.no)
Contributors:
- Jan Blechta (blechta@karlin.mff.cuni.cz)
Documentation
-------------
Documentation can be viewed at http://fenics-dijitso.readthedocs.org/.
.. image:: https://readthedocs.org/projects/fenics-dijitso/badge/?version=latest
:target: http://fenics.readthedocs.io/projects/dijitso/en/latest/?badge=latest
:alt: Documentation Status
Automated Testing
-----------------
We use Bitbucket Pipelines and Atlassian Bamboo to perform automated
testing.
.. image:: https://bitbucket-badges.useast.atlassian.io/badge/fenics-project/dijitso.svg
:target: https://bitbucket.org/fenics-project/dijitso/addon/pipelines/home
:alt: Pipelines Build Status
.. image:: http://fenics-bamboo.simula.no:8085/plugins/servlet/wittified/build-status/DIJ-DIDO
:target: http://fenics-bamboo.simula.no:8085/browse/DIJ-DIDO/latest
:alt: Bamboo Build Status
Code Coverage
-------------
Code coverage reports can be viewed at
https://coveralls.io/bitbucket/fenics-project/dijitso.
.. image:: https://coveralls.io/repos/bitbucket/fenics-project/dijitso/badge.svg?branch=master
:target: https://coveralls.io/bitbucket/fenics-project/dijitso?branch=master
:alt: Coverage Status
Motivation
----------
This module was written to improve a core component of the FEniCS
framework, namely the just in time compilation of C++ code that is
generated from Python modules, but is only called from within a C++
library, and thus do not need wrapping in a nice Python interface.
The main approach of dijitso is to use ctypes to import the dynamic
shared library directly with no attempt at wrapping it in a Python
interface.
As long as the compiled code can provide a simple factory function to
a class implementing a predefined C++ interface, there is no limit to
the complexity of that interface as long as it is only called from C++
code, If you want a Python interface to your generated code, dijitso
is probably not the answer.
Although dijitso serves a very specific role within the FEniCS
project, it does not depend on other FEniCS components.
The parallel support depends on the mpi4py interface, although mpi4py
is not actually imported within the dijitso module so it would be
possible to mock the communicator object with a similar interface.
Feature list
------------
- Disk cache system based on user provided signature string (user is
responsible of the quality of the signature)
- Lazy evaluation of possibly costly code generation through
user-provided callback, called only if signature is not found in
disk cache
- Low overhead invocation of C++ compiler to produce a shared library
with no Python wrapping
- Portable shared library import using ctypes
- Automatic compression of source code in the cache directory saves
space
- Autodetect which MPI processes share the same physical cache
directory (doesn't matter if this is all cores on a node or shared
across nodes with network mapped storage)
- Automatic avoidance of race conditions in disk cache by only
compiling on one process per physical cache directory
- Optional MPI based distribution of shared library binary file
- Configurable parallel behaviour:
- "root": build only on single root node and distribute binary to
each physical cache directory with MPI
- "node": build on one process per physical cache directory
- "process": build on each process, automatic separation of cache
directories
fenics-project-dijitso-c92dcb05ca82/dijitso/ 0000775 0000000 0000000 00000000000 13456064662 0021004 5 ustar 00root root 0000000 0000000 fenics-project-dijitso-c92dcb05ca82/dijitso/__init__.py 0000664 0000000 0000000 00000002450 13456064662 0023116 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
from pkg_resources import get_distribution
"""This is dijitso -- a lightweight distributed just-in-time shared
library builder."""
__author__ = "Martin Sandve Alnæs"
__version__ = get_distribution('fenics-dijitso').version
__all__ = ["validate_params", "jit", "extract_factory_function",
"set_log_level"]
from dijitso.params import validate_params
from dijitso.jit import jit, DijitsoError
from dijitso.jit import extract_factory_function
from dijitso.log import set_log_level
# Import main function, entry point to script
from dijitso.__main__ import main
fenics-project-dijitso-c92dcb05ca82/dijitso/__main__.py 0000664 0000000 0000000 00000007313 13456064662 0023102 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""This is the commandline interface to dijitso. For usage help, run 'dijitso --help'."""
import sys
import argparse
from dijitso.params import validate_params
import dijitso.cmdline as cmd_namespace
def build_commands(cmd_namespace):
"""Collects functions called cmd_ from given namespace.
Returns dict {basename: function}.
"""
commands = {}
cmd_args = {}
for name in list(cmd_namespace.keys()):
if name.startswith("cmd_"):
cmd_name = name.replace("cmd_", "")
cmd = cmd_namespace[name]
commands[cmd_name] = cmd
args_name = "args_" + cmd_name
if args_name in cmd_namespace:
cmd_args[cmd_name] = cmd_namespace.get(args_name)
return commands, cmd_args
def add_top_arguments(parser):
"Add arguments to top level parser."
parser.add_argument("--verbose", "-v", default=False,
help="set logging level")
parser.add_argument("--cache-dir", "-r", default=None,
help="use non-default cache root path")
parser.add_argument("--dry-run", "-n", default=False,
help="only show what would be done, don't modify filesystem")
def extract_params_from_args(args):
p = {}
p["cache"] = {}
if args.cache_dir is not None:
p["cache"]["cache_dir"] = args.cache_dir
return p
def add_common_arguments(parser):
"Add arguments to each subparser."
pass
def add_cmd_arguments(cmd, parser, args):
"Add arguments specific to a command."
if hasattr(cmd, "add_arguments"):
cmd.add_arguments(parser)
def build_parsers(commands, args):
"""Builds a top parser with subparsers for each command."""
top_parser = argparse.ArgumentParser()
add_top_arguments(top_parser)
subparsers = top_parser.add_subparsers(help="command description", dest="cmd_name")
cmd_parsers = {}
for cmd_name, cmd in commands.items():
parser = subparsers.add_parser(cmd_name, help=cmd.__doc__)
add_common_arguments(parser)
if cmd_name in args:
args[cmd_name](parser)
cmd_parsers[cmd_name] = parser
return top_parser, subparsers, cmd_parsers
def main(args=None):
"""This is the commandline tool for the python module dijitso."""
if args is None:
args = sys.argv[1:]
# Build subparsers for each command
commands, cmd_args = build_commands(vars(cmd_namespace))
top_parser, subparsers, cmd_parsers = build_parsers(commands, cmd_args)
# Populate args namespace
args_ns = argparse.Namespace()
top_parser.parse_args(args, namespace=args_ns)
# Extract generic params
params = extract_params_from_args(args_ns)
params = validate_params(params)
# Run the chosen command (argparse doesn't allow
# getting to this point with an invalid cmd_name)
assert args_ns.cmd_name in commands
cmd = commands[args_ns.cmd_name]
return cmd(args_ns, params)
if __name__ == "__main__":
sys.exit(main())
fenics-project-dijitso-c92dcb05ca82/dijitso/build.py 0000664 0000000 0000000 00000022634 13456064662 0022464 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""Utilities for building libraries with dijitso."""
import tempfile
import os
import sys
from dijitso.system import get_status_output, lockfree_move_file
from dijitso.system import make_dirs, make_executable, store_textfile
from dijitso.log import warning, info, debug
from dijitso.cache import ensure_dirs, make_lib_dir, make_inc_dir
from dijitso.cache import create_fail_dir_path
from dijitso.cache import create_lib_filename, create_lib_basename, create_libname
from dijitso.cache import create_src_filename, create_src_basename
from dijitso.cache import create_inc_filename, create_inc_basename
from dijitso.cache import create_log_filename
from dijitso.cache import compress_source_code
def make_unique(dirs):
"""Take a sequence of hashable items and return a tuple including each
only once.
Preserves original ordering.
"""
udirs = []
found = set()
for d in dirs:
if d not in found:
udirs.append(d)
found.add(d)
return tuple(udirs)
def make_compile_command(src_filename, lib_filename, dependencies,
build_params, cache_params):
"""Piece together the compile command from build params.
Returns the command as a list with the command and its arguments.
"""
# Get dijitso dirs based on cache_params
inc_dir = make_inc_dir(cache_params)
lib_dir = make_lib_dir(cache_params)
# Add dijitso directories to includes, libs, and rpaths
include_dirs = make_unique(build_params["include_dirs"] + (inc_dir,))
lib_dirs = make_unique(build_params["lib_dirs"] + (lib_dir,))
rpath_dirs = make_unique(build_params["rpath_dirs"] + (lib_dir,))
# Make all paths absolute
include_dirs = [os.path.abspath(d) for d in include_dirs]
lib_dirs = [os.path.abspath(d) for d in lib_dirs]
rpath_dirs = [os.path.abspath(d) for d in rpath_dirs]
# Build options (defaults assume gcc compatibility)
cxxflags = list(build_params["cxxflags"])
if build_params["debug"]:
cxxflags.extend(build_params["cxxflags_debug"])
else:
cxxflags.extend(build_params["cxxflags_opt"])
# Create library names for all dependencies and additional given
# libs
deplibs = [create_libname(depsig, cache_params)
for depsig in dependencies]
deplibs.extend(build_params["libs"])
# Get compiler name
args = [build_params["cxx"]]
# Compiler args
args.extend(cxxflags)
args.extend("-I" + path for path in include_dirs)
# The input source
args.append(src_filename)
# Linker args
args.extend("-L" + path for path in lib_dirs)
args.extend("-Wl,-rpath," + path for path in rpath_dirs)
args.extend("-l" + lib for lib in deplibs)
# OSX specific:
if sys.platform == "darwin":
full_lib_filename = os.path.join(cache_params["cache_dir"],
cache_params["lib_dir"],
os.path.basename(lib_filename))
args.append("-Wl,-install_name,%s" % full_lib_filename)
# The output library
args.append("-o" + lib_filename)
return args
def temp_dir(cache_params):
"""Return a uniquely named temp directory.
Optionally residing under temp_dir_root from cache_params.
"""
return tempfile.mkdtemp(dir=cache_params["temp_dir_root"])
def build_shared_library(signature, header, source, dependencies, params):
"""Build shared library from a source file and store library in
cache.
"""
cache_params = params["cache"]
build_params = params["build"]
# Create basenames
inc_basename = create_inc_basename(signature, cache_params)
src_basename = create_src_basename(signature, cache_params)
lib_basename = create_lib_basename(signature, cache_params)
# Create a temp directory and filenames within it
tmpdir = temp_dir(cache_params)
temp_inc_filename = os.path.join(tmpdir, inc_basename)
temp_src_filename = os.path.join(tmpdir, src_basename)
temp_lib_filename = os.path.join(tmpdir, lib_basename)
# Store source and header in temp dir
if header:
store_textfile(temp_inc_filename, header)
store_textfile(temp_src_filename, source)
# Build final command as list of arguments
cmd = make_compile_command(temp_src_filename, temp_lib_filename,
dependencies, build_params, cache_params)
# Execute command to compile generated source code to dynamic
# library
status, output = get_status_output(cmd)
# Move files to cache on success or a local dir on failure,
# using safe lockfree move
if status == 0:
# Ensure dirnames exist in cache dirs
ensure_dirs(cache_params)
# Move library first
lib_filename = create_lib_filename(signature, cache_params)
assert os.path.exists(os.path.dirname(lib_filename))
lockfree_move_file(temp_lib_filename, lib_filename)
# Write header only if there is one
if header:
inc_filename = create_inc_filename(signature, cache_params)
assert os.path.exists(os.path.dirname(inc_filename))
lockfree_move_file(temp_inc_filename, inc_filename)
else:
inc_filename = None
# Compress or delete source code based on params
temp_src_filename = compress_source_code(temp_src_filename, cache_params)
if temp_src_filename:
src_filename = create_src_filename(signature, cache_params)
if temp_src_filename.endswith(".gz"):
src_filename = src_filename + ".gz"
assert os.path.exists(os.path.dirname(src_filename))
lockfree_move_file(temp_src_filename, src_filename)
else:
src_filename = None
# Write compiler command and output to log file
if cache_params["enable_build_log"]:
# Recreate compiler command without the tempdir
cmd = make_compile_command(src_basename, lib_basename,
dependencies, build_params, cache_params)
log_contents = "%s\n\n%s" % (" ".join(cmd), output)
log_filename = create_log_filename(signature, cache_params)
assert os.path.exists(os.path.dirname(log_filename))
store_textfile(log_filename, log_contents)
else:
log_filename = None
files = set((inc_filename, src_filename, lib_filename, log_filename))
files = files - set((None,))
files = sorted(files)
debug("Compilation succeeded. Files written to cache:\n" +
"\n".join(files))
err_info = None
else:
# Create filenames in a local directory to store files for
# reproducing failure
fail_dir = create_fail_dir_path(signature, cache_params)
make_dirs(fail_dir)
# Library name is returned below
lib_filename = None
# Write header only if there is one
if header:
inc_filename = os.path.join(fail_dir, inc_basename)
lockfree_move_file(temp_inc_filename, inc_filename)
# Always write source for inspection after compilation failure
src_filename = os.path.join(fail_dir, src_basename)
lockfree_move_file(temp_src_filename, src_filename)
# Write compile command to failure dir, adjusted to use local
# source file name so it can be rerun
cmd = make_compile_command(src_basename, lib_basename, dependencies,
build_params, cache_params)
cmds = " ".join(cmd)
script = "#!/bin/bash\n# Execute this file to recompile locally\n" + cmds
cmd_filename = os.path.join(fail_dir, "recompile.sh")
store_textfile(cmd_filename, script)
make_executable(cmd_filename)
# Write readme file with instructions
readme = "Run or source recompile.sh to compile locally and reproduce the build failure.\n"
readme_filename = os.path.join(fail_dir, "README")
store_textfile(readme_filename, readme)
# Write compiler output to failure dir (will refer to temp paths)
log_filename = os.path.join(fail_dir, "error.log")
store_textfile(log_filename, output)
info("------------------- Start compiler output ------------------------")
info(output)
info("------------------- End compiler output ------------------------")
warning("Compilation failed! Sources, command, and "
"errors have been written to: %s" % (fail_dir,))
err_info = {'src_filename': src_filename,
'cmd_filename': cmd_filename,
'readme_filename': readme_filename,
'fail_dir': fail_dir,
'log_filename': log_filename}
return status, output, lib_filename, err_info
fenics-project-dijitso-c92dcb05ca82/dijitso/cache.py 0000664 0000000 0000000 00000040577 13456064662 0022436 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""Utilities for disk cache features of dijitso."""
from glob import glob
import os
import re
import sys
import ctypes
from dijitso.system import ldd
from dijitso.system import make_dirs
from dijitso.system import try_delete_file, try_copy_file
from dijitso.system import gzip_file, gunzip_file
from dijitso.system import read_textfile, store_textfile
from dijitso.log import debug, error, warning
def extract_files(signature, cache_params, prefix="", path=os.curdir,
categories=("inc", "src", "lib", "log")):
"""Make a copy of files stored under this signature.
Target filenames are '/-.*'
"""
path = os.path.join(path, prefix + signature)
make_dirs(path)
if "inc" in categories:
inc_filename = create_inc_filename(signature, cache_params)
try_copy_file(inc_filename, path)
if "src" in categories:
src_filename = create_src_filename(signature, cache_params)
if not os.path.exists(src_filename):
src_filename = src_filename + ".gz"
if os.path.exists(src_filename):
try_copy_file(src_filename, path)
if src_filename.endswith(".gz"):
gunzip_file(os.path.join(path, os.path.basename(src_filename)))
if "lib" in categories:
lib_filename = create_lib_filename(signature, cache_params)
try_copy_file(lib_filename, path)
if "log" in categories:
log_filename = create_log_filename(signature, cache_params)
try_copy_file(log_filename, path)
return path
def extract_lib_signatures(cache_params):
"Extract signatures from library files in cache."
p = os.path.join(cache_params["cache_dir"], cache_params["lib_dir"])
filenames = glob(os.path.join(p, "*"))
r = re.compile(create_lib_filename("(.*)", cache_params))
sigs = []
for f in filenames:
m = r.match(f)
if m:
sigs.append(m.group(1))
return sigs
def clean_cache(cache_params, dryrun=True,
categories=("inc", "src", "lib", "log")):
"Delete files from cache."
gc = glob_cache(cache_params, categories=categories)
for category in gc:
for fn in gc[category]:
if dryrun:
print("rm %s" % (fn,))
else:
try_delete_file(fn)
def glob_cache(cache_params, categories=("inc", "src", "lib", "log")):
"""Return dict with contents of cache subdirectories."""
g = {}
for foo in categories:
p = os.path.join(cache_params["cache_dir"], cache_params[foo + "_dir"])
g[foo] = glob(os.path.join(p, "*"))
return g
def grep_cache(regex, cache_params,
linenumbers=False, countonly=False,
signature=None,
categories=("inc", "src", "log")):
"Search through files in cache for a pattern."
allmatches = {}
gc = glob_cache(cache_params, categories=categories)
for category in categories:
for fn in gc.get(category, ()):
# Skip non-matches if specific signature is specified
if signature is not None and signature not in fn:
continue
if countonly:
matches = 0
else:
matches = []
if category == "lib":
# If category is "lib", use ldd
# TODO: on mac need to use otool
libs = ldd(fn)
for k, libpath in sorted(libs.items()):
if not libpath:
continue
m = regex.match(libpath)
if m:
if countonly:
matches += 1
else:
line = "%s => %s" % (k, libpath)
matches.append(line)
else:
content = read_textfile(fn)
lines = content.splitlines() if content else ()
for i, line in enumerate(lines):
m = regex.match(line)
if m:
if countonly:
matches += 1
else:
line = line.rstrip("\n\r")
if linenumbers:
line = (i, line)
matches.append(line)
if matches:
allmatches[fn] = matches
return allmatches
def extract_function(lines):
"Extract function code starting at first line of lines."
n = len(lines)
# Function starts at line 0 by assumption
begin = 0
# Worst case body range
body_begin = begin
body_end = n
# Body starts at first {
for i in range(begin, n):
if "{" in lines[i]:
body_begin = i
break
# Body ends when {} are balanced back to 0
braces = 0
for i in range(body_begin, n):
if "{" in lines[i]:
braces += 1
if "}" in lines[i]:
braces -= 1
if braces == 0:
body_end = i
break
# Include the last line in range
end = body_end + 1
sublines = lines[begin:end]
return "".join(sublines)
def _create_basename(foo, signature, cache_params):
return "".join((cache_params.get(foo + "_prefix", ""),
cache_params.get(foo + "_basename", ""),
signature,
cache_params.get(foo + "_postfix", "")))
def _create_filename(foo, signature, cache_params):
basename = _create_basename(foo, signature, cache_params)
return os.path.join(cache_params["cache_dir"],
cache_params[foo + "_dir"], basename)
def create_log_filename(signature, cache_params):
"Create log filename based on signature and params."
return _create_filename("log", signature, cache_params)
def create_inc_basename(signature, cache_params):
"Create header filename based on signature and params."
return _create_basename("inc", signature, cache_params)
def create_inc_filename(signature, cache_params):
"Create header filename based on signature and params."
return _create_filename("inc", signature, cache_params)
def create_src_filename(signature, cache_params):
"Create source code filename based on signature and params."
return _create_filename("src", signature, cache_params)
def create_src_basename(signature, cache_params):
"Create source code filename based on signature and params."
return _create_basename("src", signature, cache_params)
def create_lib_basename(signature, cache_params):
"Create library filename based on signature and params."
return _create_basename("lib", signature, cache_params)
def create_lib_filename(signature, cache_params):
"Create library filename based on signature and params."
return _create_filename("lib", signature, cache_params)
def create_libname(signature, cache_params):
"""Create library name based on signature and params,
without path, prefix 'lib', or extension '.so'."""
return cache_params["lib_basename"] + signature
def create_fail_dir_path(signature, cache_params):
"Create path name to place files after a module build failure."
fail_root = cache_params["fail_dir_root"] or os.curdir
fail_dir = os.path.join(fail_root, "jitfailure-" + signature)
return os.path.abspath(fail_dir)
def make_inc_dir(cache_params):
d = os.path.join(cache_params["cache_dir"], cache_params["inc_dir"])
make_dirs(d)
return d
def make_src_dir(cache_params):
d = os.path.join(cache_params["cache_dir"], cache_params["src_dir"])
make_dirs(d)
return d
def make_lib_dir(cache_params):
d = os.path.join(cache_params["cache_dir"], cache_params["lib_dir"])
make_dirs(d)
return d
def make_log_dir(cache_params):
d = os.path.join(cache_params["cache_dir"], cache_params["log_dir"])
make_dirs(d)
return d
_ensure_dirs_called = {}
def ensure_dirs(cache_params):
global _ensure_dirs_called
# This ensures directories are created only once during a process
# for each value that cache_dir takes, in case it changes during
# the process lifetime.
c = cache_params["cache_dir"]
if c not in _ensure_dirs_called:
make_inc_dir(cache_params)
make_src_dir(cache_params)
make_lib_dir(cache_params)
make_log_dir(cache_params)
_ensure_dirs_called[c] = True
def read_library_binary(lib_filename):
"Read compiled shared library as binary blob into a numpy byte array."
import numpy
return numpy.fromfile(lib_filename, dtype=numpy.uint8)
def write_library_binary(lib_data, signature, cache_params):
"Store compiled shared library from binary blob in numpy byte array to cache."
make_lib_dir(cache_params)
lib_filename = create_lib_filename(signature, cache_params)
lib_data.tofile(lib_filename)
# TODO: Set permissions?
def analyse_load_error(e, lib_filename, cache_params):
# Try to analyse error further for better error message:
msg = str(e)
r = re.compile("(" + create_lib_basename(".*", cache_params) + ")")
m = r.match(msg)
if m:
# Found libname mentioned in message
mlibname = m.group(1)
mlibname = os.path.join(cache_params["cache_dir"],
cache_params["lib_dir"], mlibname)
else:
mlibname = lib_filename
if lib_filename != mlibname:
# Message mentions some other dijitso library,
# double check if this other file exists
# (if it does, could be paths or rpath issue)
if os.path.exists(mlibname):
emsg = ("dijitso failed to load library:\n\t%s\n"
"but dependency file exists:\n\t%s\nerror is:\n\t%s" % (
lib_filename, mlibname, str(e)))
else:
emsg = ("dijitso failed to load library:\n\t%s\n"
"dependency file missing:\n\t%s\nerror is:\n\t%s" % (
lib_filename, mlibname, str(e)))
else:
# Message doesn't mention another dijitso library,
# double check if library file we tried to load exists
# (if it does, could be paths issue)
if os.path.exists(lib_filename):
emsg = ("dijitso failed to load existing file:\n"
"\t%s\nerror is:\n\t%s" % (lib_filename, str(e)))
else:
emsg = ("dijitso failed to load missing file:\n"
"\t%s\nerror is:\n\t%s" % (lib_filename, str(e)))
return emsg
def load_library(signature, cache_params):
"""Load existing dynamic library from disk.
Returns library module if found, otherwise None.
If found, the module is placed in memory cache for later lookup_lib calls.
"""
lib_filename = create_lib_filename(signature, cache_params)
if not os.path.exists(lib_filename):
debug("File %s does not exist" % (lib_filename,))
return None
debug("Loading %s from %s" % (signature, lib_filename))
if cache_params["lib_loader"] == "ctypes":
try:
lib = ctypes.cdll.LoadLibrary(lib_filename)
except os.error as e:
lib = None
emsg = analyse_load_error(e, lib_filename, cache_params)
warning(emsg)
else:
debug("Loaded %s from %s" % (signature, lib_filename))
elif cache_params["lib_loader"] == "import":
sys.path.append(os.path.dirname(lib_filename))
# Will raise an exception if it does not load correctly
lib = __import__(signature)
debug("Loaded %s from %s" % (signature, lib_filename))
else:
error("Invalid loader: %s" % cache_params["lib_loader"])
if lib is not None:
# Disk loading succeeded, register loaded library in memory
# cache for next time
_lib_cache[signature] = lib
return lib
# A cache is always something to be careful about. This one stores
# references to loaded jit-compiled libraries, which will stay in
# memory unless manually unloaded anyway and should not cause any
# trouble.
_lib_cache = {}
def lookup_lib(lib_signature, cache_params):
"""Lookup library in memory cache then in disk cache.
Returns library module if found, otherwise None.
"""
# Look for already loaded library in memory cache
lib = _lib_cache.get(lib_signature)
if lib is None:
# Cache miss in memory, try looking on disk
lib = load_library(lib_signature, cache_params)
else:
debug("Fetched %s from memory cache" % (lib_signature,))
# Return library or None
return lib
def read_src(signature, cache_params):
"""Lookup source code in disk cache and return file contents or None."""
filename = create_src_filename(signature, cache_params)
return read_textfile(filename)
def read_inc(signature, cache_params):
"""Lookup header file in disk cache and return file contents or None."""
filename = create_inc_filename(signature, cache_params)
return read_textfile(filename)
def read_log(signature, cache_params):
"""Lookup log file in disk cache and return file contents or None."""
filename = create_log_filename(signature, cache_params)
return read_textfile(filename)
def store_src(signature, content, cache_params):
"Store source code in file within dijitso directories."
make_src_dir(cache_params)
filename = create_src_filename(signature, cache_params)
store_textfile(filename, content)
return filename
def store_inc(signature, content, cache_params):
"Store header file within dijitso directories."
make_inc_dir(cache_params)
filename = create_inc_filename(signature, cache_params)
store_textfile(filename, content)
return filename
def store_log(signature, content, cache_params):
"Store log file within dijitso directories."
make_log_dir(cache_params)
filename = create_log_filename(signature, cache_params)
store_textfile(filename, content)
return filename
def compress_source_code(src_filename, cache_params):
"""Keep, delete or compress source code based on value of cache parameter 'src_storage'.
Can be "keep", "delete", or "compress".
"""
src_storage = cache_params["src_storage"]
if src_storage == "keep":
filename = src_filename
elif src_storage == "delete":
try_delete_file(src_filename)
filename = None
elif src_storage == "compress":
filename = gzip_file(src_filename)
try_delete_file(src_filename)
else:
error("Invalid src_storage parameter. Expecting 'keep', 'delete', or 'compress'.")
return filename
def get_dijitso_dependencies(libname, cache_params):
"Run ldd and filter output to only include dijitso cache entries."
libs = ldd(libname)
dlibs = {}
for k in libs:
if k.startswith(cache_params["lib_prefix"]):
dlibs[k] = libs[k]
return dlibs
# TODO: Use this in command-line tools?
def check_cache_integrity(cache_params):
"Check dijitso cache integrity."
libnames = set(glob(cache_params["lib_prefix"] + "*" + cache_params["lib_postfix"]))
dmissing = {}
for libname in libnames:
dlibs = get_dijitso_dependencies(libname, cache_params)
# Missing on file system:
missing = [k for k in dlibs if k not in libnames]
for k in dlibs:
if k not in missing:
# ldd thinks file is missing but it's there, linker issue?
pass
if missing:
dmissing[libname] = sorted(missing)
return dmissing
def report_cache_integrity(dmissing, out=warning):
"Print cache integrity report."
if dmissing:
out("%d libraries are missing one or more dependencies:" % len(dmissing))
for k in sorted(dmissing):
out("\t%s depends on missing libraries:" % k)
for m in dmissing[k]:
out("\t\t%s" % m)
fenics-project-dijitso-c92dcb05ca82/dijitso/cmdline.py 0000664 0000000 0000000 00000021377 13456064662 0023003 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""This file contains the commands available through command-line dijitso-cache.
Each function cmd_ becomes a subcommand invoked by::
dijitso-cache cmdname ...args
The docstrings in the cmd_ are shown when running::
dijitso-cache cmdname --help
The 'args' argument to cmd_* is a Namespace object with the commandline arguments.
"""
import os
import re
from dijitso import __version__
from dijitso.cache import glob_cache, grep_cache, clean_cache
from dijitso.cache import extract_lib_signatures
from dijitso.cache import extract_files, extract_function
from dijitso.system import read_textfile
def parse_categories(categories):
if categories == "all":
return ("inc", "src", "lib", "log")
return categories.split(",")
def args_version(parser):
pass
def cmd_version(args, params):
"print dijitso version"
print(__version__)
def args_config(parser):
parser.add_argument("--key", default="", help="specific key to show (e.g. build.cxxflags)")
def cmd_config(args, params):
"show configuration"
# Show single value if asked for
key = args.key
if key:
name = key
value = params
for k in key.split("."):
value = value[k]
# Compiler flags etc are more useful in space separated form:
if isinstance(value, tuple):
value = " ".join(value)
print(" %s: %s" % (name, value))
return 0
# Pick non-empty categories
categories = sorted(c for c in params if params[c])
print("Showing default flags for dijitso:")
for category in categories:
print("%s:" % (category,))
for name in sorted(params[category]):
value = params[category][name]
# Compiler flags etc are more useful in space separated form:
if isinstance(value, tuple):
value = " ".join(value)
print(" %s: %s" % (name, value))
return 0
def args_show(parser):
parser.add_argument("--categories", default="all",
help="comma separated list to enable file types (inc,src,lib,log)")
parser.add_argument("--no-summary", action="store_true",
help="don't show summary")
parser.add_argument("--files", action="store_true",
help="show file lists")
parser.add_argument("--signatures", action="store_true",
help="show library signatures")
def cmd_show(args, params):
"show lists of files in cache"
cache_params = params["cache"]
summary = not args.no_summary
files = args.files
signatures = args.signatures
categories = parse_categories(args.categories)
gc = glob_cache(cache_params, categories=categories)
if signatures:
sigs = extract_lib_signatures(cache_params)
print("\n".join("\t" + s for s in sorted(sigs)))
if files:
for cat in categories:
print("\n".join("\t" + f for f in sorted(gc.get(cat, ()))))
if summary:
print("dijitso cache summary (number of cached files):")
for cat in categories:
print("%s: %d" % (cat, len(gc.get(cat, ()))))
# TODO: Add summary of file sizes
return 0
def args_clean(parser):
parser.add_argument("--categories", default="inc,src,lib,log",
help="comma separated list to enable file types (inc,src,lib,log)")
def cmd_clean(args, params):
"remove files from cache"
cache_params = params["cache"]
dryrun = args.dry_run
categories = parse_categories(args.categories)
clean_cache(cache_params, dryrun=dryrun, categories=categories)
return 0
def args_grep(parser):
parser.add_argument("--categories", default="inc,src",
help="comma separated list to enable file types (inc,src,lib,log)")
parser.add_argument("--pattern", default="",
help="line search pattern")
parser.add_argument("--regexmode", action="store_true",
help="pattern is a regular expression (python style)")
parser.add_argument("--linenumbers", action="store_true",
help="show linenumbers on matches")
parser.add_argument("--countonly", action="store_true",
help="show only match line count for each file")
parser.add_argument("--filesonly", action="store_true",
help="show only filenames with matches")
parser.add_argument("--signature", default="",
help="look for module with this signature (default all)")
def cmd_grep(args, params):
"grep content of header and source file(s) in cache"
cache_params = params["cache"]
# Get command-line arguments
pattern = args.pattern
signature = args.signature
regexmode = args.regexmode
linenumbers = args.linenumbers
countonly = args.countonly
filesonly = args.filesonly
categories = parse_categories(args.categories)
if not regexmode:
pattern = ".*(" + pattern + ").*"
regex = re.compile(pattern)
allmatches = grep_cache(regex, cache_params,
linenumbers=linenumbers, countonly=countonly,
signature=signature,
categories=categories)
if filesonly:
print("\n".join(sorted(allmatches)))
elif countonly:
print("\n".join("%s: %d" % (k, v) for k, v in sorted(allmatches.items())))
else:
for fn in sorted(allmatches):
print("\nFile '%s' matches:" % (fn,))
if linenumbers:
print("\n".join("%5d:\t%s" % line for line in allmatches[fn]))
else:
print("\n".join("\t" + line for line in allmatches[fn]))
return 0
def args_grepfunction(parser):
parser.add_argument("--categories", default="src",
help="comma separated list to enable file types (inc,src,lib,log)")
parser.add_argument("--name", default="",
help="function name to search for")
parser.add_argument("--signature", default="",
help="look for module with this signature (default all)")
parser.add_argument("--no-body", action="store_true",
help="don't show function bodies")
def cmd_grepfunction(args, params):
"search for function name in source files in cache"
cache_params = params["cache"]
name = args.name
signature = args.signature
categories = parse_categories(args.categories)
no_body = args.no_body
pattern = r".*(" + name + r")[ ]*\((.*)"
regex = re.compile(pattern)
allmatches = grep_cache(regex, cache_params,
linenumbers=True, countonly=False,
signature=signature,
categories=categories)
for fn in sorted(allmatches):
if no_body:
# Just print signature lines
print("\nFile '%s' matches:" % (fn,))
for i, line in allmatches[fn]:
print("%5d: %s" % (i, line))
else:
# Print function bodies
content = read_textfile(fn)
lines = content.splitlines() if content else ()
for i, line in allmatches[fn]:
print("%s:%d" % (fn, i))
assert name in lines[i]
print(extract_function(lines[i:]))
print()
return 0
def args_checkout(parser):
parser.add_argument("--categories", default="inc,src,lib,log",
help="comma separated list to enable file types (inc,src,lib,log)")
parser.add_argument("--signature",
help="module signature (required)")
def cmd_checkout(args, params):
"copy files from cache to a directory"
cache_params = params["cache"]
signature = args.signature
categories = parse_categories(args.categories)
prefix = "jitcheckout-"
path = os.curdir
path = extract_files(signature, cache_params,
prefix=prefix, path=path,
categories=categories)
print("Extracted files to '%s'." % (path,))
return 0
fenics-project-dijitso-c92dcb05ca82/dijitso/jit.py 0000664 0000000 0000000 00000021202 13456064662 0022141 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""This module contains the main jit() function and related utilities."""
import ctypes
import numpy
from dijitso.log import error
from dijitso.params import validate_params
from dijitso.str import as_unicode
from dijitso.cache import lookup_lib, load_library
from dijitso.cache import write_library_binary, read_library_binary
from dijitso.build import build_shared_library
from dijitso.signatures import hash_params
class DijitsoError(RuntimeError):
def __init__(self, message, err_info):
super(DijitsoError, self).__init__(message)
self.err_info = err_info
def extract_factory_function(lib, name):
"""Extract function from loaded library.
Assuming signature ``(void *)()``, for anything else use look at
ctypes documentation.
Returns the factory function or raises error.
"""
function = getattr(lib, name)
function.restype = ctypes.c_void_p
return function
def jit_signature(name, params): # TODO: Unused?
"""Compute the signature that jit will use for given name and params."""
# Validation and completion with defaults for missing parameters
params = validate_params(params)
# Extend provided name of jitable with hash of relevant parameters
signature_params = {
"generator": params["generator"],
"build": params["build"]
}
signature = "%s_%s" % (name, hash_params(signature_params))
return signature
# TODO: send, receive, wait functionality is not currently in use,
# decide to use it from dolfin or clean up the code and comments here.
def jit(jitable, name, params, generate=None,
send=None, receive=None, wait=None):
"""Just-in-time compile and import of a shared library with a cache mechanism.
A signature is computed from the name, params["generator"],
and params["build"]. The name should be a unique identifier
for the jitable, preferrably produced by a good hash function.
The signature is used to identity if the library has already been
compiled and cached. A two-level memory and disk cache ensures good
performance for repeated lookups within a single program as well as
persistence across program runs.
If no library has been cached, the passed 'generate' function is
called to generate the source code:
header, source, dependencies = \
generate(jitable, name, signature, params["generator"])
It is expected to translate the 'jitable' object into
C or C++ (default) source code which will subsequently be
compiled as a shared library and stored in the disk cache.
The returned 'dependencies' should be a tuple of signatures
returned from other completed dijitso.jit calls, and are
linked to when building.
The compiled shared library is then loaded with ctypes and returned.
For use in a parallel (MPI) context, three functions send, receive,
and wait can be provided. Each process can take on a different role
depending on whether generate, or receive, or neither is provided.
* Every process that gets a generate function is called a 'builder',
and will generate and compile code as described above on a cache miss.
If the function send is provided, it will then send the shared library
binary file as a binary blob by calling send(numpy_array).
* Every process that gets a receive function is called a 'receiver',
and will call 'numpy_array = receive()' expecting the binary blob
with a compiled binary shared library which will subsequently be
written to file in the local disk cache.
* The rest of the processes are called 'waiters' and will do nothing.
* If provided, all processes will call wait() before attempting to
load the freshly compiled library from disk cache.
The intention of the above pattern is to be flexible, allowing several
different strategies for sharing build results. The user of dijitso
can determine groups of processes that share a disk cache, and assign
one process per physical disk cache directory to write to that directory,
avoiding multiple processes writing to the same files.
This forms the basis for three main strategies:
* Build on every process.
* Build on one process per physical cache directory.
* Build on a single global root node and send a copy of
the binary to one process per physical cache directory.
It is highly recommended to avoid have multiple builder processes
sharing a physical cache directory.
"""
# TODO: Could simplify interface here and roll
# (jitable, name, params["generator"]) into a single jitobject?
# TODO: send/receive doesn't combine well with generate
# triggering additional jit calls for dependencies.
# It's possible that dependencies are hard to determine without
# generate doing some analysis that we want to avoid.
# Drop send/receive? Probably not that useful anyway.
# Complete params with hardcoded defaults and config file defaults
params = validate_params(params)
# 0) Look for library in memory or disk cache
# FIXME: use only name as signature for now
# TODO: just remove one of signature or name from API?
# signature = jit_signature(name, params)
name = as_unicode(name)
signature = name
cache_params = params["cache"]
lib = lookup_lib(signature, cache_params)
err_info = None
if lib is None:
# Since we didn't find the library in cache, we must build it.
if receive and generate:
# We're not supposed to generate if we're receiving
error("Please provide only one of generate or receive.")
elif generate:
# 1) Generate source code
header, source, dependencies = generate(jitable, name, signature, params["generator"])
# Ensure we got unicode from generate
header = as_unicode(header)
source = as_unicode(source)
dependencies = [as_unicode(dep) for dep in dependencies]
# 2) Compile shared library and 3) store in dijitso
# inc/src/lib dir on success
# NB! It's important to not raise exception on compilation
# failure, such that we can reach wait() together with
# other processes if any.
status, output, lib_filename, err_info = \
build_shared_library(signature, header, source, dependencies,
params)
# 4a) Send library over network if we have a send function
if send:
if status == 0:
lib_data = read_library_binary(lib_filename)
else:
lib_data = numpy.zeros((1,))
send(lib_data)
elif receive:
# 4b) Get library as binary blob from given receive
# function and store in cache
lib_data = receive()
# Empty if compilation failed
status = -1 if lib_data.shape == (1,) else 0
if status == 0:
write_library_binary(lib_data, signature, cache_params)
else:
# Do nothing (we'll be waiting below for other process to
# build)
if not wait:
error("Please provide wait if not providing one of generate or receive.")
# 5) Notify waiters that we're done / wait for builder to
# notify us
if wait:
wait()
# Finally load library from disk cache (places in memory
# cache)
# NB! This returns None if the file does not exist,
# i.e. if compilation failed on builder process
lib = load_library(signature, cache_params)
if err_info:
# TODO: Parse output to find error(s) for better error messages
raise DijitsoError("Dijitso JIT compilation failed, see '%s' for details"
% err_info['fail_dir'], err_info)
# Return built library and its signature
return lib, signature
fenics-project-dijitso-c92dcb05ca82/dijitso/log.py 0000664 0000000 0000000 00000004022 13456064662 0022135 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs, Jan Blechta
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
import logging
__all__ = ['set_log_level', 'get_logger', 'get_log_handler', 'set_log_handler']
_log = logging.getLogger("dijitso")
_loghandler = logging.StreamHandler()
_log.addHandler(_loghandler)
_log.setLevel(logging.INFO)
def get_log_handler():
return _loghandler
def get_logger():
return _log
def set_log_handler(handler):
global _loghandler
_log.removeHandler(_loghandler)
_loghandler = handler
_log.addHandler(_loghandler)
def set_log_level(level):
"""Set verbosity of logging. Argument is int or one of "INFO", "WARNING",
"ERROR", or "DEBUG".
"""
if isinstance(level, str):
level = level.upper()
assert level in ("INFO", "WARNING", "ERROR", "DEBUG")
level = getattr(logging, level)
else:
assert isinstance(level, int)
_log.setLevel(level)
# Logging interface for dijitso library
def debug(*message):
_log.debug(*message)
def info(*message):
_log.info(*message)
def warning(*message):
_log.warning(*message)
def error(*message):
_log.error(*message)
text = message[0] % message[1:]
raise RuntimeError(text)
def dijitso_assert(condition, *message):
if not condition:
_log.error(*message)
text = message[0] % message[1:]
raise AssertionError(text)
fenics-project-dijitso-c92dcb05ca82/dijitso/mpi.py 0000664 0000000 0000000 00000022427 13456064662 0022152 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""Utilities for mpi features of dijitso."""
import io
import os
import uuid
from glob import glob
import numpy
from dijitso.log import info, error
from dijitso.system import try_delete_file
def bcast_uuid(comm):
"Create a unique id shared across all processes in comm."
guid = numpy.ndarray((1,), dtype=numpy.uint64)
if comm.rank == 0:
# uuid creates a unique 128 bit id, we just pick the low 64 bits
guid[0] = numpy.uint64(uuid.uuid4().int & ((1 << 64) - 1))
comm.Bcast(guid, root=0)
return int(guid[0])
def discover_path_access_ranks(comm, path):
"""Discover which ranks share access to the same directory.
This cannot be done by comparing paths, because
a path string can represent a local work directory
or a network mapped directory, depending on cluster
configuration.
Current approach is that each process touches a
filename with its own rank in their given path.
By reading in the filelist from the same path,
we'll find which ranks have access to the same
directory.
To avoid problems with leftover files from previous
program crashes, or collisions between simultaneously
running programs, we use a random uuid in the filenames
written.
"""
# Create a unique basename for rank files of this program
guid = bcast_uuid(comm) # TODO: Run this in an init function and store for program duration?
basename = os.path.join(path, "rank.%d." % guid)
# Write the rank of this process to a filename
filename = basename + str(comm.rank)
with io.open(filename, "wb"):
pass
# Wait for all writes to take place. Don't know how robust this is
# with nfs!!!
comm.Barrier()
# Read filelist
noderanks = sorted([int(fn.replace(basename, "")) for fn in glob(basename + "*")])
# Wait for everyone to finish reading filelist
comm.Barrier()
# Clean up our own rank file. If the process is aborted,
# this may fail to happen and leave a dangling file!
# However the file takes no space, and the guid ensures
# it won't be colliding with other filenames.
# TODO: Include a gc command in dijitso to clean up this and other stuff.
try_delete_file(filename)
return noderanks
def gather_global_partitions(comm, partition):
"""Gather an ordered list of unique partition values within comm."""
global_partitions = numpy.ndarray((comm.size,), dtype=numpy.uint64)
local_partition = numpy.ndarray((1,), dtype=numpy.uint64)
local_partition[0] = partition
comm.Allgather(local_partition, global_partitions)
return sorted(set(global_partitions))
def create_subcomm(comm, ranks):
"Create a communicator for a set of ranks."
group = comm.Get_group()
subgroup = group.Incl(ranks)
subcomm = comm.Create(subgroup)
subgroup.Free()
group.Free()
return subcomm
def create_node_comm(comm, comm_dir):
"""Create comms for communicating within a node."""
# Find ranks that share this physical comm_dir (physical dir, not same path string)
node_ranks = discover_path_access_ranks(comm, comm_dir)
# Partition comm into one communicator for each physical comm_dir
assert len(node_ranks) >= 1
node_root = min(node_ranks)
node_comm = comm.Split(node_root, node_ranks.index(comm.rank))
return node_comm, node_root
def create_node_roots_comm(comm, node_root):
"""Build comm for communicating among the node roots."""
unique_global_node_roots = gather_global_partitions(comm, node_root)
roots_comm = create_subcomm(comm, unique_global_node_roots)
return roots_comm
def create_comms_and_role_root(comm, node_comm, node_root):
"""Approach: global root builds and sends binary to node roots,
everyone waits on their node group."""
copy_comm = create_node_roots_comm(comm, node_root)
wait_comm = node_comm
if comm.rank == 0:
role = "builder"
elif node_comm.rank == 0:
assert comm.rank == node_root
role = "receiver"
else:
assert comm.rank != node_root
role = "waiter"
return copy_comm, wait_comm, role
def create_comms_and_role_node(comm, node_comm, node_root):
"""Approach: each node root builds, everyone waits on their node group."""
copy_comm = None
wait_comm = node_comm
if node_comm.rank == 0:
assert comm.rank == node_root
role = "builder"
else:
assert comm.rank != node_root
role = "waiter"
return copy_comm, wait_comm, role
def create_comms_and_role_process(comm, node_comm, node_root):
"""Approach: each process builds its own module, no communication.
To ensure no race conditions in this case independently of cache dir setup,
we include an error check on the size of the autodetected node_comm.
This should always be 1, or we provide the user with an informative message.
TODO: Append program uid and process rank to basedir instead?
"""
if node_comm.size > 1:
error("Asking for per-process building but processes share cache dir."
" Please configure dijitso dirs to be distinct per process.")
copy_comm = None
wait_comm = None
assert node_comm.rank == 0
assert comm.rank == node_root
role = "builder"
return copy_comm, wait_comm, role
def create_comms_and_role(comm, comm_dir, buildon):
"""Determine which role each process should take, and create
the right copy_comm and wait_comm for the build strategy.
buildon must be one of "root", "node", or "process".
Returns (copy_comm, wait_comm, role).
"""
# Now assign values to the copy_comm, wait_comm, and role,
# depending on buildon strategy chosen. If we have no comm,
# always return the builder role
if comm is None:
copy_comm, wait_comm, role = None, None, "builder"
else:
node_comm, node_root = create_node_comm(comm, comm_dir)
if buildon == "root":
copy_comm, wait_comm, role = create_comms_and_role_root(comm,
node_comm,
node_root)
elif buildon == "node":
copy_comm, wait_comm, role = create_comms_and_role_node(comm,
node_comm,
node_root)
elif buildon == "process":
copy_comm, wait_comm, role = create_comms_and_role_process(comm,
node_comm,
node_root)
else:
error("Invalid parameter buildon=%s" % (buildon,))
return copy_comm, wait_comm, role
def send_binary(comm, lib_data):
"Send compiled library as binary blob over MPI."
# TODO: Test this in parallel locally.
# TODO: Test this in parallel on clusters.
# http://mpi4py.scipy.org/docs/usrman/tutorial.html
# Check that we are the root
root = 0
assert comm.rank == root
# Send file size
lib_size = numpy.ndarray((1,), dtype=numpy.uint32)
lib_size[0] = lib_data.shape[0]
info("rank %d: send size with root=%d." % (comm.rank, root))
comm.Bcast(lib_size, root=root)
# Send file contents
info("rank %d: send data with root=%d." % (comm.rank, root))
comm.Bcast(lib_data, root=root)
def receive_binary(comm):
"Store shared library received as a binary blob to cache."
# Check that we are not the root
root = 0
assert comm.rank != root
# Receive file size
lib_size = numpy.ndarray((1,), dtype=numpy.uint32)
info("rank %d: receive size with root=%d." % (comm.rank, root))
comm.Bcast(lib_size, root=root)
# Receive file contents
lib_data = numpy.ndarray(lib_size[0], dtype=numpy.uint8)
info("rank %d: receive data with root=%d." % (comm.rank, root))
comm.Bcast(lib_data, root=root)
return lib_data
"""
def foo():
# TODO: Should call these once (for each comm at least) globally
# in dolfin, not on each jit call
def get_comm_dir(cache_params):
return os.path.join(cache_params["cache_dir"], cache_params["comm_dir"])
comm_dir = get_comm_dir()
copy_comm, wait_comm, role = create_comms_and_role(comm, comm_dir, buildon)
if wait_comm is not None:
def wait():
wait_comm.Barrier()
else:
wait = None
if copy_comm is not None and copy_comm.size > 1:
def send(lib_data):
send_binary(copy_comm, lib_data)
else:
send = None
def receive():
return receive_binary(copy_comm)
"""
fenics-project-dijitso-c92dcb05ca82/dijitso/params.py 0000664 0000000 0000000 00000020733 13456064662 0022646 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""Utilities for dijitso parameters."""
from glob import glob
import os
import sys
import copy
import numbers
import configparser
from dijitso.log import info, error, warning
from dijitso.str import as_unicode
# Warning for fenics backwards compatibility:
if (os.environ.get("INSTANT_CACHE_DIR") and
not os.environ.get("DIJITSO_CACHE_DIR")):
warning("INSTANT_CACHE_DIR is no longer used by dijitso."
" To set the cache directory for dijitso,"
" set DIJITSO_CACHE_DIR.")
def discover_config_filename():
basename = ".dijitso.conf"
search_paths = [
os.curdir,
os.environ.get("DIJITSO_CONF"),
os.path.expanduser("~"),
"/etc/dijitso",
]
for path in search_paths:
if path is None:
continue
names = glob(os.path.join(path, basename))
if names:
assert len(names) == 1
return names[0]
return None
_config_file_contents = None
def read_config_file():
"Read config file and cache the contents for the duration of the process."
global _config_file_contents
if _config_file_contents is None:
filename = discover_config_filename()
_config_file_contents = {}
if filename is not None:
info("Using config file '%s'." % (filename,))
parser = configparser.SafeConfigParser()
parser.read(filename)
for category in parser.sections():
category = as_unicode(category)
_config_file_contents[category] = {}
for name, value in parser.items(category):
name = as_unicode(name)
value = as_unicode(value)
_config_file_contents[category][name] = value
return _config_file_contents
def default_cache_params():
if sys.platform in ("win32", "cygwin"):
default_lib_postfix = ".dll"
else:
default_lib_postfix = ".so"
p = dict(
cache_dir=None, # See validate_params
inc_dir="include",
src_dir="src",
lib_dir="lib",
fail_dir_root=None,
temp_dir_root=None,
comm_dir="comm",
log_dir="log",
enable_build_log=True,
src_storage="compress",
src_postfix=".cpp",
log_postfix=".txt",
inc_postfix=".h",
lib_postfix=default_lib_postfix,
lib_prefix="lib",
lib_basename="dijitso-",
lib_loader="ctypes"
)
return p
def default_cxx_compiler():
"Default C++ compiler"
return os.getenv("CXX", "c++")
def default_cxx_flags():
"Default C++ flags for all build modes."
# Dropped because of some symbol sharing across dependent modules from ffc:
# "-fvisibility=hidden",
return ("-Wall", "-shared", "-fPIC", "-std=c++11")
def default_cxx_debug_flags():
"Default C++ flags for debug=True. Note: FFC always overrides these."
return ("-g", "-O0")
def default_cxx_release_flags():
"Default C++ flags for debug=False. Note: FFC always overrides these."
# These flags deal with handling of nan, inf, underflow, division
# by zero, etc. which should be ok for most of our purposes. It
# might be better to place them in ffc or make them dependent on
# compiler or optional or whatever, just throwing them in here now
# to see how it works out.
safe_fastmath_parts = ("-fno-math-errno", "-fno-trapping-math",
"-ffinite-math-only")
return ("-O3",) + safe_fastmath_parts
def default_build_params():
p = dict(
cxx=default_cxx_compiler(),
cxxflags=default_cxx_flags(),
cxxflags_debug=default_cxx_debug_flags(),
cxxflags_opt=default_cxx_release_flags(),
include_dirs=(),
lib_dirs=(),
rpath_dirs=(),
libs=(),
debug=False,
)
return p
def default_generator_params():
return {}
def default_params():
p = dict(
cache=default_cache_params(),
build=default_build_params(),
generator=default_generator_params(),)
return p
_session_defaults = None
def session_default_params():
global _session_defaults
if _session_defaults is None:
_session_defaults = validate_params()
return copy.deepcopy(_session_defaults)
def as_bool(value):
if isinstance(value, bool):
return value
elif value in ("True", "true", "1"):
return True
elif value in ("False", "false", "0"):
return False
else:
error("Invalid boolean value %s" % (value,))
def as_str_tuple(p):
"""Convert p to a tuple of strings, allowing a list or tuple of
strings or a single string as input."""
if isinstance(p, str):
return (as_unicode(p),)
elif isinstance(p, (tuple, list)):
if all(isinstance(item, str) for item in p):
return tuple(as_unicode(item) for item in p)
raise RuntimeError("Expecting a string or list of strings, not %s." % (p,))
def copy_params(params):
"Copy two-level dict of params."
return {k: v.copy() for k, v in params.items()}
def check_params_keys(default, params):
"Check that keys in params exist in defaults."
for category in params:
if category == "generator":
continue
if category not in default:
error("Invalid parameter category '%s'." % category)
if params[category] is not None:
invalid = set(params[category]) - set(default[category])
if invalid:
error("Invalid parameter names %s in category '%s'." % (sorted(invalid), category))
def merge_params(default, params):
"Merge two-level param dicts."
p = {}
for category in default:
d = default[category].copy()
p[category] = d
v = params.get(category)
if v is not None:
p[category].update(v)
return p
def validate_params(params):
"""Validate parameters to dijitso and fill in with defaults where missing."""
# Start with defaults
p0 = default_params()
p = p0
# Override with config file if any
c = read_config_file()
if c:
check_params_keys(p, c)
p = merge_params(p, c)
# Override with runtime params if any
if params:
check_params_keys(p, params)
p = merge_params(p, params)
# Convert parameter types
for category in p:
category = as_unicode(category)
if category == "generator":
continue
for name, value in p[category].items():
name = as_unicode(name)
v0 = p0[category][name]
if isinstance(v0, str):
value = as_unicode(value)
# Expand paths including "~" to include
# full user home directory path
if name.endswith("_dir") and "~" in value:
value = os.path.expanduser(value)
elif isinstance(v0, bool):
value = as_bool(value)
elif isinstance(v0, numbers.Number):
value = type(v0)(value)
elif isinstance(v0, tuple):
value = as_str_tuple(value)
p[category][name] = value
# Allow environment variables to override default cache dir
# Let dijitso specific dir win the contest
cache_dir = os.environ.get("DIJITSO_CACHE_DIR")
if not cache_dir:
# Place default cache dir in virtualenv or conda prefix
# if one of them are active, or under user's home directory
home = os.path.expanduser("~")
venv = os.environ.get("VIRTUAL_ENV")
cenv = os.environ.get("CONDA_PREFIX")
if venv == sys.prefix:
env = venv
elif cenv == sys.prefix:
env = cenv
else:
env = home
cache_dir = os.path.join(env, ".cache", "dijitso")
p["cache"]["cache_dir"] = as_unicode(cache_dir)
return p
fenics-project-dijitso-c92dcb05ca82/dijitso/signatures.py 0000664 0000000 0000000 00000003265 13456064662 0023550 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
import hashlib
# Arbitrarily chosen hash digest cutoff to keep filename lengths
# reasonably small. If this is too short hashes will collide!
HASHLENGTH = 12
def hashit(data):
"Return hash of anything with a repr implementation."
h = hashlib.sha1()
h.update(repr(data).encode('utf-8'))
return h.hexdigest()[:HASHLENGTH]
def canonicalize_params_for_hashing(params):
if params:
data = ()
else:
assert isinstance(params, dict)
keys = sorted(params)
assert all(isinstance(key, str) for key in keys)
items = []
for k in keys:
k = k.encode('utf-8')
v = params[k]
if isinstance(v, dict):
items.append((k, canonicalize_params_for_hashing(v)))
else:
items.append((k, repr(v).encode('utf-8')))
data = tuple(items)
return data
def hash_params(params):
return hashit(canonicalize_params_for_hashing(params))
fenics-project-dijitso-c92dcb05ca82/dijitso/str.py 0000664 0000000 0000000 00000001700 13456064662 0022164 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2016-2016 Martin Sandve Alnæs
#
# This file is part of UFL.
#
# UFL is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# UFL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with UFL. If not, see .
"""String compatibility utilities."""
def as_unicode(s):
"Return s if unicode string, or decode bytes to unicode string using utf-8."
if isinstance(s, bytes):
return s.decode("utf-8")
else:
return s
fenics-project-dijitso-c92dcb05ca82/dijitso/system.py 0000664 0000000 0000000 00000025021 13456064662 0022702 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 Martin Sandve Alnæs
#
# This file is part of DIJITSO.
#
# DIJITSO is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DIJITSO is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DIJITSO. If not, see .
"""Utilities for interfacing with the system."""
import os
import errno
import io
import gzip
import shutil
import stat
import uuid
import re
from glob import glob
import tempfile
import subprocess
from dijitso.log import warning
def _get_status_output_subprocess(cmd, input=None, cwd=None, env=None):
"""Replacement for commands.getstatusoutput which does not work on Windows (or Python 3)."""
if isinstance(cmd, str):
cmd = cmd.strip().split()
pipe = subprocess.Popen(cmd, shell=False, cwd=cwd, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(output, errout) = pipe.communicate(input=input)
assert not errout
status = pipe.returncode
if isinstance(output, bytes):
output = output.decode('utf-8')
return (status, output)
def _get_status_output_system(cmd):
"""Replacement for commands.getstatusoutput which does not work on Windows (or Python 3)."""
if not isinstance(cmd, str):
cmd = " ".join(cmd)
# Default return values
status = 1
output = "not run"
# Execute cmd with redirection to temporary file
with tempfile.NamedTemporaryFile(delete=True) as f:
cmd += ' > ' + f.name + ' 2>&1'
# NOTE: Possibly OFED-fork-safe, tests needed!
status = os.system(cmd)
output = f.read()
if isinstance(output, bytes):
output = output.decode('utf-8')
return (status, output)
# Choose method for calling external programs. Use subprocess by default.
_call_method = "SUBPROCESS"
_call_method = os.environ.get("DIJITSO_SYSTEM_CALL_METHOD", _call_method)
if _call_method == "OS_SYSTEM":
get_status_output = _get_status_output_system
else:
get_status_output = _get_status_output_subprocess
def make_executable(filename):
"Make script executable by setting user eXecutable bit."
permissions = stat.S_IMODE(os.lstat(filename).st_mode)
os.chmod(filename, permissions | stat.S_IXUSR)
def make_dirs(path):
"""Creates a directory (tree).
Ignores error if the directory already exists.
"""
try:
os.makedirs(path)
except os.error as e:
if e.errno != errno.EEXIST:
raise
def rename_file(src, dst):
"""Rename a file.
Ignores error if the destination file exists.
"""
try:
os.rename(src, dst)
except os.error as e:
# Windows may trigger on existing destination
if e.errno not in errno.EEXIST:
raise
def try_rename_file(src, dst):
"""Try to rename a file.
NB! Ignores error if the SOURCE doesn't exist or the destination already exists.
"""
try:
os.rename(src, dst)
except os.error as e:
# Windows may trigger on existing destination,
# everyone triggers on missing source
if e.errno not in (errno.ENOENT, errno.EEXIST):
raise
def try_copy_file(src, dst):
"""Try to copy a file.
NB! Ignores any error.
"""
try:
shutil.copy(src, dst)
except Exception:
pass
def try_delete_file(filename):
"""Try to remove a file.
Ignores error if filename doesn't exist.
"""
try:
os.remove(filename)
except os.error as e:
if e.errno != errno.ENOENT:
raise
def gzip_file(filename):
"""Gzip a file.
New file gets .gz extension added.
Does nothing if the .gz file already exists.
Original file is never touched.
"""
# Expecting source file to be there
if not os.path.exists(filename):
return None
# Avoid doing work if file is already there
gz_filename = filename + ".gz"
if not os.path.exists(gz_filename):
# Write gzipped contents to a temp file
tmp_filename = filename + "-tmp-" + uuid.uuid4().hex + ".gz"
with io.open(filename, "rb") as f_in, gzip.open(tmp_filename, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
# Safe move to target filename, other processes may compete here
lockfree_move_file(tmp_filename, gz_filename)
return gz_filename
def gunzip_file(gz_filename):
"""Gunzip a file."""
assert gz_filename[-3:] == ".gz"
filename = gz_filename[:-3]
# Write gzipped contents to a temp file
tmp_filename = filename + "-tmp-" + uuid.uuid4().hex
with gzip.open(gz_filename, "rb") as f_in, io.open(tmp_filename, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
# Safe move to target filename, other processes may compete here
lockfree_move_file(tmp_filename, filename)
try_delete_file(gz_filename)
return filename
def read_textfile(filename):
"""Try to read file content, if necessary unzipped
from filename.gz, return None if not found."""
if not os.path.exists(filename):
filename = filename + ".gz"
if not os.path.exists(filename):
content = None
else:
if filename.endswith(".gz"):
content = b""
with gzip.open(filename, "rb") as f:
content = f.read()
content = content.decode("utf-8")
else:
with io.open(filename, "r", encoding="utf-8") as f:
content = f.read()
return content
def store_textfile(filename, content):
"""Store content to filename without race conditions.
Works by first writing to a unique temp file and then
moving to final destination.
Handles both bytes and unicode.
"""
# Generate a unique temporary filename in same directory as the target file
ui = uuid.uuid4().hex
tmp_filename = "%s.%s" % (filename, ui)
# Write the text to a temporary file
if isinstance(content, bytes):
# content is already bytes, write raw
f = io.open(tmp_filename, "wb")
else:
f = io.open(tmp_filename, "w", encoding="utf8")
with f:
f.write(content)
# Safely move file to target filename
lockfree_move_file(tmp_filename, filename)
return filename
def move_file(srcfilename, dstfilename):
"""Move or copy a file."""
assert os.path.exists(srcfilename)
shutil.move(srcfilename, dstfilename)
assert not os.path.exists(srcfilename)
assert os.path.exists(dstfilename)
def lockfree_move_file(src, dst):
"""Lockfree and portable nfs safe file move operation.
If target filename exists with different content,
will move it to filename.old and emit a warning.
Taken from textual description at
http://stackoverflow.com/questions/11614815/a-safe-atomic-file-copy-operation
"""
return _lockfree_move_file(src, dst, False)
def _lockfree_move_file(src, dst, recurse):
if not os.path.exists(src):
if recurse:
return
else:
raise RuntimeError("Source file does not exist.")
dst_exists = os.path.exists(dst)
if dst_exists and recurse:
warning("Backup file exists, overwriting.")
elif dst_exists:
# Destination file exists
with io.open(src, "rb") as f:
s = f.read()
with io.open(dst, "rb") as f:
d = f.read()
# Uncompress gzipped files, as they contain a timestamp
# and will otherwise always differ
if (src[-3:] == '.gz'):
s = gzip.decompress(s)
d = gzip.decompress(d)
if s == d:
# Files are the same, just delete src instead of moving
try_delete_file(src)
return
# Files differ, backup old file before moving file over it
backup = dst + ".old"
warning("Moving new file over differing existing file:\n"
"src: %s\ndst: %s\nbackup: %s" % (src, dst, backup))
_lockfree_move_file(dst, backup, True)
def priv(j):
return dst + ".priv." + str(j)
def pub(j):
return dst + ".pub." + str(j)
# Create a universally unique 128 bit integer id
ui = uuid.uuid4().int
# Move or copy file onto the target filesystem
move_file(src, priv(ui))
# Atomic rename to make file visible to competing processes
rename_file(priv(ui), pub(ui))
# Find uuids of competing files
n = len(pub("*")) - 1
uuids = sorted(int(fn[n:]) for fn in glob(pub("*")))
# Try to delete all files with larger uuids
for i in uuids:
if i > ui:
try_delete_file(pub(i))
for i in uuids:
if i < ui:
# Our file is the one with a larger uuid
try_delete_file(pub(ui))
# Cooperate on handling uuid i
ui = i
if os.path.exists(dst):
# If somebody else beat us to it, delete our file
try_delete_file(pub(ui))
else:
# Otherwise do an atomic rename to make our file final
try_rename_file(pub(ui), dst)
if os.path.exists(src):
if recurse:
# Somebody already generated new dest file which we just backed up
pass
else:
raise RuntimeError("Source file should not exist at this point!")
if not os.path.exists(dst):
raise RuntimeError("Destination file should exist at this point!")
def ldd(libname):
"""Run the ldd system tool on libname.
Returns output as a dict {basename: fullpath} with all
dynamic library dependencies and their resolution path.
This is a debugging tool and may fail if ldd is not
available or behaves differently on this system.
"""
status, output = get_status_output(["ldd", libname])
libraries = {}
for line in output.splitlines():
match = re.match(r'(.*)=>([^(]*)(.*)', line)
if match:
dlib = match.group(1).strip()
dlibpath = match.group(2).strip()
address = match.group(3).strip()
if address:
# Path can be empty for system libs
assert dlibpath == "" or os.path.exists(dlibpath)
libraries[dlib] = dlibpath
else:
assert not os.path.exists(dlibpath)
libraries[dlib] = None
return libraries
fenics-project-dijitso-c92dcb05ca82/doc/ 0000775 0000000 0000000 00000000000 13456064662 0020104 5 ustar 00root root 0000000 0000000 fenics-project-dijitso-c92dcb05ca82/doc/man/ 0000775 0000000 0000000 00000000000 13456064662 0020657 5 ustar 00root root 0000000 0000000 fenics-project-dijitso-c92dcb05ca82/doc/man/man1/ 0000775 0000000 0000000 00000000000 13456064662 0021513 5 ustar 00root root 0000000 0000000 fenics-project-dijitso-c92dcb05ca82/doc/man/man1/dijitso.1.gz 0000664 0000000 0000000 00000001145 13456064662 0023662 0 ustar 00root root 0000000 0000000 W dijitso.1 SAn0ZQAԎ8!|ŀ"UriAGi
MjggfQwߒ7Q4~\J=+>2NAJY6xf'n/svwϗVuj>Ѩw>cIuǹ]g͡FYh*(mۢ!?zR]