From: Peter Amstutz Date: Fri, 16 Jan 2015 19:05:48 +0000 (-0500) Subject: Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5' X-Git-Tag: 1.1.0~1814^2~17 X-Git-Url: https://git.arvados.org/arvados.git/commitdiff_plain/964ab3dd90ff1508efc0c77378cde2b3a4da1029?hp=f9732ad8460d013c2f28363655d0d1b91894dca5 Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5' git-subtree-dir: apps/arv-web git-subtree-mainline: b97ac7f96234cbbb491bdbaade840ab50802f357 git-subtree-split: f9732ad8460d013c2f28363655d0d1b91894dca5 --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..8cc6b89324 --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +.bundle +.rvmrc +*~ +*.pyc +docker/*/generated +docker/config.yml +doc/.site +doc/sdk/python/arvados +sdk/perl/MYMETA.* +sdk/perl/Makefile +sdk/perl/blib +sdk/perl/pm_to_blib +*/vendor/bundle +sdk/java/target +*.class +apps/workbench/vendor/bundle +services/api/vendor/bundle +sdk/java/log +sdk/cli/vendor diff --git a/COPYING b/COPYING new file mode 100644 index 0000000000..4006e686da --- /dev/null +++ b/COPYING @@ -0,0 +1,11 @@ +Server-side components of Arvados contained in the apps/ and services/ +directories, including the API Server, Workbench, and Crunch, are licenced +under the GNU Affero General Public License version 3 (see agpl-3.0.txt) + +The Arvados client Software Development Kits contained in the sdk/ directory, +example scripts in the crunch_scripts/ directory, and code samples in the +Aravados documentation are licensed under the Apache License, Version 2.0 (see +LICENSE-2.0.txt) + +The Arvados Documentation located in the doc/ directory is licensed under the +Creative Commons Attribution-Share Alike 3.0 United States (see by-sa-3.0.txt) \ No newline at end of file diff --git a/LICENSE-2.0.txt b/LICENSE-2.0.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/LICENSE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README b/README index 826092d447..c7a36c355b 100644 --- a/README +++ b/README @@ -1,28 +1,21 @@ -Run a web service from Arvados. +Welcome to Arvados! -usage: arv-web.py [-h] --project PROJECT [--port PORT] --image IMAGE +The main Arvados web site is + https://arvados.org -optional arguments: - -h, --help show this help message and exit - --project PROJECT Project to watch - --port PORT Local bind port - --image IMAGE Docker image to run +The Arvados public wiki is located at + https://arvados.org/projects/arvados/wiki +The Arvados public bug tracker is located at + https://arvados.org/projects/arvados/issues -This queries an Arvados project and FUSE mounts the most recently modified -collection into a temporary directory. It then runs the supplied Docker image -with the collection bind mounted to /mnt inside the container. +For support see + http://doc.arvados.org/user/getting_started/community.html -When a new collection is added to the project, or an existing project is -updated, it will detect the change, it will stop the running Docker container, -unmount the old collection, mount the new most recently modified collection, -and restart the Docker container with the new mount. +Installation documentation is located at + http://doc.arvados.org/install -The supplied Dockerfile builds a Docker image that runs Apache with /mnt as the -DocumentRoot. It is configured to run web applications based on Python WSGI, -Ruby Rack, CGI, to serve static HTML, or simply browse the contents of the -/public subdirectory of the collection using Apache's default index pages. +If you wish to build the documentation yourself, follow the instructions in +doc/README to build the documentation, then consult the "Install Guide". -To build the Docker image: - -$ docker build -t arvados/arv-web . +See COPYING for information about Arvados Free Software licenses. diff --git a/agpl-3.0.txt b/agpl-3.0.txt new file mode 100644 index 0000000000..dba13ed2dd --- /dev/null +++ b/agpl-3.0.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/Dockerfile b/apps/arv-web/Dockerfile similarity index 100% rename from Dockerfile rename to apps/arv-web/Dockerfile diff --git a/apps/arv-web/README b/apps/arv-web/README new file mode 100644 index 0000000000..826092d447 --- /dev/null +++ b/apps/arv-web/README @@ -0,0 +1,28 @@ +Run a web service from Arvados. + +usage: arv-web.py [-h] --project PROJECT [--port PORT] --image IMAGE + +optional arguments: + -h, --help show this help message and exit + --project PROJECT Project to watch + --port PORT Local bind port + --image IMAGE Docker image to run + + +This queries an Arvados project and FUSE mounts the most recently modified +collection into a temporary directory. It then runs the supplied Docker image +with the collection bind mounted to /mnt inside the container. + +When a new collection is added to the project, or an existing project is +updated, it will detect the change, it will stop the running Docker container, +unmount the old collection, mount the new most recently modified collection, +and restart the Docker container with the new mount. + +The supplied Dockerfile builds a Docker image that runs Apache with /mnt as the +DocumentRoot. It is configured to run web applications based on Python WSGI, +Ruby Rack, CGI, to serve static HTML, or simply browse the contents of the +/public subdirectory of the collection using Apache's default index pages. + +To build the Docker image: + +$ docker build -t arvados/arv-web . diff --git a/apache2_foreground.sh b/apps/arv-web/apache2_foreground.sh similarity index 100% rename from apache2_foreground.sh rename to apps/arv-web/apache2_foreground.sh diff --git a/apache2_vhost b/apps/arv-web/apache2_vhost similarity index 100% rename from apache2_vhost rename to apps/arv-web/apache2_vhost diff --git a/arv-web.py b/apps/arv-web/arv-web.py similarity index 100% rename from arv-web.py rename to apps/arv-web/arv-web.py diff --git a/sample-cgi-app/public/.htaccess b/apps/arv-web/sample-cgi-app/public/.htaccess similarity index 100% rename from sample-cgi-app/public/.htaccess rename to apps/arv-web/sample-cgi-app/public/.htaccess diff --git a/sample-cgi-app/public/index.cgi b/apps/arv-web/sample-cgi-app/public/index.cgi similarity index 100% rename from sample-cgi-app/public/index.cgi rename to apps/arv-web/sample-cgi-app/public/index.cgi diff --git a/sample-cgi-app/tmp/.keepkeep b/apps/arv-web/sample-cgi-app/tmp/.keepkeep similarity index 100% rename from sample-cgi-app/tmp/.keepkeep rename to apps/arv-web/sample-cgi-app/tmp/.keepkeep diff --git a/sample-rack-app/config.ru b/apps/arv-web/sample-rack-app/config.ru similarity index 100% rename from sample-rack-app/config.ru rename to apps/arv-web/sample-rack-app/config.ru diff --git a/sample-rack-app/public/.keepkeep b/apps/arv-web/sample-rack-app/public/.keepkeep similarity index 100% rename from sample-rack-app/public/.keepkeep rename to apps/arv-web/sample-rack-app/public/.keepkeep diff --git a/sample-rack-app/tmp/.keepkeep b/apps/arv-web/sample-rack-app/tmp/.keepkeep similarity index 100% rename from sample-rack-app/tmp/.keepkeep rename to apps/arv-web/sample-rack-app/tmp/.keepkeep diff --git a/sample-static-page/public/index.html b/apps/arv-web/sample-static-page/public/index.html similarity index 100% rename from sample-static-page/public/index.html rename to apps/arv-web/sample-static-page/public/index.html diff --git a/sample-static-page/tmp/.keepkeep b/apps/arv-web/sample-static-page/tmp/.keepkeep similarity index 100% rename from sample-static-page/tmp/.keepkeep rename to apps/arv-web/sample-static-page/tmp/.keepkeep diff --git a/sample-wsgi-app/passenger_wsgi.py b/apps/arv-web/sample-wsgi-app/passenger_wsgi.py similarity index 100% rename from sample-wsgi-app/passenger_wsgi.py rename to apps/arv-web/sample-wsgi-app/passenger_wsgi.py diff --git a/sample-wsgi-app/public/.keepkeep b/apps/arv-web/sample-wsgi-app/public/.keepkeep similarity index 100% rename from sample-wsgi-app/public/.keepkeep rename to apps/arv-web/sample-wsgi-app/public/.keepkeep diff --git a/sample-wsgi-app/tmp/.keepkeep b/apps/arv-web/sample-wsgi-app/tmp/.keepkeep similarity index 100% rename from sample-wsgi-app/tmp/.keepkeep rename to apps/arv-web/sample-wsgi-app/tmp/.keepkeep diff --git a/apps/workbench/.gitignore b/apps/workbench/.gitignore new file mode 100644 index 0000000000..24a7a84a31 --- /dev/null +++ b/apps/workbench/.gitignore @@ -0,0 +1,37 @@ +# Ignore the default SQLite database. +/db/*.sqlite3 + +# Ignore all logfiles and tempfiles. +/log/*.log +/tmp + +/config/.secret_token +/config/initializers/secret_token.rb + +/public/assets + +/config/environments/development.rb +/config/environments/production.rb +/config/application.yml + +# Workbench doesn't need one anyway, so this shouldn't come up, but... +/config/database.yml + +/config/piwik.yml + +# Capistrano files are coming from another repo +/Capfile* +/config/deploy* + +# Themes are coming from another repo +/themes/* + +# This can be a symlink to ../../../doc/.site in dev setups +/public/doc + +# SimpleCov reports +/coverage + +# Dev/test SSL certificates +/self-signed.key +/self-signed.pem diff --git a/apps/workbench/Gemfile b/apps/workbench/Gemfile new file mode 100644 index 0000000000..49f82f5315 --- /dev/null +++ b/apps/workbench/Gemfile @@ -0,0 +1,102 @@ +source 'https://rubygems.org' + +gem 'rails', '~> 4.1.0' +gem 'minitest', '>= 5.0.0' + +gem 'arvados', '>= 0.1.20141114230720' + +# Bundle edge Rails instead: +# gem 'rails', :git => 'git://github.com/rails/rails.git' + +gem 'sqlite3' + +gem 'multi_json' +gem 'oj' +gem 'sass' + +# Note: keeping this out of the "group :assets" section "may" allow us +# to use Coffescript for UJS responses. It also prevents a +# warning/problem when running tests: "WARN: tilt autoloading +# 'coffee_script' in a non thread-safe way; explicit require +# 'coffee_script' suggested." +gem 'coffee-rails' + +# Gems used only for assets and not required +# in production environments by default. +group :assets do + gem 'sass-rails', '~> 4.0.4' + + # See https://github.com/sstephenson/execjs#readme for more supported runtimes + gem 'therubyracer', :platforms => :ruby + + gem 'uglifier', '>= 1.0.3' +end + +group :development do + gem 'byebug' + gem 'ruby-debug-passenger' +end + +group :test, :diagnostics do + gem 'selenium-webdriver' + gem 'capybara' + gem 'poltergeist' + gem 'headless' +end + +group :test, :performance do + gem 'rails-perftest' + gem 'ruby-prof' +end + +group :test do + gem 'rvm-capistrano' + # Note: "require: false" here tells bunder not to automatically + # 'require' the packages during application startup. Installation is + # still mandatory. + gem 'simplecov', '~> 0.7.1', require: false + gem 'simplecov-rcov', require: false + gem 'mocha', require: false +end + +gem 'jquery-rails' +gem 'bootstrap-sass', '~> 3.1.0' +gem 'bootstrap-x-editable-rails' +gem 'bootstrap-tab-history-rails' + +gem 'angularjs-rails' + +gem 'less' +gem 'less-rails' +gem 'wiselinks' +gem 'sshkey' + +# To use ActiveModel has_secure_password +# gem 'bcrypt-ruby', '~> 3.0.0' + +# To use Jbuilder templates for JSON +# gem 'jbuilder' + +# Use unicorn as the app server +# gem 'unicorn' + +# Deploy with Capistrano +# gem 'capistrano' + +# To use debugger +#gem 'byebug' + +gem 'passenger', :group => :production +gem 'andand' +gem 'RedCloth' + +gem 'piwik_analytics' +gem 'httpclient', '~> 2.5.0' + +# This fork has Rails 4 compatible routes +gem 'themes_for_rails', git: 'https://github.com/holtkampw/themes_for_rails', ref: '1fd2d7897d75ae0d6375f4c390df87b8e91ad417' + +gem "deep_merge", :require => 'deep_merge/rails_compat' + +gem 'morrisjs-rails' +gem 'raphael-rails' diff --git a/apps/workbench/Gemfile.lock b/apps/workbench/Gemfile.lock new file mode 100644 index 0000000000..d29c16ea49 --- /dev/null +++ b/apps/workbench/Gemfile.lock @@ -0,0 +1,284 @@ +GIT + remote: https://github.com/holtkampw/themes_for_rails + revision: 1fd2d7897d75ae0d6375f4c390df87b8e91ad417 + ref: 1fd2d7897d75ae0d6375f4c390df87b8e91ad417 + specs: + themes_for_rails (0.5.1) + rails (>= 3.0.0) + +GEM + remote: https://rubygems.org/ + specs: + RedCloth (4.2.9) + actionmailer (4.1.8) + actionpack (= 4.1.8) + actionview (= 4.1.8) + mail (~> 2.5, >= 2.5.4) + actionpack (4.1.8) + actionview (= 4.1.8) + activesupport (= 4.1.8) + rack (~> 1.5.2) + rack-test (~> 0.6.2) + actionview (4.1.8) + activesupport (= 4.1.8) + builder (~> 3.1) + erubis (~> 2.7.0) + activemodel (4.1.8) + activesupport (= 4.1.8) + builder (~> 3.1) + activerecord (4.1.8) + activemodel (= 4.1.8) + activesupport (= 4.1.8) + arel (~> 5.0.0) + activesupport (4.1.8) + i18n (~> 0.6, >= 0.6.9) + json (~> 1.7, >= 1.7.7) + minitest (~> 5.1) + thread_safe (~> 0.1) + tzinfo (~> 1.1) + addressable (2.3.6) + andand (1.3.3) + angularjs-rails (1.3.3) + arel (5.0.1.20140414130214) + arvados (0.1.20141114230720) + activesupport (>= 3.2.13) + andand (~> 1.3, >= 1.3.3) + google-api-client (~> 0.6.3, >= 0.6.3) + json (~> 1.7, >= 1.7.7) + jwt (>= 0.1.5, < 1.0.0) + autoparse (0.3.3) + addressable (>= 2.3.1) + extlib (>= 0.9.15) + multi_json (>= 1.0.0) + bootstrap-sass (3.1.1.1) + sass (~> 3.2) + bootstrap-tab-history-rails (0.1.0) + railties (>= 3.1) + bootstrap-x-editable-rails (1.5.1.1) + railties (>= 3.0) + builder (3.2.2) + byebug (3.5.1) + columnize (~> 0.8) + debugger-linecache (~> 1.2) + slop (~> 3.6) + capistrano (2.15.5) + highline + net-scp (>= 1.0.0) + net-sftp (>= 2.0.0) + net-ssh (>= 2.0.14) + net-ssh-gateway (>= 1.1.0) + capybara (2.4.4) + mime-types (>= 1.16) + nokogiri (>= 1.3.3) + rack (>= 1.0.0) + rack-test (>= 0.5.4) + xpath (~> 2.0) + childprocess (0.5.5) + ffi (~> 1.0, >= 1.0.11) + cliver (0.3.2) + coffee-rails (4.1.0) + coffee-script (>= 2.2.0) + railties (>= 4.0.0, < 5.0) + coffee-script (2.3.0) + coffee-script-source + execjs + coffee-script-source (1.8.0) + columnize (0.8.9) + commonjs (0.2.7) + daemon_controller (1.2.0) + debugger-linecache (1.2.0) + deep_merge (1.0.1) + erubis (2.7.0) + execjs (2.2.2) + extlib (0.9.16) + faraday (0.8.9) + multipart-post (~> 1.2.0) + ffi (1.9.6) + google-api-client (0.6.4) + addressable (>= 2.3.2) + autoparse (>= 0.3.3) + extlib (>= 0.9.15) + faraday (~> 0.8.4) + jwt (>= 0.1.5) + launchy (>= 2.1.1) + multi_json (>= 1.0.0) + signet (~> 0.4.5) + uuidtools (>= 2.1.0) + headless (1.0.2) + highline (1.6.21) + hike (1.2.3) + httpclient (2.5.3.3) + i18n (0.6.11) + jquery-rails (3.1.2) + railties (>= 3.0, < 5.0) + thor (>= 0.14, < 2.0) + json (1.8.1) + jwt (0.1.13) + multi_json (>= 1.5) + launchy (2.4.3) + addressable (~> 2.3) + less (2.6.0) + commonjs (~> 0.2.7) + less-rails (2.6.0) + actionpack (>= 3.1) + less (~> 2.6.0) + libv8 (3.16.14.7) + mail (2.6.3) + mime-types (>= 1.16, < 3) + metaclass (0.0.4) + mime-types (2.4.3) + mini_portile (0.6.1) + minitest (5.4.3) + mocha (1.1.0) + metaclass (~> 0.0.1) + morrisjs-rails (0.5.1) + railties (> 3.1, < 5) + multi_json (1.10.1) + multipart-post (1.2.0) + net-scp (1.2.1) + net-ssh (>= 2.6.5) + net-sftp (2.1.2) + net-ssh (>= 2.6.5) + net-ssh (2.9.1) + net-ssh-gateway (1.2.0) + net-ssh (>= 2.6.5) + nokogiri (1.6.4.1) + mini_portile (~> 0.6.0) + oj (2.11.1) + passenger (4.0.53) + daemon_controller (>= 1.2.0) + rack + rake (>= 0.8.1) + piwik_analytics (1.0.2) + actionpack + activesupport + rails (>= 3.0.0) + poltergeist (1.5.1) + capybara (~> 2.1) + cliver (~> 0.3.1) + multi_json (~> 1.0) + websocket-driver (>= 0.2.0) + rack (1.5.2) + rack-test (0.6.2) + rack (>= 1.0) + rails (4.1.8) + actionmailer (= 4.1.8) + actionpack (= 4.1.8) + actionview (= 4.1.8) + activemodel (= 4.1.8) + activerecord (= 4.1.8) + activesupport (= 4.1.8) + bundler (>= 1.3.0, < 2.0) + railties (= 4.1.8) + sprockets-rails (~> 2.0) + rails-perftest (0.0.5) + railties (4.1.8) + actionpack (= 4.1.8) + activesupport (= 4.1.8) + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (10.4.0) + raphael-rails (2.1.2) + ref (1.0.5) + ruby-debug-passenger (0.2.0) + ruby-prof (0.15.2) + rubyzip (1.1.6) + rvm-capistrano (1.5.5) + capistrano (~> 2.15.4) + sass (3.2.19) + sass-rails (4.0.4) + railties (>= 4.0.0, < 5.0) + sass (~> 3.2.2) + sprockets (~> 2.8, < 2.12) + sprockets-rails (~> 2.0) + selenium-webdriver (2.44.0) + childprocess (~> 0.5) + multi_json (~> 1.0) + rubyzip (~> 1.0) + websocket (~> 1.0) + signet (0.4.5) + addressable (>= 2.2.3) + faraday (~> 0.8.1) + jwt (>= 0.1.5) + multi_json (>= 1.0.0) + simplecov (0.7.1) + multi_json (~> 1.0) + simplecov-html (~> 0.7.1) + simplecov-html (0.7.1) + simplecov-rcov (0.2.3) + simplecov (>= 0.4.1) + slop (3.6.0) + sprockets (2.11.3) + hike (~> 1.2) + multi_json (~> 1.0) + rack (~> 1.0) + tilt (~> 1.1, != 1.3.0) + sprockets-rails (2.2.0) + actionpack (>= 3.0) + activesupport (>= 3.0) + sprockets (>= 2.8, < 4.0) + sqlite3 (1.3.10) + sshkey (1.6.1) + therubyracer (0.12.1) + libv8 (~> 3.16.14.0) + ref + thor (0.19.1) + thread_safe (0.3.4) + tilt (1.4.1) + tzinfo (1.2.2) + thread_safe (~> 0.1) + uglifier (2.5.3) + execjs (>= 0.3.0) + json (>= 1.8.0) + uuidtools (2.1.5) + websocket (1.2.1) + websocket-driver (0.4.0) + wiselinks (1.2.1) + xpath (2.0.0) + nokogiri (~> 1.3) + +PLATFORMS + ruby + +DEPENDENCIES + RedCloth + andand + angularjs-rails + arvados (>= 0.1.20141114230720) + bootstrap-sass (~> 3.1.0) + bootstrap-tab-history-rails + bootstrap-x-editable-rails + byebug + capybara + coffee-rails + deep_merge + headless + httpclient (~> 2.5.0) + jquery-rails + less + less-rails + minitest (>= 5.0.0) + mocha + morrisjs-rails + multi_json + oj + passenger + piwik_analytics + poltergeist + rails (~> 4.1.0) + rails-perftest + raphael-rails + ruby-debug-passenger + ruby-prof + rvm-capistrano + sass + sass-rails (~> 4.0.4) + selenium-webdriver + simplecov (~> 0.7.1) + simplecov-rcov + sqlite3 + sshkey + themes_for_rails! + therubyracer + uglifier (>= 1.0.3) + wiselinks diff --git a/apps/workbench/README.textile b/apps/workbench/README.textile new file mode 100644 index 0000000000..7991978592 --- /dev/null +++ b/apps/workbench/README.textile @@ -0,0 +1,23 @@ +h1. Developing Workbench + +This document includes information to help developers who would like to contribute to Workbench. If you just want to install it, please refer to our "Workbench installation guide":http://doc.arvados.org/install/install-workbench-app.html. + +h2. Running tests + +The Workbench application includes a series of integration tests. When you run these, it starts the API server in a test environment, with all of its fixtures loaded, then tests Workbench by starting that server and making requests against it. + +In order for this to work, you must have Firefox installed (or Iceweasel, if you're running Debian), as well as the X Virtual Frame Buffer driver. + +
+$ sudo apt-get install iceweasel xvfb
+
+ +If you install the Workbench Bundle in deployment mode, you must also install the API server Bundle in deployment mode, and vice versa. If your Bundle installs have mismatched modes, the integration tests will fail with "Gem not found" errors. + +h2. Writing tests + +Integration tests are written with Capybara, which drives a fully-featured Web browser to interact with Workbench exactly as a user would. + +If your test requires JavaScript support, your test method should start with the line @Capybara.current_driver = Capybara.javascript_driver@. Otherwise, Capybara defaults to a simpler browser for speed. + +In most tests, you can directly call "Capybara's Session methods":http://rubydoc.info/github/jnicklas/capybara/Capybara/Session to drive the browser and check its state. If you need finer-grained control, refer to the "full Capybara documentation":http://rubydoc.info/github/jnicklas/capybara/Capybara. diff --git a/apps/workbench/Rakefile b/apps/workbench/Rakefile new file mode 100644 index 0000000000..752f3d8788 --- /dev/null +++ b/apps/workbench/Rakefile @@ -0,0 +1,7 @@ +#!/usr/bin/env rake +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require File.expand_path('../config/application', __FILE__) + +ArvadosWorkbench::Application.load_tasks diff --git a/apps/workbench/app/assets/images/dax.png b/apps/workbench/app/assets/images/dax.png new file mode 100644 index 0000000000..c511f0ec51 Binary files /dev/null and b/apps/workbench/app/assets/images/dax.png differ diff --git a/apps/workbench/app/assets/images/rails.png b/apps/workbench/app/assets/images/rails.png new file mode 100644 index 0000000000..d5edc04e65 Binary files /dev/null and b/apps/workbench/app/assets/images/rails.png differ diff --git a/apps/workbench/app/assets/images/spinner_32px.gif b/apps/workbench/app/assets/images/spinner_32px.gif new file mode 100644 index 0000000000..3288d1035d Binary files /dev/null and b/apps/workbench/app/assets/images/spinner_32px.gif differ diff --git a/apps/workbench/app/assets/javascripts/angular_shim.js b/apps/workbench/app/assets/javascripts/angular_shim.js new file mode 100644 index 0000000000..8665c73ddb --- /dev/null +++ b/apps/workbench/app/assets/javascripts/angular_shim.js @@ -0,0 +1,13 @@ +// Compile any new HTML content that was loaded via jQuery.ajax(). +// Currently this only works for tabs, and only because they emit an +// arv:pane:loaded event after updating the DOM. + +$(document).on('arv:pane:loaded', function(event, $updatedElement) { + if (angular && $updatedElement) { + angular.element($updatedElement).injector().invoke([ + '$compile', function($compile) { + var scope = angular.element($updatedElement).scope(); + $compile($updatedElement)(scope); + }]); + } +}); diff --git a/apps/workbench/app/assets/javascripts/application.js b/apps/workbench/app/assets/javascripts/application.js new file mode 100644 index 0000000000..63887b3ab9 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/application.js @@ -0,0 +1,240 @@ +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, +// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. +// +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// the compiled file. +// +// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD +// GO AFTER THE REQUIRES BELOW. +// +//= require jquery +//= require jquery_ujs +//= require bootstrap +//= require bootstrap/dropdown +//= require bootstrap/tab +//= require bootstrap/tooltip +//= require bootstrap/popover +//= require bootstrap/collapse +//= require bootstrap/modal +//= require bootstrap/button +//= require bootstrap3-editable/bootstrap-editable +//= require bootstrap-tab-history +//= require wiselinks +//= require angular +//= require raphael +//= require morris +//= require jquery.number.min +//= require_tree . + +jQuery(function($){ + $(document).ajaxStart(function(){ + $('.modal-with-loading-spinner .spinner').show(); + }).ajaxStop(function(){ + $('.modal-with-loading-spinner .spinner').hide(); + }); + + $('[data-toggle=tooltip]').tooltip(); + + $('.expand-collapse-row').on('click', function(event) { + var targets = $('#' + $(this).attr('data-id')); + if (targets.css('display') == 'none') { + $(this).addClass('icon-minus-sign'); + $(this).removeClass('icon-plus-sign'); + } else { + $(this).addClass('icon-plus-sign'); + $(this).removeClass('icon-minus-sign'); + } + targets.fadeToggle(200); + }); + + var ajaxCount = 0; + + $(document). + on('ajax:send', function(e, xhr) { + ajaxCount += 1; + if (ajaxCount == 1) { + $('.loading').fadeTo('fast', 1); + } + }). + on('ajax:complete', function(e, status) { + ajaxCount -= 1; + if (ajaxCount == 0) { + $('.loading').fadeOut('fast', 0); + } + }). + on('ajaxSend', function(e, xhr) { + // jQuery triggers 'ajaxSend' event when starting an ajax call, but + // rails-generated ajax triggers generate 'ajax:send'. Workbench + // event listeners currently expect 'ajax:send', so trigger the + // rails event in response to the jQuery one. + $(document).trigger('ajax:send'); + }). + on('ajaxComplete', function(e, xhr) { + // See comment above about ajaxSend/ajax:send + $(document).trigger('ajax:complete'); + }). + on('click', '.removable-tag a', function(e) { + var tag_span = $(this).parents('[data-tag-link-uuid]').eq(0) + tag_span.fadeTo('fast', 0.2); + $.ajax('/links/' + tag_span.attr('data-tag-link-uuid'), + {dataType: 'json', + type: 'POST', + data: { '_method': 'DELETE' }, + context: tag_span}). + done(function(data, status, jqxhr) { + this.remove(); + }). + fail(function(jqxhr, status, error) { + this.addClass('label-danger').fadeTo('fast', '1'); + }); + return false; + }). + on('click', 'a.add-tag-button', function(e) { + var jqxhr; + var new_tag_uuid = 'new-tag-' + Math.random(); + var tag_head_uuid = $(this).parents('tr').attr('data-object-uuid'); + var new_tag = window.prompt("Add tag for collection "+ + tag_head_uuid, + ""); + if (new_tag == null) + return false; + var new_tag_span = + $(''). + attr('data-tag-link-uuid', new_tag_uuid). + text(new_tag). + css('opacity', '0.2'). + append(' '); + $(this). + parent(). + find('>span'). + append(new_tag_span). + append(' '); + $.ajax($(this).attr('data-remote-href'), + {dataType: 'json', + type: $(this).attr('data-remote-method'), + data: { + 'link[head_uuid]': tag_head_uuid, + 'link[link_class]': 'tag', + 'link[name]': new_tag + }, + context: new_tag_span}). + done(function(data, status, jqxhr) { + this.attr('data-tag-link-uuid', data.uuid). + fadeTo('fast', '1'); + }). + fail(function(jqxhr, status, error) { + this.addClass('label-danger').fadeTo('fast', '1'); + }); + return false; + }); + + $(document). + on('ajax:complete ready', function() { + // See http://getbootstrap.com/javascript/#buttons + $('.btn').button(); + }). + on('ready ajax:complete', function() { + $('[data-toggle~=tooltip]').tooltip({container:'body'}); + }). + on('ready ajax:complete', function() { + // This makes the dialog close on Esc key, obviously. + $('.modal').attr('tabindex', '-1') + }); + + HeaderRowFixer = function(selector) { + this.duplicateTheadTr = function() { + $(selector).each(function() { + var the_table = this; + if ($('>tbody>tr:first>th', the_table).length > 0) + return; + $('>tbody', the_table). + prepend($('>thead>tr', the_table). + clone(). + css('opacity', 0)); + }); + } + this.fixThead = function() { + $(selector).each(function() { + var widths = []; + $('> tbody > tr:eq(1) > td', this).each( function(i,v){ + widths.push($(v).width()); + }); + for(i=0;i + // 'foo/bar\\040baz\\040(1).txt' + var newName; + var nameStub = origName; + var suffixInt = null; + var ok = false; + var lineMatch, linesRe = /(\S+).*/gm; + var fileTokenMatch, fileTokensRe = / \d+:\d+:(\S+)/g; + while (!ok) { + ok = true; + // Add ' (N)' before the filename extension, if any. + newName = (!suffixInt ? nameStub : + nameStub.replace(/(\.[^.]*)?$/, ' ('+suffixInt+')$1')). + replace(/ /g, '\\040'); + while (ok && null !== + (lineMatch = linesRe.exec(manifest))) { + // lineMatch is [theEntireLine, streamName] + while (ok && null !== + (fileTokenMatch = fileTokensRe.exec(lineMatch[0]))) { + // fileTokenMatch is [theEntireToken, fileName] + if (lineMatch[1] + '/' + fileTokenMatch[1] + === + newStreamName + '/' + newName) { + ok = false; + } + } + } + suffixInt = (suffixInt || 0) + 1; + } + return newName; + } + + function getDiscoveryDoc() { + if (!promiseDiscovery) { + promiseDiscovery = $.ajax({ + url: arvadosDiscoveryUri, + crossDomain: true + }).then(function(data, status, xhr) { + discoveryDoc = data; + }); + } + return promiseDiscovery; + } +} diff --git a/apps/workbench/app/assets/javascripts/bootstrap.js.coffee b/apps/workbench/app/assets/javascripts/bootstrap.js.coffee new file mode 100644 index 0000000000..c9404a8e2f --- /dev/null +++ b/apps/workbench/app/assets/javascripts/bootstrap.js.coffee @@ -0,0 +1,4 @@ +jQuery -> + $("a[rel=popover]").popover() + $(".tooltip").tooltip() + $("a[rel=tooltip]").tooltip() \ No newline at end of file diff --git a/apps/workbench/app/assets/javascripts/collections.js b/apps/workbench/app/assets/javascripts/collections.js new file mode 100644 index 0000000000..865f121e56 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/collections.js @@ -0,0 +1,55 @@ +jQuery(function($){ + $(document).on('click', '.toggle-persist button', function() { + var toggle_group = $(this).parents('[data-remote-href]').first(); + var want_persist = !toggle_group.find('button').hasClass('active'); + var want_state = want_persist ? 'persistent' : 'cache'; + toggle_group.find('button'). + toggleClass('active', want_persist). + html(want_persist ? 'Persistent' : 'Cache'); + $.ajax(toggle_group.attr('data-remote-href'), + {dataType: 'json', + type: 'POST', + data: { + value: want_state + }, + context: { + toggle_group: toggle_group, + want_state: want_state, + button: this + } + }). + done(function(data, status, jqxhr) { + var context = this; + // Remove "danger" status in case a previous action failed + $('.btn-danger', context.toggle_group). + addClass('btn-info'). + removeClass('btn-danger'); + // Update last-saved-state + context.toggle_group. + attr('data-persistent-state', context.want_state); + }). + fail(function(jqxhr, status, error) { + var context = this; + var saved_state; + // Add a visual indication that something failed + $(context.button). + addClass('btn-danger'). + removeClass('btn-info'); + // Change to the last-saved-state + saved_state = context.toggle_group.attr('data-persistent-state'); + $(context.button). + toggleClass('active', saved_state == 'persistent'). + html(saved_state == 'persistent' ? 'Persistent' : 'Cache'); + + if (jqxhr.readyState == 0 || jqxhr.status == 0) { + // Request cancelled due to page reload. + // Displaying an alert would be rather annoying. + } else if (jqxhr.responseJSON && jqxhr.responseJSON.errors) { + window.alert("Request failed: " + + jqxhr.responseJSON.errors.join("; ")); + } else { + window.alert("Request failed."); + } + }); + }); +}); diff --git a/apps/workbench/app/assets/javascripts/dates.js b/apps/workbench/app/assets/javascripts/dates.js new file mode 100644 index 0000000000..5e4b804a2d --- /dev/null +++ b/apps/workbench/app/assets/javascripts/dates.js @@ -0,0 +1,25 @@ +jQuery(function($){ +$(document).on('ajax:complete arv:pane:loaded ready', function() { + $('[data-utc-date]').each(function(i, elm) { + // Try matching the date using a couple of different formats. + var v = $(elm).attr('data-utc-date').match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d) UTC/); + if (!v) { + v = $(elm).attr('data-utc-date').match(/(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z/); + } + + if (v) { + // Create a new date object from the timestamp so the browser can + // render the date based on the locale/timezone. + var ts = new Date(Date.UTC(v[1], v[2]-1, v[3], v[4], v[5], v[6])); + if ($(elm).attr('data-utc-date-opts') && $(elm).attr('data-utc-date-opts').match(/noseconds/)) { + $(elm).text((ts.getHours() > 12 ? (ts.getHours()-12) : ts.getHours()) + + ":" + (ts.getMinutes() < 10 ? '0' : '') + ts.getMinutes() + + (ts.getHours() >= 12 ? " PM " : " AM ") + + ts.toLocaleDateString()); + } else { + $(elm).text(ts.toLocaleTimeString() + " " + ts.toLocaleDateString()); + } + } + }); +}); +}); diff --git a/apps/workbench/app/assets/javascripts/editable.js b/apps/workbench/app/assets/javascripts/editable.js new file mode 100644 index 0000000000..dc54bda7af --- /dev/null +++ b/apps/workbench/app/assets/javascripts/editable.js @@ -0,0 +1,117 @@ +$.fn.editable.defaults.ajaxOptions = {type: 'post', dataType: 'json'}; +$.fn.editable.defaults.send = 'always'; + +// Default for editing is popup. I experimented with inline which is a little +// nicer in that it shows up right under the mouse instead of nearby. However, +// the inline box is taller than the regular content, which causes the page +// layout to shift unless we make the table rows tall, which leaves a lot of +// wasted space when not editing. Also inline can get cut off if the page is +// too narrow, when the popup box will just move to do the right thing. +//$.fn.editable.defaults.mode = 'inline'; + +$.fn.editable.defaults.success = function (response, newValue) { + $(document).trigger('editable:success', [this, response, newValue]); +}; + +$.fn.editable.defaults.params = function (params) { + var a = {}; + var key = params.pk.key; + a.id = $(this).attr('data-object-uuid') || params.pk.id; + a[key] = params.pk.defaults || {}; + // Remove null values. Otherwise they get transmitted as empty + // strings in request params. + for (i in a[key]) { + if (a[key][i] == null) + delete a[key][i]; + } + a[key][params.name] = params.value; + if (!a.id) { + a['_method'] = 'post'; + } else { + a['_method'] = 'put'; + } + return a; +}; + +$.fn.editable.defaults.validate = function (value) { + if (value == "***invalid***") { + return "Invalid selection"; + } +} + +$(document). + on('ready ajax:complete', function() { + $('.editable'). + not('.editable-done-setup'). + addClass('editable-done-setup'). + editable({ + success: function(response, newValue) { + // If we just created a new object, stash its UUID + // so we edit it next time instead of creating + // another new object. + if (!$(this).attr('data-object-uuid') && response.uuid) { + $(this).attr('data-object-uuid', response.uuid); + } + if (response.href) { + $(this).editable('option', 'url', response.href); + } + if ($(this).attr('data-name')) { + var textileAttr = $(this).attr('data-name') + 'Textile'; + if (response[textileAttr]) { + $(this).attr('data-textile', response[textileAttr]); + } + } + return; + }, + error: function(response, newValue) { + var errlist = response.responseJSON.errors; + var errmsg; + if (Array.isArray(errlist)) { + errmsg = errlist.join(); + } else { + errmsg = ("The server returned an error when making " + + "this update (status " + response.status + + ": " + errlist + ")."); + } + return errmsg; + } + }). + on('hidden', function(e, reason) { + // After saving a new attribute, update the same + // information if it appears elsewhere on the page. + if (reason != 'save') return; + var html = $(this).html(); + if( $(this).attr('data-textile') ) { + html = $(this).attr('data-textile'); + $(this).html(html); + } + var uuid = $(this).attr('data-object-uuid'); + var attr = $(this).attr('data-name'); + var edited = this; + if (uuid && attr) { + $("[data-object-uuid='" + uuid + "']" + + "[data-name='" + attr + "']").each(function() { + if (this != edited) + $(this).html(html); + }); + } + }); + }). + on('ready ajax:complete', function() { + $("[data-toggle~='x-editable']"). + not('.editable-done-setup'). + addClass('editable-done-setup'). + click(function(e) { + e.stopPropagation(); + $($(this).attr('data-toggle-selector')).editable('toggle'); + }); + }); + +$.fn.editabletypes.text.defaults.tpl = '' + +$.fn.editableform.buttons = '\ +\ +\ +' diff --git a/apps/workbench/app/assets/javascripts/event_log.js b/apps/workbench/app/assets/javascripts/event_log.js new file mode 100644 index 0000000000..29ea74c417 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/event_log.js @@ -0,0 +1,370 @@ +/* + * This js establishes a websockets connection with the API Server. + */ + +/* Subscribe to websockets event log. Do nothing if already connected. */ +function subscribeToEventLog () { + // if websockets are not supported by browser, do not subscribe for events + websocketsSupported = ('WebSocket' in window); + if (websocketsSupported == false) { + return; + } + + // check if websocket connection is already stored on the window + event_log_disp = $(window).data("arv-websocket"); + if (event_log_disp == null) { + // need to create new websocket and event log dispatcher + websocket_url = $('meta[name=arv-websocket-url]').attr("content"); + if (websocket_url == null) + return; + + event_log_disp = new WebSocket(websocket_url); + + event_log_disp.onopen = onEventLogDispatcherOpen; + event_log_disp.onmessage = onEventLogDispatcherMessage; + + // store websocket in window to allow reuse when multiple divs subscribe for events + $(window).data("arv-websocket", event_log_disp); + } +} + +/* Send subscribe message to the websockets server. Without any filters + arguments, this subscribes to all events */ +function onEventLogDispatcherOpen(event) { + this.send('{"method":"subscribe"}'); +} + +/* Trigger event for all applicable elements waiting for this event */ +function onEventLogDispatcherMessage(event) { + parsedData = JSON.parse(event.data); + object_uuid = parsedData.object_uuid; + + if (!object_uuid) { + return; + } + + // if there are any listeners for this object uuid or "all", trigger the event + matches = ".arv-log-event-listener[data-object-uuid=\"" + object_uuid + "\"],.arv-log-event-listener[data-object-uuids~=\"" + object_uuid + "\"],.arv-log-event-listener[data-object-uuid=\"all\"],.arv-log-event-listener[data-object-kind=\"" + parsedData.object_kind + "\"]"; + $(matches).trigger('arv-log-event', parsedData); +} + +/* Automatically connect if there are any elements on the page that want to + receive event log events. */ +$(document).on('ajax:complete ready', function() { + var a = $('.arv-log-event-listener'); + if (a.length > 0) { + subscribeToEventLog(); + } +}); + +/* Assumes existence of: + window.jobGraphData = []; + window.jobGraphSeries = []; + window.jobGraphSortedSeries = []; + window.jobGraphMaxima = {}; + */ +function processLogLineForChart( logLine ) { + try { + var match = logLine.match(/^(\S+) (\S+) (\S+) (\S+) stderr crunchstat: (\S+) (.*)/); + if( !match ) { + match = logLine.match(/^((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2} \d\d:\d\d:\d\d \d{4}) (\S+) (\S+) (\S+) stderr crunchstat: (\S+) (.*)/); + if( match ) { + match[1] = (new Date(match[1] + ' UTC')).toISOString().replace('Z',''); + } + } + if( match ) { + var rawDetailData = ''; + var datum = null; + + // the timestamp comes first + var timestamp = match[1].replace('_','T') + 'Z'; + + // we are interested in "-- interval" recordings + var intervalMatch = match[6].match(/(.*) -- interval (.*)/); + if( intervalMatch ) { + var intervalData = intervalMatch[2].trim().split(' '); + var dt = parseFloat(intervalData[0]); + var dsum = 0.0; + for(var i=2; i < intervalData.length; i += 2 ) { + dsum += parseFloat(intervalData[i]); + } + datum = dsum/dt; + + if( datum < 0 ) { + // not interested in negative deltas + return; + } + + rawDetailData = intervalMatch[2]; + + // for the series name use the task number (4th term) and then the first word after 'crunchstat:' + var series = 'T' + match[4] + '-' + match[5]; + + // special calculation for cpus + if( /-cpu$/.test(series) ) { + // divide the stat by the number of cpus unless the time count is less than the interval length + if( dsum.toFixed(1) > dt.toFixed(1) ) { + var cpuCountMatch = intervalMatch[1].match(/(\d+) cpus/); + if( cpuCountMatch ) { + datum = datum / cpuCountMatch[1]; + } + } + } + + addJobGraphDatum( timestamp, datum, series, rawDetailData ); + } else { + // we are also interested in memory ("mem") recordings + var memoryMatch = match[6].match(/(\d+) cache (\d+) swap (\d+) pgmajfault (\d+) rss/); + if( memoryMatch ) { + rawDetailData = match[6]; + // one datapoint for rss and one for swap - only show the rawDetailData for rss + addJobGraphDatum( timestamp, parseInt(memoryMatch[4]), 'T' + match[4] + "-rss", rawDetailData ); + addJobGraphDatum( timestamp, parseInt(memoryMatch[2]), 'T' + match[4] + "-swap", '' ); + } else { + // not interested + return; + } + } + + window.redraw = true; + } + } catch( err ) { + console.log( 'Ignoring error trying to process log line: ' + err); + } +} + +function addJobGraphDatum(timestamp, datum, series, rawDetailData) { + // check for new series + if( $.inArray( series, jobGraphSeries ) < 0 ) { + var newIndex = jobGraphSeries.push(series) - 1; + jobGraphSortedSeries.push(newIndex); + jobGraphSortedSeries.sort( function(a,b) { + var matchA = jobGraphSeries[a].match(/^T(\d+)-(.*)/); + var matchB = jobGraphSeries[b].match(/^T(\d+)-(.*)/); + var termA = ('000000' + matchA[1]).slice(-6) + matchA[2]; + var termB = ('000000' + matchB[1]).slice(-6) + matchB[2]; + return termA > termB ? 1 : -1; + }); + jobGraphMaxima[series] = null; + window.recreate = true; + } + + if( datum !== 0 && ( jobGraphMaxima[series] === null || jobGraphMaxima[series] < datum ) ) { + if( isJobSeriesRescalable(series) ) { + // use old maximum to get a scale conversion + var scaleConversion = jobGraphMaxima[series]/datum; + // set new maximum and rescale the series + jobGraphMaxima[series] = datum; + rescaleJobGraphSeries( series, scaleConversion ); + } + } + + // scale + var scaledDatum = null; + if( isJobSeriesRescalable(series) && jobGraphMaxima[series] !== null && jobGraphMaxima[series] !== 0 ) { + scaledDatum = datum/jobGraphMaxima[series] + } else { + scaledDatum = datum; + } + // identify x axis point, searching from the end of the array (most recent) + var found = false; + for( var i = jobGraphData.length - 1; i >= 0; i-- ) { + if( jobGraphData[i]['t'] === timestamp ) { + found = true; + jobGraphData[i][series] = scaledDatum; + jobGraphData[i]['raw-'+series] = rawDetailData; + break; + } else if( jobGraphData[i]['t'] < timestamp ) { + // we've gone far enough back in time and this data is supposed to be sorted + break; + } + } + // index counter from previous loop will have gone one too far, so add one + var insertAt = i+1; + if(!found) { + // create a new x point for this previously unrecorded timestamp + var entry = { 't': timestamp }; + entry[series] = scaledDatum; + entry['raw-'+series] = rawDetailData; + jobGraphData.splice( insertAt, 0, entry ); + var shifted = []; + // now let's see about "scrolling" the graph, dropping entries that are too old (>10 minutes) + while( jobGraphData.length > 0 + && (Date.parse( jobGraphData[0]['t'] ) + 10*60000 < Date.parse( jobGraphData[jobGraphData.length-1]['t'] )) ) { + shifted.push(jobGraphData.shift()); + } + if( shifted.length > 0 ) { + // from those that we dropped, were any of them maxima? if so we need to rescale + jobGraphSeries.forEach( function(series) { + // test that every shifted entry in this series was either not a number (in which case we don't care) + // or else approximately (to 2 decimal places) smaller than the scaled maximum (i.e. 1), + // because otherwise we just scrolled off something that was a maximum point + // and so we need to recalculate a new maximum point by looking at all remaining displayed points in the series + if( isJobSeriesRescalable(series) && jobGraphMaxima[series] !== null + && !shifted.every( function(e) { return( !$.isNumeric(e[series]) || e[series].toFixed(2) < 1.0 ) } ) ) { + // check the remaining displayed points and find the new (scaled) maximum + var seriesMax = null; + jobGraphData.forEach( function(entry) { + if( $.isNumeric(entry[series]) && (seriesMax === null || entry[series] > seriesMax)) { + seriesMax = entry[series]; + } + }); + if( seriesMax !== null && seriesMax !== 0 ) { + // set new actual maximum using the new maximum as the conversion conversion and rescale the series + jobGraphMaxima[series] *= seriesMax; + var scaleConversion = 1/seriesMax; + rescaleJobGraphSeries( series, scaleConversion ); + } + else { + // we no longer have any data points displaying for this series + jobGraphMaxima[series] = null; + } + } + }); + } + // add a 10 minute old null data point to keep the chart honest if the oldest point is less than 9.9 minutes old + if( jobGraphData.length > 0 ) { + var earliestTimestamp = jobGraphData[0]['t']; + var mostRecentTimestamp = jobGraphData[jobGraphData.length-1]['t']; + if( (Date.parse( earliestTimestamp ) + 9.9*60000 > Date.parse( mostRecentTimestamp )) ) { + var tenMinutesBefore = (new Date(Date.parse( mostRecentTimestamp ) - 600*1000)).toISOString(); + jobGraphData.unshift( { 't': tenMinutesBefore } ); + } + } + } + +} + +function createJobGraph(elementName) { + delete jobGraph; + var emptyGraph = false; + if( jobGraphData.length === 0 ) { + // If there is no data we still want to show an empty graph, + // so add an empty datum and placeholder series to fool it into displaying itself. + // Note that when finally a new series is added, the graph will be recreated anyway. + jobGraphData.push( {} ); + jobGraphSeries.push( '' ); + emptyGraph = true; + } + var graphteristics = { + element: elementName, + data: jobGraphData, + ymax: 1.0, + yLabelFormat: function () { return ''; }, + xkey: 't', + ykeys: jobGraphSeries, + labels: jobGraphSeries, + resize: true, + hideHover: 'auto', + parseTime: true, + hoverCallback: function(index, options, content) { + var s = "
"; + s += options.data[index][options.xkey]; + s += "
"; + for( i = 0; i < jobGraphSortedSeries.length; i++ ) { + var sortedIndex = jobGraphSortedSeries[i]; + var series = options.ykeys[sortedIndex]; + var datum = options.data[index][series]; + var point = '' + point += "
"; + var labelMatch = options.labels[sortedIndex].match(/^T(\d+)-(.*)/); + point += 'Task ' + labelMatch[1] + ' ' + labelMatch[2]; + point += ": "; + if ( datum !== undefined ) { + if( isJobSeriesRescalable( series ) ) { + datum *= jobGraphMaxima[series]; + } + if( parseFloat(datum) !== 0 ) { + if( /-cpu$/.test(series) ){ + datum = $.number(datum * 100, 1) + '%'; + } else if( datum < 10 ) { + datum = $.number(datum, 2); + } else { + datum = $.number(datum); + } + if(options.data[index]['raw-'+series]) { + datum += ' (' + options.data[index]['raw-'+series] + ')'; + } + } + point += datum; + } else { + continue; + } + point += "
"; + s += point; + } + return s; + } + } + if( emptyGraph ) { + graphteristics['axes'] = false; + graphteristics['parseTime'] = false; + graphteristics['hideHover'] = 'always'; + } + window.jobGraph = Morris.Line( graphteristics ); + if( emptyGraph ) { + jobGraphData = []; + jobGraphSeries = []; + } +} + +function rescaleJobGraphSeries( series, scaleConversion ) { + if( isJobSeriesRescalable() ) { + $.each( jobGraphData, function( i, entry ) { + if( entry[series] !== null && entry[series] !== undefined ) { + entry[series] *= scaleConversion; + } + }); + } +} + +// that's right - we never do this for the 'cpu' series, which will always be between 0 and 1 anyway +function isJobSeriesRescalable( series ) { + return !/-cpu$/.test(series); +} + +$(document).on('arv-log-event', '#log_graph_div', function(event, eventData) { + if( eventData.properties.text ) { + eventData.properties.text.split('\n').forEach( function( logLine ) { + processLogLineForChart( logLine ); + } ); + } +} ); + +$(document).on('ready ajax:complete', function() { + $('#log_graph_div').not('.graph-is-setup').addClass('graph-is-setup').each( function( index, graph_div ) { + window.jobGraphData = []; + window.jobGraphSeries = []; + window.jobGraphSortedSeries = []; + window.jobGraphMaxima = {}; + window.recreate = false; + window.redraw = false; + + createJobGraph($(graph_div).attr('id')); + var object_uuid = $(graph_div).data('object-uuid'); + // if there are any listeners for this object uuid or "all", we will trigger the event + var matches = ".arv-log-event-listener[data-object-uuid=\"" + object_uuid + "\"],.arv-log-event-listener[data-object-uuids~=\"" + object_uuid + "\"]"; + + $(document).trigger('ajax:send'); + $.get('/jobs/' + $(graph_div).data('object-uuid') + '/logs.json', function(data) { + data.forEach( function( entry ) { + $(matches).trigger('arv-log-event', entry); + }); + }); + + setInterval( function() { + if( recreate ) { + window.recreate = false; + window.redraw = false; + // series have changed, draw entirely new graph + $(graph_div).html(''); + createJobGraph($(graph_div).attr('id')); + } else if( redraw ) { + window.redraw = false; + jobGraph.setData( jobGraphData ); + } + }, 5000); + }); +}); diff --git a/apps/workbench/app/assets/javascripts/filterable.js b/apps/workbench/app/assets/javascripts/filterable.js new file mode 100644 index 0000000000..34075ca56c --- /dev/null +++ b/apps/workbench/app/assets/javascripts/filterable.js @@ -0,0 +1,178 @@ +// filterable.js shows/hides content when the user operates +// search/select widgets. For "infinite scroll" content, it passes the +// filters to the server and retrieves new content. For other content, +// it filters the existing DOM elements using jQuery show/hide. +// +// Usage: +// +// 1. Add the "filterable" class to each filterable content item. +// Typically, each item is a 'tr' or a 'div class="row"'. +// +//
+//
First row
+//
Second row
+//
+// +// 2. Add the "filterable-control" class to each search/select widget. +// Also add a data-filterable-target attribute with a jQuery selector +// for an ancestor of the filterable items, i.e., the container in +// which this widget should apply filtering. +// +// +// +// Supported widgets: +// +// +// +// The input value is used as a regular expression. Rows with content +// matching the regular expression are shown. +// +// +// +// When the user selects the "Foo" option, rows with +// data-example-attr="foo" are shown, and all others are hidden. When +// the user selects the "Show all" option, all rows are shown. +// +// Notes: +// +// When multiple filterable-control widgets operate on the same +// data-filterable-target, items must pass _all_ filters in order to +// be shown. +// +// If one data-filterable-target is the parent of another +// data-filterable-target, results are undefined. Don't do this. +// +// Combining "select" filterable-controls with infinite-scroll is not +// yet supported. + +function updateFilterableQueryNow($target) { + var newquery = $target.data('filterable-query-new'); + var params = $target.data('infinite-content-params-filterable') || {}; + params.filters = [['any', 'ilike', '%' + newquery + '%']]; + $target.data('infinite-content-params-filterable', params); + $target.data('filterable-query', newquery); +} + +$(document). + on('ready ajax:success', function() { + // Copy any initial input values into + // data-filterable-query[-new]. + $('input[type=text].filterable-control').each(function() { + var $this = $(this); + var $target = $($this.attr('data-filterable-target')); + if ($target.data('filterable-query-new') === undefined) { + $target.data('filterable-query', $this.val()); + $target.data('filterable-query-new', $this.val()); + updateFilterableQueryNow($target); + } + }); + $('[data-infinite-scroller]').on('refresh-content', '[data-filterable-query]', function(e) { + // If some other event causes a refresh-content event while there + // is a new query waiting to cooloff, we should use the new query + // right away -- otherwise we'd launch an extra ajax request that + // would have to be reloaded as soon as the cooloff period ends. + if (this != e.target) + return; + if ($(this).data('filterable-query') == $(this).data('filterable-query-new')) + return; + updateFilterableQueryNow($(this)); + }); + }). + on('paste keyup input', 'input[type=text].filterable-control', function(e) { + var regexp; + if (this != e.target) return; + var $target = $($(this).attr('data-filterable-target')); + var currentquery = $target.data('filterable-query'); + if (currentquery === undefined) currentquery = ''; + if ($target.is('[data-infinite-scroller]')) { + // We already know how to load content dynamically, so we + // can do all filtering on the server side. + + if ($target.data('infinite-cooloff-timer') > 0) { + // Clear a stale refresh-after-delay timer. + clearTimeout($target.data('infinite-cooloff-timer')); + } + // Stash the new query string in the filterable container. + $target.data('filterable-query-new', $(this).val()); + if (currentquery == $(this).val()) { + // Don't mess with existing results or queries in + // progress. + return; + } + $target.data('infinite-cooloff-timer', setTimeout(function() { + // If the user doesn't do any query-changing actions + // in the next 1/4 second (like type or erase + // characters in the search box), hide the stale + // content and ask the server for new results. + updateFilterableQueryNow($target); + $target.trigger('refresh-content'); + }, 250)); + } else { + // Target does not have infinite-scroll capability. Just + // filter the rows in the browser using a RegExp. + regexp = undefined; + try { + regexp = new RegExp($(this).val(), 'i'); + } catch(e) { + if (e instanceof SyntaxError) { + // Invalid/partial regexp. See 'has-error' below. + } else { + throw e; + } + } + $target. + toggleClass('has-error', regexp === undefined). + addClass('filterable-container'). + data('q', regexp). + trigger('refresh'); + } + }).on('refresh', '.filterable-container', function() { + var $container = $(this); + var q = $(this).data('q'); + var filters = $(this).data('filters'); + $('.filterable', this).hide().filter(function() { + var $row = $(this); + var pass = true; + if (q && !$row.text().match(q)) + return false; + if (filters) { + $.each(filters, function(filterby, val) { + if (!val) return; + if (!pass) return; + pass = false; + $.each(val.split(" "), function(i, e) { + if ($row.attr(filterby) == e) + pass = true; + }); + }); + } + return pass; + }).show(); + + // Show/hide each section heading depending on whether any + // content rows are visible in that section. + $('.row[data-section-heading]', this).each(function(){ + $(this).toggle($('.row.filterable[data-section-name="' + + $(this).attr('data-section-name') + + '"]:visible').length > 0); + }); + + // Load more content if the last result is showing. + $('.infinite-scroller').add(window).trigger('scroll'); + }).on('change', 'select.filterable-control', function() { + var val = $(this).val(); + var filterby = $(this).attr('data-filterable-attribute'); + var $target = $($(this).attr('data-filterable-target')). + addClass('filterable-container'); + var filters = $target.data('filters') || {}; + filters[filterby] = val; + $target. + data('filters', filters). + trigger('refresh'); + }).on('ajax:complete', function() { + $('.filterable-control').trigger('input'); + }); diff --git a/apps/workbench/app/assets/javascripts/infinite_scroll.js b/apps/workbench/app/assets/javascripts/infinite_scroll.js new file mode 100644 index 0000000000..81a3a4639b --- /dev/null +++ b/apps/workbench/app/assets/javascripts/infinite_scroll.js @@ -0,0 +1,269 @@ +function maybe_load_more_content(event) { + var scroller = this; + var $container = $(event.data.container); + var src; // url for retrieving content + var scrollHeight; + var spinner, colspan; + var serial = Date.now(); + var params; + scrollHeight = scroller.scrollHeight || $('body')[0].scrollHeight; + if ($(scroller).scrollTop() + $(scroller).height() + > + scrollHeight - 50) + { + if (!$container.attr('data-infinite-content-href0')) { + // Remember the first page source url, so we can refresh + // from page 1 later. + $container.attr('data-infinite-content-href0', + $container.attr('data-infinite-content-href')); + } + src = $container.attr('data-infinite-content-href'); + if (!src || !$container.is(':visible')) + // Finished + return; + + // Don't start another request until this one finishes + $container.attr('data-infinite-content-href', null); + spinner = '
'; + if ($container.is('table,tbody,thead,tfoot')) { + // Hack to determine how many columns a new tr should have + // in order to reach full width. + colspan = $container.closest('table'). + find('tr').eq(0).find('td,th').length; + if (colspan == 0) + colspan = '*'; + spinner = ('' + + spinner + + ''); + } + $container.find(".spinner").detach(); + $container.append(spinner); + $container.attr('data-infinite-serial', serial); + + if (src == $container.attr('data-infinite-content-href0')) { + // If we're loading the first page, collect filters from + // various sources. + params = mergeInfiniteContentParams($container); + $.each(params, function(k,v) { + if (v instanceof Object) { + params[k] = JSON.stringify(v); + } + }); + } else { + // If we're loading page >1, ignore other filtering + // mechanisms and just use the "next page" URI from the + // previous page's response. Aside from avoiding race + // conditions (where page 2 could have different filters + // than page 1), this allows the server to use filters in + // the "next page" URI to achieve paging. (To apply any + // new filters effectively, we need to load page 1 again + // anyway.) + params = {}; + } + + $.ajax(src, + {dataType: 'json', + type: 'GET', + data: params, + context: {container: $container, src: src, serial: serial}}). + fail(function(jqxhr, status, error) { + var $faildiv; + var $container = this.container; + if ($container.attr('data-infinite-serial') != this.serial) { + // A newer request is already in progress. + return; + } + if (jqxhr.readyState == 0 || jqxhr.status == 0) { + message = "Cancelled." + } else if (jqxhr.responseJSON && jqxhr.responseJSON.errors) { + message = jqxhr.responseJSON.errors.join("; "); + } else { + message = "Request failed."; + } + // TODO: report the message to the user. + console.log(message); + $faildiv = $('
'). + attr('data-infinite-content-href', this.src). + addClass('infinite-retry'). + append(' Oops, request failed. '); + $container.find('div.spinner').replaceWith($faildiv); + }). + done(function(data, status, jqxhr) { + if ($container.attr('data-infinite-serial') != this.serial) { + // A newer request is already in progress. + return; + } + $container.find(".spinner").detach(); + $container.append(data.content); + $container.attr('data-infinite-content-href', data.next_page_href); + }); + } +} + +function ping_all_scrollers() { + // Send a scroll event to all scroll listeners that might need + // updating. Adding infinite-scroller class to the window element + // doesn't work, so we add it explicitly here. + $('.infinite-scroller').add(window).trigger('scroll'); +} + +function mergeInfiniteContentParams($container) { + var params = {}; + // Combine infiniteContentParams from multiple sources. This + // mechanism allows each of several components to set and + // update its own set of filters, without having to worry + // about stomping on some other component's filters. + // + // For example, filterable.js writes filters in + // infiniteContentParamsFilterable ("search for text foo") + // without worrying about clobbering the filters set up by the + // tab pane ("only show jobs and pipelines in this tab"). + $.each($container.data(), function(datakey, datavalue) { + // Note: We attach these data to DOM elements using + // . We store/retrieve them + // using $('element').data('foo-bar'), although + // .data('fooBar') would also work. The "all data" hash + // returned by $('element').data(), however, always has + // keys like 'fooBar'. In other words, where we have a + // choice, we stick with the 'foo-bar' style to be + // consistent with HTML. Here, our only option is + // 'fooBar'. + if (/^infiniteContentParams/.exec(datakey)) { + if (datavalue instanceof Object) { + $.each(datavalue, function(hkey, hvalue) { + if (hvalue instanceof Array) { + params[hkey] = (params[hkey] || []). + concat(hvalue); + } else if (hvalue instanceof Object) { + $.extend(params[hkey], hvalue); + } else { + params[hkey] = hvalue; + } + }); + } + } + }); + return params; +} + +function setColumnSort( $container, $header, direction ) { + // $container should be the tbody or whatever has all the infinite table data attributes + // $header should be the th with a preset data-sort-order attribute + // direction should be "asc" or "desc" + // This function returns the order by clause for this column header as a string + + // First reset all sort directions + $('th[data-sort-order]').removeData('sort-order-direction'); + // set the current one + $header.data('sort-order-direction', direction); + // change the ordering parameter + var paramsAttr = 'infinite-content-params-' + $container.data('infinite-content-params-attr'); + var params = $container.data(paramsAttr) || {}; + params.order = $header.data('sort-order').split(",").join( ' ' + direction + ', ' ) + ' ' + direction; + $container.data(paramsAttr, params); + // show the correct icon next to the column header + $container.trigger('sort-icons'); + + return params.order; +} + +$(document). + on('click', 'div.infinite-retry button', function() { + var $retry_div = $(this).closest('.infinite-retry'); + var $container = $(this).closest('.infinite-scroller-ready') + $container.attr('data-infinite-content-href', + $retry_div.attr('data-infinite-content-href')); + $retry_div. + replaceWith('
'); + ping_all_scrollers(); + }). + on('refresh-content', '[data-infinite-scroller]', function() { + // Clear all rows, reset source href to initial state, and + // (if the container is visible) start loading content. + var first_page_href = $(this).attr('data-infinite-content-href0'); + if (!first_page_href) + first_page_href = $(this).attr('data-infinite-content-href'); + $(this). + html(''). + attr('data-infinite-content-href', first_page_href); + ping_all_scrollers(); + }). + on('ready ajax:complete', function() { + $('[data-infinite-scroller]').each(function() { + if ($(this).hasClass('infinite-scroller-ready')) + return; + $(this).addClass('infinite-scroller-ready'); + + // deal with sorting if there is any, and if it was set on this page for this tab already + if( $('th[data-sort-order]').length ) { + var tabId = $(this).closest('div.tab-pane').attr('id'); + if( hasHTML5History() && history.state !== undefined && history.state !== null && history.state.order !== undefined && history.state.order[tabId] !== undefined ) { + // we will use the list of one or more table columns associated with this header to find the right element + // see sortable_columns as it is passed to render_pane in the various tab .erbs (e.g. _show_jobs_and_pipelines.html.erb) + var strippedColumns = history.state.order[tabId].replace(/\s|\basc\b|\bdesc\b/g,''); + var sortDirection = history.state.order[tabId].split(" ")[1].replace(/,/,''); + $columnHeader = $(this).closest('table').find('[data-sort-order="'+ strippedColumns +'"]'); + setColumnSort( $(this), $columnHeader, sortDirection ); + } else { + // otherwise just reset the sort icons + $(this).trigger('sort-icons'); + } + } + + // $scroller is the DOM element that hears "scroll" + // events: sometimes it's a div, sometimes it's + // window. Here, "this" is the DOM element containing the + // result rows. We pass it to maybe_load_more_content in + // event.data. + var $scroller = $($(this).attr('data-infinite-scroller')); + if (!$scroller.hasClass('smart-scroll') && + 'scroll' != $scroller.css('overflow-y')) + $scroller = $(window); + $scroller. + addClass('infinite-scroller'). + on('scroll resize', { container: this }, maybe_load_more_content). + trigger('scroll'); + }); + }). + on('shown.bs.tab', 'a[data-toggle="tab"]', function(event) { + $(event.target.getAttribute('href') + ' [data-infinite-scroller]'). + trigger('scroll'); + }). + on('click', 'th[data-sort-order]', function() { + var direction = $(this).data('sort-order-direction'); + // reverse the current direction, or do ascending if none + if( direction === undefined || direction === 'desc' ) { + direction = 'asc'; + } else { + direction = 'desc'; + } + + var $container = $(this).closest('table').find('[data-infinite-content-params-attr]'); + + var order = setColumnSort( $container, $(this), direction ); + + // put it in the browser history state if browser allows it + if( hasHTML5History() ) { + var tabId = $(this).closest('div.tab-pane').attr('id'); + var state = history.state || {}; + if( state.order === undefined ) { + state.order = {}; + } + state.order[tabId] = order; + history.replaceState( state, null, null ); + } + + $container.trigger('refresh-content'); + }). + on('sort-icons', function() { + // set or reset the icon next to each sortable column header according to the current direction attribute + $('th[data-sort-order]').each(function() { + $(this).find('i').remove(); + var direction = $(this).data('sort-order-direction'); + if( direction !== undefined ) { + $(this).append(''); + } else { + $(this).append(''); + } + }); + }); diff --git a/apps/workbench/app/assets/javascripts/keep_disks.js.coffee b/apps/workbench/app/assets/javascripts/keep_disks.js.coffee new file mode 100644 index 0000000000..e4aa4b4321 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/keep_disks.js.coffee @@ -0,0 +1,28 @@ +cache_age_in_days = (milliseconds_age) -> + ONE_DAY = 1000 * 60 * 60 * 24 + milliseconds_age / ONE_DAY + +cache_age_hover = (milliseconds_age) -> + 'Cache age ' + cache_age_in_days(milliseconds_age).toFixed(1) + ' days.' + +cache_age_axis_label = (milliseconds_age) -> + cache_age_in_days(milliseconds_age).toFixed(0) + ' days' + +float_as_percentage = (proportion) -> + (proportion.toFixed(4) * 100) + '%' + +$.renderHistogram = (histogram_data) -> + Morris.Area({ + element: 'cache-age-vs-disk-histogram', + pointSize: 0, + lineWidth: 0, + data: histogram_data, + xkey: 'age', + ykeys: ['persisted', 'cache'], + labels: ['Persisted Storage Disk Utilization', 'Cached Storage Disk Utilization'], + ymax: 1, + ymin: 0, + xLabelFormat: cache_age_axis_label, + yLabelFormat: float_as_percentage, + dateFormat: cache_age_hover + }) diff --git a/apps/workbench/app/assets/javascripts/list.js b/apps/workbench/app/assets/javascripts/list.js new file mode 100644 index 0000000000..d8ea7ba6c9 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/list.js @@ -0,0 +1,1474 @@ +;(function(){ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module._resolving && !module.exports) { + var mod = {}; + mod.exports = {}; + mod.client = mod.component = true; + module._resolving = true; + module.call(this, mod.exports, require.relative(resolved), mod); + delete module._resolving; + module.exports = mod.exports; + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("component-classes/index.js", function(exports, require, module){ +/** + * Module dependencies. + */ + +var index = require('indexof'); + +/** + * Whitespace regexp. + */ + +var re = /\s+/; + +/** + * toString reference. + */ + +var toString = Object.prototype.toString; + +/** + * Wrap `el` in a `ClassList`. + * + * @param {Element} el + * @return {ClassList} + * @api public + */ + +module.exports = function(el){ + return new ClassList(el); +}; + +/** + * Initialize a new ClassList for `el`. + * + * @param {Element} el + * @api private + */ + +function ClassList(el) { + if (!el) throw new Error('A DOM element reference is required'); + this.el = el; + this.list = el.classList; +} + +/** + * Add class `name` if not already present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.add = function(name){ + // classList + if (this.list) { + this.list.add(name); + return this; + } + + // fallback + var arr = this.array(); + var i = index(arr, name); + if (!~i) arr.push(name); + this.el.className = arr.join(' '); + return this; +}; + +/** + * Remove class `name` when present, or + * pass a regular expression to remove + * any which match. + * + * @param {String|RegExp} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.remove = function(name){ + if ('[object RegExp]' == toString.call(name)) { + return this.removeMatching(name); + } + + // classList + if (this.list) { + this.list.remove(name); + return this; + } + + // fallback + var arr = this.array(); + var i = index(arr, name); + if (~i) arr.splice(i, 1); + this.el.className = arr.join(' '); + return this; +}; + +/** + * Remove all classes matching `re`. + * + * @param {RegExp} re + * @return {ClassList} + * @api private + */ + +ClassList.prototype.removeMatching = function(re){ + var arr = this.array(); + for (var i = 0; i < arr.length; i++) { + if (re.test(arr[i])) { + this.remove(arr[i]); + } + } + return this; +}; + +/** + * Toggle class `name`, can force state via `force`. + * + * For browsers that support classList, but do not support `force` yet, + * the mistake will be detected and corrected. + * + * @param {String} name + * @param {Boolean} force + * @return {ClassList} + * @api public + */ + +ClassList.prototype.toggle = function(name, force){ + // classList + if (this.list) { + if ("undefined" !== typeof force) { + if (force !== this.list.toggle(name, force)) { + this.list.toggle(name); // toggle again to correct + } + } else { + this.list.toggle(name); + } + return this; + } + + // fallback + if ("undefined" !== typeof force) { + if (!force) { + this.remove(name); + } else { + this.add(name); + } + } else { + if (this.has(name)) { + this.remove(name); + } else { + this.add(name); + } + } + + return this; +}; + +/** + * Return an array of classes. + * + * @return {Array} + * @api public + */ + +ClassList.prototype.array = function(){ + var str = this.el.className.replace(/^\s+|\s+$/g, ''); + var arr = str.split(re); + if ('' === arr[0]) arr.shift(); + return arr; +}; + +/** + * Check if class `name` is present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.has = +ClassList.prototype.contains = function(name){ + return this.list + ? this.list.contains(name) + : !! ~index(this.array(), name); +}; + +}); +require.register("segmentio-extend/index.js", function(exports, require, module){ + +module.exports = function extend (object) { + // Takes an unlimited number of extenders. + var args = Array.prototype.slice.call(arguments, 1); + + // For each extender, copy their properties on our object. + for (var i = 0, source; source = args[i]; i++) { + if (!source) continue; + for (var property in source) { + object[property] = source[property]; + } + } + + return object; +}; +}); +require.register("component-indexof/index.js", function(exports, require, module){ +module.exports = function(arr, obj){ + if (arr.indexOf) return arr.indexOf(obj); + for (var i = 0; i < arr.length; ++i) { + if (arr[i] === obj) return i; + } + return -1; +}; +}); +require.register("component-event/index.js", function(exports, require, module){ +var bind = window.addEventListener ? 'addEventListener' : 'attachEvent', + unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent', + prefix = bind !== 'addEventListener' ? 'on' : ''; + +/** + * Bind `el` event `type` to `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.bind = function(el, type, fn, capture){ + el[bind](prefix + type, fn, capture || false); + return fn; +}; + +/** + * Unbind `el` event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +exports.unbind = function(el, type, fn, capture){ + el[unbind](prefix + type, fn, capture || false); + return fn; +}; +}); +require.register("timoxley-to-array/index.js", function(exports, require, module){ +/** + * Convert an array-like object into an `Array`. + * If `collection` is already an `Array`, then will return a clone of `collection`. + * + * @param {Array | Mixed} collection An `Array` or array-like object to convert e.g. `arguments` or `NodeList` + * @return {Array} Naive conversion of `collection` to a new `Array`. + * @api public + */ + +module.exports = function toArray(collection) { + if (typeof collection === 'undefined') return [] + if (collection === null) return [null] + if (collection === window) return [window] + if (typeof collection === 'string') return [collection] + if (isArray(collection)) return collection + if (typeof collection.length != 'number') return [collection] + if (typeof collection === 'function' && collection instanceof Function) return [collection] + + var arr = [] + for (var i = 0; i < collection.length; i++) { + if (Object.prototype.hasOwnProperty.call(collection, i) || i in collection) { + arr.push(collection[i]) + } + } + if (!arr.length) return [] + return arr +} + +function isArray(arr) { + return Object.prototype.toString.call(arr) === "[object Array]"; +} + +}); +require.register("javve-events/index.js", function(exports, require, module){ +var events = require('event'), + toArray = require('to-array'); + +/** + * Bind `el` event `type` to `fn`. + * + * @param {Element} el, NodeList, HTMLCollection or Array + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @api public + */ + +exports.bind = function(el, type, fn, capture){ + el = toArray(el); + for ( var i = 0; i < el.length; i++ ) { + events.bind(el[i], type, fn, capture); + } +}; + +/** + * Unbind `el` event `type`'s callback `fn`. + * + * @param {Element} el, NodeList, HTMLCollection or Array + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @api public + */ + +exports.unbind = function(el, type, fn, capture){ + el = toArray(el); + for ( var i = 0; i < el.length; i++ ) { + events.unbind(el[i], type, fn, capture); + } +}; + +}); +require.register("javve-get-by-class/index.js", function(exports, require, module){ +/** + * Find all elements with class `className` inside `container`. + * Use `single = true` to increase performance in older browsers + * when only one element is needed. + * + * @param {String} className + * @param {Element} container + * @param {Boolean} single + * @api public + */ + +module.exports = (function() { + if (document.getElementsByClassName) { + return function(container, className, single) { + if (single) { + return container.getElementsByClassName(className)[0]; + } else { + return container.getElementsByClassName(className); + } + }; + } else if (document.querySelector) { + return function(container, className, single) { + className = '.' + className; + if (single) { + return container.querySelector(className); + } else { + return container.querySelectorAll(className); + } + }; + } else { + return function(container, className, single) { + var classElements = [], + tag = '*'; + if (container == null) { + container = document; + } + var els = container.getElementsByTagName(tag); + var elsLen = els.length; + var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)"); + for (var i = 0, j = 0; i < elsLen; i++) { + if ( pattern.test(els[i].className) ) { + if (single) { + return els[i]; + } else { + classElements[j] = els[i]; + j++; + } + } + } + return classElements; + }; + } +})(); + +}); +require.register("javve-get-attribute/index.js", function(exports, require, module){ +/** + * Return the value for `attr` at `element`. + * + * @param {Element} el + * @param {String} attr + * @api public + */ + +module.exports = function(el, attr) { + var result = (el.getAttribute && el.getAttribute(attr)) || null; + if( !result ) { + var attrs = el.attributes; + var length = attrs.length; + for(var i = 0; i < length; i++) { + if (attr[i] !== undefined) { + if(attr[i].nodeName === attr) { + result = attr[i].nodeValue; + } + } + } + } + return result; +} +}); +require.register("javve-natural-sort/index.js", function(exports, require, module){ +/* + * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license + * Author: Jim Palmer (based on chunking idea from Dave Koelle) + */ + +module.exports = function(a, b, options) { + var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi, + sre = /(^[ ]*|[ ]*$)/g, + dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, + hre = /^0x[0-9a-f]+$/i, + ore = /^0/, + options = options || {}, + i = function(s) { return options.insensitive && (''+s).toLowerCase() || ''+s }, + // convert all to strings strip whitespace + x = i(a).replace(sre, '') || '', + y = i(b).replace(sre, '') || '', + // chunk/tokenize + xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'), + // numeric, hex or date detection + xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)), + yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null, + oFxNcL, oFyNcL, + mult = options.desc ? -1 : 1; + // first try and sort Hex codes or Dates + if (yD) + if ( xD < yD ) return -1 * mult; + else if ( xD > yD ) return 1 * mult; + // natural sorting through split numeric strings and default strings + for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { + // find floats not starting with '0', string or 0 if not defined (Clint Priest) + oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; + oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; + // handle numeric vs string comparison - number < string - (Kyle Adams) + if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; } + // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' + else if (typeof oFxNcL !== typeof oFyNcL) { + oFxNcL += ''; + oFyNcL += ''; + } + if (oFxNcL < oFyNcL) return -1 * mult; + if (oFxNcL > oFyNcL) return 1 * mult; + } + return 0; +}; + +/* +var defaultSort = getSortFunction(); + +module.exports = function(a, b, options) { + if (arguments.length == 1) { + options = a; + return getSortFunction(options); + } else { + return defaultSort(a,b); + } +} +*/ +}); +require.register("javve-to-string/index.js", function(exports, require, module){ +module.exports = function(s) { + s = (s === undefined) ? "" : s; + s = (s === null) ? "" : s; + s = s.toString(); + return s; +}; + +}); +require.register("component-type/index.js", function(exports, require, module){ +/** + * toString ref. + */ + +var toString = Object.prototype.toString; + +/** + * Return the type of `val`. + * + * @param {Mixed} val + * @return {String} + * @api public + */ + +module.exports = function(val){ + switch (toString.call(val)) { + case '[object Date]': return 'date'; + case '[object RegExp]': return 'regexp'; + case '[object Arguments]': return 'arguments'; + case '[object Array]': return 'array'; + case '[object Error]': return 'error'; + } + + if (val === null) return 'null'; + if (val === undefined) return 'undefined'; + if (val !== val) return 'nan'; + if (val && val.nodeType === 1) return 'element'; + + return typeof val.valueOf(); +}; + +}); +require.register("list.js/index.js", function(exports, require, module){ +/* +ListJS with beta 1.0.0 +By Jonny Strömberg (www.jonnystromberg.com, www.listjs.com) +*/ +(function( window, undefined ) { +"use strict"; + +var document = window.document, + getByClass = require('get-by-class'), + extend = require('extend'), + indexOf = require('indexof'); + +var List = function(id, options, values) { + + var self = this, + init, + Item = require('./src/item')(self), + addAsync = require('./src/add-async')(self), + parse = require('./src/parse')(self); + + init = { + start: function() { + self.listClass = "list"; + self.searchClass = "search"; + self.sortClass = "sort"; + self.page = 200; + self.i = 1; + self.items = []; + self.visibleItems = []; + self.matchingItems = []; + self.searched = false; + self.filtered = false; + self.handlers = { 'updated': [] }; + self.plugins = {}; + self.helpers = { + getByClass: getByClass, + extend: extend, + indexOf: indexOf + }; + + extend(self, options); + + self.listContainer = (typeof(id) === 'string') ? document.getElementById(id) : id; + if (!self.listContainer) { return; } + self.list = getByClass(self.listContainer, self.listClass, true); + + self.templater = require('./src/templater')(self); + self.search = require('./src/search')(self); + self.filter = require('./src/filter')(self); + self.sort = require('./src/sort')(self); + + this.items(); + self.update(); + this.plugins(); + }, + items: function() { + parse(self.list); + if (values !== undefined) { + self.add(values); + } + }, + plugins: function() { + for (var i = 0; i < self.plugins.length; i++) { + var plugin = self.plugins[i]; + self[plugin.name] = plugin; + plugin.init(self); + } + } + }; + + + /* + * Add object to list + */ + this.add = function(values, callback) { + if (callback) { + addAsync(values, callback); + return; + } + var added = [], + notCreate = false; + if (values[0] === undefined){ + values = [values]; + } + for (var i = 0, il = values.length; i < il; i++) { + var item = null; + if (values[i] instanceof Item) { + item = values[i]; + item.reload(); + } else { + notCreate = (self.items.length > self.page) ? true : false; + item = new Item(values[i], undefined, notCreate); + } + self.items.push(item); + added.push(item); + } + self.update(); + return added; + }; + + this.show = function(i, page) { + this.i = i; + this.page = page; + self.update(); + return self; + }; + + /* Removes object from list. + * Loops through the list and removes objects where + * property "valuename" === value + */ + this.remove = function(valueName, value, options) { + var found = 0; + for (var i = 0, il = self.items.length; i < il; i++) { + if (self.items[i].values()[valueName] == value) { + self.templater.remove(self.items[i], options); + self.items.splice(i,1); + il--; + i--; + found++; + } + } + self.update(); + return found; + }; + + /* Gets the objects in the list which + * property "valueName" === value + */ + this.get = function(valueName, value) { + var matchedItems = []; + for (var i = 0, il = self.items.length; i < il; i++) { + var item = self.items[i]; + if (item.values()[valueName] == value) { + matchedItems.push(item); + } + } + return matchedItems; + }; + + /* + * Get size of the list + */ + this.size = function() { + return self.items.length; + }; + + /* + * Removes all items from the list + */ + this.clear = function() { + self.templater.clear(); + self.items = []; + return self; + }; + + this.on = function(event, callback) { + self.handlers[event].push(callback); + return self; + }; + + this.off = function(event, callback) { + var e = self.handlers[event]; + var index = indexOf(e, callback); + if (index > -1) { + e.splice(index, 1); + } + return self; + }; + + this.trigger = function(event) { + var i = self.handlers[event].length; + while(i--) { + self.handlers[event][i](self); + } + return self; + }; + + this.reset = { + filter: function() { + var is = self.items, + il = is.length; + while (il--) { + is[il].filtered = false; + } + return self; + }, + search: function() { + var is = self.items, + il = is.length; + while (il--) { + is[il].found = false; + } + return self; + } + }; + + this.update = function() { + var is = self.items, + il = is.length; + + self.visibleItems = []; + self.matchingItems = []; + self.templater.clear(); + for (var i = 0; i < il; i++) { + if (is[i].matching() && ((self.matchingItems.length+1) >= self.i && self.visibleItems.length < self.page)) { + is[i].show(); + self.visibleItems.push(is[i]); + self.matchingItems.push(is[i]); + } else if (is[i].matching()) { + self.matchingItems.push(is[i]); + is[i].hide(); + } else { + is[i].hide(); + } + } + self.trigger('updated'); + return self; + }; + + init.start(); +}; + +module.exports = List; + +})(window); + +}); +require.register("list.js/src/search.js", function(exports, require, module){ +var events = require('events'), + getByClass = require('get-by-class'), + toString = require('to-string'); + +module.exports = function(list) { + var item, + text, + columns, + searchString, + customSearch; + + var prepare = { + resetList: function() { + list.i = 1; + list.templater.clear(); + customSearch = undefined; + }, + setOptions: function(args) { + if (args.length == 2 && args[1] instanceof Array) { + columns = args[1]; + } else if (args.length == 2 && typeof(args[1]) == "function") { + customSearch = args[1]; + } else if (args.length == 3) { + columns = args[1]; + customSearch = args[2]; + } + }, + setColumns: function() { + columns = (columns === undefined) ? prepare.toArray(list.items[0].values()) : columns; + }, + setSearchString: function(s) { + s = toString(s).toLowerCase(); + s = s.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // Escape regular expression characters + searchString = s; + }, + toArray: function(values) { + var tmpColumn = []; + for (var name in values) { + tmpColumn.push(name); + } + return tmpColumn; + } + }; + var search = { + list: function() { + for (var k = 0, kl = list.items.length; k < kl; k++) { + search.item(list.items[k]); + } + }, + item: function(item) { + item.found = false; + for (var j = 0, jl = columns.length; j < jl; j++) { + if (search.values(item.values(), columns[j])) { + item.found = true; + return; + } + } + }, + values: function(values, column) { + if (values.hasOwnProperty(column)) { + text = toString(values[column]).toLowerCase(); + if ((searchString !== "") && (text.search(searchString) > -1)) { + return true; + } + } + return false; + }, + reset: function() { + list.reset.search(); + list.searched = false; + } + }; + + var searchMethod = function(str) { + list.trigger('searchStart'); + + prepare.resetList(); + prepare.setSearchString(str); + prepare.setOptions(arguments); // str, cols|searchFunction, searchFunction + prepare.setColumns(); + + if (searchString === "" ) { + search.reset(); + } else { + list.searched = true; + if (customSearch) { + customSearch(searchString, columns); + } else { + search.list(); + } + } + + list.update(); + list.trigger('searchComplete'); + return list.visibleItems; + }; + + list.handlers.searchStart = list.handlers.searchStart || []; + list.handlers.searchComplete = list.handlers.searchComplete || []; + + events.bind(getByClass(list.listContainer, list.searchClass), 'keyup', function(e) { + var target = e.target || e.srcElement, // IE have srcElement + alreadyCleared = (target.value === "" && !list.searched); + if (!alreadyCleared) { // If oninput already have resetted the list, do nothing + searchMethod(target.value); + } + }); + + // Used to detect click on HTML5 clear button + events.bind(getByClass(list.listContainer, list.searchClass), 'input', function(e) { + var target = e.target || e.srcElement; + if (target.value === "") { + searchMethod(''); + } + }); + + list.helpers.toString = toString; + return searchMethod; +}; + +}); +require.register("list.js/src/sort.js", function(exports, require, module){ +var naturalSort = require('natural-sort'), + classes = require('classes'), + events = require('events'), + getByClass = require('get-by-class'), + getAttribute = require('get-attribute'); + +module.exports = function(list) { + list.sortFunction = list.sortFunction || function(itemA, itemB, options) { + options.desc = options.order == "desc" ? true : false; // Natural sort uses this format + return naturalSort(itemA.values()[options.valueName], itemB.values()[options.valueName], options); + }; + + var buttons = { + els: undefined, + clear: function() { + for (var i = 0, il = buttons.els.length; i < il; i++) { + classes(buttons.els[i]).remove('asc'); + classes(buttons.els[i]).remove('desc'); + } + }, + getOrder: function(btn) { + var predefinedOrder = getAttribute(btn, 'data-order'); + if (predefinedOrder == "asc" || predefinedOrder == "desc") { + return predefinedOrder; + } else if (classes(btn).has('desc')) { + return "asc"; + } else if (classes(btn).has('asc')) { + return "desc"; + } else { + return "asc"; + } + }, + getInSensitive: function(btn, options) { + var insensitive = getAttribute(btn, 'data-insensitive'); + if (insensitive === "true") { + options.insensitive = true; + } else { + options.insensitive = false; + } + }, + setOrder: function(options) { + for (var i = 0, il = buttons.els.length; i < il; i++) { + var btn = buttons.els[i]; + if (getAttribute(btn, 'data-sort') !== options.valueName) { + continue; + } + var predefinedOrder = getAttribute(btn, 'data-order'); + if (predefinedOrder == "asc" || predefinedOrder == "desc") { + if (predefinedOrder == options.order) { + classes(btn).add(options.order); + } + } else { + classes(btn).add(options.order); + } + } + } + }; + var sort = function() { + list.trigger('sortStart'); + options = {}; + + var target = arguments[0].currentTarget || arguments[0].srcElement || undefined; + + if (target) { + options.valueName = getAttribute(target, 'data-sort'); + buttons.getInSensitive(target, options); + options.order = buttons.getOrder(target); + } else { + options = arguments[1] || options; + options.valueName = arguments[0]; + options.order = options.order || "asc"; + options.insensitive = (typeof options.insensitive == "undefined") ? true : options.insensitive; + } + buttons.clear(); + buttons.setOrder(options); + + options.sortFunction = options.sortFunction || list.sortFunction; + list.items.sort(function(a, b) { + return options.sortFunction(a, b, options); + }); + list.update(); + list.trigger('sortComplete'); + }; + + // Add handlers + list.handlers.sortStart = list.handlers.sortStart || []; + list.handlers.sortComplete = list.handlers.sortComplete || []; + + buttons.els = getByClass(list.listContainer, list.sortClass); + events.bind(buttons.els, 'click', sort); + list.on('searchStart', buttons.clear); + list.on('filterStart', buttons.clear); + + // Helpers + list.helpers.classes = classes; + list.helpers.naturalSort = naturalSort; + list.helpers.events = events; + list.helpers.getAttribute = getAttribute; + + return sort; +}; + +}); +require.register("list.js/src/item.js", function(exports, require, module){ +module.exports = function(list) { + return function(initValues, element, notCreate) { + var item = this; + + this._values = {}; + + this.found = false; // Show if list.searched == true and this.found == true + this.filtered = false;// Show if list.filtered == true and this.filtered == true + + var init = function(initValues, element, notCreate) { + if (element === undefined) { + if (notCreate) { + item.values(initValues, notCreate); + } else { + item.values(initValues); + } + } else { + item.elm = element; + var values = list.templater.get(item, initValues); + item.values(values); + } + }; + this.values = function(newValues, notCreate) { + if (newValues !== undefined) { + for(var name in newValues) { + item._values[name] = newValues[name]; + } + if (notCreate !== true) { + list.templater.set(item, item.values()); + } + } else { + return item._values; + } + }; + this.show = function() { + list.templater.show(item); + }; + this.hide = function() { + list.templater.hide(item); + }; + this.matching = function() { + return ( + (list.filtered && list.searched && item.found && item.filtered) || + (list.filtered && !list.searched && item.filtered) || + (!list.filtered && list.searched && item.found) || + (!list.filtered && !list.searched) + ); + }; + this.visible = function() { + return (item.elm.parentNode == list.list) ? true : false; + }; + init(initValues, element, notCreate); + }; +}; + +}); +require.register("list.js/src/templater.js", function(exports, require, module){ +var getByClass = require('get-by-class'); + +var Templater = function(list) { + var itemSource = getItemSource(list.item), + templater = this; + + function getItemSource(item) { + if (item === undefined) { + var nodes = list.list.childNodes, + items = []; + + for (var i = 0, il = nodes.length; i < il; i++) { + // Only textnodes have a data attribute + if (nodes[i].data === undefined) { + return nodes[i]; + } + } + return null; + } else if (item.indexOf("<") !== -1) { // Try create html element of list, do not work for tables!! + var div = document.createElement('div'); + div.innerHTML = item; + return div.firstChild; + } else { + return document.getElementById(list.item); + } + } + + /* Get values from element */ + this.get = function(item, valueNames) { + templater.create(item); + var values = {}; + for(var i = 0, il = valueNames.length; i < il; i++) { + var elm = getByClass(item.elm, valueNames[i], true); + values[valueNames[i]] = elm ? elm.innerHTML : ""; + } + return values; + }; + + /* Sets values at element */ + this.set = function(item, values) { + if (!templater.create(item)) { + for(var v in values) { + if (values.hasOwnProperty(v)) { + // TODO speed up if possible + var elm = getByClass(item.elm, v, true); + if (elm) { + /* src attribute for image tag & text for other tags */ + if (elm.tagName === "IMG" && values[v] !== "") { + elm.src = values[v]; + } else { + elm.innerHTML = values[v]; + } + } + } + } + } + }; + + this.create = function(item) { + if (item.elm !== undefined) { + return false; + } + /* If item source does not exists, use the first item in list as + source for new items */ + var newItem = itemSource.cloneNode(true); + newItem.removeAttribute('id'); + item.elm = newItem; + templater.set(item, item.values()); + return true; + }; + this.remove = function(item) { + list.list.removeChild(item.elm); + }; + this.show = function(item) { + templater.create(item); + list.list.appendChild(item.elm); + }; + this.hide = function(item) { + if (item.elm !== undefined && item.elm.parentNode === list.list) { + list.list.removeChild(item.elm); + } + }; + this.clear = function() { + /* .innerHTML = ''; fucks up IE */ + if (list.list.hasChildNodes()) { + while (list.list.childNodes.length >= 1) + { + list.list.removeChild(list.list.firstChild); + } + } + }; +}; + +module.exports = function(list) { + return new Templater(list); +}; + +}); +require.register("list.js/src/filter.js", function(exports, require, module){ +module.exports = function(list) { + + // Add handlers + list.handlers.filterStart = list.handlers.filterStart || []; + list.handlers.filterComplete = list.handlers.filterComplete || []; + + return function(filterFunction) { + list.trigger('filterStart'); + list.i = 1; // Reset paging + list.reset.filter(); + if (filterFunction === undefined) { + list.filtered = false; + } else { + list.filtered = true; + var is = list.items; + for (var i = 0, il = is.length; i < il; i++) { + var item = is[i]; + if (filterFunction(item)) { + item.filtered = true; + } else { + item.filtered = false; + } + } + } + list.update(); + list.trigger('filterComplete'); + return list.visibleItems; + }; +}; + +}); +require.register("list.js/src/add-async.js", function(exports, require, module){ +module.exports = function(list) { + return function(values, callback, items) { + var valuesToAdd = values.splice(0, 100); + items = items || []; + items = items.concat(list.add(valuesToAdd)); + if (values.length > 0) { + setTimeout(function() { + addAsync(values, callback, items); + }, 10); + } else { + list.update(); + callback(items); + } + }; +}; +}); +require.register("list.js/src/parse.js", function(exports, require, module){ +module.exports = function(list) { + + var Item = require('./item')(list); + + var getChildren = function(parent) { + var nodes = parent.childNodes, + items = []; + for (var i = 0, il = nodes.length; i < il; i++) { + // Only textnodes have a data attribute + if (nodes[i].data === undefined) { + items.push(nodes[i]); + } + } + return items; + }; + + var parse = function(itemElements, valueNames) { + for (var i = 0, il = itemElements.length; i < il; i++) { + list.items.push(new Item(valueNames, itemElements[i])); + } + }; + var parseAsync = function(itemElements, valueNames) { + var itemsToIndex = itemElements.splice(0, 100); // TODO: If < 100 items, what happens in IE etc? + parse(itemsToIndex, valueNames); + if (itemElements.length > 0) { + setTimeout(function() { + init.items.indexAsync(itemElements, valueNames); + }, 10); + } else { + list.update(); + // TODO: Add indexed callback + } + }; + + return function() { + var itemsToIndex = getChildren(list.list), + valueNames = list.valueNames; + + if (list.indexAsync) { + parseAsync(itemsToIndex, valueNames); + } else { + parse(itemsToIndex, valueNames); + } + }; +}; + +}); + + + + + + + + + + + + + + + + + + + + +require.alias("component-classes/index.js", "list.js/deps/classes/index.js"); +require.alias("component-classes/index.js", "classes/index.js"); +require.alias("component-indexof/index.js", "component-classes/deps/indexof/index.js"); + +require.alias("segmentio-extend/index.js", "list.js/deps/extend/index.js"); +require.alias("segmentio-extend/index.js", "extend/index.js"); + +require.alias("component-indexof/index.js", "list.js/deps/indexof/index.js"); +require.alias("component-indexof/index.js", "indexof/index.js"); + +require.alias("javve-events/index.js", "list.js/deps/events/index.js"); +require.alias("javve-events/index.js", "events/index.js"); +require.alias("component-event/index.js", "javve-events/deps/event/index.js"); + +require.alias("timoxley-to-array/index.js", "javve-events/deps/to-array/index.js"); + +require.alias("javve-get-by-class/index.js", "list.js/deps/get-by-class/index.js"); +require.alias("javve-get-by-class/index.js", "get-by-class/index.js"); + +require.alias("javve-get-attribute/index.js", "list.js/deps/get-attribute/index.js"); +require.alias("javve-get-attribute/index.js", "get-attribute/index.js"); + +require.alias("javve-natural-sort/index.js", "list.js/deps/natural-sort/index.js"); +require.alias("javve-natural-sort/index.js", "natural-sort/index.js"); + +require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); +require.alias("javve-to-string/index.js", "list.js/deps/to-string/index.js"); +require.alias("javve-to-string/index.js", "to-string/index.js"); +require.alias("javve-to-string/index.js", "javve-to-string/index.js"); +require.alias("component-type/index.js", "list.js/deps/type/index.js"); +require.alias("component-type/index.js", "type/index.js"); +if (typeof exports == "object") { + module.exports = require("list.js"); +} else if (typeof define == "function" && define.amd) { + define(function(){ return require("list.js"); }); +} else { + this["List"] = require("list.js"); +}})(); \ No newline at end of file diff --git a/apps/workbench/app/assets/javascripts/log_viewer.js b/apps/workbench/app/assets/javascripts/log_viewer.js new file mode 100644 index 0000000000..0e12f9cfd4 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/log_viewer.js @@ -0,0 +1,282 @@ +function newTaskState() { + return {"complete_count": 0, + "failure_count": 0, + "task_count": 0, + "incomplete_count": 0, + "nodes": []}; +} + +function addToLogViewer(logViewer, lines, taskState) { + var re = /((\d\d\d\d)-(\d\d)-(\d\d))_((\d\d):(\d\d):(\d\d)) ([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}) (\d+) (\d+)? (.*)/; + + var items = []; + var count = logViewer.items.length; + for (var a in lines) { + var v = lines[a].match(re); + if (v != null) { + + var ts = new Date(Date.UTC(v[2], v[3]-1, v[4], v[6], v[7], v[8])); + + v11 = v[11]; + if (typeof v[11] === 'undefined') { + v11 = ""; + } else { + v11 = Number(v11); + } + + var message = v[12]; + var type = ""; + var node = ""; + var slot = ""; + if (v11 !== "") { + if (!taskState.hasOwnProperty(v11)) { + taskState[v11] = {}; + taskState.task_count += 1; + } + + if (/^stderr /.test(message)) { + message = message.substr(7); + if (/^crunchstat: /.test(message)) { + type = "crunchstat"; + message = message.substr(12); + } else if (/^srun: /.test(message) || /^slurmd/.test(message)) { + type = "task-dispatch"; + } else { + type = "task-print"; + } + } else { + var m; + if (m = /^success in (\d+) second/.exec(message)) { + taskState[v11].outcome = "success"; + taskState[v11].runtime = Number(m[1]); + taskState.complete_count += 1; + } + else if (m = /^failure \(\#\d+, (temporary|permanent)\) after (\d+) second/.exec(message)) { + taskState[v11].outcome = "failure"; + taskState[v11].runtime = Number(m[2]); + taskState.failure_count += 1; + if (m[1] == "permanent") { + taskState.incomplete_count += 1; + } + } + else if (m = /^child \d+ started on ([^.]*)\.(\d+)/.exec(message)) { + taskState[v11].node = m[1]; + taskState[v11].slot = m[2]; + if (taskState.nodes.indexOf(m[1], 0) == -1) { + taskState.nodes.push(m[1]); + } + for (var i in items) { + if (i > 0) { + if (items[i].taskid === v11) { + items[i].node = m[1]; + items[i].slot = m[2]; + } + } + } + } + type = "task-dispatch"; + } + node = taskState[v11].node; + slot = taskState[v11].slot; + } else { + type = "crunch"; + } + + items.push({ + id: count, + ts: ts, + timestamp: ts.toLocaleDateString() + " " + ts.toLocaleTimeString(), + taskid: v11, + node: node, + slot: slot, + message: message.replace(/&/g, '&').replace(//g, '>'), + type: type + }); + count += 1; + } else { + console.log("Did not parse line " + a + ": " + lines[a]); + } + } + logViewer.add(items); +} + +function sortById(a, b, opt) { + a = a.values(); + b = b.values(); + + if (a["id"] > b["id"]) { + return 1; + } + if (a["id"] < b["id"]) { + return -1; + } + return 0; +} + +function sortByTask(a, b, opt) { + var aa = a.values(); + var bb = b.values(); + + if (aa["taskid"] === "" && bb["taskid"] !== "") { + return -1; + } + if (aa["taskid"] !== "" && bb["taskid"] === "") { + return 1; + } + + if (aa["taskid"] !== "" && bb["taskid"] !== "") { + if (aa["taskid"] > bb["taskid"]) { + return 1; + } + if (aa["taskid"] < bb["taskid"]) { + return -1; + } + } + + return sortById(a, b, opt); +} + +function sortByNode(a, b, opt) { + var aa = a.values(); + var bb = b.values(); + + if (aa["node"] === "" && bb["node"] !== "") { + return -1; + } + if (aa["node"] !== "" && bb["node"] === "") { + return 1; + } + + if (aa["node"] !== "" && bb["node"] !== "") { + if (aa["node"] > bb["node"]) { + return 1; + } + if (aa["node"] < bb["node"]) { + return -1; + } + } + + if (aa["slot"] !== "" && bb["slot"] !== "") { + if (aa["slot"] > bb["slot"]) { + return 1; + } + if (aa["slot"] < bb["slot"]) { + return -1; + } + } + + return sortById(a, b, opt); +} + + +function dumbPluralize(n, s, p) { + if (typeof p === 'undefined') { + p = "s"; + } + if (n == 0 || n > 1) { + return n + " " + (s + p); + } else { + return n + " " + s; + } +} + +function generateJobOverview(id, logViewer, taskState) { + var html = ""; + + if (logViewer.items.length > 2) { + var first = logViewer.items[1]; + var last = logViewer.items[logViewer.items.length-1]; + var duration = (last.values().ts.getTime() - first.values().ts.getTime()) / 1000; + + var hours = 0; + var minutes = 0; + var seconds; + + if (duration >= 3600) { + hours = Math.floor(duration / 3600); + duration -= (hours * 3600); + } + if (duration >= 60) { + minutes = Math.floor(duration / 60); + duration -= (minutes * 60); + } + seconds = duration; + + var tcount = taskState.task_count; + + html += "

"; + html += "Started at " + first.values().timestamp + ". "; + html += "Ran " + dumbPluralize(tcount, " task") + " over "; + if (hours > 0) { + html += dumbPluralize(hours, " hour"); + } + if (minutes > 0) { + html += " " + dumbPluralize(minutes, " minute"); + } + if (seconds > 0) { + html += " " + dumbPluralize(seconds, " second"); + } + + html += " using " + dumbPluralize(taskState.nodes.length, " node"); + + html += ". " + dumbPluralize(taskState.complete_count, "task") + " completed"; + html += ", " + dumbPluralize(taskState.incomplete_count, "task") + " incomplete"; + html += " (" + dumbPluralize(taskState.failure_count, " failure") + ")"; + + html += ". Finished at " + last.values().timestamp + "."; + html += "

"; + } else { + html = "

Job log is empty or failed to load.

"; + } + + $(id).html(html); +} + +function gotoPage(n, logViewer, page, id) { + if (n < 0) { return; } + if (n*page > logViewer.matchingItems.length) { return; } + logViewer.page_offset = n; + logViewer.show(n*page, page); +} + +function updatePaging(id, logViewer, page) { + var p = ""; + var i = logViewer.matchingItems.length; + var n; + for (n = 0; (n*page) < i; n += 1) { + if (n == logViewer.page_offset) { + p += "" + (n+1) + " "; + } else { + p += "" + (n+1) + " "; + } + } + $(id).html(p); + for (n = 0; (n*page) < i; n += 1) { + (function(n) { + $(".log-viewer-page-" + n).on("click", function() { + gotoPage(n, logViewer, page, id); + return false; + }); + })(n); + } + + if (logViewer.page_offset == 0) { + $(".log-viewer-page-up").addClass("text-muted"); + } else { + $(".log-viewer-page-up").removeClass("text-muted"); + } + + if (logViewer.page_offset == (n-1)) { + $(".log-viewer-page-down").addClass("text-muted"); + } else { + $(".log-viewer-page-down").removeClass("text-muted"); + } +} + +function nextPage(logViewer, page, id) { + gotoPage(logViewer.page_offset+1, logViewer, page, id); +} + +function prevPage(logViewer, page, id) { + gotoPage(logViewer.page_offset-1, logViewer, page, id); +} diff --git a/apps/workbench/app/assets/javascripts/permission_toggle.js b/apps/workbench/app/assets/javascripts/permission_toggle.js new file mode 100644 index 0000000000..00c1718bd8 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/permission_toggle.js @@ -0,0 +1,55 @@ +$(document). + on('click', '[data-toggle-permission] input[type=checkbox]', function() { + var data = {}; + var keys = ['data-permission-uuid', + 'data-permission-name', + 'data-permission-head', + 'data-permission-tail']; + var attr; + for(var i in keys) { + attr = keys[i]; + data[attr] = $(this).closest('[' + attr + ']').attr(attr); + if (data[attr] === undefined) { + console.log(["Error: no " + attr + " established here.", this]); + return; + } + } + var is_checked = $(this).prop('checked'); + + if (is_checked) { + $.ajax('/links', + {dataType: 'json', + type: 'POST', + data: {'link[tail_uuid]': data['data-permission-tail'], + 'link[head_uuid]': data['data-permission-head'], + 'link[link_class]': 'permission', + 'link[name]': data['data-permission-name']}, + context: this}). + fail(function(jqxhr, status, error) { + $(this).prop('checked', false); + }). + done(function(data, status, jqxhr) { + $(this).attr('data-permission-uuid', data['uuid']); + }). + always(function() { + $(this).prop('disabled', false); + }); + } + else { + $.ajax('/links/' + data['data-permission-uuid'], + {dataType: 'json', + type: 'POST', + data: {'_method': 'DELETE'}, + context: this}). + fail(function(jqxhr, status, error) { + $(this).prop('checked', true); + }). + done(function(data, status, jqxhr) { + $(this).attr('data-permission-uuid', 'x'); + }). + always(function() { + $(this).prop('disabled', false); + }); + } + $(this).prop('disabled', true); + }); diff --git a/apps/workbench/app/assets/javascripts/pipeline_instances.js b/apps/workbench/app/assets/javascripts/pipeline_instances.js new file mode 100644 index 0000000000..e820ba978e --- /dev/null +++ b/apps/workbench/app/assets/javascripts/pipeline_instances.js @@ -0,0 +1,129 @@ +function run_pipeline_button_state() { + var a = $('a.editable.required.editable-empty,input.form-control.required[value=""]'); + if (a.length > 0) { + $(".run-pipeline-button").addClass("disabled"); + } + else { + $(".run-pipeline-button").removeClass("disabled"); + } +} + +$(document).on('editable:success', function(event, tag, response, newValue) { + var $tag = $(tag); + if ($('.run-pipeline-button').length == 0) + return; + if ($tag.hasClass("required")) { + if (newValue && newValue.trim() != "") { + $tag.removeClass("editable-empty"); + $tag.parent().css("background-color", ""); + $tag.parent().prev().css("background-color", ""); + } + else { + $tag.addClass("editable-empty"); + $tag.parent().css("background-color", "#ffdddd"); + $tag.parent().prev().css("background-color", "#ffdddd"); + } + } + if ($tag.attr('data-name')) { + // Update other inputs representing the same piece of data + $('.editable[data-name="' + $tag.attr('data-name') + '"]'). + editable('setValue', newValue); + } + run_pipeline_button_state(); +}); + +$(document).on('ready ajax:complete', function() { + $('a.editable.required').each(function() { + var $tag = $(this); + if ($tag.hasClass("editable-empty")) { + $tag.parent().css("background-color", "#ffdddd"); + $tag.parent().prev().css("background-color", "#ffdddd"); + } + else { + $tag.parent().css("background-color", ""); + $tag.parent().prev().css("background-color", ""); + } + }); + run_pipeline_button_state(); +}); + +$(document).on('arv-log-event', '.arv-refresh-on-state-change', function(event, eventData) { + if (this != event.target) { + // Not interested in events sent to child nodes. + return; + } + if (eventData.event_type == "update" && + eventData.properties.old_attributes.state != eventData.properties.new_attributes.state) + { + $(event.target).trigger('arv:pane:reload'); + } +}); + +$(document).on('arv-log-event', '.arv-log-event-subscribe-to-pipeline-job-uuids', function(event, eventData){ + if (this != event.target) { + // Not interested in events sent to child nodes. + return; + } + if (!((eventData.object_kind == 'arvados#pipelineInstance') && + (eventData.event_type == "create" || + eventData.event_type == "update") && + eventData.properties && + eventData.properties.new_attributes && + eventData.properties.new_attributes.components)) { + return; + } + var objs = ""; + var components = eventData.properties.new_attributes.components; + for (a in components) { + if (components[a].job && components[a].job.uuid) { + objs += " " + components[a].job.uuid; + } + } + $(event.target).attr("data-object-uuids", eventData.object_uuid + objs); +}); + +$(document).on('ready ajax:success', function() { + $('.arv-log-refresh-control').each(function() { + var uuids = $(this).attr('data-object-uuids'); + var $pane = $(this).closest('[data-pane-content-url]'); + $pane.attr('data-object-uuids', uuids); + }); +}); + +$(document).on('arv-log-event', '.arv-log-event-handler-append-logs', function(event, eventData){ + if (this != event.target) { + // Not interested in events sent to child nodes. + return; + } + var wasatbottom = ($(this).scrollTop() + $(this).height() >= this.scrollHeight); + + if (eventData.event_type == "stderr" || eventData.event_type == "stdout") { + if( eventData.prepend ) { + $(this).prepend(eventData.properties.text); + } else { + $(this).append(eventData.properties.text); + } + } + + if (wasatbottom) { + this.scrollTop = this.scrollHeight; + } +}); + +// Set up all events for the pipeline instances compare button. +(function() { + var compare_form = '#compare'; + var compare_inputs = '#comparedInstances :checkbox[name="uuids[]"]'; + var update_button = function(event) { + var $form = $(compare_form); + var $checked_inputs = $(compare_inputs).filter(':checked'); + $(':submit', $form).prop('disabled', (($checked_inputs.length < 2) || + ($checked_inputs.length > 3))); + $('input[name="uuids[]"]', $form).remove(); + $form.append($checked_inputs.clone() + .removeAttr('id').attr('type', 'hidden')); + }; + $(document) + .on('ready ajax:success', compare_form, update_button) + .on('change', compare_inputs, update_button); +})(); diff --git a/apps/workbench/app/assets/javascripts/report_issue.js b/apps/workbench/app/assets/javascripts/report_issue.js new file mode 100644 index 0000000000..f3c323c63b --- /dev/null +++ b/apps/workbench/app/assets/javascripts/report_issue.js @@ -0,0 +1,30 @@ +$(document). + on('click', "#report-issue-submit", function(e){ + $(this).html('Sending'); + $(this).prop('disabled', true); + var $cancelButton = $('#report-issue-cancel'); + if ($cancelButton) { + $cancelButton.html('Close'); + } + $('div').remove('.modal-footer-status'); + + $.ajax('/'). + success(function(data, status, jqxhr) { + var $sendButton = $('#report-issue-submit'); + $sendButton.html('Report sent'); + $('div').remove('.modal-footer-status'); + $('.modal-footer').append('

'); + }). + fail(function(jqxhr, status, error) { + var $sendButton = $('#report-issue-submit'); + if ($sendButton && $sendButton.prop('disabled')) { + $('div').remove('.modal-footer-status'); + $('.modal-footer').append('

'); + $sendButton.html('Send problem report'); + $sendButton.prop('disabled', false); + } + var $cancelButton = $('#report-issue-cancel'); + $cancelButton.html('Cancel'); + }); + + }); diff --git a/apps/workbench/app/assets/javascripts/select_modal.js b/apps/workbench/app/assets/javascripts/select_modal.js new file mode 100644 index 0000000000..3b51faad6a --- /dev/null +++ b/apps/workbench/app/assets/javascripts/select_modal.js @@ -0,0 +1,179 @@ +$(document).on('click', '.selectable', function() { + var any; + var $this = $(this); + var $container = $(this).closest('.selectable-container'); + if (!$container.hasClass('multiple')) { + $container. + find('.selectable'). + removeClass('active'); + } + $this.toggleClass('active'); + + if (!$this.hasClass('use-preview-selection')) { + any = ($container. + find('.selectable.active').length > 0) + } + + if (!$container.hasClass('preview-selectable-container')) { + $this. + closest('.modal'). + find('[data-enable-if-selection]'). + prop('disabled', !any); + + if ($this.hasClass('active')) { + var no_preview_available = '
(No preview available)
'; + if (!$this.attr('data-preview-href')) { + $(".modal-dialog-preview-pane").html(no_preview_available); + return; + } + $(".modal-dialog-preview-pane").html('
'); + $.ajax($this.attr('data-preview-href'), + {dataType: "html"}). + done(function(data, status, jqxhr) { + $(".modal-dialog-preview-pane").html(data); + }). + fail(function(data, status, jqxhr) { + $(".modal-dialog-preview-pane").html(no_preview_available); + }); + } + } else { + any = ($container. + find('.preview-selectable.active').length > 0) + $(this). + closest('.modal'). + find('[data-enable-if-selection]'). + prop('disabled', !any); + } + +}).on('click', '.modal button[data-action-href]', function() { + var selection = []; + var data = []; + var $modal = $(this).closest('.modal'); + var http_method = $(this).attr('data-method').toUpperCase(); + var action_data = $(this).data('action-data'); + var action_data_from_params = $(this).data('action-data-from-params'); + var selection_param = action_data.selection_param; + $modal.find('.modal-error').removeClass('hide').hide(); + + var $preview_selections = $modal.find('.preview-selectable.active'); + if ($preview_selections.length > 0) { + data.push({name: selection_param, value: $preview_selections.first().attr('href')}); + } + + if (data.length == 0) { // not using preview selection option + $modal.find('.selectable.active[data-object-uuid]').each(function() { + var val = $(this).attr('data-object-uuid'); + data.push({name: selection_param, value: val}); + }); + } + $.each($.extend({}, action_data, action_data_from_params), + function(key, value) { + if (value instanceof Array && key[-1] != ']') { + for (var i in value) { + data.push({name: key + '[]', value: value[i]}); + } + } else { + data.push({name: key, value: value}); + } + }); + if (http_method === 'PATCH') { + // Some user agents do not support HTTP PATCH (notably, + // phantomjs silently ignores our "data" and sends an empty + // request body) so we use POST instead, and supply a + // _method=PATCH param to tell Rails what we really want. + data.push({name: '_method', value: http_method}); + http_method = 'POST'; + } + $.ajax($(this).attr('data-action-href'), + {dataType: 'json', + type: http_method, + data: data, + traditional: false, + context: {modal: $modal, action_data: action_data}}). + fail(function(jqxhr, status, error) { + if (jqxhr.readyState == 0 || jqxhr.status == 0) { + message = "Cancelled." + } else if (jqxhr.responseJSON && jqxhr.responseJSON.errors) { + message = jqxhr.responseJSON.errors.join("; "); + } else { + message = "Request failed."; + } + this.modal.find('.modal-error'). + html('
' + message + '
'). + show(); + }). + done(function(data, status, jqxhr) { + var event_name = this.action_data.success; + this.modal.find('.modal-error').hide(); + $(document).trigger(event_name!=null ? event_name : 'page-refresh', + [data, status, jqxhr, this.action_data]); + }); +}).on('click', '.chooser-show-project', function() { + var params = {}; + var project_uuid = $(this).attr('data-project-uuid'); + $(this).attr('href', '#'); // Skip normal click handler + if (project_uuid) { + params = {'filters': [['owner_uuid', + '=', + project_uuid]], + 'project_uuid': project_uuid + }; + } + // Use current selection as dropdown button label + $(this). + closest('.dropdown-menu'). + prev('button'). + html($(this).text() + ' '); + // Set (or unset) filter params and refresh filterable rows + $($(this).closest('[data-filterable-target]').attr('data-filterable-target')). + data('infinite-content-params-from-project-dropdown', params). + trigger('refresh-content'); +}).on('ready', function() { + $('form[data-search-modal] a').on('click', function() { + $(this).closest('form').submit(); + return false; + }); + $('form[data-search-modal]').on('submit', function() { + // Ask the server for a Search modal. When it arrives, copy + // the search string from the top nav input into the modal's + // search query field. + var $form = $(this); + var searchq = $form.find('input').val(); + var is_a_uuid = /^([0-9a-f]{32}(\+\S+)?|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})$/; + if (searchq.trim().match(is_a_uuid)) { + window.location = '/actions?uuid=' + encodeURIComponent(searchq.trim()); + // Show the "loading" indicator. TODO: better page transition hook + $(document).trigger('ajax:send'); + return false; + } + if ($form.find('a[data-remote]').length > 0) { + // A search dialog is already loading. + return false; + } + $(''). + attr('href', $form.attr('data-search-modal')). + attr('data-remote', 'true'). + attr('data-method', 'GET'). + hide(). + appendTo($form). + on('ajax:success', function(data, status, xhr) { + $('body > .modal-container input[type=text]'). + val($form.find('input').val()). + focus(); + $form.find('input').val(''); + }).on('ajax:complete', function() { + $(this).detach(); + }). + click(); + return false; + }); +}).on('page-refresh', function(event, data, status, jqxhr, action_data) { + window.location.reload(); +}).on('tab-refresh', function(event, data, status, jqxhr, action_data) { + $(document).trigger('arv:pane:reload:all'); + $('body > .modal-container .modal').modal('hide'); +}).on('redirect-to-created-object', function(event, data, status, jqxhr, action_data) { + window.location.href = data.href.replace(/^[^\/]*\/\/[^\/]*/, ''); +}).on('shown.bs.modal', 'body > .modal-container .modal', function() { + $('.focus-on-display', this).focus(); +}); diff --git a/apps/workbench/app/assets/javascripts/selection.js.erb b/apps/workbench/app/assets/javascripts/selection.js.erb new file mode 100644 index 0000000000..0068b738ec --- /dev/null +++ b/apps/workbench/app/assets/javascripts/selection.js.erb @@ -0,0 +1,74 @@ +//= require jquery +//= require jquery_ujs + +/** Javascript for selection. */ + +jQuery(function($){ + $(document). + on('change', '.persistent-selection:checkbox', function(e) { + $(document).trigger('selections-updated'); + }); +}); + +function dispatch_selection_action() { + // Build a new "href" attribute for this link by starting with the + // "data-href" attribute and appending ?foo[]=bar&foo[]=baz (or + // &foo=... as appropriate) to reflect the current object + // selections. + var data = []; + var param_name = $(this).attr('data-selection-param-name'); + var href = $(this).attr('data-href'); + if ($(this).closest('.disabled').length > 0) { + return false; + } + $(this). + closest('.selection-action-container'). + find(':checkbox:checked:visible'). + each(function() { + data.push({name: param_name, value: $(this).val()}); + }); + if (href.indexOf('?') >= 0) + href += '&'; + else + href += '?'; + href += $.param(data, true); + $(this).attr('href', href); + return true; +} + +function enable_disable_selection_actions() { + var $container = $(this); + var $checked = $('.persistent-selection:checkbox:checked', $container); + $('[data-selection-action]', $container). + closest('div.btn-group-sm'). + find('ul li'). + toggleClass('disabled', ($checked.length == 0)); + $('[data-selection-action=compare]', $container). + closest('li'). + toggleClass('disabled', + ($checked.filter('[value*=-d1hrv-]').length < 2) || + ($checked.not('[value*=-d1hrv-]').length > 0)); + <% unless Group.copies_to_projects? %> + $('[data-selection-action=copy]', $container). + closest('li'). + toggleClass('disabled', + ($checked.filter('[value*=-j7d0g-]').length > 0) || + ($checked.length < 1)); + <% end %> + $('[data-selection-action=combine-project-contents]', $container). + closest('li'). + toggleClass('disabled', + ($checked.filter('[value*=-4zz18-]').length < 1) || + ($checked.length != $checked.filter('[value*=-4zz18-]').length)); +} + +$(document). + on('selections-updated', function() { + $('.selection-action-container').each(enable_disable_selection_actions); + }). + on('ready ajax:complete', function() { + $('[data-selection-action]'). + off('click', dispatch_selection_action). + on('click', dispatch_selection_action); + $(this).trigger('selections-updated'); + }); diff --git a/apps/workbench/app/assets/javascripts/sizing.js b/apps/workbench/app/assets/javascripts/sizing.js new file mode 100644 index 0000000000..2341628fa7 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/sizing.js @@ -0,0 +1,31 @@ +function graph_zoom(divId, svgId, scale) { + var pg = document.getElementById(divId); + vcenter = (pg.scrollTop + (pg.scrollHeight - pg.scrollTopMax)/2.0) / pg.scrollHeight; + hcenter = (pg.scrollLeft + (pg.scrollWidth - pg.scrollLeftMax)/2.0) / pg.scrollWidth; + var g = document.getElementById(svgId); + g.setAttribute("height", parseFloat(g.getAttribute("height")) * scale); + g.setAttribute("width", parseFloat(g.getAttribute("width")) * scale); + pg.scrollTop = (vcenter * pg.scrollHeight) - (pg.scrollHeight - pg.scrollTopMax)/2.0; + pg.scrollLeft = (hcenter * pg.scrollWidth) - (pg.scrollWidth - pg.scrollLeftMax)/2.0; + smart_scroll_fixup(); +} + +function smart_scroll_fixup(s) { + + if (s != null && s.type == 'shown.bs.tab') { + s = [s.target]; + } + else { + s = $(".smart-scroll"); + } + + s.each(function(i, a) { + a = $(a); + var h = window.innerHeight - a.offset().top - a.attr("data-smart-scroll-padding-bottom"); + height = String(h) + "px"; + a.css('max-height', height); + }); +} + +$(window).on('load ready resize scroll ajax:complete', smart_scroll_fixup); +$(document).on('shown.bs.tab', 'ul.nav-tabs > li > a', smart_scroll_fixup); diff --git a/apps/workbench/app/assets/javascripts/tab_panes.js b/apps/workbench/app/assets/javascripts/tab_panes.js new file mode 100644 index 0000000000..6565ea9f4c --- /dev/null +++ b/apps/workbench/app/assets/javascripts/tab_panes.js @@ -0,0 +1,197 @@ +// Load tab panes on demand. See app/views/application/_content.html.erb + +// Fire when a tab is selected/clicked. +$(document).on('shown.bs.tab', '[data-toggle="tab"]', function(event) { + // reload the pane (unless it's already loaded) + $($(event.target).attr('href')). + not('.pane-loaded'). + trigger('arv:pane:reload'); +}); + +// Ask a refreshable pane to reload via ajax. +// +// Target of this event is the DOM element to be updated. A reload +// consists of an AJAX call to load the "data-pane-content-url" and +// replace the content of the target element with the retrieved HTML. +// +// There are four CSS classes set on the element to indicate its state: +// pane-loading, pane-stale, pane-loaded, pane-reload-pending +// +// There are five states based on the presence or absence of css classes: +// +// 1. Absence of any pane-* states means the pane is empty, and should +// be loaded as soon as it becomes visible. +// +// 2. "pane-loading" means an AJAX call has been made to reload the +// pane and we are waiting on a result. +// +// 3. "pane-loading pane-stale" means the pane is loading, but has +// already been invalidated and should schedule a reload as soon as +// possible after the current load completes. (This happens when there +// is a cluster of events, where the reload is triggered by the first +// event, but we want ensure that we eventually load the final +// quiescent state). +// +// 4. "pane-loaded" means the pane is up to date. +// +// 5. "pane-loaded pane-reload-pending" means a reload is needed, and +// has been scheduled, but has not started because the pane's +// minimum-time-between-reloads throttle has not yet been reached. +// +$(document).on('arv:pane:reload', '[data-pane-content-url]', function(e) { + if (this != e.target) { + // An arv:pane:reload event was sent to an element (e.target) + // which happens to have an ancestor (this) matching the above + // '[data-pane-content-url]' selector. This happens because + // events bubble up the DOM on their way to document. However, + // here we only care about events delivered directly to _this_ + // selected element (i.e., this==e.target), not ones delivered + // to its children. The event "e" is uninteresting here. + return; + } + + // $pane, the event target, is an element whose content is to be + // replaced. Pseudoclasses on $pane (pane-loading, etc) encode the + // current loading state. + var $pane = $(this); + + if ($pane.hasClass('pane-loading')) { + // Already loading, mark stale to schedule a reload after this one. + $pane.addClass('pane-stale'); + return; + } + + // The default throttle (mininum milliseconds between refreshes) + // can be overridden by an .arv-log-refresh-control element inside + // the pane -- or, failing that, the pane element itself -- with a + // data-load-throttle attribute. This allows the server to adjust + // the throttle depending on the pane content. + var throttle = + $pane.find('.arv-log-refresh-control').attr('data-load-throttle') || + $pane.attr('data-load-throttle') || + 15000; + var now = (new Date()).getTime(); + var loaded_at = $pane.attr('data-loaded-at'); + var since_last_load = now - loaded_at; + if (loaded_at && (since_last_load < throttle)) { + if (!$pane.hasClass('pane-reload-pending')) { + $pane.addClass('pane-reload-pending'); + setTimeout((function() { + $pane.trigger('arv:pane:reload'); + }), throttle - since_last_load); + } + return; + } + + // We know this doesn't have 'pane-loading' because we tested for it above + $pane.removeClass('pane-reload-pending'); + $pane.removeClass('pane-loaded'); + $pane.removeClass('pane-stale'); + + if (!$pane.hasClass('active') && + $pane.parent().hasClass('tab-content')) { + // $pane is one of the content areas in a bootstrap tabs + // widget, and it isn't the currently selected tab. If and + // when the user does select the corresponding tab, it will + // get a shown.bs.tab event, which will invoke this reload + // function again (see handler above). For now, we just insert + // a spinner, which will be displayed while the new content is + // loading. + $pane.html('
'); + return; + } + + $pane.addClass('pane-loading'); + + var content_url = $pane.attr('data-pane-content-url'); + $.ajax(content_url, {dataType: 'html', type: 'GET', context: $pane}). + done(function(data, status, jqxhr) { + // Preserve collapsed state + var $pane = this; + var collapsable = {}; + $(".collapse", this).each(function(i, c) { + collapsable[c.id] = $(c).hasClass('in'); + }); + var tmp = $(data); + $(".collapse", tmp).each(function(i, c) { + if (collapsable[c.id]) { + $(c).addClass('in'); + } else { + $(c).removeClass('in'); + } + }); + $pane.html(tmp); + $pane.removeClass('pane-loading'); + $pane.addClass('pane-loaded'); + $pane.attr('data-loaded-at', (new Date()).getTime()); + $pane.trigger('arv:pane:loaded', [$pane]); + + if ($pane.hasClass('pane-stale')) { + $pane.trigger('arv:pane:reload'); + } + }).fail(function(jqxhr, status, error) { + var $pane = this; + var errhtml; + var contentType = jqxhr.getResponseHeader('Content-Type'); + if (contentType && contentType.match(/\btext\/html\b/)) { + var $response = $(jqxhr.responseText); + var $wrapper = $('div#page-wrapper', $response); + if ($wrapper.length) { + errhtml = $wrapper.html(); + } else { + errhtml = jqxhr.responseText; + } + } else { + errhtml = ("An error occurred: " + + (jqxhr.responseText || status)). + replace(/&/g, '&'). + replace(//g, '>'); + } + $pane.html('
'); + $('.tab_reload', $pane).click(function() { + $(this). + html('
'). + closest('.pane-loaded'). + attr('data-loaded-at', 0). + trigger('arv:pane:reload'); + }); + // We want to render the error in an iframe, in order to + // avoid conflicts with the main page's element ids, etc. + // In order to do that dynamically, we have to set a + // timeout on the iframe window to load our HTML *after* + // the default source (e.g., about:blank) has loaded. + var iframe = $('iframe', $pane)[0]; + iframe.contentWindow.setTimeout(function() { + $('body', iframe.contentDocument).html(errhtml); + iframe.height = iframe.contentDocument.body.scrollHeight + "px"; + }, 1); + $pane.removeClass('pane-loading'); + $pane.addClass('pane-loaded'); + }); +}); + +// Mark all panes as stale/dirty. Refresh any 'active' panes. +$(document).on('arv:pane:reload:all', function() { + $('[data-pane-content-url]').trigger('arv:pane:reload'); +}); + +$(document).on('arv-log-event', '.arv-refresh-on-log-event', function(event) { + if (this != event.target) { + // Not interested in events sent to child nodes. + return; + } + // Panes marked arv-refresh-on-log-event should be refreshed + $(event.target).trigger('arv:pane:reload'); +}); + +// If there is a 'tab counts url' in the nav-tabs element then use it to get some javascript that will update them +$(document).on('ready count-change', function() { + var tabCountsUrl = $('ul.nav-tabs').data('tab-counts-url'); + if( tabCountsUrl && tabCountsUrl.length ) { + $.get( tabCountsUrl ); + } +}); diff --git a/apps/workbench/app/assets/javascripts/upload_to_collection.js b/apps/workbench/app/assets/javascripts/upload_to_collection.js new file mode 100644 index 0000000000..d4333faaa9 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/upload_to_collection.js @@ -0,0 +1,476 @@ +var app = angular.module('Workbench', ['Arvados']); +app.controller('UploadToCollection', UploadToCollection); +app.directive('arvUuid', arvUuid); + +function arvUuid() { + // Copy the given uuid into the current $scope. + return { + restrict: 'A', + link: function(scope, element, attributes) { + scope.uuid = attributes.arvUuid; + } + }; +} + +UploadToCollection.$inject = ['$scope', '$filter', '$q', '$timeout', + 'ArvadosClient', 'arvadosApiToken']; +function UploadToCollection($scope, $filter, $q, $timeout, + ArvadosClient, arvadosApiToken) { + $.extend($scope, { + uploadQueue: [], + uploader: new QueueUploader(), + addFilesToQueue: function(files) { + // Angular binding doesn't work its usual magic for file + // inputs, so we need to $scope.$apply() this update. + $scope.$apply(function(){ + var i, nItemsTodo; + // Add these new files after the items already waiting + // in the queue -- but before the items that are + // 'Done' and have therefore been pushed to the + // bottom. + for (nItemsTodo = 0; + (nItemsTodo < $scope.uploadQueue.length && + $scope.uploadQueue[nItemsTodo].state !== 'Done'); ) { + nItemsTodo++; + } + for (i=0; i= 0) { + ++found; + } + }); + return found; + } + }); + //////////////////////////////// + + var keepProxy; + + function SliceReader(_slice) { + var that = this; + $.extend(this, { + go: go + }); + //////////////////////////////// + var _deferred; + var _reader; + function go() { + // Return a promise, which will be resolved with the + // requested slice data. + _deferred = $.Deferred(); + _reader = new FileReader(); + _reader.onload = resolve; + _reader.onerror = _deferred.reject; + _reader.onprogress = _deferred.notify; + _reader.readAsArrayBuffer(_slice.blob); + return _deferred.promise(); + } + function resolve() { + if (that._reader.result.length !== that._slice.size) { + // Sometimes we get an onload event even if the read + // did not return the desired number of bytes. We + // treat that as a fail. + _deferred.reject( + null, "Read error", + "Short read: wanted " + _slice.size + + ", received " + _reader.result.length); + return; + } + return _deferred.resolve(_reader.result); + } + } + + function SliceUploader(_label, _data, _dataSize) { + $.extend(this, { + go: go, + stop: stop + }); + //////////////////////////////// + var that = this; + var _deferred; + var _failCount = 0; + var _failMax = 3; + var _jqxhr; + function go() { + // Send data to the Keep proxy. Retry a few times on + // fail. Return a promise that will get resolved with + // resolve(locator) when the block is accepted by the + // proxy. + _deferred = $.Deferred(); + goSend(); + return _deferred.promise(); + } + function stop() { + _failMax = 0; + _jqxhr.abort(); + _deferred.reject({ + textStatus: 'stopped', + err: 'interrupted at slice '+_label + }); + } + function goSend() { + _jqxhr = $.ajax({ + url: proxyUriBase(), + type: 'POST', + crossDomain: true, + headers: { + 'Authorization': 'OAuth2 '+arvadosApiToken, + 'Content-Type': 'application/octet-stream', + 'X-Keep-Desired-Replicas': '2' + }, + xhr: function() { + // Make an xhr that reports upload progress + var xhr = $.ajaxSettings.xhr(); + if (xhr.upload) { + xhr.upload.onprogress = onSendProgress; + } + return xhr; + }, + processData: false, + data: _data + }); + _jqxhr.then(onSendResolve, onSendReject); + } + function onSendProgress(xhrProgressEvent) { + _deferred.notify(xhrProgressEvent.loaded, _dataSize); + } + function onSendResolve(data, textStatus, jqxhr) { + _deferred.resolve(data, _dataSize); + } + function onSendReject(xhr, textStatus, err) { + if (++_failCount < _failMax) { + // TODO: nice to tell the user that retry is happening. + console.log('slice ' + _label + ': ' + + textStatus + ', retry ' + _failCount); + goSend(); + } else { + _deferred.reject( + {xhr: xhr, textStatus: textStatus, err: err}); + } + } + function proxyUriBase() { + return ((keepProxy.service_ssl_flag ? 'https' : 'http') + + '://' + keepProxy.service_host + ':' + + keepProxy.service_port + '/'); + } + } + + function FileUploader(file) { + $.extend(this, { + file: file, + locators: [], + progress: 0.0, + state: 'Queued', // Queued, Uploading, Paused, Uploaded, Done + statistics: null, + go: go, + stop: stop // User wants to stop. + }); + //////////////////////////////// + var that = this; + var _currentUploader; + var _currentSlice; + var _deferred; + var _maxBlobSize = Math.pow(2,26); + var _bytesDone = 0; + var _queueTime = Date.now(); + var _startTime; + var _startByte; + var _finishTime; + var _readPos = 0; // number of bytes confirmed uploaded + function go() { + if (_deferred) + _deferred.reject({textStatus: 'restarted'}); + _deferred = $.Deferred(); + that.state = 'Uploading'; + _startTime = Date.now(); + _startByte = _readPos; + setProgress(); + goSlice(); + return _deferred.promise().always(function() { _deferred = null; }); + } + function stop() { + if (_deferred) { + that.state = 'Paused'; + _deferred.reject({textStatus: 'stopped', err: 'interrupted'}); + } + if (_currentUploader) { + _currentUploader.stop(); + _currentUploader = null; + } + } + function goSlice() { + // Ensure this._deferred gets resolved or rejected -- + // either right here, or when a new promise arranged right + // here is fulfilled. + _currentSlice = nextSlice(); + if (!_currentSlice) { + // All slices have been uploaded, but the work won't + // be truly Done until the target collection has been + // updated by the QueueUploader. This state is called: + that.state = 'Uploaded'; + setProgress(_readPos); + _currentUploader = null; + _deferred.resolve([that]); + return; + } + _currentUploader = new SliceUploader( + _readPos.toString(), + _currentSlice.blob, + _currentSlice.size); + _currentUploader.go().then( + onUploaderResolve, + onUploaderReject, + onUploaderProgress); + } + function onUploaderResolve(locator, dataSize) { + var sizeHint = (''+locator).split('+')[1]; + if (!locator || parseInt(sizeHint) !== dataSize) { + console.log("onUploaderResolve, but locator '" + locator + + "' with size hint '" + sizeHint + + "' does not look right for dataSize=" + dataSize); + return onUploaderReject({ + textStatus: "error", + err: "Bad response from slice upload" + }); + } + that.locators.push(locator); + _readPos += dataSize; + _currentUploader = null; + goSlice(); + } + function onUploaderReject(reason) { + that.state = 'Paused'; + setProgress(_readPos); + _currentUploader = null; + if (_deferred) + _deferred.reject(reason); + } + function onUploaderProgress(sliceDone, sliceSize) { + setProgress(_readPos + sliceDone); + } + function nextSlice() { + var size = Math.min( + _maxBlobSize, + that.file.size - _readPos); + setProgress(_readPos); + if (size === 0) { + return false; + } + var blob = that.file.slice( + _readPos, _readPos+size, + 'application/octet-stream; charset=x-user-defined'); + return {blob: blob, size: size}; + } + function setProgress(bytesDone) { + var kBps; + if (that.file.size == 0) + that.progress = 100; + else + that.progress = Math.min(100, 100 * bytesDone / that.file.size); + if (bytesDone > _startByte) { + kBps = (bytesDone - _startByte) / + (Date.now() - _startTime); + that.statistics = ( + '' + $filter('number')(bytesDone/1024, '0') + ' KiB ' + + 'at ~' + $filter('number')(kBps, '0') + ' KiB/s') + if (that.state === 'Paused') { + that.statistics += ', paused'; + } else if (that.state === 'Uploading') { + that.statistics += ', ETA ' + + $filter('date')( + new Date( + Date.now() + (that.file.size - bytesDone) / kBps), + 'shortTime') + } + } else { + that.statistics = that.state; + } + if (that.state === 'Uploaded') { + // 'Uploaded' gets reported as 'finished', which is a + // little misleading because the collection hasn't + // been updated yet. But FileUploader's portion of the + // work (and the time when it makes sense to show + // speed and ETA) is finished. + that.statistics += ', finished ' + + $filter('date')(Date.now(), 'shortTime'); + _finishTime = Date.now(); + } + if (_deferred) + _deferred.notify(); + } + } + + function QueueUploader() { + $.extend(this, { + state: 'Idle', // Idle, Running, Stopped, Failed + stateReason: null, + statusSuccess: null, + go: go, + stop: stop + }); + //////////////////////////////// + var that = this; + var _deferred; // the one we promise to go()'s caller + var _deferredAppend; // tracks current appendToCollection + function go() { + if (_deferred) return _deferred.promise(); + if (_deferredAppend) return _deferredAppend.promise(); + _deferred = $.Deferred(); + that.state = 'Running'; + ArvadosClient.apiPromise( + 'keep_services', 'list', + {filters: [['service_type','=','proxy']]}). + then(doQueueWithProxy); + onQueueProgress(); + return _deferred.promise().always(function() { _deferred = null; }); + } + function stop() { + that.state = 'Stopped'; + if (_deferred) { + _deferred.reject({}); + } + for (var i=0; i<$scope.uploadQueue.length; i++) + $scope.uploadQueue[i].stop(); + onQueueProgress(); + } + function doQueueWithProxy(data) { + keepProxy = data.items[0]; + if (!keepProxy) { + that.state = 'Failed'; + that.stateReason = + 'There seems to be no Keep proxy service available.'; + _deferred.reject(null, 'error', that.stateReason); + return; + } + return doQueueWork(); + } + function doQueueWork() { + // If anything is not Done, do it. + if ($scope.uploadQueue.length > 0 && + $scope.uploadQueue[0].state !== 'Done') { + if (_deferred) { + that.stateReason = null; + return $scope.uploadQueue[0].go(). + then(appendToCollection, null, onQueueProgress). + then(doQueueWork, onQueueReject); + } else { + // Queue work has been stopped. Just update the + // view. + onQueueProgress(); + return; + } + } + // If everything is Done, resolve the promise and clean + // up. Note this can happen even after the _deferred + // promise has been rejected: specifically, when stop() is + // called too late to prevent completion of the last + // upload. In that case we want to update state to "Idle", + // rather than leave it at "Stopped". + onQueueResolve(); + } + function onQueueReject(reason) { + if (!_deferred) { + // Outcome has already been decided (by stop()). + return; + } + + that.state = 'Failed'; + that.stateReason = ( + (reason.textStatus || 'Error') + + (reason.xhr && reason.xhr.options + ? (' (from ' + reason.xhr.options.url + ')') + : '') + + ': ' + + (reason.err || '')); + if (reason.xhr && reason.xhr.responseText) + that.stateReason += ' -- ' + reason.xhr.responseText; + _deferred.reject(reason); + onQueueProgress(); + } + function onQueueResolve() { + that.state = 'Idle'; + that.stateReason = 'Done!'; + if (_deferred) + _deferred.resolve(); + onQueueProgress(); + } + function onQueueProgress() { + // Ensure updates happen after FileUpload promise callbacks. + $timeout(function(){$scope.$apply();}); + } + function appendToCollection(uploads) { + _deferredAppend = $.Deferred(); + ArvadosClient.apiPromise( + 'collections', 'get', + { uuid: $scope.uuid }). + then(function(collection) { + var manifestText = ''; + $.each(uploads, function(_, upload) { + var locators = upload.locators; + if (locators.length === 0) { + // Every stream must have at least one + // data locator, even if it is zero bytes + // long: + locators = ['d41d8cd98f00b204e9800998ecf8427e+0']; + } + filename = ArvadosClient.uniqueNameForManifest( + collection.manifest_text, + '.', upload.file.name); + collection.manifest_text += '. ' + + locators.join(' ') + + ' 0:' + upload.file.size.toString() + ':' + + filename + + '\n'; + }); + return ArvadosClient.apiPromise( + 'collections', 'update', + { uuid: $scope.uuid, + collection: + { manifest_text: + collection.manifest_text } + }); + }). + then(function() { + // Mark the completed upload(s) as Done and push + // them to the bottom of the queue. + var i, qLen = $scope.uploadQueue.length; + for (i=0; i= 0) { + $scope.uploadQueue[i].state = 'Done'; + $scope.uploadQueue.push.apply( + $scope.uploadQueue, + $scope.uploadQueue.splice(i, 1)); + --i; + --qLen; + } + } + }). + then(_deferredAppend.resolve, + _deferredAppend.reject); + return _deferredAppend.promise(). + always(function() { + _deferredAppend = null; + }); + } + } +} diff --git a/apps/workbench/app/assets/javascripts/user_agreements.js b/apps/workbench/app/assets/javascripts/user_agreements.js new file mode 100644 index 0000000000..1b9ce4b684 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/user_agreements.js @@ -0,0 +1,7 @@ +function enable_okbutton() { + var $div = $('#open_user_agreement'); + var allchecked = $('input[name="checked[]"]', $div).not(':checked').length == 0; + $('input[type=submit]', $div).prop('disabled', !allchecked); +} +$(document).on('click keyup input', '#open_user_agreement input', enable_okbutton); +$(document).on('ready ajax:complete', enable_okbutton); diff --git a/apps/workbench/app/assets/javascripts/users.js b/apps/workbench/app/assets/javascripts/users.js new file mode 100644 index 0000000000..ee1c7dda37 --- /dev/null +++ b/apps/workbench/app/assets/javascripts/users.js @@ -0,0 +1,47 @@ +$(document). + on('notifications:recount', + function() { + var menu = $('.notification-menu'); + n = $('.notification', menu).not('.empty').length; + $('.notification-count', menu).html(n>0 ? n : ''); + }). + on('ajax:success', 'form.new_authorized_key', + function(e, data, status, xhr) { + $(e.target).parents('.notification').eq(0).fadeOut('slow', function() { + $('
  • SSH key added.
  • ').hide().replaceAll(this).fadeIn('slow'); + $(document).trigger('notifications:recount'); + }); + }). + on('ajax:complete', 'form.new_authorized_key', + function(e, data, status, xhr) { + $($('input[name=disable_element]', e.target).val()). + fadeTo(200, 1.0); + }). + on('ajax:error', 'form.new_authorized_key', + function(e, xhr, status, error) { + var error_div; + response = $.parseJSON(xhr.responseText); + error_div = $(e.target).parent().find('div.ajax-errors'); + if (error_div.length == 0) { + $(e.target).parent().append('
    '); + error_div = $(e.target).parent().find('div.ajax-errors'); + } + if (response.errors) { + error_div.html($('

    ').text(response.errors).html()); + } else { + error_div.html('

    Sorry, request failed.'); + } + error_div.show(); + $($('input[name=disable_element]', e.target).val()). + fadeTo(200, 1.0); + }). + on('click', 'form[data-remote] input[type=submit]', + function(e) { + $(e.target).parents('form').eq(0).parent().find('div.ajax-errors').html('').hide(); + $($(e.target). + parents('form'). + find('input[name=disable_element]'). + val()). + fadeTo(200, 0.3); + return true; + }); diff --git a/apps/workbench/app/assets/stylesheets/api_client_authorizations.css.scss b/apps/workbench/app/assets/stylesheets/api_client_authorizations.css.scss new file mode 100644 index 0000000000..fd2c9d86b0 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/api_client_authorizations.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the ApiClientAuthorizations controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/application.css.scss b/apps/workbench/app/assets/stylesheets/application.css.scss new file mode 100644 index 0000000000..9bc93e32bd --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/application.css.scss @@ -0,0 +1,282 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, + * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the top of the + * compiled file, but it's generally better to create a new file per style scope. + * + *= require_self + *= require bootstrap + *= require bootstrap3-editable/bootstrap-editable + *= require morris + *= require_tree . + */ + +.contain-align-left { + text-align: left; +} +table.topalign>tbody>tr>td { + vertical-align: top; +} +table.topalign>thead>tr>td { + vertical-align: bottom; +} +tr.cell-valign-center>td { + vertical-align: middle; +} +tr.cell-noborder>td,tr.cell-noborder>th { + border: none; +} +table.table-justforlayout>tr>td, +table.table-justforlayout>tr>th, +table.table-justforlayout>thead>tr>td, +table.table-justforlayout>thead>tr>th, +table.table-justforlayout>tbody>tr>td, +table.table-justforlayout>tbody>tr>th{ + border: none; +} +table.table-justforlayout { + margin-bottom: 0; +} +.smaller-text { + font-size: .8em; +} +.deemphasize { + font-size: .8em; + color: #888; +} +.lighten { + color: #888; +} +.arvados-filename, +.arvados-uuid { + font-size: .8em; + font-family: monospace; +} +table .data-size, .table .data-size { + text-align: right; +} +body .editable-empty { + color: #999; +} +body .editable-empty:hover { + color: #0088cc; +} +table.arv-index tbody td.arv-object-AuthorizedKey.arv-attr-public_key { + overflow-x: hidden; + max-width: 120px; +} +table.arv-index > thead > tr > th { + border-top: none; +} +table.table-fixedlayout { + white-space: nowrap; + table-layout: fixed; +} +table.table-fixedlayout td { + overflow: hidden; + overflow-x: hidden; + text-overflow: ellipsis; +} +table.table-smallcontent td { + font-size: 85%; +} +form input.search-mini { + padding: 0 6px; +} +form.small-form-margin { + margin-bottom: 2px; +} +.nowrap { + white-space: nowrap; +} + +/* top nav */ +$top-nav-bg: #3c163d; +$top-nav-bg-bottom: #260027; +nav.navbar-fixed-top .navbar-brand { + color: #79537a; + letter-spacing: 0.4em; +} +nav.navbar-fixed-top { + background: $top-nav-bg; + background: linear-gradient(to bottom, $top-nav-bg 0%,$top-nav-bg-bottom 100%); +} +.navbar.breadcrumbs { + line-height: 50px; + border-radius: 0; + margin-bottom: 0; + border-right: 0; + border-left: 0; +} +.navbar.breadcrumbs .nav > li > a, +.navbar.breadcrumbs .nav > li { + color: #000; +} +.navbar.breadcrumbs .nav > li.nav-separator > i { + color: #bbb; +} +.navbar.breadcrumbs .navbar-form { + margin-top: 0px; + margin-bottom: 0px; +} +.navbar.breadcrumbs .navbar-text { + margin-top: 0px; + margin-bottom: 0px; +} + +nav.navbar-fixed-top .navbar-nav.navbar-right > li.open > a, +nav.navbar-fixed-top .navbar-nav.navbar-right > li.open > a:focus, +nav.navbar-fixed-top .navbar-nav.navbar-right > li.open > a:hover { + background: lighten($top-nav-bg, 5%); +} +nav.navbar-fixed-top .navbar-nav.navbar-right > li > a, +nav.navbar-fixed-top .navbar-nav.navbar-right > li > a:focus, +nav.navbar-fixed-top .navbar-nav.navbar-right > li > a:hover { + color: #fff; +} + +.dax { + max-width: 10%; + margin-right: 1em; + float: left +} + +.smart-scroll { + overflow: auto; + margin-bottom: -15px; +} + +.infinite-scroller .fa-warning { + color: #800; +} + +th[data-sort-order] { + cursor: pointer; +} + +.inline-progress-container div.progress { + margin-bottom: 0; +} + +.inline-progress-container { + width: 100%; + display:inline-block; +} + +td.add-tag-button { + white-space: normal; +} +td.add-tag-button .add-tag-button { + margin-right: 4px; + opacity: 0.2; +} +td.add-tag-button .add-tag-button:hover { + opacity: 1; +} +span.removable-tag-container { + line-height: 1.6; +} +.label.removable-tag a { + color: #fff; + cursor: pointer; +} + +li.notification { + padding: 10px; +} + +// See HeaderRowFixer in application.js +table.table-fixed-header-row { + width: 100%; + border-spacing: 0px; + margin:0; +} +table.table-fixed-header-row thead { + position:fixed; + background: #fff; +} +table.table-fixed-header-row tbody { + position:relative; + top:1.5em; +} + +.dropdown-menu { + max-height: 30em; + overflow-y: auto; +} + +.row-fill-height, .row-fill-height>div[class*='col-'] { + display: flex; +} +.row-fill-height>div[class*='col-']>div { + width: 100%; +} + +/* Show editable popover above side-nav */ +.editable-popup.popover { + z-index:1055; +} + +/* Do not leave space for left-nav */ +div#wrapper { + padding-left: 0; +} + +.arv-description-as-subtitle { + padding-bottom: 1em; +} +.arv-description-in-table { + height: 4em; + overflow-x: hidden; + overflow-y: hidden; +} +.arv-description-in-table:hover { + overflow-y: auto; +} + +.btn.btn-nodecorate { + border: none; +} +svg text { + font-size: 6pt; +} + +div.pane-content iframe { + width: 100%; + border: none; +} +span.editable-textile { + display: inline-block; +} +.text-overflow-ellipsis { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.time-label-divider { + font-size: 80%; + min-width: 1em; + padding: 0px 2px 0px 0px; +} +.task-summary-status { + font-size: 80%; +} +#page-wrapper > div > h2 { + margin-top: 0px; +} + +.compute-summary-numbers td { + font-size: 150%; +} + +.arv-log-refresh-control { + display: none; +} + +[ng\:cloak], [ng-cloak], .ng-cloak { + display: none !important; +} diff --git a/apps/workbench/app/assets/stylesheets/authorized_keys.css.scss b/apps/workbench/app/assets/stylesheets/authorized_keys.css.scss new file mode 100644 index 0000000000..390576b164 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/authorized_keys.css.scss @@ -0,0 +1,10 @@ +// Place all the styles related to the AuthorizedKeys controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ +form .table input[type=text] { + width: 600px; +} +form .table textarea { + width: 600px; + height: 10em; +} diff --git a/apps/workbench/app/assets/stylesheets/badges.css.scss b/apps/workbench/app/assets/stylesheets/badges.css.scss new file mode 100644 index 0000000000..82c4ab0e02 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/badges.css.scss @@ -0,0 +1,28 @@ +/* Colors + * Contextual variations of badges + * Bootstrap 3.0 removed contexts for badges, we re-introduce them, based on what is done for labels + */ + +.badge.badge-error { + background-color: #b94a48; +} + +.badge.badge-warning { + background-color: #f89406; +} + +.badge.badge-success { + background-color: #468847; +} + +.badge.badge-info { + background-color: #3a87ad; +} + +.badge.badge-inverse { + background-color: #333333; +} + +.badge.badge-alert { + background: red; +} diff --git a/apps/workbench/app/assets/stylesheets/cards.css.scss b/apps/workbench/app/assets/stylesheets/cards.css.scss new file mode 100644 index 0000000000..c9560adf86 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/cards.css.scss @@ -0,0 +1,85 @@ +.card { + padding-top: 20px; + margin: 10px 0 20px 0; + background-color: #ffffff; + border: 1px solid #d8d8d8; + border-top-width: 0; + border-bottom-width: 2px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +.card.arvados-object { + position: relative; + display: inline-block; + width: 170px; + height: 175px; + padding-top: 0; + margin-left: 20px; + overflow: hidden; + vertical-align: top; +} +.card.arvados-object .card-top.green { + background-color: #53a93f; +} +.card.arvados-object .card-top.blue { + background-color: #427fed; +} +.card.arvados-object .card-top { + position: absolute; + top: 0; + left: 0; + display: inline-block; + width: 170px; + height: 25px; + background-color: #ffffff; +} +.card.arvados-object .card-info { + position: absolute; + top: 25px; + display: inline-block; + width: 100%; + height: 101px; + overflow: hidden; + background: #ffffff; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +.card.arvados-object .card-info .title { + display: block; + margin: 8px 14px 0 14px; + overflow: hidden; + font-size: 16px; + font-weight: bold; + line-height: 18px; + color: #404040; +} +.card.arvados-object .card-info .desc { + display: block; + margin: 8px 14px 0 14px; + overflow: hidden; + font-size: 12px; + line-height: 16px; + color: #737373; + text-overflow: ellipsis; +} +.card.arvados-object .card-bottom { + position: absolute; + bottom: 0; + left: 0; + display: inline-block; + width: 100%; + padding: 10px 20px; + line-height: 29px; + text-align: center; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} diff --git a/apps/workbench/app/assets/stylesheets/collections.css.scss b/apps/workbench/app/assets/stylesheets/collections.css.scss new file mode 100644 index 0000000000..35c2249ecf --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/collections.css.scss @@ -0,0 +1,66 @@ +/* Style for _show_files tree view. */ + +ul#collection_files { + padding: 0 .5em; +} + +ul.collection_files { + line-height: 2.5em; + list-style-type: none; + padding-left: 2.3em; +} + +ul.collection_files li { + clear: both; +} + +.collection_files_row { + padding: 1px; /* Replaced by border for :hover */ +} + +.collection_files_row:hover { + background-color: #D9EDF7; + padding: 0px; + border: 1px solid #BCE8F1; + border-radius: 3px; +} + +.collection_files_inline { + clear: both; + width: 80%; + margin: 0 3em; +} + +.collection_files_inline img { + max-height: 15em; +} + +.collection_files_name { + padding-left: .5em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.collection_files_name i.fa-fw:first-child { + width: 1.6em; +} + +/* + "active" and "inactive" colors are too similar for a toggle switch + in the default bootstrap theme. + */ + +$inactive-bg: #5bc0de; +$active-bg: #39b3d7; + +.btn-group.toggle-persist .btn { + width: 6em; +} +.btn-group.toggle-persist .btn-info { + background-color: lighten($inactive-bg, 15%); +} + +.btn-group.toggle-persist .btn-info.active { + background-color: $active-bg; +} diff --git a/apps/workbench/app/assets/stylesheets/groups.css.scss b/apps/workbench/app/assets/stylesheets/groups.css.scss new file mode 100644 index 0000000000..679563657b --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/groups.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Groups controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/humans.css.scss b/apps/workbench/app/assets/stylesheets/humans.css.scss new file mode 100644 index 0000000000..f8afcdfeeb --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/humans.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Humans controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/job_tasks.css.scss b/apps/workbench/app/assets/stylesheets/job_tasks.css.scss new file mode 100644 index 0000000000..ab340e918b --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/job_tasks.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the JobTasks controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/jobs.css.scss b/apps/workbench/app/assets/stylesheets/jobs.css.scss new file mode 100644 index 0000000000..cf93f20350 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/jobs.css.scss @@ -0,0 +1,15 @@ +.arv-job-log-window { + height: 40em; + white-space: pre; + overflow: scroll; + background: black; + color: white; + font-family: monospace; + font-size: .8em; + border: 2px solid black; +} + +.morris-hover-point { + text-align: left; + width: 100%; +} \ No newline at end of file diff --git a/apps/workbench/app/assets/stylesheets/keep_disks.css.scss b/apps/workbench/app/assets/stylesheets/keep_disks.css.scss new file mode 100644 index 0000000000..e7a1b12c96 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/keep_disks.css.scss @@ -0,0 +1,11 @@ +// Place all the styles related to the KeepDisks controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +/* Margin allows us some space between the table above. */ +div.graph { + margin-top: 20px; +} +div.graph h3, div.graph h4 { + text-align: center; +} diff --git a/apps/workbench/app/assets/stylesheets/links.css.scss b/apps/workbench/app/assets/stylesheets/links.css.scss new file mode 100644 index 0000000000..220eb7091f --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/links.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Links controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/loading.css.scss.erb b/apps/workbench/app/assets/stylesheets/loading.css.scss.erb new file mode 100644 index 0000000000..9f74866f53 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/loading.css.scss.erb @@ -0,0 +1,68 @@ +.loading { + opacity: 0; +} + +.spinner { + /* placeholder for stuff like $.find('.spinner').detach() */ +} + +.spinner-32px { + background-image: url('<%= asset_path('spinner_32px.gif') %>'); + background-repeat: no-repeat; + width: 32px; + height: 32px; +} + +.spinner-h-center { + margin-left: auto; + margin-right: auto; +} + +.spinner-v-center { + position: relative; + top: 45%; +} + +.rotating { + color: #f00; + /* Chrome and Firefox, at least in Linux, render a horrible shaky + mess -- better not to bother. + + animation-name: rotateThis; + animation-duration: 2s; + animation-iteration-count: infinite; + animation-timing-function: linear; + -moz-animation-name: rotateThis; + -moz-animation-duration: 2s; + -moz-animation-iteration-count: infinite; + -moz-animation-timing-function: linear; + -ms-animation-name: rotateThis; + -ms-animation-duration: 2s; + -ms-animation-iteration-count: infinite; + -ms-animation-timing-function: linear; + -webkit-animation-name: rotateThis; + -webkit-animation-duration: 2s; + -webkit-animation-iteration-count: infinite; + -webkit-animation-timing-function: linear; + */ +} + +@keyframes rotateThis { + from { transform: rotate( 0deg ); } + to { transform: rotate( 360deg ); } +} + +@-webkit-keyframes rotateThis { + from { -webkit-transform: rotate( 0deg ); } + to { -webkit-transform: rotate( 360deg ); } +} + +@-moz-keyframes rotateThis { + from { -moz-transform: rotate( 0deg ); } + to { -moz-transform: rotate( 360deg ); } +} + +@-ms-keyframes rotateThis { + from { -ms-transform: rotate( 0deg ); } + to { -ms-transform: rotate( 360deg ); } +} diff --git a/apps/workbench/app/assets/stylesheets/log_viewer.scss b/apps/workbench/app/assets/stylesheets/log_viewer.scss new file mode 100644 index 0000000000..318f6e7792 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/log_viewer.scss @@ -0,0 +1,64 @@ +.log-viewer-table { + width: 100%; + font-family: "Lucida Console", Monaco, monospace; + font-size: 11px; + table-layout: fixed; + thead tr { + th { + padding-right: 1em; + } + th.id { + display: none; + } + th.timestamp { + width: 15em; + } + th.type { + width: 8em; + } + th.taskid { + width: 4em; + } + th.node { + width: 8em; + } + th.slot { + width: 3em; + } + th.message { + width: auto; + } + } + tbody tr { + vertical-align: top; + td { + padding-right: 1em; + } + td.id { + display: none; + } + td.taskid { + text-align: right; + } + td.slot { + text-align: right; + } + td.message { + word-wrap: break-word; + } + } +} + +.log-viewer-button { + width: 12em; +} + +.log-viewer-paging-div { + font-size: 18px; + text-align: center; +} + +.log-viewer-page-num { + padding-left: .3em; + padding-right: .3em; +} \ No newline at end of file diff --git a/apps/workbench/app/assets/stylesheets/logs.css.scss b/apps/workbench/app/assets/stylesheets/logs.css.scss new file mode 100644 index 0000000000..4aaccac1b8 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/logs.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Logs controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/nodes.css.scss b/apps/workbench/app/assets/stylesheets/nodes.css.scss new file mode 100644 index 0000000000..721060242b --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/nodes.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Nodes controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/pipeline_instances.css.scss b/apps/workbench/app/assets/stylesheets/pipeline_instances.css.scss new file mode 100644 index 0000000000..c89e93d670 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/pipeline_instances.css.scss @@ -0,0 +1,33 @@ +// Place all the styles related to the PipelineInstances controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +.pipeline-compare-headrow div { + padding-top: .5em; + padding-bottom: .5em; +} +.pipeline-compare-headrow:first-child { + border-bottom: 1px solid black; +} +.pipeline-compare-row .notnormal { + background: #ffffaa; +} + +.pipeline_color_legend { + margin-top: 0.2em; + padding: 0.2em 1em; + border: 1px solid #000; +} +.pipeline_color_legend a { + color: #000; +} + +.col-md-1.pipeline-instance-spacing { + padding: 0px; + margin: 0px; +} + +.col-md-3.pipeline-instance-spacing > .progress { + padding: 0px; + margin: 0px; +} \ No newline at end of file diff --git a/apps/workbench/app/assets/stylesheets/pipeline_templates.css.scss b/apps/workbench/app/assets/stylesheets/pipeline_templates.css.scss new file mode 100644 index 0000000000..c70377a6ff --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/pipeline_templates.css.scss @@ -0,0 +1,30 @@ +// Place all the styles related to the PipelineTemplates controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ + +.pipeline_color_legend { + padding-left: 1em; + padding-right: 1em; +} + +table.pipeline-components-table { + width: 100%; + table-layout: fixed; + overflow: hidden; +} + +table.pipeline-components-table thead th { + text-align: bottom; +} +table.pipeline-components-table div.progress { + margin-bottom: 0; +} + +table.pipeline-components-table td { + overflow: hidden; + text-overflow: ellipsis; +} + +td.required { + background: #ffdddd; +} diff --git a/apps/workbench/app/assets/stylesheets/projects.css.scss b/apps/workbench/app/assets/stylesheets/projects.css.scss new file mode 100644 index 0000000000..cf1d15e6e0 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/projects.css.scss @@ -0,0 +1,67 @@ +.arv-project-list > .row { + padding-top: 5px; + padding-bottom: 5px; + padding-right: 1em; +} +.arv-project-list > .row.project:hover { + background: #d9edf7; +} +div.scroll-20em { + height: 20em; + overflow-y: scroll; +} + +.compute-summary { + margin: 0.15em 0em 0.15em 0em; + display: inline-block; +} + +.compute-summary-head { + margin-left: 0.3em; +} + +.compute-detail { + border: 1px solid; + border-color: #DDD; + border-radius: 3px; + padding: 0.2em; + position: absolute; + z-index: 1; + background: white; +} + +.compute-detail:hover { + cursor: pointer; +} + +.compute-node-summary:hover { + cursor: pointer; +} + +.compute-summary-numbers .panel { + margin-bottom: 0px; +} + +.compute-summary-numbers table { + width: 100%; + td,th { + text-align: center; + } +} + +.compute-summary-nodelist { + margin-bottom: 10px +} + +.dashboard-panel-info-row { + padding: .5em; + border-radius: .3em; +} + +.dashboard-panel-info-row:hover { + background-color: #D9EDF7; +} + +.progress-bar.progress-bar-default { + background-color: #999; +} \ No newline at end of file diff --git a/apps/workbench/app/assets/stylesheets/repositories.css.scss b/apps/workbench/app/assets/stylesheets/repositories.css.scss new file mode 100644 index 0000000000..85e38d231e --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/repositories.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Repositories controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/sb-admin.css.scss b/apps/workbench/app/assets/stylesheets/sb-admin.css.scss new file mode 100644 index 0000000000..9bae214882 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/sb-admin.css.scss @@ -0,0 +1,164 @@ +/* +Author: Start Bootstrap - http://startbootstrap.com +'SB Admin' HTML Template by Start Bootstrap + +All Start Bootstrap themes are licensed under Apache 2.0. +For more info and more free Bootstrap 3 HTML themes, visit http://startbootstrap.com! +*/ + +/* ATTN: This is mobile first CSS - to update 786px and up screen width use the media query near the bottom of the document! */ + +/* Global Styles */ + +body { + margin-top: 50px; +} + +#wrapper { + padding-left: 0; +} + +#page-wrapper { + width: 100%; + padding: 5px 15px; +} + +/* Nav Messages */ + +.messages-dropdown .dropdown-menu .message-preview .avatar, +.messages-dropdown .dropdown-menu .message-preview .name, +.messages-dropdown .dropdown-menu .message-preview .message, +.messages-dropdown .dropdown-menu .message-preview .time { + display: block; +} + +.messages-dropdown .dropdown-menu .message-preview .avatar { + float: left; + margin-right: 15px; +} + +.messages-dropdown .dropdown-menu .message-preview .name { + font-weight: bold; +} + +.messages-dropdown .dropdown-menu .message-preview .message { + font-size: 12px; +} + +.messages-dropdown .dropdown-menu .message-preview .time { + font-size: 12px; +} + + +/* Nav Announcements */ + +.announcement-heading { + font-size: 50px; + margin: 0; +} + +.announcement-text { + margin: 0; +} + +/* Table Headers */ + +table.tablesorter thead { + cursor: pointer; +} + +table.tablesorter thead tr th:hover { + background-color: #f5f5f5; +} + +/* Flot Chart Containers */ + +.flot-chart { + display: block; + height: 400px; +} + +.flot-chart-content { + width: 100%; + height: 100%; +} + +/* Edit Below to Customize Widths > 768px */ +@media (min-width:768px) { + + /* Wrappers */ + + #wrapper { + padding-left: 225px; + } + + #page-wrapper { + padding: 15px 25px; + } + + /* Side Nav */ + + .side-nav { + margin-left: -225px; + left: 225px; + width: 225px; + position: fixed; + top: 50px; + height: calc(100% - 50px); + border-radius: 0; + border: none; + background-color: #f8f8f8; + overflow-y: auto; + overflow-x: hidden; /* no left nav scroll bar */ + } + + /* Bootstrap Default Overrides - Customized Dropdowns for the Side Nav */ + + .side-nav>li.dropdown>ul.dropdown-menu { + position: relative; + min-width: 225px; + margin: 0; + padding: 0; + border: none; + border-radius: 0; + background-color: transparent; + box-shadow: none; + -webkit-box-shadow: none; + } + + .side-nav>li.dropdown>ul.dropdown-menu>li>a { + color: #777777; + padding: 15px 15px 15px 25px; + } + + .side-nav>li.dropdown>ul.dropdown-menu>li>a:hover, + .side-nav>li.dropdown>ul.dropdown-menu>li>a.active, + .side-nav>li.dropdown>ul.dropdown-menu>li>a:focus { + background-color: #ffffff; + } + + .side-nav>li>a { + width: 225px; + } + + .navbar-default .navbar-nav.side-nav>li>a:hover, + .navbar-default .navbar-nav.side-nav>li>a:focus { + background-color: #ffffff; + } + + /* Nav Messages */ + + .messages-dropdown .dropdown-menu { + min-width: 300px; + } + + .messages-dropdown .dropdown-menu li a { + white-space: normal; + } + + .navbar-collapse { + padding-left: 15px !important; + padding-right: 15px !important; + } + +} diff --git a/apps/workbench/app/assets/stylesheets/scaffolds.css.scss b/apps/workbench/app/assets/stylesheets/scaffolds.css.scss new file mode 100644 index 0000000000..d3915bd59b --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/scaffolds.css.scss @@ -0,0 +1,5 @@ +/* + We don't want the default Rails CSS, so the rules are deleted. This + empty file is left here so Rails doesn't re-add it next time it + generates a scaffold. + */ diff --git a/apps/workbench/app/assets/stylesheets/select_modal.css.scss b/apps/workbench/app/assets/stylesheets/select_modal.css.scss new file mode 100644 index 0000000000..425793a2aa --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/select_modal.css.scss @@ -0,0 +1,23 @@ +.selectable-container > .row { + padding-top: 5px; + padding-bottom: 5px; + padding-right: 1em; + color: #888; +} +.selectable-container > .row.selectable { + color: #000; +} +.selectable.active, .selectable:hover { + background: #d9edf7; + cursor: pointer; +} +.selectable.active, +.selectable.active *, +.selectable.active:hover, +.selectable.active:hover * { + background: #428bca; + color: #fff; +} +.selectable-container > .row.class-separator { + background: #ddd; +} diff --git a/apps/workbench/app/assets/stylesheets/sessions.css.scss b/apps/workbench/app/assets/stylesheets/sessions.css.scss new file mode 100644 index 0000000000..ccb1ed25b2 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/sessions.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Sessions controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/specimens.css.scss b/apps/workbench/app/assets/stylesheets/specimens.css.scss new file mode 100644 index 0000000000..460e42e180 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/specimens.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Specimens controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/traits.css.scss b/apps/workbench/app/assets/stylesheets/traits.css.scss new file mode 100644 index 0000000000..5f30857c97 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/traits.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Traits controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/user_agreements.css.scss b/apps/workbench/app/assets/stylesheets/user_agreements.css.scss new file mode 100644 index 0000000000..98edb295ee --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/user_agreements.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the user_agreements controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/users.css.scss b/apps/workbench/app/assets/stylesheets/users.css.scss new file mode 100644 index 0000000000..31a2eacb84 --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/users.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the Users controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/assets/stylesheets/virtual_machines.css.scss b/apps/workbench/app/assets/stylesheets/virtual_machines.css.scss new file mode 100644 index 0000000000..5532eb999e --- /dev/null +++ b/apps/workbench/app/assets/stylesheets/virtual_machines.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the VirtualMachines controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/apps/workbench/app/controllers/actions_controller.rb b/apps/workbench/app/controllers/actions_controller.rb new file mode 100644 index 0000000000..59dcbb92bb --- /dev/null +++ b/apps/workbench/app/controllers/actions_controller.rb @@ -0,0 +1,209 @@ +class ActionsController < ApplicationController + + skip_filter :require_thread_api_token, only: [:report_issue_popup, :report_issue] + skip_filter :check_user_agreements, only: [:report_issue_popup, :report_issue] + + @@exposed_actions = {} + def self.expose_action method, &block + @@exposed_actions[method] = true + define_method method, block + end + + def model_class + ArvadosBase::resource_class_for_uuid(params[:uuid]) + end + + def show + @object = model_class.andand.find(params[:uuid]) + if @object.is_a? Link and + @object.link_class == 'name' and + ArvadosBase::resource_class_for_uuid(@object.head_uuid) == Collection + redirect_to collection_path(id: @object.uuid) + elsif @object + redirect_to @object + else + raise ActiveRecord::RecordNotFound + end + end + + def post + params.keys.collect(&:to_sym).each do |param| + if @@exposed_actions[param] + return self.send(param) + end + end + redirect_to :back + end + + expose_action :copy_selections_into_project do + move_or_copy :copy + end + + expose_action :move_selections_into_project do + move_or_copy :move + end + + def move_or_copy action + uuids_to_add = params["selection"] + uuids_to_add = [ uuids_to_add ] unless uuids_to_add.is_a? Array + uuids_to_add. + collect { |x| ArvadosBase::resource_class_for_uuid(x) }. + uniq. + each do |resource_class| + resource_class.filter([['uuid','in',uuids_to_add]]).each do |src| + if resource_class == Collection and not Collection.attribute_info.include?(:name) + dst = Link.new(owner_uuid: @object.uuid, + tail_uuid: @object.uuid, + head_uuid: src.uuid, + link_class: 'name', + name: src.uuid) + else + case action + when :copy + dst = src.dup + if dst.respond_to? :'name=' + if dst.name + dst.name = "Copy of #{dst.name}" + else + dst.name = "Copy of unnamed #{dst.class_for_display.downcase}" + end + end + if resource_class == Collection + dst.manifest_text = Collection.select([:manifest_text]).where(uuid: src.uuid).first.manifest_text + end + when :move + dst = src + else + raise ArgumentError.new "Unsupported action #{action}" + end + dst.owner_uuid = @object.uuid + dst.tail_uuid = @object.uuid if dst.class == Link + end + begin + dst.save! + rescue + dst.name += " (#{Time.now.localtime})" if dst.respond_to? :name= + dst.save! + end + end + end + redirect_to @object + end + + def arv_normalize mt, *opts + r = "" + env = Hash[ENV]. + merge({'ARVADOS_API_HOST' => + arvados_api_client.arvados_v1_base. + sub(/\/arvados\/v1/, ''). + sub(/^https?:\/\//, ''), + 'ARVADOS_API_TOKEN' => 'x', + 'ARVADOS_API_HOST_INSECURE' => + Rails.configuration.arvados_insecure_https ? 'true' : 'false' + }) + IO.popen([env, 'arv-normalize'] + opts, 'w+b') do |io| + io.write mt + io.close_write + while buf = io.read(2**16) + r += buf + end + end + r + end + + expose_action :combine_selected_files_into_collection do + uuids = [] + pdhs = [] + files = [] + params["selection"].each do |s| + a = ArvadosBase::resource_class_for_uuid s + if a == Link + begin + if (m = CollectionsHelper.match(Link.find(s).head_uuid)) + pdhs.append(m[1] + m[2]) + files.append(m) + end + rescue + end + elsif (m = CollectionsHelper.match(s)) + pdhs.append(m[1] + m[2]) + files.append(m) + elsif (m = CollectionsHelper.match_uuid_with_optional_filepath(s)) + uuids.append(m[1]) + files.append(m) + end + end + + pdhs = pdhs.uniq + uuids = uuids.uniq + chash = {} + + Collection.select([:uuid, :manifest_text]).where(uuid: uuids).each do |c| + chash[c.uuid] = c + end + + Collection.select([:portable_data_hash, :manifest_text]).where(portable_data_hash: pdhs).each do |c| + chash[c.portable_data_hash] = c + end + + combined = "" + files.each do |m| + mt = chash[m[1]+m[2]].andand.manifest_text + if not m[4].nil? and m[4].size > 1 + combined += arv_normalize mt, '--extract', ".#{m[4]}" + else + combined += mt + end + end + + normalized = arv_normalize combined + newc = Collection.new({:manifest_text => normalized}) + newc.name = newc.name || "Collection created at #{Time.now.localtime}" + + # set owner_uuid to current project, provided it is writable + current_project_writable = false + action_data = JSON.parse(params['action_data']) if params['action_data'] + if action_data && action_data['current_project_uuid'] + current_project = Group.find(action_data['current_project_uuid']) rescue nil + if (current_project && current_project.writable_by.andand.include?(current_user.uuid)) + newc.owner_uuid = action_data['current_project_uuid'] + current_project_writable = true + end + end + + newc.save! + + chash.each do |k,v| + l = Link.new({ + tail_uuid: k, + head_uuid: newc.uuid, + link_class: "provenance", + name: "provided" + }) + l.save! + end + + msg = current_project_writable ? + "Created new collection in the project #{current_project.name}." : + "Created new collection in your Home project." + + redirect_to newc, flash: {'message' => msg} + end + + def report_issue_popup + respond_to do |format| + format.js + format.html + end + end + + def report_issue + logger.warn "report_issue: #{params.inspect}" + + respond_to do |format| + IssueReporter.send_report(current_user, params).deliver + format.js {render nothing: true} + end + end + +end diff --git a/apps/workbench/app/controllers/api_client_authorizations_controller.rb b/apps/workbench/app/controllers/api_client_authorizations_controller.rb new file mode 100644 index 0000000000..85f52f20ab --- /dev/null +++ b/apps/workbench/app/controllers/api_client_authorizations_controller.rb @@ -0,0 +1,7 @@ +class ApiClientAuthorizationsController < ApplicationController + + def index_pane_list + %w(Recent Help) + end + +end diff --git a/apps/workbench/app/controllers/application_controller.rb b/apps/workbench/app/controllers/application_controller.rb new file mode 100644 index 0000000000..c7575176de --- /dev/null +++ b/apps/workbench/app/controllers/application_controller.rb @@ -0,0 +1,1048 @@ +class ApplicationController < ActionController::Base + include ArvadosApiClientHelper + include ApplicationHelper + + respond_to :html, :json, :js + protect_from_forgery + + ERROR_ACTIONS = [:render_error, :render_not_found] + + around_filter :thread_clear + around_filter :set_thread_api_token + # Methods that don't require login should + # skip_around_filter :require_thread_api_token + around_filter :require_thread_api_token, except: ERROR_ACTIONS + before_filter :set_cache_buster + before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS + before_filter :check_user_agreements, except: ERROR_ACTIONS + before_filter :check_user_profile, except: ERROR_ACTIONS + before_filter :check_user_notifications, except: ERROR_ACTIONS + before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS + before_filter :find_object_by_uuid, except: [:create, :index, :choose] + ERROR_ACTIONS + theme :select_theme + + begin + rescue_from(ActiveRecord::RecordNotFound, + ActionController::RoutingError, + ActionController::UnknownController, + AbstractController::ActionNotFound, + with: :render_not_found) + rescue_from(Exception, + ActionController::UrlGenerationError, + with: :render_exception) + end + + def set_cache_buster + response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate" + response.headers["Pragma"] = "no-cache" + response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT" + end + + def unprocessable(message=nil) + @errors ||= [] + + @errors << message if message + render_error status: 422 + end + + def render_error(opts={}) + opts[:status] ||= 500 + respond_to do |f| + # json must come before html here, so it gets used as the + # default format when js is requested by the client. This lets + # ajax:error callback parse the response correctly, even though + # the browser can't. + f.json { render opts.merge(json: {success: false, errors: @errors}) } + f.html { render({action: 'error'}.merge(opts)) } + end + end + + def render_exception(e) + logger.error e.inspect + logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace + err_opts = {status: 422} + if e.is_a?(ArvadosApiClient::ApiError) + err_opts.merge!(action: 'api_error', locals: {api_error: e}) + @errors = e.api_response[:errors] + elsif @object.andand.errors.andand.full_messages.andand.any? + @errors = @object.errors.full_messages + else + @errors = [e.to_s] + end + # Make user information available on the error page, falling back to the + # session cache if the API server is unavailable. + begin + load_api_token(session[:arvados_api_token]) + rescue ArvadosApiClient::ApiError + unless session[:user].nil? + begin + Thread.current[:user] = User.new(session[:user]) + rescue ArvadosApiClient::ApiError + # This can happen if User's columns are unavailable. Nothing to do. + end + end + end + # Preload projects trees for the template. If that's not doable, set empty + # trees so error page rendering can proceed. (It's easier to rescue the + # exception here than in a template.) + unless current_user.nil? + begin + build_project_trees + rescue ArvadosApiClient::ApiError + # Fall back to the default-setting code later. + end + end + @my_project_tree ||= [] + @shared_project_tree ||= [] + render_error(err_opts) + end + + def render_not_found(e=ActionController::RoutingError.new("Path not found")) + logger.error e.inspect + @errors = ["Path not found"] + set_thread_api_token do + self.render_error(action: '404', status: 404) + end + end + + # params[:order]: + # + # The order can be left empty to allow it to default. + # Or it can be a comma separated list of real database column names, one per model. + # Column names should always be qualified by a table name and a direction is optional, defaulting to asc + # (e.g. "collections.name" or "collections.name desc"). + # If a column name is specified, that table will be sorted by that column. + # If there are objects from different models that will be shown (such as in Jobs and Pipelines tab), + # then a sort column name can optionally be specified for each model, passed as an comma-separated list (e.g. "jobs.script, pipeline_instances.name") + # Currently only one sort column name and direction can be specified for each model. + def load_filters_and_paging_params + if params[:order].blank? + @order = 'created_at desc' + elsif params[:order].is_a? Array + @order = params[:order] + else + begin + @order = JSON.load(params[:order]) + rescue + @order = params[:order].split(',') + end + end + @order = [@order] unless @order.is_a? Array + + @limit ||= 200 + if params[:limit] + @limit = params[:limit].to_i + end + + @offset ||= 0 + if params[:offset] + @offset = params[:offset].to_i + end + + @filters ||= [] + if params[:filters] + filters = params[:filters] + if filters.is_a? String + filters = Oj.load filters + elsif filters.is_a? Array + filters = filters.collect do |filter| + if filter.is_a? String + # Accept filters[]=["foo","=","bar"] + Oj.load filter + else + # Accept filters=[["foo","=","bar"]] + filter + end + end + end + # After this, params[:filters] can be trusted to be an array of arrays: + params[:filters] = filters + @filters += filters + end + end + + def find_objects_for_index + @objects ||= model_class + @objects = @objects.filter(@filters).limit(@limit).offset(@offset) + @objects.fetch_multiple_pages(false) + end + + def render_index + respond_to do |f| + f.json { + if params[:partial] + @next_page_href = next_page_href(partial: params[:partial], filters: @filters.to_json) + render json: { + content: render_to_string(partial: "show_#{params[:partial]}", + formats: [:html]), + next_page_href: @next_page_href + } + else + render json: @objects + end + } + f.html { + if params[:tab_pane] + render_pane params[:tab_pane] + else + render + end + } + f.js { render } + end + end + + helper_method :render_pane + def render_pane tab_pane, opts={} + render_opts = { + partial: 'show_' + tab_pane.downcase, + locals: { + comparable: self.respond_to?(:compare), + objects: @objects, + tab_pane: tab_pane + }.merge(opts[:locals] || {}) + } + if opts[:to_string] + render_to_string render_opts + else + render render_opts + end + end + + def index + find_objects_for_index if !@objects + render_index + end + + helper_method :next_page_offset + def next_page_offset objects=nil + if !objects + objects = @objects + end + if objects.respond_to?(:result_offset) and + objects.respond_to?(:result_limit) and + objects.respond_to?(:items_available) + next_offset = objects.result_offset + objects.result_limit + if next_offset < objects.items_available + next_offset + else + nil + end + end + end + + helper_method :next_page_href + def next_page_href with_params={} + if next_page_offset + url_for with_params.merge(offset: next_page_offset) + end + end + + def show + if !@object + return render_not_found("object not found") + end + respond_to do |f| + f.json do + extra_attrs = { href: url_for(action: :show, id: @object) } + @object.textile_attributes.each do |textile_attr| + extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) }) + end + render json: @object.attributes.merge(extra_attrs) + end + f.html { + if params['tab_pane'] + render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end) + elsif request.method.in? ['GET', 'HEAD'] + render + else + redirect_to (params[:return_to] || + polymorphic_url(@object, + anchor: params[:redirect_to_anchor])) + end + } + f.js { render } + end + end + + def choose + params[:limit] ||= 40 + respond_to do |f| + if params[:partial] + f.json { + find_objects_for_index if !@objects + render json: { + content: render_to_string(partial: "choose_rows.html", + formats: [:html]), + next_page_href: next_page_href(partial: params[:partial]) + } + } + end + f.js { + find_objects_for_index if !@objects + render partial: 'choose', locals: {multiple: params[:multiple]} + } + end + end + + def render_content + if !@object + return render_not_found("object not found") + end + end + + def new + @object = model_class.new + end + + def update + @updates ||= params[@object.resource_param_name.to_sym] + @updates.keys.each do |attr| + if @object.send(attr).is_a? Hash + if @updates[attr].is_a? String + @updates[attr] = Oj.load @updates[attr] + end + if params[:merge] || params["merge_#{attr}".to_sym] + # Merge provided Hash with current Hash, instead of + # replacing. + @updates[attr] = @object.send(attr).with_indifferent_access. + deep_merge(@updates[attr].with_indifferent_access) + end + end + end + if @object.update_attributes @updates + show + else + self.render_error status: 422 + end + end + + def create + @new_resource_attrs ||= params[model_class.to_s.underscore.singularize] + @new_resource_attrs ||= {} + @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' } + @object ||= model_class.new @new_resource_attrs, params["options"] + + if @object.save + show + else + render_error status: 422 + end + end + + # Clone the given object, merging any attribute values supplied as + # with a create action. + def copy + @new_resource_attrs ||= params[model_class.to_s.underscore.singularize] + @new_resource_attrs ||= {} + @object = @object.dup + @object.update_attributes @new_resource_attrs + if not @new_resource_attrs[:name] and @object.respond_to? :name + if @object.name and @object.name != '' + @object.name = "Copy of #{@object.name}" + else + @object.name = "" + end + end + @object.save! + show + end + + def destroy + if @object.destroy + respond_to do |f| + f.json { render json: @object } + f.html { + redirect_to(params[:return_to] || :back) + } + f.js { render } + end + else + self.render_error status: 422 + end + end + + def current_user + Thread.current[:user] + end + + def model_class + controller_name.classify.constantize + end + + def breadcrumb_page_name + (@breadcrumb_page_name || + (@object.friendly_link_name if @object.respond_to? :friendly_link_name) || + action_name) + end + + def index_pane_list + %w(Recent) + end + + def show_pane_list + %w(Attributes Advanced) + end + + protected + + def strip_token_from_path(path) + path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1') + end + + def redirect_to_login + respond_to do |f| + f.html { + if request.method.in? ['GET', 'HEAD'] + redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url)) + else + flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request." + redirect_to :back + end + } + f.json { + @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.'] + self.render_error status: 422 + } + end + false # For convenience to return from callbacks + end + + def using_specific_api_token(api_token, opts={}) + start_values = {} + [:arvados_api_token, :user].each do |key| + start_values[key] = Thread.current[key] + end + if opts.fetch(:load_user, true) + load_api_token(api_token) + else + Thread.current[:arvados_api_token] = api_token + Thread.current[:user] = nil + end + begin + yield + ensure + start_values.each_key { |key| Thread.current[key] = start_values[key] } + end + end + + + def accept_uuid_as_id_param + if params[:id] and params[:id].match /\D/ + params[:uuid] = params.delete :id + end + end + + def find_object_by_uuid + begin + if not model_class + @object = nil + elsif not params[:uuid].is_a?(String) + @object = model_class.where(uuid: params[:uuid]).first + elsif params[:uuid].empty? + @object = nil + elsif (model_class != Link and + resource_class_for_uuid(params[:uuid]) == Link) + @name_link = Link.find(params[:uuid]) + @object = model_class.find(@name_link.head_uuid) + else + @object = model_class.find(params[:uuid]) + end + rescue ArvadosApiClient::NotFoundException, RuntimeError => error + if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/) + raise + end + render_not_found(error) + return false + end + end + + def thread_clear + load_api_token(nil) + Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/) + yield + Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/) + end + + # Set up the thread with the given API token and associated user object. + def load_api_token(new_token) + Thread.current[:arvados_api_token] = new_token + if new_token.nil? + Thread.current[:user] = nil + else + Thread.current[:user] = User.current + end + end + + # If there's a valid api_token parameter, set up the session with that + # user's information. Return true if the method redirects the request + # (usually a post-login redirect); false otherwise. + def setup_user_session + return false unless params[:api_token] + Thread.current[:arvados_api_token] = params[:api_token] + begin + user = User.current + rescue ArvadosApiClient::NotLoggedInException + false # We may redirect to login, or not, based on the current action. + else + session[:arvados_api_token] = params[:api_token] + # If we later have trouble contacting the API server, we still want + # to be able to render basic user information in the UI--see + # render_exception above. We store that in the session here. This is + # not intended to be used as a general-purpose cache. See #2891. + session[:user] = { + uuid: user.uuid, + email: user.email, + first_name: user.first_name, + last_name: user.last_name, + is_active: user.is_active, + is_admin: user.is_admin, + prefs: user.prefs + } + + if !request.format.json? and request.method.in? ['GET', 'HEAD'] + # Repeat this request with api_token in the (new) session + # cookie instead of the query string. This prevents API + # tokens from appearing in (and being inadvisedly copied + # and pasted from) browser Location bars. + redirect_to strip_token_from_path(request.fullpath) + true + else + false + end + ensure + Thread.current[:arvados_api_token] = nil + end + end + + # Save the session API token in thread-local storage, and yield. + # This method also takes care of session setup if the request + # provides a valid api_token parameter. + # If a token is unavailable or expired, the block is still run, with + # a nil token. + def set_thread_api_token + if Thread.current[:arvados_api_token] + yield # An API token has already been found - pass it through. + return + elsif setup_user_session + return # A new session was set up and received a response. + end + + begin + load_api_token(session[:arvados_api_token]) + yield + rescue ArvadosApiClient::NotLoggedInException + # If we got this error with a token, it must've expired. + # Retry the request without a token. + unless Thread.current[:arvados_api_token].nil? + load_api_token(nil) + yield + end + ensure + # Remove token in case this Thread is used for anything else. + load_api_token(nil) + end + end + + # Redirect to login/welcome if client provided expired API token (or none at all) + def require_thread_api_token + if Thread.current[:arvados_api_token] + yield + elsif session[:arvados_api_token] + # Expired session. Clear it before refreshing login so that, + # if this login procedure fails, we end up showing the "please + # log in" page instead of getting stuck in a redirect loop. + session.delete :arvados_api_token + redirect_to_login + else + redirect_to welcome_users_path(return_to: request.fullpath) + end + end + + def ensure_current_user_is_admin + unless current_user and current_user.is_admin + @errors = ['Permission denied'] + self.render_error status: 401 + end + end + + helper_method :unsigned_user_agreements + def unsigned_user_agreements + @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid + @unsigned_user_agreements ||= UserAgreement.all.map do |ua| + if not @signed_ua_uuids.index ua.uuid + Collection.find(ua.uuid) + end + end.compact + end + + def check_user_agreements + if current_user && !current_user.is_active + if not current_user.is_invited + return redirect_to inactive_users_path(return_to: request.fullpath) + end + if unsigned_user_agreements.empty? + # No agreements to sign. Perhaps we just need to ask? + current_user.activate + if !current_user.is_active + logger.warn "#{current_user.uuid.inspect}: " + + "No user agreements to sign, but activate failed!" + end + end + if !current_user.is_active + redirect_to user_agreements_path(return_to: request.fullpath) + end + end + true + end + + def check_user_profile + if request.method.downcase != 'get' || params[:partial] || + params[:tab_pane] || params[:action_method] || + params[:action] == 'setup_popup' + return true + end + + if missing_required_profile? + redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath) + end + true + end + + helper_method :missing_required_profile? + def missing_required_profile? + missing_required = false + + profile_config = Rails.configuration.user_profile_form_fields + if current_user && profile_config + current_user_profile = current_user.prefs[:profile] + profile_config.kind_of?(Array) && profile_config.andand.each do |entry| + if entry['required'] + if !current_user_profile || + !current_user_profile[entry['key'].to_sym] || + current_user_profile[entry['key'].to_sym].empty? + missing_required = true + break + end + end + end + end + + missing_required + end + + def select_theme + return Rails.configuration.arvados_theme + end + + @@notification_tests = [] + + @@notification_tests.push lambda { |controller, current_user| + AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do + return nil + end + return lambda { |view| + view.render partial: 'notifications/ssh_key_notification' + } + } + + @@notification_tests.push lambda { |controller, current_user| + Collection.limit(1).where(created_by: current_user.uuid).each do + return nil + end + return lambda { |view| + view.render partial: 'notifications/collections_notification' + } + } + + @@notification_tests.push lambda { |controller, current_user| + PipelineInstance.limit(1).where(created_by: current_user.uuid).each do + return nil + end + return lambda { |view| + view.render partial: 'notifications/pipelines_notification' + } + } + + def check_user_notifications + return if params['tab_pane'] + + @notification_count = 0 + @notifications = [] + + if current_user.andand.is_active + @showallalerts = false + @@notification_tests.each do |t| + a = t.call(self, current_user) + if a + @notification_count += 1 + @notifications.push a + end + end + end + + if @notification_count == 0 + @notification_count = '' + end + end + + helper_method :all_projects + def all_projects + @all_projects ||= Group. + filter([['group_class','=','project']]).order('name') + end + + helper_method :my_projects + def my_projects + return @my_projects if @my_projects + @my_projects = [] + root_of = {} + all_projects.each do |g| + root_of[g.uuid] = g.owner_uuid + @my_projects << g + end + done = false + while not done + done = true + root_of = root_of.each_with_object({}) do |(child, parent), h| + if root_of[parent] + h[child] = root_of[parent] + done = false + else + h[child] = parent + end + end + end + @my_projects = @my_projects.select do |g| + root_of[g.uuid] == current_user.uuid + end + end + + helper_method :projects_shared_with_me + def projects_shared_with_me + my_project_uuids = my_projects.collect &:uuid + all_projects.reject { |x| x.uuid.in? my_project_uuids } + end + + helper_method :recent_jobs_and_pipelines + def recent_jobs_and_pipelines + (Job.limit(10) | + PipelineInstance.limit(10)). + sort_by do |x| + (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at + end.reverse + end + + helper_method :running_pipelines + def running_pipelines + pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]]) + jobs = {} + pi.each do |pl| + pl.components.each do |k,v| + if v.is_a? Hash and v[:job] + jobs[v[:job][:uuid]] = {} + end + end + end + + if jobs.keys.any? + Job.filter([["uuid", "in", jobs.keys]]).each do |j| + jobs[j[:uuid]] = j + end + + pi.each do |pl| + pl.components.each do |k,v| + if v.is_a? Hash and v[:job] + v[:job] = jobs[v[:job][:uuid]] + end + end + end + end + + pi + end + + helper_method :finished_pipelines + def finished_pipelines lim + PipelineInstance.limit(lim).order(["finished_at desc"]).filter([["state", "in", ["Complete", "Failed", "Paused"]], ["finished_at", "!=", nil]]) + end + + helper_method :recent_collections + def recent_collections lim + c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]]) + own = {} + Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g| + own[g[:uuid]] = g + end + {collections: c, owners: own} + end + + helper_method :my_project_tree + def my_project_tree + build_project_trees + @my_project_tree + end + + helper_method :shared_project_tree + def shared_project_tree + build_project_trees + @shared_project_tree + end + + def build_project_trees + return if @my_project_tree and @shared_project_tree + parent_of = {current_user.uuid => 'me'} + all_projects.each do |ob| + parent_of[ob.uuid] = ob.owner_uuid + end + children_of = {false => [], 'me' => [current_user]} + all_projects.each do |ob| + if ob.owner_uuid != current_user.uuid and + not parent_of.has_key? ob.owner_uuid + parent_of[ob.uuid] = false + end + children_of[parent_of[ob.uuid]] ||= [] + children_of[parent_of[ob.uuid]] << ob + end + buildtree = lambda do |children_of, root_uuid=false| + tree = {} + children_of[root_uuid].andand.each do |ob| + tree[ob] = buildtree.call(children_of, ob.uuid) + end + tree + end + sorted_paths = lambda do |tree, depth=0| + paths = [] + tree.keys.sort_by { |ob| + ob.is_a?(String) ? ob : ob.friendly_link_name + }.each do |ob| + paths << {object: ob, depth: depth} + paths += sorted_paths.call tree[ob], depth+1 + end + paths + end + @my_project_tree = + sorted_paths.call buildtree.call(children_of, 'me') + @shared_project_tree = + sorted_paths.call({'Projects shared with me' => + buildtree.call(children_of, false)}) + end + + helper_method :get_object + def get_object uuid + if @get_object.nil? and @objects + @get_object = @objects.each_with_object({}) do |object, h| + h[object.uuid] = object + end + end + @get_object ||= {} + @get_object[uuid] + end + + helper_method :project_breadcrumbs + def project_breadcrumbs + crumbs = [] + current = @name_link || @object + while current + # Halt if a group ownership loop is detected. API should refuse + # to produce this state, but it could still arise from a race + # condition when group ownership changes between our find() + # queries. + break if crumbs.collect(&:uuid).include? current.uuid + + if current.is_a?(Group) and current.group_class == 'project' + crumbs.prepend current + end + if current.is_a? Link + current = Group.find?(current.tail_uuid) + else + current = Group.find?(current.owner_uuid) + end + end + crumbs + end + + helper_method :current_project_uuid + def current_project_uuid + if @object.is_a? Group and @object.group_class == 'project' + @object.uuid + elsif @name_link.andand.tail_uuid + @name_link.tail_uuid + elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group + @object.owner_uuid + else + nil + end + end + + # helper method to get links for given object or uuid + helper_method :links_for_object + def links_for_object object_or_uuid + raise ArgumentError, 'No input argument' unless object_or_uuid + preload_links_for_objects([object_or_uuid]) + uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid + @all_links_for[uuid] ||= [] + end + + # helper method to preload links for given objects and uuids + helper_method :preload_links_for_objects + def preload_links_for_objects objects_and_uuids + @all_links_for ||= {} + + raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array + return @all_links_for if objects_and_uuids.empty? + + uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid } + + # if already preloaded for all of these uuids, return + if not uuids.select { |x| @all_links_for[x].nil? }.any? + return @all_links_for + end + + uuids.each do |x| + @all_links_for[x] = [] + end + + # TODO: make sure we get every page of results from API server + Link.filter([['head_uuid', 'in', uuids]]).each do |link| + @all_links_for[link.head_uuid] << link + end + @all_links_for + end + + # helper method to get a certain number of objects of a specific type + # this can be used to replace any uses of: "dataclass.limit(n)" + helper_method :get_n_objects_of_class + def get_n_objects_of_class dataclass, size + @objects_map_for ||= {} + + raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase + raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0) + + # if the objects_map_for has a value for this dataclass, and the + # size used to retrieve those objects is equal, return it + size_key = "#{dataclass.name}_size" + if @objects_map_for[dataclass.name] && @objects_map_for[size_key] && + (@objects_map_for[size_key] == size) + return @objects_map_for[dataclass.name] + end + + @objects_map_for[size_key] = size + @objects_map_for[dataclass.name] = dataclass.limit(size) + end + + # helper method to get collections for the given uuid + helper_method :collections_for_object + def collections_for_object uuid + raise ArgumentError, 'No input argument' unless uuid + preload_collections_for_objects([uuid]) + @all_collections_for[uuid] ||= [] + end + + # helper method to preload collections for the given uuids + helper_method :preload_collections_for_objects + def preload_collections_for_objects uuids + @all_collections_for ||= {} + + raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array + return @all_collections_for if uuids.empty? + + # if already preloaded for all of these uuids, return + if not uuids.select { |x| @all_collections_for[x].nil? }.any? + return @all_collections_for + end + + uuids.each do |x| + @all_collections_for[x] = [] + end + + # TODO: make sure we get every page of results from API server + Collection.where(uuid: uuids).each do |collection| + @all_collections_for[collection.uuid] << collection + end + @all_collections_for + end + + # helper method to get log collections for the given log + helper_method :log_collections_for_object + def log_collections_for_object log + raise ArgumentError, 'No input argument' unless log + + preload_log_collections_for_objects([log]) + + uuid = log + fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log) + if fixup && fixup.size>1 + uuid = fixup[1] + end + + @all_log_collections_for[uuid] ||= [] + end + + # helper method to preload collections for the given uuids + helper_method :preload_log_collections_for_objects + def preload_log_collections_for_objects logs + @all_log_collections_for ||= {} + + raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array + return @all_log_collections_for if logs.empty? + + uuids = [] + logs.each do |log| + fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log) + if fixup && fixup.size>1 + uuids << fixup[1] + else + uuids << log + end + end + + # if already preloaded for all of these uuids, return + if not uuids.select { |x| @all_log_collections_for[x].nil? }.any? + return @all_log_collections_for + end + + uuids.each do |x| + @all_log_collections_for[x] = [] + end + + # TODO: make sure we get every page of results from API server + Collection.where(uuid: uuids).each do |collection| + @all_log_collections_for[collection.uuid] << collection + end + @all_log_collections_for + end + + # helper method to get object of a given dataclass and uuid + helper_method :object_for_dataclass + def object_for_dataclass dataclass, uuid + raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid) + preload_objects_for_dataclass(dataclass, [uuid]) + @objects_for[uuid] + end + + # helper method to preload objects for given dataclass and uuids + helper_method :preload_objects_for_dataclass + def preload_objects_for_dataclass dataclass, uuids + @objects_for ||= {} + + raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class + raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array + + return @objects_for if uuids.empty? + + # if already preloaded for all of these uuids, return + if not uuids.select { |x| @objects_for[x].nil? }.any? + return @objects_for + end + + dataclass.where(uuid: uuids).each do |obj| + @objects_for[obj.uuid] = obj + end + @objects_for + end + + def wiselinks_layout + 'body' + end +end diff --git a/apps/workbench/app/controllers/authorized_keys_controller.rb b/apps/workbench/app/controllers/authorized_keys_controller.rb new file mode 100644 index 0000000000..6eaec1ee59 --- /dev/null +++ b/apps/workbench/app/controllers/authorized_keys_controller.rb @@ -0,0 +1,17 @@ +class AuthorizedKeysController < ApplicationController + def index_pane_list + %w(Recent Help) + end + + def new + super + @object.authorized_user_uuid = current_user.uuid if current_user + @object.key_type = 'SSH' + end + + def create + defaults = { authorized_user_uuid: current_user.uuid, key_type: 'SSH' } + @object = AuthorizedKey.new defaults.merge(params[:authorized_key] || {}) + super + end +end diff --git a/apps/workbench/app/controllers/collections_controller.rb b/apps/workbench/app/controllers/collections_controller.rb new file mode 100644 index 0000000000..f4aa0395f3 --- /dev/null +++ b/apps/workbench/app/controllers/collections_controller.rb @@ -0,0 +1,327 @@ +require "arvados/keep" + +class CollectionsController < ApplicationController + include ActionController::Live + + skip_around_filter(:require_thread_api_token, + only: [:show_file, :show_file_links]) + skip_before_filter(:find_object_by_uuid, + only: [:provenance, :show_file, :show_file_links]) + # We depend on show_file to display the user agreement: + skip_before_filter :check_user_agreements, only: :show_file + skip_before_filter :check_user_profile, only: :show_file + + RELATION_LIMIT = 5 + + def show_pane_list + panes = %w(Files Upload Provenance_graph Used_by Advanced) + panes = panes - %w(Upload) unless (@object.editable? rescue false) + panes + end + + def set_persistent + case params[:value] + when 'persistent', 'cache' + persist_links = Link.filter([['owner_uuid', '=', current_user.uuid], + ['link_class', '=', 'resources'], + ['name', '=', 'wants'], + ['tail_uuid', '=', current_user.uuid], + ['head_uuid', '=', @object.uuid]]) + logger.debug persist_links.inspect + else + return unprocessable "Invalid value #{value.inspect}" + end + if params[:value] == 'persistent' + if not persist_links.any? + Link.create(link_class: 'resources', + name: 'wants', + tail_uuid: current_user.uuid, + head_uuid: @object.uuid) + end + else + persist_links.each do |link| + link.destroy || raise + end + end + + respond_to do |f| + f.json { render json: @object } + end + end + + def index + # API server index doesn't return manifest_text by default, but our + # callers want it unless otherwise specified. + @select ||= Collection.columns.map(&:name) + base_search = Collection.select(@select) + if params[:search].andand.length.andand > 0 + tags = Link.where(any: ['contains', params[:search]]) + @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) | + base_search.where(any: ['contains', params[:search]])). + uniq { |c| c.uuid } + else + if params[:limit] + limit = params[:limit].to_i + else + limit = 100 + end + + if params[:offset] + offset = params[:offset].to_i + else + offset = 0 + end + + @objects = base_search.limit(limit).offset(offset) + end + @links = Link.where(head_uuid: @objects.collect(&:uuid)) + @collection_info = {} + @objects.each do |c| + @collection_info[c.uuid] = { + tag_links: [], + wanted: false, + wanted_by_me: false, + provenance: [], + links: [] + } + end + @links.each do |link| + @collection_info[link.head_uuid] ||= {} + info = @collection_info[link.head_uuid] + case link.link_class + when 'tag' + info[:tag_links] << link + when 'resources' + info[:wanted] = true + info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid + when 'provenance' + info[:provenance] << link.name + end + info[:links] << link + end + @request_url = request.url + + render_index + end + + def show_file_links + Thread.current[:reader_tokens] = [params[:reader_token]] + return if false.equal?(find_object_by_uuid) + render layout: false + end + + def show_file + # We pipe from arv-get to send the file to the user. Before we start it, + # we ask the API server if the file actually exists. This serves two + # purposes: it lets us return a useful status code for common errors, and + # helps us figure out which token to provide to arv-get. + coll = nil + tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact + usable_token = find_usable_token(tokens) do + coll = Collection.find(params[:uuid]) + end + + file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './') + if usable_token.nil? + return # Response already rendered. + elsif file_name.nil? or not coll.manifest.has_file?(file_name) + return render_not_found + end + + opts = params.merge(arvados_api_token: usable_token) + + # Handle Range requests. Currently we support only 'bytes=0-....' + if request.headers.include? 'HTTP_RANGE' + if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE']) + opts[:maxbytes] = m[1] + size = params[:size] || '*' + self.response.status = 206 + self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}" + end + end + + ext = File.extname(params[:file]) + self.response.headers['Content-Type'] = + Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream' + if params[:size] + size = params[:size].to_i + if opts[:maxbytes] + size = [size, opts[:maxbytes].to_i].min + end + self.response.headers['Content-Length'] = size.to_s + end + self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition] + begin + file_enumerator(opts).each do |bytes| + response.stream.write bytes + end + ensure + response.stream.close + end + end + + def sharing_scopes + ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"] + end + + def search_scopes + begin + ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results + rescue ArvadosApiClient::AccessForbiddenException + nil + end + end + + def find_object_by_uuid + if not Keep::Locator.parse params[:id] + super + end + end + + def show + return super if !@object + if current_user + if Keep::Locator.parse params["uuid"] + @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]) + if @same_pdh.results.size == 1 + redirect_to collection_path(@same_pdh[0]["uuid"]) + return + end + owners = @same_pdh.map(&:owner_uuid).to_a.uniq + preload_objects_for_dataclass Group, owners + preload_objects_for_dataclass User, owners + render 'hash_matches' + return + else + jobs_with = lambda do |conds| + Job.limit(RELATION_LIMIT).where(conds) + .results.sort_by { |j| j.finished_at || j.created_at } + end + @output_of = jobs_with.call(output: @object.portable_data_hash) + @log_of = jobs_with.call(log: @object.portable_data_hash) + @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC") + .where(head_uuid: @object.uuid, link_class: 'name').results + project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash + @projects = project_hash.values + + @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC") + .where(head_uuid: @object.uuid, link_class: 'permission', + name: 'can_read').results + @logs = Log.limit(RELATION_LIMIT).order("created_at DESC") + .where(object_uuid: @object.uuid).results + @is_persistent = Link.limit(1) + .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid, + link_class: 'resources', name: 'wants') + .results.any? + @search_sharing = search_scopes + + if params["tab_pane"] == "Provenance_graph" + @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg", + {:request => request, + :direction => :bottom_up, + :combine_jobs => :script_only}) rescue nil + end + if params["tab_pane"] == "Used_by" + @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg", + {:request => request, + :direction => :top_down, + :combine_jobs => :script_only, + :pdata_only => true}) rescue nil + end + end + end + super + end + + def sharing_popup + @search_sharing = search_scopes + render("sharing_popup.js", content_type: "text/javascript") + end + + helper_method :download_link + + def download_link + collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/" + end + + def share + ApiClientAuthorization.create(scopes: sharing_scopes) + sharing_popup + end + + def unshare + search_scopes.each do |s| + s.destroy + end + sharing_popup + end + + protected + + def find_usable_token(token_list) + # Iterate over every given token to make it the current token and + # yield the given block. + # If the block succeeds, return the token it used. + # Otherwise, render an error response based on the most specific + # error we encounter, and return nil. + most_specific_error = [401] + token_list.each do |api_token| + begin + # We can't load the corresponding user, because the token may not + # be scoped for that. + using_specific_api_token(api_token, load_user: false) do + yield + return api_token + end + rescue ArvadosApiClient::ApiError => error + if error.api_status >= most_specific_error.first + most_specific_error = [error.api_status, error] + end + end + end + case most_specific_error.shift + when 401, 403 + redirect_to_login + when 404 + render_not_found(*most_specific_error) + end + return nil + end + + def file_enumerator(opts) + FileStreamer.new opts + end + + class FileStreamer + include ArvadosApiClientHelper + def initialize(opts={}) + @opts = opts + end + def each + return unless @opts[:uuid] && @opts[:file] + + env = Hash[ENV].dup + + require 'uri' + u = URI.parse(arvados_api_client.arvados_v1_base) + env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}" + env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token] + env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https + + bytesleft = @opts[:maxbytes].andand.to_i || 2**16 + io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb') + while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil + # shrink the bytesleft count, if we were given a maximum byte + # count to read + if @opts.include? :maxbytes + bytesleft = bytesleft - buf.length + end + yield buf + end + io.close + # "If ios is opened by IO.popen, close sets $?." + # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close + Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0 + end + end +end diff --git a/apps/workbench/app/controllers/groups_controller.rb b/apps/workbench/app/controllers/groups_controller.rb new file mode 100644 index 0000000000..080386ea5c --- /dev/null +++ b/apps/workbench/app/controllers/groups_controller.rb @@ -0,0 +1,17 @@ +class GroupsController < ApplicationController + def index + @groups = Group.filter [['group_class', '!=', 'project']] + @group_uuids = @groups.collect &:uuid + @links_from = Link.where link_class: 'permission', tail_uuid: @group_uuids + @links_to = Link.where link_class: 'permission', head_uuid: @group_uuids + render_index + end + + def show + if @object.group_class == 'project' + redirect_to(project_path(@object)) + else + super + end + end +end diff --git a/apps/workbench/app/controllers/humans_controller.rb b/apps/workbench/app/controllers/humans_controller.rb new file mode 100644 index 0000000000..e141655951 --- /dev/null +++ b/apps/workbench/app/controllers/humans_controller.rb @@ -0,0 +1,2 @@ +class HumansController < ApplicationController +end diff --git a/apps/workbench/app/controllers/job_tasks_controller.rb b/apps/workbench/app/controllers/job_tasks_controller.rb new file mode 100644 index 0000000000..5e8662b3ba --- /dev/null +++ b/apps/workbench/app/controllers/job_tasks_controller.rb @@ -0,0 +1,2 @@ +class JobTasksController < ApplicationController +end diff --git a/apps/workbench/app/controllers/jobs_controller.rb b/apps/workbench/app/controllers/jobs_controller.rb new file mode 100644 index 0000000000..08fb94d2f0 --- /dev/null +++ b/apps/workbench/app/controllers/jobs_controller.rb @@ -0,0 +1,85 @@ +class JobsController < ApplicationController + include JobsHelper + + def generate_provenance(jobs) + return if params['tab_pane'] != "Provenance" + + nodes = {} + collections = [] + hashes = [] + jobs.each do |j| + nodes[j[:uuid]] = j + hashes << j[:output] + ProvenanceHelper::find_collections(j[:script_parameters]) do |hash, uuid| + collections << uuid if uuid + hashes << hash if hash + end + nodes[j[:script_version]] = {:uuid => j[:script_version]} + end + + Collection.where(uuid: collections).each do |c| + nodes[c[:portable_data_hash]] = c + end + + Collection.where(portable_data_hash: hashes).each do |c| + nodes[c[:portable_data_hash]] = c + end + + @svg = ProvenanceHelper::create_provenance_graph nodes, "provenance_svg", { + :request => request, + :all_script_parameters => true, + :script_version_nodes => true} + end + + def index + @svg = "" + if params[:uuid] + @objects = Job.where(uuid: params[:uuid]) + generate_provenance(@objects) + render_index + else + @limit = 20 + super + end + end + + def cancel + @object.cancel + if params[:return_to] + redirect_to params[:return_to] + else + redirect_to @object + end + end + + def show + generate_provenance([@object]) + super + end + + def logs + @logs = Log.select(%w(event_type object_uuid event_at properties)) + .order('event_at DESC') + .filter([["event_type", "=", "stderr"], + ["object_uuid", "in", [@object.uuid]]]) + .limit(500) + .results + .to_a + .map{ |e| e.serializable_hash.merge({ 'prepend' => true }) } + respond_to do |format| + format.json { render json: @logs } + end + end + + def index_pane_list + if params[:uuid] + %w(Recent Provenance) + else + %w(Recent) + end + end + + def show_pane_list + %w(Status Log Details Provenance Advanced) + end +end diff --git a/apps/workbench/app/controllers/keep_disks_controller.rb b/apps/workbench/app/controllers/keep_disks_controller.rb new file mode 100644 index 0000000000..f57455b37f --- /dev/null +++ b/apps/workbench/app/controllers/keep_disks_controller.rb @@ -0,0 +1,54 @@ +class KeepDisksController < ApplicationController + def create + defaults = { is_readable: true, is_writable: true } + @object = KeepDisk.new defaults.merge(params[:keep_disk] || {}) + super + end + + def index + # Retrieve cache age histogram info from logs. + + # In the logs we expect to find it in an ordered list with entries + # of the form (mtime, disk proportion free). + + # An entry of the form (1388747781, 0.52) means that if we deleted + # the oldest non-presisted blocks until we had 52% of the disk + # free, then all blocks with an mtime greater than 1388747781 + # would be preserved. + + # The chart we want to produce, will tell us how much of the disk + # will be free if we use a cache age of x days. Therefore we will + # produce output specifying the age, cache and persisted. age is + # specified in milliseconds. cache is the size of the cache if we + # delete all blocks older than age. persistent is the size of the + # persisted blocks. It is constant regardless of age, but it lets + # us show a stacked graph. + + # Finally each entry in cache_age_histogram is a dictionary, + # because that's what our charting package wats. + + @cache_age_histogram = [] + @histogram_pretty_date = nil + histogram_log = Log. + filter([[:event_type, '=', 'block-age-free-space-histogram']]). + order(:created_at => :desc). + limit(1) + histogram_log.each do |log_entry| + # We expect this block to only execute at most once since we + # specified limit(1) + @cache_age_histogram = log_entry['properties'][:histogram] + # Javascript wants dates in milliseconds. + histogram_date_ms = log_entry['event_at'].to_i * 1000 + @histogram_pretty_date = log_entry['event_at'].strftime('%b %-d, %Y') + + total_free_cache = @cache_age_histogram[-1][1] + persisted_storage = 1 - total_free_cache + @cache_age_histogram.map! { |x| {:age => histogram_date_ms - x[0]*1000, + :cache => total_free_cache - x[1], + :persisted => persisted_storage} } + end + + # Do the regular control work needed. + super + end +end diff --git a/apps/workbench/app/controllers/keep_services_controller.rb b/apps/workbench/app/controllers/keep_services_controller.rb new file mode 100644 index 0000000000..eac2e226a8 --- /dev/null +++ b/apps/workbench/app/controllers/keep_services_controller.rb @@ -0,0 +1,2 @@ +class KeepServicesController < ApplicationController +end diff --git a/apps/workbench/app/controllers/links_controller.rb b/apps/workbench/app/controllers/links_controller.rb new file mode 100644 index 0000000000..fd51fb1616 --- /dev/null +++ b/apps/workbench/app/controllers/links_controller.rb @@ -0,0 +1,9 @@ +class LinksController < ApplicationController + def show + if @object.link_class == 'name' and + Collection == ArvadosBase::resource_class_for_uuid(@object.head_uuid) + return redirect_to collection_path(@object.uuid) + end + super + end +end diff --git a/apps/workbench/app/controllers/logs_controller.rb b/apps/workbench/app/controllers/logs_controller.rb new file mode 100644 index 0000000000..48ad4edf08 --- /dev/null +++ b/apps/workbench/app/controllers/logs_controller.rb @@ -0,0 +1,3 @@ +class LogsController < ApplicationController + before_filter :ensure_current_user_is_admin +end diff --git a/apps/workbench/app/controllers/nodes_controller.rb b/apps/workbench/app/controllers/nodes_controller.rb new file mode 100644 index 0000000000..36348d67b5 --- /dev/null +++ b/apps/workbench/app/controllers/nodes_controller.rb @@ -0,0 +1,2 @@ +class NodesController < ApplicationController +end diff --git a/apps/workbench/app/controllers/pipeline_instances_controller.rb b/apps/workbench/app/controllers/pipeline_instances_controller.rb new file mode 100644 index 0000000000..25f5ee421c --- /dev/null +++ b/apps/workbench/app/controllers/pipeline_instances_controller.rb @@ -0,0 +1,299 @@ +class PipelineInstancesController < ApplicationController + skip_before_filter :find_object_by_uuid, only: :compare + before_filter :find_objects_by_uuid, only: :compare + include PipelineInstancesHelper + include PipelineComponentsHelper + + def copy + template = PipelineTemplate.find?(@object.pipeline_template_uuid) + + source = @object + @object = PipelineInstance.new + @object.pipeline_template_uuid = source.pipeline_template_uuid + + if params['components'] == 'use_latest' and template + @object.components = template.components.deep_dup + @object.components.each do |cname, component| + # Go through the script parameters of each component + # that are marked as user input and copy them over. + # Skip any components that are not present in the + # source instance (there's nothing to copy) + if source.components.include? cname + component[:script_parameters].each do |pname, val| + if val.is_a? Hash and val[:dataclass] + # this is user-inputtable, so check the value from the source pipeline + srcvalue = source.components[cname][:script_parameters][pname] + if not srcvalue.nil? + component[:script_parameters][pname] = srcvalue + end + end + end + end + end + else + @object.components = source.components.deep_dup + end + + if params['script'] == 'use_same' + # Go through each component and copy the script_version from each job. + @object.components.each do |cname, component| + if source.components.include? cname and source.components[cname][:job] + component[:script_version] = source.components[cname][:job][:script_version] + end + end + end + + @object.components.each do |cname, component| + component.delete :job + end + @object.state = 'New' + + # set owner_uuid to that of source, provided it is a project and wriable by current user + current_project = Group.find(source.owner_uuid) rescue nil + if (current_project && current_project.writable_by.andand.include?(current_user.uuid)) + @object.owner_uuid = source.owner_uuid + end + + super + end + + def update + @updates ||= params[@object.class.to_s.underscore.singularize.to_sym] + if (components = @updates[:components]) + components.each do |cname, component| + if component[:script_parameters] + component[:script_parameters].each do |param, value_info| + if value_info.is_a? Hash + value_info_partitioned = value_info[:value].partition('/') if value_info[:value].andand.class.eql?(String) + value_info_value = value_info_partitioned ? value_info_partitioned[0] : value_info[:value] + value_info_class = resource_class_for_uuid value_info_value + if value_info_class == Link + # Use the link target, not the link itself, as script + # parameter; but keep the link info around as well. + link = Link.find value_info[:value] + value_info[:value] = link.head_uuid + value_info[:link_uuid] = link.uuid + value_info[:link_name] = link.name + else + # Delete stale link_uuid and link_name data. + value_info[:link_uuid] = nil + value_info[:link_name] = nil + end + if value_info_class == Collection + # to ensure reproducibility, the script_parameter for a + # collection should be the portable_data_hash + # keep the collection name and uuid for human-readability + obj = Collection.find value_info_value + if value_info_partitioned + value_info[:value] = obj.portable_data_hash + value_info_partitioned[1] + value_info_partitioned[2] + value_info[:selection_name] = obj.name ? obj.name + value_info_partitioned[1] + value_info_partitioned[2] : obj.name + else + value_info[:value] = obj.portable_data_hash + value_info[:selection_name] = obj.name + end + value_info[:selection_uuid] = obj.uuid + end + end + end + end + end + end + super + end + + def graph(pipelines) + return nil, nil if params['tab_pane'] != "Graph" + + provenance = {} + pips = {} + n = 1 + + # When comparing more than one pipeline, "pips" stores bit fields that + # indicates which objects are part of which pipelines. + + pipelines.each do |p| + collections = [] + hashes = [] + jobs = [] + + p[:components].each do |k, v| + provenance["component_#{p[:uuid]}_#{k}"] = v + + collections << v[:output_uuid] if v[:output_uuid] + jobs << v[:job][:uuid] if v[:job] + end + + jobs = jobs.compact.uniq + if jobs.any? + Job.where(uuid: jobs).each do |j| + job_uuid = j.uuid + + provenance[job_uuid] = j + pips[job_uuid] = 0 unless pips[job_uuid] != nil + pips[job_uuid] |= n + + hashes << j[:output] if j[:output] + ProvenanceHelper::find_collections(j) do |hash, uuid| + collections << uuid if uuid + hashes << hash if hash + end + + if j[:script_version] + script_uuid = j[:script_version] + provenance[script_uuid] = {:uuid => script_uuid} + pips[script_uuid] = 0 unless pips[script_uuid] != nil + pips[script_uuid] |= n + end + end + end + + hashes = hashes.compact.uniq + if hashes.any? + Collection.where(portable_data_hash: hashes).each do |c| + hash_uuid = c.portable_data_hash + provenance[hash_uuid] = c + pips[hash_uuid] = 0 unless pips[hash_uuid] != nil + pips[hash_uuid] |= n + end + end + + collections = collections.compact.uniq + if collections.any? + Collection.where(uuid: collections).each do |c| + collection_uuid = c.uuid + provenance[collection_uuid] = c + pips[collection_uuid] = 0 unless pips[collection_uuid] != nil + pips[collection_uuid] |= n + end + end + + n = n << 1 + end + + return provenance, pips + end + + def show + # the #show action can also be called by #compare, which does its own work to set up @pipelines + unless defined? @pipelines + @pipelines = [@object] + end + + provenance, pips = graph(@pipelines) + if provenance + @prov_svg = ProvenanceHelper::create_provenance_graph provenance, "provenance_svg", { + :request => request, + :all_script_parameters => true, + :combine_jobs => :script_and_version, + :pips => pips, + :only_components => true, + :no_docker => true, + :no_log => true} + end + + super + end + + def compare + @breadcrumb_page_name = 'compare' + + @rows = [] # each is {name: S, components: [...]} + + if params['tab_pane'] == "Compare" or params['tab_pane'].nil? + # Build a table: x=pipeline y=component + @objects.each_with_index do |pi, pi_index| + pipeline_jobs(pi).each do |component| + # Find a cell with the same name as this component but no + # entry for this pipeline + target_row = nil + @rows.each_with_index do |row, row_index| + if row[:name] == component[:name] and !row[:components][pi_index] + target_row = row + end + end + if !target_row + target_row = {name: component[:name], components: []} + @rows << target_row + end + target_row[:components][pi_index] = component + end + end + + @rows.each do |row| + # Build a "normal" pseudo-component for this row by picking the + # most common value for each attribute. If all values are + # equally common, there is no "normal". + normal = {} # attr => most common value + highscore = {} # attr => how common "normal" is + score = {} # attr => { value => how common } + row[:components].each do |pj| + next if pj.nil? + pj.each do |k,v| + vstr = for_comparison v + score[k] ||= {} + score[k][vstr] = (score[k][vstr] || 0) + 1 + highscore[k] ||= 0 + if score[k][vstr] == highscore[k] + # tie for first place = no "normal" + normal.delete k + elsif score[k][vstr] == highscore[k] + 1 + # more pipelines have v than anything else + highscore[k] = score[k][vstr] + normal[k] = vstr + end + end + end + + # Add a hash in component[:is_normal]: { attr => is_the_value_normal? } + row[:components].each do |pj| + next if pj.nil? + pj[:is_normal] = {} + pj.each do |k,v| + pj[:is_normal][k] = (normal.has_key?(k) && normal[k] == for_comparison(v)) + end + end + end + end + + if params['tab_pane'] == "Graph" + @pipelines = @objects + end + + @object = @objects.first + + show + end + + def show_pane_list + panes = %w(Components Log Graph Advanced) + if @object and @object.state.in? ['New', 'Ready'] + panes = %w(Inputs) + panes - %w(Log) + end + if not @object.components.values.any? { |x| x[:job] rescue false } + panes -= ['Graph'] + end + panes + end + + def compare_pane_list + %w(Compare Graph) + end + + protected + def for_comparison v + if v.is_a? Hash or v.is_a? Array + v.to_json + else + v.to_s + end + end + + def load_filters_and_paging_params + params[:limit] = 20 + super + end + + def find_objects_by_uuid + @objects = model_class.where(uuid: params[:uuids]) + end +end diff --git a/apps/workbench/app/controllers/pipeline_templates_controller.rb b/apps/workbench/app/controllers/pipeline_templates_controller.rb new file mode 100644 index 0000000000..2b2e9a4e33 --- /dev/null +++ b/apps/workbench/app/controllers/pipeline_templates_controller.rb @@ -0,0 +1,12 @@ +class PipelineTemplatesController < ApplicationController + include PipelineComponentsHelper + + def show + @objects = PipelineInstance.where(pipeline_template_uuid: @object.uuid) + super + end + + def show_pane_list + %w(Components Pipelines Advanced) + end +end diff --git a/apps/workbench/app/controllers/projects_controller.rb b/apps/workbench/app/controllers/projects_controller.rb new file mode 100644 index 0000000000..600af8d60b --- /dev/null +++ b/apps/workbench/app/controllers/projects_controller.rb @@ -0,0 +1,340 @@ +class ProjectsController < ApplicationController + before_filter :set_share_links, if: -> { defined? @object } + + def model_class + Group + end + + def find_object_by_uuid + if current_user and params[:uuid] == current_user.uuid + @object = current_user.dup + @object.uuid = current_user.uuid + class << @object + def name + 'Home' + end + def description + '' + end + def attribute_editable? attr, *args + case attr + when 'description', 'name' + false + else + super + end + end + end + else + super + end + end + + def set_share_links + @user_is_manager = false + @share_links = [] + if @object.uuid != current_user.uuid + begin + @share_links = Link.permissions_for(@object) + @user_is_manager = true + rescue ArvadosApiClient::AccessForbiddenException, + ArvadosApiClient::NotFoundException + end + end + end + + def index_pane_list + %w(Projects) + end + + # Returning an array of hashes instead of an array of strings will allow + # us to tell the interface to get counts for each pane (using :filters). + # It also seems to me that something like these could be used to configure the contents of the panes. + def show_pane_list + pane_list = [ + { + :name => 'Data_collections', + :filters => [%w(uuid is_a arvados#collection)] + }, + { + :name => 'Jobs_and_pipelines', + :filters => [%w(uuid is_a) + [%w(arvados#job arvados#pipelineInstance)]] + }, + { + :name => 'Pipeline_templates', + :filters => [%w(uuid is_a arvados#pipelineTemplate)] + }, + { + :name => 'Subprojects', + :filters => [%w(uuid is_a arvados#group)] + }, + { :name => 'Other_objects', + :filters => [%w(uuid is_a) + [%w(arvados#human arvados#specimen arvados#trait)]] + } + ] + pane_list << { :name => 'Sharing', + :count => @share_links.count } if @user_is_manager + pane_list << { :name => 'Advanced' } + end + + # Called via AJAX and returns Javascript that populates tab counts into tab titles. + # References #show_pane_list action which should return an array of hashes each with :name + # and then optionally a :filters to run or a straight up :count + # + # This action could easily be moved to the ApplicationController to genericize the tab_counts behaviour, + # but one or more new routes would have to be created, the js.erb would also have to be moved + def tab_counts + @tab_counts = {} + show_pane_list.each do |pane| + if pane.is_a?(Hash) + if pane[:count] + @tab_counts[pane[:name]] = pane[:count] + elsif pane[:filters] + @tab_counts[pane[:name]] = @object.contents(filters: pane[:filters]).items_available + end + end + end + end + + def remove_item + params[:item_uuids] = [params[:item_uuid]] + remove_items + render template: 'projects/remove_items' + end + + def remove_items + @removed_uuids = [] + links = [] + params[:item_uuids].collect { |uuid| ArvadosBase.find uuid }.each do |item| + if (item.class == Link and + item.link_class == 'name' and + item.tail_uuid == @object.uuid) + # Given uuid is a name link, linking an object to this + # project. First follow the link to find the item we're removing, + # then delete the link. + links << item + item = ArvadosBase.find item.head_uuid + else + # Given uuid is an object. Delete all names. + links += Link.where(tail_uuid: @object.uuid, + head_uuid: item.uuid, + link_class: 'name') + end + links.each do |link| + @removed_uuids << link.uuid + link.destroy + end + if item.owner_uuid == @object.uuid + # Object is owned by this project. Remove it from the project by + # changing owner to the current user. + begin + item.update_attributes owner_uuid: current_user.uuid + @removed_uuids << item.uuid + rescue ArvadosApiClient::ApiErrorResponseException => e + if e.message.include? 'collection_owner_uuid_name_unique' + rename_to = item.name + ' removed from ' + + (@object.name ? @object.name : @object.uuid) + + ' at ' + Time.now.to_s + updates = {} + updates[:name] = rename_to + updates[:owner_uuid] = current_user.uuid + item.update_attributes updates + @removed_uuids << item.uuid + else + raise + end + end + end + end + end + + def destroy + while (objects = Link.filter([['owner_uuid','=',@object.uuid], + ['tail_uuid','=',@object.uuid]])).any? + objects.each do |object| + object.destroy + end + end + while (objects = @object.contents(include_linked: false)).any? + objects.each do |object| + object.update_attributes! owner_uuid: current_user.uuid + end + end + if ArvadosBase::resource_class_for_uuid(@object.owner_uuid) == Group + params[:return_to] ||= group_path(@object.owner_uuid) + else + params[:return_to] ||= projects_path + end + super + end + + def find_objects_for_index + @objects = all_projects + super + end + + def load_contents_objects kinds=[] + kind_filters = @filters.select do |attr,op,val| + op == 'is_a' and val.is_a? Array and val.count > 1 + end + if /^created_at\b/ =~ @order[0] and kind_filters.count == 1 + # If filtering on multiple types and sorting by date: Get the + # first page of each type, sort the entire set, truncate to one + # page, and use the last item on this page as a filter for + # retrieving the next page. Ideally the API would do this for + # us, but it doesn't (yet). + + # To avoid losing items that have the same created_at as the + # last item on this page, we retrieve an overlapping page with a + # "created_at <= last_created_at" filter, then remove duplicates + # with a "uuid not in [...]" filter (see below). + nextpage_operator = /\bdesc$/i =~ @order[0] ? '<=' : '>=' + + @objects = [] + @name_link_for = {} + kind_filters.each do |attr,op,val| + (val.is_a?(Array) ? val : [val]).each do |type| + objects = @object.contents(order: @order, + limit: @limit, + include_linked: true, + filters: (@filters - kind_filters + [['uuid', 'is_a', type]]), + ) + objects.each do |object| + @name_link_for[object.andand.uuid] = objects.links_for(object, 'name').first + end + @objects += objects + end + end + @objects = @objects.to_a.sort_by(&:created_at) + @objects.reverse! if nextpage_operator == '<=' + @objects = @objects[0..@limit-1] + @next_page_filters = @filters.reject do |attr,op,val| + (attr == 'created_at' and op == nextpage_operator) or + (attr == 'uuid' and op == 'not in') + end + + if @objects.any? + last_created_at = @objects.last.created_at + + last_uuids = [] + @objects.each do |obj| + last_uuids << obj.uuid if obj.created_at.eql?(last_created_at) + end + + @next_page_filters += [['created_at', + nextpage_operator, + last_created_at]] + @next_page_filters += [['uuid', 'not in', last_uuids]] + @next_page_href = url_for(partial: :contents_rows, + limit: @limit, + filters: @next_page_filters.to_json) + else + @next_page_href = nil + end + else + @objects = @object.contents(order: @order, + limit: @limit, + include_linked: true, + filters: @filters, + offset: @offset) + @next_page_href = next_page_href(partial: :contents_rows, + filters: @filters.to_json, + order: @order.to_json) + end + + preload_links_for_objects(@objects.to_a) + end + + def show + if !@object + return render_not_found("object not found") + end + + if params[:partial] + load_contents_objects + respond_to do |f| + f.json { + render json: { + content: render_to_string(partial: 'show_contents_rows.html', + formats: [:html]), + next_page_href: @next_page_href + } + } + end + else + @objects = [] + super + end + end + + def create + @new_resource_attrs = (params['project'] || {}).merge(group_class: 'project') + @new_resource_attrs[:name] ||= 'New project' + super + end + + def update + @updates = params['project'] + super + end + + helper_method :get_objects_and_names + def get_objects_and_names(objects=nil) + objects = @objects if objects.nil? + objects_and_names = [] + objects.each do |object| + if objects.respond_to? :links_for and + !(name_links = objects.links_for(object, 'name')).empty? + name_links.each do |name_link| + objects_and_names << [object, name_link] + end + elsif @name_link_for.andand[object.uuid] + objects_and_names << [object, @name_link_for[object.uuid]] + elsif object.respond_to? :name + objects_and_names << [object, object] + else + objects_and_names << [object, + Link.new(owner_uuid: @object.uuid, + tail_uuid: @object.uuid, + head_uuid: object.uuid, + link_class: "name", + name: "")] + + end + end + objects_and_names + end + + def share_with + if not params[:uuids].andand.any? + @errors = ["No user/group UUIDs specified to share with."] + return render_error(status: 422) + end + results = {"success" => [], "errors" => []} + params[:uuids].each do |shared_uuid| + begin + Link.create(tail_uuid: shared_uuid, link_class: "permission", + name: "can_read", head_uuid: @object.uuid) + rescue ArvadosApiClient::ApiError => error + error_list = error.api_response.andand[:errors] + if error_list.andand.any? + results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" } + else + error_code = error.api_status || "Bad status" + results["errors"] << "#{shared_uuid}: #{error_code} response" + end + else + results["success"] << shared_uuid + end + end + if results["errors"].empty? + results.delete("errors") + status = 200 + else + status = 422 + end + respond_to do |f| + f.json { render(json: results, status: status) } + end + end +end diff --git a/apps/workbench/app/controllers/repositories_controller.rb b/apps/workbench/app/controllers/repositories_controller.rb new file mode 100644 index 0000000000..b6b3295ef8 --- /dev/null +++ b/apps/workbench/app/controllers/repositories_controller.rb @@ -0,0 +1,5 @@ +class RepositoriesController < ApplicationController + def index_pane_list + %w(recent help) + end +end diff --git a/apps/workbench/app/controllers/search_controller.rb b/apps/workbench/app/controllers/search_controller.rb new file mode 100644 index 0000000000..9e2ff1b00b --- /dev/null +++ b/apps/workbench/app/controllers/search_controller.rb @@ -0,0 +1,28 @@ +class SearchController < ApplicationController + def find_objects_for_index + search_what = Group + if params[:project_uuid] + # Special case for "search all things in project": + @filters = @filters.select do |attr, operator, operand| + not (attr == 'owner_uuid' and operator == '=') + end + # Special case for project_uuid is a user uuid: + if ArvadosBase::resource_class_for_uuid(params[:project_uuid]) == User + search_what = User.find params[:project_uuid] + else + search_what = Group.find params[:project_uuid] + end + end + @objects = search_what.contents(limit: @limit, + offset: @offset, + filters: @filters, + include_linked: true) + super + end + + def next_page_href with_params={} + super with_params.merge(last_object_class: @objects.last.class.to_s, + project_uuid: params[:project_uuid], + filters: @filters.to_json) + end +end diff --git a/apps/workbench/app/controllers/sessions_controller.rb b/apps/workbench/app/controllers/sessions_controller.rb new file mode 100644 index 0000000000..97c8d5a9dd --- /dev/null +++ b/apps/workbench/app/controllers/sessions_controller.rb @@ -0,0 +1,15 @@ +class SessionsController < ApplicationController + skip_around_filter :require_thread_api_token, :only => [:destroy, :index] + skip_around_filter :set_thread_api_token, :only => [:destroy, :index] + skip_before_filter :find_object_by_uuid, :only => [:destroy, :index] + + def destroy + session.clear + redirect_to arvados_api_client.arvados_logout_url(return_to: root_url) + end + + def index + redirect_to root_url if session[:arvados_api_token] + render_index + end +end diff --git a/apps/workbench/app/controllers/specimens_controller.rb b/apps/workbench/app/controllers/specimens_controller.rb new file mode 100644 index 0000000000..47dd8a2358 --- /dev/null +++ b/apps/workbench/app/controllers/specimens_controller.rb @@ -0,0 +1,2 @@ +class SpecimensController < ApplicationController +end diff --git a/apps/workbench/app/controllers/traits_controller.rb b/apps/workbench/app/controllers/traits_controller.rb new file mode 100644 index 0000000000..38f33a3363 --- /dev/null +++ b/apps/workbench/app/controllers/traits_controller.rb @@ -0,0 +1,2 @@ +class TraitsController < ApplicationController +end diff --git a/apps/workbench/app/controllers/user_agreements_controller.rb b/apps/workbench/app/controllers/user_agreements_controller.rb new file mode 100644 index 0000000000..bec11f2dc6 --- /dev/null +++ b/apps/workbench/app/controllers/user_agreements_controller.rb @@ -0,0 +1,25 @@ +class UserAgreementsController < ApplicationController + skip_before_filter :check_user_agreements + skip_before_filter :find_object_by_uuid + skip_before_filter :check_user_profile + + def index + if unsigned_user_agreements.empty? + redirect_to(params[:return_to] || :back) + end + end + + def model_class + Collection + end + + def sign + params[:checked].each do |checked| + if (r = CollectionsHelper.match_uuid_with_optional_filepath(checked)) + UserAgreement.sign uuid: r[1] + end + end + current_user.activate + redirect_to(params[:return_to] || :back) + end +end diff --git a/apps/workbench/app/controllers/users_controller.rb b/apps/workbench/app/controllers/users_controller.rb new file mode 100644 index 0000000000..43a88955f0 --- /dev/null +++ b/apps/workbench/app/controllers/users_controller.rb @@ -0,0 +1,353 @@ +class UsersController < ApplicationController + skip_around_filter :require_thread_api_token, only: :welcome + skip_before_filter :check_user_agreements, only: [:welcome, :inactive] + skip_before_filter :check_user_profile, only: [:welcome, :inactive, :profile] + skip_before_filter :find_object_by_uuid, only: [:welcome, :activity, :storage] + before_filter :ensure_current_user_is_admin, only: [:sudo, :unsetup, :setup] + + def show + if params[:uuid] == current_user.uuid + respond_to do |f| + f.html do + redirect_to(params[:return_to] || project_path(params[:uuid])) + end + end + else + super + end + end + + def welcome + if current_user + redirect_to (params[:return_to] || '/') + end + end + + def inactive + if current_user.andand.is_invited + redirect_to (params[:return_to] || '/') + end + end + + def profile + params[:offer_return_to] ||= params[:return_to] + end + + def activity + @breadcrumb_page_name = nil + @users = User.limit(params[:limit]) + @user_activity = {} + @activity = { + logins: {}, + jobs: {}, + pipeline_instances: {} + } + @total_activity = {} + @spans = [['This week', Time.now.beginning_of_week, Time.now], + ['Last week', + Time.now.beginning_of_week.advance(weeks:-1), + Time.now.beginning_of_week], + ['This month', Time.now.beginning_of_month, Time.now], + ['Last month', + 1.month.ago.beginning_of_month, + Time.now.beginning_of_month]] + @spans.each do |span, threshold_start, threshold_end| + @activity[:logins][span] = Log. + filter([[:event_type, '=', 'login'], + [:object_kind, '=', 'arvados#user'], + [:created_at, '>=', threshold_start], + [:created_at, '<', threshold_end]]) + @activity[:jobs][span] = Job. + filter([[:created_at, '>=', threshold_start], + [:created_at, '<', threshold_end]]) + @activity[:pipeline_instances][span] = PipelineInstance. + filter([[:created_at, '>=', threshold_start], + [:created_at, '<', threshold_end]]) + @activity.each do |type, act| + records = act[span] + @users.each do |u| + @user_activity[u.uuid] ||= {} + @user_activity[u.uuid][span + ' ' + type.to_s] ||= 0 + end + records.each do |record| + @user_activity[record.modified_by_user_uuid] ||= {} + @user_activity[record.modified_by_user_uuid][span + ' ' + type.to_s] ||= 0 + @user_activity[record.modified_by_user_uuid][span + ' ' + type.to_s] += 1 + @total_activity[span + ' ' + type.to_s] ||= 0 + @total_activity[span + ' ' + type.to_s] += 1 + end + end + end + @users = @users.sort_by do |a| + [-@user_activity[a.uuid].values.inject(:+), a.full_name] + end + # Prepend a "Total" pseudo-user to the sorted list + @user_activity[nil] = @total_activity + @users = [OpenStruct.new(uuid: nil)] + @users + end + + def storage + @breadcrumb_page_name = nil + @users = User.limit(params[:limit]) + @user_storage = {} + total_storage = {} + @log_date = {} + @users.each do |u| + @user_storage[u.uuid] ||= {} + storage_log = Log. + filter([[:object_uuid, '=', u.uuid], + [:event_type, '=', 'user-storage-report']]). + order(:created_at => :desc). + limit(1) + storage_log.each do |log_entry| + # We expect this block to only execute once since we specified limit(1) + @user_storage[u.uuid] = log_entry['properties'] + @log_date[u.uuid] = log_entry['event_at'] + end + total_storage.merge!(@user_storage[u.uuid]) { |k,v1,v2| v1 + v2 } + end + @users = @users.sort_by { |u| + [-@user_storage[u.uuid].values.push(0).inject(:+), u.full_name]} + # Prepend a "Total" pseudo-user to the sorted list + @users = [OpenStruct.new(uuid: nil)] + @users + @user_storage[nil] = total_storage + end + + def show_pane_list + if current_user.andand.is_admin + super | %w(Admin) + else + super + end + end + + def index_pane_list + if current_user.andand.is_admin + super | %w(Activity) + else + super + end + end + + def sudo + resp = arvados_api_client.api(ApiClientAuthorization, '', { + api_client_authorization: { + owner_uuid: @object.uuid + } + }) + redirect_to root_url(api_token: resp[:api_token]) + end + + def home + @showallalerts = false + @my_ssh_keys = AuthorizedKey.where(authorized_user_uuid: current_user.uuid) + @my_tag_links = {} + + @my_jobs = Job. + limit(10). + order('created_at desc'). + where(created_by: current_user.uuid) + + @my_collections = Collection. + limit(10). + order('created_at desc'). + where(created_by: current_user.uuid) + collection_uuids = @my_collections.collect &:uuid + + @persist_state = {} + collection_uuids.each do |uuid| + @persist_state[uuid] = 'cache' + end + + Link.filter([['head_uuid', 'in', collection_uuids], + ['link_class', 'in', ['tag', 'resources']]]). + each do |link| + case link.link_class + when 'tag' + (@my_tag_links[link.head_uuid] ||= []) << link + when 'resources' + if link.name == 'wants' + @persist_state[link.head_uuid] = 'persistent' + end + end + end + + @my_pipelines = PipelineInstance. + limit(10). + order('created_at desc'). + where(created_by: current_user.uuid) + + respond_to do |f| + f.js { render template: 'users/home.js' } + f.html { render template: 'users/home' } + end + end + + def unsetup + if current_user.andand.is_admin + @object.unsetup + end + show + end + + def setup + respond_to do |format| + if current_user.andand.is_admin + setup_params = {} + setup_params[:send_notification_email] = "#{Rails.configuration.send_user_setup_notification_email}" + if params['user_uuid'] && params['user_uuid'].size>0 + setup_params[:uuid] = params['user_uuid'] + end + if params['email'] && params['email'].size>0 + user = {email: params['email']} + setup_params[:user] = user + end + if params['openid_prefix'] && params['openid_prefix'].size>0 + setup_params[:openid_prefix] = params['openid_prefix'] + end + if params['repo_name'] && params['repo_name'].size>0 + setup_params[:repo_name] = params['repo_name'] + end + if params['vm_uuid'] && params['vm_uuid'].size>0 + setup_params[:vm_uuid] = params['vm_uuid'] + end + + if User.setup setup_params + format.js + else + self.render_error status: 422 + end + else + self.render_error status: 422 + end + end + end + + def setup_popup + @vms = VirtualMachine.all.results + + @current_selections = find_current_links @object + + respond_to do |format| + format.html + format.js + end + end + + def manage_account + # repositories current user can read / write + repo_links = Link. + filter([['head_uuid', 'is_a', 'arvados#repository'], + ['tail_uuid', '=', current_user.uuid], + ['link_class', '=', 'permission'], + ]) + @my_repositories = Repository.where uuid: repo_links.collect(&:head_uuid) + @repo_writable = {} + repo_links.each do |link| + if link.name.in? ['can_write', 'can_manage'] + @repo_writable[link.head_uuid] = true + end + end + + # virtual machines the current user can login into + @my_vm_logins = {} + Link.where(tail_uuid: current_user.uuid, + link_class: 'permission', + name: 'can_login'). + each do |perm_link| + if perm_link.properties.andand[:username] + @my_vm_logins[perm_link.head_uuid] ||= [] + @my_vm_logins[perm_link.head_uuid] << perm_link.properties[:username] + end + end + @my_virtual_machines = VirtualMachine.where(uuid: @my_vm_logins.keys) + + # current user's ssh keys + @my_ssh_keys = AuthorizedKey.where(key_type: 'SSH', owner_uuid: current_user.uuid) + + respond_to do |f| + f.html { render template: 'users/manage_account' } + end + end + + def add_ssh_key_popup + respond_to do |format| + format.html + format.js + end + end + + def add_ssh_key + respond_to do |format| + key_params = {'key_type' => 'SSH'} + key_params['authorized_user_uuid'] = current_user.uuid + + if params['name'] && params['name'].size>0 + key_params['name'] = params['name'].strip + end + if params['public_key'] && params['public_key'].size>0 + key_params['public_key'] = params['public_key'].strip + end + + if !key_params['name'] && params['public_key'].andand.size>0 + split_key = key_params['public_key'].split + key_params['name'] = split_key[-1] if (split_key.size == 3) + end + + new_key = AuthorizedKey.create! key_params + if new_key + format.js + else + self.render_error status: 422 + end + end + end + + protected + + def find_current_links user + current_selections = {} + + if !user + return current_selections + end + + # oid login perm + oid_login_perms = Link.where(tail_uuid: user.email, + head_kind: 'arvados#user', + link_class: 'permission', + name: 'can_login') + + if oid_login_perms.any? + prefix_properties = oid_login_perms.first.properties + current_selections[:identity_url_prefix] = prefix_properties[:identity_url_prefix] + end + + # repo perm + repo_perms = Link.where(tail_uuid: user.uuid, + head_kind: 'arvados#repository', + link_class: 'permission', + name: 'can_write') + if repo_perms.any? + repo_uuid = repo_perms.first.head_uuid + repos = Repository.where(head_uuid: repo_uuid) + if repos.any? + repo_name = repos.first.name + current_selections[:repo_name] = repo_name + end + end + + # vm login perm + vm_login_perms = Link.where(tail_uuid: user.uuid, + head_kind: 'arvados#virtualMachine', + link_class: 'permission', + name: 'can_login') + if vm_login_perms.any? + vm_uuid = vm_login_perms.first.head_uuid + current_selections[:vm_uuid] = vm_uuid + end + + return current_selections + end + +end diff --git a/apps/workbench/app/controllers/virtual_machines_controller.rb b/apps/workbench/app/controllers/virtual_machines_controller.rb new file mode 100644 index 0000000000..a62ba81b09 --- /dev/null +++ b/apps/workbench/app/controllers/virtual_machines_controller.rb @@ -0,0 +1,22 @@ +class VirtualMachinesController < ApplicationController + def index + @objects ||= model_class.all + @vm_logins = {} + if @objects.andand.first + Link.where(tail_uuid: current_user.uuid, + head_uuid: @objects.collect(&:uuid), + link_class: 'permission', + name: 'can_login'). + each do |perm_link| + if perm_link.properties.andand[:username] + @vm_logins[perm_link.head_uuid] ||= [] + @vm_logins[perm_link.head_uuid] << perm_link.properties[:username] + end + end + @objects.each do |vm| + vm.current_user_logins = @vm_logins[vm.uuid].andand.compact || [] + end + end + super + end +end diff --git a/apps/workbench/app/controllers/websocket_controller.rb b/apps/workbench/app/controllers/websocket_controller.rb new file mode 100644 index 0000000000..a49c15f5bc --- /dev/null +++ b/apps/workbench/app/controllers/websocket_controller.rb @@ -0,0 +1,10 @@ +class WebsocketController < ApplicationController + skip_before_filter :find_objects_for_index + + def index + end + + def model_class + "Websocket" + end +end diff --git a/apps/workbench/app/helpers/application_helper.rb b/apps/workbench/app/helpers/application_helper.rb new file mode 100644 index 0000000000..f1502afee1 --- /dev/null +++ b/apps/workbench/app/helpers/application_helper.rb @@ -0,0 +1,422 @@ +module ApplicationHelper + def current_user + controller.current_user + end + + def self.match_uuid(uuid) + /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s) + end + + def current_api_host + Rails.configuration.arvados_v1_base.gsub /https?:\/\/|\/arvados\/v1/,'' + end + + def render_markup(markup) + raw RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile) if markup + end + + def human_readable_bytes_html(n) + return h(n) unless n.is_a? Fixnum + return "0 bytes" if (n == 0) + + orders = { + 1 => "bytes", + 1024 => "KiB", + (1024*1024) => "MiB", + (1024*1024*1024) => "GiB", + (1024*1024*1024*1024) => "TiB" + } + + orders.each do |k, v| + sig = (n.to_f/k) + if sig >=1 and sig < 1024 + if v == 'bytes' + return "%i #{v}" % sig + else + return "%0.1f #{v}" % sig + end + end + end + + return h(n) + #raw = n.to_s + #cooked = '' + #while raw.length > 3 + # cooked = ',' + raw[-3..-1] + cooked + # raw = raw[0..-4] + #end + #cooked = raw + cooked + end + + def resource_class_for_uuid(attrvalue, opts={}) + ArvadosBase::resource_class_for_uuid(attrvalue, opts) + end + + ## + # Returns HTML that links to the Arvados object specified in +attrvalue+ + # Provides various output control and styling options. + # + # +attrvalue+ an Arvados model object or uuid + # + # +opts+ a set of flags to control output: + # + # [:link_text] the link text to use (may include HTML), overrides everything else + # + # [:friendly_name] whether to use the "friendly" name in the link text (by + # calling #friendly_link_name on the object), otherwise use the uuid + # + # [:with_class_name] prefix the link text with the class name of the model + # + # [:no_tags] disable tags in the link text (default is to show tags). + # Currently tags are only shown for Collections. + # + # [:thumbnail] if the object is a collection, show an image thumbnail if the + # collection consists of a single image file. + # + # [:no_link] don't create a link, just return the link text + # + # +style_opts+ additional HTML properties for the anchor tag, passed to link_to + # + def link_to_if_arvados_object(attrvalue, opts={}, style_opts={}) + if (resource_class = resource_class_for_uuid(attrvalue, opts)) + if attrvalue.is_a? ArvadosBase + object = attrvalue + link_uuid = attrvalue.uuid + else + object = nil + link_uuid = attrvalue + end + link_name = opts[:link_text] + tags = "" + if !link_name + link_name = object.andand.default_name || resource_class.default_name + + if opts[:friendly_name] + if attrvalue.respond_to? :friendly_link_name + link_name = attrvalue.friendly_link_name opts[:lookup] + else + begin + if resource_class.name == 'Collection' + link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name + else + link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name + end + rescue ArvadosApiClient::NotFoundException + # If that lookup failed, the link will too. So don't make one. + return attrvalue + end + end + end + if link_name.nil? or link_name.empty? + link_name = attrvalue + end + if opts[:with_class_name] + link_name = "#{resource_class.to_s}: #{link_name}" + end + if !opts[:no_tags] and resource_class == Collection + links_for_object(link_uuid).each do |tag| + if tag.link_class.in? ["tag", "identifier"] + tags += ' ' + tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json + tags += '' + end + end + end + if opts[:thumbnail] and resource_class == Collection + # add an image thumbnail if the collection consists of a single image file. + collections_for_object(link_uuid).each do |c| + if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1] + link_name += " " + link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto" + end + end + end + end + style_opts[:class] = (style_opts[:class] || '') + ' nowrap' + if opts[:no_link] + raw(link_name) + else + (link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags) + end + else + # just return attrvalue if it is not recognizable as an Arvados object or uuid. + if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?) + "(none)" + else + attrvalue + end + end + end + + def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}) + attrvalue = object.send(attr) if attrvalue.nil? + if not object.attribute_editable?(attr) + if attrvalue && attrvalue.length > 0 + return render_attribute_as_textile( object, attr, attrvalue, false ) + else + return (attr == 'name' and object.andand.default_name) || + '(none)' + end + end + + input_type = 'text' + case object.class.attribute_info[attr.to_sym].andand[:type] + when 'text' + input_type = 'textarea' + when 'datetime' + input_type = 'date' + else + input_type = 'text' + end + + attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array + rendervalue = render_attribute_as_textile( object, attr, attrvalue, false ) + + ajax_options = { + "data-pk" => { + id: object.uuid, + key: object.class.to_s.underscore + } + } + if object.uuid + ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore) + else + ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore) + ajax_options['data-pk'][:defaults] = object.attributes + end + ajax_options['data-pk'] = ajax_options['data-pk'].to_json + @unique_id ||= (Time.now.to_f*1000000).to_i + span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s + + span_tag = content_tag 'span', rendervalue, { + "data-emptytext" => '(none)', + "data-placement" => "bottom", + "data-type" => input_type, + "data-title" => "Edit #{attr.to_s.gsub '_', ' '}", + "data-name" => attr, + "data-object-uuid" => object.uuid, + "data-toggle" => "manual", + "data-value" => attrvalue, + "id" => span_id, + :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}" + }.merge(htmloptions).merge(ajax_options) + edit_button = raw('') + if htmloptions[:btnplacement] == :left + edit_button + ' ' + span_tag + else + span_tag + ' ' + edit_button + end + end + + def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={}) + datatype = nil + required = true + attrvalue = value_info + + if value_info.is_a? Hash + if value_info[:output_of] + return raw("#{value_info[:output_of]}") + end + if value_info[:dataclass] + dataclass = value_info[:dataclass] + end + if value_info[:optional] != nil + required = (value_info[:optional] != "true") + end + if value_info[:required] != nil + required = value_info[:required] + end + + # Pick a suitable attrvalue to show as the current value (i.e., + # the one that would be used if we ran the pipeline right now). + if value_info[:value] + attrvalue = value_info[:value] + elsif value_info[:default] + attrvalue = value_info[:default] + else + attrvalue = '' + end + preconfigured_search_str = value_info[:search_for] + end + + if not object.andand.attribute_editable?(attr) + return link_to_if_arvados_object attrvalue + end + + if dataclass + begin + dataclass = dataclass.constantize + rescue NameError + end + else + dataclass = ArvadosBase.resource_class_for_uuid(attrvalue) + end + + id = "#{object.uuid}-#{subattr.join('-')}" + dn = "[#{attr}]" + subattr.each do |a| + dn += "[#{a}]" + end + if value_info.is_a? Hash + dn += '[value]' + end + + if (dataclass == Collection) or (dataclass == File) + selection_param = object.class.to_s.underscore + dn + display_value = attrvalue + if value_info.is_a?(Hash) + if (link = Link.find? value_info[:link_uuid]) + display_value = link.name + elsif value_info[:link_name] + display_value = value_info[:link_name] + elsif value_info[:selection_name] + display_value = value_info[:selection_name] + end + end + if (attr == :components) and (subattr.size > 2) + chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:" + else + chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:" + end + modal_path = choose_collections_path \ + ({ title: chooser_title, + filters: [['owner_uuid', '=', object.owner_uuid]].to_json, + action_name: 'OK', + action_href: pipeline_instance_path(id: object.uuid), + action_method: 'patch', + preconfigured_search_str: (preconfigured_search_str || ""), + action_data: { + merge: true, + use_preview_selection: dataclass == File ? true : nil, + selection_param: selection_param, + success: 'page-refresh' + }.to_json, + }) + return content_tag('div', :class => 'input-group') do + html = text_field_tag(dn, display_value, + :class => + "form-control #{'required' if required}") + html + content_tag('span', :class => 'input-group-btn') do + link_to('Choose', + modal_path, + { :class => "btn btn-primary", + :remote => true, + :method => 'get', + }) + end + end + end + + if dataclass == 'number' or attrvalue.is_a? Fixnum or attrvalue.is_a? Float + datatype = 'number' + elsif attrvalue.is_a? String + datatype = 'text' + elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class) + # TODO: find a way to edit with x-editable + return attrvalue + end + + # When datatype is a String or Fixnum, link_to the attrvalue + lt = link_to attrvalue, '#', { + "data-emptytext" => "none", + "data-placement" => "bottom", + "data-type" => datatype, + "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true), + "data-title" => "Set value for #{subattr[-1].to_s}", + "data-name" => dn, + "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}", + "data-value" => attrvalue, + # "clear" button interferes with form-control's up/down arrows + "data-clear" => false, + :class => "editable #{'required' if required} form-control", + :id => id + }.merge(htmloptions) + + lt + end + + def render_arvados_object_list_start(list, button_text, button_href, + params={}, *rest, &block) + show_max = params.delete(:show_max) || 3 + params[:class] ||= 'btn btn-xs btn-default' + list[0...show_max].each { |item| yield item } + unless list[show_max].nil? + link_to(h(button_text) + + raw('   '), + button_href, params, *rest) + end + end + + def render_controller_partial partial, opts + cname = opts.delete :controller_name + begin + render opts.merge(partial: "#{cname}/#{partial}") + rescue ActionView::MissingTemplate + render opts.merge(partial: "application/#{partial}") + end + end + + RESOURCE_CLASS_ICONS = { + "Collection" => "fa-archive", + "Group" => "fa-users", + "Human" => "fa-male", # FIXME: Use a more inclusive icon. + "Job" => "fa-gears", + "KeepDisk" => "fa-hdd-o", + "KeepService" => "fa-exchange", + "Link" => "fa-arrows-h", + "Node" => "fa-cloud", + "PipelineInstance" => "fa-gears", + "PipelineTemplate" => "fa-gears", + "Repository" => "fa-code-fork", + "Specimen" => "fa-flask", + "Trait" => "fa-clipboard", + "User" => "fa-user", + "VirtualMachine" => "fa-terminal", + } + DEFAULT_ICON_CLASS = "fa-cube" + + def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS) + RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default) + end + + def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS) + fa_icon_class_for_class(resource_class_for_uuid(uuid), default) + end + + def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS) + case class_name = object.class.to_s + when "Group" + object.group_class ? 'fa-folder' : 'fa-users' + else + RESOURCE_CLASS_ICONS.fetch(class_name, default) + end + end + + def chooser_preview_url_for object, use_preview_selection=false + case object.class.to_s + when 'Collection' + polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection) + else + nil + end + end + + def render_attribute_as_textile( object, attr, attrvalue, truncate ) + if attrvalue && (is_textile? object, attr) + markup = render_markup attrvalue + markup = markup[0,markup.index('

    ')+4] if (truncate && markup.index('

    ')) + return markup + else + return attrvalue + end + end + + def render_localized_date(date, opts="") + raw("#{date}") + end + +private + def is_textile?( object, attr ) + is_textile = object.textile_attributes.andand.include?(attr) + end +end diff --git a/apps/workbench/app/helpers/arvados_api_client_helper.rb b/apps/workbench/app/helpers/arvados_api_client_helper.rb new file mode 100644 index 0000000000..b6c29a9070 --- /dev/null +++ b/apps/workbench/app/helpers/arvados_api_client_helper.rb @@ -0,0 +1,13 @@ +module ArvadosApiClientHelper + def arvados_api_client + ArvadosApiClient.new_or_current + end +end + +# For the benefit of themes that still expect $arvados_api_client to work: +class ArvadosClientProxyHack + def method_missing *args + ArvadosApiClient.new_or_current.send *args + end +end +$arvados_api_client = ArvadosClientProxyHack.new diff --git a/apps/workbench/app/helpers/collections_helper.rb b/apps/workbench/app/helpers/collections_helper.rb new file mode 100644 index 0000000000..23a440ad1e --- /dev/null +++ b/apps/workbench/app/helpers/collections_helper.rb @@ -0,0 +1,56 @@ +module CollectionsHelper + def d3ify_links(links) + links.collect do |x| + {source: x.tail_uuid, target: x.head_uuid, type: x.name} + end + end + + ## + # Regex match for collection portable data hash, returns a regex match object with the + # hash in group 1, (optional) size in group 2, (optional) subsequent uuid + # fields in group 3, and (optional) file path within the collection as group + # 4 + # returns nil for no match. + # + # +pdh+ the portable data hash string to match + # + def self.match(pdh) + /^([a-f0-9]{32})(\+\d+)(\+[^+]+)*?(\/.*)?$/.match(pdh.to_s) + end + + ## + # Regex match for collection UUIDs, returns a regex match object with the + # uuid in group 1, empty groups 2 and 3 (for consistency with the match + # method above), and (optional) file path within the collection as group + # 4. + # returns nil for no match. + # + def self.match_uuid_with_optional_filepath(uuid_with_optional_file) + /^([0-9a-z]{5}-4zz18-[0-9a-z]{15})()()(\/.*)?$/.match(uuid_with_optional_file.to_s) + end + + ## + # Regex match for common image file extensions, returns a regex match object + # with the matched extension in group 1; or nil for no match. + # + # +file+ the file string to match + # + def self.is_image file + /\.(jpg|jpeg|gif|png|svg)$/i.match(file) + end + + ## + # Generates a relative file path than can be appended to the URL of a + # collection to get a file download link without adding a spurious ./ at the + # beginning for files in the default stream. + # + # +file+ an entry in the Collection.files list in the form [stream, name, size] + # + def self.file_path file + f0 = file[0] + f0 = '' if f0 == '.' + f0 = f0[2..-1] if f0[0..1] == './' + f0 += '/' if not f0.empty? + file_path = "#{f0}#{file[1]}" + end +end diff --git a/apps/workbench/app/helpers/jobs_helper.rb b/apps/workbench/app/helpers/jobs_helper.rb new file mode 100644 index 0000000000..06c3d0d420 --- /dev/null +++ b/apps/workbench/app/helpers/jobs_helper.rb @@ -0,0 +1,22 @@ +module JobsHelper + def stderr_log_history(job_uuids) + results = [] + + log_history = Log.where(event_type: 'stderr', + object_uuid: job_uuids).order('id DESC') + if !log_history.results.empty? + reversed_results = log_history.results.reverse + reversed_results.each do |entry| + if entry.andand.properties + properties = entry.properties + text = properties[:text] + if text + results = results.concat text.split("\n") + end + end + end + end + return results + end + +end diff --git a/apps/workbench/app/helpers/pipeline_components_helper.rb b/apps/workbench/app/helpers/pipeline_components_helper.rb new file mode 100644 index 0000000000..8f5dba1a87 --- /dev/null +++ b/apps/workbench/app/helpers/pipeline_components_helper.rb @@ -0,0 +1,16 @@ +module PipelineComponentsHelper + def render_pipeline_components(template_suffix, fallback=nil, locals={}) + begin + render(partial: "pipeline_instances/show_components_#{template_suffix}", + locals: locals) + rescue => e + logger.error "#{e.inspect}" + logger.error "#{e.backtrace.join("\n\t")}" + case fallback + when :json + render(partial: "pipeline_instances/show_components_json", + locals: {error_name: e.inspect, backtrace: e.backtrace.join("\n\t")}) + end + end + end +end diff --git a/apps/workbench/app/helpers/pipeline_instances_helper.rb b/apps/workbench/app/helpers/pipeline_instances_helper.rb new file mode 100644 index 0000000000..b0d5216efd --- /dev/null +++ b/apps/workbench/app/helpers/pipeline_instances_helper.rb @@ -0,0 +1,309 @@ +module PipelineInstancesHelper + + def pipeline_jobs object=nil + object ||= @object + if object.components[:steps].is_a? Array + pipeline_jobs_oldschool object + elsif object.components.is_a? Hash + pipeline_jobs_newschool object + end + end + + def render_pipeline_jobs + pipeline_jobs.collect do |pj| + render_pipeline_job pj + end + end + + def render_pipeline_job pj + pj[:progress_bar] = render partial: 'job_progress', locals: {:j => pj[:job]} + pj[:output_link] = link_to_if_arvados_object pj[:output] + pj[:job_link] = link_to_if_arvados_object pj[:job][:uuid] if pj[:job] + pj + end + + # Merge (started_at, finished_at) time range into the list of time ranges in + # timestamps (timestamps must be sorted and non-overlapping). + # return the updated timestamps list. + def merge_range timestamps, started_at, finished_at + # in the comments below, 'i' is the entry in the timestamps array and 'j' + # is the started_at, finished_at range which is passed in. + timestamps.each_index do |i| + if started_at + if started_at >= timestamps[i][0] and finished_at <= timestamps[i][1] + # 'j' started and ended during 'i' + return timestamps + end + + if started_at < timestamps[i][0] and finished_at >= timestamps[i][0] and finished_at <= timestamps[i][1] + # 'j' started before 'i' and finished during 'i' + # re-merge range between when 'j' started and 'i' finished + finished_at = timestamps[i][1] + timestamps.delete_at i + return merge_range timestamps, started_at, finished_at + end + + if started_at >= timestamps[i][0] and started_at <= timestamps[i][1] + # 'j' started during 'i' and finished sometime after + # move end time of 'i' back + # re-merge range between when 'i' started and 'j' finished + started_at = timestamps[i][0] + timestamps.delete_at i + return merge_range timestamps, started_at, finished_at + end + + if finished_at < timestamps[i][0] + # 'j' finished before 'i' started, so insert before 'i' + timestamps.insert i, [started_at, finished_at] + return timestamps + end + end + end + + timestamps << [started_at, finished_at] + end + + # Accept a list of objects with [:started_at] and [:finshed_at] keys and + # merge overlapping ranges to compute the time spent running after periods of + # overlapping execution are factored out. + def determine_wallclock_runtime jobs + timestamps = [] + jobs.each do |j| + insert_at = 0 + started_at = j[:started_at] + finished_at = (if j[:finished_at] then j[:finished_at] else Time.now end) + if started_at + timestamps = merge_range timestamps, started_at, finished_at + end + end + timestamps.map { |t| t[1] - t[0] }.reduce(:+) || 0 + end + + protected + + def pipeline_jobs_newschool object + ret = [] + i = -1 + + jobuuids = object.components.values.map { |c| + c[:job][:uuid] if c.is_a?(Hash) and c[:job].is_a?(Hash) + }.compact + job = {} + Job.where(uuid: jobuuids).each do |j| + job[j[:uuid]] = j + end + + object.components.each do |cname, c| + i += 1 + pj = {index: i, name: cname} + if not c.is_a?(Hash) + ret << pj + next + end + if c[:job] and c[:job][:uuid] and job[c[:job][:uuid]] + pj[:job] = job[c[:job][:uuid]] + elsif c[:job].is_a?(Hash) + pj[:job] = c[:job] + if pj[:job][:started_at].is_a? String + pj[:job][:started_at] = Time.parse(pj[:job][:started_at]) + end + if pj[:job][:finished_at].is_a? String + pj[:job][:finished_at] = Time.parse(pj[:job][:finished_at]) + end + # If necessary, figure out the state based on the other fields. + pj[:job][:state] ||= if pj[:job][:cancelled_at] + "Cancelled" + elsif pj[:job][:success] == false + "Failed" + elsif pj[:job][:success] == true + "Complete" + elsif pj[:job][:running] == true + "Running" + else + "Queued" + end + else + pj[:job] = {} + end + pj[:percent_done] = 0 + pj[:percent_running] = 0 + if pj[:job][:success] + if pj[:job][:output] + pj[:progress] = 1.0 + pj[:percent_done] = 100 + else + pj[:progress] = 0.0 + end + else + if pj[:job][:tasks_summary] + begin + ts = pj[:job][:tasks_summary] + denom = ts[:done].to_f + ts[:running].to_f + ts[:todo].to_f + pj[:progress] = (ts[:done].to_f + ts[:running].to_f/2) / denom + pj[:percent_done] = 100.0 * ts[:done].to_f / denom + pj[:percent_running] = 100.0 * ts[:running].to_f / denom + pj[:progress_detail] = "#{ts[:done]} done #{ts[:running]} run #{ts[:todo]} todo" + rescue + pj[:progress] = 0.5 + pj[:percent_done] = 0.0 + pj[:percent_running] = 100.0 + end + else + pj[:progress] = 0.0 + end + end + + case pj[:job][:state] + when 'Complete' + pj[:result] = 'complete' + pj[:labeltype] = 'success' + pj[:complete] = true + pj[:progress] = 1.0 + when 'Failed' + pj[:result] = 'failed' + pj[:labeltype] = 'danger' + pj[:failed] = true + when 'Cancelled' + pj[:result] = 'cancelled' + pj[:labeltype] = 'danger' + pj[:failed] = true + when 'Running' + pj[:result] = 'running' + pj[:labeltype] = 'primary' + when 'Queued' + pj[:result] = 'queued' + pj[:labeltype] = 'default' + else + pj[:result] = 'none' + pj[:labeltype] = 'default' + end + + pj[:job_id] = pj[:job][:uuid] + pj[:script] = pj[:job][:script] || c[:script] + pj[:repository] = pj[:job][:script] || c[:repository] + pj[:script_parameters] = pj[:job][:script_parameters] || c[:script_parameters] + pj[:script_version] = pj[:job][:script_version] || c[:script_version] + pj[:nondeterministic] = pj[:job][:nondeterministic] || c[:nondeterministic] + pj[:output] = pj[:job][:output] + pj[:output_uuid] = c[:output_uuid] + pj[:finished_at] = pj[:job][:finished_at] + ret << pj + end + ret + end + + def pipeline_jobs_oldschool object + ret = [] + object.components[:steps].each_with_index do |step, i| + pj = {index: i, name: step[:name]} + if step[:complete] and step[:complete] != 0 + if step[:output_data_locator] + pj[:progress] = 1.0 + else + pj[:progress] = 0.0 + end + else + if step[:progress] and + (re = step[:progress].match /^(\d+)\+(\d+)\/(\d+)$/) + pj[:progress] = (((re[1].to_f + re[2].to_f/2) / re[3].to_f) rescue 0.5) + else + pj[:progress] = 0.0 + end + if step[:failed] + pj[:result] = 'failed' + pj[:failed] = true + end + end + if step[:warehousejob] + if step[:complete] + pj[:result] = 'complete' + pj[:complete] = true + pj[:progress] = 1.0 + elsif step[:warehousejob][:finishtime] + pj[:result] = 'failed' + pj[:failed] = true + elsif step[:warehousejob][:starttime] + pj[:result] = 'running' + else + pj[:result] = 'queued' + end + end + pj[:progress_detail] = (step[:progress] rescue nil) + pj[:job_id] = (step[:warehousejob][:id] rescue nil) + pj[:job_link] = pj[:job_id] + pj[:script] = step[:function] + pj[:script_version] = (step[:warehousejob][:revision] rescue nil) + pj[:output] = step[:output_data_locator] + pj[:finished_at] = (Time.parse(step[:warehousejob][:finishtime]) rescue nil) + ret << pj + end + ret + end + + MINUTE = 60 + HOUR = 60 * MINUTE + DAY = 24 * HOUR + + def render_runtime duration, use_words, round_to_min=true + days = 0 + hours = 0 + minutes = 0 + seconds = 0 + + if duration >= DAY + days = (duration / DAY).floor + duration -= days * DAY + end + + if duration >= HOUR + hours = (duration / HOUR).floor + duration -= hours * HOUR + end + + if duration >= MINUTE + minutes = (duration / MINUTE).floor + duration -= minutes * MINUTE + end + + seconds = duration.floor + + if round_to_min and seconds >= 30 + minutes += 1 + end + + if use_words + s = [] + if days > 0 then + s << "#{days} day#{'s' if days != 1}" + end + if hours > 0 then + s << "#{hours} hour#{'s' if hours != 1}" + end + if minutes > 0 then + s << "#{minutes} minute#{'s' if minutes != 1}" + end + if not round_to_min or s.size == 0 + s << "#{seconds} second#{'s' if seconds != 1}" + end + s = s * " " + else + s = "" + if days > 0 + s += "#{days}d " + end + + if (hours > 0) + s += "#{hours}h" + end + + s += "#{minutes}m" + + if not round_to_min + s += "#{seconds}s" + end + end + + raw(s) + end + +end diff --git a/apps/workbench/app/helpers/provenance_helper.rb b/apps/workbench/app/helpers/provenance_helper.rb new file mode 100644 index 0000000000..a4723a3ec1 --- /dev/null +++ b/apps/workbench/app/helpers/provenance_helper.rb @@ -0,0 +1,332 @@ +module ProvenanceHelper + + class GenerateGraph + def initialize(pdata, opts) + @pdata = pdata + @opts = opts + @visited = {} + @jobs = {} + @node_extra = {} + end + + def self.collection_uuid(uuid) + Keep::Locator.parse(uuid).andand.strip_hints.andand.to_s + end + + def url_for u + p = { :host => @opts[:request].host, + :port => @opts[:request].port, + :protocol => @opts[:request].protocol } + p.merge! u + Rails.application.routes.url_helpers.url_for (p) + end + + def determine_fillcolor(n) + fillcolor = %w(666666 669966 666699 666666 996666)[n || 0] || '666666' + "style=\"filled\",color=\"#ffffff\",fillcolor=\"##{fillcolor}\",fontcolor=\"#ffffff\"" + end + + def describe_node(uuid, describe_opts={}) + bgcolor = determine_fillcolor (describe_opts[:pip] || @opts[:pips].andand[uuid]) + + rsc = ArvadosBase::resource_class_for_uuid uuid + + if GenerateGraph::collection_uuid(uuid) || rsc == Collection + if Collection.is_empty_blob_locator? uuid.to_s + # special case + return "\"#{uuid}\" [label=\"(empty collection)\"];\n" + end + + href = url_for ({:controller => Collection.to_s.tableize, + :action => :show, + :id => uuid.to_s }) + + return "\"#{uuid}\" [label=\"#{encode_quotes(describe_opts[:label] || (@pdata[uuid] and @pdata[uuid][:name]) || uuid)}\",shape=box,href=\"#{href}\",#{bgcolor}];\n" + else + href = "" + if describe_opts[:href] + href = ",href=\"#{url_for ({:controller => describe_opts[:href][:controller], + :action => :show, + :id => describe_opts[:href][:id] })}\"" + end + return "\"#{uuid}\" [label=\"#{encode_quotes(describe_opts[:label] || uuid)}\",#{bgcolor},shape=#{describe_opts[:shape] || 'box'}#{href}];\n" + end + end + + def job_uuid(job) + d = Digest::MD5.hexdigest(job[:script_parameters].to_json) + if @opts[:combine_jobs] == :script_only + uuid = "#{job[:script]}_#{d}" + elsif @opts[:combine_jobs] == :script_and_version + uuid = "#{job[:script]}_#{job[:script_version]}_#{d}" + else + uuid = "#{job[:uuid]}" + end + + @jobs[uuid] = [] unless @jobs[uuid] + @jobs[uuid] << job unless @jobs[uuid].include? job + + uuid + end + + def edge(tail, head, extra) + if @opts[:direction] == :bottom_up + gr = "\"#{encode_quotes head}\" -> \"#{encode_quotes tail}\"" + else + gr = "\"#{encode_quotes tail}\" -> \"#{encode_quotes head}\"" + end + + if extra.length > 0 + gr += " [" + extra.each do |k, v| + gr += "#{k}=\"#{encode_quotes v}\"," + end + gr += "]" + end + gr += ";\n" + gr + end + + def script_param_edges(uuid, sp) + gr = "" + + sp.each do |k, v| + if @opts[:all_script_parameters] + if v.is_a? Array or v.is_a? Hash + encv = JSON.pretty_generate(v).gsub("\n", "\\l") + "\\l" + else + encv = v.to_json + end + gr += "\"#{encode_quotes encv}\" [shape=box];\n" + gr += edge(encv, uuid, {:label => k}) + end + end + gr + end + + def job_edges job, edge_opts={} + uuid = job_uuid(job) + gr = "" + + ProvenanceHelper::find_collections job[:script_parameters] do |collection_hash, collection_uuid, key| + if collection_uuid + gr += describe_node(collection_uuid) + gr += edge(collection_uuid, uuid, {:label => key}) + else + gr += describe_node(collection_hash) + gr += edge(collection_hash, uuid, {:label => key}) + end + end + + if job[:docker_image_locator] and !@opts[:no_docker] + gr += describe_node(job[:docker_image_locator], {label: (job[:runtime_constraints].andand[:docker_image] || job[:docker_image_locator])}) + gr += edge(job[:docker_image_locator], uuid, {label: "docker_image"}) + end + + if @opts[:script_version_nodes] + gr += describe_node(job[:script_version], {:label => "git:#{job[:script_version]}"}) + gr += edge(job[:script_version], uuid, {:label => "script_version"}) + end + + if job[:output] and !edge_opts[:no_output] + gr += describe_node(job[:output]) + gr += edge(uuid, job[:output], {label: "output" }) + end + + if job[:log] and !edge_opts[:no_log] + gr += describe_node(job[:log]) + gr += edge(uuid, job[:log], {label: "log"}) + end + + gr + end + + def generate_provenance_edges(uuid) + gr = "" + m = GenerateGraph::collection_uuid(uuid) + uuid = m if m + + if uuid.nil? or uuid.empty? or @visited[uuid] + return "" + end + + if @pdata[uuid].nil? + return "" + else + @visited[uuid] = true + end + + if uuid.start_with? "component_" + # Pipeline component inputs + job = @pdata[@pdata[uuid][:job].andand[:uuid]] + + if job + gr += describe_node(job_uuid(job), {label: uuid[38..-1], pip: @opts[:pips].andand[job[:uuid]], shape: "oval", + href: {controller: 'jobs', id: job[:uuid]}}) + gr += job_edges job, {no_output: true, no_log: true} + end + + # Pipeline component output + outuuid = @pdata[uuid][:output_uuid] + if outuuid + outcollection = @pdata[outuuid] + if outcollection + gr += edge(job_uuid(job), outcollection[:portable_data_hash], {label: "output"}) + gr += describe_node(outcollection[:portable_data_hash], {label: outcollection[:name]}) + end + elsif job and job[:output] + gr += describe_node(job[:output]) + gr += edge(job_uuid(job), job[:output], {label: "output" }) + end + else + rsc = ArvadosBase::resource_class_for_uuid uuid + + if rsc == Job + job = @pdata[uuid] + gr += job_edges job if job + end + end + + @pdata.each do |k, link| + if link[:head_uuid] == uuid.to_s and link[:link_class] == "provenance" + href = url_for ({:controller => Link.to_s.tableize, + :action => :show, + :id => link[:uuid] }) + + gr += describe_node(link[:tail_uuid]) + gr += edge(link[:head_uuid], link[:tail_uuid], {:label => link[:name], :href => href}) + gr += generate_provenance_edges(link[:tail_uuid]) + end + end + + gr + end + + def describe_jobs + gr = "" + @jobs.each do |k, v| + href = url_for ({:controller => Job.to_s.tableize, + :action => :index }) + + gr += "\"#{k}\" [href=\"#{href}?" + + n = 0 + v.each do |u| + gr += ";" unless gr.end_with? "?" + gr += "uuid%5b%5d=#{u[:uuid]}" + n |= @opts[:pips][u[:uuid]] if @opts[:pips] and @opts[:pips][u[:uuid]] + end + + gr += "\",label=\"" + + label = "#{v[0][:script]}" + + if label == "run-command" and v[0][:script_parameters][:command].is_a? Array + label = v[0][:script_parameters][:command].join(' ') + end + + if not @opts[:combine_jobs] + label += "\\n#{v[0][:finished_at]}" + end + + gr += encode_quotes label + + gr += "\",#{determine_fillcolor n}];\n" + end + gr + end + + def encode_quotes value + value.to_s.gsub("\"", "\\\"").gsub("\n", "\\n") + end + end + + def self.create_provenance_graph(pdata, svgId, opts={}) + if pdata.is_a? Array or pdata.is_a? ArvadosResourceList + p2 = {} + pdata.each do |k| + p2[k[:uuid]] = k if k[:uuid] + end + pdata = p2 + end + + unless pdata.is_a? Hash + raise "create_provenance_graph accepts Array or Hash for pdata only, pdata is #{pdata.class}" + end + + gr = """strict digraph { +node [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"]; +edge [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"]; +""" + + if opts[:direction] == :bottom_up + gr += "edge [dir=back];" + end + + begin + pdata = pdata.stringify_keys + + g = GenerateGraph.new(pdata, opts) + + pdata.each do |k, v| + if !opts[:only_components] or k.start_with? "component_" + gr += g.generate_provenance_edges(k) + else + #gr += describe_node(k) + end + end + + if !opts[:only_components] + gr += g.describe_jobs + end + + rescue => e + Rails.logger.warn "#{e.inspect}" + Rails.logger.warn "#{e.backtrace.join("\n\t")}" + raise + end + + gr += "}" + svg = "" + + require 'open3' + + Open3.popen2("dot", "-Tsvg") do |stdin, stdout, wait_thr| + stdin.print(gr) + stdin.close + svg = stdout.read() + wait_thr.value + stdout.close() + end + + svg = svg.sub(/<\?xml.*?\?>/m, "") + svg = svg.sub(//m, "") + svg = svg.sub(/ true) + errors = @api_response[:errors] + if errors.respond_to?(:join) + errors = errors.join("\n\n") + else + errors = errors.to_s + end + super(request_url, "#{errors} [API: #{@api_status}]") + end + end + + class AccessForbiddenException < ApiErrorResponseException; end + class NotFoundException < ApiErrorResponseException; end + class NotLoggedInException < ApiErrorResponseException; end + + ERROR_CODE_CLASSES = { + 401 => NotLoggedInException, + 403 => AccessForbiddenException, + 404 => NotFoundException, + } + + @@profiling_enabled = Rails.configuration.profiling_enabled + @@discovery = nil + + # An API client object suitable for handling API requests on behalf + # of the current thread. + def self.new_or_current + # If this thread doesn't have an API client yet, *or* this model + # has been reloaded since the existing client was created, create + # a new client. Otherwise, keep using the latest client created in + # the current thread. + unless Thread.current[:arvados_api_client].andand.class == self + Thread.current[:arvados_api_client] = new + end + Thread.current[:arvados_api_client] + end + + def initialize *args + @api_client = nil + @client_mtx = Mutex.new + end + + def api(resources_kind, action, data=nil, tokens={}) + + profile_checkpoint + + if not @api_client + @client_mtx.synchronize do + @api_client = HTTPClient.new + if Rails.configuration.arvados_insecure_https + @api_client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE + else + # Use system CA certificates + @api_client.ssl_config.add_trust_ca('/etc/ssl/certs') + end + end + end + + resources_kind = class_kind(resources_kind).pluralize if resources_kind.is_a? Class + url = "#{self.arvados_v1_base}/#{resources_kind}#{action}" + + # Clean up /arvados/v1/../../discovery/v1 to /discovery/v1 + url.sub! '/arvados/v1/../../', '/' + + query = { + 'api_token' => tokens[:arvados_api_token] || Thread.current[:arvados_api_token] || '', + 'reader_tokens' => (tokens[:reader_tokens] || Thread.current[:reader_tokens] || []).to_json, + } + if !data.nil? + data.each do |k,v| + if v.is_a? String or v.nil? + query[k] = v + elsif v == true + query[k] = 1 + elsif v == false + query[k] = 0 + else + query[k] = JSON.dump(v) + end + end + else + query["_method"] = "GET" + end + if @@profiling_enabled + query["_profile"] = "true" + end + + header = {"Accept" => "application/json"} + + profile_checkpoint { "Prepare request #{url} #{query[:uuid]} #{query[:where]} #{query[:filters]} #{query[:order]}" } + msg = @client_mtx.synchronize do + begin + @api_client.post(url, query, header: header) + rescue => exception + raise NoApiResponseException.new(url, exception) + end + end + profile_checkpoint 'API transaction' + + begin + resp = Oj.load(msg.content, :symbol_keys => true) + rescue Oj::ParseError + resp = nil + end + if not resp.is_a? Hash + raise InvalidApiResponseException.new(url, msg) + elsif msg.status_code != 200 + error_class = ERROR_CODE_CLASSES.fetch(msg.status_code, + ApiErrorResponseException) + raise error_class.new(url, msg) + end + + if resp[:_profile] + Rails.logger.info "API client: " \ + "#{resp.delete(:_profile)[:request_time]} request_time" + end + profile_checkpoint 'Parse response' + resp + end + + def self.patch_paging_vars(ary, items_available, offset, limit, links=nil) + if items_available + (class << ary; self; end).class_eval { attr_accessor :items_available } + ary.items_available = items_available + end + if offset + (class << ary; self; end).class_eval { attr_accessor :offset } + ary.offset = offset + end + if limit + (class << ary; self; end).class_eval { attr_accessor :limit } + ary.limit = limit + end + if links + (class << ary; self; end).class_eval { attr_accessor :links } + ary.links = links + end + ary + end + + def unpack_api_response(j, kind=nil) + if j.is_a? Hash and j[:items].is_a? Array and j[:kind].match(/(_list|List)$/) + ary = j[:items].collect { |x| unpack_api_response x, x[:kind] } + links = ArvadosResourceList.new Link + links.results = (j[:links] || []).collect do |x| + unpack_api_response x, x[:kind] + end + self.class.patch_paging_vars(ary, j[:items_available], j[:offset], j[:limit], links) + elsif j.is_a? Hash and (kind || j[:kind]) + oclass = self.kind_class(kind || j[:kind]) + if oclass + j.keys.each do |k| + childkind = j["#{k.to_s}_kind".to_sym] + if childkind + j[k] = self.unpack_api_response(j[k], childkind) + end + end + oclass.new.private_reload(j) + else + j + end + else + j + end + end + + def arvados_login_url(params={}) + if Rails.configuration.respond_to? :arvados_login_base + uri = Rails.configuration.arvados_login_base + else + uri = self.arvados_v1_base.sub(%r{/arvados/v\d+.*}, '/login') + end + if params.size > 0 + uri += '?' << params.collect { |k,v| + CGI.escape(k.to_s) + '=' + CGI.escape(v.to_s) + }.join('&') + end + uri + end + + def arvados_logout_url(params={}) + arvados_login_url(params).sub('/login','/logout') + end + + def arvados_v1_base + Rails.configuration.arvados_v1_base + end + + def discovery + @@discovery ||= api '../../discovery/v1/apis/arvados/v1/rest', '' + end + + def kind_class(kind) + kind.match(/^arvados\#(.+?)(_list|List)?$/)[1].pluralize.classify.constantize rescue nil + end + + def class_kind(resource_class) + resource_class.to_s.underscore + end + + def self.class_kind(resource_class) + resource_class.to_s.underscore + end + + protected + def profile_checkpoint label=nil + return if !@@profiling_enabled + label = yield if block_given? + t = Time.now + if label and @profile_t0 + Rails.logger.info "API client: #{t - @profile_t0} #{label}" + end + @profile_t0 = t + end +end diff --git a/apps/workbench/app/models/arvados_base.rb b/apps/workbench/app/models/arvados_base.rb new file mode 100644 index 0000000000..bc5a9a37dd --- /dev/null +++ b/apps/workbench/app/models/arvados_base.rb @@ -0,0 +1,443 @@ +class ArvadosBase < ActiveRecord::Base + self.abstract_class = true + attr_accessor :attribute_sortkey + attr_accessor :create_params + + def self.arvados_api_client + ArvadosApiClient.new_or_current + end + + def arvados_api_client + ArvadosApiClient.new_or_current + end + + def self.uuid_infix_object_kind + @@uuid_infix_object_kind ||= + begin + infix_kind = {} + arvados_api_client.discovery[:schemas].each do |name, schema| + if schema[:uuidPrefix] + infix_kind[schema[:uuidPrefix]] = + 'arvados#' + name.to_s.camelcase(:lower) + end + end + + # Recognize obsolete types. + infix_kind. + merge('mxsvm' => 'arvados#pipelineTemplate', # Pipeline + 'uo14g' => 'arvados#pipelineInstance', # PipelineInvocation + 'ldvyl' => 'arvados#group') # Project + end + end + + def initialize raw_params={}, create_params={} + super self.class.permit_attribute_params(raw_params) + @create_params = create_params + @attribute_sortkey ||= { + 'id' => nil, + 'name' => '000', + 'owner_uuid' => '002', + 'event_type' => '100', + 'link_class' => '100', + 'group_class' => '100', + 'tail_uuid' => '101', + 'head_uuid' => '102', + 'object_uuid' => '102', + 'summary' => '104', + 'description' => '104', + 'properties' => '150', + 'info' => '150', + 'created_at' => '200', + 'modified_at' => '201', + 'modified_by_user_uuid' => '202', + 'modified_by_client_uuid' => '203', + 'uuid' => '999', + } + end + + def self.columns + return @columns if @columns.andand.any? + @columns = [] + @attribute_info ||= {} + schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym] + return @columns if schema.nil? + schema[:properties].each do |k, coldef| + case k + when :etag, :kind + attr_reader k + else + if coldef[:type] == coldef[:type].downcase + # boolean, integer, etc. + @columns << column(k, coldef[:type].to_sym) + else + # Hash, Array + @columns << column(k, :text) + serialize k, coldef[:type].constantize + end + @attribute_info[k] = coldef + end + end + @columns + end + + def self.column(name, sql_type = nil, default = nil, null = true) + ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) + end + + def self.attribute_info + self.columns + @attribute_info + end + + def self.find(uuid, opts={}) + if uuid.class != String or uuid.length < 27 then + raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx' + end + + if self == ArvadosBase + # Determine type from uuid and defer to the appropriate subclass. + return resource_class_for_uuid(uuid).find(uuid, opts) + end + + # Only do one lookup on the API side per {class, uuid, workbench + # request} unless {cache: false} is given via opts. + cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}" + if opts[:cache] == false + Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid) + end + hash = Rails.cache.fetch cache_key do + arvados_api_client.api(self, '/' + uuid) + end + new.private_reload(hash) + end + + def self.find?(*args) + find(*args) rescue nil + end + + def self.order(*args) + ArvadosResourceList.new(self).order(*args) + end + + def self.filter(*args) + ArvadosResourceList.new(self).filter(*args) + end + + def self.where(*args) + ArvadosResourceList.new(self).where(*args) + end + + def self.limit(*args) + ArvadosResourceList.new(self).limit(*args) + end + + def self.select(*args) + ArvadosResourceList.new(self).select(*args) + end + + def self.eager(*args) + ArvadosResourceList.new(self).eager(*args) + end + + def self.all + ArvadosResourceList.new(self) + end + + def self.permit_attribute_params raw_params + # strong_parameters does not provide security in Workbench: anyone + # who can get this far can just as well do a call directly to our + # database (Arvados) with the same credentials we use. + # + # The following permit! is necessary even with + # "ActionController::Parameters.permit_all_parameters = true", + # because permit_all does not permit nested attributes. + ActionController::Parameters.new(raw_params).permit! + end + + def self.create raw_params={}, create_params={} + x = super(permit_attribute_params(raw_params)) + x.create_params = create_params + x + end + + def update_attributes raw_params={} + super(self.class.permit_attribute_params(raw_params)) + end + + def save + obdata = {} + self.class.columns.each do |col| + unless self.send(col.name.to_sym).nil? and !self.changed.include?(col.name) + obdata[col.name.to_sym] = self.send(col.name.to_sym) + end + end + obdata.delete :id + postdata = { self.class.to_s.underscore => obdata } + if etag + postdata['_method'] = 'PUT' + obdata.delete :uuid + resp = arvados_api_client.api(self.class, '/' + uuid, postdata) + else + postdata.merge!(@create_params) if @create_params + resp = arvados_api_client.api(self.class, '', postdata) + end + return false if !resp[:etag] || !resp[:uuid] + + # set read-only non-database attributes + @etag = resp[:etag] + @kind = resp[:kind] + + # attributes can be modified during "save" -- we should update our copies + resp.keys.each do |attr| + if self.respond_to? "#{attr}=".to_sym + self.send(attr.to_s + '=', resp[attr.to_sym]) + end + end + + @new_record = false + + self + end + + def save! + self.save or raise Exception.new("Save failed") + end + + def destroy + if etag || uuid + postdata = { '_method' => 'DELETE' } + resp = arvados_api_client.api(self.class, '/' + uuid, postdata) + resp[:etag] && resp[:uuid] && resp + else + true + end + end + + def links(*args) + o = {} + o.merge!(args.pop) if args[-1].is_a? Hash + o[:link_class] ||= args.shift + o[:name] ||= args.shift + o[:tail_uuid] = self.uuid + if all_links + return all_links.select do |m| + ok = true + o.each do |k,v| + if !v.nil? + test_v = m.send(k) + if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s) + ok = false + end + end + end + ok + end + end + @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true } + @links = arvados_api_client.unpack_api_response(@links) + end + + def all_links + return @all_links if @all_links + res = arvados_api_client.api Link, '', { + _method: 'GET', + where: { + tail_kind: self.kind, + tail_uuid: self.uuid + }, + eager: true + } + @all_links = arvados_api_client.unpack_api_response(res) + end + + def reload + private_reload(self.uuid) + end + + def private_reload(uuid_or_hash) + raise "No such object" if !uuid_or_hash + if uuid_or_hash.is_a? Hash + hash = uuid_or_hash + else + hash = arvados_api_client.api(self.class, '/' + uuid_or_hash) + end + hash.each do |k,v| + if self.respond_to?(k.to_s + '=') + self.send(k.to_s + '=', v) + else + # When ArvadosApiClient#schema starts telling us what to expect + # in API responses (not just the server side database + # columns), this sort of awfulness can be avoided: + self.instance_variable_set('@' + k.to_s, v) + if !self.respond_to? k + singleton = class << self; self end + singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) } + end + end + end + @all_links = nil + @new_record = false + self + end + + def to_param + uuid + end + + def initialize_copy orig + super + forget_uuid! + end + + def attributes_for_display + self.attributes.reject { |k,v| + attribute_sortkey.has_key?(k) and !attribute_sortkey[k] + }.sort_by { |k,v| + attribute_sortkey[k] or k + } + end + + def class_for_display + self.class.to_s.underscore.humanize + end + + def self.class_for_display + self.to_s.underscore.humanize + end + + # Array of strings that are names of attributes that should be rendered as textile. + def textile_attributes + [] + end + + def self.creatable? + current_user + end + + def self.goes_in_projects? + false + end + + # can this class of object be copied into a project? + # override to false on indivudal model classes for which this should not be true + def self.copies_to_projects? + self.goes_in_projects? + end + + def editable? + (current_user and current_user.is_active and + (current_user.is_admin or + current_user.uuid == self.owner_uuid or + new_record? or + (respond_to?(:writable_by) ? + writable_by.include?(current_user.uuid) : + (ArvadosBase.find(owner_uuid).writable_by.include? current_user.uuid rescue false)))) or false + end + + # Array of strings that are the names of attributes that can be edited + # with X-Editable. + def editable_attributes + self.class.columns.map(&:name) - + %w(created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at) + end + + def attribute_editable?(attr, ever=nil) + if not editable_attributes.include?(attr.to_s) + false + elsif not (current_user.andand.is_active) + false + elsif attr == 'uuid' + current_user.is_admin + elsif ever + true + else + editable? + end + end + + def self.resource_class_for_uuid(uuid, opts={}) + if uuid.is_a? ArvadosBase + return uuid.class + end + unless uuid.is_a? String + return nil + end + if opts[:class].is_a? Class + return opts[:class] + end + if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/ + return Collection + end + resource_class = nil + uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re| + resource_class ||= arvados_api_client. + kind_class(self.uuid_infix_object_kind[re[1]]) + end + if opts[:referring_object] and + opts[:referring_attr] and + opts[:referring_attr].match /_uuid$/ + resource_class ||= arvados_api_client. + kind_class(opts[:referring_object]. + attributes[opts[:referring_attr]. + sub(/_uuid$/, '_kind')]) + end + resource_class + end + + def resource_param_name + self.class.to_s.underscore + end + + def friendly_link_name lookup=nil + (name if self.respond_to? :name) || default_name + end + + def content_summary + self.class_for_display + end + + def selection_label + friendly_link_name + end + + def self.default_name + self.to_s.underscore.humanize + end + + def controller + (self.class.to_s.pluralize + 'Controller').constantize + end + + def controller_name + self.class.to_s.tableize + end + + # Placeholder for name when name is missing or empty + def default_name + if self.respond_to? :name + "New #{class_for_display.downcase}" + else + uuid + end + end + + def owner + ArvadosBase.find(owner_uuid) rescue nil + end + + protected + + def forget_uuid! + self.uuid = nil + @etag = nil + self + end + + def self.current_user + Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token] + Thread.current[:user] + end + def current_user + self.class.current_user + end +end diff --git a/apps/workbench/app/models/arvados_resource_list.rb b/apps/workbench/app/models/arvados_resource_list.rb new file mode 100644 index 0000000000..d989715080 --- /dev/null +++ b/apps/workbench/app/models/arvados_resource_list.rb @@ -0,0 +1,218 @@ +class ArvadosResourceList + include ArvadosApiClientHelper + include Enumerable + + attr_reader :resource_class + + def initialize resource_class=nil + @resource_class = resource_class + @fetch_multiple_pages = true + @arvados_api_token = Thread.current[:arvados_api_token] + @reader_tokens = Thread.current[:reader_tokens] + end + + def eager(bool=true) + @eager = bool + self + end + + def limit(max_results) + if not max_results.nil? and not max_results.is_a? Integer + raise ArgumentError("argument to limit() must be an Integer or nil") + end + @limit = max_results + self + end + + def offset(skip) + @offset = skip + self + end + + def order(orderby_spec) + @orderby_spec = orderby_spec + self + end + + def select(columns=nil) + # If no column arguments were given, invoke Enumerable#select. + if columns.nil? + super() + else + @select ||= [] + @select += columns + self + end + end + + def filter _filters + @filters ||= [] + @filters += _filters + self + end + + def where(cond) + @cond = cond.dup + @cond.keys.each do |uuid_key| + if @cond[uuid_key] and (@cond[uuid_key].is_a? Array or + @cond[uuid_key].is_a? ArvadosBase) + # Coerce cond[uuid_key] to an array of uuid strings. This + # allows caller the convenience of passing an array of real + # objects and uuids in cond[uuid_key]. + if !@cond[uuid_key].is_a? Array + @cond[uuid_key] = [@cond[uuid_key]] + end + @cond[uuid_key] = @cond[uuid_key].collect do |item| + if item.is_a? ArvadosBase + item.uuid + else + item + end + end + end + end + @cond.keys.select { |x| x.match /_kind$/ }.each do |kind_key| + if @cond[kind_key].is_a? Class + @cond = @cond.merge({ kind_key => 'arvados#' + arvados_api_client.class_kind(@cond[kind_key]) }) + end + end + self + end + + def fetch_multiple_pages(f) + @fetch_multiple_pages = f + self + end + + def results + if !@results + @results = [] + self.each_page do |r| + @results.concat r + end + end + @results + end + + def results=(r) + @results = r + @items_available = r.items_available if r.respond_to? :items_available + @result_limit = r.limit if r.respond_to? :limit + @result_offset = r.offset if r.respond_to? :offset + @results + end + + def to_ary + results + end + + def each(&block) + if not @results.nil? + @results.each &block + else + self.each_page do |items| + items.each do |i| + block.call i + end + end + end + self + end + + def first + results.first + end + + def last + results.last + end + + def [](*x) + results.send('[]', *x) + end + + def |(x) + if x.is_a? Hash + self.to_hash | x + else + results | x.to_ary + end + end + + def to_hash + Hash[self.collect { |x| [x.uuid, x] }] + end + + def empty? + self.first.nil? + end + + def items_available + results + @items_available + end + + def result_limit + results + @result_limit + end + + def result_offset + results + @result_offset + end + + # Obsolete method retained during api transition. + def links_for item_or_uuid, link_class=false + [] + end + + protected + + def each_page + api_params = { + _method: 'GET' + } + api_params[:where] = @cond if @cond + api_params[:eager] = '1' if @eager + api_params[:select] = @select if @select + api_params[:order] = @orderby_spec if @orderby_spec + api_params[:filters] = @filters if @filters + + + item_count = 0 + offset = @offset || 0 + @result_limit = nil + @result_offset = nil + + begin + api_params[:offset] = offset + api_params[:limit] = (@limit - item_count) if @limit + + res = arvados_api_client.api(@resource_class, '', api_params, + arvados_api_token: @arvados_api_token, + reader_tokens: @reader_tokens) + items = arvados_api_client.unpack_api_response res + + @items_available = items.items_available if items.respond_to?(:items_available) + @result_limit = items.limit if (@fetch_multiple_pages == false) and items.respond_to?(:limit) + @result_offset = items.offset if (@fetch_multiple_pages == false) and items.respond_to?(:offset) + + break if items.nil? or not items.any? + + item_count += items.size + if items.respond_to?(:offset) + offset = items.offset + items.size + else + offset = item_count + end + + yield items + + break if @limit and item_count >= @limit + break if items.respond_to? :items_available and offset >= items.items_available + end while @fetch_multiple_pages + self + end + +end diff --git a/apps/workbench/app/models/authorized_key.rb b/apps/workbench/app/models/authorized_key.rb new file mode 100644 index 0000000000..2d804e1a53 --- /dev/null +++ b/apps/workbench/app/models/authorized_key.rb @@ -0,0 +1,9 @@ +class AuthorizedKey < ArvadosBase + def attribute_editable?(attr, ever=nil) + if (attr.to_s == 'authorized_user_uuid') and (not ever) + current_user.andand.is_admin + else + super + end + end +end diff --git a/apps/workbench/app/models/collection.rb b/apps/workbench/app/models/collection.rb new file mode 100644 index 0000000000..686b816c08 --- /dev/null +++ b/apps/workbench/app/models/collection.rb @@ -0,0 +1,101 @@ +require "arvados/keep" + +class Collection < ArvadosBase + MD5_EMPTY = 'd41d8cd98f00b204e9800998ecf8427e' + + def default_name + if Collection.is_empty_blob_locator? self.uuid + "Empty Collection" + else + super + end + end + + # Return true if the given string is the locator of a zero-length blob + def self.is_empty_blob_locator? locator + !!locator.to_s.match("^#{MD5_EMPTY}(\\+.*)?\$") + end + + def self.goes_in_projects? + true + end + + def manifest + if @manifest.nil? or manifest_text_changed? + @manifest = Keep::Manifest.new(manifest_text || "") + end + @manifest + end + + def files + # This method provides backwards compatibility for code that relied on + # the old files field in API results. New code should use manifest + # methods directly. + manifest.files + end + + def content_summary + ApplicationController.helpers.human_readable_bytes_html(total_bytes) + " " + super + end + + def total_bytes + manifest.files.inject(0) { |sum, filespec| sum + filespec.last } + end + + def files_tree + tree = manifest.files.group_by do |file_spec| + File.split(file_spec.first) + end + return [] if tree.empty? + # Fill in entries for empty directories. + tree.keys.map { |basedir, _| File.split(basedir) }.each do |splitdir| + until tree.include?(splitdir) + tree[splitdir] = [] + splitdir = File.split(splitdir.first) + end + end + dir_to_tree = lambda do |dirname| + # First list subdirectories, with their files inside. + subnodes = tree.keys.select { |bd, td| (bd == dirname) and (td != '.') } + .sort.flat_map do |parts| + [parts + [nil]] + dir_to_tree.call(File.join(parts)) + end + # Then extend that list with files in this directory. + subnodes + tree[File.split(dirname)] + end + dir_to_tree.call('.') + end + + def editable_attributes + %w(name description manifest_text) + end + + def self.creatable? + false + end + + def provenance + arvados_api_client.api "collections/#{self.uuid}/", "provenance" + end + + def used_by + arvados_api_client.api "collections/#{self.uuid}/", "used_by" + end + + def uuid + if self[:uuid].nil? + return self[:portable_data_hash] + else + super + end + end + + def friendly_link_name lookup=nil + name || portable_data_hash + end + + def textile_attributes + [ 'description' ] + end + +end diff --git a/apps/workbench/app/models/group.rb b/apps/workbench/app/models/group.rb new file mode 100644 index 0000000000..3f5da155c4 --- /dev/null +++ b/apps/workbench/app/models/group.rb @@ -0,0 +1,35 @@ +class Group < ArvadosBase + def self.goes_in_projects? + true + end + + def self.copies_to_projects? + false + end + + def self.contents params={} + res = arvados_api_client.api self, "/contents", { + _method: 'GET' + }.merge(params) + ret = ArvadosResourceList.new + ret.results = arvados_api_client.unpack_api_response(res) + ret + end + + def contents params={} + res = arvados_api_client.api self.class, "/#{self.uuid}/contents", { + _method: 'GET' + }.merge(params) + ret = ArvadosResourceList.new + ret.results = arvados_api_client.unpack_api_response(res) + ret + end + + def class_for_display + group_class == 'project' ? 'Project' : super + end + + def textile_attributes + [ 'description' ] + end +end diff --git a/apps/workbench/app/models/human.rb b/apps/workbench/app/models/human.rb new file mode 100644 index 0000000000..7c2d3e4396 --- /dev/null +++ b/apps/workbench/app/models/human.rb @@ -0,0 +1,5 @@ +class Human < ArvadosBase + def self.goes_in_projects? + true + end +end diff --git a/apps/workbench/app/models/job.rb b/apps/workbench/app/models/job.rb new file mode 100644 index 0000000000..c59bb89fe8 --- /dev/null +++ b/apps/workbench/app/models/job.rb @@ -0,0 +1,48 @@ +class Job < ArvadosBase + def self.goes_in_projects? + true + end + + def content_summary + "#{script} job" + end + + def editable_attributes + %w(description) + end + + def self.creatable? + false + end + + def default_name + if script + x = "\"#{script}\" job" + else + x = super + end + if finished_at + x += " finished #{finished_at.strftime('%b %-d')}" + elsif started_at + x += " started #{started_at.strftime('%b %-d')}" + elsif created_at + x += " submitted #{created_at.strftime('%b %-d')}" + end + end + + def cancel + arvados_api_client.api "jobs/#{self.uuid}/", "cancel", {} + end + + def self.queue_size + arvados_api_client.api("jobs/", "queue_size", {"_method"=> "GET"})[:queue_size] rescue 0 + end + + def self.queue + arvados_api_client.unpack_api_response arvados_api_client.api("jobs/", "queue", {"_method"=> "GET"}) + end + + def textile_attributes + [ 'description' ] + end +end diff --git a/apps/workbench/app/models/job_task.rb b/apps/workbench/app/models/job_task.rb new file mode 100644 index 0000000000..15fc7fdae3 --- /dev/null +++ b/apps/workbench/app/models/job_task.rb @@ -0,0 +1,2 @@ +class JobTask < ArvadosBase +end diff --git a/apps/workbench/app/models/keep_disk.rb b/apps/workbench/app/models/keep_disk.rb new file mode 100644 index 0000000000..8ced4eb5f3 --- /dev/null +++ b/apps/workbench/app/models/keep_disk.rb @@ -0,0 +1,5 @@ +class KeepDisk < ArvadosBase + def self.creatable? + current_user and current_user.is_admin + end +end diff --git a/apps/workbench/app/models/keep_service.rb b/apps/workbench/app/models/keep_service.rb new file mode 100644 index 0000000000..f27e369b86 --- /dev/null +++ b/apps/workbench/app/models/keep_service.rb @@ -0,0 +1,5 @@ +class KeepService < ArvadosBase + def self.creatable? + current_user and current_user.is_admin + end +end diff --git a/apps/workbench/app/models/link.rb b/apps/workbench/app/models/link.rb new file mode 100644 index 0000000000..271fa0f010 --- /dev/null +++ b/apps/workbench/app/models/link.rb @@ -0,0 +1,21 @@ +class Link < ArvadosBase + attr_accessor :head + attr_accessor :tail + def self.by_tail(t, opts={}) + where(opts.merge :tail_uuid => t.uuid) + end + + def default_name + self.class.resource_class_for_uuid(head_uuid).default_name rescue super + end + + def self.permissions_for(thing) + if thing.respond_to? :uuid + uuid = thing.uuid + else + uuid = thing + end + result = arvados_api_client.api("permissions", "/#{uuid}") + arvados_api_client.unpack_api_response(result) + end +end diff --git a/apps/workbench/app/models/log.rb b/apps/workbench/app/models/log.rb new file mode 100644 index 0000000000..39d585bf90 --- /dev/null +++ b/apps/workbench/app/models/log.rb @@ -0,0 +1,8 @@ +class Log < ArvadosBase + attr_accessor :object + def self.creatable? + # Technically yes, but not worth offering: it will be empty, and + # you won't be able to edit it. + false + end +end diff --git a/apps/workbench/app/models/node.rb b/apps/workbench/app/models/node.rb new file mode 100644 index 0000000000..e66be83078 --- /dev/null +++ b/apps/workbench/app/models/node.rb @@ -0,0 +1,8 @@ +class Node < ArvadosBase + def self.creatable? + current_user and current_user.is_admin + end + def friendly_link_name lookup=nil + (hostname && !hostname.empty?) ? hostname : uuid + end +end diff --git a/apps/workbench/app/models/pipeline_instance.rb b/apps/workbench/app/models/pipeline_instance.rb new file mode 100644 index 0000000000..f575e20d4e --- /dev/null +++ b/apps/workbench/app/models/pipeline_instance.rb @@ -0,0 +1,84 @@ +class PipelineInstance < ArvadosBase + attr_accessor :pipeline_template + + def self.goes_in_projects? + true + end + + def friendly_link_name lookup=nil + pipeline_name = self.name + if pipeline_name.nil? or pipeline_name.empty? + template = if lookup and lookup[self.pipeline_template_uuid] + lookup[self.pipeline_template_uuid] + else + PipelineTemplate.where(uuid: self.pipeline_template_uuid).first + end + if template + template.name + else + self.uuid + end + else + pipeline_name + end + end + + def content_summary + begin + PipelineTemplate.find(pipeline_template_uuid).name + rescue + super + end + end + + def update_job_parameters(new_params) + self.components[:steps].each_with_index do |step, i| + step[:params].each do |param| + if new_params.has_key?(new_param_name = "#{i}/#{param[:name]}") or + new_params.has_key?(new_param_name = "#{step[:name]}/#{param[:name]}") or + new_params.has_key?(new_param_name = param[:name]) + param_type = :value + %w(hash data_locator).collect(&:to_sym).each do |ptype| + param_type = ptype if param.has_key? ptype + end + param[param_type] = new_params[new_param_name] + end + end + end + end + + def editable_attributes + %w(name description components) + end + + def attribute_editable?(name, ever=nil) + if name.to_s == "components" + (ever or %w(New Ready).include?(state)) and super + else + super + end + end + + def attributes_for_display + super.reject { |k,v| k == 'components' } + end + + def self.creatable? + false + end + + def component_input_title(component_name, input_name) + component = components[component_name] + return nil if component.nil? + param_info = component[:script_parameters].andand[input_name.to_sym] + if param_info.is_a?(Hash) and param_info[:title] + param_info[:title] + else + "\"#{input_name.to_s}\" parameter for #{component[:script]} script in #{component_name} component" + end + end + + def textile_attributes + [ 'description' ] + end +end diff --git a/apps/workbench/app/models/pipeline_template.rb b/apps/workbench/app/models/pipeline_template.rb new file mode 100644 index 0000000000..6e79775397 --- /dev/null +++ b/apps/workbench/app/models/pipeline_template.rb @@ -0,0 +1,13 @@ +class PipelineTemplate < ArvadosBase + def self.goes_in_projects? + true + end + + def self.creatable? + false + end + + def textile_attributes + [ 'description' ] + end +end diff --git a/apps/workbench/app/models/repository.rb b/apps/workbench/app/models/repository.rb new file mode 100644 index 0000000000..bed7edc6e7 --- /dev/null +++ b/apps/workbench/app/models/repository.rb @@ -0,0 +1,8 @@ +class Repository < ArvadosBase + def self.creatable? + current_user and current_user.is_admin + end + def attributes_for_display + super.reject { |x| x[0] == 'fetch_url' } + end +end diff --git a/apps/workbench/app/models/specimen.rb b/apps/workbench/app/models/specimen.rb new file mode 100644 index 0000000000..7c611e47ff --- /dev/null +++ b/apps/workbench/app/models/specimen.rb @@ -0,0 +1,5 @@ +class Specimen < ArvadosBase + def self.goes_in_projects? + true + end +end diff --git a/apps/workbench/app/models/trait.rb b/apps/workbench/app/models/trait.rb new file mode 100644 index 0000000000..e7a6ceb70a --- /dev/null +++ b/apps/workbench/app/models/trait.rb @@ -0,0 +1,5 @@ +class Trait < ArvadosBase + def self.goes_in_projects? + true + end +end diff --git a/apps/workbench/app/models/user.rb b/apps/workbench/app/models/user.rb new file mode 100644 index 0000000000..7aaa4fe939 --- /dev/null +++ b/apps/workbench/app/models/user.rb @@ -0,0 +1,63 @@ +class User < ArvadosBase + def initialize(*args) + super(*args) + @attribute_sortkey['first_name'] = '050' + @attribute_sortkey['last_name'] = '051' + end + + def self.current + res = arvados_api_client.api self, '/current' + arvados_api_client.unpack_api_response(res) + end + + def self.system + @@arvados_system_user ||= begin + res = arvados_api_client.api self, '/system' + arvados_api_client.unpack_api_response(res) + end + end + + def full_name + (self.first_name || "") + " " + (self.last_name || "") + end + + def activate + self.private_reload(arvados_api_client.api(self.class, + "/#{self.uuid}/activate", + {})) + end + + def contents params={} + Group.contents params.merge(uuid: self.uuid) + end + + def attributes_for_display + super.reject { |k,v| %w(owner_uuid default_owner_uuid identity_url prefs).index k } + end + + def attribute_editable?(attr, ever=nil) + (ever or not (self.uuid.andand.match(/000000000000000$/) and + self.is_admin)) and super + end + + def friendly_link_name lookup=nil + [self.first_name, self.last_name].compact.join ' ' + end + + def unsetup + self.private_reload(arvados_api_client.api(self.class, + "/#{self.uuid}/unsetup", + {})) + end + + def self.setup params + arvados_api_client.api(self, "/setup", params) + end + + def update_profile params + self.private_reload(arvados_api_client.api(self.class, + "/#{self.uuid}/profile", + params)) + end + +end diff --git a/apps/workbench/app/models/user_agreement.rb b/apps/workbench/app/models/user_agreement.rb new file mode 100644 index 0000000000..d77038cdd5 --- /dev/null +++ b/apps/workbench/app/models/user_agreement.rb @@ -0,0 +1,10 @@ +class UserAgreement < ArvadosBase + def self.signatures + res = arvados_api_client.api self, '/signatures' + arvados_api_client.unpack_api_response(res) + end + def self.sign(params) + res = arvados_api_client.api self, '/sign', params + arvados_api_client.unpack_api_response(res) + end +end diff --git a/apps/workbench/app/models/virtual_machine.rb b/apps/workbench/app/models/virtual_machine.rb new file mode 100644 index 0000000000..3b44397df5 --- /dev/null +++ b/apps/workbench/app/models/virtual_machine.rb @@ -0,0 +1,21 @@ +class VirtualMachine < ArvadosBase + attr_accessor :current_user_logins + def self.creatable? + current_user.andand.is_admin + end + def attributes_for_display + super.append ['current_user_logins', @current_user_logins] + end + def editable_attributes + super - %w(current_user_logins) + end + def self.attribute_info + merger = ->(k,a,b) { a.merge(b, &merger) } + merger [nil, + {current_user_logins: {column_heading: "logins", type: 'array'}}, + super] + end + def friendly_link_name lookup=nil + (hostname && !hostname.empty?) ? hostname : uuid + end +end diff --git a/apps/workbench/app/views/api_client_authorizations/_show_help.html.erb b/apps/workbench/app/views/api_client_authorizations/_show_help.html.erb new file mode 100644 index 0000000000..1481721535 --- /dev/null +++ b/apps/workbench/app/views/api_client_authorizations/_show_help.html.erb @@ -0,0 +1,14 @@ +
    +### Pasting the following lines at a shell prompt will allow Arvados SDKs
    +### to authenticate to your account, <%= current_user.email %>
    +
    +read ARVADOS_API_TOKEN <<EOF
    +<%= Thread.current[:arvados_api_token] %>
    +EOF
    +export ARVADOS_API_TOKEN ARVADOS_API_HOST=<%= current_api_host %>
    +<% if Rails.configuration.arvados_insecure_https %>
    +export ARVADOS_API_HOST_INSECURE=true
    +<% else %>
    +unset ARVADOS_API_HOST_INSECURE
    +<% end %>
    +
    diff --git a/apps/workbench/app/views/application/404.html.erb b/apps/workbench/app/views/application/404.html.erb new file mode 100644 index 0000000000..8a0482274a --- /dev/null +++ b/apps/workbench/app/views/application/404.html.erb @@ -0,0 +1,26 @@ +<% + if (controller.andand.action_name == 'show') and params[:uuid] + class_name = controller.model_class.to_s.underscore + class_name_h = class_name.humanize(capitalize: false) + req_item = safe_join([class_name_h, " with UUID ", + raw(""), params[:uuid], raw("")], "") + req_item_plain_text = safe_join([class_name_h, " with UUID ", params[:uuid]]) + else + req_item = "page you requested" + req_item_plain_text = "page you requested" + end +%> + +

    Not Found

    + +

    The <%= req_item %> was not found. + +<% if class_name %> +Perhaps you'd like to +<%= link_to("browse all #{class_name_h.pluralize}", action: :index, controller: class_name.tableize) %>? +<% end %> + +

    + +<% error_message = "The #{req_item_plain_text} was not found." %> +<%= render :partial => "report_error", :locals => {error_message: error_message, error_type: '404'} %> diff --git a/apps/workbench/app/views/application/404.json.erb b/apps/workbench/app/views/application/404.json.erb new file mode 100644 index 0000000000..8371ff9c0e --- /dev/null +++ b/apps/workbench/app/views/application/404.json.erb @@ -0,0 +1 @@ +{"errors":<%= raw @errors.to_json %>} \ No newline at end of file diff --git a/apps/workbench/app/views/application/_arvados_attr_value.html.erb b/apps/workbench/app/views/application/_arvados_attr_value.html.erb new file mode 100644 index 0000000000..3df892fd5a --- /dev/null +++ b/apps/workbench/app/views/application/_arvados_attr_value.html.erb @@ -0,0 +1,22 @@ +<% if attrvalue.is_a? Array and attrvalue.collect(&:class).uniq.compact == [String] %> + <% attrvalue.each do |message| %> + <%= message %>
    + <% end %> +<% else %> + <% if attr and obj.attribute_editable?(attr) and (!defined?(editable) || editable) %> + <% if resource_class_for_uuid(attrvalue, {referring_object: obj, referring_attr: attr}) %> + <%= link_to_if_arvados_object attrvalue, {referring_attr: attr, referring_object: obj, with_class_name: true, friendly_name: true} %> +
    + <% end %> + <%= render_editable_attribute obj, attr %> + <% elsif attr == 'uuid' %> + <%= link_to_if_arvados_object attrvalue, {referring_attr: attr, referring_object: obj, with_class_name: false, friendly_name: false} %> + <% else %> + <%= link_to_if_arvados_object attrvalue, {referring_attr: attr, referring_object: obj, with_class_name: true, friendly_name: true, thumbnail: true} %> + <% end %> + +<% end %> diff --git a/apps/workbench/app/views/application/_arvados_object.html.erb b/apps/workbench/app/views/application/_arvados_object.html.erb new file mode 100644 index 0000000000..b4bf70dd23 --- /dev/null +++ b/apps/workbench/app/views/application/_arvados_object.html.erb @@ -0,0 +1,36 @@ +<% content_for :arvados_object_table do %> + +<% end %> + +<% if content_for? :page_content %> +<%= yield :page_content %> +<% else %> +<%= yield :arvados_object_table %> +<% end %> + +
    + + +
    + <% if content_for? :page_content %> +
    + <%= yield :arvados_object_table %> +
    + <% end %> +
    + +
    + + +
    +
    diff --git a/apps/workbench/app/views/application/_arvados_object_attr.html.erb b/apps/workbench/app/views/application/_arvados_object_attr.html.erb new file mode 100644 index 0000000000..b06dd8c756 --- /dev/null +++ b/apps/workbench/app/views/application/_arvados_object_attr.html.erb @@ -0,0 +1,17 @@ +<% object ||= @object %> +<% if attrvalue.is_a? Hash then attrvalue.each do |infokey, infocontent| %> + + <%= attr %>[<%= infokey %>] + + <%= render partial: 'application/arvados_attr_value', locals: { obj: object, attr: nil, attrvalue: infocontent } %> + + +<% end %> +<% elsif attrvalue.is_a? String or attrvalue.respond_to? :to_s %> + + <%= attr %> + + <%= render partial: 'application/arvados_attr_value', locals: { obj: object, attr: attr, attrvalue: attrvalue } %> + + +<% end %> diff --git a/apps/workbench/app/views/application/_breadcrumb_page_name.html.erb b/apps/workbench/app/views/application/_breadcrumb_page_name.html.erb new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/apps/workbench/app/views/application/_breadcrumb_page_name.html.erb @@ -0,0 +1 @@ + diff --git a/apps/workbench/app/views/application/_breadcrumbs.html.erb b/apps/workbench/app/views/application/_breadcrumbs.html.erb new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apps/workbench/app/views/application/_choose.html.erb b/apps/workbench/app/views/application/_choose.html.erb new file mode 100644 index 0000000000..4e1503bde5 --- /dev/null +++ b/apps/workbench/app/views/application/_choose.html.erb @@ -0,0 +1,86 @@ +