pax_global_header 0000666 0000000 0000000 00000000064 13126740172 0014515 g ustar 00root root 0000000 0000000 52 comment=dc7f79241923e9e204adb940ffdf69c915067933 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/ 0000775 0000000 0000000 00000000000 13126740172 0025043 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/.gitignore 0000664 0000000 0000000 00000000734 13126740172 0027037 0 ustar 00root root 0000000 0000000 # Python bytecode: *.py[co] # Packaging files: *.egg* # Editor temp files: *.swp *.swo *~ # Sphinx docs: build _build # SQLite3 database files: *.db # Logs: *.log .ropeproject celerybeat-schedule .coverage *,cover coverage.xml .noseids # Gettext object file: *.mo # saml circle/attribute-maps circle/remote_metadata.xml circle/*.key circle/*.pem # collected static files: circle/static_collected circle/bower_components # jsi18n files jsi18n scripts.rc # less *.css CONTRIBUTORS.txt 0000664 0000000 0000000 00000000141 13126740172 0027456 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933 Adam Dudas Bence Danyi Daniel Bach Gergo Nagy Imre Szeberenyi Mate Ory Sandor Guba Viktor Kalman cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/COPYING 0000664 0000000 0000000 00000104513 13126740172 0026102 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 . cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/LICENSE.txt 0000664 0000000 0000000 00000000206 13126740172 0026664 0 ustar 00root root 0000000 0000000 Copyright (c) 2012--2013 Budapest University of Technology and Economics (BME-IK), and contributors. [SOME OPEN SOURCE LICENSE HERE] cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/README.rst 0000664 0000000 0000000 00000001474 13126740172 0026540 0 ustar 00root root 0000000 0000000 ============ circle-cloud ============ This is the Django based controller and web portal of the CIRCLE Cloud. License ======= Copyright 2014 Budapest University of Technology and Economics (BME IK_). CIRCLE 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. Foobar 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 Foobar. If not, see . .. _IK: http://ik.bme.hu/ cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/ 0000775 0000000 0000000 00000000000 13126740172 0026304 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/ 0000775 0000000 0000000 00000000000 13126740172 0027043 5 ustar 00root root 0000000 0000000 __init__.py 0000664 0000000 0000000 00000000000 13126740172 0031063 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl management/ 0000775 0000000 0000000 00000000000 13126740172 0031100 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl __init__.py 0000664 0000000 0000000 00000005435 13126740172 0033220 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/management """ Creates Levels for all installed apps that have levels. """ from django.db.models import signals from django.apps import apps from django.db import DEFAULT_DB_ALIAS from django.core.exceptions import ImproperlyConfigured from ..models import Level, AclBase def create_levels(app_config, verbosity=False, using=DEFAULT_DB_ALIAS, **kwargs): """Create and set the weights of the configured Levels. Based on django.contrib.auth.management.__init__.create_permissions""" # if not router.allow_migrate(using, auth_app.Permission): # return from django.contrib.contenttypes.models import ContentType app_models = [k for k in apps.get_models(app_config) if AclBase in k.__bases__] print "Creating levels for models: %s." % ", ".join( [m.__name__ for m in app_models]) # This will hold the levels we're looking for as # (content_type, (codename, name)) searched_levels = list() level_weights = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_models: # Force looking up the content types in the current database # before creating foreign keys to them. ctype1 = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype1) weight = 0 try: for codename, name in klass.ACL_LEVELS: searched_levels.append((ctype1, (codename, name))) level_weights.append((ctype1, codename, weight)) weight += 1 except AttributeError: raise ImproperlyConfigured( "Class %s doesn't have ACL_LEVELS attribute." % klass) # Find all the Levels that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_levels = set(Level.objects.using(using).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) levels = [ Level(codename=codename, name=name, content_type=ctype) for ctype, (codename, name) in searched_levels if (ctype.pk, codename) not in all_levels ] Level.objects.using(using).bulk_create(levels) if verbosity >= 2: print("Adding levels [%s]." % ", ".join(unicode(l) for l in levels)) print("Searched: [%s]." % ", ".join( unicode(l) for l in searched_levels)) print("All: [%s]." % ", ".join(unicode(l) for l in all_levels)) # set weights for ctype, codename, weight in level_weights: Level.objects.filter(codename=codename, content_type=ctype).update(weight=weight) signals.post_migrate.connect( create_levels, dispatch_uid="circle.acl.management.create_levels") commands/ 0000775 0000000 0000000 00000000000 13126740172 0032701 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/management __init__.py 0000664 0000000 0000000 00000000000 13126740172 0035000 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/management/commands update_levels.py 0000664 0000000 0000000 00000001707 13126740172 0036114 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/management/commands # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from django.core.management.base import BaseCommand from .. import create_levels class Command(BaseCommand): args = '' help = 'Regenerates Levels' def handle(self, *args, **options): create_levels(None, None, 3) migrations/ 0000775 0000000 0000000 00000000000 13126740172 0031140 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl 0001_initial.py 0000664 0000000 0000000 00000003643 13126740172 0033611 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/migrations # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='Level', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=50, verbose_name=b'name')), ('codename', models.CharField(max_length=100, verbose_name=b'codename')), ('weight', models.IntegerField(null=True, verbose_name=b'weight')), ('content_type', models.ForeignKey(to='contenttypes.ContentType')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='ObjectLevel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object_id', models.IntegerField()), ('content_type', models.ForeignKey(to='contenttypes.ContentType')), ('groups', models.ManyToManyField(to='auth.Group')), ('level', models.ForeignKey(to='acl.Level')), ('users', models.ManyToManyField(to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='objectlevel', unique_together=set([('content_type', 'object_id', 'level')]), ), migrations.AlterUniqueTogether( name='level', unique_together=set([('content_type', 'codename')]), ), ] __init__.py 0000664 0000000 0000000 00000000000 13126740172 0033237 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/migrations models.py 0000664 0000000 0000000 00000022555 13126740172 0030632 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . import logging from django.contrib.auth.models import User, Group from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation ) from django.contrib.contenttypes.models import ContentType from django.db.models import ( ManyToManyField, ForeignKey, CharField, Model, IntegerField, Q ) logger = logging.getLogger(__name__) class Level(Model): """Definition of a permission level. Instances are automatically populated based on AclBase.""" name = CharField('name', max_length=50) content_type = ForeignKey(ContentType) codename = CharField('codename', max_length=100) weight = IntegerField('weight', null=True) def __unicode__(self): return "<%s/%s>" % (unicode(self.content_type), self.name) class Meta: app_label = 'acl' unique_together = (('content_type', 'codename'), # ('content_type', 'weight'), # TODO find a way of temp. disabling this constr. ) class ObjectLevel(Model): """Permission level for a specific object.""" level = ForeignKey(Level) content_type = ForeignKey(ContentType) object_id = IntegerField() content_object = GenericForeignKey() users = ManyToManyField(User) groups = ManyToManyField(Group) def __unicode__(self): return "<%s: %s>" % (unicode(self.content_object), unicode(self.level)) class Meta: app_label = 'acl' unique_together = (('content_type', 'object_id', 'level'),) class AclBase(Model): """Define permission levels for Users/Groups per object.""" object_level_set = GenericRelation(ObjectLevel) def clone_acl(self, other): """Clone full ACL from other object.""" assert self.id != other.id or type(self) != type(other) self.object_level_set.clear() for i in other.object_level_set.all(): ol = self.object_level_set.create(level=i.level) for j in i.users.all(): ol.users.add(j) for j in i.groups.all(): ol.groups.add(j) @classmethod def get_level_object(cls, level): """Get Level object for this model by codename.""" ct = ContentType.objects.get_for_model(cls) return Level.objects.get(codename=level, content_type=ct) def set_level(self, whom, level): """Set level of object for a user or group. :param whom: user or group the level is set for :type whom: User or Group :param level: codename of level to set, or None :type level: Level or str or unicode or NoneType """ if isinstance(whom, User): self.set_user_level(whom, level) elif isinstance(whom, Group): self.set_group_level(whom, level) else: raise AttributeError('"whom" must be a User or Group object.') def set_user_level(self, user, level): """Set level of object for a user. :param whom: user the level is set for :type whom: User :param level: codename of level to set, or None :type level: Level or str or unicode or NoneType """ logger.info('%s.set_user_level(%s, %s) called', *[unicode(p) for p in [self, user, level]]) if level is None: pk = None else: if isinstance(level, basestring): level = self.get_level_object(level) if not self.object_level_set.filter(level_id=level.pk).exists(): self.object_level_set.create(level=level) pk = level.pk for i in self.object_level_set.all(): if i.level_id != pk: i.users.remove(user) else: i.users.add(user) i.save() def set_group_level(self, group, level): """Set level of object for a user. :param whom: user the level is set for :type whom: User or unicode or str :param level: codename of level to set :type level: str or unicode """ logger.info('%s.set_group_level(%s, %s) called', *[unicode(p) for p in [self, group, level]]) if level is None: pk = None else: if isinstance(level, basestring): level = self.get_level_object(level) if not self.object_level_set.filter(level_id=level.pk).exists(): self.object_level_set.create(level=level) pk = level.pk for i in self.object_level_set.all(): if i.level_id != pk: i.groups.remove(group) else: i.groups.add(group) i.save() def has_level(self, user, level, group_also=True): logger.debug('%s.has_level(%s, %s, %s) called', *[unicode(p) for p in [self, user, level, group_also]]) if user is None or not user.is_authenticated(): return False if getattr(user, 'is_superuser', False): logger.debug('- superuser granted') return True if isinstance(level, basestring): level = self.get_level_object(level) logger.debug("- level set by str: %s", unicode(level)) object_levels = self.object_level_set.filter( level__weight__gte=level.weight).all() groups = user.groups.values_list('id', flat=True) if group_also else [] for i in object_levels: if i.users.filter(pk=user.pk).exists(): return True if group_also and i.groups.filter(pk__in=groups).exists(): return True return False def get_users_with_level(self, **kwargs): logger.debug('%s.get_users_with_level() called', unicode(self)) object_levels = (self.object_level_set.filter(**kwargs).select_related( 'level').prefetch_related('users').all()) users = [] for object_level in object_levels: name = object_level.level.codename olusers = object_level.users.all() users.extend([(u, name) for u in olusers]) logger.debug('- %s: %s' % (name, [u.username for u in olusers])) return users def get_groups_with_level(self): logger.debug('%s.get_groups_with_level() called', unicode(self)) object_levels = (self.object_level_set.select_related( 'level').prefetch_related('groups').all()) groups = [] for object_level in object_levels: name = object_level.level.codename olgroups = object_level.groups.all() groups.extend([(g, name) for g in olgroups]) logger.debug('- %s: %s' % (name, [g.name for g in olgroups])) return groups @classmethod def get_objects_with_level(cls, level, user, group_also=True, owner_also=False, disregard_superuser=False): logger.debug('%s.get_objects_with_level(%s,%s) called', unicode(cls), unicode(level), unicode(user)) if user is None or not user.is_authenticated(): return cls.objects.none() if getattr(user, 'is_superuser', False) and not disregard_superuser: logger.debug('- superuser granted') return cls.objects.all() if isinstance(level, basestring): level = cls.get_level_object(level) logger.debug("- level set by str: %s", unicode(level)) ct = ContentType.objects.get_for_model(cls) levelfilter = Q(users=user) if group_also: levelfilter |= Q(groups__in=user.groups.all()) ols = ObjectLevel.objects.filter( levelfilter, content_type=ct, level__weight__gte=level.weight).distinct() clsfilter = Q(object_level_set__in=ols.all()) if owner_also: clsfilter |= Q(owner=user) return cls.objects.filter(clsfilter).distinct() @classmethod def get_objects_with_group_level(cls, level, group): if isinstance(level, basestring): level = cls.get_level_object(level) ct = ContentType.objects.get_for_model(cls) levelfilter = Q(groups=group) ols = ObjectLevel.objects.filter( levelfilter, content_type=ct, level__weight__gte=level.weight).distinct() clsfilter = Q(object_level_set__in=ols.all()) return cls.objects.filter(clsfilter).distinct() def save(self, *args, **kwargs): super(AclBase, self).save(*args, **kwargs) if 'owner' in dict(self.ACL_LEVELS) and (hasattr(self, 'owner') and self.owner): self.set_user_level(self.owner, 'owner') class Meta: abstract = True tests/ 0000775 0000000 0000000 00000000000 13126740172 0030126 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl __init__.py 0000664 0000000 0000000 00000000000 13126740172 0032225 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/tests models.py 0000664 0000000 0000000 00000001632 13126740172 0031765 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/tests # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from django.conf import settings # https://code.djangoproject.com/ticket/7835 if settings.SETTINGS_MODULE == 'circle.settings.test': from .test_acl import TestModel, Test2Model # noqa test_acl.py 0000664 0000000 0000000 00000025431 13126740172 0032303 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl/tests # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from django.test import TestCase from django.contrib.auth.models import User, Group, AnonymousUser from django.db.models import TextField, ForeignKey from ..models import ObjectLevel, AclBase class TestModel(AclBase): normal_field = TextField() ACL_LEVELS = ( ('alfa', 'Alfa'), ('bravo', 'Bravo'), ('charlie', 'Charlie'), ) class Test2Model(AclBase): normal2_field = TextField() owner = ForeignKey(User, null=True) ACL_LEVELS = ( ('one', 'One'), ('two', 'Two'), ('three', 'Three'), ('owner', 'owner'), ) class AclUserTest(TestCase): def setUp(self): self.u1 = User.objects.create(username='user1') self.u2 = User.objects.create(username='user2', is_staff=True) self.us = User.objects.create(username='superuser', is_superuser=True) self.g1 = Group.objects.create(name='group1') self.g1.user_set.add(self.u1) self.g1.user_set.add(self.u2) self.g1.save() self.g2 = Group.objects.create(name='group2') self.g2.save() def test_level_exists(self): for codename, name in TestModel.ACL_LEVELS: level = TestModel.get_level_object(codename) self.assertEqual(level.codename, codename) for codename, name in Test2Model.ACL_LEVELS: level = Test2Model.get_level_object(codename) self.assertEqual(level.codename, codename) def test_lowest_user_level(self): i = TestModel.objects.create(normal_field='Hello') self.assertFalse(i.has_level(self.u1, 'alfa', False)) self.assertFalse(i.has_level(self.u1, 'bravo', False)) i.set_level(self.u1, 'alfa') i.set_level(self.g1, 'bravo') self.assertTrue(i.has_level(self.u1, 'alfa', False)) self.assertFalse(i.has_level(self.u1, 'bravo', False)) def test_anonymous_user_level(self): i = TestModel.objects.create(normal_field='Hello') anon = AnonymousUser() self.assertFalse(i.has_level(anon, 'alfa')) self.assertFalse(i.has_level(anon, 'bravo')) def test_middle_user_level(self): i = TestModel.objects.create(normal_field='Hello') self.assertFalse(i.has_level(self.u1, 'alfa')) self.assertFalse(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) i.set_level(self.u1, 'bravo') self.assertTrue(i.has_level(self.u1, 'alfa')) self.assertTrue(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) def test_level_set_twice_same(self): i = TestModel.objects.create(normal_field='Hello') self.assertFalse(i.has_level(self.u1, 'alfa')) self.assertFalse(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) i.set_level(self.u1, 'bravo') i.set_level(self.u1, 'bravo') self.assertTrue(i.has_level(self.u1, 'alfa')) self.assertTrue(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) def test_level_set_twice_different(self): i = TestModel.objects.create(normal_field='Hello') self.assertFalse(i.has_level(self.u1, 'alfa')) self.assertFalse(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) i.set_level(self.u1, 'charlie') i.set_level(self.u1, 'bravo') self.assertTrue(i.has_level(self.u1, 'alfa')) self.assertTrue(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) def test_superuser(self): i = TestModel.objects.create(normal_field='Hello') for u, v in [(self.u1, False), (self.u2, False), (self.us, True)]: self.assertEqual(i.has_level(u, 'alfa'), v) self.assertEqual(i.has_level(u, 'bravo'), v) self.assertEqual(i.has_level(u, 'charlie'), v) def test_check_group_membership(self): groups = self.u1.groups.values_list('id', flat=True) self.assertIn(self.g1.id, groups) self.assertTrue(self.g1.user_set.filter(id=self.u2.id).exists()) def test_lowest_group_level(self): i = TestModel.objects.create(normal_field='Hello') self.assertFalse(i.has_level(self.u1, 'alfa')) self.assertFalse(i.has_level(self.u1, 'bravo')) i.set_level(self.g1, 'alfa') self.assertTrue(i.has_level(self.u1, 'alfa')) self.assertFalse(i.has_level(self.u1, 'bravo')) def test_middle_group_level(self): i = TestModel.objects.create(normal_field='Hello') self.assertFalse(i.has_level(self.u1, 'alfa')) self.assertFalse(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) i.set_level(self.g1, 'bravo') self.assertTrue(i.has_level(self.u1, 'alfa')) self.assertTrue(i.has_level(self.u1, 'bravo')) self.assertFalse(i.has_level(self.u1, 'charlie')) def test_set_level_error_handling(self): with self.assertRaises(AttributeError): TestModel.objects.create().set_level('wrong arg', 'level') def test_get_users_with_level(self): i1 = TestModel.objects.create(normal_field='Hello') i2 = Test2Model.objects.create(normal2_field='Hello2') i1.set_level(self.u1, 'bravo') i1.set_level(self.u2, 'charlie') i2.set_level(self.u1, 'one') i2.set_level(self.us, u'three') res1 = i1.get_users_with_level() self.assertEqual([(self.u1, u'bravo'), (self.u2, u'charlie')], res1) res2 = i2.get_users_with_level() self.assertEqual([(self.u1, u'one'), (self.us, u'three')], res2) def test_get_groups_with_level(self): i1 = TestModel.objects.create(normal_field='Hello') i2 = Test2Model.objects.create(normal2_field='Hello2') i1.set_level(self.g1, 'bravo') i1.set_level(self.u2, 'charlie') i2.set_level(self.g1, 'one') i2.set_level(self.us, u'three') res1 = i1.get_groups_with_level() self.assertEqual([(self.g1, u'bravo')], res1) res2 = i2.get_groups_with_level() self.assertEqual([(self.g1, u'one')], res2) def test_object_level_unicode(self): i1 = TestModel.objects.create(normal_field='Hello') i1.set_level(self.g1, 'bravo') unicode(ObjectLevel.objects.all()[0]) def test_set_user_level_none(self): i = TestModel.objects.create(normal_field='Hello') i.set_level(self.u1, 'alfa') self.assertTrue(i.has_level(self.u1, 'alfa')) i.set_level(self.u1, None) self.assertFalse(i.has_level(self.u1, 'alfa')) def test_set_group_level_none(self): i = TestModel.objects.create(normal_field='Hello') i.set_level(self.g1, 'alfa') self.assertTrue(i.has_level(self.u1, 'alfa')) i.set_level(self.g1, None) self.assertFalse(i.has_level(self.u1, 'alfa')) def test_get_objects_with_level(self): i1 = TestModel.objects.create(normal_field='Hello1') i2 = TestModel.objects.create(normal_field='Hello2') i1.set_level(self.u1, 'alfa') i2.set_level(self.u1, 'bravo') i2.set_level(self.u2, 'bravo') self.assertItemsEqual( TestModel.get_objects_with_level('alfa', self.u1), [i1, i2]) self.assertItemsEqual( TestModel.get_objects_with_level('alfa', self.u2), [i2]) def test_get_objects_with_level_for_superuser(self): i1 = TestModel.objects.create(normal_field='Hello1') i2 = TestModel.objects.create(normal_field='Hello2') i1.set_level(self.u1, 'alfa') i2.set_level(self.us, 'alfa') self.assertItemsEqual( TestModel.get_objects_with_level('alfa', self.u1), [i1]) self.assertItemsEqual( TestModel.get_objects_with_level('alfa', self.us), [i1, i2]) self.assertItemsEqual( TestModel.get_objects_with_level('alfa', self.us, disregard_superuser=True), [i2]) def test_get_objects_with_level_for_group(self): i1 = TestModel.objects.create(normal_field='Hello1') i2 = TestModel.objects.create(normal_field='Hello2') i1.set_level(self.g1, 'alfa') i2.set_level(self.g1, 'bravo') i2.set_level(self.u1, 'bravo') self.assertItemsEqual( TestModel.get_objects_with_level('alfa', self.u1), [i1, i2]) def test_get_objects_with_group_level(self): i1 = TestModel.objects.create(normal_field='Hello1') i2 = TestModel.objects.create(normal_field='Hello2') i1.set_level(self.g1, 'alfa') i2.set_level(self.g1, 'bravo') i2.set_level(self.g2, 'bravo') self.assertItemsEqual( TestModel.get_objects_with_group_level('alfa', self.g1), [i1, i2]) self.assertItemsEqual( TestModel.get_objects_with_group_level('alfa', self.g2), [i2]) def test_owner(self): i = Test2Model.objects.create(normal2_field='Hello', owner=self.u1) self.assertTrue(i.has_level(self.u1, 'one')) self.assertTrue(i.has_level(self.u1, 'owner')) self.assertFalse(i.has_level(self.u2, 'owner')) def test_owner_change(self): i = Test2Model.objects.create(normal2_field='Hello', owner=self.u1) self.assertTrue(i.has_level(self.u1, 'one')) self.assertTrue(i.has_level(self.u1, 'owner')) self.assertFalse(i.has_level(self.u2, 'owner')) i.owner = self.u2 i.save() self.assertTrue(i.has_level(self.u1, 'one')) self.assertTrue(i.has_level(self.u1, 'owner')) self.assertTrue(i.has_level(self.u2, 'owner')) def test_owner_change_from_none(self): i = Test2Model.objects.create(normal2_field='Hello') self.assertFalse(i.has_level(self.u1, 'one')) self.assertFalse(i.has_level(self.u1, 'owner')) self.assertFalse(i.has_level(self.u2, 'owner')) i.owner = self.u2 i.save() self.assertFalse(i.has_level(self.u1, 'one')) self.assertFalse(i.has_level(self.u1, 'owner')) self.assertTrue(i.has_level(self.u2, 'owner')) views.py 0000664 0000000 0000000 00000001366 13126740172 0030501 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/acl # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . # Create your views here. bower.json 0000664 0000000 0000000 00000001051 13126740172 0030233 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle { "name": "circle", "version": "0.0.0", "license": "GPL", "private": true, "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests" ], "dependencies": { "bootstrap": "~3.2.0", "fontawesome": "~4.3.0", "jquery": "~2.1.1", "no-vnc": "0.5.1", "jquery-knob": "~1.2.9", "jquery-simple-slider": "https://github.com/BME-IK/jquery-simple-slider.git", "bootbox": "~4.3.0", "intro.js": "0.9.0", "favico.js": "~0.3.5", "datatables": "~1.10.4", "chart.js": "2.3.0" } } bower_components/ 0000775 0000000 0000000 00000000000 13126740172 0031610 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle .gitkeep 0000664 0000000 0000000 00000000000 13126740172 0033227 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/bower_components circle/ 0000775 0000000 0000000 00000000000 13126740172 0027466 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle __init__.py 0000664 0000000 0000000 00000001234 13126740172 0031577 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from django.db.models.signals import post_migrate def update_permissions_after_migration(sender, **kwargs): """ Update app permission just after every migration. This is based on app django_extensions update_permissions management command. """ from django.conf import settings from django.apps import apps from django.contrib.auth.management import create_permissions create_permissions(sender, apps.get_models(), 2 if settings.DEBUG else 0) post_migrate.connect(update_permissions_after_migration) settings/ 0000775 0000000 0000000 00000000000 13126740172 0031326 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle __init__.py 0000664 0000000 0000000 00000000000 13126740172 0033425 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle/settings base.py 0000664 0000000 0000000 00000046025 13126740172 0032621 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle/settings # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . """Common settings and globals.""" # flake8: noqa from os import environ from os.path import (abspath, basename, dirname, join, normpath, isfile, exists, expanduser) from sys import path from subprocess import check_output from uuid import getnode from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ from json import loads # from socket import SOCK_STREAM # Normally you should not import ANYTHING from Django directly # into your settings, but ImproperlyConfigured is an exception. def get_env_variable(var_name, default=None): """ Get the environment variable or return exception/default """ try: return environ[var_name] except KeyError: if default is None: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg) else: return default ########## PATH CONFIGURATION # Absolute filesystem path to the Django project directory: BASE_DIR = dirname(dirname(abspath(__file__))) # Absolute filesystem path to the top-level project folder: SITE_ROOT = dirname(BASE_DIR) # Site name: SITE_NAME = basename(BASE_DIR) # Url to site: (e.g. http://localhost:8080/) DJANGO_URL = get_env_variable('DJANGO_URL', '/') # Add our project to our pythonpath, this way we don't need to type our project # name in our dotted import paths: path.append(BASE_DIR) ########## END PATH CONFIGURATION ########## DEBUG CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = False # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATE_DEBUG = DEBUG ########## END DEBUG CONFIGURATION ########## MANAGER CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = ( ('Root', 'root@localhost'), ) EMAIL_SUBJECT_PREFIX = get_env_variable('DJANGO_SUBJECT_PREFIX', '[CIRCLE] ') ########## END MANAGER CONFIGURATION ########## DATABASE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.' + get_env_variable('DJANG_DB_TYPE', 'postgresql_psycopg2'), 'NAME': get_env_variable('DJANGO_DB_NAME', 'circle'), 'USER': get_env_variable('DJANGO_DB_USER', 'circle'), 'PASSWORD': get_env_variable('DJANGO_DB_PASSWORD'), 'HOST': get_env_variable('DJANGO_DB_HOST', ''), 'PORT': get_env_variable('DJANGO_DB_PORT', ''), } } ########## END DATABASE CONFIGURATION ########## GENERAL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone try: with open("/etc/timezone", "r") as f: systz = f.readline().rstrip() except: systz = None TIME_ZONE = get_env_variable('DJANGO_TIME_ZONE', default=systz) # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = get_env_variable("DJANGO_LANGUAGE_CODE", "en") # https://docs.djangoproject.com/en/dev/ref/settings/#languages LANGUAGES = ( ('en', _('English')), ('hu', _('Hungarian')), ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id SITE_ID = 1 # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n USE_I18N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n USE_L10N = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz USE_TZ = True ########## END GENERAL CONFIGURATION ########## MEDIA CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = get_env_variable('DJANGO_MEDIA_URL', default='/media/') ########## END MEDIA CONFIGURATION ########## STATIC FILE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, 'static_collected')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = get_env_variable('DJANGO_STATIC_URL', default='/static/') # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) ########## END STATIC FILE CONFIGURATION STATICFILES_DIRS = [normpath(join(SITE_ROOT, 'bower_components'))] p = normpath(join(SITE_ROOT, '../../site-circle/static')) if exists(p): STATICFILES_DIRS.append(p) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' PIPELINE = { 'COMPILERS' : ('pipeline.compilers.less.LessCompiler',), 'LESS_ARGUMENTS': u'--include-path={}'.format(':'.join(STATICFILES_DIRS)), 'CSS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor', 'JS_COMPRESSOR': None, 'DISABLE_WRAPPER': True, 'STYLESHEETS': { "all": {"source_filenames": ( "compile_bootstrap.less", "bootstrap/dist/css/bootstrap-theme.css", "fontawesome/css/font-awesome.css", "jquery-simple-slider/css/simple-slider.css", "intro.js/introjs.css", "template.less", "dashboard/dashboard.less", "network/network.less", "autocomplete_light/style.css", ), "output_filename": "all.css", } }, 'JAVASCRIPT': { "all": {"source_filenames": ( # "jquery/dist/jquery.js", # included separately "bootbox/bootbox.js", "bootstrap/dist/js/bootstrap.js", "intro.js/intro.js", "jquery-knob/dist/jquery.knob.min.js", "jquery-simple-slider/js/simple-slider.js", "favico.js/favico.js", "datatables/media/js/jquery.dataTables.js", "dashboard/dashboard.js", "dashboard/activity.js", "dashboard/group-details.js", "dashboard/group-list.js", "dashboard/js/stupidtable.min.js", # no bower file "dashboard/node-create.js", "dashboard/node-details.js", "dashboard/node-list.js", "dashboard/profile.js", "dashboard/store.js", "dashboard/template-list.js", "dashboard/vm-common.js", "dashboard/vm-create.js", "dashboard/vm-list.js", "dashboard/help.js", "js/host.js", "js/network.js", "js/switch-port.js", "js/host-list.js", "autocomplete_light/autocomplete.js", "autocomplete_light/widget.js", "autocomplete_light/addanother.js", "autocomplete_light/text_widget.js", "autocomplete_light/remote.js", ), "output_filename": "all.js", }, "vm-detail": {"source_filenames": ( "dashboard/vm-details.js", "no-vnc/include/util.js", "no-vnc/include/webutil.js", "no-vnc/include/base64.js", "no-vnc/include/websock.js", "no-vnc/include/des.js", "no-vnc/include/keysym.js", "no-vnc/include/keysymdef.js", "no-vnc/include/keyboard.js", "no-vnc/include/input.js", "no-vnc/include/display.js", "no-vnc/include/jsunzip.js", "no-vnc/include/rfb.js", "dashboard/vm-console.js", "dashboard/vm-tour.js", ), "output_filename": "vm-detail.js", }, "datastore": {"source_filenames": ( "chart.js/dist/Chart.min.js", "dashboard/datastore-details.js" ), "output_filename": "datastore.js", }, }, } ########## SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Note: This key should only be used for development and testing. SECRET_KEY = r"a5w*b0wajigd^kd7b=@w=5=+l_0c62@vljnhzqu3dfc@vx2jw-" ########## END SECRET CONFIGURATION ########## SITE CONFIGURATION # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] ########## END SITE CONFIGURATION ########## FIXTURE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS FIXTURE_DIRS = ( normpath(join(SITE_ROOT, 'fixtures')), ) ########## END FIXTURE CONFIGURATION ########## TEMPLATE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#TEMPLATES TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS' : ( normpath(join(SITE_ROOT, '../../site-circle/templates')), normpath(join(SITE_ROOT, 'templates')), ), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': ( 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', 'dashboard.context_processors.notifications', 'dashboard.context_processors.extract_settings', 'dashboard.context_processors.broadcast_messages', ), }, }] ########## END TEMPLATE CONFIGURATION ########## MIDDLEWARE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes MIDDLEWARE_CLASSES = ( # Default Django middleware. 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ########## END MIDDLEWARE CONFIGURATION ########## URL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf ROOT_URLCONF = '%s.urls' % SITE_NAME ########## END URL CONFIGURATION ########## APP CONFIGURATION DJANGO_APPS = ( # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Useful template tags: # 'django.contrib.humanize', # Admin panel and documentation: 'django.contrib.admin', # 'django.contrib.admindocs', ) THIRD_PARTY_APPS = ( 'django_tables2', 'crispy_forms', 'sizefield', 'taggit', 'statici18n', 'django_sshkey', 'dal', 'dal_select2', 'pipeline', ) # Apps specific for this project go here. LOCAL_APPS = ( 'common', 'vm', 'storage', 'firewall', 'network', 'dashboard', 'manager', 'acl', 'monitor', 'request', ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS ########## END APP CONFIGURATION ########## LOGGING CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(asctime)s [%(levelname)s]: %(name)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'syslog': { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'simple', 'address': '/dev/log', # 'socktype': SOCK_STREAM, # 'address': ('host', '514'), } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins', 'syslog'], 'level': 'INFO', 'propagate': True, }, } } ########## END LOGGING CONFIGURATION ########## WSGI CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME ########## END WSGI CONFIGURATION FIREWALL_SETTINGS = loads(get_env_variable('DJANGO_FIREWALL_SETTINGS')) CRISPY_TEMPLATE_PACK = 'bootstrap3' # format: id: (name, port, protocol) VM_ACCESS_PROTOCOLS = loads(get_env_variable('DJANGO_VM_ACCESS_PROTOCOLS', '''{"nx": ["NX", 22, "tcp"], "rdp": ["RDP", 3389, "tcp"], "ssh": ["SSH", 22, "tcp"]}''')) VM_SCHEDULER = 'manager.scheduler' #BROKER_URL = get_env_variable('AMQP_URI') #BROKER_URL=get_env_variable('AMQP_URI') CACHES = { 'default': { 'BACKEND': 'pylibmc', 'LOCATION': '127.0.0.1:11211', } } if get_env_variable('DJANGO_SAML', 'FALSE') == 'TRUE': try: from shutil import which # python >3.4 except ImportError: from shutilwhich import which from saml2 import BINDING_HTTP_POST, BINDING_HTTP_REDIRECT INSTALLED_APPS += ( 'djangosaml2', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'common.backends.Saml2Backend', ) remote_metadata = join(SITE_ROOT, 'remote_metadata.xml') if not isfile(remote_metadata): raise ImproperlyConfigured('Download SAML2 metadata to %s' % remote_metadata) required_attrs = loads(get_env_variable('DJANGO_SAML_REQUIRED', '["uid"]')) optional_attrs = loads(get_env_variable('DJANGO_SAML_OPTIONAL', '["mail", "cn", "sn"]')) SAML_CONFIG = { 'xmlsec_binary': which('xmlsec1'), 'entityid': DJANGO_URL + 'saml2/metadata/', 'attribute_map_dir': join(SITE_ROOT, 'attribute-maps'), 'service': { 'sp': { 'name': SITE_NAME, 'endpoints': { 'assertion_consumer_service': [ (DJANGO_URL + 'saml2/acs/', BINDING_HTTP_POST), ], 'single_logout_service': [ (DJANGO_URL + 'saml2/ls/', BINDING_HTTP_REDIRECT), ], }, 'required_attributes': required_attrs, 'optional_attributes': optional_attrs, }, }, 'metadata': {'local': [remote_metadata], }, 'key_file': join(SITE_ROOT, 'samlcert.key'), # private part 'cert_file': join(SITE_ROOT, 'samlcert.pem'), # public part } try: SAML_CONFIG += loads(get_env_variable('DJANGO_SAML_SETTINGS')) except ImproperlyConfigured: pass SAML_CREATE_UNKNOWN_USER = True SAML_ATTRIBUTE_MAPPING = loads(get_env_variable( 'DJANGO_SAML_ATTRIBUTE_MAPPING', '{"mail": ["email"], "sn": ["last_name"], ' '"uid": ["username"], "cn": ["first_name"]}')) SAML_GROUP_ATTRIBUTES = get_env_variable( 'DJANGO_SAML_GROUP_ATTRIBUTES', '').split(',') SAML_GROUP_OWNER_ATTRIBUTES = get_env_variable( 'DJANGO_SAML_GROUP_OWNER_ATTRIBUTES', '').split(',') SAML_CREATE_UNKNOWN_USER = True if get_env_variable('DJANGO_SAML_ORG_ID_ATTRIBUTE', False) is not False: SAML_ORG_ID_ATTRIBUTE = get_env_variable( 'DJANGO_SAML_ORG_ID_ATTRIBUTE') SAML_MAIN_ATTRIBUTE_MAX_LENGTH = int(get_env_variable( "DJANGO_SAML_MAIN_ATTRIBUTE_MAX_LENGTH", 0)) LOGIN_REDIRECT_URL = "/" AGENT_DIR = get_env_variable( 'DJANGO_AGENT_DIR', join(unicode(expanduser("~")), 'agent')) # AGENT_DIR is the root directory for the agent. # The directory structure SHOULD be: # /home/username/agent # |-- agent-linux # | |-- .git # | +-- ... # |-- agent-win # | +-- agent-win-%(version).exe # try: git_env = {'GIT_DIR': join(join(AGENT_DIR, "agent-linux"), '.git')} AGENT_VERSION = check_output( ('git', 'log', '-1', r'--pretty=format:%h', 'HEAD'), env=git_env) except: AGENT_VERSION = None LOCALE_PATHS = (join(SITE_ROOT, 'locale'), ) COMPANY_NAME = get_env_variable("COMPANY_NAME", "BME IK 2015") first, last = get_env_variable( 'VNC_PORT_RANGE', '50000, 60000').replace(' ', '').split(',') VNC_PORT_RANGE = (int(first), int(last)) # inclusive start, exclusive end graphite_host = environ.get("GRAPHITE_HOST", None) graphite_port = environ.get("GRAPHITE_PORT", None) if graphite_host and graphite_port: GRAPHITE_URL = 'http://%s:%s/render/' % (graphite_host, graphite_port) else: GRAPHITE_URL = None STORE_BASIC_AUTH = get_env_variable("STORE_BASIC_AUTH", "") == "True" STORE_VERIFY_SSL = get_env_variable("STORE_VERIFY_SSL", "") == "True" STORE_SSL_AUTH = get_env_variable("STORE_SSL_AUTH", "") == "True" STORE_CLIENT_USER = get_env_variable("STORE_CLIENT_USER", "") STORE_CLIENT_PASSWORD = get_env_variable("STORE_CLIENT_PASSWORD", "") STORE_CLIENT_KEY = get_env_variable("STORE_CLIENT_KEY", "") STORE_CLIENT_CERT = get_env_variable("STORE_CLIENT_CERT", "") STORE_URL = get_env_variable("STORE_URL", "") SESSION_COOKIE_NAME = "csessid%x" % (((getnode() // 139) ^ (getnode() % 983)) & 0xffff) MAX_NODE_RAM = get_env_variable("MAX_NODE_RAM", 1024) # Url to download the client: (e.g. http://circlecloud.org/client/download/) CLIENT_DOWNLOAD_URL = get_env_variable('CLIENT_DOWNLOAD_URL', 'http://circlecloud.org/client/download/') ADMIN_ENABLED = False BLACKLIST_PASSWORD = get_env_variable("BLACKLIST_PASSWORD", "") BLACKLIST_HOOK_URL = get_env_variable("BLACKLIST_HOOK_URL", "") REQUEST_HOOK_URL = get_env_variable("REQUEST_HOOK_URL", "") SSHKEY_EMAIL_ADD_KEY = False TWO_FACTOR_ISSUER = get_env_variable("TWO_FACTOR_ISSUER", "CIRCLE") local.py 0000664 0000000 0000000 00000006754 13126740172 0033006 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle/settings # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . """Development settings and globals.""" # flake8: noqa from base import * # noqa ########## DEBUG CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATES[0]['OPTIONS']['debug'] = DEBUG ########## END DEBUG CONFIGURATION SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') ########## EMAIL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ########## END EMAIL CONFIGURATION ########## DATABASE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': normpath(join(BASE_DIR, 'default.db')), # 'USER': '', # 'PASSWORD': '', # 'HOST': '', # 'PORT': '', # } # } ########## END DATABASE CONFIGURATION ########## CACHE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } } ########## END CACHE CONFIGURATION ########## ROSETTA CONFIGURATION INSTALLED_APPS += ( 'rosetta', ) ########## END ROSETTA CONFIGURATION ########## TOOLBAR CONFIGURATION # https://github.com/django-debug-toolbar/django-debug-toolbar#installation if get_env_variable('DJANGO_TOOLBAR', 'FALSE') == 'TRUE': INSTALLED_APPS += ( 'debug_toolbar', ) # https://github.com/django-debug-toolbar/django-debug-toolbar#installation INTERNAL_IPS = ( get_env_variable('SSH_CLIENT', '127.0.0.1').split(' ')[0], ) # https://github.com/django-debug-toolbar/django-debug-toolbar#installation MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) # https://github.com/django-debug-toolbar/django-debug-toolbar#installation DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TEMPLATE_CONTEXT': True, } ########## END TOOLBAR CONFIGURATION LOGGING['loggers']['djangosaml2'] = {'handlers': ['console'], 'level': 'DEBUG'} LOGGING['handlers']['console'] = {'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple'} for i in LOCAL_APPS: LOGGING['loggers'][i] = {'handlers': ['console'], 'level': 'DEBUG'} CRISPY_FAIL_SILENTLY = not DEBUG # propagate exceptions from signals if DEBUG: from django.dispatch import Signal Signal.send_robust = Signal.send PIPELINE["COMPILERS"] = ( 'dashboard.compilers.DummyLessCompiler', ) ADMIN_ENABLED = True ALLOWED_HOSTS = ['*'] production.py 0000664 0000000 0000000 00000006353 13126740172 0034075 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle/settings # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . """Production settings and globals.""" # flake8: noqa from os import environ from sys import argv from base import * # noqa if 'runserver' in argv: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') ########## HOST CONFIGURATION # See: https://docs.djangoproject.com/en/1.5/releases/1.5/ # #allowed-hosts-required-in-production ALLOWED_HOSTS = get_env_variable('DJANGO_ALLOWED_HOSTS').split(',') ########## END HOST CONFIGURATION ########## EMAIL CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' try: # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host EMAIL_HOST = get_env_variable('EMAIL_HOST') except ImproperlyConfigured: EMAIL_HOST = 'localhost' else: # https://docs.djangoproject.com/en/dev/ref/settings/#email-host-password EMAIL_HOST_PASSWORD = get_env_variable('EMAIL_HOST_PASSWORD', '') # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-host-user EMAIL_HOST_USER = get_env_variable('EMAIL_HOST_USER', 'your_email@example.com') # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-port EMAIL_PORT = get_env_variable('EMAIL_PORT', 587) # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-use-tls EMAIL_USE_TLS = True # See: https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix EMAIL_SUBJECT_PREFIX = '[%s] ' % SITE_NAME # See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email DEFAULT_FROM_EMAIL = get_env_variable('DEFAULT_FROM_EMAIL') SERVER_EMAIL = get_env_variable('SERVER_EMAIL', DEFAULT_FROM_EMAIL) ########## END EMAIL CONFIGURATION ########## CACHE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#caches from urlparse import urlsplit CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': urlsplit(get_env_variable('CACHE_URI')).netloc, } } ########## END CACHE CONFIGURATION ########## SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = get_env_variable('SECRET_KEY') ########## END SECRET CONFIGURATION level = environ.get('LOGLEVEL', 'INFO') LOGGING['handlers']['syslog']['level'] = level for i in LOCAL_APPS: LOGGING['loggers'][i] = {'handlers': ['syslog'], 'level': level} LOGGING['loggers']['djangosaml2'] = {'handlers': ['syslog'], 'level': level} LOGGING['loggers']['django'] = {'handlers': ['syslog'], 'level': level} selenium_test.py 0000664 0000000 0000000 00000005765 13126740172 0034575 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle/settings # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . import os from .base import * # noqa # fix https://github.com/django-nose/django-nose/issues/197 # AttributeError: 'module' object has no attribute 'commit_unless_managed' # TypeError: _skip_create_test_db() got an unexpected keyword argument 'keepdb' from django.db import transaction from django_nose import runner def _skip_create_test_db(self, verbosity=1, autoclobber=False, serialize=True, keepdb=True): return old_skip_create_test_db( self, verbosity=verbosity, autoclobber=autoclobber, serialize=serialize) setattr(transaction, "commit_unless_managed", lambda using: using) old_skip_create_test_db = runner._skip_create_test_db setattr(runner, "_skip_create_test_db", _skip_create_test_db) os.environ['REUSE_DB'] = "1" os.environ['DJANGO_TEST_DB_NAME'] = "circle" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.' + get_env_variable('DJANG_DB_TYPE', 'postgresql_psycopg2'), 'NAME': get_env_variable('DJANGO_DB_NAME', 'circle'), 'TEST_NAME': get_env_variable('DJANGO_TEST_DB_NAME', 'circle'), 'USER': get_env_variable('DJANGO_DB_USER', 'circle'), 'PASSWORD': get_env_variable('DJANGO_DB_PASSWORD'), 'HOST': get_env_variable('DJANGO_DB_HOST', ''), 'PORT': get_env_variable('DJANGO_DB_PORT', ''), } } SOUTH_TESTS_MIGRATE = False INSTALLED_APPS += ( 'acl.tests', 'django_nose', 'django_jenkins', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' path_to_selenium_test = os.path.join(SITE_ROOT, "dashboard/tests/selenium") NOSE_ARGS = ['--stop', '--with-doctest', '--with-selenium-driver', '--selenium-driver=firefox', '-w%s' % path_to_selenium_test] PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher'] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache' } } LOGGING['loggers']['djangosaml2'] = {'handlers': ['console'], 'level': 'CRITICAL'} level = environ.get('LOGLEVEL', 'CRITICAL') LOGGING['handlers']['console'] = {'level': level, 'class': 'logging.StreamHandler', 'formatter': 'simple'} for i in LOCAL_APPS: LOGGING['loggers'][i] = {'handlers': ['console'], 'level': level} test.py 0000664 0000000 0000000 00000004447 13126740172 0032670 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle/settings # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from .base import * # noqa # flake8: noqa ########## IN-MEMORY TEST DATABASE DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", }, } SOUTH_TESTS_MIGRATE = False INSTALLED_APPS += ( 'acl.tests', 'django_nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--with-doctest', '--exclude-dir=dashboard/tests/selenium', '--exclude=circle' ] PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher'] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache' } } LOGGING['loggers']['djangosaml2'] = {'handlers': ['console'], 'level': 'CRITICAL'} level = environ.get('LOGLEVEL', 'CRITICAL') LOGGING['handlers']['console'] = {'level': level, 'class': 'logging.StreamHandler', 'formatter': 'simple'} for i in LOCAL_APPS: LOGGING['loggers'][i] = {'handlers': ['console'], 'level': level} # don't print SQL queries LOGGING['handlers']['null'] = {'level': "DEBUG", 'class': "logging.NullHandler"} LOGGING['loggers']['django.db.backends'] = { 'handlers': ['null'], 'propagate': False, 'level': 'DEBUG', } # Forbid store usage STORE_URL = "" # buildbot doesn't love pipeline STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' SAML_MAIN_ATTRIBUTE_MAX_LENGTH=0 # doctest on SAML2 backend runs either way urls.py 0000664 0000000 0000000 00000006603 13126740172 0031032 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from django.conf.urls import patterns, include, url from django.views.generic import TemplateView from django.conf import settings from django.contrib import admin from django.core.urlresolvers import reverse from django.shortcuts import redirect from circle.settings.base import get_env_variable from dashboard.views import ( CircleLoginView, HelpView, ResizeHelpView, TwoFactorLoginView ) from dashboard.forms import CirclePasswordResetForm, CircleSetPasswordForm from firewall.views import add_blacklist_item admin.autodiscover() urlpatterns = patterns( '', url(r'^$', lambda x: redirect(reverse("dashboard.index"))), url(r'^network/', include('network.urls')), url(r'^blacklist-add/', add_blacklist_item), url(r'^dashboard/', include('dashboard.urls')), url(r'^request/', include('request.urls')), # django/contrib/auth/urls.py (care when new version) url((r'^accounts/reset/(?P[0-9A-Za-z_\-]+)/' r'(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'), 'django.contrib.auth.views.password_reset_confirm', {'set_password_form': CircleSetPasswordForm}, name='accounts.password_reset_confirm' ), url(r'^accounts/password/reset/$', ("django.contrib.auth.views." "password_reset"), {'password_reset_form': CirclePasswordResetForm}, name="accounts.password-reset", ), url(r'^accounts/login/?$', CircleLoginView.as_view(), name="accounts.login"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^two-factor-login/$', TwoFactorLoginView.as_view(), name="two-factor-login"), url(r'^info/help/$', HelpView.as_view(template_name="info/help.html"), name="info.help"), url(r'^info/policy/$', TemplateView.as_view(template_name="info/policy.html"), name="info.policy"), url(r'^info/legal/$', TemplateView.as_view(template_name="info/legal.html"), name="info.legal"), url(r'^info/support/$', TemplateView.as_view(template_name="info/support.html"), name="info.support"), url(r'^info/resize-how-to/$', ResizeHelpView.as_view(), name="info.resize"), ) if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += patterns( '', url(r'^rosetta/', include('rosetta.urls')), ) if settings.ADMIN_ENABLED: urlpatterns += patterns( '', url(r'^admin/', include(admin.site.urls)), ) if get_env_variable('DJANGO_SAML', 'FALSE') == 'TRUE': urlpatterns += patterns( '', (r'^saml2/', include('djangosaml2.urls')), ) handler500 = 'common.views.handler500' handler403 = 'common.views.handler403' wsgi.py 0000664 0000000 0000000 00000004765 13126740172 0031025 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/circle # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . """ WSGI config for circle project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from os.path import abspath, dirname from sys import path SITE_ROOT = dirname(dirname(abspath(__file__))) path.append(SITE_ROOT) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "jajaja.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "circle.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application # noqa _application = get_wsgi_application() def application(environ, start_response): # copy DJANGO_* wsgi-env vars to process-env for i in environ.keys(): if i.startswith('DJANGO_'): os.environ[i] = environ[i] return _application(environ, start_response) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) common/ 0000775 0000000 0000000 00000000000 13126740172 0027515 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle __init__.py 0000664 0000000 0000000 00000000000 13126740172 0031614 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common backends.py 0000664 0000000 0000000 00000004257 13126740172 0031651 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common # -*- coding: utf-8 -*- # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . import re import logging import sha from django.conf import settings from djangosaml2.backends import Saml2Backend as Saml2BackendBase logger = logging.getLogger(__name__) class Saml2Backend(Saml2BackendBase): u""" >>> b = Saml2Backend() >>> b.clean_user_main_attribute(u'Ékezetes Enikő') u'+00c9kezetes+0020Enik+0151' >>> b.clean_user_main_attribute(u'Cé++') u'C+00e9+002b+002b' >>> b.clean_user_main_attribute(u'test') u'test' >>> b.clean_user_main_attribute(u'3+4') u'3+002b4' """ def clean_user_main_attribute(self, main_attribute): def replace(match): match = match.group() return '+%04x' % ord(match) if isinstance(main_attribute, str): main_attribute = main_attribute.decode('UTF-8') assert isinstance(main_attribute, unicode) attr = re.sub(r'[^\w.@-]', replace, main_attribute) max_length = settings.SAML_MAIN_ATTRIBUTE_MAX_LENGTH if max_length > 0 and len(attr) > max_length: logger.info("Main attribute '%s' is too long." % attr) hashed = sha.new(attr).hexdigest() attr = hashed[:max_length] logger.info("New main attribute: %s" % attr) return attr def _set_attribute(self, obj, attr, value): if attr == 'username': value = self.clean_user_main_attribute(value) return super(Saml2Backend, self)._set_attribute(obj, attr, value) management/ 0000775 0000000 0000000 00000000000 13126740172 0031631 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common __init__.py 0000664 0000000 0000000 00000000000 13126740172 0033730 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/management commands/ 0000775 0000000 0000000 00000000000 13126740172 0033432 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/management __init__.py 0000664 0000000 0000000 00000000000 13126740172 0035531 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/management/commands compileless.py 0000664 0000000 0000000 00000001770 13126740172 0036330 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/management/commands # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from django.core.management.base import BaseCommand from common.management.commands.watch import LessUtils class Command(BaseCommand): help = "Compiles all LESS files." def handle(self, *args, **kwargs): print("Compiling LESS") LessUtils.initial_compile() watch.py 0000664 0000000 0000000 00000007016 13126740172 0035116 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/management/commands # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . import subprocess import os import pyinotify from django.core.management.base import BaseCommand from django.conf import settings STATIC_FILES = u'--include-path={}'.format(':'.join(settings.STATICFILES_DIRS)) IGNORED_FOLDERS = ("static_collected", "bower_components", ) class LessUtils(object): @staticmethod def less_path_to_css_path(pathname): return "%s.css" % pathname[:-1 * len(".less")] @staticmethod def compile_less(less_pathname, css_pathname): cmd = ["lessc", STATIC_FILES, less_pathname, css_pathname] print("\n%s" % ("=" * 30)) print("Compiling: %s" % os.path.basename(less_pathname)) try: subprocess.check_output(cmd) except subprocess.CalledProcessError as e: print(e.output) else: print("Successfully compiled:\n%s\n->\n%s" % ( less_pathname, css_pathname)) @staticmethod def initial_compile(): """ Walks through the project looking for LESS files and compiles them into CSS. """ for root, dirs, files in os.walk(settings.SITE_ROOT): for f in files: if not f.endswith(".less"): continue relpath = os.path.relpath(root, settings.SITE_ROOT) if relpath.startswith(IGNORED_FOLDERS): continue less_pathname = "%s/%s" % (root, f) css_pathname = LessUtils.less_path_to_css_path(less_pathname) LessUtils.compile_less(less_pathname, css_pathname) @staticmethod def start_watch(): """ Watches for changes in LESS files recursively from the project's root and compiles the files """ wm = pyinotify.WatchManager() class EventHandler(pyinotify.ProcessEvent): def process_IN_MODIFY(self, event): if not event.name.endswith(".less"): return relpath = os.path.relpath(event.pathname, settings.SITE_ROOT) if relpath.startswith(IGNORED_FOLDERS): return css_pathname = LessUtils.less_path_to_css_path(event.pathname) LessUtils.compile_less(event.pathname, css_pathname) handler = EventHandler() notifier = pyinotify.Notifier(wm, handler) wm.add_watch(settings.SITE_ROOT, pyinotify.IN_MODIFY, rec=True) notifier.loop() class Command(BaseCommand): help = "Compiles all LESS files then watches for changes." def handle(self, *args, **kwargs): # for first run compile everything print("Initial LESS compiles") LessUtils.initial_compile() print("\n%s\n" % ("=" * 30)) print("End of initial LESS compiles\n") # after first run watch less files LessUtils.start_watch() models.py 0000664 0000000 0000000 00000051362 13126740172 0031361 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from collections import deque from contextlib import contextmanager from functools import update_wrapper from hashlib import sha224 from itertools import chain, imap from logging import getLogger from time import time from warnings import warn from django.contrib import messages from django.contrib.auth.models import User from django.core.cache import cache from django.core.exceptions import PermissionDenied from django.core.serializers.json import DjangoJSONEncoder from django.db.models import ( CharField, DateTimeField, ForeignKey, NullBooleanField ) from django.template import defaultfilters from django.utils import timezone from django.utils.encoding import force_text from django.utils.functional import Promise from django.utils.translation import ugettext_lazy as _, ugettext_noop from jsonfield import JSONField from manager.mancelery import celery from model_utils.models import TimeStampedModel logger = getLogger(__name__) class WorkerNotFound(Exception): pass def get_error_msg(exception): try: return unicode(exception) except UnicodeDecodeError: return unicode(str(exception), encoding='utf-8', errors='replace') def activitycontextimpl(act, on_abort=None, on_commit=None): result = None try: try: yield act except HumanReadableException as e: result = e raise except BaseException as e: # BaseException is the common parent of Exception and # system-exiting exceptions, e.g. KeyboardInterrupt result = create_readable( ugettext_noop("Failure."), ugettext_noop("Unhandled exception: %(e)s: %(error)s"), e=str(e.__class__.__name__), error=get_error_msg(e)) raise except: logger.exception("Failed activity %s" % unicode(act)) handler = None if on_abort is None else lambda a: on_abort(a, e) act.finish(succeeded=False, result=result, event_handler=handler) raise else: act.finish(succeeded=True, event_handler=on_commit) activity_context = contextmanager(activitycontextimpl) activity_code_separator = '.' def has_prefix(activity_code, *prefixes): """Determine whether the activity code has the specified prefix. >>> assert has_prefix('foo.bar.buz', 'foo.bar') >>> assert has_prefix('foo.bar.buz', 'foo', 'bar') >>> assert has_prefix('foo.bar.buz', 'foo.bar', 'buz') >>> assert has_prefix('foo.bar.buz', 'foo', 'bar', 'buz') >>> assert not has_prefix('foo.bar.buz', 'foo', 'buz') """ def equal(a, b): return a == b act_code_parts = split_activity_code(activity_code) prefixes = chain(*imap(split_activity_code, prefixes)) return all(imap(equal, act_code_parts, prefixes)) def has_suffix(activity_code, *suffixes): """Determine whether the activity code has the specified suffix. >>> assert has_suffix('foo.bar.buz', 'bar.buz') >>> assert has_suffix('foo.bar.buz', 'bar', 'buz') >>> assert has_suffix('foo.bar.buz', 'foo.bar', 'buz') >>> assert has_suffix('foo.bar.buz', 'foo', 'bar', 'buz') >>> assert not has_suffix('foo.bar.buz', 'foo', 'buz') """ def equal(a, b): return a == b act_code_parts = split_activity_code(activity_code) suffixes = list(chain(*imap(split_activity_code, suffixes))) return all(imap(equal, reversed(act_code_parts), reversed(suffixes))) def join_activity_code(*args): """Join the specified parts into an activity code. :returns: Activity code string. """ return activity_code_separator.join(args) def split_activity_code(activity_code): """Split the specified activity code into its parts. :returns: A list of activity code parts. """ return activity_code.split(activity_code_separator) class Encoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Promise): obj = force_text(obj) try: return super(Encoder, self).default(obj) except TypeError: return unicode(obj) class ActivityModel(TimeStampedModel): activity_code = CharField(max_length=100, verbose_name=_('activity code')) readable_name_data = JSONField(blank=True, null=True, dump_kwargs={"cls": Encoder}, verbose_name=_('human readable name'), help_text=_('Human readable name of ' 'activity.')) parent = ForeignKey('self', blank=True, null=True, related_name='children') task_uuid = CharField(blank=True, max_length=50, null=True, unique=True, help_text=_('Celery task unique identifier.'), verbose_name=_('task_uuid')) user = ForeignKey(User, blank=True, null=True, verbose_name=_('user'), help_text=_('The person who started this activity.')) started = DateTimeField(verbose_name=_('started at'), blank=True, null=True, help_text=_('Time of activity initiation.')) finished = DateTimeField(verbose_name=_('finished at'), blank=True, null=True, help_text=_('Time of activity finalization.')) succeeded = NullBooleanField(blank=True, null=True, help_text=_('True, if the activity has ' 'finished successfully.')) result_data = JSONField(verbose_name=_('result'), blank=True, null=True, dump_kwargs={"cls": Encoder}, help_text=_('Human readable result of activity.')) def __unicode__(self): if self.parent: return self.parent.activity_code + "->" + self.activity_code else: return self.activity_code class Meta: abstract = True def finish(self, succeeded, result=None, event_handler=None): if not self.finished: self.finished = timezone.now() self.succeeded = succeeded if result is not None: self.result = result if event_handler is not None: event_handler(self) self.save() @property def has_succeeded(self): return self.finished and self.succeeded @property def has_failed(self): return self.finished and not self.succeeded @property def readable_name(self): return HumanReadableObject.from_dict(self.readable_name_data) @readable_name.setter def readable_name(self, value): self.readable_name_data = None if value is None else value.to_dict() @property def result(self): return HumanReadableObject.from_dict(self.result_data) @result.setter def result(self, value): if isinstance(value, basestring): warn("Using string as result value is deprecated. Use " "HumanReadableObject instead.", DeprecationWarning, stacklevel=2) value = create_readable(user_text_template="", admin_text_template=value) elif not hasattr(value, "to_dict"): warn("Use HumanReadableObject.", DeprecationWarning, stacklevel=2) value = create_readable(user_text_template="", admin_text_template=unicode(value)) self.result_data = None if value is None else value.to_dict() @classmethod def construct_activity_code(cls, code_suffix, sub_suffix=None): code = join_activity_code(cls.ACTIVITY_CODE_BASE, code_suffix) if sub_suffix: return join_activity_code(code, sub_suffix) else: return code def get_status_id(self): if self.succeeded is None: return 'wait' elif self.succeeded: return 'success' else: return 'failed' @celery.task() def compute_cached(method, instance, memcached_seconds, key, start, *args, **kwargs): """Compute and store actual value of cached method.""" if isinstance(method, basestring): model, id = instance instance = model.objects.get(id=id) try: method = getattr(model, method) while hasattr(method, '_original') or hasattr(method, 'fget'): try: method = method._original except AttributeError: method = method.fget except AttributeError: logger.exception("Couldnt get original method of %s", unicode(method)) raise # call the actual method result = method(instance, *args, **kwargs) # save to memcache cache.set(key, result, memcached_seconds) elapsed = time() - start cache.set("%s.cached" % key, 2, max(memcached_seconds * 0.5, memcached_seconds * 0.75 - elapsed)) logger.debug('Value of <%s>.%s(%s)=<%s> saved to cache (%s elapsed).', unicode(instance), method.__name__, unicode(args), unicode(result), elapsed) return result def method_cache(memcached_seconds=60, instance_seconds=5): # noqa """Cache return value of decorated method to memcached and memory. :param memcached_seconds: Invalidate memcached results after this time. :param instance_seconds: Invalidate results cached to static memory after this time. If a result is cached on instance, return that first. If that fails, check memcached. If all else fails, run the method and cache on instance and in memcached. Do not use for methods with side effects. Instances are hashed by their id attribute, args by their unicode representation. ** NOTE: Methods that return None are always "recached". Based on https://djangosnippets.org/snippets/2477/ """ def inner_cache(method): method_name = method.__name__ def get_key(instance, *args, **kwargs): return sha224(unicode(method.__module__) + method_name + unicode(instance.id) + unicode(args) + unicode(kwargs)).hexdigest() def x(instance, *args, **kwargs): invalidate = kwargs.pop('invalidate_cache', False) now = time() key = get_key(instance, *args, **kwargs) result = None try: vals = getattr(instance, key) except AttributeError: pass else: if vals['time'] + instance_seconds > now: # has valid on class cache, return that result = vals['value'] setattr(instance, key, {'time': now, 'value': result}) if result is None: result = cache.get(key) if invalidate or (result is None): logger.debug("all caches failed, compute now") result = compute_cached(method, instance, memcached_seconds, key, time(), *args, **kwargs) setattr(instance, key, {'time': now, 'value': result}) elif not cache.get("%s.cached" % key): logger.debug("caches expiring, compute async") cache.set("%s.cached" % key, 1, memcached_seconds * 0.5) try: compute_cached.apply_async( queue='localhost.man', kwargs=kwargs, args=[ method_name, (instance.__class__, instance.id), memcached_seconds, key, time()] + list(args)) except: logger.exception("Couldnt compute async %s", method_name) return result update_wrapper(x, method) x._original = method return x return inner_cache class HumanSortField(CharField): """ A CharField that monitors another field on the same model and sets itself to a normalized value, which can be used for sensible lexicographycal sorting for fields containing numerals. (Avoiding technically correct orderings like [a1, a10, a2], which can be annoying for file or host names.) Apart from CharField's default arguments, an argument is requered: - monitor sets the base field, whose value is normalized. - maximum_number_length can also be provided, and defaults to 4. If you have to sort values containing numbers greater than 9999, you should increase it. Code is based on carljm's django-model-utils. """ def __init__(self, *args, **kwargs): kwargs.setdefault('default', "") self.maximum_number_length = kwargs.pop('maximum_number_length', 4) monitor = kwargs.pop('monitor', None) if not monitor: raise TypeError( '%s requires a "monitor" argument' % self.__class__.__name__) self.monitor = monitor kwargs['blank'] = True super(HumanSortField, self).__init__(*args, **kwargs) def get_monitored_value(self, instance): return getattr(instance, self.monitor) def deconstruct(self): name, path, args, kwargs = super(HumanSortField, self).deconstruct() if self.monitor is not None: kwargs['monitor'] = self.monitor return name, path, args, kwargs @staticmethod def _partition(s, pred): """Partition a deque of chars to a tuple of a - string of the longest prefix matching pred, - string of the longest prefix after the former one not matching, - deque of the remaining characters. >>> HumanSortField._partition(deque("1234abc567"), ... lambda s: s.isdigit()) ('1234', 'abc', deque(['5', '6', '7'])) >>> HumanSortField._partition(deque("12ab"), lambda s: s.isalpha()) ('', '12', deque(['a', 'b'])) """ match, notmatch = deque(), deque() while s and pred(s[0]): match.append(s.popleft()) while s and not pred(s[0]): notmatch.append(s.popleft()) return (''.join(match), ''.join(notmatch), s) def get_normalized_value(self, val): logger.debug('Normalizing value: %s', val) norm = "" val = deque(val) while val: numbers, letters, val = self._partition(val, lambda s: s[0].isdigit()) if numbers: norm += numbers.rjust(self.maximum_number_length, '0') norm += letters logger.debug('Normalized value: %s', norm) return norm def pre_save(self, model_instance, add): logger.debug('Pre-saving %s.%s. %s', model_instance, self.attname, add) value = self.get_normalized_value( self.get_monitored_value(model_instance)) setattr(model_instance, self.attname, value[:self.max_length]) return super(HumanSortField, self).pre_save(model_instance, add) class HumanReadableObject(object): def __init__(self, user_text_template, admin_text_template, params): self._set_values(user_text_template, admin_text_template, params) def _set_values(self, user_text_template, admin_text_template, params): if isinstance(user_text_template, Promise): user_text_template = user_text_template._proxy____args[0] if isinstance(admin_text_template, Promise): admin_text_template = admin_text_template._proxy____args[0] self.user_text_template = user_text_template self.admin_text_template = admin_text_template for k, v in params.iteritems(): try: v = timezone.datetime.strptime( v, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.UTC()) except (ValueError, TypeError): # Mock raises TypeError pass if isinstance(v, timezone.datetime): params[k] = defaultfilters.date(v, "DATETIME_FORMAT") self.params = params @classmethod def create(cls, user_text_template, admin_text_template=None, **params): return cls(user_text_template=user_text_template, admin_text_template=(admin_text_template or user_text_template), params=params) def set(self, user_text_template, admin_text_template=None, **params): self._set_values(user_text_template, admin_text_template or user_text_template, params) @classmethod def from_dict(cls, d): return None if d is None else cls(**d) def _get_parsed_text(self, key): value = getattr(self, key) if value == "": return "" try: return _(value) % self.params except KeyError: logger.exception("Can't render %s '%s' %% %s", key, value, unicode(self.params)) raise def get_admin_text(self): try: return self._get_parsed_text("admin_text_template") except KeyError: return self.get_user_text() def get_user_text(self): try: return self._get_parsed_text("user_text_template") except KeyError: return self.user_text_template def get_text(self, user): if user and user.is_superuser: return self.get_admin_text() else: return self.get_user_text() def to_dict(self): return {"user_text_template": self.user_text_template, "admin_text_template": self.admin_text_template, "params": self.params} def __unicode__(self): return self.get_user_text() create_readable = HumanReadableObject.create class HumanReadableException(HumanReadableObject, Exception): """HumanReadableObject that is an Exception so can used in except clause. """ def __init__(self, level=None, *args, **kwargs): super(HumanReadableException, self).__init__(*args, **kwargs) if level is not None: if hasattr(messages, level): self.level = level else: raise ValueError( "Level should be the name of an attribute of django." "contrib.messages (and it should be callable with " "(request, message)). Like 'error', 'warning'.") elif not hasattr(self, "level"): self.level = "error" def send_message(self, request, level=None): msg = self.get_text(request.user) getattr(messages, level or self.level)(request, msg) def fetch_human_exception(exception, user=None): """Fetch user readable message from exception. >>> r = humanize_exception("foo", Exception()) >>> fetch_human_exception(r, User()) u'foo' >>> fetch_human_exception(r).get_text(User()) u'foo' >>> fetch_human_exception(Exception(), User()) u'Unknown error' >>> fetch_human_exception(PermissionDenied(), User()) u'Permission Denied' """ if not isinstance(exception, HumanReadableException): if isinstance(exception, PermissionDenied): exception = create_readable(ugettext_noop("Permission Denied")) else: exception = create_readable(ugettext_noop("Unknown error"), ugettext_noop("Unknown error: %(ex)s"), ex=unicode(exception)) return exception.get_text(user) if user else exception def humanize_exception(message, exception=None, level=None, **params): """Return new dynamic-class exception which is based on HumanReadableException and the original class with the dict of exception. >>> try: raise humanize_exception("Welcome!", TypeError("hello")) ... except HumanReadableException as e: print e.get_admin_text() ... Welcome! """ Ex = type("HumanReadable" + type(exception).__name__, (HumanReadableException, type(exception)), exception.__dict__) ex = Ex.create(message, **params) if level: ex.level = level return ex operations.py 0000664 0000000 0000000 00000026232 13126740172 0032257 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from inspect import getargspec from logging import getLogger from django.core.exceptions import PermissionDenied, ImproperlyConfigured from django.utils.translation import ugettext_noop from .models import (activity_context, has_suffix, humanize_exception, HumanReadableObject) logger = getLogger(__name__) class SubOperationMixin(object): required_perms = () def create_activity(self, parent, user, kwargs): if not parent: raise TypeError("SubOperation can only be called with " "parent_activity specified.") return super(SubOperationMixin, self).create_activity( parent, user, kwargs) class Operation(object): """Base class for VM operations. """ async_queue = 'localhost.man' required_perms = None superuser_required = False do_not_call_in_templates = True abortable = False has_percentage = False @classmethod def get_activity_code_suffix(cls): return cls.id def __call__(self, **kwargs): return self.call(**kwargs) def __init__(self, subject): """Initialize a new operation bound to the specified subject. """ self.subject = subject def __unicode__(self): return self.name def __prelude(self, kwargs): """This method contains the shared prelude of call and async. """ defaults = {'parent_activity': None, 'system': False, 'user': None} allargs = dict(defaults, **kwargs) # all arguments auxargs = allargs.copy() # auxiliary (i.e. only for _operation) args # NOTE: consumed items should be removed from auxargs, and no new items # should be added to it skip_auth_check = auxargs.pop('system') user = auxargs.pop('user') parent_activity = auxargs.pop('parent_activity') if parent_activity and user is None and not skip_auth_check: user = allargs['user'] = parent_activity.user if user is None: # parent was a system call skip_auth_check = True # check for unexpected keyword arguments argspec = getargspec(self._operation) if argspec.keywords is None: # _operation doesn't take ** args unexpected_kwargs = set(auxargs) - set(argspec.args) if unexpected_kwargs: raise TypeError("Operation got unexpected keyword arguments: " "%s" % ", ".join(unexpected_kwargs)) if not skip_auth_check: self.check_auth(user) self.check_precond() activity = self.create_activity( parent=parent_activity, user=user, kwargs=kwargs) return activity, allargs, auxargs def _exec_op(self, allargs, auxargs): """Execute the operation inside the specified activity's context. """ # compile arguments for _operation argspec = getargspec(self._operation) if argspec.keywords is not None: # _operation takes ** args arguments = allargs.copy() else: # _operation doesn't take ** args arguments = {k: v for (k, v) in allargs.iteritems() if k in argspec.args} arguments.update(auxargs) with activity_context(allargs['activity'], on_abort=self.on_abort, on_commit=self.on_commit) as act: retval = self._operation(**arguments) if (act.result is None and isinstance( retval, (basestring, int, HumanReadableObject))): act.result = retval return retval def _operation(self, **kwargs): """This method is the operation's particular implementation. Deriving classes should implement this method. """ raise NotImplementedError def async(self, **kwargs): """Execute the operation asynchronously. Only a quick, preliminary check is ran before creating the associated activity and queuing the job. The returned value is the handle for the asynchronous job. For more information, check the synchronous call's documentation. """ logger.info("%s called asynchronously on %s with the following " "parameters: %r", self.__class__.__name__, self.subject, kwargs) activity, allargs, auxargs = self.__prelude(kwargs) return self.async_operation.apply_async( args=(self.id, self.subject.pk, activity.pk, allargs, auxargs, ), queue=self.async_queue) def call(self, **kwargs): """Execute the operation (synchronously). Anticipated keyword arguments: * parent_activity: Parent activity for the operation. If this argument is present, the operation's activity will be created as a child activity of it. * system: Indicates that the operation is invoked by the system, not a User. If this argument is present and has a value of True, then authorization checks are skipped. * user: The User invoking the operation. If this argument is not present, it'll be provided with a default value of None. """ logger.info("%s called (synchronously) on %s with the following " "parameters: %r", self.__class__.__name__, self.subject, kwargs) activity, allargs, auxargs = self.__prelude(kwargs) allargs['activity'] = activity return self._exec_op(allargs, auxargs) def check_precond(self): pass @classmethod def check_perms(cls, user): """Check if user is permitted to run this operation on any instance """ if cls.required_perms is None: raise ImproperlyConfigured( "Set required_perms to () if none needed.") if not user.has_perms(cls.required_perms): raise humanize_exception(ugettext_noop( "You don't have the required permissions."), PermissionDenied()) if cls.superuser_required and not user.is_superuser: raise humanize_exception(ugettext_noop( "Superuser privileges are required."), PermissionDenied()) def check_auth(self, user): """Check if user is permitted to run this operation on this instance """ self.check_perms(user) def create_activity(self, parent, user, kwargs): raise NotImplementedError def on_abort(self, activity, error): """This method is called when the operation aborts (i.e. raises an exception). """ pass def get_activity_name(self, kwargs): try: return self.activity_name except AttributeError: try: return self.name._proxy____args[0] # ewww! except AttributeError: raise ImproperlyConfigured( "Set Operation.activity_name to an ugettext_nooped " "string or a create_readable call, or override " "get_activity_name to create a name dynamically") def on_commit(self, activity): """This method is called when the operation executes successfully. """ pass operation_registry_name = '_ops' class OperatedMixin(object): def __getattr__(self, name): # NOTE: __getattr__ is only called if the attribute doesn't already # exist in your __dict__ return self.get_operation_class(name)(self) @classmethod def get_operation_class(cls, name): ops = getattr(cls, operation_registry_name, {}) op = ops.get(name) if op: return op else: raise AttributeError("%r object has no attribute %r" % (cls.__name__, name)) def get_available_operations(self, user): """Yield Operations that match permissions of user and preconditions. """ for name in getattr(self, operation_registry_name, {}): op = getattr(self, name) try: op.check_auth(user) op.check_precond() except: pass # unavailable else: yield op def get_operation_from_activity_code(self, activity_code): """Get an instance of the Operation corresponding to the specified activity code. :returns: A bound instance of an operation, or None if no matching operation could be found. """ for op in getattr(self, operation_registry_name, {}).itervalues(): if has_suffix(activity_code, op.get_activity_code_suffix()): return op(self) else: return None def register_operation(op_cls, op_id=None, target_cls=None): """Register the specified operation with the target class. You can optionally specify an ID to be used for the registration; otherwise, the operation class' 'id' attribute will be used. """ if op_id is None: try: op_id = op_cls.id except AttributeError: raise NotImplementedError("Operations should specify an 'id' " "attribute designating the name the " "operation can be called by on its " "host. Alternatively, provide the name " "in the 'op_id' parameter to this call.") if target_cls is None: try: target_cls = op_cls.host_cls except AttributeError: raise NotImplementedError("Operations should specify a 'host_cls' " "attribute designating the host class " "the operation should be registered to. " "Alternatively, provide the host class " "in the 'target_cls' parameter to this " "call.") assert not hasattr(target_cls, op_id), ( "target class already has an attribute with this id") if not issubclass(target_cls, OperatedMixin): raise TypeError("%r is not a subclass of %r" % (target_cls.__name__, OperatedMixin.__name__)) if not hasattr(target_cls, operation_registry_name): setattr(target_cls, operation_registry_name, dict()) getattr(target_cls, operation_registry_name)[op_id] = op_cls return op_cls tests/ 0000775 0000000 0000000 00000000000 13126740172 0030657 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common __init__.py 0000664 0000000 0000000 00000000000 13126740172 0032756 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/tests celery_mock.py 0000664 0000000 0000000 00000002771 13126740172 0033534 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/tests # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from mock import patch class MockCeleryMixin(object): def _pre_setup(self): self.reloadtask_patcher = patch( 'firewall.tasks.local_tasks.reloadtask.apply_async', spec=True) self.reloadtask_patcher.start() self.kombu_patcher = patch('kombu.connection.Connection.ensure', side_effect=RuntimeError()) self.kombu_patcher.start() self.check_queue_patcher = patch('vm.tasks.vm_tasks.check_queue', return_value=True) self.check_queue_patcher.start() super(MockCeleryMixin, self)._pre_setup() def _post_teardown(self): self.reloadtask_patcher.stop() self.kombu_patcher.stop() super(MockCeleryMixin, self)._post_teardown() models.py 0000664 0000000 0000000 00000002020 13126740172 0032506 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/tests # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from ..models import method_cache class TestClass(object): id = None called = 0 def __init__(self, id): self.id = id @method_cache() def method(self, s): # print 'Called TestClass(%d).method(%s)' % (self.id, s) self.called += 1 return self.id + len(s) test_models.py 0000664 0000000 0000000 00000006773 13126740172 0033570 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/tests # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from collections import deque from django.test import TestCase from mock import MagicMock from .celery_mock import MockCeleryMixin from .models import TestClass from ..models import HumanSortField from ..models import activitycontextimpl class MethodCacheTestCase(MockCeleryMixin, TestCase): def test_cache(self): t1 = TestClass(1) t2 = TestClass(2) val1a = t1.method('a') val1b = t1.method('a') val2a = t2.method('a') val2b = t2.method('a') val2b = t2.method('a') self.assertEqual(val1a, val1b) self.assertEqual(val2a, val2b) self.assertNotEqual(val1a, val2a) t1.method('b') self.assertEqual(t1.called, 2) self.assertEqual(t2.called, 1) def test_invalidate(self): t1 = TestClass(1) val1a = t1.method('a') val1b = t1.method('a', invalidate_cache=True) t1.method('a') self.assertEqual(val1a, val1b) self.assertEqual(t1.called, 2) class TestHumanSortField(TestCase): def test_partition(self): values = {(lambda s: s.isdigit(), "1234abc56"): ("1234", "abc", "56"), (lambda s: s.isalpha(), "abc567"): ("abc", "567", ""), (lambda s: s == "a", "aaababaa"): ("aaa", "b", "abaa"), (lambda s: s == "a", u"aaababaa"): ("aaa", "b", "abaa"), } for (pred, val), result in values.iteritems(): a, b, c = HumanSortField._partition(deque(val), pred) assert isinstance(c, deque) c = ''.join(c) # print "%s, %s => %s" % (val, str(pred), str((a, b, c))) self.assertEquals((a, b, c), result) def test_get_normalized(self): values = {("1234abc56", 4): "1234abc0056", ("abc567", 2): "abc567", ("aaababaa", 8): "aaababaa", ("aa4ababaa", 2): "aa04ababaa", ("aa4aba24baa4", 4): "aa0004aba0024baa0004", } for (val, length), result in values.iteritems(): obj = MagicMock(spec=HumanSortField, maximum_number_length=length, _partition=HumanSortField._partition) test_result = HumanSortField.get_normalized_value(obj, val) self.assertEquals(test_result, result) class ActivityContextTestCase(TestCase): class MyException(Exception): pass def test_unicode(self): act = MagicMock() gen = activitycontextimpl(act) gen.next() with self.assertRaises(self.MyException): gen.throw(self.MyException(u'test\xe1')) def test_str(self): act = MagicMock() gen = activitycontextimpl(act) gen.next() with self.assertRaises(self.MyException): gen.throw(self.MyException('test\xbe')) test_operations.py 0000664 0000000 0000000 00000006627 13126740172 0034466 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common/tests # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from mock import MagicMock, patch from django.test import TestCase from ..operations import Operation class OperationTestCase(TestCase): def test_activity_created_before_async_job(self): class AbortEx(Exception): pass op = TestOp(MagicMock()) op.async_operation = MagicMock( apply_async=MagicMock(side_effect=AbortEx)) with patch.object(Operation, 'check_precond'): with patch.object(Operation, 'create_activity') as create_act: try: op.async(system=True) except AbortEx: self.assertTrue(create_act.called) def test_check_precond_called_before_create_activity(self): class AbortEx(Exception): pass op = TestOp(MagicMock()) with patch.object(Operation, 'create_activity', side_effect=AbortEx): with patch.object(Operation, 'check_precond') as chk_pre: try: op.call(system=True) except AbortEx: self.assertTrue(chk_pre.called) def test_auth_check_on_non_system_call(self): op = TestOp(MagicMock()) user = MagicMock() with patch.object(Operation, 'check_auth') as check_auth: with patch.object(Operation, 'check_precond'), \ patch.object(Operation, 'create_activity'), \ patch.object(Operation, '_exec_op'): op.call(user=user) check_auth.assert_called_with(user) def test_no_auth_check_on_system_call(self): op = TestOp(MagicMock()) with patch.object(Operation, 'check_auth', side_effect=AssertionError): with patch.object(Operation, 'check_precond'), \ patch.object(Operation, 'create_activity'), \ patch.object(Operation, '_exec_op'): op.call(system=True) def test_no_exception_for_more_arguments_when_operation_takes_kwargs(self): op = TestOp(MagicMock()) with patch.object(TestOp, 'create_activity'), \ patch.object(TestOp, '_exec_op'): op.call(system=True, foo=42) def test_exception_for_unexpected_arguments(self): op = TestOp(MagicMock()) with patch.object(TestOp, 'create_activity'), \ patch.object(TestOp, '_exec_op'): self.assertRaises(TypeError, op.call, system=True, bar=42) def test_exception_for_missing_arguments(self): op = TestOp(MagicMock()) with patch.object(TestOp, 'create_activity'): self.assertRaises(TypeError, op.call, system=True) class TestOp(Operation): id = 'test' def _operation(self, foo): pass views.py 0000664 0000000 0000000 00000003544 13126740172 0031232 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/common # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from sys import exc_info import logging from django.shortcuts import render_to_response from django.template import RequestContext from .models import HumanReadableException logger = logging.getLogger(__name__) def get_context(request, exception): ctx = {} if issubclass(exception.__class__, HumanReadableException): try: if request.user.is_superuser: ctx['error'] = exception.get_admin_text() else: ctx['error'] = exception.get_user_text() except: pass return ctx def handler500(request): cls, exception, traceback = exc_info() logger.exception("unhandled exception") ctx = get_context(request, exception) try: resp = render_to_response("500.html", ctx, RequestContext(request).flatten()) except: resp = render_to_response("500.html", ctx) resp.status_code = 500 return resp def handler403(request): cls, exception, traceback = exc_info() ctx = get_context(request, exception) resp = render_to_response("403.html", ctx) resp.status_code = 403 return resp dashboard/ 0000775 0000000 0000000 00000000000 13126740172 0030154 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle __init__.py 0000664 0000000 0000000 00000000000 13126740172 0032253 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard admin.py 0000664 0000000 0000000 00000002744 13126740172 0031625 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . # -*- coding: utf-8 -*- from django import contrib from django.contrib.auth.admin import UserAdmin, GroupAdmin from django.contrib.auth.models import User, Group from dashboard.models import Profile, GroupProfile, ConnectCommand, Message class ProfileInline(contrib.admin.TabularInline): model = Profile class CommandInline(contrib.admin.TabularInline): model = ConnectCommand class GroupProfileInline(contrib.admin.TabularInline): model = GroupProfile UserAdmin.inlines = (ProfileInline, CommandInline, ) GroupAdmin.inlines = (GroupProfileInline, ) contrib.admin.site.unregister(User) contrib.admin.site.register(User, UserAdmin) contrib.admin.site.unregister(Group) contrib.admin.site.register(Group, GroupAdmin) contrib.admin.site.register(Message) autocomplete_light_registry.py 0000664 0000000 0000000 00000007277 13126740172 0036363 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . import autocomplete_light from django.contrib.auth.models import User from django.utils.html import escape from django.utils.translation import ugettext as _ from .views import AclUpdateView from .models import Profile def highlight(field, q, none_wo_match=True): """ >>> highlight('Akkount Krokodil', 'kro', False) u'<b>Akkount Krokodil' """ if not field: return None try: match = field.lower().index(q.lower()) except ValueError: match = None if q and match is not None: match_end = match + len(q) return (escape(field[:match]) + '' + escape(field[match:match_end]) + '' + escape(field[match_end:])) elif none_wo_match: return None else: return escape(field) class AclUserGroupAutocomplete(autocomplete_light.AutocompleteGenericBase): search_fields = ( ('first_name', 'last_name', 'username', 'email', 'profile__org_id'), ('name', 'groupprofile__org_id'), ) choice_html_format = (u'%s%s') def choice_displayed_text(self, choice): q = unicode(self.request.GET.get('q', '')) name = highlight(unicode(choice), q, False) if isinstance(choice, User): extra_fields = [highlight(choice.get_full_name(), q, False), highlight(choice.email, q)] try: extra_fields.append(highlight(choice.profile.org_id, q)) except Profile.DoesNotExist: pass return '%s (%s)' % (name, ', '.join(f for f in extra_fields if f)) else: return _('%s (group)') % name def choice_html(self, choice): return self.choice_html_format % ( self.choice_value(choice), self.choice_label(choice), self.choice_displayed_text(choice)) def choices_for_request(self): user = self.request.user self.choices = (AclUpdateView.get_allowed_users(user), AclUpdateView.get_allowed_groups(user)) return super(AclUserGroupAutocomplete, self).choices_for_request() def autocomplete_html(self): html = [] for choice in self.choices_for_request(): html.append(self.choice_html(choice)) if not html: html = self.empty_html_format % _('no matches found').capitalize() return self.autocomplete_html_format % ''.join(html) class AclUserAutocomplete(AclUserGroupAutocomplete): def choices_for_request(self): user = self.request.user self.choices = (AclUpdateView.get_allowed_users(user), ) return super(AclUserGroupAutocomplete, self).choices_for_request() autocomplete_light.register(AclUserGroupAutocomplete) autocomplete_light.register(AclUserAutocomplete) compilers.py 0000664 0000000 0000000 00000001560 13126740172 0032525 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from pipeline.compilers.less import LessCompiler class DummyLessCompiler(LessCompiler): def compile_file(self, *args, **kwargs): pass context_processors.py 0000664 0000000 0000000 00000002436 13126740172 0034501 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from django.conf import settings from .models import Message def notifications(request): count = (request.user.notification_set.filter(status="new").count() if request.user.is_authenticated() else None) return { 'NEW_NOTIFICATIONS_COUNT': count } def extract_settings(request): return { 'COMPANY_NAME': getattr(settings, "COMPANY_NAME", None), 'ADMIN_ENABLED': getattr(settings, "ADMIN_ENABLED", False), } def broadcast_messages(request): return {'broadcast_messages': Message.timeframed.filter(enabled=True)} fixtures/ 0000775 0000000 0000000 00000000000 13126740172 0032025 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard node.json 0000664 0000000 0000000 00000002754 13126740172 0033655 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/fixtures [ { "pk": 1, "model": "firewall.vlan", "fields": { "comment": "", "ipv6_template": "2001:7:2:4031:%(b)d:%(c)d:%(d)d:0", "domain": 1, "dhcp_pool": "", "managed": true, "name": "pub", "vid": 3066, "created_at": "2014-02-19T17:00:17.358Z", "modified_at": "2014-02-19T17:00:17.358Z", "owner": null, "snat_ip": null, "snat_to": [], "network6": null, "network4": "10.7.0.93/16", "reverse_domain": "%(d)d.%(c)d.%(b)d.%(a)d.in-addr.arpa", "network_type": "public", "description": "" } }, { "pk": 1, "model": "firewall.host", "fields": { "comment": "", "vlan": 1, "reverse": "", "created_at": "2014-02-19T17:03:45.365Z", "hostname": "devenv", "modified_at": "2014-02-24T15:55:01.412Z", "location": "", "mac": "11:22:33:44:55:66", "shared_ip": false, "ipv4": "10.7.0.96", "groups": [], "ipv6": null, "owner": 1, "description": "" } }, { "pk": 1, "model": "firewall.domain", "fields": { "description": "", "created_at": "2014-02-19T17:00:08.819Z", "modified_at": "2014-02-19T17:00:08.819Z", "ttl": 600, "owner": 1, "name": "test.ik.bme.hu" } }, { "pk": 1, "model": "vm.node", "fields": { "name": "devenv", "created": "2014-02-19T17:03:45.322Z", "overcommit": 1.0, "enabled": true, "modified": "2014-02-19T21:11:34.671Z", "priority": 1, "traits": [], "host": 1 } } ] test-vm-fixture.json 0000664 0000000 0000000 00000014237 13126740172 0036012 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/fixtures [ { "pk": 1, "model": "sites.site", "fields": { "domain": "example.com", "name": "example.com" } }, { "pk": 1, "model": "vm.lease", "fields": { "suspend_interval_seconds": 18000, "name": "lab", "delete_interval_seconds": 180000 } }, { "pk": 1, "model": "storage.datastore", "fields": { "path": "/disks", "hostname": "wut", "name": "diszkek" } }, { "pk": 1, "model": "storage.disk", "fields": { "name": "diszk", "created": "2013-09-16T09:05:56.926Z", "modified": "2013-09-19T09:10:25.117Z", "filename": "disc.img", "destroyed": null, "base": null, "datastore": 1, "dev_num": "a", "type": "qcow2-norm", "size": 8589934592, "is_ready": true } }, { "pk": 1, "model": "auth.group", "fields": { "name": "csopi", "permissions": [] } }, { "pk": 2, "model": "auth.group", "fields": { "name": "akkorszia", "permissions": [] } }, { "pk": 3, "model": "auth.group", "fields": { "name": "akkountsoherek", "permissions": [] } }, { "pk": 4, "model": "auth.group", "fields": { "name": "helog", "permissions": [] } }, { "pk": -1, "model": "auth.user", "fields": { "username": "AnonymousUser", "first_name": "", "last_name": "", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2013-09-30T12:37:38.484Z", "groups": [], "user_permissions": [], "password": "", "email": "", "date_joined": "2013-09-30T12:37:38.484Z" } }, { "pk": 1, "model": "auth.user", "fields": { "username": "test", "first_name": "", "last_name": "", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2013-11-09T03:40:23.157Z", "groups": [], "user_permissions": [ 115 ], "password": "md5$qLN4mQMOrsUJ$f07129fd1a289a0afb4e09f7a6816a4f", "email": "test@example.org", "date_joined": "2013-09-04T15:29:49.914Z" } }, { "pk": 3, "model": "auth.user", "fields": { "username": "proba", "first_name": "", "last_name": "", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2013-10-14T06:59:48Z", "groups": [ 1 ], "user_permissions": [], "password": "", "email": "", "date_joined": "2013-10-14T06:59:48Z" } }, { "pk": 4, "model": "auth.user", "fields": { "username": "helo", "first_name": "", "last_name": "", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2013-11-09T01:11:41.534Z", "groups": [ 4 ], "user_permissions": [], "password": "", "email": "", "date_joined": "2013-11-09T01:11:41.534Z" } }, { "pk": 1, "model": "vm.instance", "fields": { "destroyed_at": null, "disks": [ 1 ], "boot_menu": false, "owner": 1, "time_of_delete": null, "max_ram_size": 200, "pw": "ads", "time_of_suspend": null, "ram_size": 200, "priority": 10, "template": null, "access_method": "nx", "lease": 1, "node": null, "description": "", "arch": "x86_64", "name": "vanneve", "created": "2013-09-16T09:05:59.991Z", "raw_data": "", "vnc_port": 1234, "num_cores": 2, "status": "RUNNING", "system": "system pls", "modified": "2013-10-14T07:27:38.192Z" } }, { "pk": 12, "model": "vm.instance", "fields": { "destroyed_at": null, "disks": [], "boot_menu": false, "owner": 1, "time_of_delete": null, "max_ram_size": 200, "pw": "ads", "time_of_suspend": null, "ram_size": 200, "priority": 10, "template": null, "access_method": "nx", "lease": 1, "node": null, "description": "", "arch": "x86_64", "name": "vanneve", "created": "2013-09-16T09:05:59.991Z", "raw_data": "", "vnc_port": 1235, "num_cores": 2, "modified": "2013-10-14T07:27:38.192Z" } }, { "pk": 1, "model": "firewall.domain", "fields": { "description": "", "created_at": "2013-09-12T14:53:04.035Z", "modified_at": "2013-10-02T14:01:00.318Z", "ttl": 600, "owner": 1, "name": "test domain" } }, { "pk": 2, "model": "firewall.vlan", "fields": { "comment": "", "domain": 1, "dhcp_pool": "", "name": "test vlan", "vid": 1, "created_at": "2013-09-12T14:54:24.044Z", "modified_at": "2013-10-21T11:19:44.544Z", "owner": null, "snat_ip": null, "snat_to": [], "network6": null, "network4": "192.168.1.0/24", "reverse_domain": "%(d)d.%(c)d.%(b2)d.%(a)d.in-addr.arpa", "network_type": "public", "description": "" } }, { "pk": 1, "model": "firewall.vlan", "fields": { "comment": "", "domain": 1, "dhcp_pool": "", "managed": true, "name": "pub", "vid": 1066, "created_at": "2014-01-23T16:51:58.125Z", "modified_at": "2014-01-23T16:51:58.125Z", "owner": null, "snat_ip": null, "snat_to": [], "network6": null, "network4": "152.66.254.61/30", "reverse_domain": "%(d)d.%(c)d.%(b)d.%(a)d.in-addr.arpa", "network_type": "public", "description": "" } }, { "pk": 1, "model": "vm.lease", "fields": { "suspend_interval_seconds": 36000, "name": "alap", "delete_interval_seconds": 360000 } }, { "pk": 2, "model": "vm.interfacetemplate", "fields": { "vlan": 1, "managed": true, "template": 1 } }, { "pk": 1, "model": "vm.instancetemplate", "fields": { "req_traits": [], "disks": [ 1 ], "name": "ubuntu", "parent": null, "created": "2014-01-23T18:03:52.319Z", "num_cores": 2, "description": "", "boot_menu": false, "ram_size": 1024, "modified": "2014-01-24T00:58:19.654Z", "system": "bubuntu", "priority": 10, "access_method": "ssh", "raw_data": "", "arch": "x86_64", "max_ram_size": 1024, "lease": 1, "owner": 1 } } ] forms.py 0000664 0000000 0000000 00000161427 13126740172 0031667 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from __future__ import absolute_import from datetime import timedelta from urlparse import urlparse import pyotp from django.forms import ModelForm from django.contrib.auth.forms import ( AuthenticationForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm, ) from django.contrib.auth.models import User, Group from django.core.validators import URLValidator from django.core.exceptions import PermissionDenied, ValidationError import autocomplete_light from crispy_forms.helper import FormHelper from crispy_forms.layout import ( Layout, Div, BaseInput, Field, HTML, Submit, TEMPLATE_PACK, Fieldset ) from crispy_forms.utils import render_field from crispy_forms.bootstrap import FormActions from django import forms from django.contrib.auth.forms import UserCreationForm as OrgUserCreationForm from django.forms.widgets import TextInput, HiddenInput from django.template import Context from django.template.loader import render_to_string from django.utils.html import escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from sizefield.widgets import FileSizeWidget from django.core.urlresolvers import reverse_lazy from django_sshkey.models import UserKey from firewall.models import Vlan, Host from vm.models import ( InstanceTemplate, Lease, InterfaceTemplate, Node, Trait, Instance ) from storage.models import DataStore, Disk from django.contrib.admin.widgets import FilteredSelectMultiple from django.contrib.auth.models import Permission from .models import Profile, GroupProfile, Message from circle.settings.base import LANGUAGES, MAX_NODE_RAM from django.utils.translation import string_concat from .validators import domain_validator from dashboard.models import ConnectCommand, create_profile LANGUAGES_WITH_CODE = ((l[0], string_concat(l[1], " (", l[0], ")")) for l in LANGUAGES) priority_choices = ( (10, _("idle")), (30, _("normal")), (80, _("server")), (100, _("realtime")), ) class NoFormTagMixin(object): @property def helper(self): helper = FormHelper(self) helper.form_tag = False return helper class OperationForm(NoFormTagMixin, forms.Form): pass class VmSaveForm(OperationForm): name = forms.CharField(max_length=100, label=_('Name'), help_text=_('Human readable name of template.')) def __init__(self, *args, **kwargs): default = kwargs.pop('default', None) clone = kwargs.pop('clone', False) super(VmSaveForm, self).__init__(*args, **kwargs) if default: self.fields['name'].initial = default if clone: self.fields["clone"] = forms.BooleanField( required=False, label=_("Clone template permissions"), help_text=_("Clone the access list of parent template. Useful " "for updating a template.")) class VmCustomizeForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={ 'class': "form-control", 'style': "max-width: 350px", 'required': "", })) cpu_count = forms.IntegerField(widget=forms.NumberInput(attrs={ 'class': "form-control input-tags cpu-count-input", 'min': 1, 'max': 10, 'required': "", }), min_value=1, max_value=10, ) ram_size = forms.IntegerField(widget=forms.TextInput(attrs={ 'class': "form-control input-tags ram-input", 'min': 128, 'pattern': "\d+", 'max': MAX_NODE_RAM, 'step': 128, 'required': "", }), min_value=128, max_value=MAX_NODE_RAM, ) cpu_priority = forms.ChoiceField( priority_choices, widget=forms.Select(attrs={ 'class': "form-control input-tags cpu-priority-input", }) ) amount = forms.IntegerField(widget=forms.NumberInput(attrs={ 'class': "form-control", 'min': "1", 'style': "max-width: 60px", 'required': "", }), initial=1, min_value=1) disks = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.SelectMultiple(attrs={ 'class': "form-control", 'id': "vm-create-disk-add-form", }) ) networks = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.SelectMultiple(attrs={ 'class': "form-control", 'id': "vm-create-network-add-vlan", }) ) template = forms.CharField(widget=forms.HiddenInput()) customized = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) self.template = kwargs.pop("template", None) super(VmCustomizeForm, self).__init__(*args, **kwargs) if self.user.has_perm("vm.set_resources"): self.allowed_fields = tuple(self.fields.keys()) # set displayed disk and network list self.fields['disks'].queryset = self.template.disks.all() self.fields['networks'].queryset = Vlan.get_objects_with_level( 'user', self.user) # set initial for disk and network list self.initial['disks'] = self.template.disks.all() self.initial['networks'] = InterfaceTemplate.objects.filter( template=self.template).values_list("vlan", flat=True) # set initial for resources self.initial['cpu_priority'] = self.template.priority self.initial['cpu_count'] = self.template.num_cores self.initial['ram_size'] = self.template.ram_size else: self.allowed_fields = ("name", "template", "customized", ) # initial name and template pk self.initial['name'] = self.template.name self.initial['template'] = self.template.pk self.initial['customized'] = True def _clean_fields(self): for name, field in self.fields.items(): if name in self.allowed_fields: value = field.widget.value_from_datadict( self.data, self.files, self.add_prefix(name)) try: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self._errors[name] = self.error_class(e.messages) if name in self.cleaned_data: del self.cleaned_data[name] class GroupCreateForm(NoFormTagMixin, forms.ModelForm): description = forms.CharField(label=_("Description"), required=False, widget=forms.Textarea(attrs={'rows': 3})) def __init__(self, *args, **kwargs): new_groups = kwargs.pop('new_groups', None) super(GroupCreateForm, self).__init__(*args, **kwargs) choices = [('', '--')] if new_groups: choices += [(g, g) for g in new_groups if len(g) <= 64] self.fields['org_id'] = forms.ChoiceField( # TRANSLATORS: directory like in LDAP choices=choices, required=False, label=_('Directory identifier')) if new_groups: self.fields['org_id'].help_text = _( "If you select an item here, the members of this directory " "group will be automatically added to the group at the time " "they log in. Please note that other users (those with " "permissions like yours) may also automatically become a " "group co-owner).") else: self.fields['org_id'].widget = HiddenInput() def save(self, commit=True): if not commit: raise AttributeError('Committing is mandatory.') group = super(GroupCreateForm, self).save() profile = group.profile # multiple blanks were not be unique unlike NULLs are profile.org_id = self.cleaned_data['org_id'] or None profile.description = self.cleaned_data['description'] profile.save() return group @property def helper(self): helper = super(GroupCreateForm, self).helper helper.add_input(Submit("submit", _("Create"))) return helper class Meta: model = Group fields = ('name', ) class GroupProfileUpdateForm(NoFormTagMixin, forms.ModelForm): def __init__(self, *args, **kwargs): new_groups = kwargs.pop('new_groups', None) superuser = kwargs.pop('superuser', False) super(GroupProfileUpdateForm, self).__init__(*args, **kwargs) if not superuser: choices = [('', '--')] if new_groups: choices += [(g, g) for g in new_groups if len(g) <= 64] self.fields['org_id'] = forms.ChoiceField( choices=choices, required=False, label=_('Directory identifier')) if not new_groups: self.fields['org_id'].widget = HiddenInput() self.fields['description'].widget = forms.Textarea(attrs={'rows': 3}) @property def helper(self): helper = super(GroupProfileUpdateForm, self).helper helper.add_input(Submit("submit", _("Save"))) return helper def save(self, commit=True): profile = super(GroupProfileUpdateForm, self).save(commit=False) profile.org_id = self.cleaned_data['org_id'] or None if commit: profile.save() return profile class Meta: model = GroupProfile fields = ('description', 'org_id') class HostForm(NoFormTagMixin, forms.ModelForm): def setowner(self, user): self.instance.owner = user @property def helper(self): helper = super(HostForm, self).helper helper.form_show_labels = False helper.layout = Layout( Div( Div( # host Div( AnyTag( 'h3', HTML(_("Host")), ), css_class="col-sm-3", ), css_class="row", ), Div( # host data Div( # hostname HTML('' 'Name' ''), css_class="col-sm-3", ), Div( # hostname 'hostname', css_class="col-sm-9", ), Div( # mac HTML('' 'MAC' ''), css_class="col-sm-3", ), Div( 'mac', css_class="col-sm-9", ), Div( # ip HTML('' 'IP' ''), css_class="col-sm-3", ), Div( 'ipv4', css_class="col-sm-9", ), Div( # vlan HTML('' 'VLAN' ''), css_class="col-sm-3", ), Div( 'vlan', css_class="col-sm-9", ), css_class="row", ), ), ) return helper class Meta: model = Host fields = ['hostname', 'vlan', 'mac', 'ipv4', ] class NodeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(NodeForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = False self.helper.layout = Layout( Div( Div( Div( Div( AnyTag( 'h3', HTML(_("Node")), ), css_class="col-sm-3", ), css_class="row", ), Div( Div( # nodename HTML('' 'Name' ''), css_class="col-sm-3", ), Div( 'name', css_class="col-sm-9", ), css_class="row", ), Div( Div( # priority HTML('' 'Priority' ''), css_class="col-sm-3", ), Div( 'priority', css_class="col-sm-9", ), css_class="row", ), Div( Div( # enabled HTML('' 'Enabled' ''), css_class="col-sm-3", ), Div( 'enabled', css_class="col-sm-9", ), css_class="row", ), Div( # nested host HTML("""{% load crispy_forms_tags %} {% crispy hostform %} """) ), Div( Div( AnyTag( # tip: don't try to use Button class "button", AnyTag( "i", css_class="fa fa-play" ), HTML("Start"), css_id="node-create-submit", css_class="btn btn-success", ), css_class="col-sm-12 text-right", ), css_class="row", ), css_class="col-sm-11", ), css_class="row", ), ) class Meta: model = Node fields = ['name', 'priority', 'enabled', ] class TemplateForm(forms.ModelForm): networks = forms.ModelMultipleChoiceField( queryset=None, required=False, label=_("Networks")) num_cores = forms.IntegerField(widget=forms.NumberInput(attrs={ 'class': "form-control input-tags cpu-count-input", 'min': 1, 'max': 10, 'required': "", }), min_value=1, max_value=10, ) ram_size = forms.IntegerField(widget=forms.NumberInput(attrs={ 'class': "form-control input-tags ram-input", 'min': 128, 'max': MAX_NODE_RAM, 'step': 128, 'required': "", }), min_value=128, max_value=MAX_NODE_RAM, ) priority = forms.ChoiceField(priority_choices, widget=forms.Select(attrs={ 'class': "form-control input-tags cpu-priority-input", })) def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) super(TemplateForm, self).__init__(*args, **kwargs) self.fields['networks'].queryset = Vlan.get_objects_with_level( 'user', self.user) data = self.data.copy() data['owner'] = self.user.pk self.data = data if self.instance.pk: n = self.instance.interface_set.values_list("vlan", flat=True) self.initial['networks'] = n if self.instance.pk and not self.instance.has_level(self.user, 'owner'): self.allowed_fields = () else: self.allowed_fields = ( 'name', 'access_method', 'description', 'system', 'tags', 'arch', 'lease', 'has_agent') if (self.user.has_perm('vm.change_template_resources') or not self.instance.pk): self.allowed_fields += tuple(set(self.fields.keys()) - set(['raw_data'])) if self.user.is_superuser: self.allowed_fields += ('raw_data', ) for name, field in self.fields.items(): if name not in self.allowed_fields: field.widget.attrs['disabled'] = 'disabled' if not self.instance.pk and len(self.errors) < 1: self.initial['num_cores'] = 1 self.initial['priority'] = 10 self.initial['ram_size'] = 512 self.initial['max_ram_size'] = 512 lease_queryset = ( Lease.get_objects_with_level("operator", self.user).distinct() | Lease.objects.filter(pk=self.instance.lease_id).distinct()) self.fields["lease"].queryset = lease_queryset self.fields['raw_data'].validators.append(domain_validator) def clean_owner(self): if self.instance.pk is not None: return User.objects.get(pk=self.instance.owner.pk) return self.user def clean_max_ram_size(self): return self.cleaned_data.get("ram_size", 0) def _clean_fields(self): try: old = InstanceTemplate.objects.get(pk=self.instance.pk) except InstanceTemplate.DoesNotExist: old = None for name, field in self.fields.items(): if name in self.allowed_fields: value = field.widget.value_from_datadict( self.data, self.files, self.add_prefix(name)) try: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self._errors[name] = self.error_class(e.messages) if name in self.cleaned_data: del self.cleaned_data[name] elif old: if name == 'networks': self.cleaned_data[name] = [ i.vlan for i in self.instance.interface_set.all()] else: self.cleaned_data[name] = getattr(old, name) if "req_traits" not in self.allowed_fields: self.cleaned_data['req_traits'] = self.instance.req_traits.all() def save(self, commit=True): data = self.cleaned_data self.instance.max_ram_size = data.get('ram_size') instance = super(TemplateForm, self).save(commit=True) # create and/or delete InterfaceTemplates networks = InterfaceTemplate.objects.filter( template=self.instance).values_list("vlan", flat=True) for m in data['networks']: if not m.has_level(self.user, "user"): raise PermissionDenied() if m.pk not in networks: InterfaceTemplate(vlan=m, managed=m.managed, template=self.instance).save() InterfaceTemplate.objects.filter( template=self.instance).exclude( vlan__in=data['networks']).delete() return instance @property def helper(self): submit_kwargs = {} if self.instance.pk and not self.instance.has_level(self.user, 'owner'): submit_kwargs['disabled'] = None helper = FormHelper() return helper class Meta: model = InstanceTemplate exclude = ('state', 'disks', ) widgets = { 'system': forms.TextInput, 'max_ram_size': forms.HiddenInput, 'parent': forms.Select(attrs={'disabled': ""}), } class LeaseForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(LeaseForm, self).__init__(*args, **kwargs) self.generate_fields() # e2ae8b048e7198428f696375b8bdcd89e90002d1/django/utils/timesince.py#L10 def get_intervals(self, delta_seconds): chunks = ( (60 * 60 * 24 * 30, "months"), (60 * 60 * 24 * 7, "weeks"), (60 * 60 * 24, "days"), (60 * 60, "hours"), ) for i, (seconds, name) in enumerate(chunks): count = delta_seconds // seconds if count != 0: break re = {'%s' % name: count} if i + 1 < len(chunks) and i > 0: seconds2, name2 = chunks[i + 1] count2 = (delta_seconds - (seconds * count)) // seconds2 if count2 != 0: re['%s' % name2] = count2 return re def generate_fields(self): intervals = ["hours", "days", "weeks", "months"] methods = ["suspend", "delete"] # feels redundant but these lines are so long s = (self.instance.suspend_interval.total_seconds() if self.instance.pk else 0) d = (self.instance.delete_interval.total_seconds() if self.instance.pk else 0) seconds = { 'suspend': s, 'delete': d } initial = { 'suspend': self.get_intervals(int(seconds['suspend'])), 'delete': self.get_intervals(int(seconds['delete'])) } for m in methods: for idx, i in enumerate(intervals): self.fields["%s_%s" % (m, i)] = forms.IntegerField( min_value=0, widget=NumberInput, initial=initial[m].get(i, 0)) def save(self, commit=True): data = self.cleaned_data suspend_seconds = timedelta( hours=data['suspend_hours'], days=(data['suspend_days'] + data['suspend_months'] % 12 * 30 + data['suspend_months'] / 12 * 365), weeks=data['suspend_weeks'], ) delete_seconds = timedelta( hours=data['delete_hours'], days=(data['delete_days'] + data['delete_months'] % 12 * 30 + data['delete_months'] / 12 * 365), weeks=data['delete_weeks'], ) self.instance.delete_interval = delete_seconds self.instance.suspend_interval = suspend_seconds instance = super(LeaseForm, self).save(commit=False) if commit: instance.save() return instance @property def helper(self): helper = FormHelper() helper.layout = Layout( Field('name'), Field("suspend_interval_seconds", type="hidden", value="0"), Field("delete_interval_seconds", type="hidden", value="0"), HTML(string_concat("", _("Suspend in"), "")), Div( NumberField("suspend_hours", css_class="form-control"), Div( HTML(_("hours")), css_class="input-group-addon", ), NumberField("suspend_days", css_class="form-control"), Div( HTML(_("days")), css_class="input-group-addon", ), NumberField("suspend_weeks", css_class="form-control"), Div( HTML(_("weeks")), css_class="input-group-addon", ), NumberField("suspend_months", css_class="form-control"), Div( HTML(_("months")), css_class="input-group-addon", ), css_class="input-group interval-input", ), HTML(string_concat("", _("Delete in"), "")), Div( NumberField("delete_hours", css_class="form-control"), Div( HTML(_("hours")), css_class="input-group-addon", ), NumberField("delete_days", css_class="form-control"), Div( HTML(_("days")), css_class="input-group-addon", ), NumberField("delete_weeks", css_class="form-control"), Div( HTML(_("weeks")), css_class="input-group-addon", ), NumberField("delete_months", css_class="form-control"), Div( HTML(_("months")), css_class="input-group-addon", ), css_class="input-group interval-input", ) ) helper.add_input(Submit("submit", _("Save changes"))) return helper class Meta: model = Lease exclude = () class VmRenewForm(OperationForm): force = forms.BooleanField(required=False, label=_( "Set expiration times even if they are shorter than " "the current value.")) save = forms.BooleanField(required=False, label=_( "Save selected lease.")) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') default = kwargs.pop('default') super(VmRenewForm, self).__init__(*args, **kwargs) self.fields['lease'] = forms.ModelChoiceField( queryset=choices, initial=default, required=False, empty_label=None, label=_('Length')) if len(choices) < 2: self.fields['lease'].widget = HiddenInput() self.fields['save'].widget = HiddenInput() class VmMigrateForm(forms.Form): live_migration = forms.BooleanField( required=False, initial=True, label=_("Live migration"), help_text=_( "Live migration is a way of moving virtual machines between " "hosts with a service interruption of at most some seconds. " "Please note that it can take very long and cause " "much network traffic in case of busy machines.")) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') default = kwargs.pop('default') super(VmMigrateForm, self).__init__(*args, **kwargs) self.fields['to_node'] = forms.ModelChoiceField( queryset=choices, initial=default, required=False, widget=forms.RadioSelect(), label=_("Node")) class VmStateChangeForm(OperationForm): interrupt = forms.BooleanField(required=False, label=_( "Forcibly interrupt all running activities."), help_text=_("Set all activities to finished state, " "but don't interrupt any tasks.")) new_state = forms.ChoiceField(Instance.STATUS, label=_( "New status")) reset_node = forms.BooleanField(required=False, label=_("Reset node")) def __init__(self, *args, **kwargs): show_interrupt = kwargs.pop('show_interrupt') status = kwargs.pop('status') super(VmStateChangeForm, self).__init__(*args, **kwargs) if not show_interrupt: self.fields['interrupt'].widget = HiddenInput() self.fields['new_state'].initial = status class RedeployForm(OperationForm): with_emergency_change_state = forms.BooleanField( required=False, initial=True, label=_("use emergency state change")) class VmCreateDiskForm(OperationForm): name = forms.CharField(max_length=100, label=_("Name")) size = forms.CharField( widget=FileSizeWidget, initial=(10 << 30), label=_('Size'), help_text=_('Size of disk to create in bytes or with units ' 'like MB or GB.')) def __init__(self, *args, **kwargs): default = kwargs.pop('default', None) super(VmCreateDiskForm, self).__init__(*args, **kwargs) if default: self.fields['name'].initial = default def clean_size(self): size_in_bytes = self.cleaned_data.get("size") if not size_in_bytes.isdigit() and len(size_in_bytes) > 0: raise forms.ValidationError(_("Invalid format, you can use " " GB or MB!")) return size_in_bytes class VmDiskResizeForm(OperationForm): size = forms.CharField( widget=FileSizeWidget, initial=(10 << 30), label=_('Size'), help_text=_('Size to resize the disk in bytes or with units ' 'like MB or GB.')) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') self.disk = kwargs.pop('default') super(VmDiskResizeForm, self).__init__(*args, **kwargs) self.fields['disk'] = forms.ModelChoiceField( queryset=choices, initial=self.disk, required=True, empty_label=None, label=_('Disk')) if self.disk: self.fields['disk'].widget = HiddenInput() self.fields['size'].initial += self.disk.size def clean(self): cleaned_data = super(VmDiskResizeForm, self).clean() size_in_bytes = self.cleaned_data.get("size") disk = self.cleaned_data.get('disk') if not size_in_bytes.isdigit() and len(size_in_bytes) > 0: raise forms.ValidationError(_("Invalid format, you can use " " GB or MB!")) if int(size_in_bytes) < int(disk.size): raise forms.ValidationError(_("Disk size must be greater than the " "actual size.")) return cleaned_data @property def helper(self): helper = super(VmDiskResizeForm, self).helper if self.disk: helper.layout = Layout( HTML(_("Disk: %s") % escape(self.disk)), Field('disk'), Field('size')) return helper class VmDiskRemoveForm(OperationForm): def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') self.disk = kwargs.pop('default') super(VmDiskRemoveForm, self).__init__(*args, **kwargs) self.fields['disk'] = forms.ModelChoiceField( queryset=choices, initial=self.disk, required=True, empty_label=None, label=_('Disk')) if self.disk: self.fields['disk'].widget = HiddenInput() @property def helper(self): helper = super(VmDiskRemoveForm, self).helper if self.disk: helper.layout = Layout( AnyTag( "div", HTML(_("Disk: %s") % escape(self.disk)), css_class="form-group", ), Field("disk"), ) return helper class VmDownloadDiskForm(OperationForm): name = forms.CharField(max_length=100, label=_("Name"), required=False) url = forms.CharField(label=_('URL'), validators=[URLValidator(), ]) def clean(self): cleaned_data = super(VmDownloadDiskForm, self).clean() if not cleaned_data['name']: if cleaned_data.get('url'): cleaned_data['name'] = urlparse( cleaned_data['url']).path.split('/')[-1] if not cleaned_data['name']: raise forms.ValidationError( _("Could not find filename in URL, " "please specify a name explicitly.")) return cleaned_data class VmRemoveInterfaceForm(OperationForm): def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') self.interface = kwargs.pop('default') super(VmRemoveInterfaceForm, self).__init__(*args, **kwargs) self.fields['interface'] = forms.ModelChoiceField( queryset=choices, initial=self.interface, required=True, empty_label=None, label=_('Interface')) if self.interface: self.fields['interface'].widget = HiddenInput() @property def helper(self): helper = super(VmRemoveInterfaceForm, self).helper if self.interface: helper.layout = Layout( AnyTag( "div", HTML(format_html( _("Vlan: {0}"), self.interface.vlan)), css_class="form-group", ), Field("interface"), ) return helper class VmAddInterfaceForm(OperationForm): def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') super(VmAddInterfaceForm, self).__init__(*args, **kwargs) field = forms.ModelChoiceField( queryset=choices, required=True, label=_('Vlan')) if not choices: field.widget.attrs['disabled'] = 'disabled' field.empty_label = _('No more networks.') self.fields['vlan'] = field class DeployChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): self.instance = kwargs.pop("instance") super(DeployChoiceField, self).__init__(*args, **kwargs) def label_from_instance(self, obj): traits = set(obj.traits.all()) req_traits = set(self.instance.req_traits.all()) # if the subset is empty the node satisfies the required traits subset = req_traits - traits label = "%s %s" % ( "" if subset else "", escape(obj.name), ) if subset: missing_traits = ", ".join(map(lambda x: escape(x.name), subset)) label += _(" (missing_traits: %s)") % missing_traits return mark_safe(label) class VmDeployForm(OperationForm): def __init__(self, *args, **kwargs): choices = kwargs.pop('choices', None) instance = kwargs.pop('instance', None) super(VmDeployForm, self).__init__(*args, **kwargs) if choices is not None: self.fields['node'] = DeployChoiceField( queryset=choices, required=False, label=_('Node'), help_text=_( "Deploy virtual machine to this node " "(blank allows scheduling automatically)."), widget=forms.Select(attrs={ 'class': "font-awesome-font", }), instance=instance ) class VmPortRemoveForm(OperationForm): def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') self.rule = kwargs.pop('default') super(VmPortRemoveForm, self).__init__(*args, **kwargs) self.fields['rule'] = forms.ModelChoiceField( queryset=choices, initial=self.rule, required=True, empty_label=None, label=_('Port')) if self.rule: self.fields['rule'].widget = HiddenInput() class VmPortAddForm(OperationForm): port = forms.IntegerField(required=True, label=_('Port'), min_value=1, max_value=65535) proto = forms.ChoiceField((('tcp', 'tcp'), ('udp', 'udp')), required=True, label=_('Protocol')) def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') self.host = kwargs.pop('default') super(VmPortAddForm, self).__init__(*args, **kwargs) self.fields['host'] = forms.ModelChoiceField( queryset=choices, initial=self.host, required=True, empty_label=None, label=_('Host')) if self.host: self.fields['host'].widget = HiddenInput() @property def helper(self): helper = super(VmPortAddForm, self).helper if self.host: helper.layout = Layout( AnyTag( "div", HTML(format_html( _("Host: {0}"), self.host)), css_class="form-group", ), Field("host"), Field("proto"), Field("port"), ) return helper class CircleAuthenticationForm(AuthenticationForm): # fields: username, password @property def helper(self): helper = FormHelper() helper.form_show_labels = False helper.layout = Layout( AnyTag( "div", AnyTag( "span", AnyTag( "i", css_class="fa fa-user", ), css_class="input-group-addon", ), Field("username", placeholder=_("Username"), css_class="form-control"), css_class="input-group", ), AnyTag( "div", AnyTag( "span", AnyTag( "i", css_class="fa fa-lock", ), css_class="input-group-addon", ), Field("password", placeholder=_("Password"), css_class="form-control"), css_class="input-group", ), ) helper.add_input(Submit("submit", _("Sign in"), css_class="btn btn-success")) return helper class CirclePasswordResetForm(PasswordResetForm): # fields: email @property def helper(self): helper = FormHelper() helper.form_show_labels = False helper.layout = Layout( AnyTag( "div", AnyTag( "span", AnyTag( "i", css_class="fa fa-envelope", ), css_class="input-group-addon", ), Field("email", placeholder=_("Email address"), css_class="form-control"), Div( AnyTag( "button", HTML(_("Reset password")), css_class="btn btn-success", ), css_class="input-group-btn", ), css_class="input-group", ), ) return helper class CircleSetPasswordForm(SetPasswordForm): @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Change password"), css_class="btn btn-success change-password", css_id="submit-password-button")) return helper class LinkButton(BaseInput): """ Used to create a link button descriptor for the {% crispy %} template tag:: back = LinkButton('back', 'Back', reverse_lazy('index')) .. note:: The first argument is also slugified and turned into the id for the submit button. """ template = "bootstrap/layout/linkbutton.html" field_classes = 'btn btn-default' def __init__(self, name, text, url, *args, **kwargs): self.href = url super(LinkButton, self).__init__(name, text, *args, **kwargs) class NumberInput(TextInput): input_type = "number" class NumberField(Field): template = "crispy_forms/numberfield.html" def __init__(self, *args, **kwargs): kwargs['min'] = 0 super(NumberField, self).__init__(*args, **kwargs) class AnyTag(Div): template = "crispy_forms/anytag.html" def __init__(self, tag, *fields, **kwargs): self.tag = tag super(AnyTag, self).__init__(*fields, **kwargs) def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): fields = '' for field in self.fields: fields += render_field(field, form, form_style, context, template_pack=template_pack) return render_to_string(self.template, Context({'tag': self, 'fields': fields})) class WorkingBaseInput(BaseInput): def __init__(self, name, value, input_type="text", **kwargs): self.input_type = input_type self.field_classes = "" # we need this for some reason super(WorkingBaseInput, self).__init__(name, value, **kwargs) class TraitForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TraitForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = False self.helper.layout = Layout( Div( Field('name', id="node-details-traits-input", css_class="input-sm input-traits"), Div( Submit("submit", _("Add trait"), css_class="btn btn-primary btn-sm input-traits"), css_class="input-group-btn", ), css_class="input-group", id="node-details-traits-form", ), ) class Meta: model = Trait fields = ['name'] class MyProfileForm(forms.ModelForm): preferred_language = forms.ChoiceField( LANGUAGES_WITH_CODE, label=_("Preferred language"), ) class Meta: fields = ('preferred_language', 'email_notifications', 'desktop_notifications', 'use_gravatar', ) model = Profile @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Save"))) return helper def save(self, *args, **kwargs): value = super(MyProfileForm, self).save(*args, **kwargs) return value class UnsubscribeForm(forms.ModelForm): class Meta: fields = ('email_notifications', ) model = Profile @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Save"))) return helper class CirclePasswordChangeForm(PasswordChangeForm): @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Change password"), css_class="btn btn-primary", css_id="submit-password-button")) return helper class UserCreationForm(OrgUserCreationForm): def __init__(self, *args, **kwargs): choices = kwargs.pop('choices') group = kwargs.pop('default') super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['groups'] = forms.ModelMultipleChoiceField( queryset=choices, initial=[group], required=False, label=_('Groups')) class Meta: model = User fields = ("username", 'email', 'first_name', 'last_name', 'groups') @property def helper(self): helper = FormHelper() helper.layout = Layout('username', 'password1', 'password2', 'email', 'first_name', 'last_name') helper.add_input(Submit("submit", _("Save"))) return helper def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() create_profile(user) user.groups.add(*self.cleaned_data["groups"]) return user class UserEditForm(forms.ModelForm): instance_limit = forms.IntegerField( label=_('Instance limit'), min_value=0, widget=NumberInput) two_factor_secret = forms.CharField( label=_('Two-factor authentication secret'), help_text=_("Remove the secret key to disable two-factor " "authentication for this user."), required=False) def __init__(self, *args, **kwargs): super(UserEditForm, self).__init__(*args, **kwargs) self.fields["instance_limit"].initial = ( self.instance.profile.instance_limit) self.fields["two_factor_secret"].initial = ( self.instance.profile.two_factor_secret) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'instance_limit', 'is_active', "two_factor_secret", ) def save(self, commit=True): user = super(UserEditForm, self).save() user.profile.instance_limit = ( self.cleaned_data['instance_limit'] or None) user.profile.two_factor_secret = ( self.cleaned_data['two_factor_secret'] or None) user.profile.save() return user @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Save"))) return helper class AclUserOrGroupAddForm(forms.Form): name = forms.CharField(widget=autocomplete_light.TextWidget( 'AclUserGroupAutocomplete', attrs={'class': 'form-control', 'placeholder': _("Name of group or user")})) class TransferOwnershipForm(forms.Form): name = forms.CharField( widget=autocomplete_light.TextWidget( 'AclUserAutocomplete', attrs={'class': 'form-control', 'placeholder': _("Name of user")}), label=_("E-mail address or identifier of user")) class AddGroupMemberForm(forms.Form): new_member = forms.CharField( widget=autocomplete_light.TextWidget( 'AclUserAutocomplete', attrs={'class': 'form-control', 'placeholder': _("Name of user")}), label=_("E-mail address or identifier of user")) class UserKeyForm(forms.ModelForm): name = forms.CharField(required=True, label=_('Name')) key = forms.CharField( label=_('Key'), required=True, help_text=_('For example: ssh-rsa AAAAB3NzaC1yc2ED...'), widget=forms.Textarea(attrs={'rows': 5})) class Meta: fields = ('name', 'key') model = UserKey @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Save"))) return helper def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) super(UserKeyForm, self).__init__(*args, **kwargs) def clean(self): if self.user: self.instance.user = self.user return super(UserKeyForm, self).clean() class ConnectCommandForm(forms.ModelForm): class Meta: fields = ('name', 'access_method', 'template') model = ConnectCommand def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super(ConnectCommandForm, self).__init__(*args, **kwargs) def clean(self): if self.user: self.instance.user = self.user return super(ConnectCommandForm, self).clean() class TraitsForm(forms.ModelForm): class Meta: model = Instance fields = ('req_traits', ) @property def helper(self): helper = FormHelper() helper.form_show_labels = False helper.form_action = reverse_lazy("dashboard.views.vm-traits", kwargs={'pk': self.instance.pk}) helper.add_input(Submit("submit", _("Save"), css_class="btn btn-success", )) return helper class RawDataForm(forms.ModelForm): raw_data = forms.CharField(validators=[domain_validator], widget=forms.Textarea(attrs={'rows': 5}), required=False) class Meta: model = Instance fields = ('raw_data', ) @property def helper(self): helper = FormHelper() helper.form_show_labels = False helper.form_action = reverse_lazy("dashboard.views.vm-raw-data", kwargs={'pk': self.instance.pk}) helper.add_input(Submit("submit", _("Save"), css_class="btn btn-success", css_id="submit-password-button")) return helper class GroupPermissionForm(forms.ModelForm): permissions = forms.ModelMultipleChoiceField( queryset=None, widget=FilteredSelectMultiple(_("permissions"), is_stacked=False) ) def get_filtered_permissions(self): """ Collected with this + djcelery source def get_model_classes_in_module(module): import sys import inspect from django.db.models import Model classes = [] for name, obj in inspect.getmembers(sys.modules[module]): if inspect.isclass(obj) and issubclass(obj, Model): classes.append(name.lower()) return classes """ excluded_objs = [ "tag", "taggeditem", "level", "objectlevel", "permission", "contenttype", "migrationhistory", "site", "session", "intervalschedule", "crontabschedule", "periodictask", "periodictasks", "workerstate", "taskstate", "taskmeta", "tasksetmeta", "logentry", "baseresourceconfigmodel", "instance", "instanceactivity", "instancetemplate", "interface", "interfacetemplate", "lease", "namedbaseresourceconfig", "node", "nodeactivity", "trait", "virtualmachinedescmodel", "aclbase", "connectcommand", "favourite", "futuremember", "groupprofile", "model", "notification", "profile", "timestampedmodel", "userkey", "datastore", "disk", "model", "timestampedmodel", "aclbase", "blacklistitem", "domain", "ethernetdevice", "firewall", "host", "record", "rule", "switchport", "vlan", "vlangroup", "sender", ] exclude_add = ["add_%s" % l for l in excluded_objs] exclude_change = ["change_%s" % l for l in excluded_objs] exclude_delete = ["delete_%s" % l for l in excluded_objs + ["user"]] return Permission.objects.exclude(codename__in=exclude_add).exclude( codename__in=exclude_change).exclude(codename__in=exclude_delete) def __init__(self, *args, **kwargs): super(GroupPermissionForm, self).__init__(*args, **kwargs) self.fields['permissions'].queryset = self.get_filtered_permissions() class Meta: model = Group fields = ('permissions', ) @property def helper(self): helper = FormHelper() helper.form_show_labels = False helper.form_action = reverse_lazy( "dashboard.views.group-permissions", kwargs={'group_pk': self.instance.pk}) helper.add_input(Submit("submit", _("Save"), css_class="btn btn-success", )) return helper class VmResourcesForm(forms.ModelForm): num_cores = forms.IntegerField(widget=forms.NumberInput(attrs={ 'class': "form-control input-tags cpu-count-input", 'min': 1, 'max': 10, 'required': "", }), min_value=1, max_value=10, ) ram_size = forms.IntegerField(widget=forms.NumberInput(attrs={ 'class': "form-control input-tags ram-input", 'min': 128, 'max': MAX_NODE_RAM, 'step': 128, 'required': "", }), min_value=128, max_value=MAX_NODE_RAM, ) priority = forms.ChoiceField(priority_choices, widget=forms.Select(attrs={ 'class': "form-control input-tags cpu-priority-input", })) def __init__(self, *args, **kwargs): self.can_edit = kwargs.pop("can_edit", None) super(VmResourcesForm, self).__init__(*args, **kwargs) if not self.can_edit: for name, field in self.fields.items(): field.widget.attrs['disabled'] = "disabled" class Meta: model = Instance fields = ('num_cores', 'priority', 'ram_size', ) vm_search_choices = ( ("owned", _("owned")), ("shared", _("shared")), ("shared_with_me", _("shared with me")), ("all", _("all")), ) class VmListSearchForm(forms.Form): s = forms.CharField(widget=forms.TextInput(attrs={ 'class': "form-control input-tags", 'placeholder': _("Search...") })) stype = forms.ChoiceField(vm_search_choices, widget=forms.Select(attrs={ 'class': "btn btn-default form-control input-tags", 'style': "min-width: 80px;", })) include_deleted = forms.BooleanField(widget=forms.CheckboxInput(attrs={ 'id': "vm-list-search-checkbox", })) def __init__(self, *args, **kwargs): super(VmListSearchForm, self).__init__(*args, **kwargs) # set initial value, otherwise it would be overwritten by request.GET if not self.data.get("stype"): data = self.data.copy() data['stype'] = "all" self.data = data class TemplateListSearchForm(forms.Form): s = forms.CharField(widget=forms.TextInput(attrs={ 'class': "form-control input-tags", 'placeholder': _("Search...") })) stype = forms.ChoiceField(vm_search_choices, widget=forms.Select(attrs={ 'class': "btn btn-default input-tags", })) def __init__(self, *args, **kwargs): super(TemplateListSearchForm, self).__init__(*args, **kwargs) # set initial value, otherwise it would be overwritten by request.GET if not self.data.get("stype"): data = self.data.copy() data['stype'] = "owned" self.data = data class UserListSearchForm(forms.Form): s = forms.CharField(widget=forms.TextInput(attrs={ 'class': "form-control input-tags", 'placeholder': _("Search...") })) class DataStoreForm(ModelForm): @property def helper(self): helper = FormHelper() helper.layout = Layout( Fieldset( '', 'name', 'path', 'hostname', ), FormActions( Submit('submit', _('Save')), ) ) return helper class Meta: model = DataStore fields = ("name", "path", "hostname", ) class DiskForm(ModelForm): created = forms.DateTimeField() modified = forms.DateTimeField() def __init__(self, *args, **kwargs): super(DiskForm, self).__init__(*args, **kwargs) for k, v in self.fields.iteritems(): v.widget.attrs['readonly'] = True self.fields['created'].initial = self.instance.created self.fields['modified'].initial = self.instance.modified class Meta: model = Disk fields = ("name", "filename", "datastore", "type", "bus", "size", "base", "dev_num", "destroyed", "is_ready", ) class MessageForm(ModelForm): class Meta: model = Message fields = ("message", "enabled", "effect", "start", "end") help_texts = { 'start': _("Start time of the message in " "YYYY-MM-DD hh:mm:ss format."), 'end': _("End time of the message in " "YYYY-MM-DD hh:mm:ss format."), 'effect': _('The color of the message box defined by the ' 'respective ' '' 'Bootstrap class.') } labels = { 'start': _("Start time"), 'end': _("End time") } @property def helper(self): helper = FormHelper() helper.add_input(Submit("submit", _("Save"))) return helper class TwoFactorForm(ModelForm): class Meta: model = Profile fields = ["two_factor_secret", ] class TwoFactorConfirmationForm(forms.Form): confirmation_code = forms.CharField( label=_('Two-factor authentication passcode'), help_text=_("Get the code from your authenticator."), widget=forms.TextInput(attrs={'autofocus': True}) ) def __init__(self, user, *args, **kwargs): self.user = user super(TwoFactorConfirmationForm, self).__init__(*args, **kwargs) def clean_confirmation_code(self): totp = pyotp.TOTP(self.user.profile.two_factor_secret) if not totp.verify(self.cleaned_data.get('confirmation_code')): raise ValidationError(_("Invalid confirmation code.")) management/ 0000775 0000000 0000000 00000000000 13126740172 0032270 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard __init__.py 0000664 0000000 0000000 00000000000 13126740172 0034367 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/management commands/ 0000775 0000000 0000000 00000000000 13126740172 0034071 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/management __init__.py 0000664 0000000 0000000 00000000000 13126740172 0036170 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/management/commands init.py 0000664 0000000 0000000 00000013665 13126740172 0035421 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/management/commands # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from __future__ import unicode_literals, absolute_import import logging from optparse import make_option from django.contrib.auth.models import User from django.core.management.base import BaseCommand from firewall.models import Vlan, VlanGroup, Domain, Firewall, Rule from storage.models import DataStore from vm.models import Lease logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--force', action="store_true"), make_option('--external-net'), make_option('--management-net'), make_option('--vm-net'), make_option('--external-if'), make_option('--management-if'), make_option('--vm-if'), make_option('--datastore-queue'), make_option('--firewall-queue'), make_option('--admin-user'), make_option('--admin-pass'), ) def create(self, model, field, **kwargs): value = kwargs[field] qs = model.objects.filter(**{field: value})[:1] if not qs.exists(): obj = model.objects.create(**kwargs) logger.info('New %s: %s', model, obj) self.changed = True return obj else: return qs[0] # http://docs.saltstack.com/en/latest/ref/states/all/salt.states.cmd.html def print_state(self): print "\nchanged=%s" % ("yes" if self.changed else "no") def handle(self, *args, **options): self.changed = False if (DataStore.objects.exists() and Vlan.objects.exists() and not options['force']): return self.print_state() admin = self.create(User, 'username', username=options['admin_user'], is_superuser=True, is_staff=True) admin.set_password(options['admin_pass']) admin.save() self.create(DataStore, 'path', path='/datastore', name='default', hostname=options['datastore_queue']) # leases self.create(Lease, 'name', name='lab', suspend_interval_seconds=3600 * 5, delete_interval_seconds=3600 * 24 * 7) self.create(Lease, 'name', name='project', suspend_interval_seconds=3600 * 24 * 30, delete_interval_seconds=3600 * 24 * 30 * 6) self.create(Lease, 'name', name='server', suspend_interval_seconds=3600 * 24 * 365, delete_interval_seconds=3600 * 24 * 365 * 3) net_domain = self.create(Domain, 'name', name='net.example.com', owner=admin) man_domain = self.create(Domain, 'name', name='man.example.com', owner=admin) vm_domain = self.create(Domain, 'name', name='vm.example.com', owner=admin) # vlans net = self.create(Vlan, 'vid', name=options['external_if'], vid=4, network4=options['external_net'], domain=net_domain) man = self.create(Vlan, 'vid', name=options['management_if'], vid=3, dhcp_pool='manual', network4=options['management_net'], domain=man_domain, snat_ip=options['external_net'].split('/')[0]) man.snat_to.add(net) man.snat_to.add(man) vm = self.create(Vlan, 'vid', name=options['vm_if'], vid=2, dhcp_pool='manual', network4=options['vm_net'], domain=vm_domain, snat_ip=options['external_net'].split('/')[0]) vm.snat_to.add(net) vm.snat_to.add(vm) # default vlan groups vg_all = self.create(VlanGroup, 'name', name='all') vg_all.vlans.add(vm, man, net) vg_pf = self.create(VlanGroup, 'name', name='portforward') vg_pf.vlans.add(vm, man, net) vg_net = self.create(VlanGroup, 'name', name='net') vg_net.vlans.add(net) # firewall rules fw = self.create(Firewall, 'name', name=options['firewall_queue']) self.create(Rule, 'description', description='default output rule', direction='out', action='accept', foreign_network=vg_all, firewall=fw) self.create(Rule, 'description', description='portal https', direction='in', action='accept', proto='tcp', dport=443, foreign_network=vg_all, firewall=fw) self.create(Rule, 'description', description='portal http', direction='in', action='accept', proto='tcp', dport=80, foreign_network=vg_all, firewall=fw) self.create(Rule, 'description', description='ssh', direction='in', action='accept', proto='tcp', dport=22, foreign_network=vg_all, firewall=fw) # vlan rules self.create(Rule, 'description', description='allow vm->net', direction='out', action='accept', foreign_network=vg_net, vlan=vm) self.create(Rule, 'description', description='allow man->net', direction='out', action='accept', foreign_network=vg_net, vlan=man) return self.print_state() migrations/ 0000775 0000000 0000000 00000000000 13126740172 0032330 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard 0001_initial.py 0000664 0000000 0000000 00000013447 13126740172 0035004 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/migrations # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import dashboard.validators import dashboard.models import model_utils.fields import sizefield.models import jsonfield.fields import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vm', '__first__'), ] operations = [ migrations.CreateModel( name='ConnectCommand', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('access_method', models.CharField(help_text='Type of the remote access method.', max_length=10, verbose_name='access method', choices=[('nx', 'NX'), ('rdp', 'RDP'), ('ssh', 'SSH')])), ('name', models.CharField(help_text='Name of your custom command.', max_length=b'128', verbose_name='name')), ('template', models.CharField(validators=[dashboard.validators.connect_command_template_validator], max_length=256, blank=True, help_text='Template for connection command string. Available parameters are: username, password, host, port.', null=True, verbose_name='command template')), ('user', models.ForeignKey(related_name='command_set', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Favourite', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('instance', models.ForeignKey(to='vm.Instance')), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='FutureMember', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('org_id', models.CharField(help_text='Unique identifier of the person, e.g. a student number.', max_length=64)), ('group', models.ForeignKey(to='auth.Group')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='GroupProfile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('org_id', models.CharField(help_text='Unique identifier of the group at the organization.', max_length=64, unique=True, null=True, blank=True)), ('description', models.TextField(blank=True)), ('group', models.OneToOneField(to='auth.Group')), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='Notification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('status', model_utils.fields.StatusField(default=b'new', max_length=100, no_check_for_status=True, choices=[(b'new', 'new'), (b'delivered', 'delivered'), (b'read', 'read')])), ('subject_data', jsonfield.fields.JSONField(null=True)), ('message_data', jsonfield.fields.JSONField(null=True)), ('valid_until', models.DateTimeField(default=None, null=True)), ('to', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['-created'], }, bases=(models.Model,), ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('preferred_language', models.CharField(default=b'en', max_length=32, verbose_name='preferred language', choices=[(b'en', 'English'), (b'hu', 'Hungarian')])), ('org_id', models.CharField(help_text='Unique identifier of the person, e.g. a student number.', max_length=64, unique=True, null=True, blank=True)), ('instance_limit', models.IntegerField(default=5)), ('use_gravatar', models.BooleanField(default=True, help_text='Whether to use email address as Gravatar profile image', verbose_name='Use Gravatar')), ('email_notifications', models.BooleanField(default=True, help_text='Whether user wants to get digested email notifications.', verbose_name='Email notifications')), ('smb_password', models.CharField(default=dashboard.models.pwgen, help_text='Generated password for accessing store from virtual machines.', max_length=20, verbose_name='Samba password')), ('disk_quota', sizefield.models.FileSizeField(default=2147483648, help_text='Disk quota in mebibytes.', verbose_name='disk quota')), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ], options={ 'permissions': (('use_autocomplete', 'Can use autocomplete.'),), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='futuremember', unique_together=set([('org_id', 'group')]), ), ] 0002_auto_20150318_1317.py 0000664 0000000 0000000 00000001442 13126740172 0035752 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/migrations # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='connectcommand', options={'ordering': ('id',)}, ), migrations.AlterModelOptions( name='futuremember', options={'ordering': ('id',)}, ), migrations.AlterModelOptions( name='groupprofile', options={'ordering': ('id',)}, ), migrations.AlterModelOptions( name='profile', options={'ordering': ('id',), 'permissions': (('use_autocomplete', 'Can use autocomplete.'),)}, ), ] 0003_message.py 0000664 0000000 0000000 00000003056 13126740172 0034774 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/migrations # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('dashboard', '0002_auto_20150318_1317'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('start', models.DateTimeField(null=True, verbose_name='start', blank=True)), ('end', models.DateTimeField(null=True, verbose_name='end', blank=True)), ('message', models.CharField(max_length=500, verbose_name='message')), ('effect', models.CharField(default=b'info', max_length=10, verbose_name='effect', choices=[(b'success', 'success'), (b'info', 'info'), (b'warning', 'warning'), (b'danger', 'danger')])), ('enabled', models.BooleanField(default=False, verbose_name='enabled')), ], options={ 'ordering': ['id'], 'verbose_name': 'message', 'verbose_name_plural': 'messages', }, bases=(models.Model,), ), ] 0004_profile_desktop_notifications.py 0000664 0000000 0000000 00000001072 13126740172 0041467 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/migrations # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0003_message'), ] operations = [ migrations.AddField( model_name='profile', name='desktop_notifications', field=models.BooleanField(default=False, help_text='Whether user wants to get desktop notification when an activity has finished and the window is not in focus.', verbose_name='Desktop notifications'), ), ] 0005_profile_two_factor_secret.py 0000664 0000000 0000000 00000000746 13126740172 0040611 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/migrations # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0004_profile_desktop_notifications'), ] operations = [ migrations.AddField( model_name='profile', name='two_factor_secret', field=models.CharField(max_length=32, null=True, verbose_name='two factor secret key', blank=True), ), ] __init__.py 0000664 0000000 0000000 00000000000 13126740172 0034427 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/migrations models.py 0000664 0000000 0000000 00000040275 13126740172 0032021 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard # Copyright 2014 Budapest University of Technology and Economics (BME IK) # # This file is part of CIRCLE Cloud. # # CIRCLE 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. # # CIRCLE 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 CIRCLE. If not, see . from __future__ import absolute_import from datetime import timedelta from itertools import chain from hashlib import md5 from logging import getLogger from django.conf import settings from django.contrib.auth.models import User, Group from django.contrib.auth.signals import user_logged_in from django.core.urlresolvers import reverse from django.db.models import ( Model, ForeignKey, OneToOneField, CharField, IntegerField, TextField, DateTimeField, BooleanField ) from django.db.models.signals import post_save, pre_delete, post_delete from django.templatetags.static import static from django.utils import timezone from django.utils.html import escape from django.utils.translation import ugettext_lazy as _ from django_sshkey.models import UserKey from django.core.exceptions import ObjectDoesNotExist from sizefield.models import FileSizeField from jsonfield import JSONField from model_utils.models import TimeFramedModel, TimeStampedModel from model_utils.fields import StatusField from model_utils import Choices from acl.models import AclBase from common.models import HumanReadableObject, create_readable, Encoder from vm.models.instance import ACCESS_METHODS from .store_api import Store, NoStoreException, NotOkException, Timeout from .validators import connect_command_template_validator logger = getLogger(__name__) def pwgen(): return User.objects.make_random_password() class Message(TimeStampedModel, TimeFramedModel): message = CharField(max_length=500, verbose_name=_('message')) effect = CharField( default='info', max_length=10, verbose_name=_('effect'), choices=(('success', _('success')), ('info', _('info')), ('warning', _('warning')), ('danger', _('danger')))) enabled = BooleanField(default=False, verbose_name=_('enabled')) class Meta: ordering = ["id"] verbose_name = _('message') verbose_name_plural = _('messages') def __unicode__(self): return self.message def get_absolute_url(self): return reverse('dashboard.views.message-detail', kwargs={'pk': self.pk}) class Favourite(Model): instance = ForeignKey("vm.Instance") user = ForeignKey(User) class Notification(TimeStampedModel): STATUS = Choices(('new', _('new')), ('delivered', _('delivered')), ('read', _('read'))) status = StatusField() to = ForeignKey(User) subject_data = JSONField(null=True, dump_kwargs={"cls": Encoder}) message_data = JSONField(null=True, dump_kwargs={"cls": Encoder}) valid_until = DateTimeField(null=True, default=None) class Meta: ordering = ['-created'] @classmethod def send(cls, user, subject, template, context, valid_until=None, subject_context=None): hro = create_readable(template, user=user, **context) subject = create_readable(subject, **(subject_context or context)) return cls.objects.create(to=user, subject_data=subject.to_dict(), message_data=hro.to_dict(), valid_until=valid_until) @property def subject(self): return HumanReadableObject.from_dict( self.escape_dict(self.subject_data)) @subject.setter def subject(self, value): self.subject_data = None if value is None else value.to_dict() @property def message(self): return HumanReadableObject.from_dict( self.escape_dict(self.message_data)) def escape_dict(self, data): for k, v in data['params'].items(): if isinstance(v, basestring): data['params'][k] = escape(v) return data @message.setter def message(self, value): self.message_data = None if value is None else value.to_dict() @property def has_valid_renew_url(self): params = self.message_data['params'] return ('token' in params and 'suspend' in params and self.modified > timezone.now() - timedelta(days=3)) @property def renew_url(self): return (settings.DJANGO_URL.rstrip("/") + str(self.message_data['params'].get('token'))) class ConnectCommand(Model): user = ForeignKey(User, related_name='command_set') access_method = CharField(max_length=10, choices=ACCESS_METHODS, verbose_name=_('access method'), help_text=_('Type of the remote access method.')) name = CharField(max_length=128, verbose_name=_('name'), blank=False, help_text=_("Name of your custom command.")) template = CharField(blank=True, null=True, max_length=256, verbose_name=_('command template'), help_text=_('Template for connection command string. ' 'Available parameters are: ' 'username, password, ' 'host, port.'), validators=[connect_command_template_validator]) class Meta: ordering = ('id', ) def __unicode__(self): return self.template class Profile(Model): user = OneToOneField(User) preferred_language = CharField(verbose_name=_('preferred language'), choices=settings.LANGUAGES, max_length=32, default=settings.LANGUAGE_CODE, blank=False) org_id = CharField( # may be populated from eduPersonOrgId field unique=True, blank=True, null=True, max_length=64, help_text=_('Unique identifier of the person, e.g. a student number.')) instance_limit = IntegerField(default=5) use_gravatar = BooleanField( verbose_name=_("Use Gravatar"), default=True, help_text=_("Whether to use email address as Gravatar profile image")) email_notifications = BooleanField( verbose_name=_("Email notifications"), default=True, help_text=_('Whether user wants to get digested email notifications.')) desktop_notifications = BooleanField( verbose_name=_("Desktop notifications"), default=False, help_text=_('Whether user wants to get desktop notification when an ' 'activity has finished and the window is not in focus.')) smb_password = CharField( max_length=20, verbose_name=_('Samba password'), help_text=_( 'Generated password for accessing store from ' 'virtual machines.'), default=pwgen, ) disk_quota = FileSizeField( verbose_name=_('disk quota'), default=2048 * 1024 * 1024, help_text=_('Disk quota in mebibytes.')) two_factor_secret = CharField( verbose_name=_("two factor secret key"), max_length=32, null=True, blank=True, ) def get_connect_commands(self, instance, use_ipv6=False): """ Generate connection command based on template.""" single_command = instance.get_connect_command(use_ipv6) if single_command: # can we even connect to that VM commands = self.user.command_set.filter( access_method=instance.access_method) if commands.count() < 1: return [single_command] else: return [ command.template % { 'port': instance.get_connect_port(use_ipv6=use_ipv6), 'host': instance.get_connect_host(use_ipv6=use_ipv6), 'password': instance.pw, 'username': 'cloud', } for command in commands] else: return [] def notify(self, subject, template, context=None, valid_until=None, **kwargs): if context is not None: kwargs.update(context) return Notification.send(self.user, subject, template, kwargs, valid_until) def get_absolute_url(self): return reverse("dashboard.views.profile", kwargs={'username': self.user.username}) def get_avatar_url(self): if self.use_gravatar: gravatar_hash = md5(self.user.email).hexdigest() return ("https://secure.gravatar.com/avatar/%s" "?s=200" % gravatar_hash) else: return static("dashboard/img/avatar.png") def get_display_name(self): if self.user.get_full_name(): name = self.user.get_full_name() else: name = self.user.username if self.org_id: name = "%s (%s)" % (name, self.org_id) return name def __unicode__(self): return self.get_display_name() def save(self, *args, **kwargs): if self.org_id == "": self.org_id = None super(Profile, self).save(*args, **kwargs) class Meta: ordering = ('id', ) permissions = ( ('use_autocomplete', _('Can use autocomplete.')), ) class FutureMember(Model): org_id = CharField(max_length=64, help_text=_( 'Unique identifier of the person, e.g. a student number.')) group = ForeignKey(Group) class Meta: ordering = ('id', ) unique_together = ('org_id', 'group') def __unicode__(self): return u"%s (%s)" % (self.org_id, self.group) class GroupProfile(AclBase): ACL_LEVELS = ( ('operator', _('operator')), ('owner', _('owner')), ) group = OneToOneField(Group) org_id = CharField( unique=True, blank=True, null=True, max_length=64, help_text=_('Unique identifier of the group at the organization.')) description = TextField(blank=True) class Meta: ordering = ('id', ) def __unicode__(self): return self.group.name def save(self, *args, **kwargs): if not self.org_id: self.org_id = None super(GroupProfile, self).save(*args, **kwargs) @classmethod def search(cls, name): try: return cls.objects.get(org_id=name).group except cls.DoesNotExist: return Group.objects.get(name=name) def get_absolute_url(self): return reverse('dashboard.views.group-detail', kwargs={'pk': self.group.pk}) def get_or_create_profile(self): obj, created = GroupProfile.objects.get_or_create(group_id=self.pk) return obj Group.profile = property(get_or_create_profile) def create_profile(user): if not user.pk: return False profile, created = Profile.objects.get_or_create(user=user) try: Store(user).create_user(profile.smb_password, None, profile.disk_quota) except: logger.exception("Can't create user %s", unicode(user)) return created def create_profile_hook(sender, user, request, **kwargs): return create_profile(user) user_logged_in.connect(create_profile_hook) if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'): logger.debug("Register save_org_id to djangosaml2 pre_user_save") from djangosaml2.signals import pre_user_save def save_org_id(sender, **kwargs): logger.debug("save_org_id called by %s", sender.username) attributes = kwargs.pop('attributes') atr = settings.SAML_ORG_ID_ATTRIBUTE try: value = attributes[atr][0].upper() except Exception as e: value = None logger.info("save_org_id couldn't find attribute. %s", unicode(e)) if sender.pk is None: sender.save() logger.debug("save_org_id saved user %s", unicode(sender)) profile, created = Profile.objects.get_or_create(user=sender) if created or profile.org_id != value: logger.info("org_id of %s added to user %s's profile", value, sender.username) profile.org_id = value profile.save() else: logger.debug("org_id of %s already added to user %s's profile", value, sender.username) memberatrs = getattr(settings, 'SAML_GROUP_ATTRIBUTES', []) for group in chain(*[attributes[i] for i in memberatrs if i in attributes]): try: g = GroupProfile.search(group) except Group.DoesNotExist: logger.debug('cant find membergroup %s', group) else: logger.debug('could find membergroup %s (%s)', group, unicode(g)) g.user_set.add(sender) for i in FutureMember.objects.filter(org_id__iexact=value): i.group.user_set.add(sender) i.delete() owneratrs = getattr(settings, 'SAML_GROUP_OWNER_ATTRIBUTES', []) for group in chain(*[attributes[i] for i in owneratrs if i in attributes]): try: g = GroupProfile.search(group) except Group.DoesNotExist: logger.debug('cant find ownergroup %s', group) else: logger.debug('could find ownergroup %s (%s)', group, unicode(g)) g.profile.set_level(sender, 'owner') return False # User did not change pre_user_save.connect(save_org_id) def update_store_profile(sender, **kwargs): profile = kwargs.get('instance') keys = [i.key for i in profile.user.userkey_set.all()] try: s = Store(profile.user) s.create_user(profile.smb_password, keys, profile.disk_quota) except NoStoreException: logger.debug("Store is not available.") except (NotOkException, Timeout): logger.critical("Store is not accepting connections.") post_save.connect(update_store_profile, sender=Profile) def update_store_keys(sender, **kwargs): userkey = kwargs.get('instance') try: profile = userkey.user.profile except ObjectDoesNotExist: pass # If there is no profile the user is deleted else: keys = [i.key for i in profile.user.userkey_set.all()] try: s = Store(userkey.user) s.create_user(profile.smb_password, keys, profile.disk_quota) except NoStoreException: logger.debug("Store is not available.") except NotOkException: logger.critical("Store is not accepting connections.") post_save.connect(update_store_keys, sender=UserKey) post_delete.connect(update_store_keys, sender=UserKey) def add_ssh_keys(sender, **kwargs): from vm.models import Instance userkey = kwargs.get('instance') instances = Instance.get_objects_with_level( 'user', userkey.user, disregard_superuser=True ).filter(status='RUNNING') for i in instances: logger.info('called add_keys(%s, %s)', i, userkey) try: i.install_keys(user=userkey.user, keys=[userkey.key]) except Instance.NoAgentError: logger.info("%s has no agent running", i) def del_ssh_keys(sender, **kwargs): from vm.models import Instance userkey = kwargs.get('instance') instances = Instance.get_objects_with_level( 'user', userkey.user, disregard_superuser=True ).filter(status='RUNNING') for i in instances: logger.info('called del_keys(%s, %s)', i, userkey) try: i.remove_keys(user=userkey.user, keys=[userkey.key]) except Instance.NoAgentError: logger.info("%s has no agent running", i) post_save.connect(add_ssh_keys, sender=UserKey) pre_delete.connect(del_ssh_keys, sender=UserKey) static/ 0000775 0000000 0000000 00000000000 13126740172 0031443 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard compile_bootstrap.less 0000664 0000000 0000000 00000003426 13126740172 0036065 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/static // Core variables and mixins @import "bootstrap/less/variables.less"; // Custom variables @navbar-height: 45px; @import "bootstrap/less/mixins.less"; // Reset and dependencies @import "bootstrap/less/normalize.less"; @import "bootstrap/less/print.less"; // we don't use these, also they make collectstatic fail ... // @import "bootstrap/less/glyphicons.less"; // Core CSS @import "bootstrap/less/scaffolding.less"; @import "bootstrap/less/type.less"; @import "bootstrap/less/code.less"; @import "bootstrap/less/grid.less"; @import "bootstrap/less/tables.less"; @import "bootstrap/less/forms.less"; @import "bootstrap/less/buttons.less"; // Components @import "bootstrap/less/component-animations.less"; @import "bootstrap/less/dropdowns.less"; @import "bootstrap/less/button-groups.less"; @import "bootstrap/less/input-groups.less"; @import "bootstrap/less/navs.less"; @import "bootstrap/less/navbar.less"; @import "bootstrap/less/breadcrumbs.less"; @import "bootstrap/less/pagination.less"; @import "bootstrap/less/pager.less"; @import "bootstrap/less/labels.less"; @import "bootstrap/less/badges.less"; @import "bootstrap/less/jumbotron.less"; @import "bootstrap/less/thumbnails.less"; @import "bootstrap/less/alerts.less"; @import "bootstrap/less/progress-bars.less"; @import "bootstrap/less/media.less"; @import "bootstrap/less/list-group.less"; @import "bootstrap/less/panels.less"; @import "bootstrap/less/responsive-embed.less"; @import "bootstrap/less/wells.less"; @import "bootstrap/less/close.less"; // Components w/ JavaScript @import "bootstrap/less/modals.less"; @import "bootstrap/less/tooltip.less"; @import "bootstrap/less/popovers.less"; @import "bootstrap/less/carousel.less"; // Utility classes @import "bootstrap/less/utilities.less"; @import "bootstrap/less/responsive-utilities.less"; dashboard/ 0000775 0000000 0000000 00000000000 13126740172 0033372 5 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/static activity.js 0000664 0000000 0000000 00000017234 13126740172 0035573 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/static/dashboard $(function() { var in_progress = false; var activity_hash = 5; var show_all = false; var reload_vm_detail = false; /* do we need to check for new activities */ if(decideActivityRefresh()) { if(!in_progress) { checkNewActivity(1); in_progress = true; } } $('a[href="#activity"]').click(function(){ $('a[href="#activity"] i').addClass('fa-spin'); if(!in_progress) { checkNewActivity(1); in_progress = true; } }); $("#activity-refresh").on("click", "#show-all-activities", function() { $(this).find("i").addClass("fa-spinner fa-spin"); show_all = !show_all; $('a[href="#activity"]').trigger("click"); return false; }); /* operations */ $('#ops, #vm-details-resources-disk, #vm-details-renew-op, #vm-details-pw-reset, #vm-details-add-interface, .operation-wrapper').on('click', '.operation', function(e) { var icon = $(this).children("i").addClass('fa-spinner fa-spin'); $.ajax({ type: 'GET', url: $(this).attr('href'), success: function(data) { icon.removeClass("fa-spinner fa-spin"); $('body').append(data); $('#confirmation-modal').modal('show'); $('#confirmation-modal').on('hidden.bs.modal', function() { $('#confirmation-modal').remove(); }); $('#vm-migrate-node-list li input:checked').closest('li').addClass('panel-primary'); } }); e.preventDefault(); }); /* if the operation fails show the modal again */ $("body").on("click", "#confirmation-modal #op-form-send", function() { var url = $(this).closest("form").prop("action"); $.ajax({ url: url, headers: {"X-CSRFToken": getCookie('csrftoken')}, type: 'POST', data: $(this).closest('form').serialize(), success: function(data, textStatus, xhr) { /* hide the modal we just submitted */ $('#confirmation-modal').modal("hide"); /* if it was successful trigger a click event on activity, this will * - go to that tab * - starts refreshing the activity */ if(data.success) { $('a[href="#activity"]').trigger("click"); if(data.with_reload) { // when the activity check stops the page will reload reload_vm_detail = true; } /* if there are messages display them */ if(data.messages && data.messages.length > 0) { addMessage(data.messages.join(""), data.success ? "success" : "danger"); } } else { /* if the post was not successful wait for the modal to disappear * then append the new modal */ $('#confirmation-modal').on('hidden.bs.modal', function() { $('body').append(data); $('#confirmation-modal').modal('show'); $('#confirmation-modal').on('hidden.bs.modal', function() { $('#confirmation-modal').remove(); }); }); } }, error: function(xhr, textStatus, error) { $('#confirmation-modal').modal("hide"); if (xhr.status == 500) { addMessage("500 Internal Server Error", "danger"); } else { addMessage(xhr.status + " Unknown Error", "danger"); } } }); return false; }); function decideActivityRefresh() { var check = false; /* if something is still spinning */ if($('.timeline .activity i').hasClass('fa-spin')) check = true; return check; } function checkNewActivity(runs) { $.ajax({ type: 'GET', url: $('a[href="#activity"]').attr('data-activity-url'), data: {'show_all': show_all}, success: function(data) { var new_activity_hash = (data.activities + "").hashCode(); if(new_activity_hash != activity_hash) { $("#activity-refresh").html(data.activities); } activity_hash = new_activity_hash; $("#ops").html(data.ops); $("#disk-ops").html(data.disk_ops); $("[title]").tooltip(); /* changing the status text */ var icon = $("#vm-details-state i"); if(data.is_new_state) { if(!icon.hasClass("fa-spin")) icon.prop("class", "fa fa-spinner fa-spin"); } else { icon.prop("class", "fa " + data.icon); } var vm_state = $("#vm-details-state"); if (vm_state.length) { vm_state.data("status", data['status']); // jshint ignore:line $("#vm-details-state span").html(data.human_readable_status.toUpperCase()); } if(data['status'] == "RUNNING") { // jshint ignore:line if(data.connect_uri) { $("#dashboard-vm-details-connect-button").removeClass('disabled'); } $("[data-target=#_console]").attr("data-toggle", "pill").attr("href", "#console").parent("li").removeClass("disabled"); $("#getScreenshotButton").prop("disabled", false); } else { if(data.connect_uri) { $("#dashboard-vm-details-connect-button").addClass('disabled'); } $("[data-target=#_console]").attr("data-toggle", "_pill").attr("href", "#").parent("li").addClass("disabled"); $("#getScreenshotButton").prop("disabled", true); } if(data.status == "STOPPED" || data.status == "PENDING") { $(".change-resources-button").prop("disabled", false); $(".change-resources-help").hide(); } else { $(".change-resources-button").prop("disabled", true); $(".change-resources-help").show(); } if(runs > 0 && decideActivityRefresh()) { setTimeout( function() {checkNewActivity(runs + 1);}, 1000 + Math.exp(runs * 0.05) ); } else { in_progress = false; if(document.hasFocus() === false && userWantNotifications()){ sendNotification(generateMessageFromLastActivity()); } if(reload_vm_detail) location.reload(); if(runs > 1) addConnectText(); } $('a[href="#activity"] i').removeClass('fa-spin'); }, error: function() { in_progress = false; } }); } }); // Notification init $(function(){ if(userWantNotifications()) Notification.requestPermission(); }); function generateMessageFromLastActivity(){ var ac = $("div.activity").first(); var error = ac.children(".timeline-icon-failed").length; var sign = (error === 1) ? "⌠" : "✓ "; var msg = ac.children("strong").text().replace(/\s+/g, " "); return sign + msg; } function sendNotification(message) { var options = { icon: "/static/dashboard/img/favicon.png"}; if (Notification.permission === "granted") { var notification = new Notification(message, options); } else if (Notification.permission !== "denied") { Notification.requestPermission(function (permission) { if (permission === "granted") { var notification = new Notification(message, options); } }); } } function userWantNotifications(){ var dn = $("#user-options").data("desktop_notifications"); return dn === "True"; } function addConnectText() { var activities = $(".timeline .activity"); if(activities.length > 1) { if(activities.eq(0).data("activity-code") == "vm.Instance.wake_up" || activities.eq(0).data("activity-code") == "vm.Instance.agent") { $("#vm-detail-successful-boot").slideDown(500); } } } String.prototype.hashCode = function() { var hash = 0, i, chr, len; if (this.length === 0) return hash; for (i = 0, len = this.length; i < len; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; dashboard.js 0000664 0000000 0000000 00000043046 13126740172 0035666 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/static/dashboard $(function () { var favicon= new Favico({ animation:'none' }); var notifications = $("#notification_count").data("notifications"); if(notifications) favicon.badge(notifications); $(".not-tab-pane").removeClass("not-tab-pane").addClass("tab-pane"); $('.vm-create').click(function(e) { var url = $(this).data("href"); if(!url) url = $(this).prop("href"); $.ajax({ type: 'GET', url: url, success: function(data) { $('body').append(data); vmCreateLoaded(); addSliderMiscs(); var modal = $('#confirmation-modal'); modal.modal('show'); modal.on('hidden.bs.modal', function() { modal.remove(); }); } }); return false; }); $('.group-create, .node-create, .tx-tpl-ownership, .group-delete, .node-delete, .disk-remove, .template-delete, .delete-from-group, .lease-delete').click(function(e) { $.ajax({ type: 'GET', url: $(this).prop('href'), success: function(data) { $('body').append(data); var modal = $('#confirmation-modal'); modal.modal('show'); modal.on('hidden.bs.modal', function() { modal.remove(); }); }, error: function(xhr, textStatus, error) { if(xhr.status === 403) { addMessage(gettext("Only the owners can delete the selected object."), "warning"); } else { addMessage(gettext("An error occurred. (") + xhr.status + ")", 'danger'); } } }); return false; }); $('.template-choose').click(function(e) { $.ajax({ type: 'GET', url: $(this).prop('href'), success: function(data) { $('body').append(data); var modal = $('#confirmation-modal'); modal.modal('show'); modal.on('hidden.bs.modal', function() { modal.remove(); }); // check if user selected anything $("#template-choose-next-button").click(function() { var radio = $('input[type="radio"]:checked', "#template-choose-form").val(); if(!radio) { $("#template-choose-alert").addClass("alert-warning") .text(gettext("Select an option to proceed!")); return false; } return true; }); } }); return false; }); $('[href=#index-graph-view]').click(function (e) { var box = $(this).data('index-box'); $("#" + box + "-list-view").hide(); $("#" + box + "-graph-view").show(); $(this).next('a').removeClass('disabled'); $(this).addClass('disabled'); e.stopImmediatePropagation(); return false; }); $('[href=#index-list-view]').click(function (e) { var box = $(this).data('index-box'); $('#' + box + '-graph-view').hide(); $('#' + box + '-list-view').show(); $(this).addClass('disabled'); $(this).prev("a").removeClass('disabled'); e.stopImmediatePropagation(); return false; }); $('body .title-favourite').tooltip({'placement': 'right'}); $('body :input[title]').tooltip({trigger: 'focus', placement: 'auto right'}); $('body [title]').tooltip(); $(".knob").knob(); $('[data-toggle="pill"]').click(function() { window.location.hash = $(this).attr('href'); }); if (window.location.hash) { if(window.location.hash.substring(1,4) == "ipv") $("a[href=#network]").tab('show'); if(window.location.hash == "activity") checkNewActivity(false, 1); $("a[href=" + window.location.hash +"]").tab('show'); } /* no js compatibility */ noJS(); $('.no-js-hidden').show(); $('.js-hidden').hide(); /* favourite star */ $("#dashboard-vm-list, .page-header").on('click', '.dashboard-vm-favourite', function(e) { var star = $(this).children("i"); var pk = $(this).data("vm"); if(star.hasClass("fa-star-o")) { star.removeClass("fa-star-o").addClass("fa-star"); star.prop("title", gettext("Unfavourite")); } else { star.removeClass("fa-star").addClass("fa-star-o"); star.prop("title", gettext("Mark as favourite")); } $.ajax({ url: "/dashboard/favourite/", type: "POST", data: {'vm': pk}, headers: {"X-CSRFToken": getCookie('csrftoken')}, success: function(data, textStatus, xhr) { // success }, error: function(xhr, textStatus, error) { addMessage(gettext("An error occurred. (") + xhr.status + ")", 'danger'); } }); $(star).tooltip('destroy').tooltip({'placement': 'right'}); my_vms = []; return false; }); /* scroll to top if there is a message */ if($(".messagelist").children(".alert").length > 0) $('body').animate({scrollTop: 0}); addSliderMiscs(); /* search */ function register_search(form, list, generateHTML) { var my_vms = []; /* 0 - default state * 1 - ajax request sent * 2 - ajax request received, we have our list of vms */ var search_state = 0; form.find('input').keyup(function(e) { if (search_state == 1) { return; } // if my_vms is empty get a list of our vms if(search_state === 0) { search_state = 1; var btn = form.find('button'); btn.find('i').addClass("fa-spinner fa-spin"); $.get(form.prop('action'), function(result) { search_state = 3; my_vms = result; form.find("input").trigger("keyup"); btn.find('i').removeClass("fa-spinner fa-spin").addClass("fa-search"); }); return; } input = $(this).val().toLowerCase(); var search_result = []; for(var i in my_vms) { if(my_vms[i].name.toLowerCase().indexOf(input) != -1 || (my_vms[i].host && my_vms[i].host.indexOf(input) != -1) || (my_vms[i].org_id && my_vms[i].org_id.toLowerCase().indexOf(input) != -1) ) { search_result.push(my_vms[i]); } } search_result.sort(compareVmByFav); var html = ''; var is_last = search_result.length < 5; for(i=0; i<5 && i' + gettext("No result") + ''; list.html(html); $('.title-favourite').tooltip({'placement': 'right'}); }); form.submit(function() { var vm_list_items = list.find(".list-group-item"); if(vm_list_items.length == 1 && vm_list_items.first().prop("href")) { window.location.href = vm_list_items.first().prop("href"); return false; } return true; }); } register_search($("#dashboard-vm-search-form"), $("#dashboard-vm-list"), generateVmHTML); register_search($("#dashboard-node-search-form"), $("#dashboard-node-list"), generateNodeHTML); register_search($("#dashboard-group-search-form"), $("#dashboard-group-list"), generateGroupHTML); register_search($("#dashboard-user-search-form"), $("#dashboard-user-list"), generateUserHTML); register_search($("#dashboard-template-search-form"), $("#dashboard-template-list"), generateTemplateHTML); /* notification message toggle */ $(document).on('click', ".notification-message-subject", function() { $(".notification-message-text", $(this).parent()).slideToggle(); return false; }); /* don't close notifications window on missclick */ $(document).on("click", "#notification-messages", function(e) { if($(e.target).closest("a").length) return true; else return false; }); $("#notification-button a").click(function() { $('#notification-messages').load("/dashboard/notifications/"); $('#notification-button a span[class*="badge-pulse"]').remove(); favicon.reset(); }); /* on the client confirmation button fire the clientInstalledAction */ $(document).on("click", "#client-check-button", function(event) { var connectUri = $('#connect-uri').val(); clientInstalledAction(connectUri); return false; }); $("#dashboard-vm-details-connect-button").click(function(event) { var connectUri = $(this).attr("href"); clientInstalledAction(connectUri); return false; }); /* change graphs */ $(".graph-buttons a").click(function() { var time = $(this).data("graph-time"); $(".graph-images img").each(function() { var src = $(this).prop("src"); var new_src = src.substring(0, src.lastIndexOf("/") + 1) + time; $(this).prop("src", new_src); }); // change the buttons too $(".graph-buttons a").removeClass("btn-primary").addClass("btn-default"); $(this).removeClass("btn-default").addClass("btn-primary"); return false; }); // vm migrate select for node $(document).on("click", "#vm-migrate-node-list li", function(e) { var li = $(this).closest('li'); if (li.find('input').attr('disabled')) return true; $('#vm-migrate-node-list li').removeClass('panel-primary'); li.addClass('panel-primary').find('input').prop("checked", true); return true; }); }); function generateVmHTML(data, is_last) { return '' + '' + ' ' + safe_tags_replace(data.name) + '' + ' ' + data.host + '' + '' + (data.fav ? '' : '' ) + '' + '' + ''; } function generateGroupHTML(data, is_last) { return ''+ ' '+ safe_tags_replace(data.name) + ''; } function generateUserHTML(data, is_last) { return ''+ ' '+ safe_tags_replace(data.name) + '' + '' + ' ' + (data.org_id ? safe_tags_replace(data.org_id) : "") + '' + ''; } function generateTemplateHTML(data, is_last) { return ''+ ' ' + ' '+ safe_tags_replace(data.name) + ' ' + ' ' + safe_tags_replace(data.system) + '' + ' ' + ''; } function generateNodeHTML(data, is_last) { return '' + '' + ' ' + safe_tags_replace(data.name) + '' + '' + ''; } /* copare vm-s by fav, pk order */ function compareVmByFav(a, b) { if(a.fav && b.fav) { return a.pk < b.pk ? -1 : 1; } else if(a.fav && !b.fav) { return -1; } else if(!a.fav && b.fav) { return 1; } else return a.pk < b.pk ? -1 : 1; } $(document).on('shown.bs.tab', 'a[href="#resources"]', function (e) { $(".cpu-priority-input").trigger("change"); $(".cpu-count-input, .ram-input").trigger("input"); }); function addSliderMiscs() { // set max values based on inputs var cpu_count_range = "0, " + $(".cpu-count-input").prop("max"); var ram_range = "0, " + $(".ram-input").prop("max"); $(".cpu-count-slider").data("slider-range", cpu_count_range); $(".ram-slider").data("slider-range", ram_range); $(".vm-slider").simpleSlider(); $(".cpu-priority-slider").bind("slider:changed", function (event, data) { var value = data.value + 0; $('.cpu-priority-input option[value="' + value + '"]').attr("selected", "selected"); }); $(".cpu-priority-input").change(function() { var val = $(":selected", $(this)).val(); $(".cpu-priority-slider").simpleSlider("setValue", val); }); $(".cpu-count-slider").bind("slider:changed", function (event, data) { var value = data.value + 0; $(".cpu-count-input").val(parseInt(value)); }); $(".cpu-count-input").bind("input", function() { var val = parseInt($(this).val()); if(!val) return; $(".cpu-count-slider").simpleSlider("setValue", val); }); var ram_fire = false; $(".ram-slider").bind("slider:changed", function (event, data) { if(ram_fire) { ram_fire = false; return; } var value = data.value + 0; $(".ram-input").val(value); }); $(".ram-input").bind("input", function() { var val = $(this).val(); ram_fire = true; $(".ram-slider").simpleSlider("setValue", parseInt(val)); }); setDefaultSliderValues(); $(".cpu-priority-slider").simpleSlider("setDisabled", $(".cpu-priority-input").prop("disabled")); $(".cpu-count-slider").simpleSlider("setDisabled", $(".cpu-count-input").prop("disabled")); $(".ram-slider").simpleSlider("setDisabled", $(".ram-input").prop("disabled")); } function setDefaultSliderValues() { $(".cpu-priority-input").trigger("change"); $(".ram-input, .cpu-count-input").trigger("input"); } function addMessage(text, type) { $('body').animate({scrollTop: 0}); div = '' + text + ''; $('.messagelist').html('').append(div); var div = $('.messagelist div').fadeIn(); setTimeout(function() { $(div).fadeOut(); }, 9000); } function addModalConfirmation(func, data) { $.ajax({ type: 'GET', url: data.url, data: jQuery.param(data.data), success: function(result) { $('body').append(result); $('#confirmation-modal').modal('show'); $('#confirmation-modal').on('hidden.bs.modal', function() { $('#confirmation-modal').remove(); }); $('#confirmation-modal-button').click(function() { func(data); $('#confirmation-modal').modal('hide'); }); } }); } function clientInstalledAction(location) { setCookie('downloaded_client', true, 365 * 24 * 60 * 60 * 1000, "/"); window.location.href = location; $('#confirmation-modal').modal("hide"); } function setCookie(name, value, seconds, path) { if (seconds !== null) { var today = new Date(); var expire = new Date(); expire.setTime(today.getTime() + seconds); document.cookie = name+"="+escape(value)+"; expires="+expire.toUTCString()+"; path="+path; } } /* no js compatibility */ function noJS() { $('.no-js-hidden').show(); $('.js-hidden').hide(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } // for AJAX calls /** * Getter for user cookies * @param {String} name Cookie name * @return {String} Cookie value */ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken")); } } }); /* for autocomplete */ $(function() { yourlabs.TextWidget.prototype.getValue = function(choice) { return choice.children().html(); }; }); var tagsToReplace = { '&': '&', '<': '<', '>': '>' }; function replaceTag(tag) { return tagsToReplace[tag] || tag; } function safe_tags_replace(str) { return str.replace(/[&<>]/g, replaceTag); } $(function () { var closed = JSON.parse(getCookie('broadcast-messages')); $('.broadcast-message').each(function() { var id = $(this).data('id'); if (closed && closed.indexOf(id) != -1) { $(this).remove(); } }); $('.broadcast-message').on('closed.bs.alert', function () { var closed = JSON.parse(getCookie('broadcast-messages')); if (!closed) { closed = []; } closed.push($(this).data('id')); setCookie('broadcast-messages', JSON.stringify(closed), 7 * 24 * 60 * 60 * 1000, "/"); }); $("#id_message").on('input', function() { $('.broadcast-message').html($(this).val()); }); $("#id_effect").on('input', function() { $('.broadcast-message').removeClass( 'alert-info alert-warning alert-success alert-danger').addClass( "alert-" + $(this).val()); }); }); /* select all in template list */ $(function() { $("#manage-access-select-all").click(function(e) { var inputs = $(this).closest("table").find('input[type="checkbox"]'); inputs.prop("checked", !inputs.prop("checked")); }); }); dashboard.less 0000664 0000000 0000000 00000064271 13126740172 0036223 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/static/dashboard /* Move down content because we have a fixed navbar that is 50px tall */ body { padding-top: 50px; padding-bottom: 20px; margin-bottom: 30px; /* sticky footer */ } html { position: relative; min-height: 100%; } .navbar-nav img { width: 46px; height: 46px; margin-top: -4px; } .profile-avatar { width: 24px; height: 24px; } .navbar-fixed-top { border: 0px; } /* Set widths on the navbar form inputs since otherwise they're 100% wide */ .navbar-form input[type="text"], .navbar-form input[type="password"] { width: 180px; } /* Wrapping element */ /* Set some basic padding to keep content from hitting the edges */ .body-content { padding-left: 15px; padding-right: 15px; } /* --- */ #dashboard-menu > li > a { color: white; font-size: 10px; } #dashboard-menu { margin-right: 0px; } /* we need this for mobile view */ .container > :first-child { margin-top: 15px; } /* Responsive: Portrait tablets and up */ @media screen and (min-width: 768px) { /* Let the jumbotron breathe */ .container > :first-child { margin-top: 20px; } /* Remove padding from wrapping element since we kick in the grid classes here */ .body-content { padding: 0; } .navbar-nav > li > a { padding-top: 12.5px; padding-bottom: 12.5px; } #dashboard-menu > li:last-child > a { padding: 4px 0 0 0; } } .no-margin { margin: 0!important; } .list-group .list-group-footer { height: 41px; } .list-group-footer .text-right { padding-top: 4px; } .big { font-size: 2em; } .bigbig { font-size: 3em; } .timeline { border-left: 4px #428bca solid; margin-left: 20px; padding-left: 20px; } .timeline > div { margin: 0; padding: 0; margin-bottom: .5em; line-height: 24px; } .timeline > div:last-child { margin-bottom: 0; } .timeline .timeline-icon { margin-left: -34px; padding: 0; width: 24px; height: 24px; text-align: center; display: inline-block; border-radius: 50%; background-color: #428bca; color: #fff; } .timeline .activity-active .timeline-icon { background-color: black!important; } .timeline img{ border-radius: 50%; margin-bottom: 2px; } .timeline a { color: black; } .timeline-icon.timeline-warning { border-color: #c09853; border-style: solid; border-width: 2px; background-color: white; color: #c09853; line-height: 20px; } .timeline .timeline-icon.timeline-nobg { background-color: transparent; } .sub-timeline { } .sub-activity { margin-left: -4px; padding-left: 10px; border-left: 3px solid green; } .sub-activity-active { border-left: 8px solid black; } .sub-activity-failed { border-left: 3px solid #d9534f; } .timeline-icon-failed { background-color: #d9534f !important; } .table-with-form-fields tbody tr td { line-height: 34px; } #vm-detail-panel .panel-body { min-height: 20em; } #node-detail-panel .panel-body { min-height: 20em; } #group-detail-panel .panel-body { min-height: 20em; } :link i:before:hover { text-decoration: none !important; } .rule-table tr >:nth-child(1) { text-align: right; } .rule-table tr >:nth-child(2) { text-align: center; } .dashboard-index .panel { height: 294px; } #vm-details-rename, #vm-details-h1-name, #vm-details-rename , #node-details-rename, #node-details-rename *, #node-details-h1-name, #node-list-rename, #node-list-rename *#group-details-rename, #group-details-rename *, #group-details-h1-name, #group-list-rename, #group-list-rename * { display: inline; } #vm-details-rename, #vm-list-rename, #node-details-rename, #node-list-rename, #group-details-rename, #group-list-rename { display: none; } #group-details-rename-form { display: inline-block; } .vm-details-home-name, #group-details-rename-form .input-group { max-width: 401px; } #node-details-rename-name { max-width: 160px; } #vm-list-rename-name, #node-list-rename-name, #group-list-rename-name { max-width: 150px; } .label-tag { /* pass */ } #vm-details-tags-form, #node-details-traits-form { margin-top: 15px; max-width: 250px; } .vm-details-remove-tag, .node-details-remove-trait { color: white; padding-left: 5px; } .vm-details-remove-tag:hover, .node-details-remove-trait:hover { cursor: pointer; color: black; text-decoration: none; } /* small buttons for tags, copied from Bootstraps input-sm, bnt-sm */ .btn-tags, .btn-traits { padding: 3px 6px; font-size: 11px; line-height: 1.5; border-radius: 3px; } .input-tags, .input-tratis { height: 22px; padding: 2px 8px; font-size: 11px; line-height: 1.5; border-radius: 3px; } /* --- */ .vm-details-remove-port:hover { text-decoration: none; } /* arrow in port add table */ #ipv4 tbody td:nth-child(2), #ipv6 tbody td:nth-child(2) { width: 60px; } /* port add buttons */ .vm-details-network-port-add .input-group-addon, .vm-details-network-port-add .input-group-btn { width: inherit ; } /* vm-create */ a.hover-black { color:white; } .hover-black:hover { color: black; /*#d9534f*/ text-decoration: none; } .no-js-hidden { display: none; } #vm-create-network-addcheckbox-managed { -webkit-transform: scale(1.3, 1.3); margin-top: 4px; } /* --- */ .interval-input { margin-bottom: 20px; max-width: 600px; } .interval-input input { text-align: right; } /* vm details connection */ .vm-details-connection dd { padding: 4px 0 4px 0; margin-left: 160px; } .vm-details-connection dt { text-align: left; padding: 4px 0 4px 15px; } #vm-details-pw-confirm { margin-top: 10px; display: none; } #vm-details-pw-confirm dt { text-align: right; } .dashboard-vm-details-network-h3 { margin-top: 20px; } /* font awesome font */ .font-awesome-font { font-family: "FontAwesome"; } .template-list-table tbody>tr>td, .template-list-table thead>tr>th, .lease-list-table tbody>tr>td, .lease-list-table thead>tr>th { vertical-align: middle; text-align: center; } .template-list-table td:nth-child(1), .lease-list-table td:nth-child(1) { text-align: left; } .template-list-table-thin { width: 100px; } .nojs-dropdown-menu { position:absolute; display:none; z-index: 1; } .nojs-dropdown-toggle:focus + .nojs-dropdown-menu { display: block; } .nojs-dropdown-toggle:focus { outline:none; } .nojs-dropdown-menu:hover { display: block; } #notification-messages { padding: 10px 8px; width: 350px; right: 0; left: auto; } .notification-message { margin-bottom: 10px; padding: 0 0 4px 0; border-bottom: 1px dotted #D3D3D3; } #notification-messages .notification-message:last-child { margin-bottom: 0px; padding: 0px; border-bottom: none; } .notification-message-text { padding: 8px 15px; display: none; } .notification-message .notification-message-subject { cursor: pointer; } #notification-button a.dropdown-toggle { color: white; font-size: 12px; } #vm-migrate-node-list { list-style: none; } #vm-migrate-node-list li { padding-bottom: 10px; } .vm-migrate-node-property { display: block; padding-left: 15px; } .vm-details-help { max-width: 700px; padding: 10px 10px 0px 10px; margin-left: 50px; /* fancy stuff border: 1px solid #ccc; box-shadow: 0 0 10px rgba(0,0,0,0.2); border-radius: 8px; */ } .vm-details-help li { padding-bottom: 5px; } .vm-details-help ul { padding-left: 0px; } /* footer */ footer { position: absolute; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 30px; background-color: #101010; color: white; font-size: 13px; padding: 5px 5px 0 5px; box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); text-align: center; } footer a, footer a:hover, footer a:visited { color: white; text-decoration: underline; } .template-disk-list { list-style: none; padding-left: 0; } .template-disk-list li { padding-bottom: 5px; } #node-info-pane { margin-bottom: 20px; } .template-choose-list { max-width: 600px; } .template-choose-list-element small { display: none; float: right; padding-right: 50px; } .template-choose-list-element { padding: 6px 10px; cursor: pointer; margin-bottom: 15px; /* bootstrap panel default is 20px */ } .template-choose-list input[type="radio"] { float: right; } /* template create vm help */ .alert-new-template { background: #3071a9; color: white; font-size: 22px; } .alert-new-template ol { margin-left: 25px; } /* bootstrap tour */ .tour-template { max-width: 400px; min-width: 270px; font-size: 16px; } .tour-template { text-align: justify; } .tour-template .popover-title { font-weight: bold; } #vm-details-resources-form { padding: 5px; /* it's nice this way in the tour */ } #dashboard-vm-list a small { padding-left: 10px; } .index-template-list-name { display: inline-block; max-width: 50%; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; float: left; } #dashboard-template-list a small { max-width: 45%; float: left; padding-top: 2px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; padding-left: 10px; } #vm-details-home-description { display: inline-block; position: relative; } #vm-details-home-description textarea { min-width: 240px; min-height: 250px; } .vm-details-home-edit-description-click, .vm-details-home-edit-name-click { cursor: pointer; } .vm-details-description-submit { position: absolute; bottom: 10px; right: 20px; } .vm-list-table th i { margin-top: 3px; } .table-sorting { display: none; } #ops { padding: 15px 0 15px 15px; } #vm-access-table th:last-child, #vm-access-table td:last-child, #template-access-table th:last-child, #template-access-table td:last-child { text-align: center; } #notifications-button { margin: 0; } #dashboard-vm-list, #dashboard-node-list, #dashboard-group-list, #dashboard-template-list, #dashboard-files-toplist, #dashboard-user-list { min-height: 200px; } #group-detail-user-table td:first-child, #group-detail-user-table th:last-child, #group-detail-user-table td:last-child, #group-detail-perm-table td:first-child, #group-detail-perm-table th:last-child, #group-detail-perm-table td:last-child { text-align: center; width: 100px; } #group-detail-user-table tr:last-child td:nth-child(2) { text-align: left; } #group-detail-perm-header { margin-top: 25px; } textarea[name="new_members"] { max-width: 500px; min-height: 80px; margin-bottom: 10px; } /* 2px border bottom for all bootstrap tables */ .table thead>tr>th { border-bottom: 1px; } .badge-pulse { -webkit-animation-name: 'pulse_animation'; -webkit-animation-duration: 1000ms; -webkit-transform-origin: 70% 70%; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; } @-webkit-keyframes pulse_animation { 0% { -webkit-transform: scale(1); } 30% { -webkit-transform: scale(1); } 40% { -webkit-transform: scale(1.18); } 50% { -webkit-transform: scale(1); } 60% { -webkit-transform: scale(1); } 70% { -webkit-transform: scale(1.08); } 80% { -webkit-transform: scale(1); } 100% { -webkit-transform: scale(1); } } .btn-toolbar { margin-bottom: 5px; } #vm-console-screenshot { display: none; } /* vm list css */ .vm-list-selected, .vm-list-selected td { background-color: #e8e8e8 !important; } .vm-list-selected:hover, .vm-list-selected:hover td { background-color: #d0d0d0 !important; } .vm-list-selected td:first-child { font-weight: bold; } .vm-list-table-thin { width: 10px; } .vm-list-table-admin { width: 130px; } .vm-details-connection-string-copy, #vm-details-pw-show { cursor: pointer; } .dashboard-profile-vm-list, .dashboard-profile-group-list { list-style: none; padding-left: 28px; } .dashboard-profile-vm-list, .dashboard-profile-group-list { a, a:hover { text-decoration: none; color: #555; } } #group-detail-user-table td:nth-child(2) a, #group-detail-perm-table td:nth-child(2) a, #template-access-table td:nth-child(2) a, #vm-access-table td:nth-child(2) a, .no-style-link, .no-style-link:hover { color: #555 !important; text-decoration: none; } #dashboard-profile-avatar { max-width: 200px; } .dashboard-vm-details-connect-command { /* for mobile view */ padding-bottom: 20px; } #store-list-list { list-style: none; } .store-list-item { cursor: pointer; } .store-list-item:hover { background: rgba(0, 0, 0, 0.6); } .store-list-item-icon { width: 20px; text-align: center; display: inline-block; margin-right: 15px; float: left; } .store-list-item-size { width: 70px; text-align: right; float: right; } .store-list-file-infos { padding: 15px; display: none; border-left: 1px solid #ddd; border-right: 1px solid #ddd; position: relative; } .store-list-item-new { display: inline-block; } .store-list-item-new .badge { margin-left: 5px; background: #5bc0dc; } .store-list-item-icon-directory { color: #ff8c00; } .store-remove-button { margin-top: 8px; } #dashboard-files-toplist { div.list-group-item { color: #555; height: 41px; &:hover { background: #eee; } } } .store-list-item-name { max-width: 70%; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; float: left; } .dashboard-toplist-icon { float: left; padding: 2px 5px 0 0; } .no-hover:hover { background: none !important; } #group-detail-permissions .filtered { margin: 2px 0; padding: 2px 3px; vertical-align: middle; font-family: "Lucida Grande", Verdana, Arial, sans-serif; font-weight: normal; font-size: 11px; border: 1px solid #ccc; } #group-detail-permissions .selector-available h2, #group-detail-permissions .selector-chosen h2 { margin: 0; padding: 5px 8px 5px 8px; font-size: 12px; text-align: left; font-weight: bold; background: #7CA0C7; color: white; } #group-detail-user-table { margin-top: 20px; } #group-detail-permissions input[type="submit"]{ margin-top: -6px; } .store-action-button { margin-left: 5px; } #progress-marker-hard { border-top-right-radius: 4px; border-bottom-right-radius: 4px; right: 0; background: red; } .progress-marker { width: 6px; height: 20px; position: absolute; } #show-all-activities-container { margin: 20px 0 0 10px; } #vm-details-resources-form { margin-top: 15px; } #vm-details-resources-form .row, .resources-sliders .row { margin-bottom: 15px; } #vm-create-disk-add-form { max-width: 450px; margin-top: 15px; } .vm-create-template { max-width: 800px; border: 1px solid black; border-bottom: none; } .vm-create-template-list .vm-create-template:last-child { border-bottom: 1px solid black; } .vm-create-template-summary { padding: 15px; cursor: pointer; } .vm-create-template:nth-child(odd) .vm-create-template-summary { background: #F5F5F5; } .vm-create-template-list .vm-create-template-summary:hover { background: #D2D2D2; } .vm-create-template-details { border-top: 1px dashed #D3D3D3; padding: 15px; } .vm-create-template-details ul { list-style: none; padding: 0 15px; } .vm-create-template-details li { border-bottom: 1px dotted #aaa; padding: 5px 0px; } #profile-key-list-table td:last-child, #profile-key-list-table th:last-child, #profile-command-list-table td:last-child, #profile-command-list-table th:last-child, #profile-command-list-table td:nth-child(2), #profile-command-list-table th:nth-child(2) { text-align: center; vertical-align: middle; } #vm-list-table .migrating-icon { -webkit-animation: passing 2s linear infinite; animation: passing 2s linear infinite; } @-webkit-keyframes passing { 0% { -webkit-transform: translateX(50%); transform: translateX(50%); opacity: 0; } 50% { -webkit-transform: translateX(0%); transform: translateX(0%); opacity: 1; } 100% { -webkit-transform: translateX(-50%); transform: translateX(-50%); opacity: 0; } } @keyframes passing { 0% { -webkit-transform: translateX(50%); -ms-transform: translateX(50%); transform: translateX(50%); opacity: 0; } 50% { -webkit-transform: translateX(0%); -ms-transform: translateX(0%); transform: translateX(0%); opacity: 1; } 100% { -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); opacity: 0; } } .mass-migrate-node { cursor: pointer; } .mass-op-panel { padding: 6px 10px; } .mass-op-panel .check { color: #449d44; } .mass-op-panel .minus { color: #d9534f; } .mass-op-panel .status-icon { font-size: .8em; } #vm-list-search, #vm-mass-ops { margin-top: 8px; } .list-group-item { border-bottom: 0px !important; } .list-group-item-last { border-bottom: 1px solid #ddd !important; } .slider { display: inline-block; } .slider .track { height: 20px; top: 50%; } .slider > .dragger, .slider > .dragger:hover { border-radius: 0px; -moz-border-radius: 0px; -webkit-border-radius: 0px; width: 8px; height: 24px; margin-top: -12px!important; text-shadow: 0 1px 0 #fff; background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#3071a9)); background-image: -webkit-linear-gradient(top, #428bca, 0%, #3071a9, 100%); background-image: -moz-linear-gradient(top, #428bca 0%, #3071a9 100%); background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%); background-repeat: repeat-x; border-color: #2d6ca2; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0); } .slider > .dragger:hover { background-color: #3071a9; background-image: none; border-color: #2d6ca2; } .slider > .highlight-track { height: 20px; top: 50%; } .slider > .track, .slider > .highlight-track { border-radius: 5px; } .slider { width: 100%; } #vm-list-search-checkbox { margin-top: -1px; display: inline-block; vertical-align: middle; } #vm-list-search-checkbox-span { cursor: pointer } #vm-details-resources-disk { padding: 2px 5px 10px 5px; } #vm-details-start-template-tour { margin-right: 5px; } #vm-activity-state { margin-bottom: 15px; } .autocomplete-hl { color: #b20000; font-weight: bold; } .hilight .autocomplete-hl { color: orange; } .introjs-skipbutton { color: #333; } .introjs-button:focus { text-decoration: none; color: #333; outline: none; } .introjs-button:hover:not(.introjs-disabled) { color: #428bca; } .introjs-tooltip { min-width: 250px; } #vm-info-pane { margin-bottom: 20px; } .node-list-table tbody>tr>td, .node-list-table thead>tr>th { vertical-align: middle; } .node-list-table thead>tr>th, .node-list-table .enabled, .node-list-table .priority, .node-list-table .overcommit, .node-list-table .number_of_VMs { text-align: center; } .node-list-table-thin { width: 10px; } .node-list-table-monitor { width: 250px; } .graph-images img { max-width: 100%; } #vm-list-table td.state, #vm-list-table td.memory { white-space: nowrap; } #vm-list-table td { vertical-align: middle; } .disk-resize-btn { margin-right: 5px; } #vm-migrate-node-list li { cursor: pointer; } .group-list-table .actions, .group-list-table .admin, .group-list-table .number_of_users, .group-list-table .pk { width: 1px; white-space: nowrap; text-align: center; } .vm-create-list-name { display: inline-block; max-width: 60%; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; float: left; } .vm-create-list-system { display: inline-block; max-width: 40%; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; float: right; } /* for introjs * newer version has this fixed * but it doesn't work w bootstrap 3.2.0 */ .introjs-helperLayer *, .introjs-helperLayer *:before, .introjs-helperLayer *:after { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; -ms-box-sizing: content-box; -o-box-sizing: content-box; box-sizing: content-box; } .node-list-table .monitor { .progress { position: relative; width: 150px; height: 16px; margin-bottom: 4px; margin-top: 0px; background-image: linear-gradient(to bottom, #BBEBEB 0px, #F5F5F5 100%); } .progress-bar-text { position: absolute; top: -1px; display: block; width: 100%; color: white; /* outline */ text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; font-size: 13px; } } .infobtn { cursor: help; &:hover { background-position: 0 0px; } } #dashboard-vm-list { .list-group-item { display: flex; } .index-vm-list-name, .index-vm-list-host { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } .index-vm-list-name { max-width: 70%; } .index-vm-list-host { padding-top: 3px; flex: 1; } } #dashboard-user-list { .list-group-item { display: flex; } .index-user-list-name, .index-user-list-org { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } .index-user-list-name { max-width: 80%; } .index-user-list-org { padding-left: 5px; flex: 1; } } .fa-fw-12 { /* fa-fw is too wide */ width: 12px; } .btn-op-form-send { padding: 6px 12px 6px 8px; } @media (max-width: 767px) { #vm-detail-panel .graph-buttons { padding-top: 15px; } .graph-buttons a { margin-bottom: 8px; } #ops .operation { margin-bottom: 5px; } .vm-details-connection dd { margin-left: 25px; } .vm-details-connection dt { padding-left: 0px; } } #notifications-upper-pagination { margin-top: 4px; } #notifications-bottom-pagination { * { display: inline-block; } a { font-size: 20px; &:hover { text-decoration: none; } } .page-numbers { padding: 25px; } } .pagination { width: 100%; } #empty-vm-help { position: absolute; bottom: 70px; right: 30px; color: #101010; text-align: right; i { padding-right: 10px; } } #vm-detail-successful-boot { margin-bottom: 20px; display: none; .label { width: 100%; display: block; overflow: hidden; text-overflow: ellipsis; } } #vm-detail-access-help { background: #f9f9f9; margin-top: 20px; } #vm-renew-request-lease, #vm-request-resource-form { display: none; } .label-100 { display: block; width: 100%; } #modify-the-resources { font-size: 18px; display: none; } #vm-request-resource-form textarea { max-width: 500px; height: 150px; } #disk-list-table { td:last-child { text-align: center; } } /* help page */ .help-tabs li { width: 50%; text-align: center; } // note: padding-margin hack to skip banner on anchor #help-tab-content { h1, h2, h3, h4, h5 { font-weight: bold; padding-top: 55px; margin-top: -55px; } blockquote { background-color:#dfe4e4; } } #wrapper { position: fixed; padding-left: 0px; background: #252525; left: 0px; top: 46px; height: 100%; width: 210px; transition: all .4s ease 0s; /* Firefox */ height: -moz-calc(100% - 130px); /* WebKit */ height: -webkit-calc(100% - 120px); /* Opera */ height: -o-calc(100% - 110px); /* Standard */ height: calc(100% - 130px); } #sidebar-wrapper { margin-left: 0px; left: 0px; top: inherit; bottom: 30px; width: inherit; position: inherit; z-index: 10000; transition: all .4s ease 0s; overflow: auto; overflow-x: hidden; overflow-y: auto; } #sidebar-wrapper ul { display: block; float: left; list-style: none; margin: 0; padding: 0px; } #sidebar-wrapper a { font-family: "proxima-nova", 'Helvetica Neue', 'Helvetica', 'sans-serif'; color: #ddd; display: block; float: left; width: 200px; text-decoration: none; background: #252525; border-top: 1px solid #333; border-bottom: 1px solid #222; -webkit-transition: background .5s; -moz-transition: background .5s; -o-transition: background .5s; -ms-transition: background .5s; transition: background .5s; } #sidebar-wrapper ul a{ padding-top: 10px; padding-bottom: 10px; padding-left: 10px; font-size: larger; } #sidebar-wrapper li a{ padding-top: 6px; padding-bottom: 6px; padding-left: 20px; padding-right: 6px; font-size: smaller; } #sidebar-wrapper ul ul a{ padding-top: 10px; padding-bottom: 10px; padding-left: 16px; font-size: larger; } #sidebar-wrapper li li a{ padding-top: 6px; padding-bottom: 6px; padding-left: 24px; padding-right: 6px; font-size: smaller; } #sidebar-wrapper li a:hover, #sidebar-wrapper ul a:hover{ color: #fff; background: rgba(200,200,255,0.15); text-decoration: none; } #page-content { margin-left: 200px; } @media only screen and (max-width: 600px) { #wrapper { -webkit-transform: translateX(-250px); -moz-transform: translateX(-250px); -o-transform: translateX(-250px); -ms-transform: translateX(-250px); transform: translateX(-250px); } #page-content { margin-left: 0px; -webkit-transition: background .5s; -moz-transition: background .5s; -o-transition: background .5s; -ms-transition: background .5s; transition: background .5s; } } .overview_href { cursor: pointer; } #request-buttons { form { display: inline; } textarea { resize: none; min-height: 80px; } } .nowrap { white-space: nowrap; } .little-margin-bottom { margin-bottom: 5px; } .broadcast-message { margin-bottom: 5px; padding-top: 5px; padding-bottom: 5px; } .acl-table td:first-child { text-align: center; } #resize-help { table { background-color: #f5f5f5; } .panel { padding: 2px 20px; background-color: #f5f5f5; margin: 20px 0px; } ol li { margin-top: 15px; } img { display: block; margin: 15px 0 5px 0; } pre { margin-top: 5px; } hr { margin: 50px 0; } } #vm-details-resize-how-to { font-size: 1.5em; text-align: center; width: 100%; } #manage-access-select-all { cursor: pointer; } #two-factor-qr { text-align: center; span, small { display: block; } } #two-factor-confirm { text-align: center; button { margin-left: 15px; } } #two-factor-box { .help-block { display: block; } h4 { margin: 0; } hr { margin: 15px 0 2px 0; } } #datastore-chart-legend { width: 350px; margin-top: 100px; margin-left: -120px; /* Landscape phones and down */ @media (max-width: 992px) { margin-left: -25px; } ul { list-style: none; } li { font-size: 18px; margin-bottom: 2px; span { display: inline-block; width: 30px; height: 18px; margin-right: 8px; } } } datastore-details.js 0000664 0000000 0000000 00000001653 13126740172 0037346 0 ustar 00root root 0000000 0000000 cloud-dc7f79241923e9e204adb940ffdf69c915067933-dc7f79241923e9e204adb940ffdf69c915067933/circle/dashboard/static/dashboard $(function() { var data = JSON.parse($("#chart-data").data("data")); var labels = []; for(var i=0; i