diff --git a/client/LICENSE.en.txt b/client/LICENSE.en.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/client/LICENSE.en.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/client/README.es.txt b/client/README.es.txt new file mode 100644 index 0000000..374bf3c --- /dev/null +++ b/client/README.es.txt @@ -0,0 +1,23 @@ +OpenGnsys Client README +======================== + +Este directorio contiene la estructura principal de datos que será +importada por los clientes OpenGnsys mediante Samba. + +Los subdirectorios se copian íntegramente al servidor bajo +/opt/opengnsys/client y serán importados por los clientes en +/opt/opengnsys. + +La estructura de datos es la siguiente: + +- bin scripts o binarios ejecutables por el cliente (compilados estáticamente). +- etc ficheros de configuración del cliente. +- interfaceAdm interface con el agente +- lib librerías de funciones. + - engine/bin ficheros con las funciones del motor de clonación. + - httpd ficheros de configuración del servicio lighttpd. + - modules módulos extra para el Kernel del cliente. + - qtlib librerías Qt complementarias del Browser. + - qtplugins plugins Qt para el Browser. +- scripts funciones de alto nivel ejecutables por OpenGnsys Browser + y OpenGnsys Admin. diff --git a/client/bin/EACInterfaces b/client/bin/EACInterfaces new file mode 100755 index 0000000..b63b1db Binary files /dev/null and b/client/bin/EACInterfaces differ diff --git a/client/bin/browser b/client/bin/browser new file mode 100755 index 0000000..54663a5 Binary files /dev/null and b/client/bin/browser differ diff --git a/client/bin/grub-probe1.99_i686 b/client/bin/grub-probe1.99_i686 new file mode 100755 index 0000000..21659ef Binary files /dev/null and b/client/bin/grub-probe1.99_i686 differ diff --git a/client/bin/grub-probe1.99_x86_64 b/client/bin/grub-probe1.99_x86_64 new file mode 100755 index 0000000..b62e88f Binary files /dev/null and b/client/bin/grub-probe1.99_x86_64 differ diff --git a/client/bin/poweroffconf b/client/bin/poweroffconf new file mode 100755 index 0000000..de6726b --- /dev/null +++ b/client/bin/poweroffconf @@ -0,0 +1,82 @@ +#!/bin/bash +#/** +#@file poweroffconf +#@brief Control de parada tras tiempo de inactividad para ahorro de energía. +#@license GNU GPLv3+ +#@param int_minutos Minutos de inactividad (opcional); "no" para deshabilitar.. +#@note La comprobación periódica debe ejecutarse en el "cron" del sistema. +#@note Fichero de configuración: /etc/poweroff.conf +#@author Ramón Gómez - Univ. Sevilla +#@date 2011-10-25 +#@version 1.0.5: incluir opción para deshabilitar ahorro de energía. +#@author Ramón Gómez - Univ. Sevilla +#@date 2014-02-07 +#@version 1.1.1: Corregir problema al cambiar de día +#@author Ramón Gómez - Univ. Sevilla +#@date 2018-07-04 +#*/ + + +# Variables generales. +OPENGNSYS=${OPENGNSYS:-/opt/opengnsys} # Instalación de OpenGnsys +OGETC=${OGETC:-$OPENGNSYS/etc} # Configuración de OpenGnsys +POWEROFFCONF=/etc/poweroff.conf # Configuración del script + +# Error si no existe el fichero de configuración de ahorro de energía. +if [ ! -f $POWEROFFCONF ]; then + ogRaiseError $OG_ERR_NOTFOUND "$POWEROFFCONF" + exit $? +fi +# Obtener parámetros de configuración de ahorro de energía. +source $POWEROFFCONF +export TZ + +case $# in + 0) # Sin parámetros, comprobar que existe la variable POWEROFFSLEEP. + if [ -z "$POWEROFFSLEEP" ]; then + ogRaiseError $OG_ERR_FORMAT "Sin tiempo de espera." + exit $? + fi + ;; + 1) # Nuevo timepo de espera. + POWEROFFSLEEP="$1" + # Se deshabilita si se introduce la cadena "no" como tiempo de espera. + [ "$POWEROFFSLEEP" == "no" ] && POWEROFFSLEEP= + # Error si tiempo de espera no es nulo o entero positivo. + if [[ ! "$POWEROFFSLEEP" =~ ^[0-9]*$ ]]; then + ogRaiseError $OG_ERR_FORMAT "Parámetro debe ser núm. minutos o \"no\" para deshabilitar." + exit $? + fi + # Actualizar fichero de configuración con nuevo periodo de parada. + perl -pi -e "s/POWEROFFSLEEP=.*/POWEROFFSLEEP=$POWEROFFSLEEP/" $POWEROFFCONF + # Si se necesita, recalcular tiempo de parada. + if [ -n "POWEROFFTIME" ]; then + # Asignar tiempo de apagado si no está deshabilitado y actualizar fichero. + POWEROFFTIME=${POWEROFFSLEEP:+$(date --date="$POWEROFFSLEEP min" +"%s")} + perl -pi -e "s/POWEROFFTIME=.*/POWEROFFTIME=$POWEROFFTIME/" $POWEROFFCONF + fi + exit 0 ;; + *) # Error de formato de ejecución. + ogRaiseError $OG_ERR_FORMAT "Formato: $0 [int_minutos | no]" + exit $? ;; +esac +# Comprobar si hay algún script en ejecución (verificando compatibilidad de "pgrep"). +[ -n "$(pgrep -fa 2>&1 | grep "invalid")" ] && PGREP="pgrep -fl" || PGREP="pgrep -fa" +if [ -n "$($PGREP $OPENGNSYS | egrep -v "$OGETC|$0")" ]; then + # Eliminar tiempo de inicio de espera, si se está ejecutando operación. + perl -pi -e 's/POWEROFFTIME=.*$/POWEROFFTIME=/' $POWEROFFCONF +else + # Si el sistema está en estado de espera, ... + NOW=$(date +"%s") + if [ -z "$POWEROFFTIME" ]; then + # Asignar tiempo de inicio, si no estaba definido. + POWEROFFTIME=$(date --date="$POWEROFFSLEEP min" +"%s") + perl -pi -e "s/POWEROFFTIME=.*$/POWEROFFTIME=$POWEROFFTIME/" $POWEROFFCONF + else + # Apagar el equipo si se sobrepasa el periodo de espera. + if [ $NOW -ge $POWEROFFTIME ]; then + $OPENGNSYS/scripts/poweroff + fi + fi +fi + diff --git a/client/bin/rsync-31 b/client/bin/rsync-31 new file mode 100755 index 0000000..366204f Binary files /dev/null and b/client/bin/rsync-31 differ diff --git a/client/bin/runtest b/client/bin/runtest new file mode 100755 index 0000000..b18778c --- /dev/null +++ b/client/bin/runtest @@ -0,0 +1,246 @@ +#!/usr/bin/env python +from __future__ import print_function + +import os +import subprocess +import doctest +import re + +FIRST_SCRIPT = 'prepare' +LAST_SCRIPT = 'cleanup' + +PRE_EXTENSION = '.pre' +POST_EXTENSION = '.post' + +PYTHON_TEST_EXTENSION = '.pytest' +BASH_TEST_EXTENSION = '.shtest' + + +class RunTest: + '''Runs the tests''' + + def __init__(self): + self.path = os.path.abspath('.') + + # Only no-hide files + self.all_files = [filename for filename in os.listdir(self.path) + if filename[0] != '.' and os.path.isfile(filename)] + + self.all_files = sorted(self.all_files) + + self.python_tests = [] + self.bash_tests = [] + self.script_tests = [] + self.first_script = '' + self.last_script = '' + self.pre_scripts = [] + self.post_scripts = [] + + for filename in self.all_files: + if filename.endswith(PYTHON_TEST_EXTENSION): + self.python_tests.append(filename) + + elif filename.endswith(BASH_TEST_EXTENSION): + self.bash_tests.append(filename) + + elif os.access(filename, os.X_OK): + basename, extension = os.path.splitext(filename) + if basename == FIRST_SCRIPT: + if self.first_script: + raise MoreThanOneFirstScript() + self.first_script = filename + elif basename == LAST_SCRIPT: + if self.last_script: + raise MoreThanOneLastScript() + self.last_script = filename + elif extension == PRE_EXTENSION: + self.pre_scripts.append(filename) + elif extension == POST_EXTENSION: + self.post_scripts.append(filename) + else: + self.script_tests.append(filename) + + self.fails = 0 + + def run_script(self, script): + '''Run a script test''' + path_script = os.path.join(self.path, script) + proc = subprocess.Popen((path_script), shell=True, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + return_value = proc.wait() + if return_value != 0: + self.fails += 1 + stdout, stderr = proc.communicate() + print("*******************************************************") + print("Error %d in %s:" % (return_value, script)) + print(stdout.decode(), end='') + print(stderr.decode(), end='') + + return return_value + + def run_bash_test(self, script): + '''Run bash test''' + #import pdb; pdb.set_trace() + path_script = os.path.join(self.path, script) + errors = 0 + test_no = 0 + + for command, result, line in read_bash_tests(path_script): + test_no += 1 + try: + proc = subprocess.Popen(('/bin/bash', '-c', command), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + stdout = proc.communicate()[0] + except OSError as exc: + print('File "%s" line %d:' % (script, line)) + print('Failed example:') + print(' ' + command) + print("Exception was raised:") + print(" ", end="") + print(exc) + print("*******************************************************") + errors += 1 + + else: + if result != stdout.decode(): + print('File "%s" line %d:' % (script, line)) + print('Failed example:') + print(' ' + command) + print("Expected:") + for l in result.split('\n')[:-1]: + print(' ' + l) + print("Got:") + for l in stdout.decode().split('\n')[:-1]: + print(' ' + l) + errors += 1 + print("*******************************************************") + + if errors != 0: + print("%d items had failures:" % errors) + print(" %d of %d in %s" % (errors, test_no, script)) + print("***Test failed***") + else: + print("%3d tests PASSED in %s" % (test_no, script)) + + return errors + + + def run_pre_test(self, test): + '''Run the pre-test of a test''' + pre_test = test + PRE_EXTENSION + return_value = 0 + if pre_test in self.pre_scripts: + return_value = self.run_script(pre_test) + if return_value: + print("No running: %s %s" % (test, test + POST_EXTENSION)) + + return return_value + + def run_post_test(self, test): + '''Run the post-test of a test''' + post_test = test + POST_EXTENSION + if post_test in self.post_scripts: + return self.run_script(post_test) + + def run_tests(self): + '''Run the tests in the correct order''' + if self.first_script: + if self.run_script(self.first_script) != 0: + print('*Error in prepare script. Aborting.*') + return self.show_errors() + + all_tests = sorted(self.script_tests + self.python_tests + self.bash_tests) + for test in all_tests: + if self.run_pre_test(test) != 0: + continue + + if test in self.script_tests: + self.run_script(test) + elif test in self.bash_tests: + fails = self.run_bash_test(test) + self.fails += fails + elif test in self.python_tests: + fails, n_tests = doctest.testfile(test, module_relative=False) + self.fails += fails + + self.run_post_test(test) + + if self.last_script: + self.run_script(self.last_script) + + return self.show_errors() + + def show_errors(self): + '''Show the total errors''' + if self.fails: + print("*******************************************************") + print("Total errors: %d" % self.fails) + + return self.fails + +class MoreThanOneFirstScript(Exception): + def __init__(self): + super(MoreThanOneFirstScript, self).__init__( + "More than one %s script" % FIRST_SCRIPT) + +class MoreThanOneLastScript(Exception): + def __init__(self): + super(MoreThanOneLastScript, self).__init__( + "More than one %s script" % LAST_SCRIPT) + + +def read_bash_tests(file_name): + '''Iterator that yields the found tests''' + fd = open(file_name) + command = '' + result = '' + tests = [] + line_no = 0 + command_line = 0 + command_re = re.compile("^\$ (.*)\n") + + for line in fd.readlines(): + line_no += 1 + + match = command_re.match(line) + if match: + # Is it a command? + if command: + # If it is a command but we have a previous command to send + yield (command, result, command_line) + result = '' + + command = match.group(1) + command_line = line_no + + elif command: + # If not a command but we have a previous command + if line != "\n": + # It's a part of the result + if line == "\n": + result += '\n' + else: + result += line + + else: + # Or it's the end of the result, yielding + + yield (command, result, command_line) + command = '' + result = '' + + + else: + # This line is a comment + pass + + if command: + # Cheking if the last command was sent + yield (command, result, command_line) + + fd.close() + + +if __name__ == "__main__": + r = RunTest() + r.run_tests() diff --git a/client/cache/README.es.txt b/client/cache/README.es.txt new file mode 100644 index 0000000..9c4ec9f --- /dev/null +++ b/client/cache/README.es.txt @@ -0,0 +1 @@ +Directorio de caché para el cliente diff --git a/client/etc/engine.cfg b/client/etc/engine.cfg new file mode 100644 index 0000000..279acd5 --- /dev/null +++ b/client/etc/engine.cfg @@ -0,0 +1,56 @@ +## Definicion general +set -a +OGENGINECONFIGURATE="TRUE" +OGLOGSESSION="/tmp/session.log" +OGLOGCOMMAND="/tmp/command.log" + +##Configuracion de la PostConfiguracion OS WIndows +#Hacer chkdisk tras la clonacion +OGWINCHKDISK=TRUE + +#Configuracion de interface restauracion +#Que hacer cuando la cache no tenga espacio libre. [ NONE | FORMAT ] ] +ACTIONCACHEFULL=NONE +#Que protocolo de restauracion usar en el caso de que no exista cache o no exista espacio sufiente. [NONE | UNICAST | MULTICAST].NONE retorna error +RESTOREPROTOCOLNOTCACHE=NONE + +#script Creacion imagen +IMGPROG="partclone" +IMGCOMP="lzop" +IMGEXT="img" +IMGREDUCE="TRUE" + +#Configuracion del asistente de Clonacion remota usando master +#Al enviar particion reducir el sistema de archivos previamente. +OGWINREDUCE=TRUE + +# Sesion MULTICAST de cliente +#timeout (segundos) para abortar la sesion de multicast si no contacta con el servidor de multicast. Valor asignado a 0, utiliza los valores por defecto de udp-cast +MCASTERRORSESSION=120 +# timeout (segundos) para abortar la la transferencia si se interrumpe. Valor asignado a 0, utiliza los valores por defecto de udp-cast +MCASTWAIT=30 + +# Imagenes sincronizadas +# Factor para calcular el time-out al crear la imagen. 100000k -> 4s +CREATESPEED=100000*4 +# Factor de compresion para las imagenes (windos en ext4). +FACTORSYNC=120 +# Realizar copia de seguridad antes de crear la imagen. +BACKUP=false +# Sistema de archivo de la imagenes sincronizadas. EXT4 o BTRFS +IMGFS=EXT4 + +# Tiempo de sleep antes de realizar el reboot +OGSLEEP="20" + +# La variable INSTALLOSCLIENT no se utiliza en OpenGnsys 1.1.0. + +# Funciones que no deben mostrar salida de avisos si son llamadas por otras funciones. +NODEBUGFUNCTIONS="ogCreateImageSyntax ogGetHivePath ogGetOsType ogRestoreImageSyntax ogUnmountAll ogUnmountCache" + +# Velocidad de comunicación por defecto (muestra aviso en Browser si no se cumple): +# "", no usar esta característica. +# "100Mb/s", Fast Ethernet. +# "1000Mb/s", Gigabit Ethernet. +DEFAULTSPEED="" + diff --git a/client/etc/engine.json b/client/etc/engine.json new file mode 100644 index 0000000..7d9e75f --- /dev/null +++ b/client/etc/engine.json @@ -0,0 +1,804 @@ +{ + "variables": [ + { + "description": "applying engine configuration (boolean)", + "name": "OGENGINECONFIGURATE", + "value": true + }, + { + "description": "session log file (path)", + "name": "OGLOGSESSION", + "value": "/tmp/session.log" + }, + { + "description": "command log file (path)", + "name": "OGLOGCOMMAND", + "value": "/tmp/command.log" + }, + { + "description": "image clonation program (string)", + "name": "IMGPROG", + "value": "partclone" + }, + { + "description": "image compresson (string)", + "name": "IMGCOMP", + "value": "lzop" + }, + { + "description": "filesystem image extension (string)", + "name": "IMGEXT", + "value": "img" + }, + { + "description": "disk image extension (string)", + "name": "DISKIMGEXT", + "value": "dsk" + }, + { + "description": "trying to reduce image (boolean)", + "name": "IMGREDUCE", + "value": true + }, + { + "description": "trying to reduce Windows filesystem before creating image (boolean)", + "name": "OGWINREDUCE", + "value": true + }, + { + "description": "time to sleep before reboot (seconds)", + "name": "OGSLEEP", + "value": 20 + }, + { + "description": "do not show warnings in this functions (list of functions)", + "name": "NODEBUGFUNCTIONS", + "value": "ogCreateImageSyntax ogGetHivePath ogGetOsType ogRestoreImageSyntax ogUnmountAll ogUnmountCache" + }, + { + "description": "action to take if cache is full (NONE; FORMAT)", + "name": "ACTIONCACHEFULL", + "value": "NONE" + }, + { + "description": "restoration protocol if cache is full or it does not exists (NONE, returns error; UNICAST; MULTICAST)", + "name": "RESTOREPROTOCOLNOTCACHE", + "value": "UNICAST" + }, + { + "description": "timout if Multicast transfer does not begins (seconds)", + "name": "MCASTERRORSESSION", + "value": 120 + }, + { + "description": "timout if Multicast transfer does it's interrupted (seconds)", + "name": "MCASTWAIT", + "value": 30 + }, + { + "description": "run CHKDSK after Windows depolying (boolean)", + "name": "OGWINCHKDISK", + "value": true + }, + { + "description": "timeout factor creating synchronized image (integer, 100000k => 4s)", + "name": "CREATESPEED", + "value": 400000 + }, + { + "description": "compression factor creating synchronized image (integer)", + "name": "FACTORSYNC", + "value": 120 + }, + { + "description": "make backup before creating synchronized image (boolean)", + "name": "BACKUP", + "value": false + }, + { + "description": "filesystem type creating synchronized image (string)", + "name": "IMGFS", + "value": "EXT4" + }, + { + "description": "default communication speed (blank, do not use; 100Mb/s; 1000Mb/s)", + "name": "DEFAULTSPEED", + "value": "" + } + ], + "errors": [ + { + "id": 1, + "description": "format error", + "name": "OG_ERR_FORMAT" + }, + { + "id": 2, + "description": "resource not found", + "name": "OG_ERR_NOTFOUND" + }, + { + "id": 3, + "description": "partition error", + "name": "OG_ERR_PARTITION" + }, + { + "id": 4, + "description": "resource locked", + "name": "OG_ERR_LOCKED" + }, + { + "id": 5, + "description": "image error", + "name": "OG_ERR_IMAGE" + }, + { + "id": 6, + "description": "operating system not detected", + "name": "OG_ERR_NOTOS" + }, + { + "id": 7, + "description": "program or function not executable", + "name": "OG_ERR_NOTEXEC" + }, + { + "id": 14, + "description": "cannot write", + "name": "OG_ERR_NOTWRITE" + }, + { + "id": 15, + "description": "cache filesystem does not exists", + "name": "OG_ERR_NOTCACHE" + }, + { + "id": 16, + "description": "cache filesystem is full", + "name": "OG_ERR_CACHESIZE" + }, + { + "id": 17, + "description": "error reducing filesystem", + "name": "OG_ERR_REDUCEFS" + }, + { + "id": 18, + "description": "error extending filesystem", + "name": "OG_ERR_EXTENDFS" + }, + { + "id": 19, + "description": "value out of limit", + "name": "OG_ERR_OUTOFLIMIT" + }, + { + "id": 20, + "description": "filesystem error", + "name": "OG_ERR_FILESYS" + }, + { + "id": 21, + "description": "cache error", + "name": "OG_ERR_CACHE" + }, + { + "id": 22, + "description": "no GPT partition table", + "name": "OG_ERR_NOGPT" + }, + { + "id": 23, + "description": "cannot mount repository", + "name": "OG_ERR_REPO" + }, + { + "id": 30, + "description": "trying to restore an image into an smaller partition", + "name": "OG_ERR_IMGSIZEPARTITION" + }, + { + "id": 31, + "description": "error updating cache", + "name": "OG_ERR_UPDATECACHE" + }, + { + "id": 32, + "description": "formatting error", + "name": "OG_ERR_DONTFORMAT" + }, + { + "id": 40, + "description": "unknown error", + "name": "OG_ERR_GENERIC" + }, + { + "id": 50, + "description": "error preparing Unicast syntax", + "name": "OG_ERR_UCASTSYNTAXT" + }, + { + "id": 51, + "description": "error sending partition using Unicast protocol", + "name": "OG_ERR_UCASTSENDPARTITION" + }, + { + "id": 52, + "description": "error sending file using Unicast protocol", + "name": "OG_ERR_UCASTSENDFILE" + }, + { + "id": 52, + "description": "error receiving partition using Unicast protocol", + "name": "OG_ERR_UCASTRECEIVERPARTITION" + }, + { + "id": 53, + "description": "error receiving file using Unicast protocol", + "name": "OG_ERR_UCASTRECEIVERFILE" + }, + { + "id": 55, + "description": "error preparing Multicast syntax", + "name": "OG_ERR_MCASTSYNTAXT" + }, + { + "id": 56, + "description": "error sending file using Multicast protocol", + "name": "OG_ERR_MCASTSENDFILE" + }, + { + "id": 57, + "description": "error receiving file using Multicast protocol", + "name": "OG_ERR_MCASTRECEIVERFILE" + }, + { + "id": 58, + "description": "error sending partition using Multicast protocol", + "name": "OG_ERR_MCASTSENDPARTITION" + }, + { + "id": 59, + "description": "error receiving partition using Multicast protocol", + "name": "OG_ERR_MCASTRECEIVERPARTITION" + }, + { + "id": 60, + "description": "error connecting master node", + "name": "OG_ERR_PROTOCOLJOINMASTER" + }, + { + "id": 70, + "description": "cannot mount a syncrhronized image", + "name": "OG_ERR_DONTMOUNT_IMAGE" + }, + { + "id": 71, + "description": "it's not a syncrhronized image", + "name": "OG_ERR_DONTSYNC_IMAGE" + }, + { + "id": 72, + "description": "cannot unmount a syncrhronized image", + "name": "OG_ERR_DONTUNMOUNT_IMAGE" + }, + { + "id": 73, + "description": "there are no differences between basic image and filesystem", + "name": "OG_ERR_NOTDIFFERENT" + }, + { + "id": 74, + "description": "synchronization error", + "name": "OG_ERR_SYNCHRONIZING" + } + ], + "disks": [ + { + "type": "DISK" + }, + { + "type": "USB" + }, + { + "type": "CDROM" + }, + { + "type": "RAID" + }, + { + "type": "MAPPER" + } + ], + "partitiontables": [ + { + "id": 1, + "type": "MSDOS", + "partitions": [ + { + "id": "0", + "type": "EMPTY", + "clonable": false + }, + { + "id": "1", + "type": "FAT12", + "clonable": true + }, + { + "id": "5", + "type": "EXTENDED", + "clonable": false + }, + { + "id": "6", + "type": "FAT16", + "clonable": true + }, + { + "id": "7", + "type": "NTFS", + "clonable": true + }, + { + "id": "b", + "type": "FAT32", + "clonable": true + }, + { + "id": "11", + "type": "HFAT12", + "clonable": true + }, + { + "id": "16", + "type": "HFAT16", + "clonable": true + }, + { + "id": "17", + "type": "HNTFS", + "clonable": true + }, + { + "id": "1b", + "type": "HFAT32", + "clonable": true + }, + { + "id": "27", + "type": "HNTFS-WINRE", + "clonable": true + }, + { + "id": "82", + "type": "LINUX-SWAP", + "clonable": false + }, + { + "id": "83", + "type": "LINUX", + "clonable": true + }, + { + "id": "8e", + "type": "LINUX-LVM", + "clonable": true + }, + { + "id": "a5", + "type": "FREEBSD", + "clonable": true + }, + { + "id": "a6", + "type": "OPENBSD", + "clonable": true + }, + { + "id": "a9", + "type": "NETBSD", + "clonable": true + }, + { + "id": "af", + "type": "HFS", + "clonable": true + }, + { + "id": "be", + "type": "SOLARIS-BOOT", + "clonable": true + }, + { + "id": "bf", + "type": "SOLARIS", + "clonable": true + }, + { + "id": "ca", + "type": "CACHE", + "clonable": false + }, + { + "id": "da", + "type": "DATA", + "clonable": true + }, + { + "id": "ee", + "type": "GPT", + "clonable": false + }, + { + "id": "ef", + "type": "EFI", + "clonable": true + }, + { + "id": "fb", + "type": "VMFS", + "clonable": true + }, + { + "id": "fd", + "type": "LINUX-RAID", + "clonable": true + } + ] + }, + { + "id": 2, + "type": "GPT", + "partitions": [ + { + "id": "700", + "type": "WINDOWS", + "clonable": true + }, + { + "id": "c01", + "type": "WIN-RESERV", + "clonable": true + }, + { + "id": "2700", + "type": "WIN-RECOV", + "clonable": true + }, + { + "id": "7f00", + "type": "CHROMEOS-KRN", + "clonable": true + }, + { + "id": "7f01", + "type": "CHROMEOS", + "clonable": true + }, + { + "id": "7f02", + "type": "CHROMEOS-RESERV", + "clonable": true + }, + { + "id": "8200", + "type": "LINUX-SWAP", + "clonable": false + }, + { + "id": "8300", + "type": "LINUX", + "clonable": true + }, + { + "id": "8301", + "type": "LINUX-RESERV", + "clonable": true + }, + { + "id": "8302", + "type": "LINUX", + "clonable": true + }, + { + "id": "8e00", + "type": "LINUX-LVM", + "clonable": true + }, + { + "id": "a500", + "type": "FREEBSD-DISK", + "clonable": false + }, + { + "id": "a501", + "type": "FREEBSD-BOOT", + "clonable": true + }, + { + "id": "a502", + "type": "FREEBSD-SWAP", + "clonable": false + }, + { + "id": "a503", + "type": "FREEBSD", + "clonable": true + }, + { + "id": "a504", + "type": "FREEBSD", + "clonable": true + }, + { + "id": "a901", + "type": "NETBSD-SWAP", + "clonable": false + }, + { + "id": "a902", + "type": "NETBSD", + "clonable": true + }, + { + "id": "a903", + "type": "NETBSD", + "clonable": true + }, + { + "id": "a904", + "type": "NETBSD", + "clonable": true + }, + { + "id": "a905", + "type": "NETBSD", + "clonable": true + }, + { + "id": "a906", + "type": "NETBSD-RAID", + "clonable": true + }, + { + "id": "ab00", + "type": "HFS-BOOT", + "clonable": true + }, + { + "id": "af00", + "type": "HFS", + "clonable": true + }, + { + "id": "af01", + "type": "HFS-RAID", + "clonable": true + }, + { + "id": "af02", + "type": "HFS-RAID", + "clonable": true + }, + { + "id": "be00", + "type": "SOLARIS-BOOT", + "clonable": true + }, + { + "id": "bf00", + "type": "SOLARIS", + "clonable": true + }, + { + "id": "bf01", + "type": "SOLARIS", + "clonable": true + }, + { + "id": "bf02", + "type": "SOLARIS-SWAP", + "clonable": false + }, + { + "id": "bf03", + "type": "SOLARIS-DISK", + "clonable": true + }, + { + "id": "bf04", + "type": "SOLARIS", + "clonable": true + }, + { + "id": "bf05", + "type": "SOLARIS", + "clonable": true + }, + { + "id": "ca00", + "type": "CACHE", + "clonable": false + }, + { + "id": "ef00", + "type": "EFI", + "clonable": true + }, + { + "id": "ef01", + "type": "MBR", + "clonable": false + }, + { + "id": "ef02", + "type": "BIOS-BOOT", + "clonable": false + }, + { + "id": "fb00", + "type": "VMFS", + "clonable": true + }, + { + "id": "fb01", + "type": "VMFS-RESERV", + "clonable": true + }, + { + "id": "fb02", + "type": "VMFS-KRN", + "clonable": true + }, + { + "id": "fd00", + "type": "LINUX-RAID", + "clonable": true + }, + { + "id": "ffff", + "type": "UNKNOWN", + "clonable": true + } + ] + }, + { + "id": 3, + "type": "LVM", + "partitions": [ + { + "id": "10000", + "type": "LVM-LV", + "clonable": true + } + ] + }, + { + "id": 4, + "type": "ZPOOL", + "partitions": [ + { + "id": "10010", + "type": "ZFS-VOL", + "clonable": true + } + ] + } + ], + "filesystems": [ + { + "id": 1, + "type": "EMPTY" + }, + { + "id": 2, + "type": "CACHE" + }, + { + "id": 3, + "type": "BTRFS" + }, + { + "id": 4, + "type": "EXT2" + }, + { + "id": 5, + "type": "EXT3" + }, + { + "id": 6, + "type": "EXT4" + }, + { + "id": 7, + "type": "FAT12" + }, + { + "id": 8, + "type": "FAT16" + }, + { + "id": 9, + "type": "FAT32" + }, + { + "id": 10, + "type": "HFS" + }, + { + "id": 11, + "type": "HFSPLUS" + }, + { + "id": 12, + "type": "JFS" + }, + { + "id": 13, + "type": "NTFS" + }, + { + "id": 14, + "type": "REISERFS" + }, + { + "id": 15, + "type": "REISER4" + }, + { + "id": 16, + "type": "UFS" + }, + { + "id": 17, + "type": "XFS" + }, + { + "id": 18, + "type": "LINUX-SWAP" + }, + { + "id": 19, + "type": "EXFAT" + }, + { + "id": 20, + "type": "F2FS" + }, + { + "id": 21, + "type": "NILFS2" + } + ], + "operatingsystems": [ + { + "type": "Android" + }, + { + "type": "BSD" + }, + { + "type": "GrubLoader" + }, + { + "type": "Hurd" + }, + { + "type": "Linux" + }, + { + "type": "MacOS" + }, + { + "type": "Solaris" + }, + { + "type": "Windows" + }, + { + "type": "WinLoader" + } + ] +} diff --git a/client/etc/es.qmap b/client/etc/es.qmap new file mode 100644 index 0000000..fa1fc5a Binary files /dev/null and b/client/etc/es.qmap differ diff --git a/client/etc/init/default.sh b/client/etc/init/default.sh new file mode 100755 index 0000000..1ca273b --- /dev/null +++ b/client/etc/init/default.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Proceso general de arranque de OpenGnsys Client. + + +# Fichero de registro de incidencias (en el servidor; si no, en local). +OPENGNSYS=${OPENGNSYS:-/opt/opengnsys} +OGLOGFILE=${OGLOGFILE:-$OPENGNSYS/log/$(ogGetIpAdderss).log} +if ! touch $OGLOGFILE 2>/dev/null; then + OGLOGFILE=/var/log/opengnsys.log +fi +LOGLEVEL=5 + +# Matando plymount para inicir browser o shell +pkill -9 plymouthd + +# Arranque de OpenGnsys Client daemon (socket). +echo "${MSG_LAUNCHCLIENT:-.}" +# Indicar fichero de teclado de Qt para el idioma especificado (tipo "es.qmap"). +[ -f /usr/local/etc/${LANG%_*}.qmap ] && export QWS_KEYBOARD="TTY:keymap=/usr/local/etc/${LANG%_*}.qmap" + +if [ -f "/usr/share/OGAgent/opengnsys/linux/OGAgentService.py" -a "$ogstatus" != "offline" ]; then + # Ejecutar servicio cliente. + cd /usr/share/OGAgent + export OGAGENTCFG_OGCORE_IP=$ogcore + export OGAGENTCFG_OGLOG_IP=$oglog + export OGAGENTCFG_URLMENU_IP=$ogcore + python3 -m opengnsys.linux.OGAgentService fg +else + for FILE in index $OGGROUP $(ogGetIpAddress) + do + [ -f $OGCAC/menus/$FILE.html ] && OGMENU="$OGCAC/menus/$FILE.html" + done + echo "exec /usr/bin/OGBrowser $OGMENU" > /home/root/ + /usr/bin/OGBrowser -qws $OGMENU +fi + +# Si fallo en cliente y modo "admin", cargar shell; si no, salir. +if [ "$ogactiveadmin" == "true" ]; then + bash +fi \ No newline at end of file diff --git a/client/etc/lang.ca_ES.UTF-8.conf b/client/etc/lang.ca_ES.UTF-8.conf new file mode 120000 index 0000000..db97a00 --- /dev/null +++ b/client/etc/lang.ca_ES.UTF-8.conf @@ -0,0 +1 @@ +lang.ca_ES.conf \ No newline at end of file diff --git a/client/etc/lang.ca_ES.conf b/client/etc/lang.ca_ES.conf new file mode 100644 index 0000000..6dce8a5 --- /dev/null +++ b/client/etc/lang.ca_ES.conf @@ -0,0 +1,398 @@ +# Fichero de idioma: catalá. +#@version 1.1.1 +#@author + + +# Mensajes de error. +MSG_ERR_GENERIC="Error imprevisto no definido" +MSG_ERR_FORMAT="Formato de ejecución incorrecto" +MSG_ERR_OUTOFLIMIT="Valor fuera de rango o no válido" +MSG_ERR_NOTFOUND="Fichero o dispositivo no encontrado" +MSG_ERR_PARTITION="Partición errónea o desconocida" +MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo" +MSG_ERR_CACHE="Error en partición de caché local" +MSG_ERR_NOGPT="El disco indicado no contiene una particion GPT" +MSG_ERR_REPO="Error al montar el repositorio de imágenes" +MSG_ERR_NOMSDOS="El disco indicado no contiene una partición MSDOS" +MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar" +MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar" +MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema" +MSG_ERR_IMAGEFILE="Archivo de imagen corrupto o de otra versión de partclone" +MSG_ERR_NOTEXEC="Programa o función no ejecutable" +MSG_ERR_NOTWRITE="No hay acceso de escritura" +MSG_ERR_NOTCACHE="No existe particion Cache en el cliente" +MSG_ERR_NOTUEFI="La interfaz UEFI no está activa" +MSG_ERR_NOTBIOS="La interfaz BIOS Legacy no está activa" +MSG_ERR_CACHESIZE="El espacio de la cache local o remota no es suficiente" +MSG_ERR_REDUCEFS="Error al reducir el sistema de archivos" +MSG_ERR_EXTENDFS="Error al expandir el sistema de archivos" +MSG_ERR_IMGSIZEPARTITION="Error al restaurar: Particion mas pequeña que la imagen" +MSG_ERR_UPDATECACHE="Error al realizar el comando updateCache" +MSG_ERR_UCASTSYNTAXT="Error en la generación de sintaxis de transferenica unicast" +MSG_ERR_UCASTSENDPARTITION="Error en envio UNICAST de una particion" +MSG_ERR_UCASTSENDFILE="Error en envio UNICAST de un fichero" +MSG_ERR_UCASTRECEIVERPARTITION="Error en la recepcion UNICAST de una particion" +MSG_ERR_UCASTRECEIVERFILE="Error en la recepcion UNICAST de un fichero" +MSG_ERR_MCASTSYNTAXT="Error en la generación de sintaxis de transferenica multicast" +MSG_ERR_MCASTSENDFILE="Error en envio MULTICAST de un fichero" +MSG_ERR_MCASTRECEIVERFILE="Error en la recepcion MULTICAST de un fichero" +MSG_ERR_MCASTSENDPARTITION="Error en envio MULTICAST de una particion" +MSG_ERR_MCASTRECEIVERPARTITION="Error en la recepcion MULTICAST de un fichero" +MSG_ERR_PROTOCOLJOINMASTER="Error en la conexion de una sesion UNICAST|MULTICAST con el MASTER" +MSG_ERR_DONTFORMAT="Error al formatear" +MSG_ERR_DONTMOUNT_IMAGE="Error al montar/reducir la imagen" +MSG_ERR_DONTUNMOUNT_IMAGE="Error al desmontar la imagen" +MSG_ERR_DONTSYNC_IMAGE="Imagen no sincronizable" +MSG_ERR_NOTDIFFERENT="No se detectan diferencias entre la imagen basica y la particion." +MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restauracion de la imagen" + +# Mensajes de avisos. +MSG_DONTUSE="NO USAR" +MSG_DONTMOUNT="Sistema de archivos no montado" +MSG_DONTUNMOUNT="El sistema de archivos no se puede desmontar o no está montado" +MSG_MOUNT="Sistema de archivos montado" +MSG_MOUNTREADONLY="Sistema de archivos montado solo de lectura" +MSG_OBSOLETE="EN DESUSO" + +# Mensajes complementarios para las ayudas. +MSG_64BIT="64 bits" +MSG_DISK="disc" +MSG_ERROR="Error" +MSG_EXAMPLE="Exemple" +MSG_FORMAT="Format" +MSG_FUNCTION="Funció" +MSG_HARDWAREINVENTORY="Inventario de maquinari de la màquina" +MSG_IMAGE="imatge" +MSG_INSTALLED="instal-lat" +MSG_NOCACHE="sense caché local" +MSG_NOEXTENDED="sense partició estensa" +MSG_PARTITION="partició" +MSG_PROTOCOL="protocol" +MSG_RESERVEDVALUE="Valor reservat" +MSG_SEE="Veure" +MSG_UNKNOWN="Desconegut" +MSG_WARNING="Avís" + +# Mensajes del proceso de arranque. +MSG_DETECTLVMRAID="Detectar metadispositivos LVM y RAID." +MSG_ERRBOOTMODE="$MSG_ERROR: Modo de arranque desconocido." +MSG_LAUNCHCLIENT="Ejecutar cliente." +MSG_LOADAPI="Cargar funciones del motor de clonación." +MSG_LOADMODULES="Cargar módulos del kernel." +MSG_MAKELINKS="Crear enlaces simbólicos." +MSG_MOUNTREPO="Montar repositorio por %s en modo %s." +MSG_OFFLINEMODE="Modo de arranque sin conexión." +MSG_OTHERSERVICES="Iniciar servicios complementarios del cliente." +MSG_POWEROFFCONF="Definir parámetros de ahorro de energía." + +# Mensajes del menú por defecto. +MSG_BOOT="Iniciar" +MSG_DUPLEX="Dúplex" +MSG_HOSTNAME="Equipo" +MSG_IPADDR="Dirección IP" +MSG_MACADDR="Dirección MAC" +MSG_MENUTITLE="Menú de opciones" +MSG_POWEROFF="Apagar el equipo" +MSG_SPEED="Velocidad" + +# Mensajes de descripción breve de las funciones de la API. +MSG_HELP_ogAclFilter="Extrae las acl de los ficheros de la diferencial" +MSG_HELP_ogAddCmd="Añade comandos al fichero creado por la función ogInstalMiniSetup." +MSG_HELP_ogAddRegistryKey="Añade una nueva clave al registro de Windows." +MSG_HELP_ogAddRegistryValue="Añade un nuevo valor al registro de Windows." +MSG_HELP_ogAddToLaunchDaemon="" +MSG_HELP_ogBoot="Arranca un sistema operativo instalado." +MSG_HELP_ogBootLoaderDeleteEntry="$MSG_DONTUSE." +MSG_HELP_ogBootLoaderHidePartitions="$MSG_DONTUSE." +MSG_HELP_ogBootMbrGeneric="" +MSG_HELP_ogBootMbrXP="" +MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg." +MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion." +MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)." +MSG_HELP_ogBurgInstallMbr="Instal·la el carregador d'arrencada BURG al MBR del primer disc dur" +MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg." +MSG_HELP_ogCalculateChecksum="Calcula la suma de comprobación (checksum) de un fichero." +MSG_HELP_ogCalculateFullChecksum="" +MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images." +MSG_HELP_ogCheckFs="Comprueba la consistencia de un sistema de archivos." +MSG_HELP_ogCheckIpAddress="" +MSG_HELP_ogCheckProgram="" +MSG_HELP_ogCheckStringInGroup="" +MSG_HELP_ogCheckStringInReg="" +MSG_HELP_ogCheckSyncImage="Muestra el contenido de la imagen para comprobarla." +MSG_HELP_ogCleanLinuxDevices="" +MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo." +MSG_HELP_ogCompareChecksumFiles="Compara si coinciden las sumas de comprobación almacenadas de 2 ficheros." +MSG_HELP_ogConfigureFstab="" +MSG_HELP_ogConfigureOgagent="Configura el nuevo agente OGAgent para sistemas ooperativos." +MSG_HELP_ogCopyFile="Copia un fichero a otro almacenamiento." +MSG_HELP_ogCreateBootLoaderImage="" +MSG_HELP_ogCreateCache="Reserva espacio para la partición de caché al final del disco." +MSG_HELP_ogCreateDiskImage="Genera una imagen exacta de un disco completo." +MSG_HELP_ogCreateFileImage="Crea/Redimensiona el archivo de la imagen sincronizada" +MSG_HELP_ogCreateGptPartitions="" +MSG_HELP_ogCreateImage="Genera una imagen exacta de un sistema operativo instalado localmente." +MSG_HELP_ogCreateImageSyntax="" +MSG_HELP_ogCreateInfoImage="Crea informacion del contenido de la imagen" +MSG_HELP_ogCreateMbrImage="Genera una imagen del sector de arranque (MBR)." +MSG_HELP_ogCreatePartitions="Define la estructura de particiones de un disco." +MSG_HELP_ogCreatePartitionTable="Genera una tabla de particiones en caso de que no sea valida." +MSG_HELP_ogCreateTorrent="" +MSG_HELP_ogCopyEfiBootLoader="Copia el cargador de arranque desde la partición EFI a la de sistema." +MSG_HELP_ogDeleteCache="Elimina la partición de caché local." +MSG_HELP_ogDeleteFile="Borra un fichero de un espacio de almacenamiento." +MSG_HELP_ogDeletePartitionTable="Elimina la tabla de particiones del disco" +MSG_HELP_ogDeleteRegistryKey="Borra una clave vacía del registro de Windows." +MSG_HELP_ogDeleteRegistryValue="Borra un valor del registro de Windows." +MSG_HELP_ogDeleteTree="Borra un árbol de directorios de un espacio de almacenamiento." +MSG_HELP_ogDevToDisk="Devuelve el nº de orden de disco o de partición correspondiente al camino del fichero de dispositivo." +MSG_HELP_ogDiskToDev="Devuelve el camino del fichero de dispositivo correspondiente al nº de orden de disco o de partición." +MSG_HELP_ogDomainScript="" +MSG_HELP_ogEcho="" +MSG_HELP_ogExecAndLog="" +MSG_HELP_ogExtendFs="Extiende el tamaño de un sistema de archivo al máximo de su partición." +MSG_HELP_ogFindCache="Indica la partición reservada para caché local." +MSG_HELP_ogFixBootSector="" +MSG_HELP_ogFormatCache="Formatea (inicia) el sistema de caché local." +MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos." +MSG_HELP_ogFormatFs=$MSG_HELP_ogFormat +MSG_HELP_ogGetArch="Devuelve el tipo de arquitectura del cliente." +MSG_HELP_ogGetCacheSize="Devuelve el tamaño de la partición de caché local." +MSG_HELP_ogGetCacheSpace="Devuelve el espacio máximo disponible que puede ser reservado para la partición de caché local." +MSG_HELP_ogGetCaller="" +MSG_HELP_ogGetDiskSize="Devuelve el tamaño del disco." +MSG_HELP_ogGetDiskType="Devuelve el mnemónico de tipo de disco." +MSG_HELP_ogGetFreeSize="" +MSG_HELP_ogGetFsSize="Devuelve el tamaño de un sistema de archivos." +MSG_HELP_ogGetFsType="Devuelve el mnemónico de tipo de sistema de archivos." +MSG_HELP_ogGetGroupDir="Devuelve el camino del directorio por defecto para el grupo del cliente." +MSG_HELP_ogGetGroupName="Devuelve el nombre del grupo al que pertenece el cliente." +MSG_HELP_ogGetHivePath="Devuelve el camino completo del fichero de una sección del registro de Windows." +MSG_HELP_ogGetHostname="Devuelve el nombre de la máquina local." +MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen." +MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB." +MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen." +MSG_HELP_ogGetImageSize="Devuelve el tamaño de una imagen de sistema." +MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen." +MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente." +MSG_HELP_ogGetLastSector="Devuelve el último sector usable del disco o de una partición." +MSG_HELP_ogGetMacAddress="Devuelve la dirección Ethernet del cliente." +MSG_HELP_ogGetMountImageDir="Devuelve el directorio de montaje de una imagen." +MSG_HELP_ogGetMountPoint="Devuelve el directorio donde está montado un sistema de archivos local." +MSG_HELP_ogGetNetInterface="" +MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado." +MSG_HELP_ogGetOsUuid="" +MSG_HELP_ogGetOsVersion="Devuelve el tipo y la versión de un sistema operativo instalado." +MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys." +MSG_HELP_ogGetPartitionActive="Indica cual es la partición marcada como activa en un disco." +MSG_HELP_ogGetPartitionId="Devuelve el identificador de tipo de una partición." +MSG_HELP_ogGetPartitionSize="Devuelve el tamaño de una partición." +MSG_HELP_ogGetPartitionsNumber="" +MSG_HELP_ogGetPartitionTableType="Devuelve el tipo de tabla de particiones del disco" +MSG_HELP_ogGetPartitionType="Devuelve el mnemónico de tipo de una partición." +MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnsys." +MSG_HELP_ogGetRegistryValue="Devuelve el dato de un valor del registro de Windows." +MSG_HELP_ogGetRepoIp="Devuelve la dirección IP del repositorio de datos." +MSG_HELP_ogGetSerialNumber="Devuelve el número de serie del cliente." +MSG_HELP_ogGetServerIp="Devuelve la dirección IP del servidor principal." +MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido." +MSG_HELP_ogGetWindowsName="Devuelve el nombre del cliente guardado en el registro de Windows." +MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB." +MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion." +MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)." +MSG_HELP_ogGrubInstallMbr="Instal·la el carregador d'arrencada GRUB al MBR del primer disc dur" +MSG_HELP_ogGrubInstallPartition="Instal·la el carregador d'arrencada BURG al BootSector" +MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB." +MSG_HELP_ogGrubSecurity="Configura usuario y clave para modificar las entradas del menu del Grub." +MSG_HELP_ogGrubUefiConf="Genera el fichero grub.cfg de la partición EFI." +MSG_HELP_ogHelp="Muestra mensajes de ayudas para las funciones." +MSG_HELP_ogHidePartition="Oculta una partición de Windows." +MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición." +MSG_HELP_ogNvramActiveEntry="Configura a activa entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramAddEntry="Crea nueva entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramDeleteEntry="Borra entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramGetCurrent="Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo." +MSG_HELP_ogNvramGetNext="Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque." +MSG_HELP_ogNvramGetOrder="Muestra el orden de las entradas del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramGetTimeout="Muestra el tiempo de espera del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramInactiveEntry="Configura a inactiva entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramList="Lista las entradas del gestor de arranque (NVRAN) marcando con un asterisco las activas" +MSG_HELP_ogNvramSetNext="Configura el próximo arranque con la entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramSetOrder="Configura el orden de las entradas del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramSetTimeout="Configura el tiempo de espera del gestor de arranque (NVRAM)." +MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado." +MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows." +MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows." +MSG_HELP_ogInstallRunonce="Crea un archivo que se ejecutará en el inicio de un usuario administrador de Windows." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." +MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado." +MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo." +MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo." +MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo." +MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado." +MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro." +MSG_HELP_ogIsPartitionLocked=$MSG_HELP_ogIsLocked +MSG_HELP_ogIsRepoLocked="" +MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable." +MSG_HELP_ogIsVirtualMachine="" +MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura." +MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado." +MSG_HELP_ogListHardwareInfo="Lista el inventario de dispositivos del cliente." +MSG_HELP_ogListLogicalPartitions="" +MSG_HELP_ogListPartitions="Lista la estructura de particiones de un disco." +MSG_HELP_ogListPrimaryPartitions="" +MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows." +MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows." +MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo." +MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo." +MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo." +MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo." +MSG_HELP_ogLockPartition=$MSG_HELP_ogLock +MSG_HELP_ogMakeChecksumFile="Almacena la suma de comprobación de un fichero." +MSG_HELP_ogMakeDir="Crea un directorio para OpenGnsys." +MSG_HELP_ogMakeGroupDir="Crea el directorio de grupo (aula) en un repositorio." +MSG_HELP_ogMcastReceiverFile="" +MSG_HELP_ogMcastReceiverPartition="" +MSG_HELP_ogMcastRequest="" +MSG_HELP_ogMcastSendFile="" +MSG_HELP_ogMcastSendPartition="" +MSG_HELP_ogMcastSyntax="" +MSG_HELP_ogMountCache="Monta el sistema de archivos dedicado a caché local." +MSG_HELP_ogMountCdrom="Monta dispositivo óptico por defecto." +MSG_HELP_ogMountFs=$MSG_HELP_ogMount +MSG_HELP_ogMountImage="Monta una imagen sincronizable" +MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje." +MSG_HELP_ogNvramActiveEntry="Configura a activa entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramAddEntry="Crea nueva entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramDeleteEntry="Borra entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramGetCurrent="Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo." +MSG_HELP_ogNvramGetNext="Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque." +MSG_HELP_ogNvramGetOrder="Muestra el orden de las entradas del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramGetTimeout="Muestra el tiempo de espera del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramInactiveEntry="Configura a inactiva entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramList="Lista las entradas del gestor de arranque (NVRAN) marcando con un asterisco las activas" +MSG_HELP_ogNvramPxeFirstEntry="Configura la tarjeta de red como primer arranque en la NVRAM." +MSG_HELP_ogNvramSetNext="Configura el próximo arranque con la entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramSetOrder="Configura el orden de las entradas del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramSetTimeout="Configura el tiempo de espera del gestor de arranque (NVRAM)." +MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente." +MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos." +MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen" +MSG_HELP_ogRefindDeleteEntry="Borra en rEFInd las entradas para el inicio en una particion." +MSG_HELP_ogRefindDefaultEntry="Configura la entrada por defecto de rEFInd." +MSG_HELP_ogRefindOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de rEFInd." +MSG_HELP_ogRefindSetTheme="Asigna un tema al rEFInd." +MSG_HELP_ogRefindSetTimeOut="Define el tiempo (segundos) que se muestran las opciones de inicio de rEFInd." +MSG_HELP_ogRefindSetResolution="Define la resolución que usuará el thema del gestor de arranque rEFInd." +MSG_HELP_ogRefindInstall="Instala y configura el gestor rEFInd en la particion EFI" +MSG_HELP_ogRestoreAclImage="" +MSG_HELP_ogRestoreBootLoaderImage="" +MSG_HELP_ogRestoreDiskImage="Restaura una imagen de un disco completo." +MSG_HELP_ogRestoreEfiBootLoader="Copia el cargador de arranque de la partición de sistema a la partición EFI." +MSG_HELP_ogRestoreImage="Restaura una imagen de sistema operativo." +MSG_HELP_ogRestoreInfoImage="Restablece informacion del sistema: acl y enlaces simbolicos" +MSG_HELP_ogRestoreMbrImage="Restaura una imagen del sector de arranque (MBR)." +MSG_HELP_ogRestoreUuidPartitions="Restaura los uuid de las particiones y la tabla de particiones." +MSG_HELP_ogSaveImageInfo="Crea un fichero con la información de la imagen." +MSG_HELP_ogSetLinuxName="" +MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco." +MSG_HELP_ogSetPartitionId="Modifica el tipo de una partición física usando el mnemónico del tipo." +MSG_HELP_ogSetPartitionSize="Establece el tamaño de una partición." +MSG_HELP_ogSetPartitionType="Modifica el identificador de tipo de una partición física." +MSG_HELP_ogSetRegistryValue="Asigna un dato a un valor del registro de Windows." +MSG_HELP_ogSetWindowsName="Asigna el nombre del cliente en el registro de Windows." +MSG_HELP_ogSetWinlogonUser="Asigna el nombre de usuario por defecto para el gestor de entrada de Windows." +MSG_HELP_ogSyncCreate="Sincroniza los datos de la particion a la imagen" +MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la particion" +MSG_HELP_ogTorrentStart="" +MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición." +MSG_HELP_ogUcastReceiverPartition="" +MSG_HELP_ogUcastSendFile="" +MSG_HELP_ogUcastSendPartition="" +MSG_HELP_ogUcastSyntax="" +MSG_HELP_ogUnhidePartition="Hace visible una partición de Windows." +MSG_HELP_ogUninstallLinuxClient="Desinstala el cliente OpenGnSys en un sistema operativo Linux." +MSG_HELP_ogUninstallWindowsClient="Desinstala el cliente OpenGnSys en un sistema operativo Windows." +MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockDisk="Desbloquea un disco tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockPartition=$MSG_HELP_ogUnlock +MSG_HELP_ogUnmountAll="Desmonta todos los sistemas de archivos." +MSG_HELP_ogUnmountCache="Desmonta el sistema de archivos de caché local." +MSG_HELP_ogUnmount="Desmonta un sistema de archivos." +MSG_HELP_ogUnmountFs=$MSG_HELP_ogUnmount +MSG_HELP_ogUnmountImage="Desmonta la imagen" +MSG_HELP_ogUnsetDirtyBit="" +MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local." +MSG_HELP_ogUpdatePartitionTable="Actualiza informacion tabla particiones del disco" +MSG_HELP_ogUuidChange="Reemplaza el UUID de un sistema de ficheros." +MSG_HELP_ogWaitSyncImage="" +MSG_HELP_ogWindowsBootParameters="" +MSG_HELP_ogWindowsRegisterPartition="" + +# Scripts +MSG_HELP_configureOs="Post-configura de arranque del sistema" +MSG_HELP_createBaseImage="Genera imagen basica de la particion" +MSG_HELP_createDiffImage="Genera imagen diferencial de la particion respecto a la imagen basica" +MSG_HELP_installOfflineMode="Prepara el equipo cliente para el modo offline." +MSG_HELP_partclone2sync="Convierte imagen de partclone en imagen sincronizable." +MSG_HELP_restoreBaseImage="Restaura una imagen basica en una particion" +MSG_HELP_restoreDiffImage="Restaura una imagen diferencial en una particion" +MSG_HELP_updateCache="Realiza la actualizacion de la cache" + +# Mensajes de descripción breve de la interfaz. +MSG_INTERFACE_START="[START Interface] Ejecutar comando: " +MSG_INTERFACE_END="[END Interface] Comando terminado con este código: " + +# Mensajes de scripts. +MSG_SCRIPTS_START=" INICIO scripts : " +MSG_SCRIPTS_END=" FIN scripts: " +MSG_SCRIPTS_TASK_END="Fin de la tarea" + +MSG_SCRIPTS_TASK_SLEEP="Esperando para iniciar" +MSG_SCRIPTS_TASK_START="Iniciando" +MSG_SCRIPTS_TASK_ERR="Error" + +# Script createImage. +MSG_SCRIPTS_FILE_RENAME=" Renombrar fichero-imagen previo: " +MSG_SCRIPTS_CREATE_SIZE=" Calcular espacio (KB) requerido para almacenarlo y el disponible: " + +# Script updateCache. +MSG_SCRIPTS_UPDATECACHE_DOUPDATE="comprovar si es necessari actualitzar el fitxer imatge" +MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE="Comprobar que el tamaño de la cache es mayor que el fichero a descargar." +# Script updateCache: para las imágenes sincronizadas tipo dir. +MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calculamos el tamaño de la imagen." +MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Comprobamos si hay que la imagen del repositorio es mayor que la de la cache." +MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Comprobar el espacio libre de la cache y actuar según engine.cfg" + +MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesion multicast: ServidorMcast:PuertoDatos" + +# interface sustituye temporalmente al scritp restore +MSG_SCRIPTS_CHECK_ENGINE="Analizar proceso a realizar según engine.cfg" +MSG_SCRIPTS_MULTICAST_PRECHECK_PORT="Determinar puerto principal y auxiliar multicast." +MSG_SCRIPTS_MULTICAST_CHECK_PORT="Comprobar puertos de sesion y datos" +MSG_SCRIPTS_MULTICAST_REQUEST_PORT="Solicitar la apertura: " +MSG_SCRIPTS_OS_CONFIGURE="Iniciar la configuracion del sistema restaurado" + +# TIME MESSAGES +MSG_SCRIPTS_TIME_TOTAL="tiempo total del proceso" +MSG_SCRIPTS_TIME_PARTIAL="tiempo parcial del subproceso" + +# HTTPLOG +MSG_HTTPLOG_NOUSE="No apague este ordenador por favor" + +# Mensajes sincronizadas +MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario" +MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen" +MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos" +MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen" +# Mensajes sincronizadas complementarios a errores +MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen" +MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff" +MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla" + +MSG_RESTORE="Restaura la imagen en" + diff --git a/client/etc/lang.en_GB.UTF-8.conf b/client/etc/lang.en_GB.UTF-8.conf new file mode 120000 index 0000000..3e5cc89 --- /dev/null +++ b/client/etc/lang.en_GB.UTF-8.conf @@ -0,0 +1 @@ +lang.en_GB.conf \ No newline at end of file diff --git a/client/etc/lang.en_GB.conf b/client/etc/lang.en_GB.conf new file mode 100644 index 0000000..9b8469c --- /dev/null +++ b/client/etc/lang.en_GB.conf @@ -0,0 +1,385 @@ +# English language file. +#@version 1.1.0 +#@author Jose Miguel Hernandez - Universidad de Salamanca +#@date 2018-03-01 + +# Error messages. +MSG_ERR_GENERIC="Undefined unknown error" +MSG_ERR_FORMAT="Wrong execution format" +MSG_ERR_OUTOFLIMIT="Out of range or invalid value" +MSG_ERR_NOTFOUND="File or device not found" +MSG_ERR_PARTITION="Unknown or wrong partition" +MSG_ERR_LOCKED="Resource locked by exclusive use operation" +MSG_ERR_CACHE="Local cache error" +MSG_ERR_NOGPT="Current disk does not include GPT partition" +MSG_ERR_REPO="Failed when mounting images repository" +MSG_ERR_NOMSDOS="Current disk does not include MSDOS partition" +MSG_ERR_FILESYS="Unknown or unmountable file system" +MSG_ERR_NOTOS="Cannot detect or boot OS" +MSG_ERR_IMAGE="Cannot create or restore a system image" +MSG_ERR_IMAGEFILE="Image file corrupt or of other partclone version" +MSG_ERR_NOTEXEC="Non executable program or function" +MSG_ERR_NOTWRITE="Write access denied" +MSG_ERR_NOTCACHE="No client cache partition" +MSG_ERR_NOTUEFI="UEFI isn't active" +MSG_ERR_NOTBIOS="BIOS legacy isn't active" +MSG_ERR_CACHESIZE="Not enough space in local or remote cache" +MSG_ERR_REDUCEFS="Error when reducing file system" +MSG_ERR_EXTENDFS="Error when expanding file system" +MSG_ERR_IMGSIZEPARTITION="Backup error: Partition smaller than image" +MSG_ERR_UPDATECACHE="Error when running `updateCache´ command" +MSG_ERR_UCASTSYNTAXT="Error when generating Unicast transfer syntax" +MSG_ERR_UCASTSENDPARTITION="Error when sending a Unicast partition" +MSG_ERR_UCASTSENDFILE="Error when sending a Unicast file" +MSG_ERR_UCASTRECEIVERPARTITION="Error when receiving an Unicast partition" +MSG_ERR_UCASTRECEIVERFILE="Error when receiving an Unicast file" +MSG_ERR_MCASTSYNTAXT="Error when generating Multicast transfer syntax" +MSG_ERR_MCASTSENDFILE="Error when sending Multicast file" +MSG_ERR_MCASTRECEIVERFILE="Error when receiving Multicast file" +MSG_ERR_MCASTSENDPARTITION="Error when sending Multicast partition" +MSG_ERR_MCASTRECEIVERPARTITION="Error when receiving Multicast partition " +MSG_ERR_PROTOCOLJOINMASTER="Error when connecting Unicast/Multicast session to Master" +MSG_ERR_DONTFORMAT="Formatting Error" +MSG_ERR_DONTMOUNT_IMAGE="Error when mounting/reducing image" +MSG_ERR_DONTUNMOUNT_IMAGE="Error when unmounting image" +MSG_ERR_DONTSYNC_IMAGE="Unsynchronizable image" +MSG_ERR_NOTDIFFERENT="Basic image identical to partition" +MSG_ERR_SYNCHRONIZING="Synchronizing error, it may affect image creation/restoration process" + +# Warning messages. +MSG_DONTUSE="DO NOT USE" +MSG_DONTMOUNT="Unmounted file system" +MSG_DONTUNMOUNT="Cannot unmount file system or it isn't mounted" +MSG_MOUNT="File system already mounted" +MSG_MOUNTREADONLY="Read-only file system mounted" +MSG_OBSOLETE="OBSOLETE" + +# Auxiliary help messages. +MSG_64BIT="64-bit" +MSG_DISK="Disk" +MSG_ERROR="Error" +MSG_EXAMPLE="Example" +MSG_FORMAT="Format" +MSG_FUNCTION="Function" +MSG_HARDWAREINVENTORY="Hardware inventory" +MSG_IMAGE="Image" +MSG_INSTALLED="Installed" +MSG_NOCACHE="No local cache" +MSG_NOEXTENDED="No extended partition" +MSG_PARTITION="Partition" +MSG_PROTOCOL="Protocol" +MSG_RESERVEDVALUE="Reserved value" +MSG_SEE="See" +MSG_UNKNOWN="Unknown" +MSG_WARNING="Warning" + +# Boot process messages. +MSG_DETECTLVMRAID="Detecting LVM and RAID meta-devices." +MSG_ERRBOOTMODE="$MSG_ERROR: Unknown boot mode." +MSG_LAUNCHCLIENT="Launching client browser." +MSG_LOADAPI="Loading cloning-engine functions." +MSG_LOADMODULES="Loading kernel modules." +MSG_MAKELINKS="Creating symbolic links." +MSG_MOUNTREPO="Mounting repository using %s by %s mode." +MSG_OFFLINEMODE="Off-line boot mode." +MSG_OTHERSERVICES="Starting client complementary services." +MSG_POWEROFFCONF="Defining power-saving parameters." + +# Default menu messages. +MSG_BOOT="Boot" +MSG_DUPLEX="Duplex" +MSG_HOSTNAME="Hostname" +MSG_IPADDR="IP Address" +MSG_MACADDR="MAC Address" +MSG_MENUTITLE="Options menu" +MSG_POWEROFF="Shutdown computer" +MSG_SPEED="Speed" + +# API functions messages. +MSG_HELP_ogAclFilter="Draws ACL files from differential image." +MSG_HELP_ogAddCmd="Adds commands to file created by ogInstalMiniSetup." +MSG_HELP_ogAddRegistryKey="Adds new Windows registry key." +MSG_HELP_ogAddRegistryValue="Adds new Windows registry value." +MSG_HELP_ogAddToLaunchDaemon="" +MSG_HELP_ogBoot="Boots installed OS." +MSG_HELP_ogBootLoaderDeleteEntry="$MSG_DONTUSE." +MSG_HELP_ogBootLoaderHidePartitions="$MSG_DONTUSE." +MSG_HELP_ogBootMbrGeneric="" +MSG_HELP_ogBootMbrXP="" +MSG_HELP_ogBurgDefaultEntry="Sets default Burg entry." +MSG_HELP_ogBurgDeleteEntry="Deletes partition start-entries from MBR BURG." +MSG_HELP_ogBurgHidePartitions="Sets MBR Burg to hide non starting windows partitions. Allows you to select a partition that will not be hidden (e.g. for data)." +MSG_HELP_ogBurgInstallMbr="Installs BURG boot-loader on 1st HD MBR." +MSG_HELP_ogBurgOgliveDefaultEntry="Sets ogLive input as default Burg input." +MSG_HELP_ogCalculateChecksum="Calculates file checksum." +MSG_HELP_ogCalculateFullChecksum="Calculates file full checksum" +MSG_HELP_ogChangeRepo="Changes repository for remote resource: images." +MSG_HELP_ogCheckFs="Checks file system consistence." +MSG_HELP_ogCheckIpAddress="" +MSG_HELP_ogCheckProgram="" +MSG_HELP_ogCheckStringInGroup="" +MSG_HELP_ogCheckStringInReg="" +MSG_HELP_ogCheckSyncImage="Displays image contents to check it." +MSG_HELP_ogCleanLinuxDevices="" +MSG_HELP_ogCleanOs="Deletes OS unnecessary files." +MSG_HELP_ogCompareChecksumFiles="Compares if the checksums match." +MSG_HELP_ogConfigureFstab="" +MSG_HELP_ogConfigureOgagent="Sets OS new agent: OGAgent." +MSG_HELP_ogCopyFile="Copies file to another storage unit ." +MSG_HELP_ogCreateBootLoaderImage="" +MSG_HELP_ogCreateCache="Saves space for cache partition at the end of disk." +MSG_HELP_ogCreateDiskImage="Creates exact image from local disk." +MSG_HELP_ogCreateFileImage="Creates/Resizes synchronized image file." +MSG_HELP_ogCreateGptPartitions="" +MSG_HELP_ogCreateImage="Creates exact image from local installed OS." +MSG_HELP_ogCreateImageSyntax="" +MSG_HELP_ogCreateInfoImage="Creates image content information." +MSG_HELP_ogCreateMbrImage="Creates MBR image." +MSG_HELP_ogCreatePartitions="Creates disk partition table." +MSG_HELP_ogCreatePartitionTable="Creates partition table, if necessary." +MSG_HELP_ogCreateTorrent="" +MSG_HELP_ogCopyEfiBootLoader="Copy the boot loader from the EFI partition to system partition." +MSG_HELP_ogDeleteCache="Deletes local cache partition." +MSG_HELP_ogDeleteFile="Deletes file from storage." +MSG_HELP_ogDeletePartitionTable="Deletes disk table partition" +MSG_HELP_ogDeleteRegistryKey="Deletes empty Windows registry key." +MSG_HELP_ogDeleteRegistryValue="Deletes Windows registry value." +MSG_HELP_ogDeleteTree="Deletes directory tree." +MSG_HELP_ogDevToDisk="Returns disk or partition ordinal number for device file path." +MSG_HELP_ogDiskToDev="Returns device file path for disk or partition ordinal number." +MSG_HELP_ogDomainScript="" +MSG_HELP_ogEcho="Displays and log messages." +MSG_HELP_ogExecAndLog="Runs and logs command" +MSG_HELP_ogExtendFs="Expands file system size to partition maximum." +MSG_HELP_ogFindCache="Shows local cache reserved partition." +MSG_HELP_ogFixBootSector="" +MSG_HELP_ogFormatCache="Formats (clears) local cache." +MSG_HELP_ogFormat="Formats file system." +MSG_HELP_ogFormatFs=$MSG_HELP_ogFormat +MSG_HELP_ogGetArch="Returns client architecture." +MSG_HELP_ogGetCacheSize="Returns local cache partition size." +MSG_HELP_ogGetCacheSpace="Returns maximum available space that can be reserved for local cache partition." +MSG_HELP_ogGetCaller="Returns program or function which is calling to current one" +MSG_HELP_ogGetDiskSize="Returns disk size." +MSG_HELP_ogGetDiskType="Returns disk type." +MSG_HELP_ogGetFreeSize="" +MSG_HELP_ogGetFsSize="Returns file system size." +MSG_HELP_ogGetFsType="Returns file system type." +MSG_HELP_ogGetGroupDir="Returns default directory path for client group." +MSG_HELP_ogGetGroupName="Returns client group name." +MSG_HELP_ogGetHivePath="Returns full path of file from Windows registry section." +MSG_HELP_ogGetHostname="Returns local hostname." +MSG_HELP_ogGetImageCompressor="Returns image compression tool." +MSG_HELP_ogGetImageInfo="Displays monolithic image information: cloning; compressor; file system; size(KB)." +MSG_HELP_ogGetImageProgram="Returns used program to create image." +MSG_HELP_ogGetImageSize="Returns system image size." +MSG_HELP_ogGetImageType="Returns image file system." +MSG_HELP_ogGetIpAddress="Returns client IP." +MSG_HELP_ogGetLastSector="Returns last available sector from disk or partition." +MSG_HELP_ogGetMacAddress="Returns client Ethernet address." +MSG_HELP_ogGetMountImageDir="Returns mounting directory of image." +MSG_HELP_ogGetMountPoint="Returns directory of local file system mount point." +MSG_HELP_ogGetNetInterface="" +MSG_HELP_ogGetOsType="Returns installed OS type." +MSG_HELP_ogGetOsUuid="Returns OS UUID" +MSG_HELP_ogGetOsVersion="Returns OS version." +MSG_HELP_ogGetParentPath="Returns full path of OpenGnsys system file parent directory." +MSG_HELP_ogGetPartitionActive="Returns disk active partition." +MSG_HELP_ogGetPartitionId="Returns partition type ID." +MSG_HELP_ogGetPartitionSize="Returns partition size." +MSG_HELP_ogGetPartitionsNumber="Returns disk partitions number." +MSG_HELP_ogGetPartitionTableType="Returns disk partition table type." +MSG_HELP_ogGetPartitionType="Returns partition type." +MSG_HELP_ogGetPath="Returns full path of OpenGnsys system file." +MSG_HELP_ogGetRegistryValue="Returns data from Windows registry value." +MSG_HELP_ogGetRepoIp="Returns OpenGnsys Repository IP address ." +MSG_HELP_ogGetSerialNumber="Returns host serial number." +MSG_HELP_ogGetServerIp="Returns main OpenGnsys Server IP address." +MSG_HELP_ogGetSizeParameters="Returns file system data size, required space for image and if it fits in the chosen repository." +MSG_HELP_ogGetWindowsName="Returns saved client name on Windows registry." +MSG_HELP_ogGrubAddOgLive="Adds MBR grub an entry calling Opengnsys client." +MSG_HELP_ogGrubDefaultEntry="Sets GRUB default entry." +MSG_HELP_ogGrubDeleteEntry="Deletes partition start entries on MBR grub." +MSG_HELP_ogGrubHidePartitions="Sets MBR grub to hide non starting Windows partitions. Allows you to select a partition that will not be hidden (e.g. for data)." +MSG_HELP_ogGrubInstallMbr="Installs GRUB boot loader on 1st HD MBR" +MSG_HELP_ogGrubInstallPartition="Installs GRUB boot loader on BootSector" +MSG_HELP_ogGrubOgliveDefaultEntry="Sets ogLive entry as default GRUB entry." +MSG_HELP_ogGrubSecurity="Configures user and password for change the menu entries of grub." +MSG_HELP_ogGrubUefiConf="Generates the grub.cfg file of the EFI partition." +MSG_HELP_ogHelp="Shows functions help messages." +MSG_HELP_ogHidePartition="Hides Windows partition." +MSG_HELP_ogIdToType="Returns partition type identifier." +MSG_HELP_ogInstallFirstBoot="Creates file to run on first Windows boot." +MSG_HELP_ogInstallLaunchDaemon="Installs file to run on MACos boot." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallMiniSetup="Installs file to run on Windows boot." +MSG_HELP_ogInstallRunonce="Creates file to run on admin-user Windows boot." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." +MSG_HELP_ogIsFormated="Checks file system if formatted." +MSG_HELP_ogIsImageLocked="Checks image if blocked by exclusive use operation." +MSG_HELP_ogIsLocked="Checks partition or disk if blocked by exclusive use operation." +MSG_HELP_ogIsDiskLocked="Checks disk if blocked by exclusive use operation." +MSG_HELP_ogIsMounted="Checks file system if mounted." +MSG_HELP_ogIsNewerFile="Checks if one file is newer (or has been modified later) than another one." +MSG_HELP_ogIsPartitionLocked=$MSG_HELP_ogIsLocked +MSG_HELP_ogIsRepoLocked="" +MSG_HELP_ogIsSyncImage="Checks image if synchronizable." +MSG_HELP_ogIsVirtualMachine="Checks if client is a virtual machine" +MSG_HELP_ogIsWritable="Checks if mounted file system has write permissions." +MSG_HELP_ogLinuxBootParameters="Returns installed Linux boot parameters." +MSG_HELP_ogListHardwareInfo="Lists the client hardware inventory." +MSG_HELP_ogListLogicalPartitions="Lists disk logic partitions." +MSG_HELP_ogListPartitions="Lists disk partitions table." +MSG_HELP_ogListPrimaryPartitions="Lists disk primary partitions" +MSG_HELP_ogListRegistryKeys="Lists sub-keys names included on a Windows registry key." +MSG_HELP_ogListRegistryValues="Lists value names included on a Windows registry key." +MSG_HELP_ogListSoftware="Lists OS installed programs inventory." +MSG_HELP_ogLock="Blocks partition for exclusive use operation." +MSG_HELP_ogLockDisk="Blocks disk for exclusive use operation." +MSG_HELP_ogLockImage="Blocks image for exclusive use operation." +MSG_HELP_ogLockPartition=$MSG_HELP_ogLock +MSG_HELP_ogMakeChecksumFile="Stores file checksum." +MSG_HELP_ogMakeDir="Makes OpenGnsys directory." +MSG_HELP_ogMakeGroupDir="Makes group (lab) directory on repository." +MSG_HELP_ogMcastReceiverFile="" +MSG_HELP_ogMcastReceiverPartition="" +MSG_HELP_ogMcastRequest="" +MSG_HELP_ogMcastSendFile="" +MSG_HELP_ogMcastSendPartition="" +MSG_HELP_ogMcastSyntax="" +MSG_HELP_ogMountCache="Mounts cache file system." +MSG_HELP_ogMountCdrom="Mounts default optical drive." +MSG_HELP_ogMountFs=$MSG_HELP_ogMount +MSG_HELP_ogMountImage="Mounts synchronizable image" +MSG_HELP_ogMount="Mounts file system and returns mount point." +MSG_HELP_ogNvramActiveEntry="Sets active a bootloader (NVRAM) entry." +MSG_HELP_ogNvramAddEntry="Creates new entry in bootloader (NVRAM)." +MSG_HELP_ogNvramDeleteEntry="Deletes a bootloader (NVRAM) entry." +MSG_HELP_ogNvramGetCurrent="Displays the bootloader (NVRAM) entry that was started by the computer." +MSG_HELP_ogNvramGetNext="Displays the bootloader (NVRAM) entry for the boot next." +MSG_HELP_ogNvramGetOrder="Displays the bootloader (NVRAM) entries order." +MSG_HELP_ogNvramGetTimeout="Displays the bootloader (NVRAM) timeout." +MSG_HELP_ogNvramInactiveEntry="Sets inactive bootloader (NVRAM) entry." +MSG_HELP_ogNvramList="Lists bootloader (NVRAM) entries, by staring actives ones." +MSG_HELP_ogNvramPxeFirstEntry="Set the network as the NVRAM first boot." +MSG_HELP_ogNvramSetNext="Set the bootloader (NVRAM) entry for the boot next." +MSG_HELP_ogNvramSetOrder="Sets the bootloader (NVRAM) entries order." +MSG_HELP_ogNvramSetTimeout="Sets the bootloader (NVRAM) timeout." +MSG_HELP_ogRaiseError="Displays and registers error messages and returns code." +MSG_HELP_ogReduceFs="Reduces file system size to minimum." +MSG_HELP_ogReduceImage="Reduces image size." +MSG_HELP_ogRefindDeleteEntry="Deletes the menu entry of a partition in rEFInd." +MSG_HELP_ogRefindDefaultEntry="Configures default menu entry in rEFInd."" +MSG_HELP_ogRefindOgliveDefaultEntry="Configures ogLive menu entry as default menu entry in rEFInd." +MSG_HELP_ogRefindSetTheme="Configures rEFInd's theme." +MSG_HELP_ogRefindSetTimeOut="Defines the time that rEFInd shows the menu." +MSG_HELP_ogRefindSetResolution="Defines the resolucion of rEFInd's theme." +MSG_HELP_ogRefindInstall="Installs and configures rEFInd boot loader in ESP." +MSG_HELP_ogRestoreAclImage="Restores Windows ACL (Inf. must be on /tmp)." +MSG_HELP_ogRestoreBootLoaderImage="" +MSG_HELP_ogRestoreDiskImage="Restores disk image." +MSG_HELP_ogRestoreEfiBootLoader="Copy the boot loader from the system partition to the EFI partition." +MSG_HELP_ogRestoreImage="Restore OS image." +MSG_HELP_ogRestoreInfoImage="Restores system information: ACL and symbolic links" +MSG_HELP_ogRestoreMbrImage="Restores boot sector image (MBR)." +MSG_HELP_ogRestoreUuidPartitions="Restores UUID of partitions and partition table." +MSG_HELP_ogSaveImageInfo="Creates the image information file." +MSG_HELP_ogSetLinuxName="" +MSG_HELP_ogSetPartitionActive="Sets active partition number of disk." +MSG_HELP_ogSetPartitionId="Changes partition ID using mnemonic." +MSG_HELP_ogSetPartitionSize="Sets partition size." +MSG_HELP_ogSetPartitionType="Changes partition type ID." +MSG_HELP_ogSetRegistryValue="Assigns data to a Windows registry values." +MSG_HELP_ogSetWindowsName="Assigns client name to Windows registry." +MSG_HELP_ogSetWinlogonUser="Assigns Windows default user name to Windows input manager." +MSG_HELP_ogSyncCreate="Synchronizes partition data to image" +MSG_HELP_ogSyncRestore="Synchronize image data to partition" +MSG_HELP_ogTorrentStart="" +MSG_HELP_ogTypeToId="Returns the ID of partition type mnemonic." +MSG_HELP_ogUcastReceiverPartition="" +MSG_HELP_ogUcastSendFile="" +MSG_HELP_ogUcastSendPartition="" +MSG_HELP_ogUcastSyntax="" +MSG_HELP_ogUnhidePartition="Unhides Windows partition." +MSG_HELP_ogUninstallLinuxClient="Uninstalls old OpenGnSys agent from Linux OS." +MSG_HELP_ogUninstallWindowsClient="Uninstalls oldOpenGnSys agent from Windows OS." +MSG_HELP_ogUnlock="Unlocks partition after exclusive use operation." +MSG_HELP_ogUnlockDisk="Unlocks disk after exclusive use operation." +MSG_HELP_ogUnlockImage="Unlocks image after exclusive use operation." +MSG_HELP_ogUnlockPartition=$MSG_HELP_ogUnlock +MSG_HELP_ogUnmountAll="Unmounts all file systems." +MSG_HELP_ogUnmountCache="Unmounts cache file system." +MSG_HELP_ogUnmountFs=$MSG_HELP_ogUnmount +MSG_HELP_ogUnmountImage="Unmounts image" +MSG_HELP_ogUnmount="Unmounts file system." +MSG_HELP_ogUnsetDirtyBit= +MSG_HELP_ogUpdateCacheIsNecesary="Checks if necessary file update in local cache." +MSG_HELP_ogUpdatePartitionTable="Updates disk partition table info " +MSG_HELP_ogUuidChange="Replaces the filesystem UUID" +MSG_HELP_ogWaitSyncImage="" +MSG_HELP_ogWindowsBootParameters="" +MSG_HELP_ogWindowsRegisterPartition="" + +# Scripts +MSG_HELP_configureOs="Post-configure system boot" +MSG_HELP_createBaseImage="Create partition basic image" +MSG_HELP_createDiffImage="Create partition differential image from basic image" +MSG_HELP_installOfflineMode="Prepare client for off-line mode." +MSG_HELP_partclone2sync="Turn part-clone image into synchronizable image." +MSG_HELP_restoreBaseImage="Restore basic image into partition" +MSG_HELP_restoreDiffImage="Restore differential image into partition" +MSG_HELP_updateCache="Update cache" + +# INTERFACE functions messages. +MSG_INTERFACE_START="[START Interface] Run command: " +MSG_INTERFACE_END="[END Interface] Command finished with this code: " + +# SCRIPTS messages. +MSG_SCRIPTS_START=" START scripts: " +MSG_SCRIPTS_END=" END scripts: " +MSG_SCRIPTS_TASK_END="End of task" + +MSG_SCRIPTS_TASK_SLEEP="Waiting to start" +MSG_SCRIPTS_TASK_START="Starting" +MSG_SCRIPTS_TASK_ERR="Error" + +# createImage script +MSG_SCRIPTS_FILE_RENAME="Rename previous image-file: " +MSG_SCRIPTS_CREATE_SIZE="Check required and available storing space(KB): " + +# updateCache script +MSG_SCRIPTS_UPDATECACHE_DOUPDATE="Check if it is necessary to update image file" +MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE="Check if Cache size is bigger than image file size." +# Script updateCache: for dir synchronized images . +MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calculate image size." +MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Check if repository image file size is bigger than Cache size." +MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Check free Cache and apply engine.cfg" + +MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Checking Multicast Session McastServer:DataPort" + +# interface temporarily replaces restore script +MSG_SCRIPTS_CHECK_ENGINE="Analyze process to carry out according to engine.cfg" +MSG_SCRIPTS_MULTICAST_PRECHECK_PORT="Check main and auxiliary Multicast port." +MSG_SCRIPTS_MULTICAST_CHECK_PORT="Check session and data ports" +MSG_SCRIPTS_MULTICAST_REQUEST_PORT="Request Multicast port opening: " +MSG_SCRIPTS_OS_CONFIGURE="Start restored system setting" + +# TIME MESSAGES +MSG_SCRIPTS_TIME_TOTAL="Total process time" +MSG_SCRIPTS_TIME_PARTIAL="Partial sub-process time" + +# HTTPLOG +MSG_HTTPLOG_NOUSE="PLEASE DO NOT TURN OFF THIS COMPUTER" + +# Messages for synchronized images (complementary to errors) +MSG_SYNC_RESIZE="Resize image to necessary size" +MSG_SYNC_RESTORE="Get files list and download image" +MSG_SYNC_DELETE="Differential: Delete old files" +MSG_SYNC_SLEEP="Wait for mounting/reducing image" +# Messages for synchronized images (complementary to errors) +MSG_SYNC_DIFFERENTFS="Destination file system does not match image" +MSG_SYNC_EXTENSION="Image extension must be img or diff" +MSG_SYNC_NOCHECK="Image mounted by another process. Cannot verify it" + +MSG_RESTORE="Restore image on " + diff --git a/client/etc/lang.es_ES.UTF-8.conf b/client/etc/lang.es_ES.UTF-8.conf new file mode 120000 index 0000000..330cec2 --- /dev/null +++ b/client/etc/lang.es_ES.UTF-8.conf @@ -0,0 +1 @@ +lang.es_ES.conf \ No newline at end of file diff --git a/client/etc/lang.es_ES.conf b/client/etc/lang.es_ES.conf new file mode 100644 index 0000000..3129f83 --- /dev/null +++ b/client/etc/lang.es_ES.conf @@ -0,0 +1,385 @@ +# Fichero de idioma: español. +#@version 1.1.1 +#@author + + +# Mensajes de error. +MSG_ERR_GENERIC="Error imprevisto no definido" +MSG_ERR_FORMAT="Formato de ejecución incorrecto" +MSG_ERR_OUTOFLIMIT="Valor fuera de rango o no válido" +MSG_ERR_NOTFOUND="Fichero o dispositivo no encontrado" +MSG_ERR_PARTITION="Partición errónea o desconocida" +MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo" +MSG_ERR_CACHE="Error en partición de caché local" +MSG_ERR_NOGPT="El disco indicado no contiene una partición GPT" +MSG_ERR_REPO="Error al montar el repositorio de imágenes" +MSG_ERR_NOMSDOS="El disco indicado no contiene una partición MSDOS" +MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar" +MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar" +MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema" +MSG_ERR_IMAGEFILE="Archivo de imagen corrupto o de otra versión de partclone" +MSG_ERR_NOTEXEC="Programa o función no ejecutable" +MSG_ERR_NOTWRITE="No hay acceso de escritura" +MSG_ERR_NOTCACHE="No existe partición caché en el cliente" +MSG_ERR_NOTUEFI="La interfaz UEFI no está activa" +MSG_ERR_NOTBIOS="La interfaz BIOS Legacy no está activa" +MSG_ERR_CACHESIZE="El espacio de la caché local o remota no es suficiente" +MSG_ERR_REDUCEFS="Error al reducir el sistema de archivos" +MSG_ERR_EXTENDFS="Error al expandir el sistema de archivos" +MSG_ERR_IMGSIZEPARTITION="Error al restaurar: Partición mas pequeña que la imagen" +MSG_ERR_UPDATECACHE="Error al realizar el comando updateCache" +MSG_ERR_UCASTSYNTAXT="Error en la generación de sintaxis de transferenica Unicast" +MSG_ERR_UCASTSENDPARTITION="Error en envío Unicast de una partición" +MSG_ERR_UCASTSENDFILE="Error en envío Unicast de un fichero" +MSG_ERR_UCASTRECEIVERPARTITION="Error en la recepción Unicast de una partición" +MSG_ERR_UCASTRECEIVERFILE="Error en la recepción Unicast de un fichero" +MSG_ERR_MCASTSYNTAXT="Error en la generación de sintaxis de transferenica Multicast" +MSG_ERR_MCASTSENDFILE="Error en envío Multicast de un fichero" +MSG_ERR_MCASTRECEIVERFILE="Error en la recepción Multicast de un fichero" +MSG_ERR_MCASTSENDPARTITION="Error en envío Multicast de una partición" +MSG_ERR_MCASTRECEIVERPARTITION="Error en la recepción Multicast de un fichero" +MSG_ERR_PROTOCOLJOINMASTER="Error en la conexión de una sesión Unicast|Multicast con el Master" +MSG_ERR_DONTFORMAT="Error al formatear" +MSG_ERR_DONTMOUNT_IMAGE="Error al montar/reducir la imagen" +MSG_ERR_DONTUNMOUNT_IMAGE="Error al desmontar la imagen" +MSG_ERR_DONTSYNC_IMAGE="Imagen no sincronizable" +MSG_ERR_NOTDIFFERENT="No se detectan diferencias entre la imagen básica y la partición" +MSG_ERR_SYNCHRONIZING="Error al sincronizar, puede afectar la creacion|restauracion de la imagen" + +# Mensajes de avisos. +MSG_DONTMOUNT="Sistema de archivos no montado" +MSG_DONTUSE="NO USAR" +MSG_DONTUNMOUNT="El sistema de archivos no se puede desmontar o no está montado" +MSG_MOUNT="Sistema de archivos montado" +MSG_MOUNTREADONLY="Sistema de archivos montado solo de lectura" +MSG_OBSOLETE="EN DESUSO" + +# Mensajes complementarios para las ayudas. +MSG_64BIT="64 bits" +MSG_DISK="disco" +MSG_ERROR="Error" +MSG_EXAMPLE="Ejemplo" +MSG_FORMAT="Formato" +MSG_FUNCTION="Función" +MSG_HARDWAREINVENTORY="Inventario de hardware de la máquina" +MSG_IMAGE="imagen" +MSG_INSTALLED="instalado" +MSG_NOCACHE="sin caché local" +MSG_NOEXTENDED="sin partición extendida" +MSG_PARTITION="partición" +MSG_PROTOCOL="protocolo" +MSG_RESERVEDVALUE="Valor reservado" +MSG_SEE="Ver" +MSG_UNKNOWN="Desconocido" +MSG_WARNING="Aviso" + +# Mensajes del proceso de arranque. +MSG_DETECTLVMRAID="Detectar metadispositivos LVM y RAID." +MSG_ERRBOOTMODE="$MSG_ERROR: Modo de arranque desconocido." +MSG_LAUNCHCLIENT="Ejecutar cliente." +MSG_LOADAPI="Cargar funciones del motor de clonación." +MSG_LOADMODULES="Cargar módulos del kernel." +MSG_MAKELINKS="Crear enlaces simbólicos." +MSG_MOUNTREPO="Montar repositorio por %s en modo %s." +MSG_OFFLINEMODE="Modo de arranque sin conexión." +MSG_OTHERSERVICES="Iniciar servicios complementarios del cliente." +MSG_POWEROFFCONF="Definir parámetros de ahorro de energía." + +# Mensajes del menú por defecto. +MSG_BOOT="Iniciar" +MSG_DUPLEX="Dúplex" +MSG_HOSTNAME="Equipo" +MSG_IPADDR="Dirección IP" +MSG_MACADDR="Dirección MAC" +MSG_MENUTITLE="Menú de opciones" +MSG_POWEROFF="Apagar el equipo" +MSG_SPEED="Velocidad" + +# Mensajes de descripción breve de las funciones de la API. +MSG_HELP_ogAclFilter="Extrae las acl de los ficheros de la diferencial" +MSG_HELP_ogAddCmd="Añade comandos al fichero creado por la función ogInstalMiniSetup." +MSG_HELP_ogAddRegistryKey="Añade una nueva clave al registro de Windows." +MSG_HELP_ogAddRegistryValue="Añade un nuevo valor al registro de Windows." +MSG_HELP_ogAddToLaunchDaemon="" +MSG_HELP_ogBoot="Arranca un sistema operativo instalado." +MSG_HELP_ogBootLoaderDeleteEntry="$MSG_DONTUSE." +MSG_HELP_ogBootLoaderHidePartitions="$MSG_DONTUSE." +MSG_HELP_ogBootMbrGeneric="" +MSG_HELP_ogBootMbrXP="" +MSG_HELP_ogBurgDefaultEntry="Configura la entrada por defecto de Burg." +MSG_HELP_ogBurgDeleteEntry="Borra en el Burg del MBR las entradas para el inicio en una particion." +MSG_HELP_ogBurgHidePartitions="Configura el Burg del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)." +MSG_HELP_ogBurgInstallMbr="Instala el gestor de arranque BURG en el MBR del primer disco duro" +MSG_HELP_ogBurgOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de Burg." +MSG_HELP_ogCalculateChecksum="Calcula la suma de comprobación (checksum) de un fichero." +MSG_HELP_ogCalculateFullChecksum="Calcula la suma de comprobación completa de un fichero." +MSG_HELP_ogChangeRepo="Cambia el repositorio para el recurso remoto images." +MSG_HELP_ogCheckFs="Comprueba la consistencia de un sistema de archivos." +MSG_HELP_ogCheckIpAddress="" +MSG_HELP_ogCheckProgram="" +MSG_HELP_ogCheckStringInGroup="" +MSG_HELP_ogCheckStringInReg="" +MSG_HELP_ogCheckSyncImage="Muestra el contenido de la imagen para comprobarla." +MSG_HELP_ogCleanLinuxDevices="" +MSG_HELP_ogCleanOs="Elimina los archivos que no son necesarios en el sistema operativo." +MSG_HELP_ogCompareChecksumFiles="Compara si coinciden las sumas de comprobación almacenadas de 2 ficheros." +MSG_HELP_ogConfigureFstab="" +MSG_HELP_ogConfigureOgagent="Configura el nuevo agente OGAgent para sistemas operativos." +MSG_HELP_ogCopyFile="Copia un fichero a otro almacenamiento." +MSG_HELP_ogCreateBootLoaderImage="" +MSG_HELP_ogCreateCache="Reserva espacio para la partición de caché al final del disco." +MSG_HELP_ogCreateDiskImage="Genera una imagen exacta de un disco completo." +MSG_HELP_ogCreateFileImage="Crea/redimensiona el archivo de la imagen sincronizada" +MSG_HELP_ogCreateGptPartitions="" +MSG_HELP_ogCreateImage="Genera una imagen exacta de un sistema operativo instalado localmente." +MSG_HELP_ogCreateImageSyntax="" +MSG_HELP_ogCreateInfoImage="Crea información del contenido de la imagen" +MSG_HELP_ogCreateMbrImage="Genera una imagen del sector de arranque (MBR)." +MSG_HELP_ogCreatePartitions="Define la estructura de particiones de un disco." +MSG_HELP_ogCreatePartitionTable="Genera una tabla de particiones en caso de que no sea valida." +MSG_HELP_ogCreateTorrent="" +MSG_HELP_ogCopyEfiBootLoader="Copia el cargador de arranque desde la partición EFI a la de sistema." +MSG_HELP_ogDeleteCache="Elimina la partición de caché local." +MSG_HELP_ogDeleteFile="Borra un fichero de un espacio de almacenamiento." +MSG_HELP_ogDeletePartitionTable="Elimina la tabla de particiones del disco" +MSG_HELP_ogDeleteRegistryKey="Borra una clave vacía del registro de Windows." +MSG_HELP_ogDeleteRegistryValue="Borra un valor del registro de Windows." +MSG_HELP_ogDeleteTree="Borra un árbol de directorios de un espacio de almacenamiento." +MSG_HELP_ogDevToDisk="Devuelve el nº de orden de disco o de partición correspondiente al camino del fichero de dispositivo." +MSG_HELP_ogDiskToDev="Devuelve el camino del fichero de dispositivo correspondiente al nº de orden de disco o de partición." +MSG_HELP_ogDomainScript="" +MSG_HELP_ogEcho="Muestra un mensaje en pantalla y permite registrarlo en fichero de log" +MSG_HELP_ogExecAndLog="Ejecuta un comando y registra su salida en fichero de log" +MSG_HELP_ogExtendFs="Extiende el tamaño de un sistema de archivo al máximo de su partición." +MSG_HELP_ogFindCache="Indica la partición reservada para caché local." +MSG_HELP_ogFixBootSector="" +MSG_HELP_ogFormatCache="Formatea (inicia) el sistema de caché local." +MSG_HELP_ogFormat="Formatea o reformatea un sistema de archivos." +MSG_HELP_ogFormatFs=$MSG_HELP_ogFormat +MSG_HELP_ogGetArch="Devuelve el tipo de arquitectura del cliente." +MSG_HELP_ogGetCacheSize="Devuelve el tamaño de la partición de caché local." +MSG_HELP_ogGetCacheSpace="Devuelve el espacio máximo disponible que puede ser reservado para la partición de caché local." +MSG_HELP_ogGetCaller="Devuelve el programa o función que llama al actual" +MSG_HELP_ogGetDiskSize="Devuelve el tamaño del disco." +MSG_HELP_ogGetDiskType="Devuelve el mnemónico de tipo de disco." +MSG_HELP_ogGetFreeSize="" +MSG_HELP_ogGetFsSize="Devuelve el tamaño de un sistema de archivos." +MSG_HELP_ogGetFsType="Devuelve el mnemónico de tipo de sistema de archivos." +MSG_HELP_ogGetGroupDir="Devuelve el camino del directorio por defecto para el grupo del cliente." +MSG_HELP_ogGetGroupName="Devuelve el nombre del grupo al que pertenece el cliente." +MSG_HELP_ogGetHivePath="Devuelve el camino completo del fichero de una sección del registro de Windows." +MSG_HELP_ogGetHostname="Devuelve el nombre de la máquina local." +MSG_HELP_ogGetImageCompressor="Devuelve la herramienta de compresión de la imagen." +MSG_HELP_ogGetImageInfo="Muestra información sobre la imagen monolitica: clonacion:compresor:sistemaarchivos:tamañoKB." +MSG_HELP_ogGetImageProgram="Devuelve el programa usado para crear la imagen." +MSG_HELP_ogGetImageSize="Devuelve el tamaño de una imagen de sistema." +MSG_HELP_ogGetImageType="Devuelve el sistema de ficheros de la imagen." +MSG_HELP_ogGetIpAddress="Devuelve la dirección IP del cliente." +MSG_HELP_ogGetLastSector="Devuelve el último sector usable del disco o de una partición." +MSG_HELP_ogGetMacAddress="Devuelve la dirección Ethernet del cliente." +MSG_HELP_ogGetMountImageDir="Devuelve el directorio de montaje de una imagen." +MSG_HELP_ogGetMountPoint="Devuelve el directorio donde está montado un sistema de archivos local." +MSG_HELP_ogGetNetInterface="" +MSG_HELP_ogGetOsType="Devuelve el tipo de un sistema operativo instalado." +MSG_HELP_ogGetOsUuid="Devuelve el UUID de un sistema operativo" +MSG_HELP_ogGetOsVersion="Devuelve el tipo y la versión de un sistema operativo instalado." +MSG_HELP_ogGetParentPath="Devuelve el camino completo del directorio padre de un fichero de sistema OpenGnsys." +MSG_HELP_ogGetPartitionActive="Indica cual es la partición marcada como activa en un disco." +MSG_HELP_ogGetPartitionId="Devuelve el identificador de tipo de una partición." +MSG_HELP_ogGetPartitionSize="Devuelve el tamaño de una partición." +MSG_HELP_ogGetPartitionsNumber="Devuelve el número de particiones de un disco" +MSG_HELP_ogGetPartitionTableType="Devuelve el tipo de tabla de particiones del disco" +MSG_HELP_ogGetPartitionType="Devuelve el mnemónico de tipo de una partición." +MSG_HELP_ogGetPath="Devuelve el camino completo de un fichero de sistema OpenGnsys." +MSG_HELP_ogGetRegistryValue="Devuelve el dato de un valor del registro de Windows." +MSG_HELP_ogGetRepoIp="Devuelve la dirección IP del repositorio de datos." +MSG_HELP_ogGetSerialNumber="Devuelve el número de serie del equipo" +MSG_HELP_ogGetServerIp="Devuelve la dirección IP del servidor principal." +MSG_HELP_ogGetSizeParameters="Devuelve el tamaño de los datos de un sistema de ficheros, el espacio necesario para la imagen y si cabe en el repositorio elegido." +MSG_HELP_ogGetWindowsName="Devuelve el nombre del cliente guardado en el registro de Windows." +MSG_HELP_ogGrubAddOgLive="Incluye en el grub del MBR una entrada llamando al cliente de opengnsys." +MSG_HELP_ogGrubDefaultEntry="Configura la entrada por defecto de GRUB." +MSG_HELP_ogGrubDeleteEntry="Borra en el grub del MBR las entradas para el inicio en una particion." +MSG_HELP_ogGrubHidePartitions="Configura el grub del MBR para que oculte las particiones de windows que no se esten iniciando. Permite definir una partición que no se ocultará (ej: para datos)." +MSG_HELP_ogGrubInstallMbr="Instala el gestor de arranque GRUB en el MBR del primer disco duro" +MSG_HELP_ogGrubInstallPartition="Instala el gestor de arranque GRUB en el BootSector" +MSG_HELP_ogGrubOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de GRUB." +MSG_HELP_ogGrubSecurity="Configura usuario y clave para modificar las entradas del menu del Grub." +MSG_HELP_ogGrubUefiConf="Genera el fichero grub.cfg de la partición EFI." +MSG_HELP_ogHelp="Muestra mensajes de ayudas para las funciones." +MSG_HELP_ogHidePartition="Oculta una partición de Windows." +MSG_HELP_ogIdToType="Devuelve el mnemónico asociado al identificador de tipo de partición." +MSG_HELP_ogInstallFirstBoot="Crea un archivo que se ejecutará en el primer arranque de Windows." +MSG_HELP_ogInstallLaunchDaemon="Instala un archivo que se ejecutará en el arranque de macOS." +MSG_HELP_ogInstallLinuxClient="$MSG_OBSOLETE." +MSG_HELP_ogInstallMiniSetup="Instala un archivo que se ejecutará en el arranque de Windows." +MSG_HELP_ogInstallRunonce="Crea archivo que se ejecutará en el inicio de un usuario administrador de Windows." +MSG_HELP_ogInstallWindowsClient="$MSG_OBSOLETE." +MSG_HELP_ogIsFormated="Comprueba si un sistema de archivos está formateado." +MSG_HELP_ogIsImageLocked="Comprueba si una imagen está bloqueada por una operación de uso exclusivo." +MSG_HELP_ogIsLocked="Comprueba si una partición o su disco están bloqueados por una operación de uso exclusivo." +MSG_HELP_ogIsDiskLocked="Comprueba si un disco está bloqueado por una operación de uso exclusivo." +MSG_HELP_ogIsMounted="Comprueba si un sistema de archivos está montado." +MSG_HELP_ogIsNewerFile="Comprueba si un fichero es más nuevo (se ha modificado después) que otro." +MSG_HELP_ogIsPartitionLocked=$MSG_HELP_ogIsLocked +MSG_HELP_ogIsRepoLocked="" +MSG_HELP_ogIsSyncImage="Comprueba si la imagen es sincronizable." +MSG_HELP_ogIsVirtualMachine="Comprueba si el cliente es una máquina virtual" +MSG_HELP_ogIsWritable="Comprueba si un sistema de archivos está montado con permiso de escritura." +MSG_HELP_ogLinuxBootParameters="Devuelve los parámetros de arranque de un sistema operativo Linux instalado." +MSG_HELP_ogListHardwareInfo="Lista el inventario de dispositivos del cliente." +MSG_HELP_ogListLogicalPartitions="Lista las particiones lógicas de un disco" +MSG_HELP_ogListPartitions="Lista la estructura de particiones de un disco." +MSG_HELP_ogListPrimaryPartitions="Lista las particiones primarias de un disco" +MSG_HELP_ogListRegistryKeys="Lista los nombres de las subclaves incluidas en una clave del registro de Windows." +MSG_HELP_ogListRegistryValues="Lista los nombres de los valores incluidos en una clave del registro de Windows." +MSG_HELP_ogListSoftware="Lista el inventario de programas instalados en un sistema operativo." +MSG_HELP_ogLock="Bloquea una partición para operación de uso exclusivo." +MSG_HELP_ogLockDisk="Bloquea un disco para operación de uso exclusivo." +MSG_HELP_ogLockImage="Bloquea una imagen para operación de uso exclusivo." +MSG_HELP_ogLockPartition=$MSG_HELP_ogLock +MSG_HELP_ogMakeChecksumFile="Almacena la suma de comprobación de un fichero." +MSG_HELP_ogMakeDir="Crea un directorio para OpenGnsys." +MSG_HELP_ogMakeGroupDir="Crea el directorio de grupo (aula) en un repositorio." +MSG_HELP_ogMcastReceiverFile="" +MSG_HELP_ogMcastReceiverPartition="" +MSG_HELP_ogMcastRequest="" +MSG_HELP_ogMcastSendFile="" +MSG_HELP_ogMcastSendPartition="" +MSG_HELP_ogMcastSyntax="" +MSG_HELP_ogMountCache="Monta el sistema de archivos dedicado a caché local." +MSG_HELP_ogMountCdrom="Monta dispositivo óptico por defecto." +MSG_HELP_ogMountFs=$MSG_HELP_ogMount +MSG_HELP_ogMountImage="Monta una imagen sincronizable" +MSG_HELP_ogMount="Monta un sistema de archivos y devuelve el punto de montaje." +MSG_HELP_ogNvramActiveEntry="Configura a activa entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramAddEntry="Crea nueva entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramDeleteEntry="Borra entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramGetCurrent="Muestra la entrada del gestor de arranque (NVRAM) que ha iniciado el equipo." +MSG_HELP_ogNvramGetNext="Muestra la entrada del gestor de arranque (NVRAM) que se utilizará en el próximo arranque." +MSG_HELP_ogNvramGetOrder="Muestra el orden de las entradas del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramGetTimeout="Muestra el tiempo de espera del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramInactiveEntry="Configura a inactiva entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramList="Lista las entradas del gestor de arranque (NVRAN) marcando con un asterisco las activas" +MSG_HELP_ogNvramPxeFirstEntry="Configura la tarjeta de red como primer arranque en la NVRAM." +MSG_HELP_ogNvramSetNext="Configura el próximo arranque con la entrada del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramSetOrder="Configura el orden de las entradas del gestor de arranque (NVRAM)." +MSG_HELP_ogNvramSetTimeout="Configura el tiempo de espera del gestor de arranque (NVRAM)." +MSG_HELP_ogRaiseError="Muestra y registra mensajes de error y devuelve el código correspondiente." +MSG_HELP_ogReduceFs="Reduce el tamaño del sistema de archivos al mínimo ocupado por sus datos." +MSG_HELP_ogReduceImage="Reduce el tamaño de la imagen" +MSG_HELP_ogRefindDeleteEntry="Borra en rEFInd las entradas para el inicio en una particion." +MSG_HELP_ogRefindDefaultEntry="Configura la entrada por defecto de rEFInd." +MSG_HELP_ogRefindOgliveDefaultEntry="Configura la entrada de ogLive como la entrada por defecto de rEFInd." +MSG_HELP_ogRefindSetTheme="Asigna un tema al rEFInd." +MSG_HELP_ogRefindSetTimeOut="Define el tiempo (segundos) que se muestran las opciones de inicio de rEFInd." +MSG_HELP_ogRefindSetResolution="Define la resolución que usuará el thema del gestor de arranque rEFInd." +MSG_HELP_ogRefindInstall="Instala y configura el gestor rEFInd en la particion EFI" +MSG_HELP_ogRestoreAclImage="Restaura las ACL de Windows (La informacion debe estar copiada en /tmp)." +MSG_HELP_ogRestoreBootLoaderImage="" +MSG_HELP_ogRestoreDiskImage="Restaura una imagen de un disco completo." +MSG_HELP_ogRestoreEfiBootLoader="Copia el cargador de arranque de la partición de sistema a la partición EFI." +MSG_HELP_ogRestoreImage="Restaura una imagen de sistema operativo." +MSG_HELP_ogRestoreInfoImage="Restablece información del sistema: ACL y enlaces simbolicos" +MSG_HELP_ogRestoreMbrImage="Restaura una imagen del sector de arranque (MBR)." +MSG_HELP_ogRestoreUuidPartitions="Restaura los uuid de las particiones y la tabla de particiones." +MSG_HELP_ogSaveImageInfo="Crea un fichero con la información de la imagen." +MSG_HELP_ogSetLinuxName="" +MSG_HELP_ogSetPartitionActive="Establece el número de partición activa de un disco." +MSG_HELP_ogSetPartitionId="Modifica el tipo de una partición física usando el mnemónico del tipo." +MSG_HELP_ogSetPartitionSize="Establece el tamaño de una partición." +MSG_HELP_ogSetPartitionType="Modifica el identificador de tipo de una partición física." +MSG_HELP_ogSetRegistryValue="Asigna un dato a un valor del registro de Windows." +MSG_HELP_ogSetWindowsName="Asigna el nombre del cliente en el registro de Windows." +MSG_HELP_ogSetWinlogonUser="Asigna el nombre de usuario por defecto para el gestor de entrada de Windows." +MSG_HELP_ogSyncCreate="Sincroniza los datos de la partición a la imagen" +MSG_HELP_ogSyncRestore="Sincroniza los datos de la imagen a la partición" +MSG_HELP_ogTorrentStart="" +MSG_HELP_ogTypeToId="Devuelve el identificador asociado al mnemónico de tipo de partición." +MSG_HELP_ogUcastReceiverPartition="" +MSG_HELP_ogUcastSendFile="" +MSG_HELP_ogUcastSendPartition="" +MSG_HELP_ogUcastSyntax="" +MSG_HELP_ogUnhidePartition="Hace visible una partición de Windows." +MSG_HELP_ogUninstallLinuxClient="Desinstala el antiguo cliente OpenGnSys en un sistema operativo Linux." +MSG_HELP_ogUninstallWindowsClient="Desinstala el antiguo cliente OpenGnSys en un sistema operativo Windows." +MSG_HELP_ogUnlock="Desbloquea una partición tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockDisk="Desbloquea un disco tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockImage="Desbloquea una imagen tras finalizar una operación de uso exclusivo." +MSG_HELP_ogUnlockPartition=$MSG_HELP_ogUnlock +MSG_HELP_ogUnmountAll="Desmonta todos los sistemas de archivos." +MSG_HELP_ogUnmountCache="Desmonta el sistema de archivos de caché local." +MSG_HELP_ogUnmount="Desmonta un sistema de archivos." +MSG_HELP_ogUnmountFs=$MSG_HELP_ogUnmount +MSG_HELP_ogUnmountImage="Desmonta la imagen." +MSG_HELP_ogUnsetDirtyBit="" +MSG_HELP_ogUpdateCacheIsNecesary="Comprueba si es necesario actualizar una archivo en la cache local." +MSG_HELP_ogUpdatePartitionTable="Actualiza información de la tabla de particiones del disco." +MSG_HELP_ogUuidChange="Reemplaza el UUID de un sistema de ficheros." +MSG_HELP_ogWaitSyncImage="" +MSG_HELP_ogWindowsBootParameters="" +MSG_HELP_ogWindowsRegisterPartition="" + +# Scripts +MSG_HELP_configureOs="Post-configura de arranque del sistema" +MSG_HELP_createBaseImage="Genera imagen básica de la partición" +MSG_HELP_createDiffImage="Genera imagen diferencial de la partición respecto a la imagen básica" +MSG_HELP_installOfflineMode="Prepara el equipo cliente para el modo offline." +MSG_HELP_partclone2sync="Convierte imagen de partclone en imagen sincronizable." +MSG_HELP_restoreBaseImage="Restaura una imagen básica en una partición" +MSG_HELP_restoreDiffImage="Restaura una imagen diferencial en una partición" +MSG_HELP_updateCache="Realiza la actualización de la caché" + +# Mensajes de descripción breve de la interfaz. +MSG_INTERFACE_START="[START Interface] Ejecutar comando: " +MSG_INTERFACE_END="[END Interface] Comando terminado con este código: " + +# Mensajes de scripts. +MSG_SCRIPTS_START=" INICIO scripts: " +MSG_SCRIPTS_END=" FIN scripts: " +MSG_SCRIPTS_TASK_END="Fin de la tarea" + +MSG_SCRIPTS_TASK_SLEEP="Esperando para iniciar" +MSG_SCRIPTS_TASK_START="Iniciando" +MSG_SCRIPTS_TASK_ERR="Error" + +# Script createImage. +MSG_SCRIPTS_FILE_RENAME=" Renombrar fichero-imagen previo: " +MSG_SCRIPTS_CREATE_SIZE=" Calcular espacio (KB) requerido para almacenarlo y el disponible: " + +# Script updateCache. +MSG_SCRIPTS_UPDATECACHE_DOUPDATE="Comprobar si es necesario actualizar el fichero imagen " +MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE="Comprobar que el tamaño de la caché es mayor que el fichero a descargar." +# Script updateCache: para las imágenes sincronizadas tipo dir. +MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calcular el tamaño de la imagen." +MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Comprobar si la imagen del repositorio es mayor que la de la caché." +MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Comprobar el espacio libre de la caché y actuar según engine.cfg" + +MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesión Multicast: ServidorMcast:PuertoDatos" + +# interface sustituye temporalmente al scritp restore +MSG_SCRIPTS_CHECK_ENGINE="Analizar proceso a realizar según engine.cfg" +MSG_SCRIPTS_MULTICAST_PRECHECK_PORT="Determinar puerto principal y auxiliar Multicast." +MSG_SCRIPTS_MULTICAST_CHECK_PORT="Comprobar puertos de sesión y datos" +MSG_SCRIPTS_MULTICAST_REQUEST_PORT="Solicitar la apertura: " +MSG_SCRIPTS_OS_CONFIGURE="Iniciar la configuración del sistema restaurado" + +# TIME MESSAGES +MSG_SCRIPTS_TIME_TOTAL="tiempo total del proceso" +MSG_SCRIPTS_TIME_PARTIAL="tiempo parcial del subproceso" + +# HTTPLOG +MSG_HTTPLOG_NOUSE="No apague este ordenador por favor" + +# Mensajes sincronizadas +MSG_SYNC_RESIZE="Redimensiona la imagen al tamaño necesario" +MSG_SYNC_RESTORE="Trae el listado ficheros y baja la imagen" +MSG_SYNC_DELETE="Diferencial: Borra archivos antiguos" +MSG_SYNC_SLEEP="Espera que se monte/reduzca la imagen" +# Mensajes sincronizadas complementarios a errores +MSG_SYNC_DIFFERENTFS="El sistema de ficheros de destino no coincide con el de la imagen" +MSG_SYNC_EXTENSION="Las extensiones de la imagenes deben ser img o diff" +MSG_SYNC_NOCHECK="La imagen esta montada por otro proceso, no podemos comprobarla" + +MSG_RESTORE="Restaura la imagen en" + diff --git a/client/etc/preinit/NetLib.py b/client/etc/preinit/NetLib.py deleted file mode 100755 index 40e7fa9..0000000 --- a/client/etc/preinit/NetLib.py +++ /dev/null @@ -1,254 +0,0 @@ -import subprocess -import sys -import os - -from engine.FileLib import * -from engine.SystemLib import * - -def ogChangeRepo(): - SRCIMG = "" - NEWREPO = "" - REPO = "" - OGUNIT = "" - - if len(sys.argv) < 2: - print("Usage: ogChangeRepo IPREPO [ OgUnit ]") - print("Example: ogChangeRepo 10.1.120.3") - print("Example: ogChangeRepo 10.1.120.3 cdc") - return - - if sys.argv[1] == "help": - print("Usage: ogChangeRepo IPREPO [ OgUnit ]") - print("Example: ogChangeRepo 10.1.120.3") - print("Example: ogChangeRepo 10.1.120.3 cdc") - return - - if len(sys.argv) >= 2: - NEWREPO = sys.argv[1] - - # Opciones de montaje: lectura o escritura - subprocess.run(["mount", "|", "grep", "ogimages.*rw,"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - RW = ",rw" if subprocess.returncode == 0 else ",ro" - - # Si REPO tomamos el repositorio y la unidad organizativa actual - REPO = ogGetRepoIp() - OGUNIT = subprocess.run(["df", "|", "awk", "-F", " ", "'/ogimages/ {sub(\"//.*/ogimages\",\"\",$1); sub(\"/\",\"\",$1); print $1}'"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip() - - # Parametros de entrada. Si $1 = "REPO" dejo el repositorio actual - if sys.argv[1].upper() == "REPO": - NEWREPO = REPO - - # Si $1 y $2 son el repositorio y la OU actual me salgo - if NEWREPO == REPO and sys.argv[2] == OGUNIT: - return 0 - - subprocess.run(["source", "/scripts/functions"], shell=True) - subprocess.run(["source", "/scripts/ogfunctions"], shell=True) - subprocess.run(["umount", OGIMG]) - - if sys.argv[2] == "": - SRCIMG = "ogimages" - else: - SRCIMG = "ogimages/" + sys.argv[2] - - subprocess.run(["eval", "$(grep \"OPTIONS=\" /scripts/ogfunctions)"]) - - ogEcho("session", "log", MSG_HELP_ogChangeRepo + " " + NEWREPO + " " + sys.argv[2].rstrip()) - ogConnect(NEWREPO, ogprotocol, SRCIMG, OGIMG, RW) - - # Si da error volvemos a montar el inicial - if subprocess.returncode != 0: - ogConnect(REPO, ogprotocol, SRCIMG, OGIMG, RW) - ogRaiseError("session", OG_ERR_REPO, NEWREPO) - return subprocess.returncode - -def ogGetGroupDir(): - REPO = "" - DIR = "" - GROUP = "" - - if len(sys.argv) < 2: - ogHelp("ogGetGroupDir", "ogGetGroupDir str_repo", "ogGetGroupDir REPO ==> /opt/opengnsys/images/groups/Grupo1") - return - - if len(sys.argv) == 1: - REPO = "REPO" - else: - REPO = sys.argv[1] - - GROUP = ogGetGroupName() - if GROUP: - DIR = ogGetPath(REPO, "/groups/" + GROUP, stderr=subprocess.DEVNULL) - if os.path.isdir(DIR): - print(DIR) - - return 0 - -def ogGetGroupName(): - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetGroupName", "ogGetGroupName", "ogGetGroupName => Grupo1") - return - - if "group" in globals() and group: - print(group) - - return 0 - -def ogGetHostname(): - HOST = "" - - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetHostname", "ogGetHostname", "ogGetHostname => pc1") - return - - # Tomar nombre de la variable HOSTNAME - HOST = os.getenv("HOSTNAME") - - # Si no, tomar del DHCP, opción host-name - if not HOST: - with open("/var/lib/dhcp3/dhclient.leases", "r") as f: - for line in f: - if "option host-name" in line: - HOST = line.split('"')[1] - break - - # Si no, leer el parámetro del kernel hostname - if not HOST: - with open("/proc/cmdline", "r") as f: - cmdline = f.read() - HOST = re.search(r"hostname=([^ ]+)", cmdline) - if HOST: - HOST = HOST.group(1) - - if HOSTNAME != HOST: - os.environ["HOSTNAME"] = HOST - - if HOST: - print(HOST) - -def ogGetIpAddress(): - IP = "" - - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetIpAddress", "ogGetIpAddress", "ogGetIpAddress => 192.168.0.10") - return - - if "IPV4ADDR" in os.environ: - IP = os.environ["IPV4ADDR"] - else: - # Obtener direcciones IP. - if "DEVICE" in os.environ: - IP = subprocess.run(["ip", "-o", "address", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split() - else: - IP = subprocess.run(["ip", "-o", "address", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split() - - IP = [addr.split("/")[0] for addr in IP if "inet" in addr] - - # Mostrar solo la primera. - if IP: - print(IP[0]) - - return 0 - -def ogGetMacAddress(): - MAC = "" - - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetMacAddress", "ogGetMacAddress", "ogGetMacAddress => 00:11:22:33:44:55") - return - - # Obtener direcciones Ethernet. - if "DEVICE" in os.environ: - MAC = subprocess.run(["ip", "-o", "link", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split() - MAC = [addr.upper() for addr in MAC if "ether" in addr] - else: - MAC = subprocess.run(["ip", "-o", "link", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split() - MAC = [addr.upper() for addr in MAC if "ether" in addr and "lo" not in addr] - - # Mostrar solo la primera. - if MAC: - print(MAC[0]) - - return 0 - -def ogGetNetInterface(): - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetNetInterface", "ogGetNetInterface", "ogGetNetInterface => eth0") - return - - if "DEVICE" in os.environ: - print(os.environ["DEVICE"]) - - return 0 - -def ogGetRepoIp(): - # Variables locales. - SOURCE = "" - FSTYPE = "" - - # Mostrar ayuda. - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetRepoIp", "ogGetRepoIp", "ogGetRepoIp => 192.168.0.2") - return - - # Obtener direcciones IP, según el tipo de montaje. - output = subprocess.run(["findmnt", "-P", "-o", "SOURCE,FSTYPE", OGIMG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip() - lines = output.split("\n") - for line in lines: - fields = line.split() - if len(fields) == 2: - if fields[1] == "nfs": - SOURCE = fields[0].split(":")[0] - elif fields[1] == "cifs": - SOURCE = fields[0].split("/")[2] - - if SOURCE: - print(SOURCE) - - return 0 - -def ogGetServerIp(): - # Variables locales. - SOURCE = "" - FSTYPE = "" - - # Mostrar ayuda. - if len(sys.argv) >= 2 and sys.argv[1] == "help": - ogHelp("ogGetServerIp", "ogGetServerIp", "ogGetServerIp => 192.168.0.2") - return - - # Obtener direcciones IP, según el tipo de montaje. - output = subprocess.run(["findmnt", "-P", "-o", "SOURCE,FSTYPE", OGIMG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip() - lines = output.split("\n") - for line in lines: - fields = line.split() - if len(fields) == 2: - if fields[1] == "nfs": - SOURCE = fields[0].split(":")[0] - elif fields[1] == "cifs": - SOURCE = fields[0].split("/")[2] - - if SOURCE: - print(SOURCE) - - return 0 - -def ogMakeGroupDir(): - REPO = "" - DIR = "" - GROUP = "" - - if len(sys.argv) < 2: - ogHelp("ogMakeGroupDir", "ogMakeGroupDir str_repo", "ogMakeGroupDir", "ogMakeGroupDir REPO") - return - - if len(sys.argv) == 1: - REPO = "REPO" - else: - REPO = sys.argv[1] - - DIR = ogGetPath(REPO, "/groups/" + ogGetGroupName(), stderr=subprocess.DEVNULL) - if DIR: - subprocess.run(["mkdir", "-p", DIR], stderr=subprocess.DEVNULL) - - return 0 diff --git a/client/etc/preinit/default.py b/client/etc/preinit/default.py deleted file mode 100644 index 7914407..0000000 --- a/client/etc/preinit/default.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -import subprocess - -print (">>>>>>>>>>>>>>>>>>>> Load ", __name__, " <<<<<<<<<<<<<<<<<<<<<<") - -print("==============================================") -print("OpenGnsys Clonning Engine Start...") -# Cargar entorno de OpenGnsys -#os.environ['OGETC'] = '/opt/opengnsys/etc' #Entorno opengnsys -os.environ['OGETC'] = 'etc' #Pruebas locales -print (f"OGETC: {os.environ['OGETC']}") - -os.environ['PYTHONUNBUFFERED'] = '1' -print (f"PYTHONUNBUFFERED: {os.environ['PYTHONUNBUFFERED']}") - -#loadenviron_path = os.path.join(os.environ['OGETC'], 'preinit', 'loadenviron.sh') -loadenviron_path = os.path.join(os.environ['OGETC'], 'preinit', 'loadenviron.py') -print (f"loadenviron_path: {loadenviron_path}") -print ("s//////////////////////////////////////////////////") -# Ejecutar el script y cargar las variables de entorno en Python -exec(open(loadenviron_path).read()) - -# Configurar las variables de entorno globales -for key, value in globals().items(): - if isinstance(value, str): - os.environ[key] = value - -print ("Variables de entorno cargadas desde loadenviron.py") - -# Ejecutar un subproceso que utilizará las nuevas variables de entorno -################################################################################subprocess.run(['bash', '-c', 'env'], shell=True) -# Scripts de inicio -print ("step 2.1 >>>>>>>>>>>>>>>>>>>>>>>>>>") -scripts = ['fileslinks', 'loadmodules', 'metadevs', 'mountrepo', 'poweroff', 'otherservices'] -for script in scripts: - script_path = os.path.join(os.environ['OGETC'], 'preinit', f'{script}.py') - print (f"<<<<<< script_path: {script_path}") - #subprocess.run(['bash', script_path]) - subprocess.run(['python3', script_path]) - -print ("step 2.2 >>>>>>>>>>>>>>>>>>>>>>>>>>") -# Check and run the appropriate init script -init_scripts = [ - os.path.join(os.environ['OGETC'], 'init', f'{os.environ.get("IPV4ADDR", "")}.sh'), - os.path.join(os.environ['OGETC'], 'init', f'{os.environ.get("OGGROUP", "")}.sh'), - os.path.join(os.environ['OGETC'], 'init', 'default.sh') -] - -print ("step 2.3 >>>>>>>>>>>>>>>>>>>>>>>>>>") -for script in init_scripts: - if os.path.isfile(script): - subprocess.run(['bash', script]) - break -else: - print("No se ha encontrado script de inicio (RUN halt)") - #subprocess.run(['halt']) - -print("OpenGnsys Clonning Engine End.") -print("==============================================") diff --git a/client/etc/preinit/default.sh b/client/etc/preinit/default.sh new file mode 100755 index 0000000..e5d1d0b --- /dev/null +++ b/client/etc/preinit/default.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# Cargar entorno de OpenGnsys +set -a +source /opt/opengnsys/etc/preinit/loadenviron.sh + +# Scripts de inicio. +for f in fileslinks loadmodules metadevs mountrepo poweroff otherservices; do + $OGETC/preinit/$f.sh +done +unset f + +if [ -f $OGETC/init/$IPV4ADDR.sh ]; then + $OGETC/init/$OG_IP.sh + +elif [ -f $OGETC/init/$OGGROUP.sh ]; then + $OGETC/init/$OGGROUP.sh + +elif [ -f $OGETC/init/default.sh ]; then + $OGETC/init/default.sh + +else + echo "No se ha encontrado script de inicio" + halt +fi diff --git a/client/etc/preinit/fileslinks.py b/client/etc/preinit/fileslinks.py deleted file mode 100644 index 527dfd8..0000000 --- a/client/etc/preinit/fileslinks.py +++ /dev/null @@ -1,74 +0,0 @@ -import os -import shutil -import stat - -# Si está configurado OpenGnsys ... -if os.getenv("OPENGNSYS"): - print(os.getenv("MSG_MAKELINKS", ".")) - - # Shell BASH por defecto (para usar "runtest") - try: - os.symlink('/bin/bash', '/bin/sh') - except FileExistsError: - pass - - # Crear directorio de bloqueos - os.makedirs('/var/lock', exist_ok=True) - if not os.path.exists('/var/lock'): - os.makedirs('/run/lock', exist_ok=True) - - # Crear ficheros temporales. - oglogcommand = os.getenv("OGLOGCOMMAND") - oglogsession = os.getenv("OGLOGSESSION") - temp_files = [oglogcommand, f"{oglogcommand}.tmp", oglogsession, "/tmp/menu.tmp"] - for temp_file in temp_files: - with open(temp_file, 'a'): - os.utime(temp_file, None) - os.chmod(temp_file, 0o777) -##################################################################################### -##### Pendiente instalar Qt5 en el sistema y crear enlaces simbólicos a las librerías - # Enlaces para Qt Embeded. ###################################################### - qtdir = "/usr/local" - os.makedirs(os.path.join(qtdir, 'etc'), exist_ok=True) - os.makedirs(os.path.join(qtdir, 'lib'), exist_ok=True) - os.makedirs(os.path.join(qtdir, 'plugins'), exist_ok=True) - - oglib = os.getenv("OGLIB") - for i in os.listdir(os.path.join(oglib, 'qtlib')) + [os.path.join(oglib, 'fonts')]: - src = os.path.join(oglib, 'qtlib', i) - dst = os.path.join(qtdir, 'lib', i) - if not os.path.exists(dst): - try: - os.symlink(src, dst) - except FileExistsError: - pass - - for i in os.listdir(os.path.join(oglib, 'qtplugins')): - src = os.path.join(oglib, 'qtplugins', i) - dst = os.path.join(qtdir, 'plugins', i) - if not os.path.exists(dst): - try: - os.symlink(src, dst) - except FileExistsError: - pass - - ogetc = os.getenv("OGETC") - for i in os.listdir(ogetc): - if i.endswith('.qmap'): - src = os.path.join(ogetc, i) - dst = os.path.join(qtdir, 'etc', i) - if not os.path.exists(dst): - try: - os.symlink(src, dst) - except FileExistsError: - pass - - # Autenticación con clave pública para SSH - if os.path.isfile('/scripts/ssl/authorized_keys'): - for file in os.listdir('/scripts/ssl'): - shutil.copy(os.path.join('/scripts/ssl', file), '/root/.ssh') - -else: - # FIXME Error: entorno de OpenGnsys no configurado. - print("Error: OpenGnsys environment is not configured.") # FIXME: definir mensaje. - exit(1) \ No newline at end of file diff --git a/client/etc/preinit/fileslinks.sh b/client/etc/preinit/fileslinks.sh new file mode 100755 index 0000000..826282d --- /dev/null +++ b/client/etc/preinit/fileslinks.sh @@ -0,0 +1,53 @@ +#!/bin/bash +#/** +#@file fileslinks.sh +#@brief Script de inicio para copiar ficheros y deinir enlaces simbólicos. +#@warning License: GNU GPLv3+ +#@version 0.9 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2009-10-10 +#@version 1.0.5 - Enlace para librería libmac (obsoleto en versión 1.1.1). +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2012-06-28 +#@version 1.1.2 - Autenticación con clave pública para SSH +#@author Irina Gómez, ETSII Universidad de Sevilla +#@date 2019-09-25 +#*/ + + +# Si está configurado OpenGnsys ... +if [ -n "$OPENGNSYS" ]; then + echo "${MSG_MAKELINKS:-.}" + + # Shell BASH por defecto (para usar "runtest") + ln -fs /bin/bash /bin/sh 2>/dev/null + + # Crear directorio de bloqueos + mkdir -p /var/lock 2>/dev/null || mkdir -p /run/lock + + # Crear ficheros temporales. + touch $OGLOGCOMMAND $OGLOGCOMMAND.tmp $OGLOGSESSION /tmp/menu.tmp + chmod 777 $OGLOGCOMMAND $OGLOGCOMMAND.tmp $OGLOGSESSION /tmp/menu.tmp + + # Enlaces para Qt Embeded. + QTDIR="/usr/local" + mkdir -p $QTDIR/{etc,lib,plugins} + for i in $OGLIB/qtlib/* $OGLIB/fonts; do + [ -f $QTDIR/lib/$i ] || ln -fs $i $QTDIR/lib 2>/dev/null + done + for i in $OGLIB/qtplugins/*; do + [ -f $QTDIR/plugins/$i ] || ln -fs $i $QTDIR/plugins 2>/dev/null + done + for i in $OGETC/*.qmap; do + [ -f $QTDIR/etc/$i ] || ln -fs $i $QTDIR/etc 2>/dev/null + done + + # Autenticación con clave pública para SSH + [ -f /scripts/ssl/authorized_keys ] && cp /scripts/ssl/* /root/.ssh + +else + # FIXME Error: entorno de OpenGnsys no configurado. + echo "Error: OpenGnsys environment is not configured." # FIXME: definir mensaje. + exit 1 +fi + diff --git a/client/etc/preinit/loadenviron.py b/client/etc/preinit/loadenviron.py deleted file mode 100644 index 6ea85b9..0000000 --- a/client/etc/preinit/loadenviron.py +++ /dev/null @@ -1,215 +0,0 @@ -import os -import subprocess -import sys - -sys.path.append('/opt/opengnsys/client/lib/engine/bin') -from NetLib import * - -print(f"##################+++++++++++++++ {sys.path} ++++++++++++++################3") -print(" ") -print("=============== path =================") -print("-- step 0") -print(sys.path) -#!/usr/bin/env python3 - -# Cargar API de funciones. -def execute_lib_file(filepath): - with open(filepath) as f: - code = compile(f.read(), filepath, 'exec') - exec(code, globals()) - -print("=============== START LOAD ENVIRONMENT =================") -# Idioma por defecto. -os.environ["LANG"] = os.getenv("LANG", "es_ES") - -print("-- step 2") -os.environ["LC_ALL"] = os.getenv("LC_ALL", os.environ["LANG"]) - -print("-- step 3") -result = subprocess.run(["locale-gen", os.environ["LANG"]], capture_output=True, text=True) -if result.returncode != 0: - print(f"Error generating locale: {result.stderr}") - -print("-- step 4") -print("-- step 5") - -# Directorios del proyecto OpenGnsys. -os.environ["OPENGNSYS"] = os.getenv("OPENGNSYS", "/opt/opengnsys") - -opengnsys_path = os.environ['OPENGNSYS'] -print(f"OPENGNSYS Directory: {opengnsys_path}") - -print("-- step 6") - -print (f"OPENGNSYS: {os.environ['OPENGNSYS']}") - -if os.path.isdir(os.environ["OPENGNSYS"]): - print("OPENGNSYS directory found") - os.environ["OGBIN"] = os.path.join(os.environ["OPENGNSYS"], "bin") - os.environ["OGETC"] = os.path.join(os.environ["OPENGNSYS"], "etc") - os.environ["OGLIB"] = os.path.join(os.environ["OPENGNSYS"], "lib") - os.environ["OGAPI"] = os.path.join(os.environ["OGLIB"], "engine", "bin") - os.environ["OGSCRIPTS"] = os.path.join(os.environ["OPENGNSYS"], "scripts") - os.environ["OGIMG"] = os.path.join(os.environ["OPENGNSYS"], "images") - os.environ["OGCAC"] = os.path.join(os.environ["OPENGNSYS"], "cache") - os.environ["OGLOG"] = os.path.join(os.environ["OPENGNSYS"], "log") - - os.environ["PATH"] = os.pathsep.join([ - os.environ["PATH"], - "/sbin", - "/usr/sbin", - "/usr/local/sbin", - "/bin", - "/usr/bin", - "/usr/local/bin", - "/opt/oglive/rootfs/opt/drbl/sbin", - os.environ["OGSCRIPTS"], - os.environ["OGAPI"], - os.environ["OGBIN"] - ]) - print("-- step 7") - # Exportar parámetros del kernel. - with open("/proc/cmdline") as f: - for i in f.read().split(): - if "=" in i: - key, value = i.split("=", 1) - os.environ[key] = value - - print("-- step 8") - # Cargar fichero de idioma. - lang_file = os.path.join(os.environ["OGETC"], f"lang.{os.environ['LANG'].split('@')[0]}.conf") - if os.path.isfile(lang_file): - with open(lang_file) as f: - for line in f: - if "=" in line: - key, value = line.strip().split("=", 1) - os.environ[key] = value - print("-- step 9") - # Mensaje de carga del entorno. - print(os.getenv("MSG_LOADAPI", ".")) - - print("-- step 10") - # Cargar mapa de teclado. - subprocess.run(["loadkeys", os.environ["LANG"].split("_")[0]], stdout=subprocess.DEVNULL) - - - print("-- step 10.1") - # Imprimir todas las variables de entorno declaradas hasta el momento. - for key, value in os.environ.items(): - print(f"{key}: {value}") - - - print("-- step 11") - for lib_file in os.listdir(os.environ["OGAPI"]): - if lib_file.endswith(".lib"): - execute_lib_file(os.path.join(os.environ["OGAPI"], lib_file)) - - - -# for lib_file in os.listdir(os.environ["OGAPI"]): -# if lib_file.endswith(".lib"): -# exec(open(os.path.join(os.environ["OGAPI"], lib_file)).read()) - - print("-- step 12") - # Cargar configuración del engine. - engine_cfg = os.path.join(os.environ["OGETC"], "engine.cfg") - if os.path.isfile(engine_cfg): - exec(open(engine_cfg).read()) - os.environ["OGLOGCOMMAND"] = os.getenv("OGLOGCOMMAND", "/tmp/command.log") - os.environ["OGLOGSESSION"] = os.getenv("OGLOGSESSION", "/tmp/session.log") - - - print("-- step 13") - # Cargar las APIs según engine. - ogengine = os.getenv("ogengine") - if ogengine: - for api_file in os.listdir(os.environ["OGAPI"]): - if api_file.endswith(f".{ogengine}"): - exec(open(os.path.join(os.environ["OGAPI"], api_file)).read()) - - print("-- step 14") - # Configuración de la red (modo offline). - initrd_cfg = "/tmp/initrd.cfg" - if os.path.isfile(initrd_cfg): - with open(initrd_cfg) as f: - for line in f: - if line.startswith("DEVICECFG="): - device_cfg = line.strip().split("=", 1)[1] - os.environ["DEVICECFG"] = device_cfg - if os.path.isfile(device_cfg): - exec(open(device_cfg).read()) - - print("-- step 15") - # FIXME Pruebas para grupos de ordenadores - os.environ["OGGROUP"] = os.getenv("group", "") - - print("-- step 16") - root_repo = os.getenv("ROOTREPO", os.getenv("OGSERVERIMAGES")) - - print(f"-- step 17",ogGetIpAddress()) - # Fichero de registros. - og_log_file = os.path.join(os.environ["OGLOG"], f"{ogGetIpAddress()}.log") - os.environ["OGLOGFILE"] = og_log_file -else: - print("ERROR: OPENGNSYS directory not found") - -print("-- step 18") -# Compatibilidad para usar proxy en clientes ogLive. -if not os.getenv("http_proxy") and os.getenv("ogproxy"): - os.environ["http_proxy"] = os.getenv("ogproxy") - -print("-- step 19") -# Compatibilidad para usar servidor DNS en clientes ogLive. -if not os.path.isfile("/run/resolvconf/resolv.conf") and os.getenv("ogdns"): - os.makedirs("/run/resolvconf", exist_ok=True) - with open("/run/resolvconf/resolv.conf", "w") as f: - f.write(f"nameserver {os.getenv('ogdns')}\n") - -print("-- step 20") -# Declaración de códigos de error. -error_codes = { - "OG_ERR_FORMAT": 1, - "OG_ERR_NOTFOUND": 2, - "OG_ERR_PARTITION": 3, - "OG_ERR_LOCKED": 4, - "OG_ERR_IMAGE": 5, - "OG_ERR_NOTOS": 6, - "OG_ERR_NOTEXEC": 7, - "OG_ERR_NOTWRITE": 14, - "OG_ERR_NOTCACHE": 15, - "OG_ERR_CACHESIZE": 16, - "OG_ERR_REDUCEFS": 17, - "OG_ERR_EXTENDFS": 18, - "OG_ERR_OUTOFLIMIT": 19, - "OG_ERR_FILESYS": 20, - "OG_ERR_CACHE": 21, - "OG_ERR_NOGPT": 22, - "OG_ERR_REPO": 23, - "OG_ERR_NOMSDOS": 24, - "OG_ERR_IMGSIZEPARTITION": 30, - "OG_ERR_UPDATECACHE": 31, - "OG_ERR_DONTFORMAT": 32, - "OG_ERR_IMAGEFILE": 33, - "OG_ERR_GENERIC": 40, - "OG_ERR_UCASTSYNTAXT": 50, - "OG_ERR_UCASTSENDPARTITION": 51, - "OG_ERR_UCASTSENDFILE": 52, - "OG_ERR_UCASTRECEIVERPARTITION": 53, - "OG_ERR_UCASTRECEIVERFILE": 54, - "OG_ERR_MCASTSYNTAXT": 55, - "OG_ERR_MCASTSENDFILE": 56, - "OG_ERR_MCASTRECEIVERFILE": 57, - "OG_ERR_MCASTSENDPARTITION": 58, - "OG_ERR_MCASTRECEIVERPARTITION": 59, - "OG_ERR_PROTOCOLJOINMASTER": 60, - "OG_ERR_DONTMOUNT_IMAGE": 70, - "OG_ERR_DONTSYNC_IMAGE": 71, - "OG_ERR_DONTUNMOUNT_IMAGE": 72, - "OG_ERR_NOTDIFFERENT": 73, - "OG_ERR_SYNCHRONIZING": 74, - "OG_ERR_NOTUEFI": 80, - "OG_ERR_NOTBIOS": 81 -} -print("-- step 20") -for key, value in error_codes.items(): - os.environ[key] = str(value) diff --git a/client/etc/preinit/loadenviron.sh b/client/etc/preinit/loadenviron.sh new file mode 100755 index 0000000..0884404 --- /dev/null +++ b/client/etc/preinit/loadenviron.sh @@ -0,0 +1,151 @@ +#!/bin/bash +#/** +#@file loadenviron.sh +#@brief Script de carga de la API de funciones de OpenGnsys. +#@warning License: GNU GPLv3+ +#@version 0.9 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2009-10-10 +#@version 1.0.3 - Limpiar código y configuración modo off-line +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2012-01-12 +#@version 1.0.5 - Compatibilidad para usar proxy y servidor DNS. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2014-04-23 +#*/ + +# Idioma por defecto. +export LANG="${LANG:-es_ES}" +locale-gen $LANG + +# Directorios del proyecto OpenGnsys. +export OPENGNSYS="${OPENGNSYS:-/opt/opengnsys}" +if [ -d $OPENGNSYS ]; then + export OGBIN=$OPENGNSYS/bin + export OGETC=$OPENGNSYS/etc + export OGLIB=$OPENGNSYS/lib + export OGAPI=$OGLIB/engine/bin + export OGPYFUNCS=$OPENGNSYS/functions + export OGSCRIPTS=$OPENGNSYS/scripts + export OGIMG=$OPENGNSYS/images + export OGCAC=$OPENGNSYS/cache + export OGLOG=$OPENGNSYS/log + + export PATH=$PATH:/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin:/opt/oglive/rootfs/opt/drbl/sbin + export PATH=$OGSCRIPTS:$OGPYFUNCS:$PATH:$OGBIN + export PYTHONPATH=$OPENGNSYS/lib/python3 + + # Exportar parámetros del kernel. + for i in $(cat /proc/cmdline); do + echo $i | grep -q "=" && export $i + done + + # Cargar sysctls + sysctl -p &>/dev/null + + # Cargar fichero de idioma. + LANGFILE=$OGETC/lang.${LANG%@*}.conf + if [ -f $LANGFILE ]; then + source $LANGFILE + for i in $(awk -F= '{if (NF==2) print $1}' $LANGFILE); do + export $i + done + fi + # Mensaje de carga del entorno. + echo "${MSG_LOADAPI:-.}" + + # Cargar mapa de teclado. + loadkeys ${LANG%_*} >/dev/null + + # Cargar API de funciones. + for i in $OGAPI/*.lib; do + source $i + done + + for i in $(typeset -F | cut -f3 -d" "); do + export -f $i + done + + # Cargar configuración del engine. + [ -f ${OGETC}/engine.cfg ] && source ${OGETC}/engine.cfg + export OGLOGCOMMAND=${OGLOGCOMMAND:-/tmp/command.log} + export OGLOGSESSION=${OGLOGSESSION:-/tmp/session.log} + + # Cargar las APIs según engine. + if [ -n "$ogengine" ]; then + for i in $OGAPI/*.$ogengine; do + [ -f $i ] && source $i + done + fi + + # Configuración de la red (modo offline). + eval $(grep "^DEVICECFG=" /tmp/initrd.cfg 2>/dev/null) + if [ -n "$DEVICECFG" ]; then + export DEVICECFG + [ -f $DEVICECFG ] && source $DEVICECFG + fi + + # FIXME Pruebas para grupos de ordenadores + export OGGROUP="$group" + + ROOTREPO=${ROOTREPO:-"$OGSERVERIMAGES"} + + # Fichero de registros. + export OGLOGFILE="$OGLOG/$(ogGetIpAddress).log" +fi + +# Compatibilidad para usar proxy en clientes ogLive. +[ -z "$http_proxy" -a -n "$ogproxy" ] && export http_proxy="$ogproxy" + +# Compatibilidad para usar servidor DNS en clientes ogLive. +if [ ! -f /run/resolvconf/resolv.conf -a -n "$ogdns" ]; then + mkdir -p /run/resolvconf + echo "nameserver $ogdns" > /run/resolvconf/resolv.conf +fi + +# Declaración de códigos de error. +export OG_ERR_FORMAT=1 # Formato de ejecución incorrecto. +export OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado. +export OG_ERR_PARTITION=3 # Error en partición de disco. +export OG_ERR_LOCKED=4 # Partición o fichero bloqueado. +export OG_ERR_IMAGE=5 # Error al crear o restaurar una imagen. +export OG_ERR_NOTOS=6 # Sin sistema operativo. +export OG_ERR_NOTEXEC=7 # Programa o función no ejecutable. +# Códigos 8-13 reservados por ogAdmClient.h +export OG_ERR_NOTWRITE=14 # No hay acceso de escritura +export OG_ERR_NOTCACHE=15 # No hay particion cache en cliente +export OG_ERR_CACHESIZE=16 # No hay espacio en la cache para almacenar fichero-imagen +export OG_ERR_REDUCEFS=17 # Error al reducir sistema archivos +export OG_ERR_EXTENDFS=18 # Error al expandir el sistema de archivos +export OG_ERR_OUTOFLIMIT=19 # Valor fuera de rango o no válido. +export OG_ERR_FILESYS=20 # Sistema de archivos desconocido o no se puede montar +export OG_ERR_CACHE=21 # Error en partición de caché local +export OG_ERR_NOGPT=22 # El disco indicado no contiene una particion GPT +export OG_ERR_REPO=23 # Error al montar el repositorio de imagenes +export OG_ERR_NOMSDOS=24 # El disco indicado no contienen una particion MSDOS + +export OG_ERR_IMGSIZEPARTITION=30 # Error al restaurar partición más pequeña que la imagen +export OG_ERR_UPDATECACHE=31 # Error al realizar el comando updateCache +export OG_ERR_DONTFORMAT=32 # Error al formatear +export OG_ERR_IMAGEFILE=33 # Archivo de imagen corrupto o de otra versión de $IMGPROG +export OG_ERR_GENERIC=40 # Error imprevisto no definido +export OG_ERR_UCASTSYNTAXT=50 # Error en la generación de sintaxis de transferenica UNICAST +export OG_ERR_UCASTSENDPARTITION=51 # Error en envío UNICAST de partición +export OG_ERR_UCASTSENDFILE=52 # Error en envío UNICAST de un fichero +export OG_ERR_UCASTRECEIVERPARTITION=53 # Error en la recepcion UNICAST de una particion +export OG_ERR_UCASTRECEIVERFILE=54 # Error en la recepcion UNICAST de un fichero +export OG_ERR_MCASTSYNTAXT=55 # Error en la generacion de sintaxis de transferenica Multicast. +export OG_ERR_MCASTSENDFILE=56 # Error en envio MULTICAST de un fichero +export OG_ERR_MCASTRECEIVERFILE=57 # Error en la recepcion MULTICAST de un fichero +export OG_ERR_MCASTSENDPARTITION=58 # Error en envio MULTICAST de una particion +export OG_ERR_MCASTRECEIVERPARTITION=59 # Error en la recepcion MULTICAST de una particion +export OG_ERR_PROTOCOLJOINMASTER=60 # Error en la conexion de una sesion UNICAST|MULTICAST con el MASTER + +export OG_ERR_DONTMOUNT_IMAGE=70 # Error al montar una imagen sincronizada. +export OG_ERR_DONTSYNC_IMAGE=71 # Imagen no sincronizable (es monolitica) +export OG_ERR_DONTUNMOUNT_IMAGE=72 # Error al desmontar la imagen +export OG_ERR_NOTDIFFERENT=73 # No se detectan diferencias entre la imagen basica y la particion. +export OG_ERR_SYNCHRONIZING=74 # Error al sincronizar, puede afectar la creacion/restauracion de la imagen + +export OG_ERR_NOTUEFI=80 # La interfaz UEFI no está activa +export OG_ERR_NOTBIOS=81 # La interfaz BIOS legacy no está activa diff --git a/client/etc/preinit/loadmodules.py b/client/etc/preinit/loadmodules.py deleted file mode 100644 index bae5ec7..0000000 --- a/client/etc/preinit/loadmodules.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python3 - -import os -import subprocess -import glob - -""" -@file loadmodules.py -@brief Script de inicio para cargar módulos complementarios del kernel. -@version 1.0.5 - Cargar módulos específicos para el cliente. -""" - - -def main(): - msg_loadmodules = os.getenv('MSG_LOADMODULES', '.') - print(msg_loadmodules) - - # Módulo del ratón. - subprocess.run(['modprobe', 'psmouse'], stderr=subprocess.DEVNULL) - - # Cargar módulos específicos del kernel del cliente. - kernel_version = os.uname().release - module_path = os.path.join(os.getenv('OGLIB', ''), 'modules', kernel_version, '*.ko') - for module in glob.glob(module_path): - if os.access(module, os.R_OK): - subprocess.run(['insmod', module], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/client/etc/preinit/loadmodules.sh b/client/etc/preinit/loadmodules.sh new file mode 100755 index 0000000..ded3539 --- /dev/null +++ b/client/etc/preinit/loadmodules.sh @@ -0,0 +1,23 @@ +#!/bin/bash +#/** +#@file loadmodules.sh +#@brief Script de inicio para cargar módulos complementarios del kernel. +#@version 1.0 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2010-01-26 +#@version 1.0.5 - Cargar módulos específicos para el cliente. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2013-11-11 +#*/ + + +echo "${MSG_LOADMODULES:-.}" + +# Módulo del ratón. +modprobe psmouse 2>/dev/null + +# Cargar módulos específicos del kernel del cliente. +for m in $OGLIB/modules/$(uname -r)/*.ko; do + [ -r $m ] && insmod $m &>/dev/null +done + diff --git a/client/etc/preinit/metadevs.py b/client/etc/preinit/metadevs.py deleted file mode 100644 index 3d433a6..0000000 --- a/client/etc/preinit/metadevs.py +++ /dev/null @@ -1,32 +0,0 @@ -import os -import subprocess -import sys - -#!/usr/bin/env python3 -""" -@file metadevs.py -@brief Script de inicio para detectar metadispositivos LVM y RAID. -@note Desglose del script "loadenviron.sh". -@warning License: GNU GPLv3+ -""" - -def main(): - opengnsys = os.getenv('OPENGNSYS') - print(f"____________________________________ OpenGnsys environment: {opengnsys}") - msg_detectlvmraid = os.getenv('MSG_DETECTLVMRAID', '') - - print(f"____________________________________ Message: {msg_detectlvmraid}") - - if opengnsys: - print(msg_detectlvmraid) - # Detectar metadispositivos LVM. - subprocess.run(['vgchange', '-ay'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - # Detectar metadispositivos RAID. - subprocess.run(['dmraid', '-ay'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - else: - # FIXME Error: entorno de OpenGnsys no configurado. - print("Error: OpenGnsys environment is not configured.") # FIXME: definir mensaje. - sys.exit(1) - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/client/etc/preinit/metadevs.sh b/client/etc/preinit/metadevs.sh new file mode 100755 index 0000000..e2454c5 --- /dev/null +++ b/client/etc/preinit/metadevs.sh @@ -0,0 +1,28 @@ +#!/bin/bash +#/** +#@file metadevs.sh +#@brief Script de inicio para detectar metadispositivos LVM y RAID. +#@note Desglose del script "loadenviron.sh". +#@warning License: GNU GPLv3+ +#@version 0.9 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2009-10-10 +#@version 0.9.4 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2010-04-19 +#*/ + + +# Si está configurado OpenGnsys ... +if [ -n "$OPENGNSYS" ]; then + echo "$MSG_DETECTLVMRAID" + # Detectar metadispositivos LVM. + vgchange -ay &>/dev/null + # Detectar metadispositivos RAID. + dmraid -ay &>/dev/null +else + # FIXME Error: entorno de OpenGnsys no configurado. + echo "Error: OpenGnsys environment is not configured." # FIXME: definir mensaje. + exit 1 +fi + diff --git a/client/etc/preinit/mountrepo.py b/client/etc/preinit/mountrepo.py deleted file mode 100644 index 488c6ad..0000000 --- a/client/etc/preinit/mountrepo.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python3 - -import os -import subprocess - -#/** -# @file mountrepo.py -# @brief Script para montar el repositorio de datos remoto. -#*/ - -OGIMG = os.getenv('OGIMG', '/opt/opengnsys/images') -ROOTREPO = os.getenv('ROOTREPO', os.getenv('ROOTSERVER')) -ogactiveadmin = os.getenv('ogactiveadmin') -ogprotocol = os.getenv('ogprotocol', 'smb') -ogunit = os.getenv('ogunit', '') -ogstatus = os.getenv('ogstatus') -SERVER = os.getenv('SERVER') -OGCAC = os.getenv('OGCAC') -MSG_MOUNTREPO = "Mounting repository using protocol: {} in mode: {}" - -def mount_repo(): - if ogactiveadmin == "true": - os.environ['boot'] = 'admin' # ATENCIÓN: siempre en modo "admin". - subprocess.run(['umount', OGIMG], stderr=subprocess.DEVNULL) - - protocol = ogprotocol - OGUNIT = f"/{ogunit}" if ogunit else "" - print(MSG_MOUNTREPO.format(protocol, 'admin')) - - if protocol == 'nfs': - subprocess.run(['mount.nfs', f'{ROOTREPO}:{OGIMG}{OGUNIT}', OGIMG, '-o', 'rw,nolock']) - elif protocol == 'smb': - PASS = get_password() - subprocess.run(['mount.cifs', f'//{ROOTREPO}/ogimages{OGUNIT}', OGIMG, '-o', f'rw,serverino,acl,username=opengnsys,password={PASS}']) - elif protocol == 'local': - handle_local_mount() - -def get_password(): - try: - with open('/scripts/ogfunctions') as f: - for line in f: - if 'OPTIONS=' in line: - return line.split('pass=')[1].split()[0] - except Exception: - pass - return 'og' - -def handle_local_mount(): - if ogstatus == "offline" or not SERVER: - TYPE = subprocess.getoutput("blkid | grep REPO | awk -F'TYPE=' '{print $2}' | tr -d '\"'") - if not TYPE: - if os.path.isdir(f'{OGCAC}/{OGIMG}'): - subprocess.run(['mount', '--bind', f'{OGCAC}/{OGIMG}', OGIMG]) - else: - subprocess.run(['mount', '-t', TYPE, 'LABEL=REPO', OGIMG], stderr=subprocess.DEVNULL) - else: - if subprocess.run(['smbclient', '-L', SERVER, '-N'], stderr=subprocess.DEVNULL).returncode == 0: - PASS = get_password() - subprocess.run(['mount.cifs', f'//{ROOTREPO}/ogimages', OGIMG, '-o', f'rw,serverino,acl,username=opengnsys,password={PASS}']) - -if __name__ == "__main__": - mount_repo() \ No newline at end of file diff --git a/client/etc/preinit/mountrepo.sh b/client/etc/preinit/mountrepo.sh new file mode 100755 index 0000000..e1c18fe --- /dev/null +++ b/client/etc/preinit/mountrepo.sh @@ -0,0 +1,54 @@ +#!/bin/bash +#/** +#@file mountrepo.sh +#@brief Script para montar el repositorio de datos remoto. +#@warning License: GNU GPLv3+ +#@version 1.0 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2011-03-17 +#*/ + +OGIMG=${OGIMG:-/opt/opengnsys/images} +ROOTREPO=${ROOTREPO:-"$ROOTSERVER"} + +# TODO Revisar proceso de arranque para no montar 2 veces el repositorio. +if [ "$ogactiveadmin" == "true" ]; then + export boot=admin # ATENCIÓN: siempre en modo "admin". + umount $OGIMG 2>/dev/null + + protocol=${ogprotocol:-"smb"} + [ "$ogunit" != "" ] && OGUNIT="/$ogunit" + printf "$MSG_MOUNTREPO\n" "$protocol" "$boot" + case "$ogprotocol" in + nfs) mount.nfs ${ROOTREPO}:$OGIMG$OGUNIT $OGIMG -o rw,nolock ;; + smb) PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ + sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') + PASS=${PASS:-"og"} + mount.cifs //${ROOTREPO}/ogimages$OGUNIT $OGIMG -o rw,serverino,acl,username=opengnsys,password=$PASS + ;; + local) # TODO: hacer funcion dentro de este script que monte smb + # Comprobamos que estatus sea online. + if [ "$ogstatus" == "offline" -o "$SERVER" == "" ]; then + # Si estatus es offline buscamos un dispositivo con etiqueta repo + # y si no existe montamos la cache como repo (si existe). + TYPE=$(blkid | grep REPO | awk -F"TYPE=" '{print $2}' | tr -d \") + if [ "$TYPE" == "" ]; then + [ -d $OGCAC/$OGIMG ] && mount --bind $OGCAC/$OGIMG $OGIMG + else + mount -t $TYPE LABEL=REPO $OGIMG &>/dev/null + fi + else + # Comprobamos que existe un servicio de samba. + smbclient -L $SERVER -N &>/dev/null + if [ $? -eq 0 ]; then + PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ + sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') + PASS=${PASS:-"og"} + mount.cifs //${ROOTREPO}/ogimages $OGIMG -o rw,serverino,acl,username=opengnsys,password=$PASS + fi + # TODO: buscar condicion para NFS + fi + ;; + esac +fi + diff --git a/client/etc/preinit/otherservices.py b/client/etc/preinit/otherservices.py deleted file mode 100644 index 30f7a6d..0000000 --- a/client/etc/preinit/otherservices.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3 - -import os -import subprocess - -""" -@file otherservices.py -@brief Script de inicio para cargar otros servicios complementarios. -""" - -# Lanzar servicios complementarios del cliente. -print(os.getenv('MSG_OTHERSERVICES', '.')) - -# Iniciar rsyslog, si es necesario. -if not os.path.exists('/dev/log'): - subprocess.run(['service', 'rsyslog', 'start']) - -# Adpatar la clave de "root" para acceso SSH. -with open('/scripts/ogfunctions', 'r') as file: - for line in file: - if 'OPTIONS=' in line: - pass_option = line.split('pass=')[1].split()[0] - break - else: - pass_option = 'og' - -passwd = pass_option or 'og' -subprocess.run(['passwd', 'root'], input=f'{passwd}\n{passwd}\n', text=True) - -# Cargar el entorno OpenGnsys en conexión SSH. -subprocess.run(['cp', '-a', f'{os.getenv("OPENGNSYS")}/etc/preinit/loadenviron.py', '/etc/profile.d/']) - -# Arrancar SSH. -subprocess.run(['/etc/init.d/ssh', 'start'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - -# Desactivado apagado de monitor. -# subprocess.run(['setterm', '-blank', '0', '-powersave', 'off', '-powerdown', '0'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - -# Activado WOL en la interfaz usada en arranque PXE. -subprocess.run(['ethtool', '-s', os.getenv('DEVICE'), 'wol', 'g'], stderr=subprocess.DEVNULL) - -# TODO Localizar correctamente el script de arranque. -if os.path.isfile('/opt/opengnsys/scripts/runhttplog.sh'): - subprocess.run(['/opt/opengnsys/scripts/runhttplog.sh'], stderr=subprocess.DEVNULL) \ No newline at end of file diff --git a/client/etc/preinit/otherservices.sh b/client/etc/preinit/otherservices.sh new file mode 100755 index 0000000..2bd011b --- /dev/null +++ b/client/etc/preinit/otherservices.sh @@ -0,0 +1,38 @@ +#!/bin/bash +#/** +#@file otherservices.sh +#@brief Script de inicio para cargar otros servicios complementarios. +#@version 1.0.3 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2012-01-12 +#*/ + +# Montar efivar filesystem +isEfiActive && mount -t efivarfs none /sys/firmware/efi/efivars + +# Lanzar servicios complementarios del cliente. +echo "${MSG_OTHERSERVICES:-.}" + +# Iniciar rsyslog, si es necesario. +[ -S /dev/log ] || service rsyslog start + +# Adpatar la clave de "root" para acceso SSH. +PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ + sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') +PASS=${PASS:-"og"} +echo -ne "$PASS\n$PASS\n" | passwd root 2>/dev/null +# Cargar el entorno OpenGnsys en conexión SSH. +cp -a $OPENGNSYS/etc/preinit/loadenviron.sh /etc/profile.d/ +# Arrancar SSH. +/etc/init.d/ssh start &>/dev/null + +# Desactivado apagado de monitor. +#setterm -blank 0 -powersave off -powerdown 0 < /dev/console > /dev/console 2>&1 + +# Activado WOL en la interfaz usada en arranque PXE. +ethtool -s $DEVICE wol g 2>/dev/null + +# TODO Localizar correctamente el script de arranque. +[ -f /opt/opengnsys/scripts/runhttplog.sh ] && /opt/opengnsys/scripts/runhttplog.sh 2>/dev/null + + diff --git a/client/etc/preinit/poweroff.py b/client/etc/preinit/poweroff.py deleted file mode 100644 index 8b372dd..0000000 --- a/client/etc/preinit/poweroff.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python3 - -import os -import subprocess -import sys - -""" -@file poweroff.py -@brief Script de inicio para cargar el proceso comprobación de clientes inactivos. -@note Arranca y configura el proceso "cron". -""" - -def main(): - opengnsys = os.getenv('OPENGNSYS') - if opengnsys: - msg_poweroffconf = os.getenv('MSG_POWEROFFCONF', '.') - print(msg_poweroffconf) - - ogntp = os.getenv('ogntp') - status = os.getenv('status') - - # Sincronización horaria con servidor NTP. - if ogntp and status != "offline": - subprocess.run(['ntpdate', ogntp]) - - # Crear fichero de configuración por defecto (30 min. de espera). - poweroff_conf = '/etc/poweroff.conf' - with open(poweroff_conf, 'w') as f: - f.write("POWEROFFSLEEP=30\nPOWEROFFTIME=\n") - - # Incluir zona horaria en el fichero de configuración. - with open('/proc/cmdline') as f: - cmdline = f.read() - tz = ' '.join([x for x in cmdline.split() if x.startswith('TZ=')]) - with open(poweroff_conf, 'a') as f: - f.write(tz + '\n') - - # Lanzar el proceso "cron". - subprocess.run(['cron', '-l']) - - # Definir la "crontab" lanzando el proceso de comprobación cada minuto. - ogbin = os.getenv('OGBIN') - crontab_line = f"* * * * * [ -x {ogbin}/poweroffconf ] && {ogbin}/poweroffconf\n" - subprocess.run(['crontab', '-'], input=crontab_line, text=True) - - else: - # FIXME Error: entorno de OpenGnsys no configurado. - print("Error: OpenGnsys environment is not configured.") # FIXME: definir mensaje. - sys.exit(1) - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/client/etc/preinit/poweroff.sh b/client/etc/preinit/poweroff.sh new file mode 100755 index 0000000..f5f9f98 --- /dev/null +++ b/client/etc/preinit/poweroff.sh @@ -0,0 +1,40 @@ +#!/bin/bash +#/** +#@file poweroff.sh +#@brief Script de inicio para cargar el proceso comprobación de clientes inactivos. +#@note Arranca y configura el proceso "cron". +#@warning License: GNU GPLv3+ +#@version 1.0.2 +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2011-10-25 +#*/ + + +# Si está configurado OpenGnsys ... +if [ -n "$OPENGNSYS" ]; then + echo "${MSG_POWEROFFCONF:-.}" + + # Sincronización horaria con servidor NTP. + [ -n "$ogntp" -a "$status" != "offline" ] && ntpdate $ogntp + + # Crear fichero de configuración por defecto (30 min. de espera). + POWEROFFCONF=/etc/poweroff.conf + cat << FIN > $POWEROFFCONF +POWEROFFSLEEP=30 +POWEROFFTIME= +FIN + # Incluir zona horaria en el fichero de configuración. + awk 'BEGIN {RS=" "} /^TZ=/ {print}' /proc/cmdline >> $POWEROFFCONF + + # Lanzar el proceso "cron". + cron -l + + # Definir la "crontab" lanzando el proceso de comprobación cada minuto. + echo "* * * * * [ -x $OGBIN/poweroffconf ] && $OGBIN/poweroffconf" | crontab - + +else + # FIXME Error: entorno de OpenGnsys no configurado. + echo "Error: OpenGnsys environment is not configured." # FIXME: definir mensaje. + exit 1 +fi + diff --git a/client/shared/functions/ogAddCmd b/client/functions/ogAddCmd similarity index 100% rename from client/shared/functions/ogAddCmd rename to client/functions/ogAddCmd diff --git a/client/shared/functions/ogAddRegistryKey b/client/functions/ogAddRegistryKey similarity index 100% rename from client/shared/functions/ogAddRegistryKey rename to client/functions/ogAddRegistryKey diff --git a/client/shared/functions/ogAddRegistryValue b/client/functions/ogAddRegistryValue similarity index 100% rename from client/shared/functions/ogAddRegistryValue rename to client/functions/ogAddRegistryValue diff --git a/client/shared/functions/ogCalculateChecksum b/client/functions/ogCalculateChecksum similarity index 100% rename from client/shared/functions/ogCalculateChecksum rename to client/functions/ogCalculateChecksum diff --git a/client/shared/functions/ogCalculateFullChecksum b/client/functions/ogCalculateFullChecksum similarity index 100% rename from client/shared/functions/ogCalculateFullChecksum rename to client/functions/ogCalculateFullChecksum diff --git a/client/shared/functions/ogChangeRepo b/client/functions/ogChangeRepo similarity index 100% rename from client/shared/functions/ogChangeRepo rename to client/functions/ogChangeRepo diff --git a/client/shared/functions/ogCheckFs b/client/functions/ogCheckFs similarity index 100% rename from client/shared/functions/ogCheckFs rename to client/functions/ogCheckFs diff --git a/client/shared/functions/ogCheckIpAddress b/client/functions/ogCheckIpAddress similarity index 100% rename from client/shared/functions/ogCheckIpAddress rename to client/functions/ogCheckIpAddress diff --git a/client/shared/functions/ogCleanLinuxDevices b/client/functions/ogCleanLinuxDevices similarity index 100% rename from client/shared/functions/ogCleanLinuxDevices rename to client/functions/ogCleanLinuxDevices diff --git a/client/shared/functions/ogCleanOs b/client/functions/ogCleanOs similarity index 100% rename from client/shared/functions/ogCleanOs rename to client/functions/ogCleanOs diff --git a/client/shared/functions/ogConfigureFstab b/client/functions/ogConfigureFstab similarity index 100% rename from client/shared/functions/ogConfigureFstab rename to client/functions/ogConfigureFstab diff --git a/client/shared/functions/ogConfigureOgagent b/client/functions/ogConfigureOgagent similarity index 100% rename from client/shared/functions/ogConfigureOgagent rename to client/functions/ogConfigureOgagent diff --git a/client/shared/functions/ogCopyEfiBootLoader b/client/functions/ogCopyEfiBootLoader similarity index 100% rename from client/shared/functions/ogCopyEfiBootLoader rename to client/functions/ogCopyEfiBootLoader diff --git a/client/shared/functions/ogCopyFile b/client/functions/ogCopyFile similarity index 100% rename from client/shared/functions/ogCopyFile rename to client/functions/ogCopyFile diff --git a/client/shared/functions/ogCreateCache b/client/functions/ogCreateCache similarity index 100% rename from client/shared/functions/ogCreateCache rename to client/functions/ogCreateCache diff --git a/client/shared/functions/ogCreateGptPartitions b/client/functions/ogCreateGptPartitions similarity index 100% rename from client/shared/functions/ogCreateGptPartitions rename to client/functions/ogCreateGptPartitions diff --git a/client/shared/functions/ogCreateImage b/client/functions/ogCreateImage similarity index 100% rename from client/shared/functions/ogCreateImage rename to client/functions/ogCreateImage diff --git a/client/shared/functions/ogCreateImageSyntax b/client/functions/ogCreateImageSyntax similarity index 100% rename from client/shared/functions/ogCreateImageSyntax rename to client/functions/ogCreateImageSyntax diff --git a/client/shared/functions/ogCreatePartitionTable b/client/functions/ogCreatePartitionTable similarity index 100% rename from client/shared/functions/ogCreatePartitionTable rename to client/functions/ogCreatePartitionTable diff --git a/client/shared/functions/ogCreatePartitions b/client/functions/ogCreatePartitions similarity index 100% rename from client/shared/functions/ogCreatePartitions rename to client/functions/ogCreatePartitions diff --git a/client/shared/functions/ogCreateTorrent b/client/functions/ogCreateTorrent similarity index 100% rename from client/shared/functions/ogCreateTorrent rename to client/functions/ogCreateTorrent diff --git a/client/shared/functions/ogDeleteCache b/client/functions/ogDeleteCache similarity index 100% rename from client/shared/functions/ogDeleteCache rename to client/functions/ogDeleteCache diff --git a/client/shared/functions/ogDeleteFile b/client/functions/ogDeleteFile similarity index 100% rename from client/shared/functions/ogDeleteFile rename to client/functions/ogDeleteFile diff --git a/client/shared/functions/ogDeletePartitionTable b/client/functions/ogDeletePartitionTable similarity index 100% rename from client/shared/functions/ogDeletePartitionTable rename to client/functions/ogDeletePartitionTable diff --git a/client/shared/functions/ogDeleteRegistryKey b/client/functions/ogDeleteRegistryKey similarity index 100% rename from client/shared/functions/ogDeleteRegistryKey rename to client/functions/ogDeleteRegistryKey diff --git a/client/shared/functions/ogDeleteRegistryValue b/client/functions/ogDeleteRegistryValue similarity index 100% rename from client/shared/functions/ogDeleteRegistryValue rename to client/functions/ogDeleteRegistryValue diff --git a/client/shared/functions/ogDeleteTree b/client/functions/ogDeleteTree similarity index 100% rename from client/shared/functions/ogDeleteTree rename to client/functions/ogDeleteTree diff --git a/client/shared/functions/ogDevToDisk b/client/functions/ogDevToDisk similarity index 100% rename from client/shared/functions/ogDevToDisk rename to client/functions/ogDevToDisk diff --git a/client/shared/functions/ogDiskToDev b/client/functions/ogDiskToDev similarity index 100% rename from client/shared/functions/ogDiskToDev rename to client/functions/ogDiskToDev diff --git a/client/shared/functions/ogEcho b/client/functions/ogEcho similarity index 100% rename from client/shared/functions/ogEcho rename to client/functions/ogEcho diff --git a/client/shared/functions/ogExecAndLog b/client/functions/ogExecAndLog similarity index 100% rename from client/shared/functions/ogExecAndLog rename to client/functions/ogExecAndLog diff --git a/client/shared/functions/ogExtendFs b/client/functions/ogExtendFs similarity index 100% rename from client/shared/functions/ogExtendFs rename to client/functions/ogExtendFs diff --git a/client/shared/functions/ogFindCache b/client/functions/ogFindCache similarity index 100% rename from client/shared/functions/ogFindCache rename to client/functions/ogFindCache diff --git a/client/shared/functions/ogFixBootSector b/client/functions/ogFixBootSector similarity index 100% rename from client/shared/functions/ogFixBootSector rename to client/functions/ogFixBootSector diff --git a/client/shared/functions/ogFormat b/client/functions/ogFormat similarity index 100% rename from client/shared/functions/ogFormat rename to client/functions/ogFormat diff --git a/client/shared/functions/ogFormatCache b/client/functions/ogFormatCache similarity index 100% rename from client/shared/functions/ogFormatCache rename to client/functions/ogFormatCache diff --git a/client/shared/functions/ogFormatFs b/client/functions/ogFormatFs similarity index 100% rename from client/shared/functions/ogFormatFs rename to client/functions/ogFormatFs diff --git a/client/shared/functions/ogGetArch b/client/functions/ogGetArch similarity index 100% rename from client/shared/functions/ogGetArch rename to client/functions/ogGetArch diff --git a/client/shared/functions/ogGetCacheSize b/client/functions/ogGetCacheSize similarity index 100% rename from client/shared/functions/ogGetCacheSize rename to client/functions/ogGetCacheSize diff --git a/client/shared/functions/ogGetCacheSpace b/client/functions/ogGetCacheSpace similarity index 100% rename from client/shared/functions/ogGetCacheSpace rename to client/functions/ogGetCacheSpace diff --git a/client/shared/functions/ogGetCaller b/client/functions/ogGetCaller similarity index 100% rename from client/shared/functions/ogGetCaller rename to client/functions/ogGetCaller diff --git a/client/shared/functions/ogGetDiskSize b/client/functions/ogGetDiskSize similarity index 100% rename from client/shared/functions/ogGetDiskSize rename to client/functions/ogGetDiskSize diff --git a/client/shared/functions/ogGetDiskType b/client/functions/ogGetDiskType similarity index 100% rename from client/shared/functions/ogGetDiskType rename to client/functions/ogGetDiskType diff --git a/client/shared/functions/ogGetEsp b/client/functions/ogGetEsp similarity index 100% rename from client/shared/functions/ogGetEsp rename to client/functions/ogGetEsp diff --git a/client/shared/functions/ogGetFreeSize b/client/functions/ogGetFreeSize similarity index 100% rename from client/shared/functions/ogGetFreeSize rename to client/functions/ogGetFreeSize diff --git a/client/shared/functions/ogGetFsSize b/client/functions/ogGetFsSize similarity index 100% rename from client/shared/functions/ogGetFsSize rename to client/functions/ogGetFsSize diff --git a/client/shared/functions/ogGetFsType b/client/functions/ogGetFsType similarity index 100% rename from client/shared/functions/ogGetFsType rename to client/functions/ogGetFsType diff --git a/client/shared/functions/ogGetHivePath b/client/functions/ogGetHivePath similarity index 100% rename from client/shared/functions/ogGetHivePath rename to client/functions/ogGetHivePath diff --git a/client/shared/functions/ogGetHostname b/client/functions/ogGetHostname similarity index 100% rename from client/shared/functions/ogGetHostname rename to client/functions/ogGetHostname diff --git a/client/shared/functions/ogGetImageCompressor b/client/functions/ogGetImageCompressor similarity index 100% rename from client/shared/functions/ogGetImageCompressor rename to client/functions/ogGetImageCompressor diff --git a/client/shared/functions/ogGetImageInfo b/client/functions/ogGetImageInfo similarity index 100% rename from client/shared/functions/ogGetImageInfo rename to client/functions/ogGetImageInfo diff --git a/client/shared/functions/ogGetImageProgram b/client/functions/ogGetImageProgram similarity index 100% rename from client/shared/functions/ogGetImageProgram rename to client/functions/ogGetImageProgram diff --git a/client/shared/functions/ogGetImageSize b/client/functions/ogGetImageSize similarity index 100% rename from client/shared/functions/ogGetImageSize rename to client/functions/ogGetImageSize diff --git a/client/shared/functions/ogGetImageType b/client/functions/ogGetImageType similarity index 100% rename from client/shared/functions/ogGetImageType rename to client/functions/ogGetImageType diff --git a/client/shared/functions/ogGetIpAddress b/client/functions/ogGetIpAddress similarity index 100% rename from client/shared/functions/ogGetIpAddress rename to client/functions/ogGetIpAddress diff --git a/client/shared/functions/ogGetLastSector b/client/functions/ogGetLastSector similarity index 100% rename from client/shared/functions/ogGetLastSector rename to client/functions/ogGetLastSector diff --git a/client/shared/functions/ogGetMacAddress b/client/functions/ogGetMacAddress similarity index 100% rename from client/shared/functions/ogGetMacAddress rename to client/functions/ogGetMacAddress diff --git a/client/shared/functions/ogGetMountPoint b/client/functions/ogGetMountPoint similarity index 100% rename from client/shared/functions/ogGetMountPoint rename to client/functions/ogGetMountPoint diff --git a/client/shared/functions/ogGetOsType b/client/functions/ogGetOsType similarity index 100% rename from client/shared/functions/ogGetOsType rename to client/functions/ogGetOsType diff --git a/client/shared/functions/ogGetOsUuid b/client/functions/ogGetOsUuid similarity index 100% rename from client/shared/functions/ogGetOsUuid rename to client/functions/ogGetOsUuid diff --git a/client/shared/functions/ogGetOsVersion b/client/functions/ogGetOsVersion similarity index 100% rename from client/shared/functions/ogGetOsVersion rename to client/functions/ogGetOsVersion diff --git a/client/shared/functions/ogGetParentPath b/client/functions/ogGetParentPath similarity index 100% rename from client/shared/functions/ogGetParentPath rename to client/functions/ogGetParentPath diff --git a/client/shared/functions/ogGetPartitionActive b/client/functions/ogGetPartitionActive similarity index 100% rename from client/shared/functions/ogGetPartitionActive rename to client/functions/ogGetPartitionActive diff --git a/client/shared/functions/ogGetPartitionId b/client/functions/ogGetPartitionId similarity index 100% rename from client/shared/functions/ogGetPartitionId rename to client/functions/ogGetPartitionId diff --git a/client/shared/functions/ogGetPartitionSize b/client/functions/ogGetPartitionSize similarity index 100% rename from client/shared/functions/ogGetPartitionSize rename to client/functions/ogGetPartitionSize diff --git a/client/shared/functions/ogGetPartitionTableType b/client/functions/ogGetPartitionTableType similarity index 100% rename from client/shared/functions/ogGetPartitionTableType rename to client/functions/ogGetPartitionTableType diff --git a/client/shared/functions/ogGetPartitionType b/client/functions/ogGetPartitionType similarity index 100% rename from client/shared/functions/ogGetPartitionType rename to client/functions/ogGetPartitionType diff --git a/client/shared/functions/ogGetPartitionsNumber b/client/functions/ogGetPartitionsNumber similarity index 100% rename from client/shared/functions/ogGetPartitionsNumber rename to client/functions/ogGetPartitionsNumber diff --git a/client/shared/functions/ogGetPath b/client/functions/ogGetPath similarity index 100% rename from client/shared/functions/ogGetPath rename to client/functions/ogGetPath diff --git a/client/shared/functions/ogGetRegistryValue b/client/functions/ogGetRegistryValue similarity index 100% rename from client/shared/functions/ogGetRegistryValue rename to client/functions/ogGetRegistryValue diff --git a/client/shared/functions/ogGetRepoIp b/client/functions/ogGetRepoIp similarity index 100% rename from client/shared/functions/ogGetRepoIp rename to client/functions/ogGetRepoIp diff --git a/client/shared/functions/ogGetSerialNumber b/client/functions/ogGetSerialNumber similarity index 100% rename from client/shared/functions/ogGetSerialNumber rename to client/functions/ogGetSerialNumber diff --git a/client/shared/functions/ogGetServerIp b/client/functions/ogGetServerIp similarity index 100% rename from client/shared/functions/ogGetServerIp rename to client/functions/ogGetServerIp diff --git a/client/shared/functions/ogGetSizeParameters b/client/functions/ogGetSizeParameters similarity index 100% rename from client/shared/functions/ogGetSizeParameters rename to client/functions/ogGetSizeParameters diff --git a/client/shared/functions/ogGrubInstallMbr b/client/functions/ogGrubInstallMbr similarity index 100% rename from client/shared/functions/ogGrubInstallMbr rename to client/functions/ogGrubInstallMbr diff --git a/client/shared/functions/ogGrubInstallPartition b/client/functions/ogGrubInstallPartition similarity index 100% rename from client/shared/functions/ogGrubInstallPartition rename to client/functions/ogGrubInstallPartition diff --git a/client/shared/functions/ogHelp b/client/functions/ogHelp similarity index 100% rename from client/shared/functions/ogHelp rename to client/functions/ogHelp diff --git a/client/shared/functions/ogHidePartition b/client/functions/ogHidePartition similarity index 100% rename from client/shared/functions/ogHidePartition rename to client/functions/ogHidePartition diff --git a/client/shared/functions/ogIdToType b/client/functions/ogIdToType similarity index 100% rename from client/shared/functions/ogIdToType rename to client/functions/ogIdToType diff --git a/client/shared/functions/ogInstallFirstBoot b/client/functions/ogInstallFirstBoot similarity index 100% rename from client/shared/functions/ogInstallFirstBoot rename to client/functions/ogInstallFirstBoot diff --git a/client/shared/functions/ogInstallMiniSetup b/client/functions/ogInstallMiniSetup similarity index 100% rename from client/shared/functions/ogInstallMiniSetup rename to client/functions/ogInstallMiniSetup diff --git a/client/shared/functions/ogInstallRunonce b/client/functions/ogInstallRunonce similarity index 100% rename from client/shared/functions/ogInstallRunonce rename to client/functions/ogInstallRunonce diff --git a/client/shared/functions/ogIsDiskLocked b/client/functions/ogIsDiskLocked similarity index 100% rename from client/shared/functions/ogIsDiskLocked rename to client/functions/ogIsDiskLocked diff --git a/client/shared/functions/ogIsEfiActive b/client/functions/ogIsEfiActive similarity index 100% rename from client/shared/functions/ogIsEfiActive rename to client/functions/ogIsEfiActive diff --git a/client/shared/functions/ogIsFormated b/client/functions/ogIsFormated similarity index 100% rename from client/shared/functions/ogIsFormated rename to client/functions/ogIsFormated diff --git a/client/shared/functions/ogIsImageLocked b/client/functions/ogIsImageLocked similarity index 100% rename from client/shared/functions/ogIsImageLocked rename to client/functions/ogIsImageLocked diff --git a/client/shared/functions/ogIsLocked b/client/functions/ogIsLocked similarity index 100% rename from client/shared/functions/ogIsLocked rename to client/functions/ogIsLocked diff --git a/client/shared/functions/ogIsMounted b/client/functions/ogIsMounted similarity index 100% rename from client/shared/functions/ogIsMounted rename to client/functions/ogIsMounted diff --git a/client/shared/functions/ogIsPartitionLocked b/client/functions/ogIsPartitionLocked similarity index 100% rename from client/shared/functions/ogIsPartitionLocked rename to client/functions/ogIsPartitionLocked diff --git a/client/shared/functions/ogIsReadonly b/client/functions/ogIsReadonly similarity index 100% rename from client/shared/functions/ogIsReadonly rename to client/functions/ogIsReadonly diff --git a/client/shared/functions/ogIsRepoLocked b/client/functions/ogIsRepoLocked similarity index 100% rename from client/shared/functions/ogIsRepoLocked rename to client/functions/ogIsRepoLocked diff --git a/client/shared/functions/ogIsVirtualMachine b/client/functions/ogIsVirtualMachine similarity index 100% rename from client/shared/functions/ogIsVirtualMachine rename to client/functions/ogIsVirtualMachine diff --git a/client/shared/functions/ogIsWritable b/client/functions/ogIsWritable similarity index 100% rename from client/shared/functions/ogIsWritable rename to client/functions/ogIsWritable diff --git a/client/shared/functions/ogListHardwareInfo b/client/functions/ogListHardwareInfo similarity index 100% rename from client/shared/functions/ogListHardwareInfo rename to client/functions/ogListHardwareInfo diff --git a/client/shared/functions/ogListLogicalPartitions b/client/functions/ogListLogicalPartitions similarity index 100% rename from client/shared/functions/ogListLogicalPartitions rename to client/functions/ogListLogicalPartitions diff --git a/client/shared/functions/ogListPartitions b/client/functions/ogListPartitions similarity index 100% rename from client/shared/functions/ogListPartitions rename to client/functions/ogListPartitions diff --git a/client/shared/functions/ogListPrimaryPartitions b/client/functions/ogListPrimaryPartitions similarity index 100% rename from client/shared/functions/ogListPrimaryPartitions rename to client/functions/ogListPrimaryPartitions diff --git a/client/shared/functions/ogListRegistryKeys b/client/functions/ogListRegistryKeys similarity index 100% rename from client/shared/functions/ogListRegistryKeys rename to client/functions/ogListRegistryKeys diff --git a/client/shared/functions/ogListRegistryValues b/client/functions/ogListRegistryValues similarity index 100% rename from client/shared/functions/ogListRegistryValues rename to client/functions/ogListRegistryValues diff --git a/client/shared/functions/ogListSoftware b/client/functions/ogListSoftware similarity index 100% rename from client/shared/functions/ogListSoftware rename to client/functions/ogListSoftware diff --git a/client/shared/functions/ogLock b/client/functions/ogLock similarity index 100% rename from client/shared/functions/ogLock rename to client/functions/ogLock diff --git a/client/shared/functions/ogLockDisk b/client/functions/ogLockDisk similarity index 100% rename from client/shared/functions/ogLockDisk rename to client/functions/ogLockDisk diff --git a/client/shared/functions/ogLockImage b/client/functions/ogLockImage similarity index 100% rename from client/shared/functions/ogLockImage rename to client/functions/ogLockImage diff --git a/client/shared/functions/ogLockPartition b/client/functions/ogLockPartition similarity index 100% rename from client/shared/functions/ogLockPartition rename to client/functions/ogLockPartition diff --git a/client/shared/functions/ogMakeDir b/client/functions/ogMakeDir similarity index 100% rename from client/shared/functions/ogMakeDir rename to client/functions/ogMakeDir diff --git a/client/shared/functions/ogMcastReceiverFile b/client/functions/ogMcastReceiverFile similarity index 100% rename from client/shared/functions/ogMcastReceiverFile rename to client/functions/ogMcastReceiverFile diff --git a/client/shared/functions/ogMcastReceiverPartition b/client/functions/ogMcastReceiverPartition similarity index 100% rename from client/shared/functions/ogMcastReceiverPartition rename to client/functions/ogMcastReceiverPartition diff --git a/client/shared/functions/ogMcastSendFile b/client/functions/ogMcastSendFile similarity index 100% rename from client/shared/functions/ogMcastSendFile rename to client/functions/ogMcastSendFile diff --git a/client/shared/functions/ogMcastSendPartition b/client/functions/ogMcastSendPartition similarity index 100% rename from client/shared/functions/ogMcastSendPartition rename to client/functions/ogMcastSendPartition diff --git a/client/shared/functions/ogMcastSyntax b/client/functions/ogMcastSyntax similarity index 100% rename from client/shared/functions/ogMcastSyntax rename to client/functions/ogMcastSyntax diff --git a/client/shared/functions/ogMount b/client/functions/ogMount similarity index 100% rename from client/shared/functions/ogMount rename to client/functions/ogMount diff --git a/client/shared/functions/ogMountCache b/client/functions/ogMountCache similarity index 100% rename from client/shared/functions/ogMountCache rename to client/functions/ogMountCache diff --git a/client/shared/functions/ogMountCdrom b/client/functions/ogMountCdrom similarity index 100% rename from client/shared/functions/ogMountCdrom rename to client/functions/ogMountCdrom diff --git a/client/shared/functions/ogMountFirstFs b/client/functions/ogMountFirstFs similarity index 100% rename from client/shared/functions/ogMountFirstFs rename to client/functions/ogMountFirstFs diff --git a/client/shared/functions/ogMountFs b/client/functions/ogMountFs similarity index 100% rename from client/shared/functions/ogMountFs rename to client/functions/ogMountFs diff --git a/client/shared/functions/ogNvramActiveEntry b/client/functions/ogNvramActiveEntry similarity index 100% rename from client/shared/functions/ogNvramActiveEntry rename to client/functions/ogNvramActiveEntry diff --git a/client/shared/functions/ogNvramAddEntry b/client/functions/ogNvramAddEntry similarity index 100% rename from client/shared/functions/ogNvramAddEntry rename to client/functions/ogNvramAddEntry diff --git a/client/shared/functions/ogNvramDeleteEntry b/client/functions/ogNvramDeleteEntry similarity index 100% rename from client/shared/functions/ogNvramDeleteEntry rename to client/functions/ogNvramDeleteEntry diff --git a/client/shared/functions/ogNvramGetCurrent b/client/functions/ogNvramGetCurrent similarity index 100% rename from client/shared/functions/ogNvramGetCurrent rename to client/functions/ogNvramGetCurrent diff --git a/client/shared/functions/ogNvramGetNext b/client/functions/ogNvramGetNext similarity index 100% rename from client/shared/functions/ogNvramGetNext rename to client/functions/ogNvramGetNext diff --git a/client/shared/functions/ogNvramGetOrder b/client/functions/ogNvramGetOrder similarity index 100% rename from client/shared/functions/ogNvramGetOrder rename to client/functions/ogNvramGetOrder diff --git a/client/shared/functions/ogNvramGetTimeout b/client/functions/ogNvramGetTimeout similarity index 100% rename from client/shared/functions/ogNvramGetTimeout rename to client/functions/ogNvramGetTimeout diff --git a/client/shared/functions/ogNvramInactiveEntry b/client/functions/ogNvramInactiveEntry similarity index 100% rename from client/shared/functions/ogNvramInactiveEntry rename to client/functions/ogNvramInactiveEntry diff --git a/client/shared/functions/ogNvramList b/client/functions/ogNvramList similarity index 100% rename from client/shared/functions/ogNvramList rename to client/functions/ogNvramList diff --git a/client/shared/functions/ogNvramPxeFirstEntry b/client/functions/ogNvramPxeFirstEntry similarity index 100% rename from client/shared/functions/ogNvramPxeFirstEntry rename to client/functions/ogNvramPxeFirstEntry diff --git a/client/shared/functions/ogNvramSetNext b/client/functions/ogNvramSetNext similarity index 100% rename from client/shared/functions/ogNvramSetNext rename to client/functions/ogNvramSetNext diff --git a/client/shared/functions/ogNvramSetOrder b/client/functions/ogNvramSetOrder similarity index 100% rename from client/shared/functions/ogNvramSetOrder rename to client/functions/ogNvramSetOrder diff --git a/client/shared/functions/ogNvramSetTimeout b/client/functions/ogNvramSetTimeout similarity index 100% rename from client/shared/functions/ogNvramSetTimeout rename to client/functions/ogNvramSetTimeout diff --git a/client/shared/functions/ogRaiseError b/client/functions/ogRaiseError similarity index 100% rename from client/shared/functions/ogRaiseError rename to client/functions/ogRaiseError diff --git a/client/shared/functions/ogReduceFs b/client/functions/ogReduceFs similarity index 100% rename from client/shared/functions/ogReduceFs rename to client/functions/ogReduceFs diff --git a/client/shared/functions/ogRestoreEfiBootLoader b/client/functions/ogRestoreEfiBootLoader similarity index 100% rename from client/shared/functions/ogRestoreEfiBootLoader rename to client/functions/ogRestoreEfiBootLoader diff --git a/client/shared/functions/ogRestoreImage b/client/functions/ogRestoreImage similarity index 100% rename from client/shared/functions/ogRestoreImage rename to client/functions/ogRestoreImage diff --git a/client/shared/functions/ogRestoreImageSyntax b/client/functions/ogRestoreImageSyntax similarity index 100% rename from client/shared/functions/ogRestoreImageSyntax rename to client/functions/ogRestoreImageSyntax diff --git a/client/shared/functions/ogSetPartitionActive b/client/functions/ogSetPartitionActive similarity index 100% rename from client/shared/functions/ogSetPartitionActive rename to client/functions/ogSetPartitionActive diff --git a/client/shared/functions/ogSetPartitionId b/client/functions/ogSetPartitionId similarity index 100% rename from client/shared/functions/ogSetPartitionId rename to client/functions/ogSetPartitionId diff --git a/client/shared/functions/ogSetPartitionSize b/client/functions/ogSetPartitionSize similarity index 100% rename from client/shared/functions/ogSetPartitionSize rename to client/functions/ogSetPartitionSize diff --git a/client/shared/functions/ogSetPartitionType b/client/functions/ogSetPartitionType similarity index 100% rename from client/shared/functions/ogSetPartitionType rename to client/functions/ogSetPartitionType diff --git a/client/shared/functions/ogSetRegistryValue b/client/functions/ogSetRegistryValue similarity index 100% rename from client/shared/functions/ogSetRegistryValue rename to client/functions/ogSetRegistryValue diff --git a/client/shared/functions/ogSetWindowsName b/client/functions/ogSetWindowsName similarity index 100% rename from client/shared/functions/ogSetWindowsName rename to client/functions/ogSetWindowsName diff --git a/client/shared/functions/ogTorrentStart b/client/functions/ogTorrentStart similarity index 100% rename from client/shared/functions/ogTorrentStart rename to client/functions/ogTorrentStart diff --git a/client/shared/functions/ogTypeToId b/client/functions/ogTypeToId similarity index 100% rename from client/shared/functions/ogTypeToId rename to client/functions/ogTypeToId diff --git a/client/shared/functions/ogUcastReceiverPartition b/client/functions/ogUcastReceiverPartition similarity index 100% rename from client/shared/functions/ogUcastReceiverPartition rename to client/functions/ogUcastReceiverPartition diff --git a/client/shared/functions/ogUcastSendFile b/client/functions/ogUcastSendFile similarity index 100% rename from client/shared/functions/ogUcastSendFile rename to client/functions/ogUcastSendFile diff --git a/client/shared/functions/ogUcastSendPartition b/client/functions/ogUcastSendPartition similarity index 100% rename from client/shared/functions/ogUcastSendPartition rename to client/functions/ogUcastSendPartition diff --git a/client/shared/functions/ogUcastSyntax b/client/functions/ogUcastSyntax similarity index 100% rename from client/shared/functions/ogUcastSyntax rename to client/functions/ogUcastSyntax diff --git a/client/shared/functions/ogUnhidePartition b/client/functions/ogUnhidePartition similarity index 100% rename from client/shared/functions/ogUnhidePartition rename to client/functions/ogUnhidePartition diff --git a/client/shared/functions/ogUninstallLinuxClient b/client/functions/ogUninstallLinuxClient similarity index 100% rename from client/shared/functions/ogUninstallLinuxClient rename to client/functions/ogUninstallLinuxClient diff --git a/client/shared/functions/ogUninstallWindowsClient b/client/functions/ogUninstallWindowsClient similarity index 100% rename from client/shared/functions/ogUninstallWindowsClient rename to client/functions/ogUninstallWindowsClient diff --git a/client/shared/functions/ogUnlock b/client/functions/ogUnlock similarity index 100% rename from client/shared/functions/ogUnlock rename to client/functions/ogUnlock diff --git a/client/shared/functions/ogUnlockDisk b/client/functions/ogUnlockDisk similarity index 100% rename from client/shared/functions/ogUnlockDisk rename to client/functions/ogUnlockDisk diff --git a/client/shared/functions/ogUnlockImage b/client/functions/ogUnlockImage similarity index 100% rename from client/shared/functions/ogUnlockImage rename to client/functions/ogUnlockImage diff --git a/client/shared/functions/ogUnlockPartition b/client/functions/ogUnlockPartition similarity index 100% rename from client/shared/functions/ogUnlockPartition rename to client/functions/ogUnlockPartition diff --git a/client/shared/functions/ogUnmount b/client/functions/ogUnmount similarity index 100% rename from client/shared/functions/ogUnmount rename to client/functions/ogUnmount diff --git a/client/shared/functions/ogUnmountAll b/client/functions/ogUnmountAll similarity index 100% rename from client/shared/functions/ogUnmountAll rename to client/functions/ogUnmountAll diff --git a/client/shared/functions/ogUnmountCache b/client/functions/ogUnmountCache similarity index 100% rename from client/shared/functions/ogUnmountCache rename to client/functions/ogUnmountCache diff --git a/client/shared/functions/ogUnmountFs b/client/functions/ogUnmountFs similarity index 100% rename from client/shared/functions/ogUnmountFs rename to client/functions/ogUnmountFs diff --git a/client/shared/functions/ogUnsetDirtyBit b/client/functions/ogUnsetDirtyBit similarity index 100% rename from client/shared/functions/ogUnsetDirtyBit rename to client/functions/ogUnsetDirtyBit diff --git a/client/shared/functions/ogUpdateCacheIsNecesary b/client/functions/ogUpdateCacheIsNecesary similarity index 100% rename from client/shared/functions/ogUpdateCacheIsNecesary rename to client/functions/ogUpdateCacheIsNecesary diff --git a/client/shared/functions/ogUpdatePartitionTable b/client/functions/ogUpdatePartitionTable similarity index 100% rename from client/shared/functions/ogUpdatePartitionTable rename to client/functions/ogUpdatePartitionTable diff --git a/client/shared/functions/ogWindowsBootParameters b/client/functions/ogWindowsBootParameters similarity index 100% rename from client/shared/functions/ogWindowsBootParameters rename to client/functions/ogWindowsBootParameters diff --git a/client/shared/functions/ogWindowsRegisterPartition b/client/functions/ogWindowsRegisterPartition similarity index 100% rename from client/shared/functions/ogWindowsRegisterPartition rename to client/functions/ogWindowsRegisterPartition diff --git a/client/images/README.es.txt b/client/images/README.es.txt new file mode 100644 index 0000000..7035c67 --- /dev/null +++ b/client/images/README.es.txt @@ -0,0 +1 @@ +Directorio de imágenes para el cliente diff --git a/client/interfaceAdm/Apagar b/client/interfaceAdm/Apagar new file mode 100755 index 0000000..ae1e5ba --- /dev/null +++ b/client/interfaceAdm/Apagar @@ -0,0 +1,3 @@ +#!/bin/bash +poweroff +exit 0 diff --git a/client/interfaceAdm/CambiarAcceso b/client/interfaceAdm/CambiarAcceso new file mode 100755 index 0000000..88ce5c8 --- /dev/null +++ b/client/interfaceAdm/CambiarAcceso @@ -0,0 +1,54 @@ +#!/bin/bash + +#______________________________________ +# +# PARAMETROS RECIBIDOS DESDE EL CLIENTE +# $1 modo (admin, user) +#______________________________________ + +# Error si llamada no se realliza desde OpenGnsys Client. +PROG=$(basename $0) +#CALLER=$(ogGetCaller) +#if ! $(ogCheckStringInGroup "$CALLER" "CrearImagen ConsolaRemota CrearImagenBasica CrearSoftIncremental"); then +# ogRaiseError $OG_ERR_NOTEXEC "$CALLER -> $PROG" +# exit $? +#fi + +# Salir si el repositorio está bloquedo (tiene ficheros abiertos). +REPOIP=$(ogGetRepoIp) +if [ -z "$REPOIP" ]; then + ogRaiseError $OG_ERR_NOTFOUND "repo no montado" + exit $? +fi +if ogIsRepoLocked; then + ogRaiseError $OG_ERR_LOCKED "repo $REPOIP" + exit $? +fi + +# Comprobar protocolo y modo de acceso. +PROTO=${ogprotocol:-"smb"} +case "$PROTO" in + nfs|smb) ;; + *) ogRaiseError $OG_ERR_FORMAT "protocolo desconocido $PROTO" + exit $? ;; +esac +case "$1" in + admin) MODE="rw" ;; + user) MODE="ro" ;; + *) ogRaiseError $OG_ERR_FORMAT "modo desconocido $1" + exit $? ;; +esac + +# Desmontar repositorio y volver a montarlo con el modo adecuado. +umount $OGIMG +# Unidad organizativa +[ "$ogunit" != "" ] && OGUNIT="/$ogunit" +ogEcho info "$PROG: Montar repositorio $REPO por $PROTO en modo $1" +case "$PROTO" in + nfs) mount -t nfs $REPOIP:$OGIMG$OGUNIT $OGIMG -o $MODE ;; + smb) PASS=$(grep "^[ ]*\(export \)\?OPTIONS=" /scripts/ogfunctions 2>&1 | \ + sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/') + PASS=${PASS:-"og"} + mount.cifs //$REPOIP/ogimages$OGUNIT $OGIMG -o $MODE,serverino,acl,username=opengnsys,password=$PASS +esac + diff --git a/client/interfaceAdm/Configurar b/client/interfaceAdm/Configurar new file mode 100755 index 0000000..e88d073 --- /dev/null +++ b/client/interfaceAdm/Configurar @@ -0,0 +1,159 @@ +#!/bin/bash + + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimieincludento para httpdlog +echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp + +# Registro de inicio de ejecución +ogEcho log session "$MSG_INTERFACE_START $0 $*" + +# Solo ejecutable por OpenGnsys Client. +PATH=$PATH:$(dirname $0) +PROG=$(basename $0) + +#____________________________________________________________________ +# +# El parámetro $2 es el que aporta toda la información y el $1 se queda obsoleto +# Formato de entrada: +# dis=Número de disco +# *=caracter de separación +# che=Vale 0 o 1 +# *=caracter de separación +# $tch=tamaño cache +# != caracter de separación +# +# Y un numero indeterminado de cadenas del tipo siguuenteseparadas por el caracter '$': +# par=Número de particion*cod=Código de partición*sfi=Sistema de ficheros*tam=Tamaño de la partición*ope=Operación +# @= caracter de separación +#____________________________________________________________________ + +# Captura de parámetros (se ignora el 1er parámetro y se eliminan espacios y tabuladores). +#param='dis=1*che=0*tch=70000000!par=1*cpt=NTFS*sfi=NTFS*tam=11000000*ope=0%' +shift +param="$(echo $* | sed 's/[ ]//g')" + +# Activa navegador para ver progreso +coproc /opt/opengnsys/bin/browser -qws http://localhost/cgi-bin/httpd-log.sh + +# Leer los dos bloques de parámetros, separados por '!'. +declare -a TBPRM + +IFS='!' read -a TBPRM <<<"$param" +pparam="${TBPRM[0]}" # Parámetros generales del disco. +sparam="${TBPRM[1]}" # Parámetros de particionado y formateo. + + +# Toma valores de disco y caché, separados por "*". +# Los valores están en las variables $dis: disco, $che: existe cache (1, 0), $tch: Tamaño de la cache. +unset TBPRM +IFS='*' read -a TBPRM <<<"$pparam" +[[ ${TBPRM} =~ = ]] && eval ${TBPRM[@]} # Comprobar asignación antes de exportar valores. + +# Error si no se define el parámetro de disco (dis). +[ -z "$dis" ] && exit $OG_ERR_FORMAT + +# Toma valores de distribución de particiones, separados por "%". +declare -a CFG # Valores de configuración. +declare -a TBP # Tabla de particionado. +declare -a TBF # Tabla de formateo. + +unset TBPRM +IFS='%' read -a TBPRM <<<"$sparam" + +maxp=0 +for ((i=0; i<${#TBPRM[@]}; i++)); do + # Leer datos de la partición, separados por "*". + unset par + IFS='*' read -a CFG <<<"${TBPRM[i]}" 2>/dev/null + [[ ${CFG} =~ = ]] && eval ${CFG[@]} # Comprobar asignación antes de exportar valores. + # Componer datos de particionado. + if [ "$cpt" != "CACHE" ]; then + TBP[par]="$cpt:$tam" + fi + # Si se activa operación de formatear, componer datos de formateo. + if [ "$ope" == 1 ]; then + # Comprobamos que la particion y el s.f sean validos. + ogCheckStringInGroup $cpt "EMPTY EXTENDED LINUX-LVM LVM ZPOOL" + [ $? -ne 0 ] && TBF[par]="$sfi" + fi + # Obtener la partición mayor. + [ $par -gt $maxp ] && maxp=$par +done +#____________________________________________________ +# +# Proceso +#____________________________________________________ + +# Tamaño actual de la cache +CACHESIZE=$(ogGetCacheSize) + +# Desmonta todas las particiones y la caché + +ogEcho session log "[10] $MSG_HELP_ogUnmountAll" +ogUnmountAll $dis &>/dev/null +ogUnmountCache + +# Elimina la tabla de particiones +if [ `ogGetPartitionTableType 1` != 'MSDOS' ]; then + ogDeletePartitionTable $dis + ogExecAndLog COMMAND ogUpdatePartitionTable $dis + + # Crea tabla de particiones MSDOS (NOTA: adaptar para tablas GPT). + ogCreatePartitionTable $dis MSDOS +fi + +# Inicia la cache. +if echo "$sparam" |grep "CACHE" >/dev/null; then + ogEcho session log "[30] $MSG_HELP_ogCreateCache" + ogEcho session log " initCache $tch" + ogExecAndLog COMMAND initCache $tch +fi + +# Definir particionado. +ogEcho session log "[50] $MSG_HELP_ogCreatePartitions" +ogEcho session log " ogCreatePartitions $dis ${TBP[@]}" +ogExecAndLog COMMAND ogCreatePartitions $dis ${TBP[@]} +if [ $? -ne 0 ]; then + kill $COPROC_PID + exit $(ogRaiseError session log $OG_ERR_GENERIC "ogCreatePartitions $dis ${TBP[@]}") +fi +ogExecAndLog COMMAND ogUpdatePartitionTable $dis + +# Formatear particiones +ogEcho session log "[70] $MSG_HELP_ogFormat" + +for ((par=1; par<=$maxp; par++)); do + case "${TBF[par]}" in + CACHE) # Si el tamaño es distinto ya se ha formateado. + if [ "$CACHESIZE" == $tch ]; then + ogEcho session log " ogFormatCache" + ogExecAndLog COMMAND ogFormatCache + fi + ;; + "") ;; + *) ogEcho session log " ogFormatFs $dis $par ${TBF[par]}" + ogExecAndLog COMMAND ogFormatFs $dis $par ${TBF[par]} + if [ $? -ne 0 ]; then + kill $COPROC_PID + exit $(ogRaiseError session log $OG_ERR_GENERIC "ogFormatFs $dis $par ${TBF[par]}"); + fi + ;; + esac +done +RETVAL=$? +# Registro de fin de ejecución +ogEcho log session "$MSG_INTERFACE_END $RETVAL" + +#___________________________________________________________________ +# +# Retorno +#___________________________________________________________________ + +kill $COPROC_PID +exit 0 + diff --git a/client/interfaceAdm/ConsolaRemota b/client/interfaceAdm/ConsolaRemota new file mode 100755 index 0000000..f569771 --- /dev/null +++ b/client/interfaceAdm/ConsolaRemota @@ -0,0 +1,3 @@ +#!/bin/bash +chmod +x $1 +$1>$2 || exit $? diff --git a/client/interfaceAdm/CrearImagen b/client/interfaceAdm/CrearImagen new file mode 100755 index 0000000..4f84ec0 --- /dev/null +++ b/client/interfaceAdm/CrearImagen @@ -0,0 +1,91 @@ +#!/bin/bash + +#___________________________________________________ +# +# PARAMETROS RECIBIDOS DESDE EL CLIENTE: +# $1 Número de disco +# $2 Número de particion +# $3 Nombre canónico de la imagen (sin extensión) +# $4 Dirección del repositorio (REPO, por defecto) +#___________________________________________________ + + +#$OG_ERR_NOTEXEC Si no es llamada por OG client +#$OG_ERR_LOCKED=4 Si la particion está bloqueada. + + +#Codigos de error del scripts createImage +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@exception OG_ERR_PARTITION # 3 Error en partición de disco o en su sistema de archivos +#@exception OG_ERR_IMAGE # 5 Error en funcion ogCreateImage o ogRestoreImage. +#@exception OG_ERR_NOTWRITE # 14 error de escritura +#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15 +#@exception OG_ERR_CACHESIZE # 16 si espacio de la cache local o remota no tiene espacio 16 +#@exception OG_ERR_REDUCEFS # 17 error al reducir sistema de archivos. +#@exception OG_ERR_EXTENDFS # 18 Errror al expandir el sistema de archivos. + + +#Códigos de error de la funcion ogCreateImage + + + +TIME1=$SECONDS + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp + +# Registro de inicio de ejecución +ogEcho log session "$MSG_INTERFACE_START $0 $*" + +# Solo ejecutable por OpenGnsys Client. +PATH=$PATH:$(dirname $0) +PROG=$(basename $0) +#CALLER=$(ogGetCaller) +#if [ "$CALLER" != "ogAdmClient" ]; then +# ogRaiseError $OG_ERR_NOTEXEC "$CALLER -> $PROG" +# exit $? +#fi + +# Valor por defecto para el repositorio. +REPO=${4:-"REPO"} +[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPO +if [ $? == 0 -o $REPO == "REPO" ] ; then + # Unidad organizativa + [ "$ogunit" != "" ] && OGUNIT="$ogunit" + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?) + REPO="REPO" +fi + +# Si el destino es REPO y el cliente no está en modo "admin"; activar repositorio para escritura, +if [ "$REPO" == "REPO" -a "$boot" != "admin" ] +then + CambiarAcceso admin &>> $OGLOGFILE + RETVAL=$? + [ $RETVAL -gt 0 ] && exit $RETVAL +fi + +ogEcho createImage "$1" "$2" "$4" /"$3" +# Si existe, ejecuta script personalizado "createImageCustom"; si no, llama al genérico "createImage". +if which createImageCustom &>/dev/null; then + createImageCustom "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND +else + createImage "$1" "$2" "$4" /"$3" &>> $OGLOGCOMMAND +fi +RETVAL=$? + +# Cambiar acceso a modo usuario, si es necesario. +[ "$REPO" == "REPO" -a "$boot" != "admin" ] && CambiarAcceso user + +# Registro de fin de ejecución +ogEcho log session "$MSG_INTERFACE_END $RETVAL" + +exit $RETVAL + diff --git a/client/interfaceAdm/EjecutarScript b/client/interfaceAdm/EjecutarScript new file mode 100755 index 0000000..26453ed --- /dev/null +++ b/client/interfaceAdm/EjecutarScript @@ -0,0 +1,44 @@ +#!/bin/bash +TIME1=$SECONDS + + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo -n "" > $OGLOGSESSION; echo -n "" > $OGLOGCOMMAND + +# Registro de inicio de ejecución +ogEcho log session "$MSG_INTERFACE_START $0 $*" + +echo -e "\n Instrucciones a ejecutar: *****************************" >> $OGLOGFILE +cat $1 >> $OGLOGFILE + + +echo -e "\n Salida de las instrucciones: *****************************" >> $OGLOGFILE +chmod +x $1 +# Si mandamos la salida a OGLOGCOMMAND reescribimos lo que manda el comando. +#$1 &>> $OGLOGCOMMAND +$1 +RETVAL=$? + + + +TIME=$[SECONDS-TIME1] +if [ $RETVAL == 0 ] +then + ogEcho log session "[100] Duracion de la operacion $[TIME/60]m $[TIME%60]s" +else + ogRaiseError log session $RETVAL + ogEcho log session error "Operacion no realizada" +fi + + +# Registro de fin de ejecución +ogEcho log session "$MSG_INTERFACE_END $RETVAL" + + +exit $RETVAL + diff --git a/client/interfaceAdm/GetConfiguration.py b/client/interfaceAdm/GetConfiguration.py deleted file mode 100755 index eabf97c..0000000 --- a/client/interfaceAdm/GetConfiguration.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python3 -import os -import subprocess -import sys -import FileSystemLib -import DiskLib - -os.environ["DEBUG"] = "no" - -# Obtener el número de serie y configuración inicial -ser = subprocess.getoutput("ogGetSerialNumber") -cfg = "" - -# Obtener el número de discos -disks = len(subprocess.getoutput("ogDiskToDev").split()) - - -for dsk in disk_list: - # Número de particiones - particiones = FileSystemLib.ogGetPartitionsNumber(dsk) or "0" - particiones = int(particiones) - - # Tipo de tabla de particiones - ptt = DiskLib.ogGetPartitionTableType(dsk) - ptt_mapping = {"MSDOS": 1, "GPT": 2, "LVM": 3, "ZPOOL": 4} - ptt = ptt_mapping.get(ptt, 0) - - # Información de disco (partición 0) - disk_size = DiskLib.ogGetDiskSize(dsk) - cfg += f"{dsk}:0:{ptt}:::{disk_size}:0;" - - # Recorrer particiones - for par in range(1, particiones + 1): - # Código del identificador de tipo de partición - cod = DiskLib.ogGetPartitionId(dsk, par) - - # Tipo del sistema de ficheros - fsi = FileSystemLib.getFsType(dsk, par) or "EMPTY" - - # Tamaño de la partición - tam = DiskLib.ogGetPartitionSize(dsk, par) or "0" - - # Sistema operativo instalado - soi = "" - uso = 0 - if fsi not in ["", "EMPTY", "LINUX-SWAP", "LINUX-LVM", "ZVOL"]: - mount_point = DiskLib.ogMount(dsk, par) - if mount_point: - # Obtener la versión del sistema operativo instalado - try: - # Asumiendo que getOsVersion es una función disponible - import OsLib # Debes tener OsLib.py disponible con la función getOsVersion - soi_output = OsLib.getOsVersion(dsk, par) - except ImportError: - # Si no está disponible, usar subprocess como alternativa - soi_output = subprocess.getoutput(f"getOsVersion {dsk} {par} 2>/dev/null") - - soi = soi_output.split(':')[1] if ':' in soi_output else '' - # Hacer un segundo intento para algunos casos especiales - if not soi: - soi_output = subprocess.getoutput(f"getOsVersion {dsk} {par} 2>/dev/null") - soi = soi_output.split(':')[1] if ':' in soi_output else '' - - # Sistema de archivos para datos (sistema operativo "DATA") - if not soi and fsi not in ["EMPTY", "CACHE"]: - soi = "DATA" - - # Obtener porcentaje de uso - mount_point = DiskLib.ogGetMountPoint(dsk, par) - df_output = subprocess.getoutput(f"df {mount_point}") - lines = df_output.splitlines() - if len(lines) >= 2: - uso_str = lines[1].split()[4] # Esta debería ser la quinta columna - if uso_str.endswith('%'): - uso = int(uso_str.rstrip('%')) - else: - uso = int(uso_str) - else: - uso = 0 - else: - soi = "" - uso = 0 - else: - soi = "" - uso = 0 - - cfg += f"{dsk}:{par}:{cod}:{fsi}:{soi}:{tam}:{uso};" - -# Configuración por defecto para cliente sin disco -if not cfg: - cfg = "1:0:0:::0;" - -# Guardar salida en fichero temporal -cfgfile = "/tmp/getconfig" -with open(cfgfile, 'w') as f: - f.write(f"{ser + ';' if ser else ''}{cfg}") - -# Crear el menú por defecto desde el archivo generado -subprocess.run(["generateMenuDefault"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - -# Componer salida formateada -formatted_output = [] -with open(cfgfile, 'r') as f: - content = f.read().strip().split(";") - for item in content: - fields = item.split(":") - if len(fields) == 1: - formatted_output.append(f"ser={fields[0]}") - else: - formatted_output.append( - f"disk={fields[0]}\tpar={fields[1]}\tcpt={fields[2]}\tfsi={fields[3]}\tsoi={fields[4]}\ttam={fields[5]}\tuso={fields[6]}" - ) - -# Mostrar la salida formateada -print("\n".join(formatted_output)) - -# Borrar marcas de arranque de Windows -subprocess.run(["rm", "-f", "/mnt/*/ogboot.*", "/mnt/*/*/ogboot.*"]) - -# Volver a registrar los errores -os.environ.pop("DEBUG", None) diff --git a/client/interfaceAdm/IniciarSesion b/client/interfaceAdm/IniciarSesion new file mode 100755 index 0000000..750d96d --- /dev/null +++ b/client/interfaceAdm/IniciarSesion @@ -0,0 +1,13 @@ +#!/bin/bash + +# UHU - Comprobamos el disco, si solo hay un parametro, disco es 1, por compatibilidad con clientes antiguos +if [ $# == 1 ] +then + disk=1 + part=$1 +else + disk=$1 + part=$2 +fi + +bootOs $disk $part diff --git a/client/interfaceAdm/InventarioHardware b/client/interfaceAdm/InventarioHardware new file mode 100755 index 0000000..17614a5 --- /dev/null +++ b/client/interfaceAdm/InventarioHardware @@ -0,0 +1,6 @@ +#!/bin/bash +# Script de interfaz para guardar en un fichero el inventario de hardware de un cliente. + +file=$(listHardwareInfo) +tail -n+2 $file >$1 + diff --git a/client/interfaceAdm/InventarioSoftware b/client/interfaceAdm/InventarioSoftware new file mode 100755 index 0000000..fa96565 --- /dev/null +++ b/client/interfaceAdm/InventarioSoftware @@ -0,0 +1,19 @@ +#!/bin/bash + +TIME1=$SECONDS + +#Carga el configurador del engine desde el fichero engine.cfg +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo -n " " | tee $OGLOGSESSION $OGLOGCOMMAND ${OGLOGCOMMAND}.tmp + +# Registro de inicio de ejecución +ogEcho log session "$MSG_INTERFACE_START $0 $*" + +file=$(listSoftwareInfo $1 $2) +cp $file $3 + +TIME=$[SECONDS-TIME1] +ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL : $[TIME/60]m $[TIME%60]s" + diff --git a/client/interfaceAdm/Reiniciar b/client/interfaceAdm/Reiniciar new file mode 100755 index 0000000..df93c1b --- /dev/null +++ b/client/interfaceAdm/Reiniciar @@ -0,0 +1,3 @@ +#!/bin/bash +reboot +exit 0 diff --git a/client/interfaceAdm/RestaurarImagen b/client/interfaceAdm/RestaurarImagen new file mode 100755 index 0000000..6f9ae24 --- /dev/null +++ b/client/interfaceAdm/RestaurarImagen @@ -0,0 +1,15 @@ +#!/bin/bash +#_______________________________________________________________________________________________________________________________ +# +# PARAMETROS RECIBIDOS DESDE EL CLIENTE: +# $1 disco +# $2 par=Número de particion +# $3 Nombre canónico de la imagen +# $4 Dirección IP del repositorio +# $5 Protocolo UNICAST MULTICAST TORRENT +# $6 Opciones del protocolo +#_______________________________________________________________________________________________________________________________ + +# Llamar al script de despliegue "deployImage". +deployImage "$4" "$3" "$1" "$2" "$5" "$6" "$7" "$8" || exit $? + diff --git a/client/interfaceAdm/getConfiguration b/client/interfaceAdm/getConfiguration new file mode 100755 index 0000000..ddfc382 --- /dev/null +++ b/client/interfaceAdm/getConfiguration @@ -0,0 +1,88 @@ +#!/bin/bash + +#_______________________________________________________________________________________________________________________________ +# +# Formato de salida: +# disk=Número de disco\tpar=Número de particion\tcod=Código de partición\tsfi=Sistema de ficheros\tsoi=Sistema instalado\ttam=Tamaño de la partición\n +#_______________________________________________________________________________________________________________________________ + + +# No registrar los errores. +export DEBUG="no" + +ser=$(ogGetSerialNumber) +cfg="" +disks=$(ogDiskToDev | wc -w) +for ((dsk=1; dsk<=$disks; dsk++)); do + particiones=$(ogGetPartitionsNumber $dsk) + particiones=${particiones:-0} + # Tipo de tabla de particiones: 1=MSDOS, 2=GPT + ptt=$(ogGetPartitionTableType $dsk) + case "$ptt" in + MSDOS) ptt=1 ;; + GPT) ptt=2 ;; + LVM) ptt=3 ;; + ZPOOL) ptt=4 ;; + *) ptt=0 ;; + esac + # Información de disco (partición 0) + cfg="$cfg$dsk:0:$ptt:::$(ogGetDiskSize $dsk):0;" + for ((par=1;par<=$particiones;par++)); do + # Código del identificador de tipo de partición + cod=$(ogGetPartitionId $dsk $par 2>/dev/null) + # Tipo del sistema de ficheros + fsi=$(getFsType $dsk $par 2>/dev/null) + fsi=${fsi:-"EMPTY"} + # Tamaño de la particón + tam=$(ogGetPartitionSize $dsk $par 2>/dev/null) + tam=${tam:-"0"} + # Sistema operativo instalado + case "$fsi" in + ""|EMPTY|LINUX-SWAP|LINUX-LVM|ZVOL) + soi=""; uso=0 ;; + *) if [ -n "$(ogMount $dsk $par 2>/dev/null)" ]; then + soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:) + # Hacer un 2º intento para algunos casos especiales. + [ -z "$soi" ] && soi=$(getOsVersion $dsk $par 2>/dev/null | cut -f2 -d:) + # Sistema de archivos para datos (sistema operativo "DATA") + [ -z "$soi" -a "$fsi" != "EMPTY" -a "$fsi" != "CACHE" ] && soi="DATA" + # Obtener porcentaje de uso. + uso=$(df $(ogGetMountPoint $dsk $par) | awk '{getline; printf "%d",$5}') + uso=${uso:0} + else + soi=""; uso=0 + fi + ;; + esac + cfg="$cfg$dsk:$par:$cod:$fsi:$soi:$tam:$uso;" + done +done + +# Crear configuración por defecto para cliente sin disco. +[ -z "$cfg" ] && cfg="1:0:0:::0;" + +# Guardar salida en fichero temporal. +cfgfile=/tmp/getconfig +echo "${ser:+$ser;}$cfg" > $cfgfile + +# Crear el menú por defecto a partir del fichero generado (no dar ninguna salida). +generateMenuDefault &>/dev/null + +# Componer salida formateada. +awk '{ n=split($0,sep,";"); + for (i=1; i/dev/null; then + echo "[10] Configuración personalizada del inicio." + bootOsCustom $@ +fi + +echo "[70] Desmontar todos los sistemas de archivos." +sync +for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do + ogUnmountAll $i &>/dev/null +done +echo "[80] Desmontar cache local." +ogUnmountCache +echo "[90] Arrancar sistema operativo." +ogBoot "$@" diff --git a/client/scripts/bootOsCustom.template b/client/scripts/bootOsCustom.template new file mode 100755 index 0000000..efd4c1f --- /dev/null +++ b/client/scripts/bootOsCustom.template @@ -0,0 +1,92 @@ +#!/bin/bash +#/** +# bootOsCustom +#@brief Plantilla para script de configuración personalizada de sistema operativo restaurado. +#@param $1 nº de disco +#@param $2 nº de partición +#@warning Renombrar este fichero como "bootOsCustom" para personalizar el script estándar "bootOs". +#@note La partición a inicializar debe estar montada +#@version 1.1.1 Soporta varios discos +#@date 2019/08/26 +#**/ +# CONFIGURAR: Partición de datos de Windows que no queremos ocultar (valor por defecto '0' no oculta nada) +DISKDATA=0 +PARTDATA=0 + +PROG="$(basename $0)" +# Control de errores +if [ $# -lt 2 ]; then + ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nparticion" + exit $? +fi + +# Parámetros obligatorios. +DISK="$1" # Nº de disco. +PART="$2" # Nº de partición. + +# Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado). +DEVICE=$(ogDiskToDev "$DISK" "$PART") || exit $? + +# Paso 1: Adaptar el código de ejemplo para arranque personalizado. +# Nota: el script "bootOs" llama al script "bootOsCustom" después de realizar la operaciones de inicio estándar y antes de desmontar las particiones e iniciar el sistema operativo. + + +MNTDIR=$(ogMount $DISK $PART) || exit $? +NAME="$(ogGetHostname)" +NAME=${NAME:-"pc"} +OSTYPE=$(ogGetOsType $DISK $PART) + +case "$OSTYPE" in + Windows) + ## Mostrar las particiones NTFS de sistema (dos opciones) + ## Opción 1: SIN ocultar las demás. + #ogEcho log session "[40] Mostrar y activar particion de Windows $PART." + #[ $(ogGetPartitionType $DISK $PART) == "HNTFS" -o $(ogGetPartitionType $DISK $PART) == "WIN-RESERV" ] && ogUnhidePartition $DISK $PART + + ## Recorremos los distintos discos + #for DEVICE in $(ogDiskToDev); do + # d=$(ogDevToDisk $DEVICE) + + # ## Mostrar las particiones NTFS de sistema (dos opciones) + # ## Opción 2: Ocultamos las demás. + # ogEcho log session "[40] Activar particion de Windows $PART y ocultar las demás." + # for (( i=1; i<=$(ogGetPartitionsNumber $d); i++ )); do + # if [ $d == $DISK -a $i == $PART ] || [ $d == $DISKDATA -a $i == $PARTDATA ]; then + # [ $(ogGetPartitionType $d $i) == "HNTFS" -o $(ogGetPartitionType $d $i) == "WIN-RESERV" ] && ogUnhidePartition $d $i + # else + # [ "$(ogGetPartitionType $d $i)" == NTFS -o "$(ogGetPartitionType $d $i)" == "WINDOWS" ] && ogHidePartition $d $i + # fi + # done + + # ## Borrar marcas de arrranque de todos los Windows instalados en el disco. + # ogEcho log session "[30] Borrar marcas de arrranque de todos los Windows instalados en el disco." + # for (( i=1; i<=$(ogGetPartitionsNumber $d); i++ )); do + # [ "$(ogGetOsType $d $i)" == "Windows" ] && ogMount $d $i &>/dev/null + # done + # rm -f /mnt/*/ogboot.* + + #done + ;; + Linux) + ## Modificar el nombre del equipo + #ogEcho log session "[30] Asignar nombre Linux \"$NAME\"." + #ETC=$(ogGetPath $DISK $PART /etc) + #[ -d "$ETC" ] && echo "$NAME" >$ETC/hostname 2>/dev/null + + ## Sustituir UUID o LABEL por su dispositivo en definición de sistema de archivo raíz. + #if [ -f "$ETC/fstab" ]; then + # ogEcho log session "[40] Actualizar fstab con particion raíz \"$PART\"." + # awk -v P="$PART " '{ if ($2=="/" && $1!~/^#/) {sub(/^.*$/, P, $1)} + # print }' $ETC/fstab >/tmp/fstab + # mv /tmp/fstab $ETC/fstab + #fi + + ## Cambiar claves usuarios, copiando fichero /etc/passwd + ## En el servidor el nuevo fichero debe situarse en el directorio del grupo: + ## /opt/opengnsys/images/groups/nombre_aula + #if [ -r $(ogGetGroupDir)/passwd ]; then + # ogEcho log session "[65] Cambiar claves de usuarios." + # cp $(ogGetGroupDir)/passwd $MNTDIR/etc + #fi + ;; +esac diff --git a/client/scripts/bootWindows b/client/scripts/bootWindows new file mode 120000 index 0000000..d19be90 --- /dev/null +++ b/client/scripts/bootWindows @@ -0,0 +1 @@ +bootOs \ No newline at end of file diff --git a/client/scripts/buildToOrder b/client/scripts/buildToOrder new file mode 100755 index 0000000..5bbc938 --- /dev/null +++ b/client/scripts/buildToOrder @@ -0,0 +1,79 @@ +#!/bin/bash + +#/** +# BuildToOrder +#@brief Script de ejemplo para realizar una configuracion del sistema operativo antes de generar imagen o de restaurado. +#@brief Activa el uso de los contralodres de disco más usados en windows 7. +#@brief (puede usarse como complemento para el programa de creación de imágenes o de restauración). +#@param 1 disco +#@param 2 particion +#@return +#@TODO +#@exception +#@version 1.0.4 - Discos ide + SATA. +#@author +#@date 2012-10-05 +#@version 1.1.1b - Funciona para Windows8 y Windows 10. Si la clave no existe (tiene valor vacío) se crea. +#@date 2020-05-04 + + +#Control de parametros. +PROG="$(basename $0)" +if [ $# -ne 2 ]; then + ogRaiseError $OG_ERR_FORMAT "Formato: $PROG ndisco nparticion" + exit $? +fi + + +MNTDIR=$(ogMount $1 $2) + +# filtro Tipo de sistema operativo. +OSTYPE="$(ogGetOsType $1 $2)" + + +case "$OSTYPE" in + Windows) + echo "Filtro versión de sistema operativo windows." + TYPE=$(ogGetOsVersion $1 $2) + case "$TYPE" in + *Windows\ XP) + echo "Versión de sistema operativo Windows XP no soportado" + exit + ;; + *Windows\ 7*) + # Claves a modificar + KEYS="intelide pciide msahci iaStorV iaStor LSI_SAS" + + ;; + *Windows\ *8*|*10*) + # Claves a modificar + KEYS="intelide pciide storahci iaStorV iaStorAC iaStorAVC LSI_SAS" + ;; + esac + + echo "$TYPE" + CONTROLSET="ControlSet001 ControlSet002" + for C in $CONTROLSET; + # Si no existe la rama de registro continuo a la siguiente. + [ "$(ogListRegistryKeys $MNTDIR SYSTEM '\'${C})" == "" ] && continue + + for K in $KEYS; do + FULLK='\'$C'\Services\'$K'\Start' + VALUE=$(ogGetRegistryValue $MNTDIR SYSTEM "$FULLK") + # Si el valor está vacío la creo. + if [ "$VALUE" == "" ]; then + ogDeleteRegistryValue $MNTDIR SYSTEM "$FULLK" + ogAddRegistryValue $MNTDIR SYSTEM "$FULLK" DWORD + fi + ogSetRegistryValue $MNTDIR SYSTEM "$FULLK" '0' + echo " * $C $K enabled" + done + done + ;; + Linux) + echo "Versión de Sistema Operativo GNU/Linux no soportado" + ;; + *) + echo "Sistema Operativo no soportado" + ;; +esac diff --git a/client/shared/scripts/buildToOrder.py b/client/scripts/buildToOrder.py similarity index 100% rename from client/shared/scripts/buildToOrder.py rename to client/scripts/buildToOrder.py diff --git a/client/scripts/cloneRemoteFromMaster b/client/scripts/cloneRemoteFromMaster new file mode 100755 index 0000000..6d8001d --- /dev/null +++ b/client/scripts/cloneRemoteFromMaster @@ -0,0 +1,324 @@ +#!/bin/bash + +#/** +# cloneremoteFromMaster +#@brief Restaura una particion o imagen sobre las particiones de equipos cliente remotos +#@param 1 str_origen admite dirección IP del equipo Master. +#@param 2 str_origen admite int_disk str_REPO|str_CACHE +#@param 3 str_origen admite int partorigen stre_imagen +#@param 4 str_sesion multicast|unicast +#@param $5 int_disco_destino +#@param $6 init_particion_destino +#@param $7 str_tool_clone +#@param $8 str_tool_compresor +#@param ejemplo: cloneRemoteFromMaster 172.17.36.11 1 1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop +#@param ejemplo: cloneRemoteFromMaster 172.17.36.11 REPO /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop +#@param ejemplo: cloneRemoteFromMaster 172.17.36.11 CACHE /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop +#@return +#@exception OG_ERR_FORMAT formato incorrecto. +#@exception $OG_ERR_IMGSIZEPARTITION=30 #Imagen demasiado pequeña para ser clonada +#@exception OG_ERR_REDUCEFS=17 #error al reducir sistema de archivos. +#@exception OG_ERR_EXTENDFS=18 #errror al expandir el sistema de archivos. +#@exception OG_ERR_UCASTSYNTAXT=50 # Error en la generación de sintaxis de transferenica unicast +#@exception OG_ERR_UCASTSENDPARTITION=51 # Error en envio UNICAST de una particion +#@exception OG_ERR_UCASTSENDFILE=52 # Error en envio UNICAST de un fichero +#@exception OG_ERR_UCASTRECEIVERPARTITION=53 #Error en la recepcion UNICAST de una particion +#@exception OG_ERR_UCASTRECEIVERFILE=54 #Error en la recepcion UNICAST de un fichero +#@exception OG_ERR_MCASTSYNTAXT=55 # Error en la generacion de sintaxis de transferenica Multicast. +#@exception OG_ERR_MCASTSENDFILE=56 # Error en envio MULTICAST de un fichero +#@exception OG_ERR_MCASTRECEIVERFILE=57 #Error en la recepcion MULTICAST de un fichero +#@exception OG_ERR_MCASTSENDPARTITION=58 # Error en envio MULTICAST de una particion +#@exception OG_ERR_MCASTRECEIVERPARTITION=59 # Error en la recepcion MULTICAST de una particion +#@exception OG_ERR_PROTOCOLJOINMASTER=60 # Error en la conexion de una sesion UNICAST|MULTICAST con el MASTER +#@note +#@todo: +#@version 0.9.1 - integración con OpenGnsys +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2009/03/17 +#@version 0.9.2 - adaptacion a OpenGnsys +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2010/07/27 +#@version 0.1.0 - gestion unicast +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011/01/26 +#@version 1.0 - control de errores para el ogAdmServer +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011/04/24 +#@version 1.0 - Uso de parted para controlar tamaño particion destino. Requiere Formateo FS previo -parted usa FS para el tamanyo". +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011/04/24 +#@version 1.0.1 - Se elimina la operación de reducir la particion. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011/05/16 +#@version 1.0.3 - se integra con httpd-log. +#@version 1.0.3 - Habilita el uso de la variable OGWINREDUCE=TRUE|TRUE para reducir el sistema de archivos a enviar +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011/12/22 +#@version 1.0.6 - Uso de la funcion ogExecuteAndLog +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2012/02/12 +#@version 1.1.0.a - sesion multicast cliente puerto:master:0:0 (ticket #872) +#@author Antonio J. Doblas Viso +#@date 2018/09/11 +#*/ ## +#*/ ## + +#test 1. cliente sin particiones. Detectado TODO: crear estrucutras de particiones +#test 2. cliente con particion mas pequeña. Detectado. +#test 3. cleinte con particion destinio no formateado. Detectado. +#test 4. cliente con particion destino ocupado por el usuario pwd . FALLO. +#test 5. master sin origen particion. +#test 6. master sin origen fichero. + +TIME1=$SECONDS +PROG="$(basename $0)" + +trap "pkill faucet; exit 1" 0 1 2 3 6 9 14 15 + +#AYUDA +if [ $# -lt 1 -o "$1" == "help" ]; then + echo "cloneRemoteFromMaster ipmaster disk init [MULTICAST|UNICAST] session disk part tool comp" + exit 1 +fi + +#ERROR +if [ $# -lt 6 ]; then + ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ipMaster SOURCE_disco SOURCE_particion [MULTICAST|UNICAST] SESSION TARGET_disk TARGET_partition" + exit $? +fi + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE" +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo " " > $OGLOGCOMMAND + +ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" + +# Procesar parámetros de entrada +HOSTIP=`ogGetIpAddress` +if [ -z "$HOSTIP" ] +then + source /tmp/net-eth* + HOSTIP=`ogGetIpAddress` +fi +MASTERIP="$1" +PROTOCOL="$4" +case "${PROTOCOL^^}" in + MULTICAST) + SESSIONMCASTSERVER=$5 + SESSIONMCASTCLIENT=`echo $5 | awk -F: '{print $1}'`:$MASTERIP:0:0 + ;; + UNICAST) + SESSIONUCASTSERVER=$5 + SESSIONUCASTCLIENT=`echo $5 | awk -F: '{print $1}'`:$MASTERIP + ;; + *) + exit $(ogRaiseError $OG_ERR_FORMAT "Protocolo $PROTOCOL no soportado en esta operacion"; echo $?) +;; +esac +# contenedor destino (disco particion) +DISKTARGET="$6" +PARTTARGET="$7" +#herramienta de compresión. +TOOLCLONE="$8" +COMPRESOR="$9" + +pkill faucet + +# Preparando Instrucción según sea Master o Client +case $MASTERIP in + $HOSTIP) + ogEcho log session "[1] Equipo Master preparando el origen de los datos a enviar" + ogGetPath $2 $3.img &>/dev/null; RC=$?; + ogDiskToDev $2 $3 &>/dev/null; RETVAL=$?; + + if [ "$RC" == "0" ]; then + IMG=$(ogGetPath $2 $3.img); MODEMASTER=SENDFILE + elif [ "$RETVAL" == "0" ]; then + DISKSOURCE=$2; PARTSOURCE=$3; MODEMASTER=SENDPARTITION + else + ogRaiseError $OG_ERR_NOTFOUND "$2 $3"; exit $? + fi + echo $MODEMASTER + # Preparando instrucción del Master segun $MODEMASTER{SENDPARTITION SENDFILE} + case "$MODEMASTER" in + SENDPARTITION) + ogEcho log session "[5] Master en modo $MODEMASTER: informacion inicial a los clientes-slaves" + if ps aux | grep -v grep | grep "faucet 4000" + then + ogRaiseError $OG_ERR_NOTFOUND "MASTER: puerto en uso: 118"; exit $? + else + faucet 4000 --out echo "WORKING" & + fi + ogEcho log session "[10]: Desmontando DISK:$DISKSOURCE PARTITION:$PARTSOURCE" + ogUnmount $2 $3 || exit $(ogRaiseError $OG_ERR_LOCKED "no se puede desmontar $2 $3 l124"; echo $?) + #Obtener tamaño de la partición. + SIZE=$(ogGetPartitionSize $2 $3) || exit $(ogRaiseError $OG_ERR_REDUCEFS "Error al detectar tamaño partcion $2 $3 l127"; echo $?) + + # Si es UEFI copio el cargador de arranque a la partición + OSTYPE="$(ogGetOsType $2 $3)" + if ogIsEfiActive && [ "$OSTYPE" == "Windows" ]; then + ogEcho log session "[12] $MSG_HELP_ogCopyEfiBootLoader" + ogCopyEfiBootLoader $2 $3 + fi + + if [ "$OGWINREDUCE" == "TRUE" ] + then + ogEcho log session "[15]: Calculando la reduccion del sistema de archivos DISK:$DISKSOURCE PARTITION:$PARTSOURCE SIZE:$SIZE" + ogReduceFs $2 $3 || exit $(ogRaiseError $OG_ERR_REDUCEFS "Error al reducir el FS $2 $3 l129"; echo $?) + fi + + REDSIZE=$(ogGetFsSize $2 $3) || exit $(ogRaiseError $OG_ERR_REDUCEFS "Error al detectar el nuevo FS $2 $3 l130"; echo $?) + TIMEAUX=$[SECONDS-TIME1] + ogEcho log session "[20]: Preparada para enviar el sistema de archivos: Tamaño datos: $REDSIZE origne: $DISKSOURCE $PARTSOURCE" + ogEcho log session " tiempo de reducción del sistema de archivos: $[TIMEAUX/60]m $[TIMEAUX%60]s" + + #if [ $REDSIZE -lt $SIZE ]; then + # echo "[24] Redimensionar partición a $REDSIZE KB." + # ogSetPartitionSize $2 $3 $REDSIZE + #fi + + ogEcho log session "[25] Master en Modo $MODEMASTER: informacion de transferencia a los clientes-slaves $PROTOCOL $TOOLCLONE $COMPRESOR $REDSIZE" + pkill faucet + if ps aux | grep -v grep | grep "faucet 4000" + then + ogRaiseError $OG_ERR_NOTFOUND "MASTER: puerto en uso: 140"; exit $? + else + faucet 4000 --out echo "READY $TOOLCLONE $COMPRESOR $REDSIZE" & + fi + case "${PROTOCOL^^}" in + MULTICAST) + ogEcho log session "[29] Transferencia Multicast: ogMcastSendPartition $DISKSOURCE $PARTSOURCE $SESSIONMCASTSERVER $TOOLCLONE $COMPRESOR " + ogExecAndLog session "ogMcastSendPartition" "$DISKSOURCE" "$PARTSOURCE" "$SESSIONMCASTSERVER" "$TOOLCLONE" "$COMPRESOR" || RETVAL=$? + ;; + UNICAST) + sleep 60 + ogEcho log session "[29] Transferencia Unicast: ogUcastSendPartition $DISKSOURCE $PARTSOURCE $SESSIONUCASTSERVER $TOOLCLONE $COMPRESOR" + ogExecAndLog session "ogUcastSendPartition" "$DISKSOURCE" "$PARTSOURCE" "$SESSIONUCASTSERVER" "$TOOLCLONE" "$COMPRESOR" || RETVAL=$? + ;; + esac + + #if [ $REDSIZE -lt $SIZE ]; then + # echo "[85] Redimensionar partición a $SIZE KB." + # ogSetPartitionSize $2 $3 $SIZE + ogEcho log session "[90] Extender sistema de archivos." + ogExtendFs $2 $3 + #fi + pkill faucet + if [ $RETVAL == 0 ] + then + exit 0 + else + exit $(ogRaiseError $OG_ERR_MCASTSENDPARTITION "Error al enviar la particion $2 $3 con protocolo $PROTOCOL l167"; echo $?) + fi + + ;; + SENDFILE) + ogEcho log session "[5] Master en modo $MODEMASTER: informacion inicial a los clientes-slaves" + ogEcho log session "[10]: Preparando Imagen: $IMG" + TOOLCLONE=$(ogGetImageProgram $2 $3) || exit $(ogRaiseError $OG_ERR_LOCKED "TOOLCLONE no detectado l174"; echo $?) + COMPRESOR=$(ogGetImageCompressor $2 $3) || exit $(ogRaiseError $OG_ERR_LOCKED "COMPRESOR NO DETECTADO l175"; echo $?) + REDSIZE=$(ogGetImageSize $2 $3) || exit $(ogRaiseError $OG_ERR_LOCKED "REDSIZE NO DETECTADO l176"; echo $?) + ogEcho log session "[25] Master en Modo $MODEMASTER" + ogEcho log "Informacion de transferencia a los clientes-slaves $PROTOCOL $TOOLCLONE $COMPRESOR $REDSIZE" + if ps aux | grep -v grep | grep "faucet 4000" + then + ogRaiseError $OG_ERR_NOTFOUND "MASTER: puerto en uso: 140"; exit $? + else + faucet 4000 --out echo "READY $TOOLCLONE $COMPRESOR $REDSIZE" & + fi + case "${PROTOCOL^^}" in + MULTICAST) + echo "[29] ogMcastSendFile $2 $3.img $SESSIONMCASTSERVER " + ogMcastSendFile $2 $3.img $SESSIONMCASTSERVER || RETVAL=$? + ;; + UNICAST) + sleep 60 + echo "[29] ogUcastSendFile $2 $3.img $SESSIONUCASTSERVER" + ogUcastSendFile $2 $3.img $SESSIONUCASTSERVER || RETVAL=$? + ;; + esac + pkill faucet + if [ $RETVAL == 0 ] + then + exit 0 + else + exit $(ogRaiseError $OG_ERR_MCASTSENDFILE "Error al enviar la image $2 $3.img con protocolo $PROTOCOL l200"; echo $?) + fi + ;; + esac + # FIN Preparando instrucción del Master segun $MODEMASTER{SENDPARTITION SENDFILE} + ;; + *) + ogEcho log session "[1] Equipo -Client- preparando para recibir datos $PROTOCOL" + ogDiskToDev $DISKTARGET $PARTTARGET &>/dev/null || exit $(ogRaiseError $OG_ERR_LOCKED "El cliente no tiene esas particiones $DISKTARGET $PARTTARGET l211"; echo $?) + # TODO: si el cliente no está en la lista de clientes UNICAST salir. + case "${PROTOCOL^^}" in + UNICAST) + echo "$SESSIONUCASTSERVER" | grep $HOSTIP || exit $(ogRaiseError $OG_ERR_PROTOCOLJOINMASTER "Este cliente no pertence a la sesion UNICAST l214"; echo $?) + ;; + esac + ogEcho log session "[2] Desmontando particion destino" + ogUnmount $DISKTARGET $PARTTARGET || exit $(ogRaiseError $OG_ERR_LOCKED "no se puede desmontar la particion destino $2 $3 l218"; echo $?) + ogEcho log session "[25] Buscando informacion extra sobre la clonacion con el master $MASTERIP: " + sleep 10 + TIMEWAITMASTER=120 + TIMEWAITING=0 + GETINFO="NONE" + while [ "${GETINFO}" != "OK" ] + do + INFOEXTRA=`hose $MASTERIP 4000 --in cat 2>/dev/null` + sleep 10; echo -n "." + #echo comienza el timeout $TIMEWAITMASTER para abortar + [ -z "$INFOEXTRA" ] && let TIMEWAITMASTER=$TIMEWAITMASTER-10 + [ "$TIMEWAITMASTER" -gt "0" ] || exit $(ogRaiseError $OG_ERR_PROTOCOLJOINMASTER " l230 "; echo $?) + #Si primer parametro desde el server es READY, salimos del bucle + GETINFO=$(echo $INFOEXTRA | awk '{print $1}') + [ "$GETINFO" == "READY" ] && GETINFO="OK" + done + echo $INFOEXTRA + TOOLCLONE=$(echo $INFOEXTRA | awk '{print $2}') + COMPRESOR=$(echo $INFOEXTRA | awk '{print $3}') + SIZEIMAGE=$(echo $INFOEXTRA | awk '{print $4}') + ogEcho log "$INFOEXTRA = herramienta= $TOOLCLONE compresor= $COMPRESOR size= $SIZEIMAGE" + ogMount $DISKTARGET $PARTTARGET || ogFormat $DISKTARGET $PARTTARGET + #SIZEPARTTARGET=$(parted `ogDiskToDev $DISKTARGET $PARTTARGET` unit kB print | grep Disk | awk -F" " '{print $3}' | tr -d kB); + SIZEPARTTARGET=$(ogGetPartitionSize $DISKTARGET $PARTTARGET ) + ogEcho log session "[28] comprobando que el tamaño de la imagen $SIZEIMAGE es menor que el de la particion destino $SIZEPARTTARGET" + # comprobamos que el tamaño de a imagen es menor que la del cliente. + if [ "$SIZEIMAGE" -lt "$SIZEPARTTARGET" ] + then + ogEcho log session "[30] Iniciando Cliente $PROTOCOL " + case "${PROTOCOL^^}" in + MULTICAST) + ogEcho log session "ogMcastReceiverPartition $DISKTARGET $PARTTARGET $SESSIONMCASTCLIENT $TOOLCLONE $COMPRESOR" + ogExecAndLog command "ogMcastReceiverPartition" "$DISKTARGET" "$PARTTARGET" "$SESSIONMCASTCLIENT" "$TOOLCLONE" "$COMPRESOR" || exit $(ogRaiseError $OG_ERR_MCASTRECEIVERPARTITION " l251 "; echo $?) + ;; + UNICAST) + ogEcho log session "ogUcastReceiverPartition $DISKTARGET $PARTTARGET $SESSIONUCASTCLIENT $TOOLCLONE $COMPRESOR" + ogExecAndLog command "ogUcastReceiverPartition" "$DISKTARGET" "$PARTTARGET" "$SESSIONUCASTCLIENT" "$TOOLCLONE" "$COMPRESOR" || exit $(ogRaiseError $OG_ERR_UCASTRECEIVERPARTITION " l230 "; echo $?) + ;; + esac + if which configureOsCustom &>/dev/null; then + ogEcho log session "[90] configureOsCustom $DISKTARGET $PARTTARGET" + # Si $2 = num_disk las varibles REPO IMGNAME estan vacias + ! [[ $2 =~ ^[0-9]+$ ]] && REPO="$2" && IMGNAME="$3" + configureOsCustom $DISKTARGET $PARTTARGET $REPO $IMGNAME + else + ogEcho log session "[90] $MSG_SCRIPTS_OS_CONFIGURE $DISKTARGET $PARTTARGET" + configureOs $DISKTARGET $PARTTARGET + fi + + else + # Si el tamaño de los datos recibidos es más grande que la particion destino + ogRaiseError $OG_ERR_IMGSIZEPARTITION "ERROR tamanio particion= $SIZEPARTTARGET menor que la imagen= $SIZEIMAGE"; exit $? + fi + ;; +esac +TIME=$[SECONDS-TIME1] +ogEcho log session "[100] Duración de la operación $[TIME/60]m $[TIME%60]s" + diff --git a/client/shared/scripts/configureOSCustomTemplate.py b/client/scripts/configureOSCustomTemplate.py similarity index 100% rename from client/shared/scripts/configureOSCustomTemplate.py rename to client/scripts/configureOSCustomTemplate.py diff --git a/client/scripts/configureOs b/client/scripts/configureOs new file mode 100755 index 0000000..3f39c23 --- /dev/null +++ b/client/scripts/configureOs @@ -0,0 +1,175 @@ +#!/bin/bash + +#/** +# configureOs +#@brief Script para realizar la configuracion del sistema operativo restaurado. +#@param 1 disco +#@param 2 particion +#@return +#@TODO comprobar que el tipo de particion corresponde con el sistema de archivos. +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@version 1.0.1 - Integracion cambio de nombre, extender fs, chequear particion activa +#@author +#@date 2011-05-11 +#@version 1.0.1 - Configura el sector de la particion y el gestor de windows para iniciarse desde cualquier particion. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011-05-20 +#@version 1.0.2 - Configura el sector de la particion y el gestor de linux para iniciarse desde cualquier particion. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011-11-22 +#@version 1.0.3 - Configura el chkdisk en el arranque de windows, segun variable OGWINCHKDISK del engine.cfg. +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2011-12-23 +#@version 1.0.4 - Inyecta el cliente para gestión del sistema operativo. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2012-04-11 +#@version 1.0.5 - Postconfiguración para Mac OS X. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2013-10-11 +#@version 1.1.0 - Postconfiguración para agente de sistema operativo basado en REST. +#@author Ramon Gomez, ETSII Universidad de Sevilla +#@date 2016-08-16 +#@version 1.0.6b - llamadas opcionales para mejoras varias. Descomentar la instruccion para su activacion. ogConfigureFstab +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2016-11-03 +#@version 1.1.1 - Equipos UEFI: para Windows copia cargador de arranque a partición UEFI, para linux configura particion ESP en fstab. (ticket #802 #889 #890) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2019-01-08 +#*/ ## + +# Carga el configurador del engine y los parámetros de red. +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg +[ -f $DEVICECFG ] && source $DEVICECFG + +# Si el sistema de archivos no esta extendido, ampliarlo al tamaño de su partición. +PARTSIZE=$(ogGetPartitionSize $1 $2) || exit $? +FSSIZE=$(ogGetFsSize $1 $2) +if [ $FSSIZE -lt $PARTSIZE ]; then + echo "Extender sistema de archivos." + ogExtendFs $1 $2 +fi + +# Si no existe partición activa, activar este sistema. +FLAGACTIVE=$(ogGetPartitionActive $1) +[ -z $FLAGACTIVE ] && ogSetPartitionActive $1 $2 + +# Si el sistema de archivos es de solo lectura, no hacer la post-configuración. +MNTDIR=$(ogMount $1 $2) +if ! ogIsWritable $1 $2; then + echo "AVISO: sistema de archivos de solo lectura, no se ejecuta postconfiguración." + exit +fi + +# Nombre del cliente. +HOST="$(ogGetHostname)" + +# Post-configuración personalizada para cada tipo de sistema operativo. +OSTYPE="$(ogGetOsType $1 $2)" +case "$OSTYPE" in + Windows) # Postconfiguración de Windows. + # Cambiar nombre en sistemas Windows. + HOST=${HOST:-"pc"} + ogSetWindowsName $1 $2 "$HOST" + # Si es UEFI copio el cargador de arranque a la partición EFI e instalo Grub. + if ogIsEfiActive; then + ogRestoreEfiBootLoader $1 $2 + ogGrubInstallMbr $(ogGetEsp) TRUE + else + # Configurar el boot sector de la partición Windows. + ogFixBootSector $1 $2 + fi + # Configurar el gestor de arranque de Windows XP/Vista/7. + ogWindowsBootParameters $1 $2 + # Registrar en Windows que la partición indicada es su nueva unidad C:\ + ogWindowsRegisterPartition $1 $2 C $1 $2 + # Configurar nuevo agente OGAgent. + ogConfigureOgagent $1 $2 + # Eliminar el antiguo cliente de Windows. + if [ -n "$(ogGetPath $MNTDIR/windows/ogAdmWinClient.exe)$(ogGetPath $MNTDIR/winnt/ogAdmWinClient.exe)" ]; then + ogInstallMiniSetup $1 $2 postconf.cmd + ogUninstallWindowsClient $1 $2 postconf.cmd + fi + ;; + Linux) # Postconfiguración de GNU/Linux. + # Configuro fstab: particion de Swap y si es UEFI además la partición EFI. + ogConfigureFstab $1 $2 + # Si es UEFI instalo Grub en la partición EFI + ogIsEfiActive && ogGrubInstallMbr $(ogGetEsp) TRUE + ## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen) + ogGrubInstallPartition $1 $2 + # Eliminar el antiguo cliente de Linux. + [ -n "$(find $MNTDIR/usr/sbin $MNTDIR/sbin $MNTDIR/usr/local/sbin -name ogAdmLnxClient -print)" ] && ogUninstallLinuxClient $1 $2 + # Configurar nuevo agente OGAgent. + ogConfigureOgagent $1 $2 + ## Modificar el nombre del equipo + echo "Asignar nombre Linux \"$HOST\"." + ETC=$(ogGetPath $1 $2 /etc) + [ -d "$ETC" ] && echo "$HOST" >$ETC/hostname 2>/dev/null + ;; + MacOS) # Postconfiguración de Mac OS X. + # Fichero indicador de activación de postconfiguración. + touch $MNTDIR/osxpostconf + + # Crear fichero de configuración del servicio de arranque. + cat << EOT >$MNTDIR/Library/LaunchDaemons/es.opengnsys.postconfd.plist + + + + Label + es.opengnsys.postconfd.sh + ProgramArguments + + /var/root/postconfd.sh + + RunAtLoad + + StandardOutPath + /var/log/postconfd.log + StandardErrorPath + /var/log/postconfd.err + Debug + + + +EOT + + # Programa de inicio que será ejecutado en el arranque de Mac OS X. + cat << EOT >$MNTDIR/var/root/postconfd.sh +#!/bin/bash +# postconfd - ejecución de scripts de inicio. + +# Ejecutar postconfiguración si existe el fichero indicador. +if [ -e /osxpostconf ]; then + # Tomar nombre del equipo. + HOST="$HOST" + if [ -z "\$HOST" ]; then + # Si no hay nombre asociado, activar la red para obtener datos del DHCP. + source /etc/rc.common + CheckForNetwork + while [ "\$NETWORKUP" != "-YES-" ]; do + sleep 5 + NETWORKUP= + CheckForNetwork + done + # Componer nombre del equipo a partir de datos del DHCP. + IP=\$(ifconfig en0 inet | awk '{if (\$1=="inet") print \$2}') + HOST="mac-\$(echo \${IP//./-} | cut -f3-4 -d-)" + fi + # Asignar nombre del equipo. + scutil --set ComputerName "\$HOST" + scutil --set LocalHostName "\$HOST" + scutil --set HostName "\$HOST" + hostname "\$HOST" + # Descromprimir ficheros de versión para obtener inventario de aplicaciones. + find /Applications -type d -name "*.app" -prune -exec \ + ditto --nopreserveHFSCompression "{}/Contents/version.plist" "{}/Contents/version.plist.uncompress" + rm -f /osxpostconf # Borrar fichero indicador de psotconfiguración +fi +EOT + # Dar permiso de ejecución. + chmod 700 $MNTDIR/var/root/postconfd.sh + # Configurar nuevo agente OGAgent de sistema operativo. + ogConfigureOgagent $1 $2 + ;; +esac +exit 0 diff --git a/client/shared/scripts/configureOs.py b/client/scripts/configureOs.py similarity index 100% rename from client/shared/scripts/configureOs.py rename to client/scripts/configureOs.py diff --git a/client/scripts/configureOsCustom.template b/client/scripts/configureOsCustom.template new file mode 100644 index 0000000..f1c8e2a --- /dev/null +++ b/client/scripts/configureOsCustom.template @@ -0,0 +1,81 @@ +#!/bin/bash +#/** +# configureOsCustom +#@brief Plantilla para scirpt de configuracion personalizada de sistema operativo restaurado. +#@param $1 nº de disco +#@param $2 nº de partición +#@param $3 Repositorio: CACHE, REPO o dirección IP (opcional) +#@param $4 Nombre canónico de la imagen sin extensión (opcional) +#@warning Renombrar este fichero como "configureOsCustom" para sustituir al script estándar "configureOs". +#@note Los parámetros disco y partición son obligatorios y opcionalmente puede recibir también el repositorio y la imagen usada para en el despliegue. +#**/ + + +# Control de parámetros. +[ $# -eq 2 -o $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: configureOsCustom int_ndisc int_npart [str_repo str_imgname]" || exit $? + +# Parámetros obligatorios. +DISK="$1" # Nº de disco. +PART="$2" # Nº de partición. +# Parámetros opcionales. +REPO="${3^^}" # Repositorio (en mayúsculas). +IMGNAME="$4" # Nombre canónico de imagen (sin extensión). + + +# Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado). + +# Paso 1: Adaptar el código de ejemplo para postconfiguración personalizada. +# Nota: incluye llamada al script "configureOs" para realizar previamente una configuración estándar. + +# Configurarción típica. +configureOs "$1" "$2" +# Postconfiguración personalizada para cada tipo de sistema operativo. +OSTYPE="$(ogGetOsType $1 $2)" +case "$OSTYPE" in + Windows) # Postconfiguración de Windows. + # Descomentar la siguiente línea para cambiar usuario de inicio. + #ogSetWinlogonUser $1 $2 " " + # OPCIONAL: desactivar el chkdisk de windows tras la restauracion. Requiere configuracion previa en el engine.cfg + #ogLoadHiveWindows $1 $2; ogSetWindowsChkdisk $OGWINCHKDISK; ogUpdateHiveWindows + ;; + Linux) # Postconfiguración de GNU/Linux. + ##OPCIONAL Para UEFI: cambia el UUID de la partición (para tener dos linux en un equipo) + #ogUuidChange $DISK $PART + ##OPCIONAL Limpiar dispositivos reconocidos previamente + #ogCleanLinuxDevices $1 $2 + ## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen) + #ogGrubInstallPartition $1 $2 + ## OPCIONAL: instala y configura el codigo de arranque del Grub en el MBR (no lo configura, se mantiene el original de la imagen) + #ogGrubInstallMbr $1 $2 + ## OPCIONAL: Instala y configura el Grub en el MBR y lo autoconfigura, entradas para los sitemas operativos, ademas al linux restaurado le añade los parmetros indicados. + #ogGrubInstallMbr $1 $2 TRUE "irqpoll pci=noacpi noresume quiet splash" + ;; + MacOS) # Postconfiguración de Mac OS X. + # Programa de inicio que será ejecutado en el arranque de Mac OS X. + # NOTA: no modificar la línea siguiente. + cat << EOT | sed -n -e '/rm -f /r /dev/stdin' -e 1x -e '2,${x;p}' -e '${x;p}' $MNTDIR/var/root/postconfd.sh + + ### NOTA: descomentar las opciones deseadas. + # Activar Journaling en HFS+ (no usar si el cliente continua en OpenGnsys). + #diskutil enableJournal disk$[$1-1]s$2 + # Pedir usuario y clave en pantalla de conexión. + #defaults write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME -bool yes + # No mostrar botón de cambio rápido de usuario. + #defaults write /Library/Preferences/.GlobalPreferences MultipleSessionEnabled -bool NO + # Bloquear escritorio, fondo, dock, etc del usuario "usuario". + #chflags uchange /Users/usuario/Library/Preferences/com.apple.desktop.plist + #chflags uchange /Users/usuario/Library/Preferences/com.apple.dock.plist + #chflags uchange /Users/usuario/Desktop + # Añadir usuario "usuario" a la lista de desarrolladores de Xcode. + #DevToolsSecurity --enable + #dscl . -append /Groups/_developer GroupMembership usuario + # Bajar volumen (valor entre 0 y 7). + #osascript -e 'set volume 1' + +EOT + # NOTA: no modificar la línea anterior. + ;; +esac + +# Paso 2: Incluir código genérico de postconfiguración. + diff --git a/client/scripts/createImage b/client/scripts/createImage new file mode 100755 index 0000000..be1cb43 --- /dev/null +++ b/client/scripts/createImage @@ -0,0 +1,182 @@ +#!/bin/bash + +#/** +#@file createImage +#@brief Scirpt de ejemplo para crear una imagen de un sistema de archivos. +#@brief Se usa como base para el programa de creación de imágenes de OpenGnsys Admin). +#@param 1 disco +#@param 2 particion +#@param 3 REPO|CACHE +#@param 4 imagen +#@return +#@exception OG_ERR_FORMAT # 1 formato incorrecto. +#@exception OG_ERR_PARTITION # 3 Error en partición de disco o en su sistema de archivos +#@exception OG_ERR_IMAGE # 5 Error en funcion ogCreateImage o ogRestoreImage. +#@exception OG_ERR_NOTWRITE # 14 error de escritura +#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15 +#@exception OG_ERR_CACHESIZE # 16 si espacio de la cache local o remota no tiene espacio 16 +#@exception OG_ERR_REDUCEFS # 17 error al reducir sistema de archivos. +#@exception OG_ERR_EXTENDFS # 18 Errror al expandir el sistema de archivos. +#@note +#@todo: que hacer, si el tamaño de la cache es sufciente, pero no tiene espacio libre +#@todo: que hacer, si hay una imagen con igual nombre en la cache +#@version 1.0 - control de errores para el ogAdmServer +#@author +#@date 2011-04-10 +#@version 1.0.1 - Control de espacio requerido +#@author Antonio J.Doblas Viso +#@date 2011-05-10 +#@version 1.0.2 - Separacion de log +#@author Antonio J.Doblas Viso +#@date 2011-08-4 +#@version 1.1.0 - La copia de seguridad de la imagen antigua se hace después de las comprobaciones. +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2016-10-14 +#@version 1.1.0 - Se muestra el espacio necesario para alojar la imagen y el disponible (ticket #771) +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2017-03-28 +#@version 1.1.1 - #802 Equipos EFI: se guarda el cargador de arranque y UUID de las particiones +#@author Irina Gomez - ETSII Universidad de Sevilla +#@date 2019-01-08 +#*/ ## + +# Test 1. crear una imagen en un REPO sin espacio libre. +# test 2. crear una imagen en un REPO en modo solo lectura. +# test 3. intentar crear una imagen en la cache de un equipo que no la disponga. +# test 4. crear una imagen en la Cache sin espacio sufiente. +# test 5. intentar crear una imagen, en la que no se puede reducir el FS. + + +PROG="$(basename $0)" +if [ $# -ne 4 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion REPO|CACHE imagen" + exit $? +fi + +TIME1=$SECONDS + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Valores por defecto en etc/engine.cfg +#IMGPROG="partclone" +#IMGCOMP="lzop" +IMGEXT=${IMGEXT:-"img"} +#IMGREDUCE="TRUE" +REPO="${3^^}" + +# Unidad organizativa +[ "$ogunit" != "" ] && OGUNIT="$ogunit" + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +# salvo si es llamado desde createImageCustom +if [ "$(ogGetCaller)" != "createImageCustom" ]; then + echo " " > $OGLOGSESSION; echo " " > $OGLOGCOMMAND; echo " " > ${OGLOGCOMMAND}.tmp +fi + +ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" + +# Si es una ip y es igual a la del equipo restaura desde cache +[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPO +if [ $? == 0 -o $REPO == "REPO" ] ; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO'; echo $?) + REPO="REPO" +fi + +# Si el repositorio es CACHE comprobamos que exista +if [ "$REPO" == "CACHE" ]; then + ! ogFindCache >/dev/null && exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?) +fi + +# Obtener información de los parámetros de entrada. +PART=$(ogDiskToDev "$1" "$2" 2>/dev/null) || exit $(ogRaiseError $OG_ERR_PARTITION "$1 $2"; echo $?) + +#Comprobamos acceso de escritura. +DIRTEMP=$(date +%Y%m%d-%H%M%S) +ogMakeDir $REPO /$4$DIRTEMP 2>/dev/null || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO"; echo $?) && ogDeleteTree $REPO /$4$DIRTEMP + +IMGDIR=$(ogGetParentPath "$REPO" "/$4") +# Si no existe, crear subdirectorio de la imagen. +if [ $? != 0 ]; then + ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$REPO $(dirname "$4")." + ogMakeDir "$REPO" $(dirname "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?) + IMGDIR=$(ogGetParentPath "$REPO" "/$4") || exit $(ogRaiseError $OG_ERR_NOTWRITE "$REPO /$4"; echo $?) +fi +IMGFILE=$IMGDIR/$(basename "/$4").$IMGEXT + +echo " " > $OGLOGCOMMAND +# Borramos ficheros de paginacion y configuracion +ogCleanOs $1 $2 + +#Comprobar espacio que requerira la imagen para ser almacenada +read SIZEDATA SIZEREQUIRED SIZEFREE ISENOUGHSPACE <<< $(ogGetSizeParameters $1 $2 "$REPO" "$4") + +ogEcho log session "[16] $PROG: $MSG_SCRIPTS_CREATE_SIZE $SIZEREQUIRED $SIZEFREE" +[ "$ISENOUGHSPACE" == "TRUE" ] || exit $(ogRaiseError session $OG_ERR_CACHESIZE "$REPO"; echo $?) + +# Comprobar consistencia del sistema de archivos. +echo " " > $OGLOGCOMMAND +SIZEFS=$(ogGetFsSize $1 $2) +ogEcho log session "[20] $MSG_HELP_ogCheckFs $PART $SIZEFS (KB)" +ogUnmount $1 $2 2>/dev/null +ogCheckFs $1 $2 || exit $(ogRaiseError $OG_ERR_PARTITION "ogCheckFs $1 $2" && echo $?) + +# Si es UEFI copio el cargador de arranque a la partición +OSTYPE="$(ogGetOsType $1 $2)" +if ogIsEfiActive && [ "$OSTYPE" == "Windows" ]; then + ogEcho log session "[25] $MSG_HELP_ogCopyEfiBootLoader" + ogCopyEfiBootLoader $1 $2 +fi + +# Evaluar variable de engine.cfg para reducir el sistema de archivos en la creacion +if [ "$IMGREDUCE" == "TRUE" ] +then + ogEcho log session "[30] $MSG_HELP_ogReduceFs" + ogReduceFs $1 $2 &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_REDUCEFS "$1 $2"; echo $?) + NEWSIZEFS=$(ogGetFsSize $1 $2) + TIMEAUX=$[SECONDS-TIME1] + ogEcho log session " $MSG_SCRIPTS_TIME_PARTIAL ( $NEWSIZEFS KB ) : $[TIMEAUX/60]m $[TIMEAUX%60]s" +fi + +# Renombrar el fichero de imagen si ya existe. +if [ -f "$IMGFILE" ]; then + ogEcho log session "[35] $MSG_SCRIPTS_FILE_RENAME \"$IMGFILE\" -> \"$IMGFILE.ant\"." + mv "$IMGFILE" "$IMGFILE.ant" + mv "$IMGFILE.torrent" "$IMGFILE.torrent.ant" 2>/dev/null + mv "$IMGFILE.sum" "$IMGFILE.sum.ant" 2>/dev/null + mv "$IMGFILE.full.sum" "$IMGFILE.full.sum.ant" 2>/dev/null +fi + +# Crear la imagen. +echo " " > $OGLOGCOMMAND +TIME2=$SECONDS +ogEcho log session "[40] $MSG_HELP_ogCreateImage : ogCreateImage $1 $2 $REPO $4 $IMGPROG $IMGCOMP" +ogCreateImage "$1" "$2" "$REPO" "/$4" "$IMGPROG" "$IMGCOMP" &>> $OGLOGCOMMAND || exit $(ogRaiseError $OG_ERR_IMAGE "ogCreteImage"; echo $?) +RESUMECREATEIMAGE=$(grep "Total Time:" $OGLOGCOMMAND) +TIMEAUX2=$[SECONDS-TIME2] +ogEcho log session " $RESUMECREATEIMAGE " +ogEcho log session " $MSG_SCRIPTS_TIME_PARTIAL : $[TIMEAUX2/60]m $[TIMEAUX2%60]s" + +# Extender sistema de archivos +TIME3=$SECONDS +ogEcho log session "[90] Extender sistema de archivos." +ogExtendFs $1 $2 || exit $(ogRaiseError $OG_ERR_EXTENDFS "$1 $2"; echo $?) +SIZEFS2=$(ogGetFsSize $1 $2) +TIMEAUX3=$[SECONDS-TIME3] +ogEcho log session " $MSG_HELP_ogExtendFs $NEWSIZEFS -> $SIZEFS = $SIZEFS2: $[TIMEAUX3/60]m $[TIMEAUX3%60]s" + +#TODO que hacer si error al extender sistemade archivos + +#resumen de la operacion +IMGSIZE=$(ls -s `ogGetPath $REPO /$4.$IMGEXT`| cut -f1 -d" ") +IMGOS=$(ogGetImageInfo `ogGetPath $REPO /$4.$IMGEXT`) + +TIME=$[SECONDS-TIME1] +ogEcho log session "[100] $MSG_SCRIPTS_TIME_TOTAL $[TIME/60]m $[TIME%60]s" +ogEcho log session " FileSystem $PART with $NEWSIZEFS KB data created onto file-image as $4 and used $IMGSIZE KB across DFS $ogprotocol" +ogEcho log session " Image-file $4 metada: $IMGOS" diff --git a/client/shared/scripts/createImage.py b/client/scripts/createImage.py similarity index 100% rename from client/shared/scripts/createImage.py rename to client/scripts/createImage.py diff --git a/client/scripts/createImageCustom.template b/client/scripts/createImageCustom.template new file mode 100644 index 0000000..73269d1 --- /dev/null +++ b/client/scripts/createImageCustom.template @@ -0,0 +1,35 @@ +#!/bin/bash +#/** +# createImageCustom +#@brief Plantilla para scirpt de creación personalizada de imagen. +#@param $1 nº de disco +#@param $2 nº de partición +#@param $3 Repositorio: CACHE, REPO o dirección IP +#@param $4 Nombre canónico de la imagen sin extensión +#@warning Renombrar este fichero como "createImageCustom" para sustituir al script estándar "createImage". +#**/ + + +# Control de parámetros. +[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: createImageCustom int_ndisc int_npart str_repo str_imgname" || exit $? + +# Toma de parámetros. +DISK="$1" # Nº de disco. +PART="$2" # Nº de partición. +REPO="${3^^}" # Repositorio (en mayúsculas). +IMGNAME="$4" # Nombre canónico de imagen (sin extensión). + + +# Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado). + + +# Paso 1: Añadir aquí el código para el proceso previo antes de la creación de la imagen en el equipo modelo (opcional). + + +# Paso 2: Sustituir, si se desea, la llamada al proceso estándar de creación de imagen por código personalizado. +createImage "$@" + + +# Paso 3: Añadir aquí el código para el proceso posterior tras la creación de la imagen (opcional). + + diff --git a/client/shared/scripts/createImageCustomTemplate.py b/client/scripts/createImageCustomTemplate.py similarity index 100% rename from client/shared/scripts/createImageCustomTemplate.py rename to client/scripts/createImageCustomTemplate.py diff --git a/client/scripts/createLogicalPartitions b/client/scripts/createLogicalPartitions new file mode 100755 index 0000000..7a693aa --- /dev/null +++ b/client/scripts/createLogicalPartitions @@ -0,0 +1,3 @@ +#!/bin/bash + + diff --git a/client/shared/scripts/createLogicalPartitions.py b/client/scripts/createLogicalPartitions.py similarity index 100% rename from client/shared/scripts/createLogicalPartitions.py rename to client/scripts/createLogicalPartitions.py diff --git a/client/scripts/createPrimaryPartitions b/client/scripts/createPrimaryPartitions new file mode 100755 index 0000000..f69f354 --- /dev/null +++ b/client/scripts/createPrimaryPartitions @@ -0,0 +1,3 @@ +#!/bin/bash +ogCreatePartitions "$@" +exit 0 diff --git a/client/shared/scripts/createPrimaryPartitions.py b/client/scripts/createPrimaryPartitions.py similarity index 100% rename from client/shared/scripts/createPrimaryPartitions.py rename to client/scripts/createPrimaryPartitions.py diff --git a/client/scripts/deployImage b/client/scripts/deployImage new file mode 100755 index 0000000..d74d3ac --- /dev/null +++ b/client/scripts/deployImage @@ -0,0 +1,246 @@ +#!/bin/bash +#/** +#@file deployImage +#@brief Proceso completo de despliegue de imagen, incluyendo actualización de la caché, restauración y post-configuración (este script es llamado por la interfaz RestaurarImagen). +#@param $1 Repositorio (CACHE, REPO o dirección IP) +#@param $2 Nombre canónico de la imagen (sin extensión) +#@param $3 Número de disco +#@param $4 Número de particion +#@param $5 Protocolo (UNICAST, por defecto, MULTICAST o TORRENT) +#@param $6 Opciones del protocolo +#@exception OG_ERR_FORMAT 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados. +#@exception OG_ERR_PARTITION 3 # Error en partición de disco. +#@exception OG_ERR_LOCKED 4 partición bloqueada por otra operación. +#@exception OG_ERR_IMAGE 5 error al restaurar la imagen del sistema. +#@exception OG_ERR_IMGSIZEPARTITION 30 Tamaño de la particion es menor al tamaño de la imagen. +#@exception OG_ERR_NOTCACHE No existe cache -15- +#@exception OG_ERR_CACHESIZE Tamaño de la paticion menor al archivo a descargar -16- +#@version 1.0.1 - Separación en protocolos de transferencia y postconfiguracion +#@author Antonio J. Doblas Viso. Universidad de Málaga +#@date 2011-05-11 +#@version 1.0.1 - Separación de los ficheros-log para ser gestionado por el httpd-log +#@author Antonio J. Doblas Viso. Universidad de Málaga +#@date 2011-05-11 +#@version 1.0.2 - Logica basada en fichero de configuracion engine.cfg +#@author Antonio J. Doblas Viso. Universidad de Málaga +#@date 2012-01-11 +#@version 1.0.5 - Renominación del script como "deployImage". +#@author Antonio J. Doblas Viso y Ramón M. Gómez. +#@date 2013-12-04 +#@version 1.0.6 - Se añade la gestión de errores de la CACHE cuando en el engine.cfg se define RESTOREPROTOCOLNOCACHE=NONE. +#@author Antonio J. Doblas Viso. +#@date 2015-02-23 +#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 +#**/ + + +#Descripcion: +# Si Repositorio es el global (REPO) realiza un deploy. +# Si Repositorio es local (CACHE) realiza un restoreImage CACHE +# El deploy, si detecta que el cliente no tiene una CACHE o no tiene espacio suficiente consulta el engine.cfg RESTOREPROTOCOLNOCACHE + + + +PROG="$(basename $0)" +if [ $# -lt 4 ]; then + ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO imagen ndisco nparticion [ UNICAST-DIRECT|UNICAST|UNICAST-CACHE|MULTICAST-DIRECT|MULTICAST|MULTICAST-CACHE|TORRENT [opciones protocolo] ]" + exit $? +fi + +# Asignación de variables (repositorio y protocolo se convierten a mayúsculas). +TIME1=$SECONDS +REPO="${1^^}" +REPO=${REPO:-"REPO"} +IMGNAME="$2" +DISK="$3" +PART="$4" +PROTO="${5^^}" +PROTO="${PROTO:-"UNICAST"}" +PROTOOPT="$6" +# Unidad organizativa. +[ "$ogunit" != "" ] && OGUNIT="$ogunit" + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo " " > $OGLOGCOMMAND +[ "$(ogGetCaller)" == "EjecutarScript" ] || echo -n "" > $OGLOGSESSION + +# Registro de inicio de ejecución +ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" + +# Si el origen(pariticion) esta bloqueada salir. +ogIsLocked $DISK $PART && exit $(ogRaiseError session $OG_ERR_LOCKED "$MSG_PARTITION, $DISK $PART"; echo $?) + +ogEcho log session "$MSG_HELP_ogUnmount $DISK $PART" +ogUnmount $DISK $PART 2>/dev/null + +# Valor por defecto para el repositorio. +if [ "$REPO" == "$(ogGetIpAddress)" -o "$REPO" == "CACHE" ]; then + MODE="CACHE" +else + ogCheckIpAddress "$REPO" + if [ $? == 0 -o "$REPO" == "REPO" ]; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO ${OGUNIT} || exit $(ogRaiseError $OG_ERR_NOTFOUND "$REPO $OGUNIT"; echo $?) + MODE="REPO" + fi +fi + +#Informacioin previa de la imagen +IMGOS=$(ogGetImageInfo `ogGetPath $MODE $IMGNAME.img`) +case $? in + 0) ;; + 1) ogRaiseError session $OG_ERR_NOTFOUND "$REPO $2" || exit $? ;; + 5) ogRaiseError session $OG_ERR_IMAGEFILE "$REPO $2" || exit $? ;; + *) ogRaiseError session $OG_ERR_GENERIC || exit $? ;; +esac +IMGSIZE=$(ls -s `ogGetPath $MODE $IMGNAME.img`| cut -f1 -d" ") + +ogEcho log session "[1] REPO=$REPO IMG-FILE=$IMGNAME.img SIZE=$IMGSIZE (KB) METADATA=$IMGOS" + +# Procesar repositorio. +case "$MODE" in + CACHE) # Repositorio en caché local. + NEXTOPERATION=CACHE + ;; + REPO) # Repositorio remoto por defecto. + case "$PROTO" in + MULTICAST-DIRECT) + NEXTOPERATION=MULTICAST + ;; + UNICAST-DIRECT) + NEXTOPERATION=UNICAST + ;; + + # Si protocolo es torrent|torrent-cache o multicast|multicast-cache + TORRENT|TORRENT-CACHE|MULTICAST|MULTICAST-CACHE|UNICAST|UNICAST-CACHE) + # Eliminamos CACHE o DIRECT + PROTO=${PROTO%%-*} + ogEcho log session "[2] updateCache "$REPO" \"/$IMGNAME.img\" $PROTO $PROTOOPT" + TIME2=$SECONDS + updateCache "$REPO" "/$IMGNAME.img" "$PROTO" "$PROTOOPT" + RETVAL=$? + TIME2=$[SECONDS-TIME2] + ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL updateCache $[TIME2/60]m $[TIME2%60]s" + case $RETVAL in + 0) + ogEcho log session "[50] updateCache (OK)" + NEXTOPERATION=CACHE + ;; + 15|16) + # no se permite usar la cache (no existe(15) o no espacio sufiente (16). Se consulta engine.cfg para RESTOREPROTOCOLNOCACHE [ multicast unicast none ] + ogEcho log session "[50] $MSG_ERR_NOTCACHE ; $MSG_ERR_CACHESIZE " + ogEcho log session "[50] $MSG_SCRIPTS_CHECK_ENGINE: RESTOREPROTOCOLNOTCACHE=$RESTOREPROTOCOLNOTCACHE " + case "$RESTOREPROTOCOLNOTCACHE" in + MULTICAST) + case "$PROTO" in + MULTICAST) NEXTOPERATION=MULTICAST ;; + TORRENT) NEXTOPERATION=UNICAST ;; + UNICAST) NEXTOPERATION=UNICAST ;; + esac + ;; + UNICAST) + NEXTOPERATION=UNICAST + ;; + NONE) + case $RETVAL in + 15) + ogEcho log session "[100] $MSG_ERR_NOTCACHE" + ogRaiseError session $OG_ERR_NOTCACHE "NOT CACHE" + exit $? + ;; + 16) + ogEcho log session "[100] $MSG_ERR_CACHESIZE " + ogRaiseError session $OG_ERR_CACHESIZE "CACHE FULL" + exit $? + ;; + esac # del segundo RETAVAL + ;; + esac # del RESTOREPROTOCOLNOTCACHE + ;; + 57|60) + # Time-out en la transferencia multicast (El mensaje de error está enviado) + exit $RETVAL + ;; + *) + # Error desconocido + exit $RETVAL + ;; + esac + ;; + *) # Error: protocolo desconocido. + ogRaiseError session $OG_ERR_FORMAT "$MSG_ERR_FORMAT, $PROTO" + exit $? + ;; + esac + ;; + *) # Error: repositorio desconocido. + ogRaiseError session $OG_ERR_FORMAT "$MSG_ERR_FORMAT, $REPO" + exit $? + ;; +esac + +TIME3=$SECONDS + +# Obtener parámetros de restauración. +case "$NEXTOPERATION" in + CACHE) + PARAMS="CACHE $IMGNAME $DISK $PART" ;; + UNICAST) + PARAMS="$REPO $IMGNAME $DISK $PART" ;; + MULTICAST) + PARAMS="$REPO $IMGNAME $DISK $PART $PROTO $PROTOOPT" ;; +esac + +# Si existe, ejecuta script personalizado "restoreImageCustom"; si no, llama al genérico "restoreImage". +if which restoreImageCustom &>/dev/null; then + ogEcho log session "[55] $MSG_HELP_ogRestoreImage: restoreImageCustom $PARAMS" + restoreImageCustom $PARAMS +else + ogEcho log session "[55] $MSG_HELP_ogRestoreImage: restoreImage $PARAMS" + restoreImage $PARAMS +fi +RETVAL=$? + +# Mostrar resultados. +RESUMERESTOREIMAGE=$(grep -m 1 "Total Time:" $OGLOGCOMMAND) +ogEcho log session " [ ] $RESUMERESTOREIMAGE " +# Si la transferencia ha dado error me salgo. +if [ $RETVAL -ne 0 ] ; then + ogRaiseError session $OG_ERR_IMAGE "$REPO $IMGNAME" 2>&1 + # Muestro registro de fin de ejecución si no viene de Ejecutar Script + [ "$(ogGetCaller)" == "EjecutarScript" ] || ogEcho log session "$MSG_INTERFACE_END $OG_ERR_IMAGE" + exit $OG_ERR_IMAGE +fi +TIME3=$[SECONDS-TIME3] +ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL : $[TIME3/60]m $[TIME3%60]s" + +# Si existe, ejecuta script personalizado de postconfiguración "configureOsCustom"; si no, llama al genérico "configureOs". +if which configureOsCustom &>/dev/null; then + ogEcho log session "[90] configureOsCustom" + configureOsCustom "$DISK" "$PART" "$REPO" "$IMGNAME" +else + ogEcho log session "[90] $MSG_SCRIPTS_OS_CONFIGURE " + configureOs "$DISK" "$PART" +fi + +TIME=$[SECONDS-TIME1] +ogEcho log session "[100] $MSG_SCRIPTS_TIME_TOTAL $[TIME/60]m $[TIME%60]s" + +# Registro de fin de ejecución +# Si se ha llamado desde ejecutar script no lo muestro para no repetir. +if [ "$(ogGetCaller)" != "EjecutarScript" ] ; then + ogEcho log session "$MSG_INTERFACE_END $RETVAL" + exit $RETVAL +fi + diff --git a/client/shared/scripts/deployImage.py b/client/scripts/deployImage.py similarity index 100% rename from client/shared/scripts/deployImage.py rename to client/scripts/deployImage.py diff --git a/client/scripts/formatFs b/client/scripts/formatFs new file mode 100755 index 0000000..1147f25 --- /dev/null +++ b/client/scripts/formatFs @@ -0,0 +1,19 @@ +#!/bin/bash +# Scirpt de ejemplo para formatear un sistema de archivos. +# Nota: se usa como base para el programa de formateo de OpenGnsys Admin). + +TIME1=$SECONDS +PROG="$(basename $0)" +if [ $# -ne 2 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion" + exit $? +fi + +# Desmontar y formatear el sistema de archivos. +echo "[5] Desmontando sistema de archivos" +ogUnmountFs "$@" || exit $? +echo "[20] Formateando sistema de archivos" +ogFormatFs "$@" + +TIME=$[SECONDS-TIME1] +echo "[100] Duración de la operación $[TIME/60]m $[TIME%60]s" diff --git a/client/shared/scripts/formatFs.py b/client/scripts/formatFs.py similarity index 100% rename from client/shared/scripts/formatFs.py rename to client/scripts/formatFs.py diff --git a/client/scripts/generateMenuDefault b/client/scripts/generateMenuDefault new file mode 100755 index 0000000..09e4300 --- /dev/null +++ b/client/scripts/generateMenuDefault @@ -0,0 +1,81 @@ +#!/bin/bash +# generateMenuDefault - Crea fichero con la página web de inicio del cliente +# con información de red y de los sistemas operativos instalados, +# crea fichero con información del contenido de la caché local. + + +DEVICE=${DEVICE:-"eth0"} +source /tmp/net-$DEVICE.conf +FILEINFOHTML=$OGLOG/`ogGetIpAddress`.info.html +FILEINFOCACHE=$OGLOG/`ogGetIpAddress`.cache.txt +ogMountCache 2>/dev/null +CACHECONTENIDO="ls -m $OGCAC/$OGIMG 2>/dev/null" + +SPEED=$(LANG=C ethtool $DEVICE 2>/dev/null | awk '$1~/Speed/ {print $2}') +case "${SPEED,,}" in + 1000mb/s) ;; + 100mb/s) SPEED="$SPEED" ;; + 10mb/s) SPEED="$SPEED" ;; + *) SPEED="$SPEED" ;; +esac +DUPLEX=$(LANG=C ethtool $DEVICE 2>/dev/null | awk '$1~/Duplex/ {print $2}') +case "${DUPLEX,,}" in + full) ;; + *) DUPLEX="$DUPLEX" +esac + +CACHESIZEFREE=$(ogGetFreeSize `ogFindCache`) +if [ $CACHESIZEFREE == 0 ]; then + echo '0.MB,' > $FILEINFOCACHE +else + expr $CACHESIZEFREE / 1024 > $FILEINFOCACHE 2>/dev/null && echo '.MB,' >> $FILEINFOCACHE +fi + +# Crear menú por defecto. +cat > $FILEINFOHTML << EOT +
+

+ + + + + + +

$MSG_HOSTNAME $MSG_IPADDR $MSG_MACADDR $MSG_SPEED $MSG_DUPLEX
$HOSTNAME $(ogGetIpAddress) $(ogGetMacAddress) $SPEED $DUPLEX
+

+ +

$MSG_MENUTITLE

+EOT + +# Si existe el fichero de configuración creado por el script getConfiguration, ... +cfgfile=/tmp/getconfig +if [ -f $cfgfile ]; then + # Tomar los datos del fichero. + awk -v boot="$MSG_BOOT" ' + { n=split($0,sep,";"); + for (i=1; i%s %s (%s, %s)

\n", + dua[1],dua[2],boot,dua[5],dua[1],dua[2]); + } + } + }' $cfgfile >>$FILEINFOHTML +else + # Si no, obtener los datos de los discos. + for ((d=1; d<=$(ogDiskToDev | wc -w); d++)); do + for ((p=1; p<=$(ogGetPartitionsNumber $d); p++)); do + VERSION=$(ogGetOsVersion $d $p 2>/dev/null | cut -f2 -d:) + [ -n "$VERSION" ] && echo "

$MSG_BOOT $VERSION ($d, $p)

" >>$FILEINFOHTML + done + done +fi +# Añadir opción de apagado. +cat >> $FILEINFOHTML << EOT +

$MSG_POWEROFF

+
+EOT + +# Crear contenido de la caché. +eval $CACHECONTENIDO >> $FILEINFOCACHE + diff --git a/client/shared/scripts/generateMenuDefault.py b/client/scripts/generateMenuDefault.py similarity index 100% rename from client/shared/scripts/generateMenuDefault.py rename to client/scripts/generateMenuDefault.py diff --git a/client/scripts/getFsType b/client/scripts/getFsType new file mode 100755 index 0000000..b3516a4 --- /dev/null +++ b/client/scripts/getFsType @@ -0,0 +1,3 @@ +#!/bin/bash +ogGetFsType "$@" + diff --git a/client/shared/scripts/getFsType.py b/client/scripts/getFsType.py similarity index 100% rename from client/shared/scripts/getFsType.py rename to client/scripts/getFsType.py diff --git a/client/scripts/getIpAddress b/client/scripts/getIpAddress new file mode 100755 index 0000000..e428ebf --- /dev/null +++ b/client/scripts/getIpAddress @@ -0,0 +1,3 @@ +#!/bin/bash +ogGetIpAddress "$@" + diff --git a/client/shared/scripts/getIpAddress.py b/client/scripts/getIpAddress.py similarity index 100% rename from client/shared/scripts/getIpAddress.py rename to client/scripts/getIpAddress.py diff --git a/client/scripts/getOsVersion b/client/scripts/getOsVersion new file mode 100755 index 0000000..6e6d91d --- /dev/null +++ b/client/scripts/getOsVersion @@ -0,0 +1,3 @@ +#!/bin/bash +ogGetOsVersion "$@" + diff --git a/client/shared/scripts/getOsVersion.py b/client/scripts/getOsVersion.py similarity index 100% rename from client/shared/scripts/getOsVersion.py rename to client/scripts/getOsVersion.py diff --git a/client/shared/scripts/grubSyntax b/client/scripts/grubSyntax similarity index 97% rename from client/shared/scripts/grubSyntax rename to client/scripts/grubSyntax index 2ff21fb..8997c97 100755 --- a/client/shared/scripts/grubSyntax +++ b/client/scripts/grubSyntax @@ -10,8 +10,6 @@ set -e #@version 1.1.1 - En los parámetros del kernel se sustituye el UUID por el dispositivo. #@version 1.1.1 - Detecta cargador de Windows en directorio Part-xx-yy dentro de ESP (#802 #888) -export PYTHONPATH=/opt/opengnsys/lib/engine/bin/ - DISK= PART= @@ -110,9 +108,8 @@ OG_prepare_grub_to_access_device () if [[ $DEVICE == *"nvme"* ]]; then #DEVICE=`echo $DEVICE | sed -e "s/\/dev\/nvme/hd/g" | sed -e "s/n.*p/,gpt/g"` #TODO Detectar si es GPT o no... - read -r D P <<< $(python3 -c 'import DiskLib; d = DiskLib.ogDevToDisk ("'$DEVICE'"); print (d)') - PTT = $(python3 -c 'import DiskLib; t = DiskLib.ogGetPartitionTableType ("'$D'"); print (t)') - if [ "$PTT" == "GPT" ]; then + read -r D P <<< `ogDevToDisk $DEVICE` + if [ "`ogGetPartitionTableType $D`" == "GPT" ]; then # Si es gpt se sustituye por "hd(X-1),gptY" #device=`echo $device | sed -e "s/\/dev\/nvme/hd/g" | sed -e "s/n.*p/,gpt/g"` nvmeDevice=`echo "hd"$(expr $D - 1)",gpt$P"` @@ -241,7 +238,7 @@ esac # ADV OSPROBED if [ -n "${DISK}" ]; then #Si $DISK esta definido buscar en el disco y la particion parametro 1 y 2 - OSSEARCH=$(python3 -c 'import DiskLib; d = DiskLib.ogDiskToDev ("'$DISK'", "'$PART'"); print (d)') + OSSEARCH=$(ogDiskToDev $DISK $PART) OSPROBED="`os-prober | grep $OSSEARCH | tr ' ' '^' | paste -s -d ' '`" else #si no esta definido diff --git a/client/scripts/initCache b/client/scripts/initCache new file mode 100755 index 0000000..9caf0be --- /dev/null +++ b/client/scripts/initCache @@ -0,0 +1,111 @@ +#!/bin/bash +# Scirpt de iniciación de la caché local de disco. +# Nota: se usa como base para el programa de configuración de equipos de OpenGnsys Admin). +# Formato: initCache [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT] +# Versión: 0.9.1, 2009/03/17, - Ramón Gómez, Univ. Sevilla - Versión inicial. +# Versión: 0.9.2, 2010/07/27, - Ramón Gómez, Univ. Sevilla - redefinir parámetro. +# Version: 1.0.5, 2012/09/18, - Univ. Huelva - Nuevo parametro para indicar el disco donde se creara la CACHE, si no se indica, se usa 1 +# Version: 1.1.0, 2016/06/16, - Ramón Gómez, Univ. Sevilla - Nuevos parámetros: partición de caché (por defecto, 4) y cadena opcional "NOMOUNT" para dejar la caché sin montar. + +TIME1=$SECONDS +PROG="$(basename $0)" +EXECFORMAT="$PROG [int_ndisk [int_npart]] {-1 | 0 | int_size} [NOMOUNT]" + +# Si el último parámetro es la cadena "NOMOUNT", marcar para no montar y descartarlo. +if [[ "${*^^}" =~ \ NOMOUNT$ ]]; then + MOUNT=0 + PARAMS=$[$#-1] +else + MOUNT=1 + PARAMS=$# +fi +# Tomar valores según el número de parámetros restantes. +case $PARAMS in + 1) # Por defecto, disco 1 partición 4. + NDISK=1 + NPART=4 + SIZE=$1 + ;; + 2) # Elegir disco y partición 4 por defecto. + NDISK=$1 + NPART=4 + SIZE=$2 + ;; + 3) # Elegir disco y partición. + NDISK=$1 + NPART=$2 + SIZE=$3 + ;; + *) # Error de formato. + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT" + exit $? + ;; +esac + +# Si disco o partición no son mayores o iguales que 1, error. +if [ -n "${NDISK//[-0-9]/}${NPART//[-0-9]/}" ] || [ $NDISK -lt 1 ] || [ $NPART -lt 1 ] ; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT" + exit $? +fi +# Si tamaño no es numérico o tamaño<-1, error. +if [ -n "${SIZE//[-0-9]/}" ] || [ $SIZE -lt -1 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $EXECFORMAT" + exit $? +fi +# Si tamaño=0, no hacer nada. +if [ $SIZE -eq 0 ]; then + echo "No modificar la caché local." + exit +fi +# Si tamaño=-1, borrar caché. +if [ $SIZE -eq -1 ]; then + echo "[10] Trabajar sin caché local." + ogUnmountCache 2>/dev/null + ogDeleteCache +else + # Si la caché actual está definida en otro disco y partición, se elimina. + if [ -n "$(ogFindCache)" -a "$NDISK $NPART" != "$(ogFindCache)" ]; then + echo "[10] Detectada otra caché, eliminarla" + ogUnmountCache 2>/dev/null + ogDeleteCache + fi + # Tomamos el tamaño actual. Si no existe cache será 0. + OLDSIZE=$(ogGetCacheSize 2>/dev/null) || OLDSIZE=0 + + # Error si tamaño definido no es >0. + if [ ! $SIZE -gt 0 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: !($SIZE>0)" + exit $? + fi + # Si no existe caché o si cambia su tamaño, crearla. + CACHESIZE=$(ogGetCacheSize 2>/dev/null) + if [ "$SIZE" != "$CACHESIZE" ]; then + echo "[10] Crar partición de caché local." + ogUnmountCache 2>/dev/null + ogCreateCache $NDISK $NPART $SIZE + ogUpdatePartitionTable $NDISK + fi + # Si caché no montada y no formateada o cambia el tamaño: formatear. + CACHE=$(ogFindCache) || exit $? + if ! ogIsFormated $CACHE || [ $SIZE -ne $OLDSIZE ]; then + echo "[50] Formatear caché local." + ogFormatCache + fi + echo "[70] Comprobar montaje de caché local." + ogMountCache 2>/dev/null + # Si error al montar, chequear sistema de archivos y volver a montar. + if [ $? != 0 ]; then + echo "[80] Comprobar consistencia y volver a montar caché local." + ogCheckFs $CACHE + ogMountCache || exit $? + fi + # Dejar desmontada la caché si se ha solicitado. + if [ $MOUNT == 0 ]; then + echo "[90] Dejar desmontada la caché local." + ogUnmountCache 2>/dev/null + fi +fi +# Duración del proceso. +TIME=$[SECONDS-TIME1] +echo "[100] Duración de la operación $[TIME/60]m $[TIME%60]s" + diff --git a/client/shared/scripts/initCache.py b/client/scripts/initCache.py similarity index 93% rename from client/shared/scripts/initCache.py rename to client/scripts/initCache.py index 9fb4ed8..8a45ca8 100755 --- a/client/shared/scripts/initCache.py +++ b/client/scripts/initCache.py @@ -47,6 +47,7 @@ def main (NDISK, NPART, SIZE, MOUNT): if SIZE != CACHESIZE: print("[10] Crear partición de caché local.") CacheLib.ogUnmountCache() + print (f'nati: calling ogCreateCache ({NDISK}, {NPART}, {SIZE})') CacheLib.ogCreateCache (NDISK, NPART, SIZE) DiskLib.ogUpdatePartitionTable() @@ -103,19 +104,23 @@ if __name__ == "__main__": NPART = int (args[1]) SIZE = int (args[2]) else: + print (f'nati: params no es ni 1 ni 2 ni 3 sino ({PARAMS})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) except ValueError: + print (f'nati: ValueError') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) # Si disco o partición no son mayores o iguales que 1, error. if NDISK < 1 or NPART < 1: + print (f'nati: ndisk<1 or npart<1, ({NDISK}) ({NPART})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) # Si tamaño no es numérico o tamaño<-1, error. if SIZE < -1: + print (f'nati: SIZE<-1 ({SIZE})') SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, EXECFORMAT) sys.exit (1) diff --git a/client/scripts/installOfflineMode b/client/scripts/installOfflineMode new file mode 100755 index 0000000..d9ff245 --- /dev/null +++ b/client/scripts/installOfflineMode @@ -0,0 +1,60 @@ +#!/bin/bash + +#/** +# installOfflineMode +#@brief Prepara el equipo cliente para el modo offline. +#@param no +#@return +#@exception OG_ERR_NOTFOUND Fichero o dispositivo no encontrado. +#@exception OG_ERR_NOTCACHE No existe cache. +#@author Irina Gomez. ETSII. Universidad de Sevilla +#@date 2013/12/5 +#*/ ## + +PROG="$(basename $0)" +if [ "$*" == "help" ]; then + ogHelp "$PROG $MSG_HELP_installOfflineMode" \ + "$PROG [ no param ]" + exit 0 +fi + +ogEcho log session "$MSG_HELP_installOfflineMode" +# Cargamos las variables de entorno. +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg +DIRTFTP="/opt/oglive/tftpboot" +DIROGCLIENT="$DIRTFTP/ogclient" +# Comprobamos que el DIROGCLIENT esta montado desde repo +df |grep "$(ogGetRepoIp).*$DIRTFTP" &>/dev/null || ogRaiseError $OG_ERR_NOTFOUND "REPO OGclient" || exit $? + +# Copiamos el kernel y el initrd. +ogEcho log session " [10] updateBootCache" +updateBootCache || ogRaiseError $OG_ERR_NOTCACHE || exit $? + +# Creamos los dir necesarios. +ogEcho log session " [40] mkdir -p $OGCAC/{ogclient, menus, log}." +[ -d $OGCAC/menus/images/iconos ] || mkdir -p $OGCAC/menus/images/iconos +[ -d $OGCAC/ogclient ] || mkdir -p $OGCAC/ogclient +[ -d $OGCAC/log ] || mkdir -p $OGCAC/log +[ -d $OGCAC/opt/opengnsys/images ] || mkdir -p $OGCAC/opt/opengnsys/images + +# Comparamos el cliente en el server y en cache +ogEcho log session " [60] cp $DIROGCLIENT/ogclient.sqfs $OGCAC/ogclient/" +SERVEROGCLIENT=$(cat $DIROGCLIENT/ogclient.sqfs.sum 2>/dev/null) +CACHEOGCLIENT=$(cat $OGCAC/ogclient/ogclient.sqfs.sum 2>/dev/null) + +if [ "$CACHEOGCLIENT" != "$SERVEROGCLIENT" ]; then + cp $DIROGCLIENT/ogclient.sqfs $OGCAC/ogclient/ + cp $DIROGCLIENT/ogclient.sqfs.sum $OGCAC/ogclient/ +fi + +# Si se ha generado el menu de inicio lo copiamos a cache. +IPCLIENT=$(ogGetIpAddress) +MENU=$OGLOG/$IPCLIENT.info.html +ICONO="images/iconos/logoopengnsys.png" +[ -f $MENU ] || generateMenuDefault +ogEcho log session " [90] cp $MENU $OGCAC/menus/$IPCLIENT.html" +cp $MENU $OGCAC/menus/$IPCLIENT.html +sed -i s/"..\/images"/"images"/g $OGCAC/menus/$IPCLIENT.html +wget --no-check-certificate https://$(ogGetRepoIp)/opengnsys/$ICONO -O $OGCAC/menus/$ICONO + + diff --git a/client/shared/scripts/installOfflineMode.py b/client/scripts/installOfflineMode.py similarity index 100% rename from client/shared/scripts/installOfflineMode.py rename to client/scripts/installOfflineMode.py diff --git a/client/scripts/launchOgagentInstaller b/client/scripts/launchOgagentInstaller new file mode 100755 index 0000000..b999d3e --- /dev/null +++ b/client/scripts/launchOgagentInstaller @@ -0,0 +1,145 @@ +#!/bin/bash +# #/** +# launchOgagentInstaller ndisk npart [windowsadmin] +#@brief Scheduling OpenGnsys Agent installation at next boot or administrator session. +#@param integer ndsik disk number +#@param integer npart partition number +#@param string windowsadmin administrator user (only for Windows) +#@author Ramón M. Gómez, ETSII Univ. Sevilla +#@version 1.1.0 - Initial version. +#@date 2018-02-16 +#*/ ## + +# Global variables. +PROG="$(basename "$0")" +if which curl &>/dev/null; then + DOWNLOAD="curl -k -f --connect-timeout 1 -o" +else + DOWNLOAD="wget --no-check-certificate -T 1 -O" +fi + +# Show help. +if [ "$*" == "help" ]; then + echo "$PROG: scheduling OpenGnsys Agent installation." + echo "Format: $PROG ndisk npart [windowsadmin]" + exit 0 +fi +# Error control. +if ! typeset -Fp ogRaiseError &>/dev/null; then + echo "$PROG: it can only be executed by an ogLive client." >&2 + exit 1 +fi +[ $# == 2 -o $# == 3 ] || ogRaiseError $OG_ERR_FORMAT "$PROG ndisk npart [adminuser]" || exit $OG_ERR_FORMAT +MNTDIR=$(ogMount "$1" "$2") || exit $? +OGVERSION=$($DOWNLOAD - https://$(ogGetServerIp)/opengnsys/rest/info 2>/dev/null | jq -r .version) +[ -n "$OGVERSION" ] || ogRaiseError $OG_ERR_NOTFOUND "GET /rest/info" || exit $OG_ERR_NOTFOUND + +case "$(ogGetOsType $1 $2)" in + Windows) # OGAgent for Windows. + HIVE="$(ogGetHivePath "$MNTDIR" "$3")" + [ -n "$HIVE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 $3/NTUSER.DAT" || exit $OG_ERR_NOTFOUND + # Downloading OGAgent installer for Windows. + OGAGENTFILE="OGAgentSetup-${OGVERSION/pre/}.exe" + TMPDIR="$(ogGetPath "$MNTDIR/Windows/Temp")" + if ogListSoftware $1 $2 | grep -qi "opengnsys agent"; then + echo "OGAgent for Windows is already installed, you need to uninstall it before re-install." + else + if eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null; then + # Run once OGAgent Installer. + if hivexsh -w << EOT 2>/dev/null; then +load $HIVE +cd \\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce +setval 1 +Install OGAgent +string:C:\\Windows\\Temp\\$OGAGENTFILE /S /server $(ogGetServerIp) +commit +close +exit +EOT + echo "Scheduled OGAgent installation after \"$3\" logon" + echo " (for connection problems, check configuration file)." + else + ogRaiseError $OG_ERR_NOTWRITE "$1 $2 .../$3/NTUSER.DAT" + exit $OG_ERR_NOTWRITE + fi + else + ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /Windows/Temp/$OGAGENTFILE" + exit $OG_ERR_NOTFOUND + fi + fi + ;; + Linux) # OGAgent for Linux (only deb and redhat-based backages; TODO suse-based package). + if ogListSoftware $1 $2 | grep -qi "ogagent"; then + echo "OGAgent for Linux is already installed, you need to uninstall it before re-install." + else + SYSTEMDDIR="$MNTDIR/lib/systemd" + [ -d "$SYSTEMDDIR" -a -d "${SYSTEMDDIR/lib/etc}" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 systemd" || exit $OG_ERR_NOTFOUND + # Downloading OGAgent installer for Linux. + if [ -e $MNTDIR/etc/debian_version ]; then # Debian-based + OGAGENTFILE="ogagent_${OGVERSION/pre/}_all.deb" + CODE="if ! dpkg -l ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then apt-get update; apt-get install -y /var/tmp/$OGAGENTFILE; fi" + fi + if [ -e $MNTDIR/etc/redhat-release ]; then # RedHat-based + OGAGENTFILE="ogagent-${OGVERSION/pre/}-1.noarch.rpm" + CODE="if ! rpm -q ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then yum install -y /var/tmp/$OGAGENTFILE; fi" + fi + [ -n "$OGAGENTFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 ogagent" || exit $OG_ERR_NOTFOUND + TMPDIR="$MNTDIR/var/tmp" + if eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null; then + # Creating systemd script. + cat << EOT > $SYSTEMDDIR/systemd-launchogagent +#!/bin/bash +[ $EUID = 0 ] || exit 4 +start() { + $CODE + sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg + service ogagent start +} +restart() { + service ogagent stop + if [ -f /var/tmp/$OGAGENTFILE ]; then + apt-get update + apt-get install -y --reinstall /var/tmp/$OGAGENTFILE + fi + sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg + service ogagent start +} + +case "\$1" in + start|restart) "\$1" ;; +esac +EOT + chmod +x $SYSTEMDDIR/systemd-launchogagent + # Creating systemd service. + cat << EOT > $SYSTEMDDIR/system/launchogagent.service +[Unit] +Description=Installing and configuring OGAgent + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/lib/systemd/systemd-launchogagent start +TimeoutStartSec=5min + +[Install] +WantedBy=multi-user.target +EOT + ln -fs /lib/systemd/system/launchogagent.service \ + ${SYSTEMDDIR/lib/etc}/system/multi-user.target.wants + echo "Scheduled OGAgent installation at next boot" + echo " (process will be executed in the background, do not shutdown until finish)." + else + ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /var/tmp/$OGAGENTFILE" + exit $OG_ERR_NOTFOUND + fi + fi + ;; + MacOS) # OGAgent for macOS (TODO). + echo "OGAgent installer for macOS is not implemented yet." + ;; + *) # OS not detected or OGAgent not implemented. + ogRaiseError $OG_ERR_NOTOS "$1 $2" + exit $OG_ERR_NOTOS + ;; +esac + diff --git a/client/shared/scripts/launchOgagentInstaller.py b/client/scripts/launchOgagentInstaller.py similarity index 100% rename from client/shared/scripts/launchOgagentInstaller.py rename to client/scripts/launchOgagentInstaller.py diff --git a/client/scripts/listHardwareInfo b/client/scripts/listHardwareInfo new file mode 100755 index 0000000..34679a0 --- /dev/null +++ b/client/scripts/listHardwareInfo @@ -0,0 +1,24 @@ +#!/bin/bash +# Scirpt de ejemplo para almacenear en fichero temporal el listado de hardware. +# Nota: se usa como base para el programa de recogida de listado de hardware de OpenGnsys Admin. +# Formato: listHardwareInfo + +PROG=$(basename "$0") +if [ $# -ne 0 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG " + exit $? +fi + +# Directorio del servidor donde se exportan los ficheros de registro. +SERVERLOGDIR=$(mount | awk -v d=$OGLOG ' + BEGIN {FS="[: ]"} + {if ($4==d) dir=$2} + END {print dir}') + +# Fichero de listado: hard-IP +HARDFILE="hard-$(ogGetIpAddress)" +# Redirigir salida al fichero de listado. +ogListHardwareInfo>$OGLOG/$HARDFILE || exit $? +# Salida: camino del fichero de listado en el servidor de repositorio. +#echo $SERVERLOGDIR/$HARDFILE +echo $OGLOG/$HARDFILE diff --git a/client/shared/scripts/listHardwareInfo.py b/client/scripts/listHardwareInfo.py similarity index 100% rename from client/shared/scripts/listHardwareInfo.py rename to client/scripts/listHardwareInfo.py diff --git a/client/scripts/listPartitions b/client/scripts/listPartitions new file mode 100755 index 0000000..6f9c318 --- /dev/null +++ b/client/scripts/listPartitions @@ -0,0 +1,3 @@ +#!/bin/bash +ogListPartitions "$@" | sed 's/\(EMPTY:0 \)*$//' + diff --git a/client/shared/scripts/listPartitions.py b/client/scripts/listPartitions.py similarity index 100% rename from client/shared/scripts/listPartitions.py rename to client/scripts/listPartitions.py diff --git a/client/scripts/listPrimaryPartitions b/client/scripts/listPrimaryPartitions new file mode 100755 index 0000000..d20dd76 --- /dev/null +++ b/client/scripts/listPrimaryPartitions @@ -0,0 +1,3 @@ +#!/bin/bash +ogListPrimaryPartitions "$@" + diff --git a/client/shared/scripts/listPrimaryPartitions.py b/client/scripts/listPrimaryPartitions.py similarity index 100% rename from client/shared/scripts/listPrimaryPartitions.py rename to client/scripts/listPrimaryPartitions.py diff --git a/client/scripts/listSoftwareInfo b/client/scripts/listSoftwareInfo new file mode 100755 index 0000000..1b97294 --- /dev/null +++ b/client/scripts/listSoftwareInfo @@ -0,0 +1,35 @@ +#!/bin/bash +# Scirpt de ejemplo para almacenear en fichero temporal el listado de software. +# Nota: se usa como base para el programa de recogida de listado de software de OpenGnsys Admin. +# Formato: listSoftwareInfo [-r] ndisk npart +# -r listado reducido (sin parches de Windows) + +PROG=$(basename "$0") +REDUCED="no" +if [ "$1" = "-r" ]; then + REDUCED="yes" + shift +fi +if [ $# -ne 2 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion" + exit $? +fi + +# Directorio del servidor donde se exportan los ficheros de registro. +SERVERLOGDIR=$(mount | awk -v d=$OGLOG ' + BEGIN {FS="[: ]"} + {if ($4==d) dir=$2} + END {print dir}') + +# Fichero de listado: soft-IP-ndisco-npart +SOFTFILE="soft-$(ogGetIpAddress)-$1-$2" +# Redirigir salida al fichero de listado. +if [ "$REDUCED" = "no" ]; then + ogListSoftware "$1" "$2" >$OGLOG/$SOFTFILE || exit $? +else + ogListSoftware "$1" "$2" | egrep -v "\(KB[0-9]{6}\)" >$OGLOG/$SOFTFILE || exit $? +fi +# Salid: camino del fichero de listado en el servidor de repositorio. +#echo $SERVERLOGDIR/$SOFTFILE +echo $OGLOG/$SOFTFILE + diff --git a/client/shared/scripts/listSoftwareInfo.py b/client/scripts/listSoftwareInfo.py similarity index 100% rename from client/shared/scripts/listSoftwareInfo.py rename to client/scripts/listSoftwareInfo.py diff --git a/client/scripts/menuBrowser b/client/scripts/menuBrowser new file mode 100755 index 0000000..f544215 --- /dev/null +++ b/client/scripts/menuBrowser @@ -0,0 +1,11 @@ +#!/bin/bash +# Scirpt de ejemplo para iniciar el browser del cliente con un menú predefinido + +PROG=$(basename "$0") +if [ $# -ne 1 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG urlmenu" + exit $? +fi + +url="$1" +browser -qws $url diff --git a/client/shared/scripts/menuBrowser.py b/client/scripts/menuBrowser.py similarity index 100% rename from client/shared/scripts/menuBrowser.py rename to client/scripts/menuBrowser.py diff --git a/client/scripts/poweroff b/client/scripts/poweroff new file mode 100755 index 0000000..4233058 --- /dev/null +++ b/client/scripts/poweroff @@ -0,0 +1,39 @@ +#!/bin/bash +# Scirpt de ejemplo para apagar un ordenador +# Nota: se usa como base para el programa de apagado de OpenGnsys Admin. + + +# Registrar ejecución manual de script. +case "$(ogGetCaller)" in + browser|bash) ogEcho log info "Script: $0" ;; +esac + +# No registrar errores. +export DEBUG="no" + +# Desmontar los sistemas de archivos y la caché local. +echo "[10] Desmontar todos los sistemas de archivos." +sync +for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do + ogUnmountAll $i &>/dev/null +done +echo "[50] Desmontar cache local." +ogUnmountCache &>/dev/null + +# Volver a registrar errores. +unset DEBUG + +echo "[70] Apagando el equipo." +# Estado correcto de Wake-On-Lan antes de apagar. +ethtool -s $DEVICE wol g 2>/dev/null +# Detectar Busybox. +BUSYBOX=$(which busyboxOLD) +BUSYBOX=${BUSYBOX:-"busybox"} + +# Retardo para dar lugar al registro en cola de acciones. +sleep 5 +# Parar Browser para evitar "cuelgues". +[ "$ogstatus" == "offline" ] || pkill browser +# Apagar. +$BUSYBOX poweroff + diff --git a/client/scripts/reboot b/client/scripts/reboot new file mode 100755 index 0000000..689da67 --- /dev/null +++ b/client/scripts/reboot @@ -0,0 +1,54 @@ +#!/bin/bash +# Script de ejemplo para reiniciar un ordenador +# Nota: se usa como base para el programa de reinicio de OpenGnsys Admin. + + +# Registrar ejecución manual de script. +case "$(ogGetCaller)" in + browser|bash) ogEcho log info "Script: $0" ;; +esac + +# Cargamos el valor por defecto del tiempo de sleep +[ -z $OGSLEEP ] && source /opt/opengnsys/etc/engine.cfg + +# Si se recibe un parametro sera el tiempo de sleep antes de realizar el reboot +if [ $# == 1 ] && [ "${1//[^0-9]/}" == "$1" ] +then + TIME=$1 + echo "[5] Se ha introducido un retardo de $TIME segundos para reiniciar" +else + # Sin parámetros, o el parámetro introducido no es un número + TIME=${OGSLEEP:-5} + echo "[5] No se ha introducido un retardo, $TIME segundos para reiniciar" +fi + +# No registrar errores. +export DEBUG="no" + +# Desmontar los sistemas de archivos y la caché local. +echo "[10] Desmontar todos los sistemas de archivos." +sync +for (( i=1; i <= $(ogDiskToDev | wc -w); i++ )); do + ogUnmountAll $i &>/dev/null +done +echo "[50] Desmontar cache local." +ogUnmountCache &>/dev/null + +# Volver a registrar errores. +unset DEBUG + +echo "[90] Reiniciar el equipo." +# Estado correcto de Wake-On-Lan antes de reiniciar. +ethtool -s $DEVICE wol g 2>/dev/null +# Detectar Busybox. +BUSYBOX=$(which busyboxOLD) +BUSYBOX=${BUSYBOX:-"busybox"} + +# Retardo para dar lugar al registro en cola de acciones. +sleep $TIME +# Parar Browser para evitar "cuelgues". +[ "$ogstatus" == "offline" ] || pkill browser +# Reiniciar. +$BUSYBOX reboot + + diff --git a/client/scripts/remoteConsole b/client/scripts/remoteConsole new file mode 100755 index 0000000..dc0fc4b --- /dev/null +++ b/client/scripts/remoteConsole @@ -0,0 +1,22 @@ +#!/bin/bash +# Script de ejemplo para enviar eco a la consola remota al ejecutar un comando de la shell +# Formato: remoteConsole + +PROG="$(basename $0)" +if [ $# -ne 0 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: $PROG " + exit $? +fi + +# Directorio del servidor donde se exportan los ficheros de registro. +SERVERLOGDIR=$(mount | awk -v d=$OGLOG ' + BEGIN {FS="[: ]"} + {if ($4==d) dir=$2} + END {print dir}') + +# Fichero de listado: hard-IP +ECOFILE="eco-$(ogGetIpAddress)" +# Redirigir salida al fichero de listado. +/tmp/_hidrascript_ >$OGLOG/$ECOFILE || exit $? +# Salida: camino del fichero de listado en el servidor de repositorio. +echo $SERVERLOGDIR/$ECOFILE diff --git a/client/scripts/restoreImage b/client/scripts/restoreImage new file mode 100755 index 0000000..d9e7f58 --- /dev/null +++ b/client/scripts/restoreImage @@ -0,0 +1,106 @@ +#!/bin/bash +#/** +#@file restoreImage +#@brief Script de ejemplo para restaurar una imagen. +#@param $1 Repositorio (CACHE, REPO o dirección IP) +#@param $2 Nombre canónico de la imagen (sin extensión) +#@param $3 Número de disco +#@param $4 Número de particion +#@param $5 Protocolo (UNICAST, UNICAST-DIRECT, MULTICAST o MULTICAST-DIRECT) +#@param $6 Opciones del protocolo +#@exception OG_ERR_FORMAT 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND 2 cambio de repositorio: repositorio no encontrado +#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados. +#@exception $OG_ERR_MCASTRECEIVERFILE 57 Error en la recepción Multicast de un fichero +#@exception $OG_ERR_PROTOCOLJOINMASTER 60 Error en la conexión de una sesión Unicast|Multicast con el Master +#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 +#**/ + +TIME1=$SECONDS +PROG="$(basename $0)" +if [ $# -lt 4 ]; then + ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones protocolo]" + exit $? +fi + +#Load engine configurator from engine.cfg file. +#Carga el configurador del engine desde el fichero engine.cfg +# Valores por defecto: #IMGPROG="partclone" ; #IMGCOMP="lzop" ; #IMGEXT="img" #IMGREDUCE="TRUE" +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo " " > $OGLOGCOMMAND +ogCheckStringInGroup "$(ogGetCaller)" "deployImage restoreImageCustom" || echo -n "" > $OGLOGSESSION; + +ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" + +# Procesar parámetros de entrada +REPO="${1^^}" +IMGNAME="$2" +DISK="$3" +PART="$4" +PROTO="${5^^}" +PROTO=${PROTO:-"UNICAST"} +PROTOOPT="$6" +# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento +if [ "${PROTO%-*}" == "MULTICAST" ] && [[ ${PROTOOPT##*:} =~ ^-?[0-9]+$ ]]; then + [ ${MCASTWAIT:-0} -lt ${PROTOOPT##*:} ] && let MCASTWAIT=${PROTOOPT##*:}+5 +fi +IMGTYPE="${IMGTYPE:-"img"}" + +# Unidad organizativa +[ "$ogunit" != "" ] && OGUNIT="$ogunit/" + +# Si es una ip y es igual a la del equipo restaura desde cache +[ "$REPO" == "$(ogGetIpAddress)" ] && REPO="CACHE" +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPO +if [ $? == 0 -o $REPO == "REPO" ] ; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPO ${OGUNIT%/} || exit $(ogRaiseError $OG_ERR_NOTFOUND '$REPO $OGUNIT'; echo $?) + REPO="REPO" +fi + +# Comprobar que existe la imagen del origen. +IMGFILE=$(ogGetPath "$REPO" "$IMGNAME.$IMGTYPE") +IMGDIR=$(ogGetParentPath "$REPO" "$IMGNAME") +if [ "$IMGFILE" == "" -o "$IMGDIR" == "" ]; then + ogRaiseError session $OG_ERR_NOTFOUND "$REPO, ${IMGNAME%/*}" + exit $? +fi + +# Procesar protocolos de transferencia. +case "$PROTO" in + UNICAST|UNICAST-DIRECT) + # Restaurar la imagen. + ogEcho log session "[40] ogRestoreImage $REPO $IMGNAME $DISK $PART UNICAST" + ogExecAndLog command ogRestoreImage "$REPO" "$IMGNAME" "$DISK" "$PART" + RETVAL=$? + ;; + MULTICAST|MULTICAST-DIRECT) + PORT=$(echo $PROTOOPT | cut -f1 -d":") + TOOL=$(ogGetImageProgram REPO $IMGNAME) + COMPRESS=$(ogGetImageCompressor REPO $IMGNAME) + #TODO comprobar parametros anteriores + ogEcho log session "[40] ogMcastReceiverPartition $DISK $PART $PORT $TOOL $COMPRESS" + ogMcastRequest "$IMGNAME.img" "$PROTOOPT" || exit $? + ogExecAndLog command ogMcastReceiverPartition "$DISK" "$PART" "$PORT" "$TOOL" "$COMPRESS" + RETVAL=$? + ;; + *) # Protocolo desconocido. + ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG REPO|CACHE imagen ndisco nparticion [ UNICAST|MULTICAST opciones ]" + exit $? +esac + +TIME=$[SECONDS-TIME1] +ogEcho log session "[100] Duracion de la operacion $[TIME/60]m $[TIME%60]s" + +# Código de salida del comando prinicpal de restauración. +exit $RETVAL + diff --git a/client/shared/scripts/restoreImage.py b/client/scripts/restoreImage.py similarity index 100% rename from client/shared/scripts/restoreImage.py rename to client/scripts/restoreImage.py diff --git a/client/scripts/restoreImageCustom.template b/client/scripts/restoreImageCustom.template new file mode 100644 index 0000000..bb94ad1 --- /dev/null +++ b/client/scripts/restoreImageCustom.template @@ -0,0 +1,37 @@ +#!/bin/bash +#/** +# restoreImageCustom +#@brief Plantilla para scirpt de rastauración personalizada de imagen. +#@param $1 nº de disco +#@param $2 nº de partición +#@param $3 Repositorio: CACHE, REPO o dirección IP +#@param $4 Nombre canónico de la imagen sin extensión +#@warning Renombrar este fichero como "restoreImageCustom" para sustituir al script estándar "restoreImage". +#**/ + + +# Control de parámetros. +[ $# -ge 4 -a $# -le 6 ] || ogRaiseError $OG_ERR_FORMAT "$MSG_FORMAT: restoreImageCustom str_repo str_imagen int_ndisco int_npart [ str_proto [\"str_opciones\"] ]" || exit $? + +# Toma de parámetros. +REPO="${1^^}" # Repositorio (en mayúsculas). +IMGNAME="$2" # Nombre canónico de imagen (sin extensión). +DISK="$3" # Nº de disco. +PART="$4" # Nº de partición. +PROTO="${5^^}" # Protocolo de comunicaciones (por defecto, UNICAST). +PROTO=${PROTO:-"UNICAST"} +PROTOOPT="$6" # Opciones del protocolo separadas por ":" (opcional). + + +# Paso 0: Añadir código para realizar control de errores de los parámetros de entrada (recomendado). + + +# Paso 1: Añadir aquí el código para el proceso previo antes de la restauración de la imagen en los equipos (opcional). + + +# Paso 2: Sustituir, si se desea, la llamada al proceso estándar de restauración de imagen por código personalizado. +restoreImage "$@" + + +# Aviso: editar la plantilla "configureOsCustom" para añadir el código personalizado para el proceso de postconfiguración de los clientes (no incluir aquí dicho código). + diff --git a/client/shared/scripts/restoreImageCustomTemplate.py b/client/scripts/restoreImageCustomTemplate.py similarity index 100% rename from client/shared/scripts/restoreImageCustomTemplate.py rename to client/scripts/restoreImageCustomTemplate.py diff --git a/client/scripts/runAplicationX.sh b/client/scripts/runAplicationX.sh new file mode 100755 index 0000000..85f9681 --- /dev/null +++ b/client/scripts/runAplicationX.sh @@ -0,0 +1,8 @@ +#/bin/bash +/usr/X11R6/bin/Xvesa :0 -ac -shadow -screen 1024x768x24 -br -mouse /dev/input/mice & +/bin/sleep 0.1 +export DISPLAY=:0 +#/usr/bin/lxde-logout +#/usr/bin/openbox +/usr/bin/roxterm +#/usr/sbin/gparted diff --git a/client/shared/scripts/runApplicationX.py b/client/scripts/runApplicationX.py similarity index 100% rename from client/shared/scripts/runApplicationX.py rename to client/scripts/runApplicationX.py diff --git a/client/shared/scripts/runhttplog.py b/client/scripts/runhttplog.py similarity index 100% rename from client/shared/scripts/runhttplog.py rename to client/scripts/runhttplog.py diff --git a/client/scripts/runhttplog.sh b/client/scripts/runhttplog.sh new file mode 100755 index 0000000..f0f854b --- /dev/null +++ b/client/scripts/runhttplog.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +#httd-log-status +cp /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.back +cp /opt/opengnsys/lib/httpd/lighttpd.conf /etc/lighttpd/ +cp /etc/lighttpd/conf-enabled/10-cgi.conf /etc/lighttpd/conf-enabled/10-cgi.conf.back +cp /opt/opengnsys/lib/httpd/10-cgi.conf /etc/lighttpd/conf-enabled/ +/etc/init.d/lighttpd start +chmod 755 /opt +mkdir -p /usr/lib/cgi-bin +cp /opt/opengnsys/lib/httpd/* /usr/lib/cgi-bin +#TODO: +dstat -dn 10 > /tmp/bandwidth & +echo "WAITING" >> $OGLOGSESSION +# http-log-status diff --git a/client/scripts/samples/configureGroup b/client/scripts/samples/configureGroup new file mode 100755 index 0000000..6563843 --- /dev/null +++ b/client/scripts/samples/configureGroup @@ -0,0 +1,65 @@ +#!/bin/bash +#/** +#@file configureGroup +#@brief Script de ejemplo de post-configuracion del sistema operativo especifica de cada grupo de ordenadores. +#@brief El directorio del grupo en el repositorio se situa en /opt/opengnsys/groups/Nombre_Grupo +#@brief Se ponen archivos o marcas dentro del directorio del grupo (si queremos que afecte a todas las imagenes) +#@brief o del subdirectorio de la imagen dentro del grupo. Los archivos se copian en el sitio correcto del sistema +#@brief y las marcas se comprueba que existen para inicar una accion (ej: cambiar registro) +#@param str_repo repositorio de imágenes (remoto o caché local) +#@param path_image camino de la imagen (sin extensión) +#@param int_ndisk nº de orden del disco +#@param int_npartition nº de orden de la particion +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_PARTITION Tipo de partición desconocido o no se puede montar. +#@warning License: GNU GPLv3+ +#*/ + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$0" "$0 path_dir str_image int_ndisk int_npart" \ + "$0 REPO /aula1/winxp 1 1" + exit +fi + +# Error si no se reciben 4 parámetros. +[ $# -eq 4 ] || ogRaiseError $OG_ERR_FORMAT || exit $? + +# Procesar parámetros. +PART=$(ogMount $3 $4) || ogRaiseError $OG_ERR_PARTITION "$3 $4" || exit $? +IMGNAME=$(basename $2) +GROUPDIR=$(ogGetGroupDir) +IMGDIR=$GROUPDIR/$IMGNAME + +# Comprobamos que exista GROUPDIR. Si no existe no es error, nada que configurar +[ ! -x "$GROUPDIR" ] && exit 0 + + +TYPE=$(ogGetOsVersion $3 $4) + +case "$TYPE" in + Linux*) echo "PostConfiguracion de Linux para el grupo $group" + # Si existen estos ficheros en el directorio del grupo o de la imagen se copian a la particion + [ -e $IMGDIR/menu.lst ] && echo "cp -f $IMGDIR/menu.lst $PART/boot/grub/menu.lst" && cp -f $IMGDIR/menu.lst $PART/boot/grub/menu.lst + [ -e $IMGDIR/grub.cfg ] && echo "cp $IMGDIR/grub.cfg $PART/boot/grub/grub.cfg" && cp -f $IMGDIR/grub.cfg $PART/boot/grub/grub.cfg + [ -e $IMGDIR/hosts ] && echo "cp -f $IMGDIR/hosts $PART/etc/hosts" && cp -f $IMGDIR/hosts $PART/etc/hosts + [ -e $IMGDIR/fstab ] && echo "cp -f $IMGDIR/fstab $PART/etc/fstab" && cp -f $IMGDIR/fstab $PART/etc/fstab + [ -e $IMGDIR/xorg.conf ] && echo "cp -f $IMGDIR/xorg.conf $PART/etc/X11/xorg.conf" && cp -f $IMGDIR/xorg.conf $PART/etc/X11/xorg.conf + [ -e $IMGDIR/rc.local ] && echo "cp -f $IMGDIR/rc.local $PART/etc/rc.local" && cp -f $IMGDIR/rc.local $PART/etc/rc.local + [ -e $IMGDIR/interfaces ] && echo "cp -f $IMGDIR/interfaces $PART/etc/network/interfaces" && cp -f $IMGDIR/interfaces $PART/etc/network/interfaces + [ -e $IMGDIR/passwd ] && echo "cp -f $IMGDIR/passwd $PART/etc/passwd" && cp -f $IMGDIR/passwd $PART/etc/passwd + ;; + + *Windows\ XP) echo "PostConfiguracion de XP para el grupo $group" + # Si existen estos ficheros en el directorio del grupo o de la imagen se copian a la particion + [ -e $IMGDIR/SAM ] && echo "cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM" && cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM + ;; + *Windows\ 7*) echo "Postconfiguracion de W7 para el grupo $group" + # Si existen estos ficheros en el directorio del grupo o de la imagen se copian a la particion + [ -e $IMGDIR/SAM ] && echo "cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM" && cp -f $IMGDIR/SAM $PART/Windows/System32/config/SAM + ;; + *) exit 0 + ;; + esac + diff --git a/client/scripts/samples/firstRunOnceWindows b/client/scripts/samples/firstRunOnceWindows new file mode 100644 index 0000000..00a6e07 --- /dev/null +++ b/client/scripts/samples/firstRunOnceWindows @@ -0,0 +1,68 @@ +#!/bin/bash +#/** +#@file FirstRunOnceWindows +#@brief Guión de rutinas que se ejecutarán en los windows con teclado y raton desactivados. +#@param $1 número de disco +#@param $2 número de particion +#@exception OG_ERR_FORMAT 1 formato incorrecto. +#@exception OG_ERR_NOTFOUND 2 fichero de imagen o partición no detectados. +#@exception OG_ERR_PARTITION 3 # Error en partición de disco. +#@exception OG_ERR_LOCKED 4 partición bloqueada por otra operación. +#@version 1.0.1 - primera version: desactivar/activar ratón y teclado +#@author Antonio J. Doblas Viso. +#@date 2017-02-23 +#**/ + + + +PROG="$(basename $0)" +if [ $# -lt 2 ]; then + ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG ndisco nparticion" + exit $? +fi + + +# Asignación de variables +## Bloque de variables de parámetros +DISK=$1 +PART=$2 +POSTCONF=postconf.cmd +### Bloque de variables basada en un archivo de claves: ADMIN PASSADMIN USER PASSUSER +source $OGETC/os.cfg $DISK $PART + + + +OSVERSION=$(ogGetOsVersion $1 $2) +case "$OSVERSION" in + *Windows*) + # Desactivamos el telcado y el ratón + ogSetRegistryValue $(ogMount $DISK $PART) SYSTEM '\ControlSet001\Services\kbdclass\Start' 4 + ogSetRegistryValue $(ogMount $DISK $PART) SYSTEM '\ControlSet001\Services\mouclass\Start' 4 + + ## Indicación del proceso (variable $POSTCONF), usuario que lo ejecutará ($ADMIN) y configuración del windows para que arranque con autologin tras la postconfiguración (1 "$USER" "$PASSUSER") + echo "ogInstallMiniSetup $DISK $PART $POSTCONF $ADMIN $PASSADMIN 1 \"$USER\" \"$PASSUSER\" " + ogInstallMiniSetup $DISK $PART $POSTCONF $ADMIN $PASSADMIN 1 "$USER" "$PASSUSER" + ogAddCmd $DISK $PART $POSTCONF '@echo off' + ogAddCmd $DISK $PART $POSTCONF 'start "C:\Program Files\Internet Explorer\iexplore.exe" wwww.opengnsys.es' + ogAddCmd $DISK $PART $POSTCONF "timeout /t 200 /NOBREAK" + ogAddCmd $DISK $PART $POSTCONF "shutdown -r -t 300" + ogAddCmd $DISK $PART $POSTCONF 'start winword.exe' + ogAddCmd $DISK $PART $POSTCONF 'taskkill /F /IM winword.exe' + ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\CurrentControlSet\Services\kbdclass\ /v Start /t REG_DWORD /d 3 /f' + ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\CurrentControlSet\Services\mouclass\ /v Start /t REG_DWORD /d 3 /f' + ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\ControlSet001\Services\kbdclass\ /v Start /t REG_DWORD /d 3 /f' + ogAddCmd $DISK $PART $POSTCONF 'REG ADD HKLM\SYSTEM\ControlSet001\Services\mouclass\ /v Start /t REG_DWORD /d 3 /f' + #ogAddCmd $DISK $PART $POSTCONF '"c:\Program Files\Toolwiz Time Freeze 2017\ToolwizTimeFreeze.exe" /freezealways /usepass=' + #ogAddCmd $DISK $PART $POSTCONF 'reg query "HKCU\SOFTWARE\Toolwiz\TimefreezeNew"' + + #ogAddCmd $DISK $PART $POSTCONF "cscript \"c:\Archivo de Programas (x86)\agua\aguac\scripts\MSOfficeActivate.vbs\" " + #ogAddCmd $DISK $PART $POSTCONF "del \"c:\Program Files (x86)\agua\aguac\scripts\MSWinActivate.vbs\" " + #unix2dos /mnt/sda1/Windows/System32/postconf.cmd + + ### reiniciamos el equipo + ogAddCmd $DISK $PART $POSTCONF "shutdown -r" + ### consultamos + cat $(ogMount $DISK $PART)/Windows/System32/$POSTCONF + + ;; +esac diff --git a/client/scripts/samples/smartPartition b/client/scripts/samples/smartPartition new file mode 100644 index 0000000..568ed32 --- /dev/null +++ b/client/scripts/samples/smartPartition @@ -0,0 +1,62 @@ +#!/bin/bash +#/** +# smartPartition.template +#@brief particiona los clientes del laboratorio virtual. +#@param 1 +#@ejemplo: +#@return: Scripts de ejemplo para establecer particionado según tamaño. +#@exception OG_ERR_ NOTFOUND Disco duro no encontrador. +#@note +#@todo: +#@version 0.1 primera version +#@author adv +#@date 2018/07/08 + +#Calculamos el numero de discos +NDISK=$(ogDiskToDev | wc -w) + +#Si no hay discos, error +[ -z $NDISK ] && exit $(ogRaiseError $OG_ERR_NOTFOUND "ogDiskToDev | wc -w") + +#asignamos contador al primer disco de OpenGnsys +COUNTER=1 +until [ $COUNTER -gt $NDISK ]; do + ogUnmountAll $COUNTER + ogDeletePartitionTable $COUNTER + ogCreatePartitionTable $COUNTER MSDOS + ogUpdatePartitionTable $COUNTER + let COUNTER=COUNTER+1 +done + +#Establecemos las Particiones CACHE con tamaños diferentes según la capacidad del disco. +#Si el PC tiene dos discos duros, el segundo será completo para la CACHE. +#establecemos rangos de las capacidades con expresiones regulares: https://goo.gl/gJnK7g +case $NDISK in + 1) + #Calcular el tamaño máximo del disco duro redondeando a la baja en 500 MB para evitar problemas de calculo" + SIZE_DISK1=$(expr $(ogGetDiskSize 1) - 500000) + #entre 70 y 73'9GB + ogCheckStringInReg $SIZE_DISK1 "^7[0-3][0-9]{6}$" && initCache 1 4 32000000 NOMOUNT + #entre 50 y 52'9 + ogCheckStringInReg $SIZE_DISK1 "^5[0-2][0-9]{6}$" && initCache 1 4 12000000 NOMOUNT + ;; + 2) + #Calcular el tamaño máximo del disco duro redondeando a la baja en 500 MB para evitar problemas de calculo" + SIZE_DISK2=$(expr $(ogGetDiskSize 1) - 500000) + initCache 2 4 $SIZE_DISK2 NOMOUNT + ;; +esac + +#El particionado para los sistemas operativos identicos para todos. +#Requiere tener una tabla de particiones previa. +ogCreatePartitions 1 NTFS:19000000 LINUX:19000000 EMPTY:0; + +#asignamos contador al primer disco de OpenGnsys +COUNTER=1 +until [ $COUNTER -gt $NDISK ]; do + ogBootMbrGeneric $COUNTER + ogSetPartitionActive 1 $COUNTER + ogListPartitions $COUNTER + ogGetPartitionActive $COUNTER + let COUNTER=COUNTER+1 +done diff --git a/client/scripts/sendFileMcast b/client/scripts/sendFileMcast new file mode 100755 index 0000000..54e82ac --- /dev/null +++ b/client/scripts/sendFileMcast @@ -0,0 +1,56 @@ +#!/bin/bash + + + +#Este scripts llama directamente a la función ogMcastSendFile $1 $2 +#1 path absoluto del fichero. +#2 la session multicast. +# ogMcastSendFile [ str_repo | int_ndisk int_npart ] /Relative_path_file sessionMulticast +#@brief Envía un fichero por multicast ORIGEN(fichero) DESTINO(sessionmulticast) +#@param (2 parámetros) $1 path_aboluto_fichero $2 sesionMcast + + + +export OPENGNSYS="${OPENGNSYS:-/opt/opengnsys/client}" + export OGBIN=$OPENGNSYS/bin + export OGETC=$OPENGNSYS/etc + export OGLIB=$OPENGNSYS/lib + export OGAPI=$OGLIB/engine/bin + export OGSCRIPTS=$OPENGNSYS/scripts + export OGIMG=$OPENGNSYS/images + export OGCAC=$OPENGNSYS/cache + export OGLOG=$OPENGNSYS/log + + for i in $OGAPI/*.lib; do + . $i + done + + if [ "$engine" = "testing" ] + then + for i in $OGAPI/*.testing; do + . $i + done + fi + +export PATH=$PATH:/opt/opengnsys/bin + +export OG_ERR_FORMAT=1 # Formato de ejecución incorrecto. +export OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado. +export OG_ERR_PARTITION=3 # Error en partición de disco. +export OG_ERR_LOCKED=4 # Partición o fichero bloqueado. +export OG_ERR_IMAGE=5 # Error al crear o restaurar una imagen. +export OG_ERR_NOTOS=6 # Sin sistema operativo. +export OG_ERR_NOTEXEC=7 # Programa o función no ejecutable. + + + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "sendFileMcast /absolute_path_file sesionMcast" \ + "sendFileMcast /opt/opengnsys/images/aula1/hd500.vmx 9000:full-duplex:239.194.17.2:70M:20:300" + exit 0 +fi + +# los demas errores controlados por la funcion ogMcastSendFile + +ogMcastSendFile $1 $2 diff --git a/client/scripts/setBootMode b/client/scripts/setBootMode new file mode 100755 index 0000000..81eec28 --- /dev/null +++ b/client/scripts/setBootMode @@ -0,0 +1,47 @@ +#!/bin/bash +# #/** +# setBootMode +#@brief Script to configure the PXE mode to client +#@param 1 template +#@date 2012-02-2-9 +#@version 1.0.1 - Recoge como parametro el nombre interno de la plantilla en vez del nombre de fichero para que funcione correctamente al llamar a setclientmode y anade un nuevo parametro de modo de trabajo (0 o 1) que indica que el cambio del fichero PXE del servidor sera temporal o permanente +#@author Juan Carlos Garcia - Univ. Zaragoza +#@date 2015-11-17 +#*/ ## + +#REPOIP="$(ogGetRepoIp)" + +# Asignamos la IP del servidor de administracion que es el destino del script +SERVERIP="$(ogGetServerIp)" +PORT=2011 +TEMPLATE=$(grep -l "^#.* $1 *$" /opt/oglive/tftpboot/menu.lst/templates/*) +PCNAME="$(hostname)" + +PROG="$(basename $0)" +if [ "$*" == "help" ]; then + ogHelp "$PROG" "$PROG template [ 0 | 1 ] (0 - Temporary 1, - Permanent) " \ + "$PROG ogLive 1" \ + "$PROG 1hd-1partition 0" + exit +fi + + +# Control básico de errores. +if [ $# -ne 2 ]; then + ogRaiseError $OG_ERR_FORMAT "$MSG_ERR_FORMAT: $PROG TEMPLATE_NAME [ 0 | 1 ] (0 - Temporary, 1 - Permanent)" + exit $? +fi + +if [ -z "$TEMPLATE" ]; then + ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_NOTFOUND: $1" + exit $? +fi + +if [ $2 != "0" ] && [ $2 != "1" ]; then + ogRaiseError $OG_ERR_NOTFOUND "$MSG_ERR_FORMAT: modo $2 no existe" + exit $? +fi +# Crea un pipe con el servidor de administracion que llama a setclientmode pasandole los parametros de nombre de plantilla, nombre PC y modo de trabajo (0 o 1) +hose $SERVERIP $PORT --out sh -c "echo -ne SET_CLIENTMODE $1 $PCNAME $2" + + diff --git a/client/scripts/updateBootCache b/client/scripts/updateBootCache new file mode 100755 index 0000000..f2e4e72 --- /dev/null +++ b/client/scripts/updateBootCache @@ -0,0 +1,65 @@ +#!/bin/bash + +#/** +# updateBootCache +#@brief acelerador arranque pxe. incorpora a la cache el initrd y el kernel. +#@param 1 +#@param ejemplo: +#@return +#@exception OG_ERR_NOTCACHE # 15 si cache no existe 15 +#@exception OG_ERR_NOTFOUND=2 # Fichero o dispositivo no encontrado. +#@note +#@todo: +#@version 1.0.1 - requiere el gestor de arranque grub2dos +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2010/07/27 +#@version 1.1.0 - Permite varios ogLive dentro de subdirectorios +#@author Irina Gómez. ETSII Universidad de Sevilla +#@date 2017/04/27 +#@version 1.1.0 - Se permite varios ogLives en la CACHE +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2017/05/31 +#@version 1.1.0 - Limpieza de codigo, control errores +#@author Antonio J. Doblas Viso. Universidad de Malaga +#@date 2018-01-21 +#*/ ## + +OGLIVEDIR=${oglivedir:-"ogLive"} +OGBTFTP="/opt/oglive/tftpboot/$OGLIVEDIR" +OGBCACHE="$OGCAC/boot/$OGLIVEDIR" + +#control de errores +[ -d "$OGBTFTP" ] || exit $(ogRaiseError $OG_ERR_NOTFOUND "$OGBTFTP"; echo $?) +ogMountCache || exit $(ogRaiseError $OG_ERR_NOTCACHE "CACHE "; echo $?) + +[ -d $OGBCACHE ] || mkdir -p $OGBCACHE + + # comparamos los del server + SERVERVMLINUZ=`cat ${OGBTFTP}/ogvmlinuz.sum 2>/dev/null` + SERVERINITRD=`cat ${OGBTFTP}/oginitrd.img.sum 2>/dev/null` + + #comparamos los de la cache + CACHEVMLINUZ=`cat ${OGBCACHE}/ogvmlinuz.sum 2>/dev/null` + CACHEINITRD=`cat ${OGBCACHE}/oginitrd.img.sum 2>/dev/null` + + echo "MD5 on SERVER: $SERVERVMLINUZ $SERVERINITRD" + echo "MD5 on CACHE: $CACHEVMLINUZ $CACHEINITRD" + + + if [ "$CACHEVMLINUZ" != "$SERVERVMLINUZ" ] + then + echo "ogvmlinuz updating" + cp "${OGBTFTP}/ogvmlinuz" "${OGBCACHE}/ogvmlinuz" + cp "${OGBTFTP}/ogvmlinuz.sum" "${OGBCACHE}/ogvmlinuz.sum" + DOREBOOT=true + fi + if [ "$CACHEINITRD" != "$SERVERINITRD" ] + then + echo "oginitrd updating" + cp "${OGBTFTP}/oginitrd.img" "${OGBCACHE}/oginitrd.img" + cp "${OGBTFTP}/oginitrd.img.sum" "${OGBCACHE}/oginitrd.img.sum" + DOREBOOT=true + fi + +echo $DOREBOOT +# [ "$DOREBOOT" == "true" ] && busybox reboot -f diff --git a/client/shared/scripts/updateBootCache.py b/client/scripts/updateBootCache.py similarity index 100% rename from client/shared/scripts/updateBootCache.py rename to client/scripts/updateBootCache.py diff --git a/client/scripts/updateCache b/client/scripts/updateCache new file mode 100755 index 0000000..f1d64ad --- /dev/null +++ b/client/scripts/updateCache @@ -0,0 +1,315 @@ +#!/bin/bash +#/** +# updateCache +#@brief Actualiza la cache del cliente con imagen o fichero iso. +#@param 1 REPO Origen del fichero. -accesible por nfs-samba- +#@param 2 str_fichero nombre del fichero a actualizar. +#@param 3 str_protoco. TORRENT | MULTICAST | UNICAST. +#@param 4 str_opcionesprotocolo +#@param 4 str_opcionesupdatecache +#@ejemplo: oneRemoteFromMaster 172.17.36.11 CACHE /imagen1 9000:full-duplex:239.194.17.36:70M:50:100 1 1 partclone lzop +#@return +#@exception OG_ERR_FORMAT formato incorrecto. +#@exception OG_ERR_NOTCACHE No existe cache -15- +#@exception $OG_ERR_CACHESIZE Tamaño de la paticion menor al archivo a descargar -16- +#@exception $OG_ERR_MCASTRECEIVERFILE Error en la recepción Multicast de un fichero -57- +#@exception $OG_ERR_PROTOCOLJOINMASTER Error en la conexión de una sesión Unicast|Multicast con el Master -60- +#@note +#@todo: +#@version 0.9.1 - integracion EAC +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2008/03/17 +#@version 0.9.2 - integracion OpenGnsys +#@author Antonio J. Doblas Viso. Universidad de Malaga. +#@date 2010/07/27 +#@version 1.0.1 - Control de espacio requerido +#@author Antonio J.Doblas Viso +#@date 2011-05-10 +#@version 2.0.1 - Imagenes sincronizadas +#@date 2013-02-20 +#@version 1.0.5 - uso de md5 full para las transferencias torrent, en la llamada => ogUpdateCacheIsNecesary +#@date 2014-07-09 +#@version 1.1 - Cambio de repositorio para el recurso remoto images si es necesario +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2015-06-16 +#@version 1.1 - Control de errores en transferencia multicast (ticket #781) +#@author Irina Gomez, ETSII Universidad de Sevilla +#@date 2017/04/20 +#*/ ## + +PROG="$(basename $0)" +if [ $# -lt 3 ]; then + ogRaiseError session $OG_ERR_FORMAT "$MSG_FORMAT: $PROG str_REPO _str_Relative_Path_OGIMG_with_/ PROTOCOLO OPCIONES_PROTOCOLO OPCIONES_UPDATECACHE" + exit $? +fi + +#Carga del configurador del engine +[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg + +# Clear temporary file used as log track by httpdlog +# Limpia los ficheros temporales usados como log de seguimiento para httpdlog +echo " " > $OGLOGCOMMAND + +if ! [ "$(ogGetCaller)" == "deployImage" -o "$(ogGetCaller)" == "restoreBaseImage" -o "$(ogGetCaller)" == "restoreDiffImage" ]; then + echo -n "" > $OGLOGSESSION; + + # Registro de inicio de ejecución + ogEcho log session "[1] $MSG_SCRIPTS_START $0 $*" +fi + +REPOSITORIO="${1^^}" +PROTOCOLO="${3^^}" +OPTPROTOCOLO="$4" +# Si MCASTWAIT menos que tiempo de espera del servidor lo aumento +if [ "${PROTOCOLO%-*}" == "MULTICAST" ] && [[ ${OPTPROTOCOLO##*:} =~ ^-?[0-9]+$ ]]; then + [ ${MCASTWAIT:0} -lt ${OPTPROTOCOLO##*:} ] && let MCASTWAIT=${OPTPROTOCOLO##*:}+5 +fi + +# Unidad organizativa. +[ "$ogunit" != "" ] && OGUNIT="$ogunit/" + +# Si es una ip y es distinta a la del recurso samba cambiamos de REPO. +ogCheckIpAddress $REPOSITORIO +if [ $? == 0 -o $REPOSITORIO == "REPO" ] ; then + # Si falla el cambio -> salimos con error repositorio no valido + ogChangeRepo $REPOSITORIO $OGUNIT || exit $(ogRaiseError $OG_ERR_NOTFOUND $REPOSITORIO; echo $?) + REPOSITORIO="REPO" +fi +REPOIP=$(ogGetRepoIp) +ogEcho log session $REPOSITORIO $REPOIP $PROTOCOLO $OPTPROTOCOLO + +# Si el repositorio local CACHE no existe error 15. +if ! $(ogFindCache >/dev/null); then + ogRaiseError session $OG_ERR_NOTCACHE "CACHE" + exit $? +fi + +# comprobar si la imagen existe (.img, .img.diff o directorio) +REPOFILE=$(ogGetPath "REPO" "/$2") +[ -n "$REPOFILE" ] || exit $(ogRaiseError session $OG_ERR_NOTFOUND "REPO /$2"; echo $?) + +ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_DOUPDATE" +# Distingo si es monolitica o sincronizable +file "$REPOFILE" | grep -i -e " BTRFS Filesystem " -e " ext4 filesystem " -e " directory" 2>&1 > /dev/null +if [ $? == 0 ]; then + IMGSYNC=TRUE + # Para imagen sincronizada, si hay imagen en cache siempre protocolo = rsync. + CACHEFILE="$(ogGetPath "CACHE" "/$2")" + [ -n "$CACHEFILE" ] && PROTOCOLO="RSYNC" + # Si es sincronizada tipo directorio siempre protocolo = rsync. + [ -d $REPOFILE ] && PROTOCOLO="RSYNC" && IMGTYPE="dir" + + # Si es imagen sincronizada siempre da distinto md5. No podemos comprobar -> actualizamos. + RETVAL=0 +else + # Si la imagen es monolitica y ha elegido protocolo = RSYNC salimos con error. + [ $PROTOCOLO == "RSYNC" ] && exit $(ogRaiseError session $OG_ERR_DONTSYNC_IMAGE "REPO $2"; echo $?) + IMGSYNC=FALSE + ogUpdateCacheIsNecesary "$REPOSITORIO" "$2" "$PROTOCOLO" + RETVAL=$? +fi +# si RETVAL=0 => actualizamos si RETVAL=1 no actaulizasmo-exit 0 || si RETVAL>2 exit 1 +[ "$RETVAL" == "1" ] && exit 0 +[ "$RETVAL" -gt "1" ] && exit $OG_ERR_UPDATECACHE + +ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKSIZECACHE" +CACHESIZE=$(ogGetCacheSize) +CACHESIZEFREE=$(ogGetFreeSize `ogFindCache`) +FILESIZE=$(ls -sk $(ogGetPath $REPOSITORIO "$2") | cut -f1 -d" ") +if [ "$IMGTYPE" == "dir" ]; then + ogEcho log session " * $MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR" + ogEcho log session " du -sk $REPOFILE" + REALFILESIZE=$(du -sk "$REPOFILE"|awk '{print $1}') +else + REALFILESIZE=$(ls -l --block-size=1024 $REPOFILE | cut -f5 -d" ") +fi + +# La sincronizada, si existe la imagen en cache el espacio necesario +# es la nueva menos lo que ocupa la que ya hay. +if [ "$PROTOCOLO" == "RSYNC" ]; then + if [ "$CACHEFILE" == "" ]; then + CACHEFILESIZE=0 + else + if [ "$IMGTYPE" == "dir" ]; then + ogEcho log session " * $MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR $CACHEFILESIZE" + ogEcho log session " du -sk $CACHEFILE" + CACHEFILESIZE=$(du -sk $CACHEFILE |awk '{print $1}') + else + CACHEFILESIZE=$(ls -l --block-size=1024 "$CACHEFILE" | cut -f5 -d" ") + fi + fi + let SIZEREQUIRED=$REALFILESIZE-$CACHEFILESIZE + [ $SIZEREQUIRED -lt 0 ] && SIZEREQUIRED=0 +else + SIZEREQUIRED=$FILESIZE +fi + +#ERROR CACHESIZE 16 (tamanyo de la CACHE insuficiente) +if [ "$SIZEREQUIRED" -ge "$CACHESIZE" ] +then + ogEcho log session "$MSG_WARNING: $MSG_ERR_CACHESIZE: $2 = $SIZEREQUIRED > CACHE = $CACHESIZE" + ogRaiseError session $OG_ERR_CACHESIZE "CACHE" + exit $? +fi + + +#ERROR CACHESIZE 16 (Espacio libre en CACHE insuficiente) +if [ "$SIZEREQUIRED" -ge "$CACHESIZEFREE" ] +then + ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO: ACTIONCACHEFULL=$ACTIONCACHEFULL" + case "$ACTIONCACHEFULL" in + NONE) + ogEcho log session "$MSG_WARNING: $MSG_ERR_CACHESIZE: $2 = $SIZEREQUIRED > FREE SPACE CACHE = $CACHESIZEFREE" + ogRaiseError session $OG_ERR_CACHESIZE "CACHE FULL, NO SPACE FREE" + exit $? + ;; + FORMAT) + ogEcho log session "[51] $MSG_HELP_ogFormatCache " + ogUnmountCache + ogFormatCache + ogMountCache + NEXTOPERATION=REPEAT + ;; + DELETE) + ogEcho log session "[51] #MSG_HELP_ogDeleteTree $OGCAC$OGIMG/* " + rm -fr $OGCAC$OGIMG/* + NEXOPERATION=REPEAT + ;; + *) + ogEcho log session "$MSG_WARNING: $MSG_ERR_CACHESIZE: $2 = $FILESIZE > CACHE = $CACHESIZEFREE" + ogRaiseError session $OG_ERR_CACHESIZE "CACHE" + exit $? + ;; + esac +fi + +# Comprobamos que imagen cache igual a la del repo. Si sincronizada no podemos comprobar. +[ "$IMGSYNC" == "TRUE" ] || ogUpdateCacheIsNecesary $REPOSITORIO "$2" "$PROTOCOLO" +RETVAL=$? +# si RETVAL=0 => actualizamos si RETVAL=1 no actaulizasmo-exit 0 || si RETVAL>2 exit 1 +[ "$RETVAL" == "1" ] && exit 0 +[ "$RETVAL" -gt "1" ] && exit $OG_ERR_UPDATECACHE + +ogMountCache >/dev/null + +## Si no existe, crear subdirectorio para el fichero en la cache. +IMGDIR=$(ogGetParentPath CACHE "/$2") +if [ $? != 0 ]; then + ogEcho log session "[5] $MSG_HELP_ogMakeDir \"$2 $(dirname "$2")." + ogMakeDir CACHE $(dirname "/$2") + IMGDIR=$(ogGetParentPath CACHE "/$2") || exit $? +fi + +TIME1=$SECONDS + +case "$PROTOCOLO" in + TORRENT) + ogEcho log session "ogCopyFile $REPOSITORIO $2.torrent absolute $OGCAC/$OGIMG" + # tiempos + timewait=$(expr $(printf '%d\n' 0x$(ogGetMacAddress | awk -F: '{print $5$6}')) \* 120 / 65535) + ogExecAndLog command ogCopyFile $REPOSITORIO "$2.torrent" "$IMGDIR" || exit $? + #TODO: comprobar que el tracker definido en el fichero es correcto. + #TODO comprobar que el fichero torrent está en cache + # retardamos el inicio -aleatorio de 0 a 120 segundos- al tracker para gestionar mas de +-40 equipos + P2PWAIT=$[ ( $RANDOM % 120 ) + 1 ] + ogEcho log session " [ ] $MSG_SCRIPTS_TASK_SLEEP : $P2PWAIT seconds" + sleep $P2PWAIT + ogEcho log session " [ ] $MSG_SCRIPTS_TASK_START: ogTorrentStart CACHE $2.torrent $4" + ogExecAndLog command ogTorrentStart CACHE "$2.torrent" $4 + RESUMEUPDATECACHE=$(grep -m 1 -B1 "Download" $OGLOGCOMMAND) + RESUMEUPDATECACHEbf=$(grep -m 1 "Download" $OGLOGCOMMAND) + if [ "$RESUMEUPDATECACHEbf" == "Download complete." ]; then + rm -f $IMGDIR$2".torrent.bf" + fi + ;; + MULTICAST) + ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION: $REPOIP:${OPTPROTOCOLO%%:*}" + #TODO: ticket 379 + NUMBER=$[ ( $RANDOM % 30 ) + 1 ] + sleep $NUMBER + #FIN TODO + ogEcho log session ogMcastRequest "$2" $OPTPROTOCOLO + ogExecAndLog command ogMcastRequest "$2" $OPTPROTOCOLO || exit $? + ogEcho log session ogMcastReceiverFile ${OPTPROTOCOLO%%:*} CACHE "$2" + ogExecAndLog command ogMcastReceiverFile ${OPTPROTOCOLO%%:*} CACHE "$2" || exit $? + RESUMEUPDATECACHE=$(grep -m 1 -B1 "Transfer complete" $OGLOGCOMMAND.tmp) + ;; + UNICAST) + #ogEcho log session "unicast" + ogExecAndLog command ogCopyFile $REPOSITORIO "$2" "$IMGDIR" + sleep 5 + RESUMEUPDATECACHE=$(grep -m 1 "100%" $OGLOGCOMMAND.tmp) + ;; + RSYNC) + # Si parametro de protocolo no era rsync, mensaje de cambio protocolo + [ "${3^^}" == "RSYNC" ] || ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_RSYNCPROTOCOLCHANGE" + # Opciones de rsync + USERRSYNC="opengnsys" + PASSWORD=" --password-file=/scripts/passrsync " + OPTRSYNC=" --delete --progress " + [ "$ogrsyncz" == "true" ] && OPTRSYNC="z $OPTRSYNC" + [ "$ogrsyncw" == "true" ] && OPTRSYNC="w$OPTRSYNC" + + if [ -d $REPOFILE ]; then + # Si es sincronizada tipo directorio. + [ -d "$OGCAC$OGIMG/$2" ] || mkdir "$OGCAC$OGIMG/$2" + ogEcho log session "rsync -aHAX$OPTRSYNC $USERRSYNC@$REPOIP::ogimages/$OGUNIT$2/ $OGCAC$OGIMG/$2" + rsync -aHAX$OPTRSYNC $PASSWORD "$USERRSYNC@$REPOIP::ogimages/$OGUNIT$2/" "$OGCAC$OGIMG/$2" 2>> $OGLOGCOMMAND | egrep "^sent|^sending|^total%" >> $OGLOGCOMMAND + else + # Si es sincronizada tipo archivo. + [ "${2##*.}" == "img" ] && IMGTYPE="img" || IMGTYPE="diff" + IMGNAME="${2%.img*}" + + DIRMOUNT=$(ogGetMountImageDir "$IMGNAME" $IMGTYPE) + DIRLOCAL="/tmp/$DIRMOUNT" + mkdir "$DIRLOCAL" 2>/dev/null + ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG" + + # Si la imagen no existe la creo + # Si la imagen del repositorio es mayor, redimensiono la imagen de cache + if [ "$CACHEFILE" == "" -o $CACHEFILESIZE -lt $REALFILESIZE ]; then + ogEcho log session "$MSG_HELP_ogCreateFileImage" + ogCreateFileImage CACHE "$IMGNAME" $IMGTYPE $REALFILESIZE + TIMEAUX3=$[SECONDS-TIMEAUX3] + ogEcho log session " $MSG_SCRIPTS_TASK_END, $MSG_SCRIPTS_TIME_PARTIAL: $[TIMEAUX3/60]m $[TIMEAUX3%60]s" + fi + # Montamos las imagenes para sincronizarlas. Quitamos / inicial. + ogMountImage CACHE "${IMGNAME#\/}" $IMGTYPE || exit $? + ogMountImage REPO "${IMGNAME#\/}" $IMGTYPE + # Esperamos que se monte la imagen en el servidor + ogWaitSyncImage REPO "$IMGNAME" $IMGTYPE "mounted" || exit $? + ogEcho log session " rsync -aHAX$OPTRSYNC $USERRSYNC@$REPOIP::ogimages/$DIRMOUNT/ $DIRLOCAL" + rsync -aHAX$OPTRSYNC $PASSWORD "$USERRSYNC@$REPOIP::ogimages/$DIRMOUNT/" "$DIRLOCAL" 2>>$OGLOGCOMMAND | egrep "^sent|^sending|^total|%" >> $OGLOGCOMMAND + # RETVAL="1" -> OK RETVAL="2" -> error # valores igual que ogUpdateCacheIsNecesary + [ ${PIPESTATUS[0]} -eq 0 ] && RETVAL="1"|| RETVAL="2" + # Desmonto las imagenes + ogUnmountImage CACHE "$IMGNAME" $IMGTYPE + ogUnmountImage REPO "$IMGNAME" $IMGTYPE + ogUnlockImage CACHE "$2" + fi + ;; +esac + +TIME1=$[SECONDS-TIME1] + +ogEcho log session " [ ] $RESUMEUPDATECACHE " +ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL updateCache $[TIME1/60]m $[TIME1%60]s" +ogEcho log session " [ ] $MSG_SCRIPTS_TASK_START $MSG_HELP_ogCalculateChecksum " +TIME2=$SECONDS +# Si es imagen sincronizada siempre da distinto md5. No podemos comprobar +if [ "$IMGSYNC" == "TRUE" ]; then + # RETVAL="1" -> OK RETVAL="2" -> error # valores igual que ogUpdateCacheIsNecesary + [ $PROTOCOLO == "RSYNC" ] || RETVAL=1 +else + ogUpdateCacheIsNecesary $REPOSITORIO "$2" "$PROTOCOLO" + RETVAL=$? +fi +if [ "$(ogGetCaller)" != "deployImage" ]; then + TIME2=$[SECONDS-TIME2] + ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL $MSG_HELP_ogCalculateChecksum $[TIME2/60]m $[TIME2%60]s" +fi +# si RETVAL=0 => actualizamos si RETVAL=1 no actaulizamos-exit 0 || si RETVAL>2 exit 1 +[ "$RETVAL" == "0" ] && exit $OG_ERR_UPDATECACHE +[ "$RETVAL" == "1" ] && exit 0 +[ "$RETVAL" -gt "1" ] && exit $OG_ERR_UPDATECACHE + diff --git a/client/shared/scripts/updateCache.py b/client/scripts/updateCache.py similarity index 100% rename from client/shared/scripts/updateCache.py rename to client/scripts/updateCache.py diff --git a/client/shared/scripts/__init__.py b/client/shared/scripts/__init__.py deleted file mode 100755 index e69de29..0000000