pax_global_header00006660000000000000000000000064122546150440014515gustar00rootroot0000000000000052 comment=92092484201c888d2bc0f5bafd23e3900b3b14e4 repmgr-2.0beta2/000077500000000000000000000000001225461504400135705ustar00rootroot00000000000000repmgr-2.0beta2/.gitignore000066400000000000000000000001331225461504400155550ustar00rootroot00000000000000*~ *.o *.so repmgr repmgrd README.htm* README.pdf sql/repmgr_funcs.so sql/repmgr_funcs.sql repmgr-2.0beta2/COPYRIGHT000066400000000000000000000012631225461504400150650ustar00rootroot00000000000000Copyright (c) 2010-2012, 2ndQuadrant Limited All rights reserved. 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 http://www.gnu.org/licenses/ to obtain one. repmgr-2.0beta2/CREDITS000066400000000000000000000011211225461504400146030ustar00rootroot00000000000000Code and documentation contributors to repmgr include: Jaime Casanova Simon Riggs Greg Smith Robert J. Noles Gabriele Bartolini Bas van Oostveen Hannu Krosing Cédric Villemain Charles Duffy Daniel Farina Shawn Ellis Jay Taylor Christian Kruse Krzysztof Gajdemski repmgr-2.0beta2/HISTORY000066400000000000000000000065061225461504400146630ustar00rootroot000000000000002.0beta2 2013-12-19 Improve autofailover logic and algorithms (Jaime, Andres) Ignore pg_log when cloning (Jaime) Add timestamps to log line in stderr (Christian) Correctly check wal_keep_segments (Jay Taylor) Add a ssh_options parameter (Jay Taylor) 2.0beta1 2012-07-27 Make CLONE command try to make an exact copy including $PGDATA location (Cedric) Add detection of master failure (Jaime) Add the notion of a witness server (Jaime) Add autofailover capabilities (Jaime) Add a configuration parameter to indicate the script to execute on failover or follow (Jaime) Make the monitoring optional and turned off by default, it can be turned on with --monitoring-history switch (Jaime) Add tunables to specify number of retries to reconnect to master and the time between them (Jaime) 1.2.0 2012-07-27 Test ssh connection before trying to rsync (Cédric) Add CLUSTER SHOW command (Carlo) Add CLUSTER CLEANUP command (Jaime) Add function write_primary_conninfo (Marco) Teach repmgr how to get tablespace's location in different pg version (Jaime) Improve version message (Carlo) 1.1.1 2012-04-18 Add --ignore-rsync-warning (Cédric) Add strnlen for compatibility with OS X (Greg) Improve performance of the repl_status view (Jaime) Remove last argument from log_err (Jaime, Reported by Jeroen Dekkers) Complete documentation about possible error conditions (Jaime) Document how to clean history (Jaime) 1.1.0 2011-03-09 Make options -U, -R and -p not mandatory (Jaime) 1.1.0b1 2011-02-24 Fix missing "--force" option in help (Greg Smith) Correct warning message for wal_keep_segments (Bas van Oostveen) Add Debian build/usage docs (Bas, Hannu Krosing, Cedric Villemain) Add Debian .deb packaging (Hannu) Move configuration data into a structure (Bas, Gabriele Bartolini) Make rsync options configurable (Bas) Add syslog as alternate logging destination (Gabriele) Change from using malloc to static memory allocations (Gabriele) Add debugging messages after every query (Gabriele) Parameterize schema name used for repmgr (Gabriele) Avoid buffer overruns by using snprintf etc. (Gabriele) Fix use of database query after close (Gabriele) Add information about progress during "standby clone" (Gabriele) Fix double free errors in repmgrd (Charles Duffy, Greg) Make repmgr exit with an error code when encountering an error (Charles) Standardize on error return codes, use in repmgrd too (Greg) Add [un]install actions/SQL like most contrib modules (Daniel Farina) Wrap all string construction and produce error on overflow (Daniel) Correct freeing of memory from first_wal_segment (Daniel) Allow creating recovery.conf file with a password (Daniel) Inform when STANDBY CLONE sees an unused config file (Daniel) Use 64-bit computation for WAL apply_lag (Greg) Add info messages for database and general work done (Greg) Map old verbose flag into a useful setting for the new logger (Greg) Document repmgrd startup restrictions and log info about them (Greg) 1.0.0 2010-12-05 First public release repmgr-2.0beta2/LICENSE000066400000000000000000001045141225461504400146020ustar00rootroot00000000000000 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 . repmgr-2.0beta2/Makefile000066400000000000000000000034441225461504400152350ustar00rootroot00000000000000# # Makefile # Copyright (c) 2ndQuadrant, 2010-2012 repmgrd_OBJS = dbutils.o config.o repmgrd.o log.o strutil.o repmgr_OBJS = dbutils.o check_dir.o config.o repmgr.o log.o strutil.o DATA = repmgr.sql uninstall_repmgr.sql PG_CPPFLAGS = -I$(libpq_srcdir) PG_LIBS = $(libpq_pgport) all: repmgrd repmgr $(MAKE) -C sql repmgrd: $(repmgrd_OBJS) $(CC) $(CFLAGS) $(repmgrd_OBJS) $(PG_LIBS) $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o repmgrd $(MAKE) -C sql repmgr: $(repmgr_OBJS) $(CC) $(CFLAGS) $(repmgr_OBJS) $(PG_LIBS) $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o repmgr ifdef USE_PGXS PGXS := $(shell pg_config --pgxs) include $(PGXS) else subdir = contrib/repmgr top_builddir = ../.. include $(top_builddir)/src/Makefile.global include $(top_srcdir)/contrib/contrib-global.mk endif # XXX: Try to use PROGRAM construct (see pgxs.mk) someday. Right now # is overriding pgxs install. install: $(INSTALL_PROGRAM) repmgrd$(X) '$(DESTDIR)$(bindir)' $(INSTALL_PROGRAM) repmgr$(X) '$(DESTDIR)$(bindir)' $(MAKE) -C sql install ifneq (,$(DATA)$(DATA_built)) @for file in $(addprefix $(srcdir)/, $(DATA)) $(DATA_built); do \ echo "$(INSTALL_DATA) $$file '$(DESTDIR)$(datadir)/$(datamoduledir)'"; \ $(INSTALL_DATA) $$file '$(DESTDIR)$(datadir)/$(datamoduledir)'; \ done endif clean: rm -f *.o rm -f repmgrd rm -f repmgr $(MAKE) -C sql clean deb: repmgrd repmgr mkdir -p ./debian/usr/bin cp repmgrd repmgr ./debian/usr/bin/ mkdir -p ./debian/usr/share/postgresql/9.0/contrib/ cp sql/repmgr_funcs.sql ./debian/usr/share/postgresql/9.0/contrib/ cp sql/uninstall_repmgr_funcs.sql ./debian/usr/share/postgresql/9.0/contrib/ mkdir -p ./debian/usr/lib/postgresql/9.0/lib/ cp sql/repmgr_funcs.so ./debian/usr/lib/postgresql/9.0/lib/ dpkg-deb --build debian mv debian.deb ../postgresql-repmgr-9.0_1.0.0.deb rm -rf ./debian/usr repmgr-2.0beta2/README.rst000066400000000000000000001231731225461504400152660ustar00rootroot00000000000000=================================================== repmgr: Replication Manager for PostgreSQL clusters =================================================== Introduction ============ PostgreSQL 9+ allow us to have replicated Hot Standby servers which we can query and/or use for high availability. While the main components of the feature are included with PostgreSQL, the user is expected to manage the high availability part of it. repmgr allows you to monitor and manage your replicated PostgreSQL databases as a single cluster. repmgr includes two components: * repmgr: command program that performs tasks and then exits * repmgrd: management and monitoring daemon that watches the cluster and can automate remote actions. Supported Releases ------------------ repmgr works with PostgreSQL versions 9.0 and superior. There are currently no incompatibilities when upgrading repmgr from 9.0 to 9.1, so your 9.0 configuration will work with 9.1 Additional parameters must be added to postgresql.conf to take advantage of the new 9.1 features such as synchronous replication or hot standby feedback. Requirements ------------ repmgr is currently aimed for installation on UNIX-like systems that include development tools such as ``gcc`` and ``gmake``. It also requires that the ``rsync`` utility is available in the PATH of the user running the repmgr programs. Some operations also require PostgreSQL components such as ``pg_config`` and ``pg_ctl`` be in the PATH. Introduction to repmgr commands =============================== Suppose we have 3 nodes: node1 (the initial master), node2 and node3. To make node2 and node3 be standbys of node1, execute this on both nodes (node2 and node3):: repmgr -D /var/lib/pgsql/9.0 standby clone node1 In order to get full monitoring and easier state transitions, you register each of the nodes, by creating a ``repmgr.conf`` file and executing commands like this on the appropriate nodes:: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf --verbose master register repmgr -f /var/lib/pgsql/repmgr/repmgr.conf --verbose standby register Once everything is registered, you start the repmgrd daemon. It will maintain a view showing the state of all the nodes in the cluster, including how far they are lagging behind the master. If you lose node1 you can then run this on node2:: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf standby promote To make node2 the new master. Then on node3 run:: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf standby follow To make node3 follow node2 (rather than node1). If now we want to add a new node, we can a prepare a new server (node4) and run:: repmgr -D /var/lib/pgsql/9.0 standby clone node2 And if a previously failed node becomes available again, such as the lost node1 above, you can get it to resynchronize by only copying over changes made while it was down using. That hapens with what's called a forced clone, which overwrites existing data rather than assuming it starts with an empty database directory tree:: repmgr -D /var/lib/pgsql/9.0 --force standby clone node1 This can be much faster than creating a brand new node that must copy over every file in the database. Installation Outline ==================== To install and use repmgr and repmgrd follow these steps: 1. Build repmgr programs 2. Set up trusted copy between postgres accounts, needed for the ``STANDBY CLONE`` step 3. Check your primary server is correctly configured 4. Write a suitable ``repmgr.conf`` for the node 5. Setup repmgrd to aid in failover transitions Build repmgr programs --------------------- Both methods of installation will place the binaries at the same location as your postgres binaries, such as ``psql``. There are two ways to build it. The second requires a full PostgreSQL source code tree to install the program directly into. The first instead uses the PostgreSQL Extension System (PGXS) to install. For this method to work, you will need the pg_config program available in your PATH. In some distributions of PostgreSQL, this requires installing a separate development package in addition to the basic server software. Build repmgr programs - PGXS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you are using a packaged PostgreSQL build and have ``pg_config`` available, the package can be built and installed using PGXS instead:: tar xvzf repmgr-1.0.tar.gz cd repmgr make USE_PGXS=1 make USE_PGXS=1 install This is preferred to building from the ``contrib`` subdirectory of the main source code tree. If you need to remove the source code temporary files from this directory, that can be done like this:: make USE_PGXS=1 clean See below for building notes specific to RedHat Linux variants. Using a full source code tree ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In this method, the repmgr distribution is copied into the PostgreSQL source code tree, assumed to be at the ${postgresql_sources} for this example. The resulting subdirectory must be named ``contrib/repmgr``, without any version number:: cp repmgr.tar.gz ${postgresql_sources}/contrib cd ${postgresql_sources}/contrib tar xvzf repmgr-1.0.tar.gz cd repmgr make make install If you need to remove the source code temporary files from this directory, that can be done like this:: make clean Notes on RedHat Linux, Fedora, and CentOS Builds ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The RPM packages of PostgreSQL put ``pg_config`` into the ``postgresql-devel`` package, not the main server one. And if you have a RPM install of PostgreSQL 9.0, the entire PostgreSQL binary directory will not be in your PATH by default either. Individual utilities are made available via the ``alternatives`` mechanism, but not all commands will be wrapped that way. The files installed by repmgr will certainly not be in the default PATH for the postgres user on such a system. They will instead be in /usr/pgsql-9.0/bin/ on this type of system. When building repmgr against a RPM packaged build, you may discover that some development packages are needed as well. The following build errors can occur:: /usr/bin/ld: cannot find -lxslt /usr/bin/ld: cannot find -lpam Install the following packages to correct those:: yum install libxslt-devel yum install pam-devel If building repmgr as a regular user, then doing the install into the system directories using sudo, the syntax is hard. ``pg_config`` won't be in root's path either. The following recipe should work:: sudo PATH="/usr/pgsql-9.0/bin:$PATH" make USE_PGXS=1 install Issues with 32 and 64 bit RPMs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If when building, you receive a series of errors of this form:: /usr/bin/ld: skipping incompatible /usr/pgsql-9.0/lib/libpq.so when searching for -lpq This is likely because you have both the 32 and 64 bit versions of the ``postgresql90-devel`` package installed. You can check that like this:: rpm -qa --queryformat '%{NAME}\t%{ARCH}\n' | grep postgresql90-devel And if two packages appear, one for i386 and one for x86_64, that's not supposed to be allowed. This can happen when using the PGDG repo to install that package; here is an example sessions demonstrating the problem case appearing:: # yum install postgresql-devel .. Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package postgresql90-devel.i386 0:9.0.2-2PGDG.rhel5 set to be updated ---> Package postgresql90-devel.x86_64 0:9.0.2-2PGDG.rhel5 set to be updated --> Finished Dependency Resolution Dependencies Resolved ========================================================================= Package Arch Version Repository Size ========================================================================= Installing: postgresql90-devel i386 9.0.2-2PGDG.rhel5 pgdg90 1.5 M postgresql90-devel x86_64 9.0.2-2PGDG.rhel5 pgdg90 1.6 M Note how both the i386 and x86_64 platform architectures are selected for installation. Your main PostgreSQL package will only be compatible with one of those, and if the repmgr build finds the wrong postgresql90-devel these "skipping incompatible" messages appear. In this case, you can temporarily remove both packages, then just install the correct one for your architecture. Example:: rpm -e postgresql90-devel --allmatches yum install postgresql90-devel-9.0.2-2PGDG.rhel5.x86_64 Instead just deleting the package from the wrong platform might not leave behind the correct files, due to the way in which these accidentally happen to interact. If you already tried to build repmgr before doing this, you'll need to do:: make USE_PGXS=1 clean To get rid of leftover files from the wrong architecture. Notes on Ubuntu, Debian or other Debian-based Builds ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Debian packages of PostgreSQL put ``pg_config`` into the development package called ``postgresql-server-dev-$version``. When building repmgr against a Debian packages build, you may discover that some development packages are needed as well. You will need the following development packages installed:: sudo apt-get install libxslt-dev libxml2-dev libpam-dev libedit-dev If your using Debian packages for PostgreSQL and are building repmgr with the USE_PGXS option you also need to install the corresponding development package:: sudo apt-get install postgresql-server-dev-9.0 If you build and install repmgr manually it will not be on the system path. The binaries will be installed in /usr/lib/postgresql/$version/bin/ which is not on the default path. The reason behind this is that Ubuntu/Debian systems manage multiple installed versions of PostgreSQL on the same system through a wrapper called pg_wrapper and repmgr is not (yet) known to this wrapper. You can solve this in many different ways, the most Debian like is to make an alternate for repmgr and repmgrd:: sudo update-alternatives --install /usr/bin/repmgr repmgr /usr/lib/postgresql/9.0/bin/repmgr 10 sudo update-alternatives --install /usr/bin/repmgrd repmgrd /usr/lib/postgresql/9.0/bin/repmgrd 10 You can also make a deb package of repmgr using:: make USE_PGXS=1 deb This will build a Debian package one level up from where you build, normally the same directory that you have your repmgr/ directory in. Confirm software was built correctly ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You should now find the repmgr programs available in the subdirectory where the rest of your PostgreSQL installation is at. You can confirm the software is available by checking its version:: repmgr --version repmgrd --version You may need to include the full path of the binary instead, such as this RHEL example:: /usr/pgsql-9.0/bin/repmgr --version /usr/pgsql-9.0/bin/repmgrd --version Or in this Debian example:: /usr/lib/postgresql/9.0/bin/repmgr --version /usr/lib/postgresql/9.0/bin/repmgrd --version Below this binary installation base directory is referred to as PGDIR. Set up trusted copy between postgres accounts --------------------------------------------- Initial copy between nodes uses the rsync program running over ssh. For this to work, the postgres accounts on each system need to be able to access files on their partner node without a password. First generate a ssh key, using an empty passphrase, and copy the resulting keys and a maching authorization file to a privledged user on the other system:: [postgres@node1]$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/var/lib/pgsql/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /var/lib/pgsql/.ssh/id_rsa. Your public key has been saved in /var/lib/pgsql/.ssh/id_rsa.pub. The key fingerprint is: aa:bb:cc:dd:ee:ff:aa:11:22:33:44:55:66:77:88:99 postgres@db1.domain.com [postgres@node1]$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys [postgres@node1]$ chmod go-rwx ~/.ssh/* [postgres@node1]$ cd ~/.ssh [postgres@node1]$ scp id_rsa.pub id_rsa authorized_keys user@node2: Login as a user on the other system, and install the files into the postgres user's account:: [user@node2 ~]$ sudo chown postgres.postgres authorized_keys id_rsa.pub id_rsa [user@node2 ~]$ sudo mkdir -p ~postgres/.ssh [user@node2 ~]$ sudo chown postgres.postgres ~postgres/.ssh [user@node2 ~]$ sudo mv authorized_keys id_rsa.pub id_rsa ~postgres/.ssh [user@node2 ~]$ sudo chmod -R go-rwx ~postgres/.ssh Now test that ssh in both directions works. You may have to accept some new known hosts in the process. Primary server configuration ---------------------------- PostgreSQL should have been previously built and installed on the system. Here is a sample of changes to the ``postgresql.conf`` file:: listen_addresses='*' wal_level = 'hot_standby' archive_mode = on archive_command = 'cd .' # we can also use exit 0, anything that # just does nothing max_wal_senders = 10 wal_keep_segments = 5000 # 80 GB required on pg_xlog hot_standby = on Also you need to add the machines that will participate in the cluster in ``pg_hba.conf`` file. One possibility is to trust all connections from the replication users from all internal addresses, such as:: host all all 192.168.1.0/24 trust host replication all 192.168.1.0/24 trust A more secure setup adds a repmgr user and database, just giving access to that user:: host repmgr repmgr 192.168.1.0/24 trust host replication all 192.168.1.0/24 trust If you give a password to the user, you need to create a ``.pgpass`` file for them as well to allow automatic login. In this case you might use the ``md5`` authentication method instead of ``trust`` for the repmgr user. Don't forget to restart the database server after making all these changes. Usage walkthrough ================= This assumes you've already followed the steps in "Installation Outline" to install repmgr and repmgrd on the system. A normal production installation of ``repmgr`` will normally involve two different systems running on the same port, typically the default of 5432, with both using files owned by the ``postgres`` user account. This walkthrough assumes the following setup: * A primary (master) server called "node1," running as the "postgres" user who is also the owner of the files. This server is operating on port 5432. This server will be known as "node1" in the cluster "test". * A secondary (standby) server called "node2," running as the "postgres" user who is also the owner of the files. This server is operating on port 5432. This server will be known as "node2" in the cluster "test". * Another standby server called "node3" with a similar configuration to "node2". * The Postgres installation in each of the above is defined as $PGDATA, which is represented here as ``/var/lib/pgsql/9.0/data`` Creating some sample data ------------------------- If you already have a database with useful data to replicate, you can skip this step and use it instead. But if you do not already have data in this cluster to replication, you can create some like this:: createdb pgbench pgbench -i -s 10 pgbench Examples below will use the database name ``pgbench`` to match this. Substitute the name of your database instead. Note that the standby nodes created here will include information for every database in the cluster, not just the specified one. Needing the database name is mainly for user authentication purposes. Setting up a repmgr user ------------------------ Make sure that the "standby" user has a role in the database, "pgbench" in this case, and can login. On "node1":: createuser --login --superuser repmgr Alternately you could start ``psql`` on the pgbench database on "node1" and at the node1b# prompt type:: CREATE ROLE repmgr SUPERUSER LOGIN; The main advantage of the latter is that you can do it remotely to any system you already have superuser access to. Clearing the PostgreSQL installation on the Standby --------------------------------------------------- To setup a new streaming replica, startin by removing any PostgreSQL installation on the existing standby nodes. * Stop any server on "node2" and "node3". You can confirm the database servers running using a command like this:: ps -eaf | grep postgres And looking for the various database server processes: server, logger, wal writer, and autovacuum launcher. * Go to "node2" and "node3" database directories and remove the PostgreSQL installation:: cd $PGDATA rm -rf * This will delete the entire database installation in ``/var/lib/pgsql/9.0/data``. Be careful that $PGDATA is defined here; executing ``ls`` to confirm you're in the right place is always a good idea before executing ``rm``. Testing remote access to the master ----------------------------------- On the "node2" server, first test that you can connect to "node1" the way repmgr will by executing:: psql -h node1 -U repmgr -d pgbench Possible sources for a problem here include: * Login role specified was not created on "node1" * The database configuration on "node1" is not listening on a TCP/IP port. That could be because the ``listen_addresses`` parameter was not updated, or if it was but the server wasn't restarted afterwards. You can test this on "node1" itself the same way:: psql -h node1 -U repmgr -d pgbench With the "-h" parameter forcing a connnection over TCP/IP, rather than the default UNIX socket method. * There is a firewall setup that prevents incoming access to the PostgreSQL port (defaulting to 5432) used to access "node1". In this situation you would be able to connect to the "node1" server on itself, but not from any other host, and you'd just get a timeout when trying rather than a proper error message. * The ``pg_hba.conf`` file does not list appropriate statements to allow this user to login. In this case you should connect to the server, but see an error message mentioning the ``pg_hba.conf``. Cloning the standby ------------------- With "node1" server running, we want to use the ``clone standby`` command in repmgr to copy over the entire PostgreSQL database cluster onto the "node2" server. Execute the clone process with:: repmgr -D $PGDATA -d pgbench -p 5432 -U repmgr -R postgres --verbose standby clone node1 Here "-U" specifies the database user to connect to the master as, while "-R" specifies what user to run the rsync command as. Potentially you could leave out one or both of these, in situations where the user and/or role setup is the same on each node. If this fails with an error message about accessing the master database, you should return to the previous step and confirm access to "node1" from "node2" with ``psql``, using the same parameters given to repmgr. NOTE: you need to have $PGDIR/bin (where the PostgreSQL binaries are installed) in your path for the above to work. If you don't want that as a permanent setting, you can temporarily set it before running individual commands like this:: PATH=$PGDIR/bin:$PATH repmgr -D $PGDATA ... Setup repmgr configuration file ------------------------------- Create a directory to store each repmgr configuration in for each node. In that, there needs to be a ``repmgr.conf`` file for each node in the cluster. For each node we'll assume this is stored in ``/var/lib/pgsql/repmgr/repmgr.conf`` following the standard directory structure of a RHEL system. It should contain:: cluster=test node=1 node_name=earth conninfo='host=node1 user=repmgr dbname=pgbench' On "node2" create the file ``/var/lib/pgsql/repmgr/repmgr.conf`` with:: cluster=test node=2 node_name=mars conninfo='host=node2 user=repmgr dbname=pgbench' The STANDBY CLONE process should have created a recovery.conf file on "node2" in the $PGDATA directory that reads as follows:: standby_mode = 'on' primary_conninfo = 'host=node1 port=5432' Registering the master and standby ---------------------------------- First, register the master by typing on "node1":: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf --verbose master register Then start the "standby" server. You could now register the standby by typing on "node2":: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf --verbose standby register However, you can instead start repmgrd:: repmgrd -f /var/lib/pgsql/repmgr/repmgr.conf --verbose > /var/lib/pgsql/repmgr/repmgr.log 2>&1 Which will automatically register your standby system. And eventually you need repmgrd running anyway, to save lag monitoring information. repmgrd will log the deamon activity to the listed file. You can watch what it is doing with:: tail -f /var/lib/pgsql/repmgr/repmgr.log Hit control-C to exit this tail command when you are done. Monitoring and testing ---------------------- At this point, you have a functioning primary on "node1" and a functioning standby server running on "node2". You can confirm the master knows about the standby, and that it is keeping it current, by looking at ``repl_status``:: postgres@node2 $ psql -x -d pgbench -c "SELECT * FROM repmgr_test.repl_status" -[ RECORD 1 ]-------------+------------------------------ primary_node | 1 standby_node | 2 last_monitor_time | 2011-02-23 08:19:39.791974-05 last_wal_primary_location | 0/1902D5E0 last_wal_standby_location | 0/1902D5E0 replication_lag | 0 bytes apply_lag | 0 bytes time_lag | 00:26:13.30293 Some tests you might do at this point include: * Insert some records into the primary server here, confirm they appear very quickly (within milliseconds) on the standby, and that the repl_status view advances accordingly. * Verify that you can run queries against the standby server, but cannot make insertions into the standby database. Simulating the failure of the primary server -------------------------------------------- To simulate the loss of the primary server, simply stop the "node1" server. At this point, the standby contains the database as it existed at the time of the "failure" of the primary server. If looking at ``repl_status`` on "node2", you should see the time_lag value increase the longer "node1" is down. Promoting the Standby to be the Primary --------------------------------------- Now you can promote the standby server to be the primary, to allow applications to read and write to the database again, by typing:: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf --verbose standby promote The server restarts and now has read/write ability. Bringing the former Primary up as a Standby ------------------------------------------- To make the former primary act as a standby, which is necessary before restoring the original roles, type the following on node1:: repmgr -D $PGDATA -d pgbench -p 5432 -U repmgr -R postgres --verbose --force standby clone node2 Then start the "node1" server, which is now acting as a standby server. Check Make sure the record(s) inserted the earlier step are still available on the now standby (prime). Confirm the database on "node1" is read-only. Restoring the original roles of prime to primary and standby to standby ----------------------------------------------------------------------- Now restore to the original configuration by stopping "node2" (now acting as a primary), promoting "node1" again to be the primary server, then bringing up "node2" as a standby with a valid ``recovery.conf`` file. Stop the "node2" server:: repmgr -f /var/lib/pgsql/repmgr/repmgr.conf standby promote Now the original primary, "node1" is acting again as primary. Start the "node2" server and type this on "node1":: repmgr standby clone --force -h node2 -p 5432 -U postgres -R postgres --verbose Verify the roles have reversed by attempting to insert a record on "node" and on "node1". The servers are now again acting as primary on "node1" and standby on "node2". Alternate setup: both servers on one host ========================================== Another test setup assumes you might be using the default installation of PostgreSQL on port 5432 for some other purpose, and instead relocates these instances onto different ports running as different users. In places where ``127.0.0.1`` is used as a host name, a more traditional configuration would instead use the name of the relevant host for that parameter. You can usually leave out changes to the port number in this case too. * A primary (master) server called "prime," with a user as "prime," who is also the owner of the files. This server is operating on port 5433. This server will be known as "node1" in the cluster "test" * A standby server called "standby", with a user of "standby", who is the owner of the files. This server is operating on port 5434. This server will be known and "node2" on the cluster "test." * A database exists on "prime" called "testdb." * The Postgress installation in each of the above is defined as $PGDATA, which is represented here with ``/data/prime`` as the "prime" server and ``/data/standby`` as the "standby" server. You might setup such an installation by adjusting the login script for the "prime" and "standby" users as in these two examples:: # prime PGDATA=/data/prime PGENGINE=/usr/pgsql-9.0/bin PGPORT=5433 export PGDATA PGENGINE PGPORT PATH="$PATH:$PGENGINE" # standby PGDATA=/data/standby PGENGINE=/usr/pgsql-9.0/bin PGPORT=5434 export PGDATA PGENGINE PGPORT PATH="$PATH:$PGENGINE" And then starting/stopping each installation as needed using the ``pg_ctl`` utility. Note: naming your nodes based on their starting role is not a recommended best practice! As you'll see in this example, once there is a failover, names strongly associated with one particular role (primary or standby) can become confusing, once that node no longer has that role. Future versions of this walkthrough are expected to use more generic terminology for these names. Clearing the PostgreSQL installation on the Standby --------------------------------------------------- Setup a streaming replica, strip away any PostgreSQL installation on the existing replica: * Stop both servers. * Go to "standby" database directory and remove the PostgreSQL installation:: cd $PGDATA rm -rf * This will delete the entire database installation in ``/data/standby``. Building the standby -------------------- Create a directory to store each repmgr configuration in for each node. In that, there needs to be a ``repmgr.conf`` file for each node in the cluster. For "prime" we'll assume this is stored in ``/home/prime/repmgr`` and it should contain:: cluster=test node=1 node_name=earth conninfo='host=127.0.0.1 dbname=testdb' On "standby" create the file ``/home/standby/repmgr/repmgr.conf`` with:: cluster=test node=2 node_name=mars conninfo='host=127.0.0.1 dbname=testdb' Next, with "prime" server running, we want to use the ``clone standby`` command in repmgr to copy over the entire PostgreSQL database cluster onto the "standby" server. On the "standby" server, type:: repmgr -D $PGDATA -p 5433 -U prime -R prime --verbose standby clone localhost Next, we need a recovery.conf file on "standby" in the $PGDATA directory that reads as follows:: standby_mode = 'on' primary_conninfo = 'host=127.0.0.1 port=5433' Make sure that standby has a qualifying role in the database, "testdb" in this case, and can login. Start ``psql`` on the testdb database on "prime" and at the testdb# prompt type:: CREATE ROLE standby SUPERUSER LOGIN Registering the master and standby ---------------------------------- First, register the master by typing on "prime":: repmgr -f /home/prime/repmgr/repmgr.conf --verbose master register On "standby," edit the ``postgresql.conf`` file and change the port to 5434. Start the "standby" server. Register the standby by typing on "standby":: repmgr -f /home/standby/repmgr/repmgr.conf --verbose standby register At this point, you have a functioning primary on "prime" and a functioning standby server running on "standby." You can confirm the master knows about the standby, and that it is keeping it current, by running the following on the master:: psql -x -d pgbench -c "SELECT * FROM repmgr_test.repl_status" Some tests you might do at this point include: * Insert some records into the primary server here, confirm they appear very quickly (within milliseconds) on the standby, and that the repl_status view advances accordingly. * Verify that you can run queries against the standby server, but cannot make insertions into the standby database. Simulating the failure of the primary server -------------------------------------------- To simulate the loss of the primary server, simply stop the "prime" server. At this point, the standby contains the database as it existed at the time of the "failure" of the primary server. Promoting the Standby to be the Primary --------------------------------------- Now you can promote the standby server to be the primary, to allow applications to read and write to the database again, by typing:: repmgr -f /home/standby/repmgr/repmgr.conf --verbose standby promote The server restarts and now has read/write ability. Bringing the former Primary up as a Standby ------------------------------------------- To make the former primary act as a standby, which is necessary before restoring the original roles, type:: repmgr -U standby -R prime -h 127.0.0.1 -p 5433 -d testdb --force --verbose standby clone Stop and restart the "prime" server, which is now acting as a standby server. Make sure the record(s) inserted the earlier step are still available on the now standby (prime). Confirm the database on "prime" is read-only. Restoring the original roles of prime to primary and standby to standby ----------------------------------------------------------------------- Now restore to the original configuration by stopping the "standby" (now acting as a primary), promoting "prime" again to be the primary server, then bringing up "standby" as a standby with a valid ``recovery.conf`` file on "standby". Stop the "standby" server:: repmgr -f /home/prime/repmgr/repmgr.conf standby promote Now the original primary, "prime" is acting again as primary. Start the "standby" server and type this on "prime":: repmgr standby clone --force -h 127.0.0.1 -p 5434 -U prime -R standby --verbose Stop the "standby" and change the port to be 5434 in the ``postgresql.conf`` file. Verify the roles have reversed by attempting to insert a record on "standby" and on "prime." The servers are now again acting as primary on "prime" and standby on "standby". Maintainance of monitor history ------------------------------- Once you have changed roles (with a failover or to restore original roles) you would end up with records saying that node1 is primary and other records saying that node2 is the primary. Which could be confusing. Also, if you don't do anything about it the monitor history will keep growing. For both of those reasons you sometime want to make some maintainance of the ``repl_monitor`` table. If you want to clean the history after a few days you can execute the CLUSTER CLEANUP command in a cron. For example to keep just one day of history you can put this in your crontab:: 0 1 * * * repmgr cluster cleanup -k 1 -f ~/repmgr.conf Configuration and command reference =================================== Configuration File ------------------ ``repmgr.conf`` is looked for in the directory repmgrd or repmgr exists in. The configuration file should have 3 lines: 1. cluster: A string (single quoted) that identify the cluster we are on 2. node: An integer that identify our node in the cluster 3. conninfo: A string (single quoted) specifying how we can connect to this node's PostgreSQL service repmgr ------ Command line syntax ~~~~~~~~~~~~~~~~~~~ The current supported syntax for the program can be seen using:: repmgr --help The output from this program looks like this:: repmgr: Replicator manager Usage: repmgr [OPTIONS] master {register} repmgr [OPTIONS] standby {register|clone|promote|follow} General options: --help show this help, then exit --version output version information, then exit --verbose output verbose activity information Connection options: -d, --dbname=DBNAME database to connect to -h, --host=HOSTNAME database server host or socket directory -p, --port=PORT database server port -U, --username=USERNAME database user name to connect as Configuration options: -D, --data-dir=DIR local directory where the files will be copied to -f, --config_file=PATH path to the configuration file -R, --remote-user=USERNAME database server username for rsync -w, --wal-keep-segments=VALUE minimum value for the GUC wal_keep_segments (default: 5000) -I, --ignore-rsync-warning ignore rsync partial transfer warning -F, --force force potentially dangerous operations to happen repmgr performs some tasks like clone a node, promote it or making follow another node and then exits. COMMANDS: master register - registers the master in a cluster standby register - registers a standby in a cluster standby clone [node] - allows creation of a new standby standby promote - allows manual promotion of a specific standby into a new master in the event of a failover standby follow - allows the standby to re-point itself to a new master The ``--verbose`` option can be useful in troubleshooting issues with the program. repmgr commands --------------- Not all of these commands need the ``repmgr.conf`` file, but they need to be able to connect to the remote and local databases. You can teach it which is the remote database by using the -h parameter or as a last parameter in standby clone and standby follow. If you need to specify a port different then the default 5432 you can specify a -p parameter. Standby is always considered as localhost and a second -p parameter will indicate its port if is different from the default one. * master register * Registers a master in a cluster, it needs to be executed before any standby nodes are registered * standby register * Registers a standby in a cluster, it needs to be executed before repmgrd will function on the node. * standby clone [node to be cloned] * Does a backup via ``rsync`` of the data directory of the primary. And it creates the recovery file we need to start a new hot standby server. It doesn't need the ``repmgr.conf`` so it can be executed anywhere on the new node. You can change to the directory you want the new database cluster at and execute:: ./repmgr standby clone node1 or run from wherever you are with a full path:: ./repmgr -D /path/to/new/data/directory standby clone node1 That will make a backup of the primary then you only need to start the server using a command like:: pg_ctl -D /your_data_directory_path start Note that some installations will also redirect the output log file when executing ``pg_ctl``; check the server startup script you are using and try to match what it does. * standby promote * Allows manual promotion of a specific standby into a new primary in the event of a failover. This needs to be executed on the same directory where the ``repmgr.conf`` is in the standby, or you can use the ``-f`` option to indicate where the ``repmgr.conf`` is at. It doesn't need any additional arguments:: ./repmgr standby promote That will restart your standby postgresql service. * standby follow * Allows the standby to base itself to the new primary passed as a parameter. This needs to be executed on the same directory where the ``repmgr.conf`` is in the standby, or you can use the ``-f`` option to indicate where the ``repmgr.conf`` is at. Example:: ./repmgr standby follow * cluster show * Shows the role (standby/master) and connection string for all nodes configured in the cluster or "FAILED" if the node doesn't respond. This allow us to know which nodes are alive and which one needs attention and to have a notion of the structure of clusters we just have access to. Example:: ./repmgr cluster show * cluster cleanup * Cleans the monitor's history from repmgr tables. This avoids the repl_monitor table to grow excesivelly which in turns affects repl_status view performance, also keeps controlled the space in disk used by repmgr. This command can be used manually or in a cron to make it periodically. There is also a --keep-history (-k) option to indicate how many days of history we want to keep, so the command will clean up history older than "keep-history" days. Example:: ./repmgr cluster cleanup -k 2 repmgrd Daemon -------------- Command line syntax ~~~~~~~~~~~~~~~~~~~ The current supported syntax for the program can be seen using:: repmgrd --help The output from this program looks like this:: repmgrd: Replicator manager daemon Usage: repmgrd [OPTIONS] Options: --help show this help, then exit --version output version information, then exit --verbose output verbose activity information --monitoring-history track advance or lag of the replication in every standby in repl_monitor -f, --config_file=PATH database to connect to repmgrd monitors a cluster of servers. The ``--verbose`` option can be useful in troubleshooting issues with the program. Usage ----- repmgrd reads the ``repmgr.conf`` file in current directory, or as indicated with -f parameter. If run on a standby, it checks if that standby is in ``repl_nodes`` and adds it if not. Before you can run repmgrd you need to register a master in a cluster using the ``MASTER REGISTER`` command. If run on a master, repmgrd will exit, as it has nothing to do on them yet. It is only targeted at running on standby servers currently. If converting a former master into a standby, you will need to start repmgrd in order to make it fully operational in its new role. The repmgr daemon creates 2 connections: one to the master and another to the standby. Lag monitoring -------------- repmgrd helps monitor a set of master and standby servers. You can see which node is the current master, as well as how far behind each is from current. To activate the monitor capabilities of repmgr you must include the option --monitoring-history when running it:: repmgrd --monitoring-history --config-file=/path/to/repmgr.conf & To look at the current lag between primary and each node listed in ``repl_node``, consult the ``repl_status`` view:: psql -d postgres -c "SELECT * FROM repmgr_test.repl_status" This view shows the latest monitor info from every node. * replication_lag: in bytes. This is how far the latest xlog record we have received is from master. * apply_lag: in bytes. This is how far the latest xlog record we have applied is from the latest record we have received. * time_lag: in seconds. How many seconds behind the master is this node. Error codes ----------- When the repmgr or repmgrd program exits, it will set one of the following * SUCCESS 0: Program ran successfully. * ERR_BAD_CONFIG 1: One of the configuration checks the program makes failed. * ERR_BAD_RSYNC 2: An rsync call made by the program returned an error. * ERR_STOP_BACKUP 3: A ``pg_stop_backup()`` call made by the program didn't succeed. * ERR_NO_RESTART 4: An attempt to restart a PostgreSQL instance failed. * ERR_NEEDS_XLOG 5: Could note create the ``pg_xlog`` directory when cloning. * ERR_DB_CON 6: Error when trying to connect to a database. * ERR_DB_QUERY 7: Error executing a database query. * ERR_PROMOTED 8: Exiting program because the node has been promoted to master. * ERR_BAD_PASSWORD 9: Password used to connect to a database was rejected. License and Contributions ========================= repmgr is licensed under the GPL v3. All of its code and documentation is Copyright 2010-2012, 2ndQuadrant Limited. See the files COPYRIGHT and LICENSE for details. Main sponsorship of repmgr has been from 2ndQuadrant customers. Additional work has been sponsored by the 4CaaST project for cloud computing, which has received funding from the European Union's Seventh Framework Programme (FP7/2007-2013) under grant agreement 258862. Contributions to repmgr are welcome, and will be listed in the file CREDITS. 2ndQuadrant Limited requires that any contributions provide a copyright assignment and a disclaimer of any work-for-hire ownership claims from the employer of the developer. This lets us make sure that all of the repmgr distribution remains free code. Please contact info@2ndQuadrant.com for a copy of the relevant Copyright Assignment Form. Code style ---------- Code in repmgr is formatted to a consistent style using the following command:: astyle --style=ansi --indent=tab --suffix=none *.c *.h Contributors should reformat their code similarly before submitting code to the project, in order to minimize merge conflicts with other work. Support and Assistance ====================== 2ndQuadrant provides 24x7 production support for repmgr, as well as help you configure it correctly, verify an installation and train you in running a robust replication cluster. There is a mailing list/forum to discuss contributions or issues http://groups.google.com/group/repmgr #repmgr is registered in freenode IRC Further information is available at http://www.repmgr.org/ We'd love to hear from you about how you use repmgr. Case studies and news are always welcome. Send us an email at info@2ndQuadrant.com, or send a postcard to repmgr c/o 2ndQuadrant 7200 The Quorum Oxford Business Park North Oxford OX4 2JZ Thanks from the repmgr core team Jaime Casanova Simon Riggs Greg Smith Cedric Villemain repmgr-2.0beta2/TODO000066400000000000000000000015661225461504400142700ustar00rootroot00000000000000Known issues in repmgr ====================== * The check for whether ``wal_keep_segments`` is considered large enough does a string comparison rather than an integer one. It can give both false positive (setting is large enough but flagged as too small) and false negative (setting is too small but not noted as such) errors. * When running repmgr against a remote machine, operations that start the database server using the ``pg_ctl`` command may accidentally terminate after their associated ssh session ends. * After running repmgrd as a regular foreground application, hitting control-C causes the program to crash. Planned feature improvements ============================ * Before running ``pg_start_backup()``, a sanity check that there is a a working ssh connection to the destination would help find configuration errors before disturbing the database. repmgr-2.0beta2/autofailover_quick_setup.rst000066400000000000000000000162631225461504400214460ustar00rootroot00000000000000===================================================== PostgreSQL Automatic Fail-Over - User Documentation ===================================================== Automatic Failover ================== repmgr allows setups for automatic failover when it detects the failure of the master node. Following is a quick setup for this. Installation ============ For convenience, we define: * node1 is the hostname fully qualified of the Master server, IP 192.168.1.10 * node2 is the hostname fully qualified of the Standby server, IP 192.168.1.11 * witness is the hostname fully qualified of the server used for witness, IP 192.168.1.12 :Note: It is not recommanded to use name defining status of a server like «masterserver», this is a name leading to confusion once a failover take place and the Master is now on the «standbyserver». Summary ------- 2 PostgreSQL servers are involved in the replication. Automatic fail-over need to vote to decide what server it should promote, thus an odd number is required and a witness-repmgrd is installed in a third server where it uses a PostgreSQL cluster to communicate with other repmgrd daemons. 1. Install PostgreSQL in all the servers involved (including the server used for witness) 2. Install repmgr in all the servers involved (including the server used for witness) 3. Configure the Master PostreSQL 4. Clone the Master to the Standby using "repmgr standby clone" command 5. Configure repmgr in all the servers involved (including the server used for witness) 6. Register Master and Standby nodes 7. Initiate witness server 8. Start the repmgrd daemons in all nodes :Note: A complete Hight-Availability design need at least 3 servers to still have a backup node after a first failure. Install PostgreSQL ------------------ You can install PostgreSQL using any of the recommended methods. You should ensure it's 9.0 or superior. Install repmgr -------------- Install repmgr following the steps in the README. Configure PostreSQL ------------------- Log in node1. Edit the file postgresql.conf and modify the parameters:: listen_addresses='*' wal_level = 'hot_standby' archive_mode = on archive_command = 'cd .' # we can also use exit 0, anything that # just does nothing max_wal_senders = 10 wal_keep_segments = 5000 # 80 GB required on pg_xlog hot_standby = on shared_preload_libraries = 'repmgr_funcs' Edit the file pg_hba.conf and add lines for the replication:: host repmgr repmgr 127.0.0.1/32 trust host repmgr repmgr 192.168.1.10/30 trust host replication all 192.168.1.10/30 trust :Note: It is also possible to use a password authentication (md5), .pgpass file should be edited to allow connection between each node. Create the user and database to manage replication:: su - postgres createuser -s repmgr createdb -O repmgr repmgr psql -f /usr/share/postgresql/9.0/contrib/repmgr_funcs.sql repmgr Restart the PostgreSQL server:: pg_ctl -D $PGDATA restart And check everything is fine in the server log. Create the ssh-key for the postgres user and copy it to other servers:: su - postgres ssh-keygen # /!\ do not use a passphrase /!\ cat ~/.ssh/id_rsa.pub > ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys exit rsync -avz ~postgres/.ssh/authorized_keys node2:~postgres/.ssh/ rsync -avz ~postgres/.ssh/authorized_keys witness:~postgres/.ssh/ rsync -avz ~postgres/.ssh/id_rsa* node2:~postgres/.ssh/ rsync -avz ~postgres/.ssh/id_rsa* witness:~postgres/.ssh/ Clone Master ------------ Log in node2. Clone the node1 (the current Master):: su - postgres repmgr -d repmgr -U repmgr -h node1 standby clone Start the PostgreSQL server:: pg_ctl -D $PGDATA start And check everything is fine in the server log. Configure repmgr ---------------- Log in each server and configure repmgr by editing the file /etc/repmgr/repmgr.conf:: cluster=my_cluster node=1 node_name=earth conninfo='host=192.168.1.10 dbname=repmgr user=repmgr' master_response_timeout=60 reconnect_attempts=6 reconnect_interval=10 failover=automatic promote_command='promote_command.sh' follow_command='repmgr standby follow -f /etc/repmgr/repmgr.conf' * *cluster* is the name of the current replication. * *node* is the number of the current node (1, 2 or 3 in the current example). * *node_name* is an identifier for every node. * *conninfo* is used to connect to the local PostgreSQL server (where the configuration file is) from any node. In the witness server configuration it is needed to add a 'port=5499' to the conninfo. * *master_response_timeout* is the maximum amount of time we are going to wait before deciding the master has died and start failover procedure. * *reconnect_attempts* is the number of times we will try to reconnect to master after a failure has been detected and before start failover procedure. * *reconnect_interval* is the amount of time between retries to reconnect to master after a failure has been detected and before start failover procedure. * *failover* configure behavior : *manual* or *automatic*. * *promote_command* the command executed to do the failover (including the PostgreSQL failover itself). The command must return 0 on success. * *follow_command* the command executed to address the current standby to another Master. The command must return 0 on success. Register Master and Standby --------------------------- Log in node1. Register the node as Master:: su - postgres repmgr -f /etc/repmgr/repmgr.conf master register Log in node2. Register the node as Standby:: su - postgres repmgr -f /etc/repmgr/repmgr.conf standby register Initialize witness server ------------------------- Log in witness. Initialize the witness server:: su - postgres repmgr -d repmgr -U repmgr -h 192.168.1.10 -D $WITNESS_PGDATA -f /etc/repmgr/repmgr.conf witness create It needs information to connect to the master to copy the configuration of the cluster, also it needs to know where it should initialize it's own $PGDATA. As part of the procees it also ask for the superuser password so it can connect when needed. Start the repmgrd daemons ------------------------- Log in node2 and witness. su - postgres repmgrd -f /etc/repmgr/repmgr.conf > /var/log/postgresql/repmgr.log 2>&1 :Note: The Master does not need a repmgrd daemon. Suspend Automatic behavior ========================== Edit the repmgr.conf of the node to remove from automatic processing and change:: failover=manual Then, signal repmgrd daemon:: su - postgres kill -HUP `pidoff repmgrd` TODO : -HUP configuration update is not implemented and it should check its configuration file against its configuration in DB, updating accordingly the SQL conf (especialy the failover manual or auto) this allow witness-standby and standby-not-promotable features and simpler usage of the tool ;) Usage ===== The repmgr documentation is in the README file (how to build, options, etc.) repmgr-2.0beta2/check_dir.c000066400000000000000000000145321225461504400156540ustar00rootroot00000000000000/* * check_dir.c - Directories management functions * Copyright (C) 2ndQuadrant, 2010-2012 * * 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 . * */ #include #include #include #include #include #include /* NB: postgres_fe must be included BEFORE check_dir */ #include "postgres_fe.h" #include "check_dir.h" #include "strutil.h" #include "log.h" /* * make sure the directory either doesn't exist or is empty * we use this function to check the new data directory and * the directories for tablespaces * * This is the same check initdb does on the new PGDATA dir * * Returns 0 if nonexistent, 1 if exists and empty, 2 if not empty, * or -1 if trouble accessing directory */ int check_dir(char *dir) { DIR *chkdir; struct dirent *file; int result = 1; errno = 0; chkdir = opendir(dir); if (!chkdir) return (errno == ENOENT) ? 0 : -1; while ((file = readdir(chkdir)) != NULL) { if (strcmp(".", file->d_name) == 0 || strcmp("..", file->d_name) == 0) { /* skip this and parent directory */ continue; } else { result = 2; /* not empty */ break; } } #ifdef WIN32 /* * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in * released version */ if (GetLastError() == ERROR_NO_MORE_FILES) errno = 0; #endif closedir(chkdir); if (errno != 0) return -1; /* some kind of I/O error? */ return result; } /* * Create directory */ bool create_directory(char *dir) { if (mkdir_p(dir, 0700) == 0) return true; log_err(_("Could not create directory \"%s\": %s\n"), dir, strerror(errno)); return false; } bool set_directory_permissions(char *dir) { return (chmod(dir, 0700) != 0) ? false : true; } /* function from initdb.c */ /* source adapted from FreeBSD /src/bin/mkdir/mkdir.c */ /* * this tries to build all the elements of a path to a directory a la mkdir -p * we assume the path is in canonical form, i.e. uses / as the separator * we also assume it isn't null. * * note that on failure, the path arg has been modified to show the particular * directory level we had problems with. */ int mkdir_p(char *path, mode_t omode) { struct stat sb; mode_t numask, oumask; int first, last, retval; char *p; p = path; oumask = 0; retval = 0; #ifdef WIN32 /* skip network and drive specifiers for win32 */ if (strlen(p) >= 2) { if (p[0] == '/' && p[1] == '/') { /* network drive */ p = strstr(p + 2, "/"); if (p == NULL) return 1; } else if (p[1] == ':' && ((p[0] >= 'a' && p[0] <= 'z') || (p[0] >= 'A' && p[0] <= 'Z'))) { /* local drive */ p += 2; } } #endif if (p[0] == '/') /* Skip leading '/'. */ ++p; for (first = 1, last = 0; !last; ++p) { if (p[0] == '\0') last = 1; else if (p[0] != '/') continue; *p = '\0'; if (!last && p[1] == '\0') last = 1; if (first) { /* * POSIX 1003.2: For each dir operand that does not name an * existing directory, effects equivalent to those caused by the * following command shall occcur: * * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode] * dir * * We change the user's umask and then restore it, instead of * doing chmod's. */ oumask = umask(0); numask = oumask & ~(S_IWUSR | S_IXUSR); (void) umask(numask); first = 0; } if (last) (void) umask(oumask); /* check for pre-existing directory; ok if it's a parent */ if (stat(path, &sb) == 0) { if (!S_ISDIR(sb.st_mode)) { if (last) errno = EEXIST; else errno = ENOTDIR; retval = 1; break; } } else if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0) { retval = 1; break; } if (!last) *p = '/'; } if (!first && !last) (void) umask(oumask); return retval; } bool is_pg_dir(char *dir) { const size_t buf_sz = 8192; char path[buf_sz]; struct stat sb; int r; // test pgdata xsnprintf(path, buf_sz, "%s/PG_VERSION", dir); if (stat(path, &sb) == 0) return true; // test tablespace dir sprintf(path, "ls %s/PG_*/ -I*", dir); r = system(path); if (r == 0) return true; return false; } bool create_pgdir(char *dir, bool force) { bool pg_dir = false; /* Check this directory could be used as a PGDATA dir */ switch (check_dir(dir)) { case 0: /* dir not there, must create it */ log_info(_("creating directory \"%s\"...\n"), dir); if (!create_directory(dir)) { log_err(_("couldn't create directory \"%s\"...\n"), dir); exit(ERR_BAD_CONFIG); } break; case 1: /* Present but empty, fix permissions and use it */ log_info(_("checking and correcting permissions on existing directory %s ...\n"), dir); if (!set_directory_permissions(dir)) { log_err(_("could not change permissions of directory \"%s\": %s\n"), dir, strerror(errno)); exit(ERR_BAD_CONFIG); } break; case 2: /* Present and not empty */ log_warning(_("directory \"%s\" exists but is not empty\n"), dir); pg_dir = is_pg_dir(dir); /* * we use force to reduce the time needed to restore a node which * turn async after a failover or anything else */ if (pg_dir && force) { /* Let it continue */ break; } else if (pg_dir && !force) { log_warning(_("\nThis looks like a PostgreSQL directory.\n" "If you are sure you want to clone here, " "please check there is no PostgreSQL server " "running and use the --force option\n")); exit(ERR_BAD_CONFIG); } return false; default: /* Trouble accessing directory */ log_err(_("could not access directory \"%s\": %s\n"), dir, strerror(errno)); exit(ERR_BAD_CONFIG); } return true; } repmgr-2.0beta2/check_dir.h000066400000000000000000000017421225461504400156600ustar00rootroot00000000000000/* * check_dir.h * Copyright (c) 2ndQuadrant, 2010-2012 * * 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 . * */ #ifndef _REPMGR_CHECK_DIR_H_ #define _REPMGR_CHECK_DIR_H_ int mkdir_p(char *path, mode_t omode); int check_dir(char *dir); bool create_directory(char *dir); bool set_directory_permissions(char *dir); bool is_pg_dir(char *dir); bool create_pgdir(char *dir, bool force); #endif repmgr-2.0beta2/config.c000066400000000000000000000213601225461504400152030ustar00rootroot00000000000000/* * config.c - Functions to parse the config file * Copyright (C) 2ndQuadrant, 2010-2012 * * 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 . * */ #include "config.h" #include "log.h" #include "strutil.h" #include "repmgr.h" void parse_config(const char *config_file, t_configuration_options *options) { char *s, buff[MAXLINELENGTH]; char name[MAXLEN]; char value[MAXLEN]; FILE *fp = fopen (config_file, "r"); /* Initialize */ memset(options->cluster_name, 0, sizeof(options->cluster_name)); options->node = -1; memset(options->conninfo, 0, sizeof(options->conninfo)); options->failover = MANUAL_FAILOVER; options->priority = 0; memset(options->node_name, 0, sizeof(options->node_name)); memset(options->promote_command, 0, sizeof(options->promote_command)); memset(options->follow_command, 0, sizeof(options->follow_command)); memset(options->rsync_options, 0, sizeof(options->rsync_options)); memset(options->ssh_options, 0, sizeof(options->ssh_options)); /* if nothing has been provided defaults to 60 */ options->master_response_timeout = 60; /* it defaults to 6 retries with a time between retries of 10s */ options->reconnect_attempts = 6; options->reconnect_intvl = 10; /* * Since some commands don't require a config file at all, not * having one isn't necessarily a problem. */ if (fp == NULL) { log_err(_("Did not find the configuration file '%s', continuing\n"), config_file); return; } /* Read next line */ while ((s = fgets (buff, sizeof buff, fp)) != NULL) { /* Skip blank lines and comments */ if (buff[0] == '\n' || buff[0] == '#') continue; /* Parse name/value pair from line */ parse_line(buff, name, value); /* Copy into correct entry in parameters struct */ if (strcmp(name, "cluster") == 0) strncpy (options->cluster_name, value, MAXLEN); else if (strcmp(name, "node") == 0) options->node = atoi(value); else if (strcmp(name, "conninfo") == 0) strncpy (options->conninfo, value, MAXLEN); else if (strcmp(name, "rsync_options") == 0) strncpy (options->rsync_options, value, QUERY_STR_LEN); else if (strcmp(name, "ssh_options") == 0) strncpy (options->ssh_options, value, QUERY_STR_LEN); else if (strcmp(name, "loglevel") == 0) strncpy (options->loglevel, value, MAXLEN); else if (strcmp(name, "logfacility") == 0) strncpy (options->logfacility, value, MAXLEN); else if (strcmp(name, "failover") == 0) { char failoverstr[MAXLEN]; strncpy(failoverstr, value, MAXLEN); if (strcmp(failoverstr, "manual") == 0) options->failover = MANUAL_FAILOVER; else if (strcmp(failoverstr, "automatic") == 0) options->failover = AUTOMATIC_FAILOVER; else { log_warning(_("value for failover option is incorrect, it should be automatic or manual. Defaulting to manual.\n")); options->failover = MANUAL_FAILOVER; } } else if (strcmp(name, "priority") == 0) options->priority = atoi(value); else if (strcmp(name, "node_name") == 0) strncpy(options->node_name, value, MAXLEN); else if (strcmp(name, "promote_command") == 0) strncpy(options->promote_command, value, MAXLEN); else if (strcmp(name, "follow_command") == 0) strncpy(options->follow_command, value, MAXLEN); else if (strcmp(name, "master_response_timeout") == 0) options->master_response_timeout = atoi(value); else if (strcmp(name, "reconnect_attempts") == 0) options->reconnect_attempts = atoi(value); else if (strcmp(name, "reconnect_interval") == 0) options->reconnect_intvl = atoi(value); else log_warning(_("%s/%s: Unknown name/value pair!\n"), name, value); } /* Close file */ fclose (fp); /* Check config settings */ if (strnlen(options->cluster_name, MAXLEN)==0) { log_err(_("Cluster name is missing. Check the configuration file.\n")); exit(ERR_BAD_CONFIG); } if (options->node == -1) { log_err(_("Node information is missing. Check the configuration file.\n")); exit(ERR_BAD_CONFIG); } if (options->master_response_timeout <= 0) { log_err(_("Master response timeout must be greater than zero. Check the configuration file.\n")); exit(ERR_BAD_CONFIG); } if (options->reconnect_attempts < 0) { log_err(_("Reconnect attempts must be zero or greater. Check the configuration file.\n")); exit(ERR_BAD_CONFIG); } if (options->reconnect_intvl <= 0) { log_err(_("Reconnect intervals must be zero or greater. Check the configuration file.\n")); exit(ERR_BAD_CONFIG); } } char * trim (char *s) { /* Initialize start, end pointers */ char *s1 = s, *s2 = &s[strlen (s) - 1]; /* Trim and delimit right side */ while ( (isspace (*s2)) && (s2 >= s1) ) --s2; *(s2+1) = '\0'; /* Trim left side */ while ( (isspace (*s1)) && (s1 < s2) ) ++s1; /* Copy finished string */ strcpy (s, s1); return s; } void parse_line(char *buff, char *name, char *value) { int i = 0; int j = 0; /* * first we find the name of the parameter */ for ( ; i < MAXLEN; ++i) { if (buff[i] != '=') name[j++] = buff[i]; else break; } name[j] = '\0'; /* * Now the value */ j = 0; for ( ++i ; i < MAXLEN; ++i) if (buff[i] == '\'') continue; else if (buff[i] != '\n') value[j++] = buff[i]; else break; value[j] = '\0'; trim(value); } bool reload_configuration(char *config_file, t_configuration_options *orig_options) { PGconn *conn; t_configuration_options new_options; /* * Re-read the configuration file: repmgr.conf */ log_info(_("Reloading configuration file and updating repmgr tables\n")); parse_config(config_file, &new_options); if (new_options.node == -1) { log_warning(_("\nCannot load new configuration, will keep current one.\n")); return false; } if (strcmp(new_options.cluster_name, orig_options->cluster_name) != 0) { log_warning(_("\nCannot change cluster name, will keep current configuration.\n")); return false; } if (new_options.node != orig_options->node) { log_warning(_("\nCannot change node number, will keep current configuration.\n")); return false; } if (new_options.node_name != orig_options->node_name) { log_warning(_("\nCannot change standby name, will keep current configuration.\n")); return false; } if (new_options.failover != MANUAL_FAILOVER && new_options.failover != AUTOMATIC_FAILOVER) { log_warning(_("\nNew value for failover is not valid. Should be MANUAL or AUTOMATIC.\n")); return false; } if (new_options.master_response_timeout <= 0) { log_warning(_("\nNew value for master_response_timeout is not valid. Should be greater than zero.\n")); return false; } if (new_options.reconnect_attempts < 0) { log_warning(_("\nNew value for reconnect_attempts is not valid. Should be greater or equal than zero.\n")); return false; } if (new_options.reconnect_intvl < 0) { log_warning(_("\nNew value for reconnect_interval is not valid. Should be greater or equal than zero.\n")); return false; } /* Test conninfo string */ conn = establishDBConnection(new_options.conninfo, false); if (!conn || (PQstatus(conn) != CONNECTION_OK)) { log_warning(_("\nconninfo string is not valid, will keep current configuration.\n")); return false; } PQfinish(conn); /* Configuration seems ok, will load new values */ strcpy(orig_options->cluster_name, new_options.cluster_name); orig_options->node = new_options.node; strcpy(orig_options->conninfo, new_options.conninfo); orig_options->failover = new_options.failover; orig_options->priority = new_options.priority; strcpy(orig_options->node_name, new_options.node_name); strcpy(orig_options->promote_command, new_options.promote_command); strcpy(orig_options->follow_command, new_options.follow_command); strcpy(orig_options->rsync_options, new_options.rsync_options); strcpy(orig_options->ssh_options, new_options.ssh_options); orig_options->master_response_timeout = new_options.master_response_timeout; orig_options->reconnect_attempts = new_options.reconnect_attempts; orig_options->reconnect_intvl = new_options.reconnect_intvl; /* * XXX These ones can change with a simple SIGHUP? strcpy (orig_options->loglevel, new_options.loglevel); strcpy (orig_options->logfacility, new_options.logfacility); logger_shutdown(); XXX do we have progname here ? logger_init(progname, orig_options.loglevel, orig_options.logfacility); */ return true; } repmgr-2.0beta2/config.h000066400000000000000000000027061225461504400152130ustar00rootroot00000000000000/* * config.h * Copyright (c) 2ndQuadrant, 2010-2012 * * 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 . * */ #ifndef _REPMGR_CONFIG_H_ #define _REPMGR_CONFIG_H_ #include "repmgr.h" #include "strutil.h" typedef struct { char cluster_name[MAXLEN]; int node; char conninfo[MAXLEN]; int failover; int priority; char node_name[MAXLEN]; char promote_command[MAXLEN]; char follow_command[MAXLEN]; char loglevel[MAXLEN]; char logfacility[MAXLEN]; char rsync_options[QUERY_STR_LEN]; char ssh_options[QUERY_STR_LEN]; int master_response_timeout; int reconnect_attempts; int reconnect_intvl; } t_configuration_options; void parse_config(const char *config_file, t_configuration_options *options); void parse_line(char *buff, char *name, char *value); char *trim(char *s); bool reload_configuration(char *config_file, t_configuration_options *orig_options); #endif repmgr-2.0beta2/dbutils.c000066400000000000000000000272041225461504400154070ustar00rootroot00000000000000/* * dbutils.c - Database connection/management functions * Copyright (C) 2ndQuadrant, 2010-2012 * * 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 . * */ #include #include "repmgr.h" #include "strutil.h" #include "log.h" PGconn * establishDBConnection(const char *conninfo, const bool exit_on_error) { /* Make a connection to the database */ PGconn *conn = NULL; char connection_string[MAXLEN]; strcpy(connection_string, conninfo); strcat(connection_string, " fallback_application_name='repmgr'"); conn = PQconnectdb(connection_string); /* Check to see that the backend connection was successfully made */ if ((PQstatus(conn) != CONNECTION_OK)) { log_err(_("Connection to database failed: %s\n"), PQerrorMessage(conn)); if (exit_on_error) { PQfinish(conn); exit(ERR_DB_CON); } } return conn; } PGconn * establishDBConnectionByParams(const char *keywords[], const char *values[],const bool exit_on_error) { /* Make a connection to the database */ PGconn *conn = PQconnectdbParams(keywords, values, true); /* Check to see that the backend connection was successfully made */ if ((PQstatus(conn) != CONNECTION_OK)) { log_err(_("Connection to database failed: %s\n"), PQerrorMessage(conn)); if (exit_on_error) { PQfinish(conn); exit(ERR_DB_CON); } } return conn; } bool is_standby(PGconn *conn) { PGresult *res; bool result = false; res = PQexec(conn, "SELECT pg_is_in_recovery()"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't query server mode: %s"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_DB_QUERY); } if (PQntuples(res) == 1 && strcmp(PQgetvalue(res, 0, 0), "t") == 0) result = true; PQclear(res); return result; } bool is_witness(PGconn *conn, char *schema, char *cluster, int node_id) { PGresult *res; bool result = false; char sqlquery[QUERY_STR_LEN]; sqlquery_snprintf(sqlquery, "SELECT witness from %s.repl_nodes where cluster = '%s' and id = %d", schema, cluster, node_id); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't query server mode: %s"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_DB_QUERY); } if (PQntuples(res) == 1 && strcmp(PQgetvalue(res, 0, 0), "t") == 0) result = true; PQclear(res); return result; } /* check the PQStatus and try to 'select 1' to confirm good connection */ bool is_pgup(PGconn *conn, int timeout) { char sqlquery[QUERY_STR_LEN]; /* Check the connection status twice in case it changes after reset */ bool twice = false; /* Check the connection status twice in case it changes after reset */ for (;;) { if (PQstatus(conn) != CONNECTION_OK) { if (twice) return false; PQreset(conn); // reconnect twice = true; } else { /* * Send a SELECT 1 just to check if the connection is OK */ if (!CancelQuery(conn, timeout)) goto failed; if (wait_connection_availability(conn, timeout) != 1) goto failed; sqlquery_snprintf(sqlquery, "SELECT 1"); if (PQsendQuery(conn, sqlquery) == 0) { log_warning(_("PQsendQuery: Query could not be sent to primary. %s\n"), PQerrorMessage(conn)); goto failed; } if (wait_connection_availability(conn, timeout) != 1) goto failed; break; failed: // we need to retry, because we might just have loose the connection once if (twice) return false; PQreset(conn); // reconnect twice = true; } } return true; } /* * If postgreSQL version is 9 or superior returns the major version * if 8 or inferior returns an empty string */ char * pg_version(PGconn *conn, char* major_version) { PGresult *res; int major_version1; char *major_version2; res = PQexec(conn, "WITH pg_version(ver) AS " "(SELECT split_part(version(), ' ', 2)) " "SELECT split_part(ver, '.', 1), split_part(ver, '.', 2) " "FROM pg_version"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Version check PQexec failed: %s"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_DB_QUERY); } major_version1 = atoi(PQgetvalue(res, 0, 0)); major_version2 = PQgetvalue(res, 0, 1); if (major_version1 >= 9) { /* form a major version string */ xsnprintf(major_version, MAXVERSIONSTR, "%d.%s", major_version1, major_version2); } else strcpy(major_version, ""); PQclear(res); return major_version; } bool guc_setted(PGconn *conn, const char *parameter, const char *op, const char *value) { PGresult *res; char sqlquery[QUERY_STR_LEN]; sqlquery_snprintf(sqlquery, "SELECT true FROM pg_settings " " WHERE name = '%s' AND setting %s '%s'", parameter, op, value); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("GUC setting check PQexec failed: %s"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_DB_QUERY); } if (PQntuples(res) == 0) { PQclear(res); return false; } PQclear(res); return true; } /** * Just like guc_setted except with an extra parameter containing the name of * the pg datatype so that the comparison can be done properly. */ bool guc_setted_typed(PGconn *conn, const char *parameter, const char *op, const char *value, const char *datatype) { PGresult *res; char sqlquery[QUERY_STR_LEN]; sqlquery_snprintf(sqlquery, "SELECT true FROM pg_settings " " WHERE name = '%s' AND setting::%s %s '%s'::%s", parameter, datatype, op, value, datatype); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("GUC setting check PQexec failed: %s"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_DB_QUERY); } if (PQntuples(res) == 0) { PQclear(res); return false; } PQclear(res); return true; } const char * get_cluster_size(PGconn *conn) { PGresult *res; const char *size; char sqlquery[QUERY_STR_LEN]; sqlquery_snprintf( sqlquery, "SELECT pg_size_pretty(SUM(pg_database_size(oid))::bigint) " " FROM pg_database "); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Get cluster size PQexec failed: %s"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_DB_QUERY); } size = PQgetvalue(res, 0, 0); PQclear(res); return size; } /* * get a connection to master by reading repl_nodes, creating a connection * to each node (one at a time) and finding if it is a master or a standby * * NB: If master_conninfo_out may be NULL. If it is non-null, it is assumed to * point to allocated memory of MAXCONNINFO in length, and the master server * connection string is placed there. */ PGconn * getMasterConnection(PGconn *standby_conn, char *schema, char *cluster, int *master_id, char *master_conninfo_out) { PGconn *master_conn = NULL; PGresult *res1; PGresult *res2; char sqlquery[QUERY_STR_LEN]; char master_conninfo_stack[MAXCONNINFO]; char *master_conninfo = &*master_conninfo_stack; char schema_quoted[MAXLEN]; int i; /* * If the caller wanted to get a copy of the connection info string, sub * out the local stack pointer for the pointer passed by the caller. */ if (master_conninfo_out != NULL) master_conninfo = master_conninfo_out; /* * XXX: This is copied in at least two other procedures * * Assemble the unquoted schema name */ { char *identifier = PQescapeIdentifier(standby_conn, schema, strlen(schema)); maxlen_snprintf(schema_quoted, "%s", identifier); PQfreemem(identifier); } /* find all nodes belonging to this cluster */ log_info(_("finding node list for cluster '%s'\n"), cluster); sqlquery_snprintf(sqlquery, "SELECT id, conninfo FROM %s.repl_nodes " " WHERE cluster = '%s' and not witness", schema_quoted, cluster); res1 = PQexec(standby_conn, sqlquery); if (PQresultStatus(res1) != PGRES_TUPLES_OK) { log_err(_("Can't get nodes info: %s\n"), PQerrorMessage(standby_conn)); PQclear(res1); PQfinish(standby_conn); exit(ERR_DB_QUERY); } for (i = 0; i < PQntuples(res1); i++) { /* initialize with the values of the current node being processed */ *master_id = atoi(PQgetvalue(res1, i, 0)); strncpy(master_conninfo, PQgetvalue(res1, i, 1), MAXCONNINFO); log_info(_("checking role of cluster node '%s'\n"), master_conninfo); master_conn = establishDBConnection(master_conninfo, false); if (PQstatus(master_conn) != CONNECTION_OK) continue; /* * Can't use the is_standby() function here because on error that * function closes the connection passed and exits. This still * needs to close master_conn first. */ res2 = PQexec(master_conn, "SELECT pg_is_in_recovery()"); if (PQresultStatus(res2) != PGRES_TUPLES_OK) { log_err(_("Can't get recovery state from this node: %s\n"), PQerrorMessage(master_conn)); PQclear(res2); PQfinish(master_conn); continue; } /* if false, this is the master */ if (strcmp(PQgetvalue(res2, 0, 0), "f") == 0) { PQclear(res2); PQclear(res1); return master_conn; } else { /* if it is a standby clear info */ PQclear(res2); PQfinish(master_conn); *master_id = -1; } } /* If we finish this loop without finding a master then * we doesn't have the info or the master has failed (or we * reached max_connections or superuser_reserved_connections, * anything else I'm missing?). * * Probably we will need to check the error to know if we need * to start failover procedure or just fix some situation on the * standby. */ PQclear(res1); return NULL; } /* * wait until current query finishes ignoring any results, this could be an async command * or a cancelation of a query * return 1 if Ok; 0 if any error ocurred; -1 if timeout reached */ int wait_connection_availability(PGconn *conn, int timeout) { PGresult *res; while(timeout-- >= 0) { if (PQconsumeInput(conn) == 0) { log_warning(_("wait_connection_availability: could not receive data from master. %s\n"), PQerrorMessage(conn)); return 0; } if (PQisBusy(conn) == 0) { res = PQgetResult(conn); if (res == NULL) break; PQclear(res); } sleep(1); } if (timeout >= 0) return 1; else { log_warning(_("wait_connection_availability: timeout reached")); return -1; } } bool CancelQuery(PGconn *conn, int timeout) { char errbuf[ERRBUFF_SIZE]; PGcancel *pgcancel; if (wait_connection_availability(conn, timeout) != 1) return false; pgcancel = PQgetCancel(conn); if (pgcancel == NULL) return false; /* * PQcancel can only return 0 if socket()/connect()/send() * fails, in any of those cases we can assume something * bad happened to the connection */ if (PQcancel(pgcancel, errbuf, ERRBUFF_SIZE) == 0) { log_warning(_("Can't stop current query: %s\n"), errbuf); PQfreeCancel(pgcancel); return false; } PQfreeCancel(pgcancel); return true; } repmgr-2.0beta2/dbutils.h000066400000000000000000000034301225461504400154070ustar00rootroot00000000000000/* * dbutils.h * Copyright (c) 2ndQuadrant, 2010-2012 * * 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 . * */ #ifndef _REPMGR_DBUTILS_H_ #define _REPMGR_DBUTILS_H_ #include "strutil.h" PGconn *establishDBConnection(const char *conninfo, const bool exit_on_error); PGconn *establishDBConnectionByParams(const char *keywords[], const char *values[], const bool exit_on_error); bool is_standby(PGconn *conn); bool is_witness(PGconn *conn, char *schema, char *cluster, int node_id); bool is_pgup(PGconn *conn, int timeout); char *pg_version(PGconn *conn, char* major_version); bool guc_setted(PGconn *conn, const char *parameter, const char *op, const char *value); bool guc_setted_typed(PGconn *conn, const char *parameter, const char *op, const char *value, const char *datatype); const char *get_cluster_size(PGconn *conn); PGconn *getMasterConnection(PGconn *standby_conn, char *schema, char *cluster, int *master_id, char *master_conninfo_out); int wait_connection_availability(PGconn *conn, int timeout); bool CancelQuery(PGconn *conn, int timeout); #endif repmgr-2.0beta2/debian/000077500000000000000000000000001225461504400150125ustar00rootroot00000000000000repmgr-2.0beta2/debian/DEBIAN/000077500000000000000000000000001225461504400157345ustar00rootroot00000000000000repmgr-2.0beta2/debian/DEBIAN/control000066400000000000000000000005001225461504400173320ustar00rootroot00000000000000Package: repmgr-auto Version: 2.0beta2 Section: database Priority: optional Architecture: all Depends: rsync, postgresql-9.0 | postgresql-9.1 | postgresql-9.2 | postgresql-9.3 Maintainer: Jaime Casanova Description: PostgreSQL replication setup, magament and monitoring has two main executables repmgr-2.0beta2/debian/repmgr.repmgrd.default000066400000000000000000000003741225461504400213170ustar00rootroot00000000000000#!/bin/sh # default settings for repmgrd. This file is source by /bin/sh from # /etc/init.d/repmgrd # Options for repmgrd REPMGRD_OPTS="" # repmgrd binary REPMGR_BIN="/usr/bin/repmgr" # pid file REPMGR_PIDFILE="/var/run/repmgrd.pid" repmgr-2.0beta2/debian/repmgr.repmgrd.init000066400000000000000000000021331225461504400206310ustar00rootroot00000000000000#!/bin/sh ### BEGIN INIT INFO # Provides: repmgrd # Required-Start: $local_fs $remote_fs $network $syslog $postgresql # Required-Stop: $local_fs $remote_fs $network $syslog $postgresql # Should-Start: $syslog $postgresql # Should-Start: $syslog $postgresql # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Start/stop repmgrd ### END INIT INFO set -e if test -f /etc/default/repmgrd; then . /etc/default/repmgrd fi if [ -z "$REPMGRD_BIN" ]; then REPMGRD_BIN="/usr/bin/repmgrd" fi if [ -z "$REPMGRD_PIDFILE" ]; then REPMGRD_PIDFILE="/var/run/repmgrd.pid" fi test -x $REPMGRD_BIN || exit 0 case "$1" in start) start-stop-daemon --start --quiet --make-pidfile --pidfile $REPMGRD_PIDFILE --exec $REPMGRD_BIN $REPMGRD_OPTS ;; stop) start-stop-daemon --stop --oknodo --quiet --pidfile $REPMGRD_PIDFILE ;; restart) $0 stop && $0 start || exit 1 ;; *) echo "Usage: $0 {start|stop|restart}" exit 1 ;; esac exit 0 repmgr-2.0beta2/errcode.h000066400000000000000000000021411225461504400153620ustar00rootroot00000000000000/* * errcode.h * Copyright (C) 2ndQuadrant, 2010-2012 * * 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 . * */ #ifndef _ERRCODE_H_ #define _ERRCODE_H_ /* Exit return code */ #define SUCCESS 0 #define ERR_BAD_CONFIG 1 #define ERR_BAD_RSYNC 2 #define ERR_STOP_BACKUP 3 #define ERR_NO_RESTART 4 #define ERR_NEEDS_XLOG 5 #define ERR_DB_CON 6 #define ERR_DB_QUERY 7 #define ERR_PROMOTED 8 #define ERR_BAD_PASSWORD 9 #define ERR_STR_OVERFLOW 10 #define ERR_FAILOVER_FAIL 11 #define ERR_BAD_SSH 12 #endif /* _ERRCODE_H_ */ repmgr-2.0beta2/log.c000066400000000000000000000110411225461504400145120ustar00rootroot00000000000000/* * log.c - Logging methods * Copyright (C) 2ndQuadrant, 2010-2012 * * This module is a set of methods for logging (currently only syslog) * * 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 . * */ #include "repmgr.h" #include #ifdef HAVE_SYSLOG #include #endif #include #include #include "log.h" #define DEFAULT_IDENT "repmgr" #ifdef HAVE_SYSLOG #define DEFAULT_SYSLOG_FACILITY LOG_LOCAL0 #endif /* #define REPMGR_DEBUG */ void stderr_log_with_level(const char *level_name, int level, const char *fmt, ...) { size_t len = strlen(fmt); char fmt1[len + 150]; time_t t; struct tm *tm; char buff[100]; va_list ap; if(log_level >= level) { time(&t); tm = localtime(&t); va_start(ap, fmt); strftime(buff, 100, "[%Y-%m-%d %H:%M:%S]", tm); snprintf(fmt1, len + 150, "%s [%s] %s", buff, level_name, fmt); vfprintf(stderr, fmt1, ap); va_end(ap); } } static int detect_log_level(const char* level); static int detect_log_facility(const char* facility); int log_type = REPMGR_STDERR; int log_level = LOG_NOTICE; bool logger_init(const char* ident, const char* level, const char* facility) { int l; int f; #ifdef HAVE_SYSLOG int syslog_facility = DEFAULT_SYSLOG_FACILITY; #endif #ifdef REPMGR_DEBUG printf("Logger initialisation (Level: %s, Facility: %s)\n", level, facility); #endif if (!ident) { ident = DEFAULT_IDENT; } if (level && *level) { l = detect_log_level(level); #ifdef REPMGR_DEBUG printf("Assigned level for logger: %d\n", l); #endif if (l > 0) log_level = l; else stderr_log_warning(_("Cannot detect log level %s (use any of DEBUG, INFO, NOTICE, WARNING, ERR, ALERT, CRIT or EMERG)\n"), level); } if (facility && *facility) { f = detect_log_facility(facility); #ifdef REPMGR_DEBUG printf("Assigned facility for logger: %d\n", f); #endif if (f == 0) { /* No syslog requested, just stderr */ #ifdef REPMGR_DEBUG printf(_("Use stderr for logging\n")); #endif } else if (f == -1) { stderr_log_warning(_("Cannot detect log facility %s (use any of LOCAL0, LOCAL1, ..., LOCAL7, USER or STDERR)\n"), facility); } #ifdef HAVE_SYSLOG else { syslog_facility = f; log_type = REPMGR_SYSLOG; } #endif } #ifdef HAVE_SYSLOG if (log_type == REPMGR_SYSLOG) { setlogmask (LOG_UPTO (log_level)); openlog (ident, LOG_CONS | LOG_PID | LOG_NDELAY, syslog_facility); stderr_log_notice(_("Setup syslog (level: %s, facility: %s)\n"), level, facility); } #endif return true; } bool logger_shutdown(void) { #ifdef HAVE_SYSLOG if (log_type == REPMGR_SYSLOG) closelog(); #endif return true; } /* * Set a minimum logging level. Intended for command line verbosity * options, which might increase requested logging over what's specified * in the regular configuration file. */ void logger_min_verbose(int minimum) { if (log_level < minimum) log_level = minimum; } int detect_log_level(const char* level) { if (!strcmp(level, "DEBUG")) return LOG_DEBUG; if (!strcmp(level, "INFO")) return LOG_INFO; if (!strcmp(level, "NOTICE")) return LOG_NOTICE; if (!strcmp(level, "WARNING")) return LOG_WARNING; if (!strcmp(level, "ERR")) return LOG_ERR; if (!strcmp(level, "ALERT")) return LOG_ALERT; if (!strcmp(level, "CRIT")) return LOG_CRIT; if (!strcmp(level, "EMERG")) return LOG_EMERG; return 0; } int detect_log_facility(const char* facility) { int local = 0; if (!strncmp(facility, "LOCAL", 5) && strlen(facility) == 6) { local = atoi (&facility[5]); switch (local) { case 0: return LOG_LOCAL0; break; case 1: return LOG_LOCAL1; break; case 2: return LOG_LOCAL2; break; case 3: return LOG_LOCAL3; break; case 4: return LOG_LOCAL4; break; case 5: return LOG_LOCAL5; break; case 6: return LOG_LOCAL6; break; case 7: return LOG_LOCAL7; break; } } else if (!strcmp(facility, "USER")) { return LOG_USER; } else if (!strcmp(facility, "STDERR")) { return 0; } return -1; } repmgr-2.0beta2/log.h000066400000000000000000000074151225461504400145310ustar00rootroot00000000000000/* * log.h * Copyright (c) 2ndQuadrant, 2010-2012 * * 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 . * */ #ifndef _REPMGR_LOG_H_ #define _REPMGR_LOG_H_ #include "repmgr.h" #define REPMGR_SYSLOG 1 #define REPMGR_STDERR 2 void stderr_log_with_level(const char *level_name, int level, const char *fmt, ...); /* Standard error logging */ #define stderr_log_debug(...) stderr_log_with_level("DEBUG", LOG_DEBUG, __VA_ARGS__) #define stderr_log_info(...) stderr_log_with_level("INFO", LOG_INFO, __VA_ARGS__) #define stderr_log_notice(...) stderr_log_with_level("NOTICE", LOG_NOTICE, __VA_ARGS__) #define stderr_log_warning(...) stderr_log_with_level("WARNING", LOG_WARNING, __VA_ARGS__) #define stderr_log_err(...) stderr_log_with_level("ERROR", LOG_ERR, __VA_ARGS__) #define stderr_log_crit(...) stderr_log_with_level("CRITICAL", LOG_CRIT, __VA_ARGS__) #define stderr_log_alert(...) stderr_log_with_level("ALERT", LOG_ALERT, __VA_ARGS__) #define stderr_log_emerg(...) stderr_log_with_level("EMERGENCY", LOG_EMERG, __VA_ARGS__) #ifdef HAVE_SYSLOG #include #define log_debug(...) \ if (log_type == REPMGR_SYSLOG) \ syslog(LOG_DEBUG, __VA_ARGS__); \ else \ stderr_log_debug(__VA_ARGS__); #define log_info(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_INFO, __VA_ARGS__); \ else stderr_log_info(__VA_ARGS__); \ } #define log_notice(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_NOTICE, __VA_ARGS__); \ else stderr_log_notice(__VA_ARGS__); \ } #define log_warning(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_WARNING, __VA_ARGS__); \ else stderr_log_warning(__VA_ARGS__); \ } #define log_err(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_ERR, __VA_ARGS__); \ else stderr_log_err(__VA_ARGS__); \ } #define log_crit(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_CRIT, __VA_ARGS__); \ else stderr_log_crit(__VA_ARGS__); \ } #define log_alert(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_ALERT, __VA_ARGS__); \ else stderr_log_alert(__VA_ARGS__); \ } #define log_emerg(...) \ { \ if (log_type == REPMGR_SYSLOG) syslog(LOG_ALERT, __VA_ARGS__); \ else stderr_log_alert(__VA_ARGS__); \ } #else #define LOG_EMERG 0 /* system is unusable */ #define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_CRIT 2 /* critical conditions */ #define LOG_ERR 3 /* error conditions */ #define LOG_WARNING 4 /* warning conditions */ #define LOG_NOTICE 5 /* normal but significant condition */ #define LOG_INFO 6 /* informational */ #define LOG_DEBUG 7 /* debug-level messages */ #define log_debug(...) stderr_log_debug(__VA_ARGS__) #define log_info(...) stderr_log_info(__VA_ARGS__) #define log_notice(...) stderr_log_notice(__VA_ARGS__) #define log_warning(...) stderr_log_warning(__VA_ARGS__) #define log_err(...) stderr_log_err(__VA_ARGS__) #define log_crit(...) stderr_log_crit(__VA_ARGS__) #define log_alert(...) stderr_log_alert(__VA_ARGS__) #define log_emerg(...) stderr_log_emerg(__VA_ARGS__) #endif /* Logger initialisation and shutdown */ bool logger_shutdown(void); bool logger_init(const char* ident, const char* level, const char* facility); void logger_min_verbose(int minimum); extern int log_type; extern int log_level; #endif repmgr-2.0beta2/repmgr.c000066400000000000000000002025171225461504400152370ustar00rootroot00000000000000/* * repmgr.c - Command interpreter for the repmgr * Copyright (C) 2ndQuadrant, 2010-2012 * * This module is a command-line utility to easily setup a cluster of * hot standby servers for an HA environment * * Commands implemented are. * MASTER REGISTER * STANDBY REGISTER, STANDBY CLONE, STANDBY FOLLOW, STANDBY PROMOTE * CLUSTER SHOW, CLUSTER CLEANUP * WITNESS CREATE * * 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 . * */ #include "repmgr.h" #include #include #include #include #include #include "log.h" #include "config.h" #include "check_dir.h" #include "strutil.h" #include "version.h" #define RECOVERY_FILE "recovery.conf" #define RECOVERY_DONE_FILE "recovery.done" #define NO_ACTION 0 /* Not a real action, just to initialize */ #define MASTER_REGISTER 1 #define STANDBY_REGISTER 2 #define STANDBY_CLONE 3 #define STANDBY_PROMOTE 4 #define STANDBY_FOLLOW 5 #define WITNESS_CREATE 6 #define CLUSTER_SHOW 7 #define CLUSTER_CLEANUP 8 static bool create_recovery_file(const char *data_dir); static int test_ssh_connection(char *host, char *remote_user); static int copy_remote_files(char *host, char *remote_user, char *remote_path, char *local_path, bool is_directory); static bool check_parameters_for_action(const int action); static bool create_schema(PGconn *conn); static bool copy_configuration(PGconn *masterconn, PGconn *witnessconn); static void write_primary_conninfo(char* line); static void do_master_register(void); static void do_standby_register(void); static void do_standby_clone(void); static void do_standby_promote(void); static void do_standby_follow(void); static void do_witness_create(void); static void do_cluster_show(void); static void do_cluster_cleanup(void); static void usage(void); static void help(const char *progname); /* Global variables */ static const char *progname; static const char *keywords[6]; static const char *values[6]; char repmgr_schema[MAXLEN]; bool need_a_node = true; /* XXX This should be mapped into a command line option */ bool require_password = false; /* Initialization of runtime options */ t_runtime_options runtime_options = { "", "", "", "", "", "", DEFAULT_WAL_KEEP_SEGMENTS, false, false, false, false, "", "", 0 }; t_configuration_options options = { "", -1, "", MANUAL_FAILOVER, -1, "", "", "", "", "", "", "", -1 }; static char *server_mode = NULL; static char *server_cmd = NULL; int main(int argc, char **argv) { static struct option long_options[] = { {"dbname", required_argument, NULL, 'd'}, {"host", required_argument, NULL, 'h'}, {"port", required_argument, NULL, 'p'}, {"username", required_argument, NULL, 'U'}, {"dest-dir", required_argument, NULL, 'D'}, {"local-port", required_argument, NULL, 'l'}, {"config-file", required_argument, NULL, 'f'}, {"remote-user", required_argument, NULL, 'R'}, {"wal-keep-segments", required_argument, NULL, 'w'}, {"keep-history", required_argument, NULL, 'k'}, {"force", no_argument, NULL, 'F'}, {"wait", no_argument, NULL, 'W'}, {"ignore-rsync-warning", no_argument, NULL, 'I'}, {"verbose", no_argument, NULL, 'v'}, {NULL, 0, NULL, 0} }; int optindex; int c; int action = NO_ACTION; progname = get_progname(argv[0]); if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) { help(progname); exit(SUCCESS); } if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) { printf("%s %s (PostgreSQL %s)\n", progname, REPMGR_VERSION, PG_VERSION); exit(SUCCESS); } } while ((c = getopt_long(argc, argv, "d:h:p:U:D:l:f:R:w:k:FWIv", long_options, &optindex)) != -1) { switch (c) { case 'd': strncpy(runtime_options.dbname, optarg, MAXLEN); break; case 'h': strncpy(runtime_options.host, optarg, MAXLEN); break; case 'p': if (atoi(optarg) > 0) strncpy(runtime_options.masterport, optarg, MAXLEN); break; case 'U': strncpy(runtime_options.username, optarg, MAXLEN); break; case 'D': strncpy(runtime_options.dest_dir, optarg, MAXFILENAME); break; case 'l': if (atoi(optarg) > 0) strncpy(runtime_options.localport, optarg, MAXLEN); break; case 'f': strncpy(runtime_options.config_file, optarg, MAXLEN); break; case 'R': strncpy(runtime_options.remote_user, optarg, MAXLEN); break; case 'w': if (atoi(optarg) > 0) strncpy(runtime_options.wal_keep_segments, optarg, MAXLEN); break; case 'k': if (atoi(optarg) > 0) runtime_options.keep_history = atoi(optarg); else runtime_options.keep_history = 0; break; case 'F': runtime_options.force = true; break; case 'W': runtime_options.wait_for_master = true; break; case 'I': runtime_options.ignore_rsync_warn = true; break; case 'v': runtime_options.verbose = true; break; default: usage(); exit(ERR_BAD_CONFIG); } } /* * Now we need to obtain the action, this comes in one of these forms: * MASTER REGISTER | * STANDBY {REGISTER | CLONE [node] | PROMOTE | FOLLOW [node]} | * WITNESS CREATE * CLUSTER {SHOW | CLEANUP} * * the node part is optional, if we receive it then we shouldn't * have received a -h option */ if (optind < argc) { server_mode = argv[optind++]; if (strcasecmp(server_mode, "STANDBY") != 0 && strcasecmp(server_mode, "MASTER") != 0 && strcasecmp(server_mode, "WITNESS") != 0 && strcasecmp(server_mode, "CLUSTER") != 0 ) { usage(); exit(ERR_BAD_CONFIG); } } if (optind < argc) { server_cmd = argv[optind++]; /* check posibilities for all server modes */ if (strcasecmp(server_mode, "MASTER") == 0) { if (strcasecmp(server_cmd, "REGISTER") == 0) action = MASTER_REGISTER; } else if (strcasecmp(server_mode, "STANDBY") == 0) { if (strcasecmp(server_cmd, "REGISTER") == 0) action = STANDBY_REGISTER; else if (strcasecmp(server_cmd, "CLONE") == 0) action = STANDBY_CLONE; else if (strcasecmp(server_cmd, "PROMOTE") == 0) action = STANDBY_PROMOTE; else if (strcasecmp(server_cmd, "FOLLOW") == 0) action = STANDBY_FOLLOW; } else if (strcasecmp(server_mode, "CLUSTER") == 0) { if( strcasecmp(server_cmd, "SHOW") == 0) action = CLUSTER_SHOW; else if(strcasecmp(server_cmd, "CLEANUP") == 0) action = CLUSTER_CLEANUP; } else if (strcasecmp(server_mode, "WITNESS") == 0) if (strcasecmp(server_cmd, "CREATE") == 0) action = WITNESS_CREATE; } if (action == NO_ACTION) { usage(); exit(ERR_BAD_CONFIG); } /* For some actions we still can receive a last argument */ if (action == STANDBY_CLONE) { if (optind < argc) { if (runtime_options.host[0]) { log_err(_("Conflicting parameters: you can't use -h while providing a node separately.\n")); usage(); exit(ERR_BAD_CONFIG); } strncpy(runtime_options.host, argv[optind++], MAXLEN); } } switch (optind < argc) { case 0: break; default: log_err(_("%s: too many command-line arguments (first extra is \"%s\")\n"), progname, argv[optind]); usage(); exit(ERR_BAD_CONFIG); } if (!check_parameters_for_action(action)) exit(ERR_BAD_CONFIG); if (!runtime_options.dbname[0]) { if (getenv("PGDATABASE")) strncpy(runtime_options.dbname, getenv("PGDATABASE"), MAXLEN); else if (getenv("PGUSER")) strncpy(runtime_options.dbname, getenv("PGUSER"), MAXLEN); else strncpy(runtime_options.dbname, DEFAULT_DBNAME, MAXLEN); } /* Read the configuration file, normally repmgr.conf */ if (!runtime_options.config_file[0]) strncpy(runtime_options.config_file, DEFAULT_CONFIG_FILE, MAXLEN); if (runtime_options.verbose) printf(_("Opening configuration file: %s\n"), runtime_options.config_file); /* * XXX Do not read config files for action where it is not required (clone * for example). */ parse_config(runtime_options.config_file, &options); keywords[2] = "user"; values[2] = (runtime_options.username[0]) ? runtime_options.username : NULL; keywords[3] = "dbname"; values[3] = runtime_options.dbname; keywords[4] = "application_name"; values[4] = (char *) progname; keywords[5] = NULL; values[5] = NULL; /* * Initialize the logger. If verbose command line parameter was * input, make sure that the log level is at least INFO. This * is mainly useful for STANDBY CLONE. That doesn't require a * configuration file where a logging level might be specified * at, but it often requires detailed logging to troubleshoot * problems. */ logger_init(progname, options.loglevel, options.logfacility); if (runtime_options.verbose) logger_min_verbose(LOG_INFO); /* * Node configuration information is not needed for all actions, * with STANDBY CLONE being the main exception. */ if (need_a_node) { if (options.node == -1) { log_err(_("Node information is missing. " "Check the configuration file.\n")); exit(ERR_BAD_CONFIG); } } /* Prepare the repmgr schema variable */ snprintf(repmgr_schema, MAXLEN, "%s%s", DEFAULT_REPMGR_SCHEMA_PREFIX, options.cluster_name); switch (action) { case MASTER_REGISTER: do_master_register(); break; case STANDBY_REGISTER: do_standby_register(); break; case STANDBY_CLONE: do_standby_clone(); break; case STANDBY_PROMOTE: do_standby_promote(); break; case STANDBY_FOLLOW: do_standby_follow(); break; case WITNESS_CREATE: do_witness_create(); break; case CLUSTER_SHOW: do_cluster_show(); break; case CLUSTER_CLEANUP: do_cluster_cleanup(); break; default: usage(); exit(ERR_BAD_CONFIG); } logger_shutdown(); return 0; } static void do_cluster_show(void) { PGconn *conn; PGresult *res; char sqlquery[QUERY_STR_LEN]; char node_role[MAXLEN]; int i; /* We need to connect to check configuration */ log_info(_("%s connecting to database\n"), progname); conn = establishDBConnection(options.conninfo, true); sqlquery_snprintf(sqlquery, "SELECT conninfo, witness FROM %s.repl_nodes;", repmgr_schema); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get nodes information, have you registered them?\n%s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } PQfinish(conn); printf("Role | Connection String \n"); for (i = 0; i < PQntuples(res); i++) { conn = establishDBConnection(PQgetvalue(res, i, 0), false); if (PQstatus(conn) != CONNECTION_OK) strcpy(node_role, " FAILED"); else if (strcmp(PQgetvalue(res, i, 1), "t") == 0) strcpy(node_role, " witness"); else if (is_standby(conn)) strcpy(node_role, " standby"); else strcpy(node_role, "* master"); printf("%-10s", node_role); printf("| %s\n", PQgetvalue(res, i, 0)); PQfinish(conn); } PQclear(res); } static void do_cluster_cleanup(void) { int master_id; PGconn *conn = NULL; PGconn *master_conn = NULL; PGresult *res; char sqlquery[QUERY_STR_LEN]; /* We need to connect to check configuration */ log_info(_("%s connecting to database\n"), progname); conn = establishDBConnection(options.conninfo, true); /* check if there is a master in this cluster */ log_info(_("%s connecting to master database\n"), progname); master_conn = getMasterConnection(conn, repmgr_schema, options.cluster_name, &master_id, NULL); if (!master_conn) { log_err(_("cluster cleanup: cannot connect to master\n")); PQfinish(conn); exit(ERR_DB_CON); } PQfinish(conn); if (runtime_options.keep_history > 0) { sqlquery_snprintf(sqlquery, "DELETE FROM %s.repl_monitor " " WHERE age(now(), last_monitor_time) >= '%d days'::interval;", repmgr_schema, runtime_options.keep_history); } else { sqlquery_snprintf(sqlquery, "TRUNCATE TABLE %s.repl_monitor;", repmgr_schema); } res = PQexec(master_conn, sqlquery); if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_err(_("cluster cleanup: Couldn't clean history\n%s\n"), PQerrorMessage(master_conn)); PQclear(res); PQfinish(master_conn); exit(ERR_BAD_CONFIG); } PQclear(res); /* Let's VACUUM the table to avoid autovacuum to be launched in an unexpected hour */ sqlquery_snprintf(sqlquery, "VACUUM %s.repl_monitor;", repmgr_schema); res = PQexec(master_conn, sqlquery); /* XXX There is any need to check this VACUUM happens without problems? */ PQclear(res); PQfinish(master_conn); } static void do_master_register(void) { PGconn *conn; PGresult *res; char sqlquery[QUERY_STR_LEN]; bool schema_exists = false; char schema_quoted[MAXLEN]; char master_version[MAXVERSIONSTR]; conn = establishDBConnection(options.conninfo, true); /* master should be v9 or better */ log_info(_("%s connecting to master database\n"), progname); pg_version(conn, master_version); if (strcmp(master_version, "") == 0) { PQfinish(conn); log_err( _("%s needs master to be PostgreSQL 9.0 or better\n"), progname); return; } /* Check we are a master */ log_info(_("%s connected to master, checking its state\n"), progname); if (is_standby(conn)) { log_err(_("Trying to register a standby node as a master\n")); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* Assemble a quoted schema name * XXX This is not currently used due to a merge conflict, but * probably should be */ if (false) { char *identifier = PQescapeIdentifier(conn, repmgr_schema, strlen(repmgr_schema)); maxlen_snprintf(schema_quoted, "%s", identifier); PQfreemem(identifier); } /* Check if there is a schema for this cluster */ sqlquery_snprintf(sqlquery, "SELECT 1 FROM pg_namespace " "WHERE nspname = '%s'", repmgr_schema); log_debug(_("master register: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about schemas: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } if (PQntuples(res) > 0) /* schema exists */ { if (!runtime_options.force) /* and we are not forcing so error */ { log_notice(_("Schema %s already exists.\n"), repmgr_schema); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } schema_exists = true; } PQclear(res); if (!schema_exists) { log_info(_("master register: creating database objects inside the %s schema\n"), repmgr_schema); /* ok, create the schema */ if (!create_schema(conn)) return; } else { PGconn *master_conn; int id; /* Ensure there isn't any other master already registered */ master_conn = getMasterConnection(conn, repmgr_schema, options.cluster_name, &id,NULL); if (master_conn != NULL) { PQfinish(master_conn); log_warning(_("There is a master already in cluster %s\n"), options.cluster_name); exit(ERR_BAD_CONFIG); } } /* Now register the master */ if (runtime_options.force) { sqlquery_snprintf(sqlquery, "DELETE FROM %s.repl_nodes " " WHERE id = %d", repmgr_schema, options.node); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_warning(_("Cannot delete node details, %s\n"), PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } } sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes (id, cluster, name, conninfo, priority) " "VALUES (%d, '%s', '%s', '%s', %d)", repmgr_schema, options.node, options.cluster_name, options.node_name, options.conninfo, options.priority); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_warning(_("Cannot insert node details, %s\n"), PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } PQfinish(conn); log_notice(_("Master node correctly registered for cluster %s with id %d (conninfo: %s)\n"), options.cluster_name, options.node, options.conninfo); return; } static void do_standby_register(void) { PGconn *conn; PGconn *master_conn; int master_id; PGresult *res; char sqlquery[QUERY_STR_LEN]; char schema_quoted[MAXLEN]; char master_version[MAXVERSIONSTR]; char standby_version[MAXVERSIONSTR]; /* XXX: A lot of copied code from do_master_register! Refactor */ log_info(_("%s connecting to standby database\n"), progname); conn = establishDBConnection(options.conninfo, true); /* should be v9 or better */ log_info(_("%s connected to standby, checking its state\n"), progname); pg_version(conn, standby_version); if (strcmp(standby_version, "") == 0) { PQfinish(conn); log_err(_("%s needs standby to be PostgreSQL 9.0 or better\n"), progname); exit(ERR_BAD_CONFIG); } /* Check we are a standby */ if (!is_standby(conn)) { log_err(_("repmgr: This node should be a standby (%s)\n"), options.conninfo); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* Assemble a quoted schema name * XXX This is not currently used due to a merge conflict, but * probably should be */ if (false) { char *identifier = PQescapeIdentifier(conn, repmgr_schema, strlen(repmgr_schema)); maxlen_snprintf(schema_quoted, "%s", identifier); PQfreemem(identifier); } /* Check if there is a schema for this cluster */ sqlquery_snprintf(sqlquery, "SELECT 1 FROM pg_namespace WHERE nspname = '%s'", repmgr_schema); log_debug(_("standby register: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about tablespaces: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } if (PQntuples(res) == 0) { /* schema doesn't exist */ log_err(_("Schema %s doesn't exists.\n"), repmgr_schema); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } PQclear(res); /* check if there is a master in this cluster */ log_info(_("%s connecting to master database\n"), progname); master_conn = getMasterConnection(conn, repmgr_schema, options.cluster_name, &master_id, NULL); if (!master_conn) { log_err(_("A master must be defined before configuring a slave\n")); exit(ERR_BAD_CONFIG); } /* master should be v9 or better */ log_info(_("%s connected to master, checking its state\n"), progname); pg_version(master_conn, master_version); if (strcmp(master_version, "") == 0) { PQfinish(conn); PQfinish(master_conn); log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname); exit(ERR_BAD_CONFIG); } /* master and standby version should match */ if (strcmp(master_version, standby_version) != 0) { PQfinish(conn); PQfinish(master_conn); log_err(_("%s needs versions of both master (%s) and standby (%s) to match.\n"), progname, master_version, standby_version); exit(ERR_BAD_CONFIG); } /* Now register the standby */ log_info(_("%s registering the standby\n"), progname); if (runtime_options.force) { sqlquery_snprintf(sqlquery, "DELETE FROM %s.repl_nodes " " WHERE id = %d", repmgr_schema, options.node); log_debug(_("standby register: %s\n"), sqlquery); if (!PQexec(master_conn, sqlquery)) { log_err(_("Cannot delete node details, %s\n"), PQerrorMessage(master_conn)); PQfinish(master_conn); PQfinish(conn); exit(ERR_BAD_CONFIG); } } sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes(id, cluster, name, conninfo, priority) " "VALUES (%d, '%s', '%s', '%s', %d)", repmgr_schema, options.node, options.cluster_name, options.node_name, options.conninfo, options.priority); log_debug(_("standby register: %s\n"), sqlquery); if (!PQexec(master_conn, sqlquery)) { log_err(_("Cannot insert node details, %s\n"), PQerrorMessage(master_conn)); PQfinish(master_conn); PQfinish(conn); exit(ERR_BAD_CONFIG); } log_info(_("%s registering the standby complete\n"), progname); PQfinish(master_conn); PQfinish(conn); log_notice(_("Standby node correctly registered for cluster %s with id %d (conninfo: %s)\n"), options.cluster_name, options.node, options.conninfo); return; } static void do_standby_clone(void) { PGconn *conn; PGresult *res; char sqlquery[QUERY_STR_LEN]; int r = 0; int i; bool flag_success = false; bool test_mode = false; char tblspc_dir[MAXFILENAME]; char master_data_directory[MAXFILENAME]; char local_data_directory[MAXFILENAME]; char master_xlog_directory[MAXFILENAME]; char local_xlog_directory[MAXFILENAME]; char master_stats_temp_directory[MAXFILENAME]; char local_stats_temp_directory[MAXFILENAME]; char master_control_file[MAXFILENAME]; char local_control_file[MAXFILENAME]; char master_config_file[MAXFILENAME]; char local_config_file[MAXFILENAME]; char master_hba_file[MAXFILENAME]; char local_hba_file[MAXFILENAME]; char master_ident_file[MAXFILENAME]; char local_ident_file[MAXFILENAME]; char *first_wal_segment = NULL; const char *last_wal_segment = NULL; char master_version[MAXVERSIONSTR]; /* * if dest_dir has been provided, we copy everything in the same path * if dest_dir is set and the master have tablespace, repmgr will stop * because it is more complex to remap the path for the tablespaces and it * does not look useful at the moment */ if (runtime_options.dest_dir[0]) { test_mode = true; log_notice(_("%s Destination directory %s provided, try to clone everything in it.\n"), progname, runtime_options.dest_dir); } /* Connection parameters for master only */ keywords[0] = "host"; values[0] = runtime_options.host; keywords[1] = "port"; values[1] = runtime_options.masterport; /* We need to connect to check configuration and start a backup */ log_info(_("%s connecting to master database\n"), progname); conn = establishDBConnectionByParams(keywords,values,true); /* primary should be v9 or better */ log_info(_("%s connected to master, checking its state\n"), progname); pg_version(conn, master_version); if (strcmp(master_version, "") == 0) { PQfinish(conn); log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname); exit(ERR_BAD_CONFIG); } /* Check we are cloning a primary node */ if (is_standby(conn)) { PQfinish(conn); log_err(_("\nThe command should clone a primary node\n")); exit(ERR_BAD_CONFIG); } /* And check if it is well configured */ if (!guc_setted(conn, "wal_level", "=", "hot_standby")) { PQfinish(conn); log_err(_("%s needs parameter 'wal_level' to be set to 'hot_standby'\n"), progname); exit(ERR_BAD_CONFIG); } if (!guc_setted_typed(conn, "wal_keep_segments", ">=", runtime_options.wal_keep_segments, "integer")) { PQfinish(conn); log_err(_("%s needs parameter 'wal_keep_segments' to be set to %s or greater (see the '-w' option or edit the postgresql.conf of the PostgreSQL master.)\n"), progname, runtime_options.wal_keep_segments); exit(ERR_BAD_CONFIG); } if (!guc_setted(conn, "archive_mode", "=", "on")) { PQfinish(conn); log_err(_("%s needs parameter 'archive_mode' to be set to 'on'\n"), progname); exit(ERR_BAD_CONFIG); } if (!guc_setted(conn, "hot_standby", "=", "on")) { PQfinish(conn); log_err(_("%s needs parameter 'hot_standby' to be set to 'on'\n"), progname); exit(ERR_BAD_CONFIG); } /* * Check if the tablespace locations exists and that we can write to * them. */ if (strcmp(master_version, "9.0") == 0 || strcmp(master_version, "9.1") == 0) sqlquery_snprintf(sqlquery, "SELECT spclocation " " FROM pg_tablespace " "WHERE spcname NOT IN ('pg_default', 'pg_global')"); else sqlquery_snprintf(sqlquery, "SELECT pg_tablespace_location(oid) spclocation " " FROM pg_tablespace " "WHERE spcname NOT IN ('pg_default', 'pg_global')"); log_debug("standby clone: %s\n", sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about tablespaces: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } for (i = 0; i < PQntuples(res); i++) { if (test_mode) { log_err("Can't clone in test mode when master have tablespace\n"); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } strncpy(tblspc_dir, PQgetvalue(res, i, 0), MAXFILENAME); /* * Check this directory could be used for tablespace * this will create the directory a bit too early * XXX build an array of tablespace to create later in the backup */ if (!create_pgdir(tblspc_dir, runtime_options.force)) { PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } } PQclear(res); /* Get the data directory full path and the configuration files location */ sqlquery_snprintf(sqlquery, "SELECT name, setting " " FROM pg_settings " " WHERE name IN ('data_directory', 'config_file', 'hba_file', 'ident_file', 'stats_temp_directory')"); log_debug(_("standby clone: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about data directory and configuration files: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* We need all 5 parameters, and they can be retrieved only by superusers */ if (PQntuples(res) != 5) { log_err("%s: STANDBY CLONE should be run by a SUPERUSER\n", progname); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } for (i = 0; i < PQntuples(res); i++) { if (strcmp(PQgetvalue(res, i, 0), "data_directory") == 0) strncpy(master_data_directory, PQgetvalue(res, i, 1), MAXFILENAME); else if (strcmp(PQgetvalue(res, i, 0), "config_file") == 0) strncpy(master_config_file, PQgetvalue(res, i, 1), MAXFILENAME); else if (strcmp(PQgetvalue(res, i, 0), "hba_file") == 0) strncpy(master_hba_file, PQgetvalue(res, i, 1), MAXFILENAME); else if (strcmp(PQgetvalue(res, i, 0), "ident_file") == 0) strncpy(master_ident_file, PQgetvalue(res, i, 1), MAXFILENAME); else if (strcmp(PQgetvalue(res, i, 0), "stats_temp_directory") == 0) strncpy(master_stats_temp_directory, PQgetvalue(res, i, 1), MAXFILENAME); else log_warning(_("unknown parameter: %s\n"), PQgetvalue(res, i, 0)); } PQclear(res); log_info(_("Successfully connected to primary. Current installation size is %s\n"), get_cluster_size(conn)); /* * XXX master_xlog_directory should be discovered from master configuration * but it is not possible via SQL. We need to use a command via ssh */ maxlen_snprintf(master_xlog_directory, "%s/pg_xlog", master_data_directory); if (test_mode) { strncpy(local_data_directory, runtime_options.dest_dir, MAXFILENAME); strncpy(local_config_file, runtime_options.dest_dir, MAXFILENAME); strncpy(local_hba_file, runtime_options.dest_dir, MAXFILENAME); strncpy(local_ident_file, runtime_options.dest_dir, MAXFILENAME); maxlen_snprintf(local_stats_temp_directory, "%s/pg_stat_tmp", runtime_options.dest_dir); maxlen_snprintf(local_xlog_directory, "%s/pg_xlog", runtime_options.dest_dir); } else { strncpy(local_data_directory, master_data_directory, MAXFILENAME); strncpy(local_config_file, master_config_file, MAXFILENAME); strncpy(local_hba_file, master_hba_file, MAXFILENAME); strncpy(local_ident_file, master_ident_file, MAXFILENAME); strncpy(local_stats_temp_directory, master_stats_temp_directory, MAXFILENAME); strncpy(local_xlog_directory, master_xlog_directory, MAXFILENAME); } r = test_ssh_connection(runtime_options.host, runtime_options.remote_user); if (r != 0) { log_err(_("%s: Aborting, remote host %s is not reachable.\n"), progname, runtime_options.host); PQfinish(conn); exit(ERR_BAD_SSH); } log_notice(_("Starting backup...\n")); /* * in pg 9.1 default is to wait for a sync standby to ack, * avoid that by turning off sync rep for this session */ sqlquery_snprintf(sqlquery, "SET synchronous_commit TO OFF"); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_err("Can't set synchronous_commit: %s\n", PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* * inform the master we will start a backup and get the first XLog filename * so we can say to the user we need those files */ sqlquery_snprintf( sqlquery, "SELECT pg_xlogfile_name(pg_start_backup('repmgr_standby_clone_%ld'))", time(NULL)); log_debug(_("standby clone: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't start backup: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } if (runtime_options.verbose) { char *first_wal_seg_pq = PQgetvalue(res, 0, 0); size_t buf_sz = strlen(first_wal_seg_pq); first_wal_segment = malloc(buf_sz + 1); xsnprintf(first_wal_segment, buf_sz + 1, "%s", first_wal_seg_pq); } PQclear(res); /* Check the directory could be used as a PGDATA dir */ if (!create_pgdir(local_data_directory, runtime_options.force)) { log_err(_("%s: couldn't use directory %s ...\nUse --force option to force\n"), progname, local_data_directory); goto stop_backup; } /* * 1) first move global/pg_control * * 2) then move data_directory ommiting the files we have already moved and * pg_xlog content * * 3) finally We need to backup configuration files (that could be on other * directories, debian like systems likes to do that), so look at * config_file, hba_file and ident_file but we can omit * external_pid_file ;) * * On error we need to return but before that execute pg_stop_backup() */ /* need to create the global sub directory */ maxlen_snprintf(master_control_file, "%s/global/pg_control", master_data_directory); maxlen_snprintf(local_control_file, "%s/global", local_data_directory); log_info(_("standby clone: master control file '%s'\n"), master_control_file); if (!create_directory(local_control_file)) { log_err(_("%s: couldn't create directory %s ...\n"), progname, local_control_file); goto stop_backup; } log_info(_("standby clone: master control file '%s'\n"), master_control_file); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, master_control_file, local_control_file, false); if (r != 0) { log_warning(_("standby clone: failed copying master control file '%s'\n"), master_control_file); goto stop_backup; } log_info(_("standby clone: master data directory '%s'\n"), master_data_directory); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, master_data_directory, local_data_directory, true); if (r != 0) { log_warning(_("standby clone: failed copying master data directory '%s'\n"), master_data_directory); goto stop_backup; } /* * Copy tablespace locations, i'm doing this separately because i couldn't * find and appropiate rsync option but besides we could someday make all * these rsync happen concurrently * XXX We may not do that if we are in test_mode but it does not hurt too much * (except if a tablespace is created during the test) */ if (strcmp(master_version, "9.0") == 0 || strcmp(master_version, "9.1") == 0) sqlquery_snprintf(sqlquery, "SELECT spclocation " " FROM pg_tablespace " " WHERE spcname NOT IN ('pg_default', 'pg_global')"); else sqlquery_snprintf(sqlquery, "SELECT pg_tablespace_location(oid) spclocation " " FROM pg_tablespace " " WHERE spcname NOT IN ('pg_default', 'pg_global')"); log_debug("standby clone: %s\n", sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about tablespaces: %s\n"), PQerrorMessage(conn)); PQclear(res); goto stop_backup; } for (i = 0; i < PQntuples(res); i++) { strncpy(tblspc_dir, PQgetvalue(res, i, 0), MAXFILENAME); log_info(_("standby clone: master tablespace '%s'\n"), tblspc_dir); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, tblspc_dir, tblspc_dir, true); if (r != 0) { log_warning(_("standby clone: failed copying tablespace directory '%s'\n"), tblspc_dir); PQclear(res); goto stop_backup; } } PQclear(res); log_info(_("standby clone: master config file '%s'\n"), master_config_file); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, master_config_file, local_config_file, false); if (r != 0) { log_warning(_("standby clone: failed copying master config file '%s'\n"), master_config_file); goto stop_backup; } log_info(_("standby clone: master hba file '%s'\n"), master_hba_file); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, master_hba_file, local_hba_file, false); if (r != 0) { log_warning(_("standby clone: failed copying master hba file '%s'\n"), master_hba_file); goto stop_backup; } log_info(_("standby clone: master ident file '%s'\n"), master_ident_file); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, master_ident_file, local_ident_file, false); if (r != 0) { log_warning(_("standby clone: failed copying master ident file '%s'\n"), master_ident_file); goto stop_backup; } /* we success so far, flag that to allow a better HINT */ flag_success = true; stop_backup: /* * Inform the master that we have finished the backup. */ log_notice(_("Finishing backup...\n")); sqlquery_snprintf(sqlquery, "SELECT pg_xlogfile_name(pg_stop_backup())"); log_debug(_("standby clone: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't stop backup: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_STOP_BACKUP); } last_wal_segment = PQgetvalue(res, 0, 0); if (runtime_options.verbose) log_info(_("%s requires primary to keep WAL files %s until at least %s\n"), progname, first_wal_segment, last_wal_segment); /* Finished with the database connection now */ PQclear(res); PQfinish(conn); /* * Only free the first_wal_segment since it was copied out of the * pqresult. */ free(first_wal_segment); first_wal_segment = NULL; /* If the rsync failed then exit */ if (r != 0) { log_err(_("Couldn't rsync the master...\nYou have to cleanup the destination directory (%s) manually!\n"), local_data_directory); exit(ERR_BAD_RSYNC); } /* * We need to create the pg_xlog sub directory too. */ if (!create_directory(local_xlog_directory)) { log_err(_("%s: couldn't create directory %s, you will need to do it manually...\n"), progname, local_xlog_directory); r = ERR_NEEDS_XLOG; /* continue, but eventually exit returning error */ } /* Finally, write the recovery.conf file */ create_recovery_file(local_data_directory); /* * We don't start the service yet because we still may want to * move the directory */ log_notice(_("%s standby clone complete\n"), progname); /* HINT message : what to do next ? */ if (flag_success) { log_notice("HINT: You can now start your postgresql server\n"); if (test_mode) { log_notice(_("for example : pg_ctl -D %s start\n"), local_data_directory); } else { log_notice("for example : /etc/init.d/postgresql start\n"); } } exit(r); } static void do_standby_promote(void) { PGconn *conn; PGresult *res; char sqlquery[QUERY_STR_LEN]; char script[MAXLEN]; PGconn *old_master_conn; int old_master_id; int r; char data_dir[MAXLEN]; char recovery_file_path[MAXFILENAME]; char recovery_done_path[MAXFILENAME]; char standby_version[MAXVERSIONSTR]; /* We need to connect to check configuration */ log_info(_("%s connecting to master database\n"), progname); conn = establishDBConnection(options.conninfo, true); /* we need v9 or better */ log_info(_("%s connected to master, checking its state\n"), progname); pg_version(conn, standby_version); if (strcmp(standby_version, "") == 0) { log_err(_("%s needs standby to be PostgreSQL 9.0 or better\n"), progname); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* Check we are in a standby node */ if (!is_standby(conn)) { log_err(_("%s: The command should be executed on a standby node\n"), progname); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* we also need to check if there isn't any master already */ old_master_conn = getMasterConnection(conn, repmgr_schema, options.cluster_name, &old_master_id, NULL); if (old_master_conn != NULL) { log_err(_("There is a master already in this cluster\n")); PQfinish(old_master_conn); PQfinish(conn); exit(ERR_BAD_CONFIG); } log_notice(_("%s: Promoting standby\n"), progname); /* Get the data directory full path and the last subdirectory */ sqlquery_snprintf(sqlquery, "SELECT setting " " FROM pg_settings WHERE name = 'data_directory'"); log_debug(_("standby promote: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about data directory: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } strcpy(data_dir, PQgetvalue(res, 0, 0)); PQclear(res); PQfinish(conn); log_info(_("%s: Marking recovery done\n"), progname); maxlen_snprintf(recovery_file_path, "%s/%s", data_dir, RECOVERY_FILE); maxlen_snprintf(recovery_done_path, "%s/%s", data_dir, RECOVERY_DONE_FILE); rename(recovery_file_path, recovery_done_path); /* * We assume the pg_ctl script is in the PATH. Restart and wait for * the server to finish starting, so that the check below will * find an active server rather than one starting up. This may * hang for up the default timeout (60 seconds). */ log_notice(_("%s: restarting server using pg_ctl\n"), progname); maxlen_snprintf(script, "pg_ctl -D %s -w -m fast restart", data_dir); r = system(script); if (r != 0) { log_err(_("Can't restart PostgreSQL server\n")); exit(ERR_NO_RESTART); } /* reconnect to check we got promoted */ log_info(_("%s connecting to now restarted database\n"), progname); conn = establishDBConnection(options.conninfo, true); if (is_standby(conn)) { log_err(_("\n%s: STANDBY PROMOTE failed, this is still a standby node.\n"), progname); } else { log_err(_("\n%s: STANDBY PROMOTE successful. You should REINDEX any hash indexes you have.\n"), progname); } PQfinish(conn); return; } static void do_standby_follow(void) { PGconn *conn; PGresult *res; char sqlquery[QUERY_STR_LEN]; char script[MAXLEN]; char master_conninfo[MAXLEN]; PGconn *master_conn; int master_id; int r; char data_dir[MAXLEN]; char master_version[MAXVERSIONSTR]; char standby_version[MAXVERSIONSTR]; /* We need to connect to check configuration */ log_info(_("%s connecting to standby database\n"), progname); conn = establishDBConnection(options.conninfo, true); /* Check we are in a standby node */ log_info(_("%s connected to standby, checking its state\n"), progname); if (!is_standby(conn)) { log_err(_("\n%s: The command should be executed in a standby node\n"), progname); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* should be v9 or better */ pg_version(conn, standby_version); if (strcmp(standby_version, "") == 0) { log_err(_("\n%s needs standby to be PostgreSQL 9.0 or better\n"), progname); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* * we also need to check if there is any master in the cluster * or wait for one to appear if we have set the wait option */ log_info(_("%s discovering new master...\n"), progname); do { master_conn = getMasterConnection(conn, repmgr_schema, options.cluster_name, &master_id,(char *) &master_conninfo); } while (master_conn == NULL && runtime_options.wait_for_master); if (master_conn == NULL) { log_err(_("There isn't a master to follow in this cluster\n")); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* Check we are going to point to a master */ if (is_standby(master_conn)) { log_err(_("%s: The node to follow should be a master\n"), progname); PQfinish(conn); PQfinish(master_conn); exit(ERR_BAD_CONFIG); } /* should be v9 or better */ log_info(_("%s connected to master, checking its state\n"), progname); pg_version(master_conn, master_version); if (strcmp(master_version, "") == 0) { log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname); PQfinish(conn); PQfinish(master_conn); exit(ERR_BAD_CONFIG); } /* master and standby version should match */ if (strcmp(master_version, standby_version) != 0) { log_err(_("%s needs versions of both master (%s) and standby (%s) to match.\n"), progname, master_version, standby_version); PQfinish(conn); PQfinish(master_conn); exit(ERR_BAD_CONFIG); } /* * set the host and masterport variables with the master ones * before closing the connection because we will need them to * recreate the recovery.conf file */ strncpy(runtime_options.host, PQhost(master_conn), MAXLEN); strncpy(runtime_options.masterport, PQport(master_conn), MAXLEN); PQfinish(master_conn); log_info(_("%s Changing standby's master"),progname); /* Get the data directory full path */ sqlquery_snprintf(sqlquery, "SELECT setting " " FROM pg_settings WHERE name = 'data_directory'"); log_debug(_("standby follow: %s\n"), sqlquery); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about data directory: %s\n"), PQerrorMessage(conn)); PQclear(res); PQfinish(conn); exit(ERR_BAD_CONFIG); } strcpy(data_dir, PQgetvalue(res, 0, 0)); PQclear(res); PQfinish(conn); /* write the recovery.conf file */ if (!create_recovery_file(data_dir)) exit(ERR_BAD_CONFIG); /* Finally, restart the service */ /* We assume the pg_ctl script is in the PATH */ maxlen_snprintf(script, "pg_ctl -w -D %s -m fast restart", data_dir); r = system(script); if (r != 0) { log_err(_("Can't restart service\n")); exit(ERR_NO_RESTART); } return; } static void do_witness_create(void) { PGconn *masterconn; PGconn *witnessconn; PGresult *res; char sqlquery[QUERY_STR_LEN]; char script[MAXLEN]; char buf[MAXLEN]; FILE *pg_conf = NULL; int r = 0; int i; char master_version[MAXVERSIONSTR]; char master_hba_file[MAXLEN]; /* Check this directory could be used as a PGDATA dir */ if (!create_pgdir(runtime_options.dest_dir, runtime_options.force)) { log_err(_("witness create: couldn't create data directory (\"%s\") for witness"), runtime_options.dest_dir); exit(ERR_BAD_CONFIG); } /* Connection parameters for master only */ keywords[0] = "host"; values[0] = runtime_options.host; keywords[1] = "port"; values[1] = runtime_options.masterport; /* We need to connect to check configuration and copy it */ masterconn = establishDBConnectionByParams(keywords, values, true); if (!masterconn) { log_err(_("%s: could not connect to master\n"), progname); exit(ERR_DB_CON); } /* primary should be v9 or better */ pg_version(masterconn, master_version); if (strcmp(master_version, "") == 0) { log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname); PQfinish(masterconn); exit(ERR_BAD_CONFIG); } /* Check we are connecting to a primary node */ if (is_standby(masterconn)) { log_err(_("The command should not run on a standby node\n")); PQfinish(masterconn); exit(ERR_BAD_CONFIG); } log_info(_("Successfully connected to primary.\n")); r = test_ssh_connection(runtime_options.host, runtime_options.remote_user); if (r != 0) { log_err(_("%s: Aborting, remote host %s is not reachable.\n"), progname, runtime_options.host); PQfinish(masterconn); exit(ERR_BAD_SSH); } /* * To create a witness server we need to: * 1) initialize the cluster * 2) register the witness in repl_nodes * 3) copy configuration from master */ /* Create the cluster for witness */ /* We assume the pg_ctl script is in the PATH */ sprintf(script, "pg_ctl -D %s init -o \"-W\"", runtime_options.dest_dir); log_info("Initialize cluster for witness: %s.\n", script); r = system(script); if (r != 0) { log_err("Can't iniatialize cluster for witness server\n"); PQfinish(masterconn); exit(ERR_BAD_CONFIG); } /* * default port for the witness is 5499, * but user can provide a different one */ snprintf(buf, sizeof(buf), "%s/postgresql.conf", runtime_options.dest_dir); pg_conf = fopen(buf, "a"); if (pg_conf == NULL) { log_err(_("\n%s: could not open \"%s\" for adding extra config: %s\n"), progname, buf, strerror(errno)); PQfinish(masterconn); exit(ERR_BAD_CONFIG); } snprintf(buf, sizeof(buf), "\n#Configuration added by %s\n", progname); fputs(buf, pg_conf); if (!runtime_options.localport[0]) strncpy(runtime_options.localport, "5499", MAXLEN); snprintf(buf, sizeof(buf), "port = %s\n", runtime_options.localport); fputs(buf, pg_conf); snprintf(buf, sizeof(buf), "shared_preload_libraries = 'repmgr_funcs'\n") ; fputs(buf, pg_conf); snprintf(buf, sizeof(buf), "listen_addresses = '*'\n") ; fputs(buf, pg_conf); fclose(pg_conf); /* Get the pg_hba.conf full path */ sqlquery_snprintf(sqlquery, "SELECT name, setting " " FROM pg_settings " " WHERE name IN ('hba_file')"); log_debug(_("witness create: %s"), sqlquery); res = PQexec(masterconn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get info about pg_hba.conf: %s\n"), PQerrorMessage(masterconn)); PQclear(res); PQfinish(masterconn); exit(ERR_DB_QUERY); } for (i = 0; i < PQntuples(res); i++) { if (strcmp(PQgetvalue(res, i, 0), "hba_file") == 0) strcpy(master_hba_file, PQgetvalue(res, i, 1)); else log_err(_("uknown parameter: %s"), PQgetvalue(res, i, 0)); } PQclear(res); r = copy_remote_files(runtime_options.host, runtime_options.remote_user, master_hba_file, runtime_options.dest_dir, false); if (r != 0) { log_err(_("Can't rsync the pg_hba.conf file from master\n")); PQfinish(masterconn); exit(ERR_BAD_CONFIG); } /* start new instance */ sprintf(script, "pg_ctl -w -D %s start", runtime_options.dest_dir); log_info(_("Start cluster for witness: %s"), script); r = system(script); if (r != 0) { log_err(_("Can't start cluster for witness server\n")); PQfinish(masterconn); exit(ERR_BAD_CONFIG); } /* register ourselves in the master */ sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes(id, cluster, name, conninfo, priority, witness) " "VALUES (%d, '%s', '%s', '%s', %d, true)", repmgr_schema, options.node, options.cluster_name, options.node_name, options.conninfo); log_debug(_("witness create: %s"), sqlquery); if (!PQexec(masterconn, sqlquery)) { log_err(_("Cannot insert node details, %s\n"), PQerrorMessage(masterconn)); PQfinish(masterconn); exit(ERR_DB_QUERY); } /* establish a connection to the witness, and create the schema */ witnessconn = establishDBConnection(options.conninfo, true); log_info(_("Starting copy of configuration from master...\n")); if (!create_schema(witnessconn)) { PQfinish(masterconn); PQfinish(witnessconn); exit(ERR_BAD_CONFIG); } /* copy configuration from master, only repl_nodes is needed */ if (!copy_configuration(masterconn, witnessconn)) { PQfinish(masterconn); PQfinish(witnessconn); exit(ERR_BAD_CONFIG); } PQfinish(masterconn); PQfinish(witnessconn); log_notice(_("Configuration has been successfully copied to the witness\n")); } static void usage(void) { log_err(_("\n\n%s: Replicator manager \n"), progname); log_err(_("Try \"%s --help\" for more information.\n"), progname); } static void help(const char *progname) { printf(_("\n%s: Replicator manager \n"), progname); printf(_("Usage:\n")); printf(_(" %s [OPTIONS] master {register}\n"), progname); printf(_(" %s [OPTIONS] standby {register|clone|promote|follow}\n"), progname); printf(_(" %s [OPTIONS] cluster {show|cleanup}\n"), progname); printf(_("\nGeneral options:\n")); printf(_(" --help show this help, then exit\n")); printf(_(" --version output version information, then exit\n")); printf(_(" --verbose output verbose activity information\n")); printf(_("\nConnection options:\n")); printf(_(" -d, --dbname=DBNAME database to connect to\n")); printf(_(" -h, --host=HOSTNAME database server host or socket directory\n")); printf(_(" -p, --port=PORT database server port\n")); printf(_(" -U, --username=USERNAME database user name to connect as\n")); printf(_("\nConfiguration options:\n")); printf(_(" -D, --data-dir=DIR local directory where the files will be copied to\n")); printf(_(" -l, --local-port=PORT standby or witness server local port\n")); printf(_(" -f, --config_file=PATH path to the configuration file\n")); printf(_(" -R, --remote-user=USERNAME database server username for rsync\n")); printf(_(" -w, --wal-keep-segments=VALUE minimum value for the GUC wal_keep_segments (default: 5000)\n")); printf(_(" -I, --ignore-rsync-warning ignore rsync partial transfer warning\n")); printf(_(" -k, --keep-history=VALUE keeps indicated number of days of history\n")); printf(_(" -F, --force force potentially dangerous operations to happen\n")); printf(_(" -W, --wait wait for a master to appear")); printf(_("\n%s performs some tasks like clone a node, promote it "), progname); printf(_("or making follow another node and then exits.\n")); printf(_("COMMANDS:\n")); printf(_(" master register - registers the master in a cluster\n")); printf(_(" standby register - registers a standby in a cluster\n")); printf(_(" standby clone [node] - allows creation of a new standby\n")); printf(_(" standby promote - allows manual promotion of a specific standby into a ")); printf(_("new master in the event of a failover\n")); printf(_(" standby follow - allows the standby to re-point itself to a new master\n")); printf(_(" cluster show - print node information\n")); printf(_(" cluster cleanup - cleans monitor's history\n")); } /* * Creates a recovery file for a standby. */ static bool create_recovery_file(const char *data_dir) { FILE *recovery_file; char recovery_file_path[MAXLEN]; char line[MAXLEN]; maxlen_snprintf(recovery_file_path, "%s/%s", data_dir, RECOVERY_FILE); recovery_file = fopen(recovery_file_path, "w"); if (recovery_file == NULL) { log_err(_("could not create recovery.conf file, it could be necessary to create it manually\n")); return false; } maxlen_snprintf(line, "standby_mode = 'on'\n"); if (fputs(line, recovery_file) == EOF) { log_err(_("recovery file could not be written, it could be necessary to create it manually\n")); fclose(recovery_file); return false; } write_primary_conninfo(line); if (fputs(line, recovery_file) == EOF) { log_err(_("recovery file could not be written, it could be necessary to create it manually\n")); fclose(recovery_file); return false; } /*FreeFile(recovery_file);*/ fclose(recovery_file); return true; } static int test_ssh_connection(char *host, char *remote_user) { char script[MAXLEN]; int r; /* On some OS, true is located in a different place than in Linux */ #ifdef __FreeBSD__ #define TRUEBIN_PATH "/usr/bin/true" #else #define TRUEBIN_PATH "/bin/true" #endif /* Check if we have ssh connectivity to host before trying to rsync */ if (!remote_user[0]) maxlen_snprintf(script, "ssh -o Batchmode=yes %s %s %s", options.ssh_options, host, TRUEBIN_PATH); else maxlen_snprintf(script, "ssh -o Batchmode=yes %s %s -l %s %s", options.ssh_options, host, remote_user, TRUEBIN_PATH); log_debug(_("command is: %s"), script); r = system(script); if (r != 0) log_info(_("Can not connect to the remote host (%s)\n"), host); return r; } static int copy_remote_files(char *host, char *remote_user, char *remote_path, char *local_path, bool is_directory) { char script[MAXLEN]; char rsync_flags[MAXLEN]; char host_string[MAXLEN]; int r; if (strnlen(options.rsync_options, MAXLEN) == 0) maxlen_snprintf( rsync_flags, "%s", "--archive --checksum --compress --progress --rsh=ssh"); else maxlen_snprintf(rsync_flags, "%s", options.rsync_options); if (runtime_options.force) strcat(rsync_flags, " --delete"); if (!remote_user[0]) { maxlen_snprintf(host_string, "%s", host); } else { maxlen_snprintf(host_string,"%s@%s",remote_user,host); } if (is_directory) { strcat(rsync_flags, " --exclude=pg_xlog* --exclude=pg_log* --exclude=pg_control --exclude=*.pid"); maxlen_snprintf(script, "rsync %s %s:%s/* %s", rsync_flags, host_string, remote_path, local_path); } else { maxlen_snprintf(script, "rsync %s %s:%s %s", rsync_flags, host_string, remote_path, local_path); } log_info(_("rsync command line: '%s'\n"), script); r = system(script); /* * If we are transfering a directory (data directory, tablespace directories) * then we can ignore some rsync warnings. If we get some of those errors, we * treat them as 0 only if passed the --ignore-rsync-warning command-line option. * * List of ignorable rsync errors: * 24 Partial transfer due to vanished source files */ if ((WEXITSTATUS(r) == 24) && is_directory) { if (runtime_options.ignore_rsync_warn) { r = 0; log_info(_("rsync partial transfer warning ignored\n")); } else log_warning( _("\nrsync completed with return code 24: " "\"Partial transfer due to vanished source files\".\n" "This can happen because of normal operation " "on the master server, but it may indicate an " "unexpected change during cloning. If you are certain " "no changes were made to the master, try cloning " "again using \"repmgr --force --ignore-rsync-warning\".")); } if (r != 0) log_err(_("Can't rsync from remote file or directory (%s:%s)\n"), host_string, remote_path); return r; } /* * Tries to avoid useless or conflicting parameters */ static bool check_parameters_for_action(const int action) { bool ok = true; switch (action) { case MASTER_REGISTER: /* * To register a master we only need the repmgr.conf * all other parameters are at least useless and could be * confusing so reject them */ if (runtime_options.host[0] || runtime_options.masterport[0] || runtime_options.username[0] || runtime_options.dbname[0]) { log_err(_("You can't use connection parameters to the master when issuing a MASTER REGISTER command.\n")); usage(); ok = false; } if (runtime_options.dest_dir[0]) { log_err(_("You don't need a destination directory for MASTER REGISTER command\n")); usage(); ok = false; } break; case STANDBY_REGISTER: /* * To register a standby we only need the repmgr.conf * we don't need connection parameters to the master * because we can detect the master in repl_nodes */ if (runtime_options.host[0] || runtime_options.masterport[0] || runtime_options.username[0] || runtime_options.dbname[0]) { log_err(_("You can't use connection parameters to the master when issuing a STANDBY REGISTER command.\n")); usage(); ok = false; } if (runtime_options.dest_dir[0]) { log_err(_("You don't need a destination directory for STANDBY REGISTER command\n")); usage(); ok = false; } break; case STANDBY_PROMOTE: /* * To promote a standby we only need the repmgr.conf * we don't want connection parameters to the master * because we will try to detect the master in repl_nodes * if we can't find it then the promote action will be cancelled */ if (runtime_options.host[0] || runtime_options.masterport[0] || runtime_options.username[0] || runtime_options.dbname[0]) { log_err(_("You can't use connection parameters to the master when issuing a STANDBY PROMOTE command.\n")); usage(); ok = false; } if (runtime_options.dest_dir[0]) { log_err(_("You don't need a destination directory for STANDBY PROMOTE command\n")); usage(); ok = false; } break; case STANDBY_FOLLOW: /* * To make a standby follow a master we only need the repmgr.conf * we don't want connection parameters to the new master * because we will try to detect the master in repl_nodes * if we can't find it then the follow action will be cancelled */ if (runtime_options.host[0] || runtime_options.masterport[0] || runtime_options.username[0] || runtime_options.dbname[0]) { log_err(_("You can't use connection parameters to the master when issuing a STANDBY FOLLOW command.\n")); usage(); ok = false; } if (runtime_options.dest_dir[0]) { log_err(_("You don't need a destination directory for STANDBY FOLLOW command\n")); usage(); ok = false; } break; case STANDBY_CLONE: /* * Issue a friendly notice that the configuration file is not * necessary nor read at all in when performing a STANDBY CLONE * action. */ if (runtime_options.config_file[0]) { log_notice(_("Only command line parameters for the connection " "to the master are used when issuing a STANDBY CLONE command. " "The passed configuration file is neither required nor used for " "its node configuration portions\n\n")); } /* * To clone a master into a standby we need connection parameters * repmgr.conf is useless because we don't have a server running in * the standby; warn the user, but keep going. */ if (runtime_options.host == NULL) { log_notice(_("You need to use connection parameters to " "the master when issuing a STANDBY CLONE command.")); ok = false; } need_a_node = false; break; case WITNESS_CREATE: /* allow all parameters to be supplied */ break; case CLUSTER_SHOW: /* allow all parameters to be supplied */ break; case CLUSTER_CLEANUP: /* allow all parameters to be supplied */ break; } return ok; } static bool create_schema(PGconn *conn) { char sqlquery[QUERY_STR_LEN]; sqlquery_snprintf(sqlquery, "CREATE SCHEMA %s", repmgr_schema); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_err(_("Cannot create the schema %s: %s\n"), repmgr_schema, PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* ... the tables */ sqlquery_snprintf(sqlquery, "CREATE TABLE %s.repl_nodes ( " " id integer primary key, " " cluster text not null, " " name text not null, " " conninfo text not null, " " priority integer not null, " " witness boolean not null default false)", repmgr_schema); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_err(_("Cannot create the table %s.repl_nodes: %s\n"), repmgr_schema, PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } sqlquery_snprintf(sqlquery, "CREATE TABLE %s.repl_monitor ( " " primary_node INTEGER NOT NULL, " " standby_node INTEGER NOT NULL, " " last_monitor_time TIMESTAMP WITH TIME ZONE NOT NULL, " " last_wal_primary_location TEXT NOT NULL, " " last_wal_standby_location TEXT, " " replication_lag BIGINT NOT NULL, " " apply_lag BIGINT NOT NULL) ", repmgr_schema); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_err(_("Cannot create the table %s.repl_monitor: %s\n"), repmgr_schema, PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* a view */ sqlquery_snprintf(sqlquery, "CREATE VIEW %s.repl_status AS " " SELECT primary_node, standby_node, name AS standby_name, last_monitor_time, " " last_wal_primary_location, last_wal_standby_location, " " pg_size_pretty(replication_lag) replication_lag, " " pg_size_pretty(apply_lag) apply_lag, " " age(now(), last_monitor_time) AS time_lag " " FROM %s.repl_monitor JOIN %s.repl_nodes ON standby_node = id " " WHERE (standby_node, last_monitor_time) IN (SELECT standby_node, MAX(last_monitor_time) " " FROM %s.repl_monitor GROUP BY 1)", repmgr_schema, repmgr_schema, repmgr_schema, repmgr_schema); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_err(_("Cannot create the view %s.repl_status: %s\n"), repmgr_schema, PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* an index to improve performance of the view */ sqlquery_snprintf(sqlquery, "CREATE INDEX idx_repl_status_sort " " ON %s.repl_monitor (last_monitor_time, standby_node) ", repmgr_schema); log_debug(_("master register: %s\n"), sqlquery); if (!PQexec(conn, sqlquery)) { log_err(_("Cannot indexing table %s.repl_monitor: %s\n"), repmgr_schema, PQerrorMessage(conn)); PQfinish(conn); exit(ERR_BAD_CONFIG); } /* XXX Here we MUST try to load the repmgr_function.sql not hardcode it here */ sqlquery_snprintf(sqlquery, "CREATE OR REPLACE FUNCTION %s.repmgr_update_standby_location(text) RETURNS boolean " "AS '$libdir/repmgr_funcs', 'repmgr_update_standby_location' " "LANGUAGE C STRICT ", repmgr_schema); if (!PQexec(conn, sqlquery)) { fprintf(stderr, "Cannot create the function repmgr_update_standby_location: %s\n", PQerrorMessage(conn)); return false; } sqlquery_snprintf(sqlquery, "CREATE OR REPLACE FUNCTION %s.repmgr_get_last_standby_location() RETURNS text " "AS '$libdir/repmgr_funcs', 'repmgr_get_last_standby_location' " "LANGUAGE C STRICT ", repmgr_schema); if (!PQexec(conn, sqlquery)) { fprintf(stderr, "Cannot create the function repmgr_get_last_standby_location: %s\n", PQerrorMessage(conn)); return false; } return true; } static bool copy_configuration(PGconn *masterconn, PGconn *witnessconn) { char sqlquery[MAXLEN]; PGresult *res; int i; sqlquery_snprintf(sqlquery, "TRUNCATE TABLE %s.repl_nodes", repmgr_schema); log_debug("copy_configuration: %s\n", sqlquery); if (!PQexec(witnessconn, sqlquery)) { fprintf(stderr, "Cannot clean node details in the witness, %s\n", PQerrorMessage(witnessconn)); return false; } sqlquery_snprintf(sqlquery, "SELECT id, name, conninfo, priority, witness FROM %s.repl_nodes", repmgr_schema); res = PQexec(masterconn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "Can't get configuration from master: %s\n", PQerrorMessage(masterconn)); PQclear(res); return false; } for (i = 0; i < PQntuples(res); i++) { sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes(id, cluster, name, conninfo, priority, witness) " "VALUES (%d, '%s', '%s', '%s', %d, '%s')", repmgr_schema, atoi(PQgetvalue(res, i, 0)), options.cluster_name, PQgetvalue(res, i, 1), PQgetvalue(res, i, 2), atoi(PQgetvalue(res, i, 3)), PQgetvalue(res, i, 4)); if (!PQexec(witnessconn, sqlquery)) { fprintf(stderr, "Cannot copy configuration to witness, %s\n", PQerrorMessage(witnessconn)); PQclear(res); return false; } } return true; } /* This function uses global variables to determine connection settings. Special * usage of the PGPASSWORD variable is handled, but strongly discouraged */ static void write_primary_conninfo(char* line) { char host_buf[MAXLEN] = ""; char conn_buf[MAXLEN] = ""; char user_buf[MAXLEN] = ""; char appname_buf[MAXLEN] = ""; char password_buf[MAXLEN] = ""; /* Environment variable for password (UGLY, please use .pgpass!) */ const char *password = getenv("PGPASSWORD"); if (password != NULL) { maxlen_snprintf(password_buf, " password=%s", password); } else if (require_password) { log_err(_("%s: PGPASSWORD not set, but having one is required\n"), progname); exit(ERR_BAD_PASSWORD); } if (runtime_options.host[0]) { maxlen_snprintf(host_buf, " host=%s", runtime_options.host); } if (runtime_options.username[0]) { maxlen_snprintf(user_buf, " user=%s", runtime_options.username); } if (options.node_name[0]) { maxlen_snprintf(appname_buf, " application_name=%s", options.node_name); } maxlen_snprintf(conn_buf, "port=%s%s%s%s%s", (runtime_options.masterport[0]) ? runtime_options.masterport : "5432", host_buf, user_buf, password_buf, appname_buf); maxlen_snprintf(line, "primary_conninfo = '%s'", conn_buf); } repmgr-2.0beta2/repmgr.conf.sample000066400000000000000000000021261225461504400172140ustar00rootroot00000000000000################################################### # Replication Manager configuration file ################################################### # Cluster name cluster=test # Node ID node=2 node_name=standby2 # Connection information conninfo='host=192.168.204.104' rsync_options=--archive --checksum --compress --progress --rsh="ssh -o \"StrictHostKeyChecking no\"" ssh_options=-o "StrictHostKeyChecking no" # How many seconds we wait for master response before declaring master failure master_response_timeout=60 # How many time we try to reconnect to master before starting failover procedure reconnect_attempts=6 reconnect_interval=10 # Autofailover options failover=automatic priority=-1 promote_command='repmgr standby promote -f /path/to/repmgr.conf' follow_command='repmgr standby follow -f /path/to/repmgr.conf -W' # Log level: possible values are DEBUG, INFO, NOTICE, WARNING, ERR, ALERT, CRIT or EMERG # Default: NOTICE loglevel=NOTICE # Logging facility: possible values are STDERR or - for Syslog integration - one of LOCAL0, LOCAL1, ..., LOCAL7, USER # Default: STDERR logfacility=STDERR repmgr-2.0beta2/repmgr.h000066400000000000000000000034141225461504400152370ustar00rootroot00000000000000/* * repmgr.h * Copyright (c) 2ndQuadrant, 2010-2012 * * 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 . * */ #ifndef _REPMGR_H_ #define _REPMGR_H_ #include "postgres_fe.h" #include "getopt_long.h" #include "libpq-fe.h" #include "strutil.h" #include "dbutils.h" #include "errcode.h" #define PRIMARY_MODE 0 #define STANDBY_MODE 1 #define WITNESS_MODE 2 #include "config.h" #define MAXFILENAME 1024 #define ERRBUFF_SIZE 512 #define DEFAULT_CONFIG_FILE "./repmgr.conf" #define DEFAULT_WAL_KEEP_SEGMENTS "5000" #define DEFAULT_DEST_DIR "." #define DEFAULT_MASTER_PORT "5432" #define DEFAULT_DBNAME "postgres" #define DEFAULT_REPMGR_SCHEMA_PREFIX "repmgr_" #define MANUAL_FAILOVER 0 #define AUTOMATIC_FAILOVER 1 /* Run time options type */ typedef struct { char dbname[MAXLEN]; char host[MAXLEN]; char username[MAXLEN]; char dest_dir[MAXFILENAME]; char config_file[MAXFILENAME]; char remote_user[MAXLEN]; char wal_keep_segments[MAXLEN]; bool verbose; bool force; bool wait_for_master; bool ignore_rsync_warn; char masterport[MAXLEN]; char localport[MAXLEN]; /* parameter used by CLUSTER CLEANUP */ int keep_history; } t_runtime_options; #define SLEEP_MONITOR 2 #endif repmgr-2.0beta2/repmgr.sql000066400000000000000000000042361225461504400156120ustar00rootroot00000000000000/* * repmgr.sql * * Copyright (C) 2ndQuadrant, 2010-2012 * */ CREATE USER repmgr; CREATE SCHEMA repmgr; /* * The table repl_nodes keeps information about all machines in * a cluster */ CREATE TABLE repl_nodes ( id integer primary key, cluster text not null, -- Name to identify the cluster name text not null, conninfo text not null, priority integer not null, witness boolean not null default false ); ALTER TABLE repl_nodes OWNER TO repmgr; /* * Keeps monitor info about every node and their relative "position" * to primary */ CREATE TABLE repl_monitor ( primary_node INTEGER NOT NULL, standby_node INTEGER NOT NULL, last_monitor_time TIMESTAMP WITH TIME ZONE NOT NULL, last_wal_primary_location TEXT NOT NULL, last_wal_standby_location TEXT, -- In case of a witness server this will be NULL replication_lag BIGINT NOT NULL, apply_lag BIGINT NOT NULL ); ALTER TABLE repl_monitor OWNER TO repmgr; /* * This view shows the latest monitor info about every node. * Interesting thing to see: * replication_lag: in bytes (this is how far the latest xlog record * we have received is from master) * apply_lag: in bytes (this is how far the latest xlog record * we have applied is from the latest record we * have received) * time_lag: how many seconds are we from being up-to-date with master */ CREATE VIEW repl_status AS SELECT primary_node, standby_node, name AS standby_name, last_monitor_time, last_wal_primary_location, last_wal_standby_location, pg_size_pretty(replication_lag) replication_lag, pg_size_pretty(apply_lag) apply_lag, age(now(), last_monitor_time) AS time_lag FROM repl_monitor JOIN repl_nodes ON standby_node = id WHERE (standby_node, last_monitor_time) IN (SELECT standby_node, MAX(last_monitor_time) FROM repl_monitor GROUP BY 1); ALTER VIEW repl_status OWNER TO repmgr; CREATE INDEX idx_repl_status_sort ON repl_monitor(last_monitor_time, standby_node); repmgr-2.0beta2/repmgrd.c000066400000000000000000001012571225461504400154020ustar00rootroot00000000000000/* * repmgrd.c - Replication manager daemon * Copyright (C) 2ndQuadrant, 2010-2012 * * This module connects to the nodes of a replication cluster and monitors * how far are they from master * * 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 . */ #include #include #include #include #include "repmgr.h" #include "config.h" #include "log.h" #include "strutil.h" #include "version.h" /* PostgreSQL's headers needed to export some functionality */ #include "access/xlogdefs.h" #include "libpq/pqsignal.h" /* * we do not export InvalidXLogRecPtr so we need to define it * but since 9.3 it will be defined in xlogdefs.h which we include * so better to ask if it's defined to be future proof */ #ifndef InvalidXLogRecPtr const XLogRecPtr InvalidXLogRecPtr = {0, 0}; #endif #if PG_VERSION_NUM >= 90300 #define XLAssign(a, b) \ a = b #define XLAssignValue(a, xlogid, xrecoff) \ a = xrecoff #define XLByteLT(a, b) \ (a < b) #else #define XLAssign(a, b) \ a.xlogid = b.xlogid; \ a.xrecoff = b.xrecoff #define XLAssignValue(a, uxlogid, uxrecoff) \ a.xlogid = uxlogid; \ a.xrecoff = uxrecoff #endif /* * Struct to keep info about the nodes, used in the voting process in * do_failover() */ typedef struct nodeInfo { int nodeId; char conninfostr[MAXLEN]; XLogRecPtr xlog_location; bool is_ready; bool is_visible; bool is_witness; } nodeInfo; char myClusterName[MAXLEN]; /* Local info */ t_configuration_options local_options; int myLocalMode = STANDBY_MODE; PGconn *myLocalConn = NULL; /* Primary info */ t_configuration_options primary_options; PGconn *primaryConn = NULL; char sqlquery[QUERY_STR_LEN]; const char *progname; char *config_file = DEFAULT_CONFIG_FILE; bool verbose = false; bool monitoring_history = false; char repmgr_schema[MAXLEN]; bool failover_done = false; /* * should initialize with {0} to be ANSI complaint ? but this raises * error with gcc -Wall */ t_configuration_options config = {}; static void help(const char* progname); static void usage(void); static void checkClusterConfiguration(PGconn *conn, PGconn *primary); static void checkNodeConfiguration(char *conninfo); static void StandbyMonitor(void); static void WitnessMonitor(void); static bool CheckPrimaryConnection(void); static void update_shared_memory(char *last_wal_standby_applied); static void update_registration(void); static void do_failover(void); static unsigned long long int walLocationToBytes(char *wal_location); /* * Flag to mark SIGHUP. Whenever the main loop comes around it * will reread the configuration file. */ static volatile sig_atomic_t got_SIGHUP = false; static void handle_sighup(SIGNAL_ARGS); static void handle_sigint(SIGNAL_ARGS); static void setup_event_handlers(void); #define CloseConnections() \ if (PQisBusy(primaryConn) == 1) \ (void) CancelQuery(primaryConn, local_options.master_response_timeout); \ if (myLocalConn != NULL) \ PQfinish(myLocalConn); \ if (primaryConn != NULL && primaryConn != myLocalConn) \ PQfinish(primaryConn); int main(int argc, char **argv) { static struct option long_options[] = { {"config", required_argument, NULL, 'f'}, {"verbose", no_argument, NULL, 'v'}, {"monitoring-history", no_argument, NULL, 'm'}, {NULL, 0, NULL, 0} }; int optindex; int c; char standby_version[MAXVERSIONSTR]; progname = get_progname(argv[0]); if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) { help(progname); exit(SUCCESS); } if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) { printf("%s %s (PostgreSQL %s)\n", progname, REPMGR_VERSION, PG_VERSION); exit(SUCCESS); } } while ((c = getopt_long(argc, argv, "f:v:m", long_options, &optindex)) != -1) { switch (c) { case 'f': config_file = optarg; break; case 'v': verbose = true; break; case 'm': monitoring_history = true; break; default: usage(); exit(ERR_BAD_CONFIG); } } setup_event_handlers(); /* * Read the configuration file: repmgr.conf */ parse_config(config_file, &local_options); if (local_options.node == -1) { log_err(_("Node information is missing. " "Check the configuration file, or provide one if you have not done so.\n")); exit(ERR_BAD_CONFIG); } logger_init(progname, local_options.loglevel, local_options.logfacility); if (verbose) logger_min_verbose(LOG_INFO); snprintf(repmgr_schema, MAXLEN, "%s%s", DEFAULT_REPMGR_SCHEMA_PREFIX, local_options.cluster_name); log_info(_("%s Connecting to database '%s'\n"), progname, local_options.conninfo); myLocalConn = establishDBConnection(local_options.conninfo, true); /* should be v9 or better */ log_info(_("%s Connected to database, checking its state\n"), progname); pg_version(myLocalConn, standby_version); if (strcmp(standby_version, "") == 0) { log_err(_("%s needs standby to be PostgreSQL 9.0 or better\n"), progname); PQfinish(myLocalConn); exit(ERR_BAD_CONFIG); } /* * MAIN LOOP * This loops cicles once per failover and at startup * Requisites: * - myLocalConn needs to be already setted with an active connection * - no master connection */ do { /* * Set my server mode, establish a connection to primary * and start monitor */ if (is_witness(myLocalConn, repmgr_schema, local_options.cluster_name, local_options.node)) myLocalMode = WITNESS_MODE; else if (is_standby(myLocalConn)) myLocalMode = STANDBY_MODE; else /* is the master */ myLocalMode = PRIMARY_MODE; switch (myLocalMode) { case PRIMARY_MODE: primary_options.node = local_options.node; strncpy(primary_options.conninfo, local_options.conninfo, MAXLEN); primaryConn = myLocalConn; checkClusterConfiguration(myLocalConn, primaryConn); checkNodeConfiguration(local_options.conninfo); if (reload_configuration(config_file, &local_options)) { PQfinish(myLocalConn); myLocalConn = establishDBConnection(local_options.conninfo, true); primaryConn = myLocalConn; update_registration(); } log_info(_("%s Starting continuous primary connection check\n"), progname); /* Check that primary is still alive, and standbies are sending info */ /* * Every SLEEP_MONITOR seconds, do master checks * XXX * Check that standbies are sending info */ do { if (CheckPrimaryConnection()) { /* CheckActiveStandbiesConnections(); CheckInactiveStandbies(); */ sleep(SLEEP_MONITOR); } else { /* XXX * May we do something more verbose ? */ exit(1); } if (got_SIGHUP) { /* if we can reload, then could need to change myLocalConn */ if (reload_configuration(config_file, &local_options)) { PQfinish(myLocalConn); myLocalConn = establishDBConnection(local_options.conninfo, true); primaryConn = myLocalConn; update_registration(); } got_SIGHUP = false; } } while (!failover_done); break; case WITNESS_MODE: case STANDBY_MODE: /* I need the id of the primary as well as a connection to it */ log_info(_("%s Connecting to primary for cluster '%s'\n"), progname, local_options.cluster_name); primaryConn = getMasterConnection(myLocalConn, repmgr_schema, local_options.cluster_name, &primary_options.node, NULL); if (primaryConn == NULL) { CloseConnections(); exit(ERR_BAD_CONFIG); } checkClusterConfiguration(myLocalConn, primaryConn); checkNodeConfiguration(local_options.conninfo); if (reload_configuration(config_file, &local_options)) { PQfinish(myLocalConn); myLocalConn = establishDBConnection(local_options.conninfo, true); update_registration(); } /* * Every SLEEP_MONITOR seconds, do checks */ if (myLocalMode == WITNESS_MODE) { log_info(_("%s Starting continuous witness node monitoring\n"), progname); } else if (myLocalMode == STANDBY_MODE) { log_info(_("%s Starting continuous standby node monitoring\n"), progname); } do { if (myLocalMode == WITNESS_MODE) WitnessMonitor(); else if (myLocalMode == STANDBY_MODE) StandbyMonitor(); sleep(SLEEP_MONITOR); if (got_SIGHUP) { /* if we can reload, then could need to change myLocalConn */ if (reload_configuration(config_file, &local_options)) { PQfinish(myLocalConn); myLocalConn = establishDBConnection(local_options.conninfo, true); update_registration(); } got_SIGHUP = false; } } while (!failover_done); break; default: log_err(_("%s: Unrecognized mode for node %d\n"), progname, local_options.node); } failover_done = false; } while (true); /* Prevent a double-free */ if (primaryConn == myLocalConn) myLocalConn = NULL; /* close the connection to the database and cleanup */ CloseConnections(); /* Shuts down logging system */ logger_shutdown(); return 0; } /* * */ static void WitnessMonitor(void) { char monitor_witness_timestamp[MAXLEN]; PGresult *res; /* * Check if the master is still available, if after 5 minutes of retries * we cannot reconnect, return false. */ CheckPrimaryConnection(); // this take up to local_options.reconnect_attempts * local_options.reconnect_intvl seconds if (PQstatus(primaryConn) != CONNECTION_OK) { /* * If we can't reconnect, just exit... * XXX we need to make witness connect to the new master */ PQfinish(myLocalConn); exit(0); } /* Fast path for the case where no history is requested */ if (!monitoring_history) return; /* * Cancel any query that is still being executed, * so i can insert the current record */ if (!CancelQuery(primaryConn, local_options.master_response_timeout)) return; if (wait_connection_availability(primaryConn, local_options.master_response_timeout) != 1) return; /* Get local xlog info */ sqlquery_snprintf(sqlquery, "SELECT CURRENT_TIMESTAMP "); res = PQexec(myLocalConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s\n"), PQerrorMessage(myLocalConn)); PQclear(res); /* if there is any error just let it be and retry in next loop */ return; } strcpy(monitor_witness_timestamp, PQgetvalue(res, 0, 0)); PQclear(res); /* * Build the SQL to execute on primary */ sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_monitor " "VALUES(%d, %d, '%s'::timestamp with time zone, " " pg_current_xlog_location(), null, " " 0, 0)", repmgr_schema, primary_options.node, local_options.node, monitor_witness_timestamp); /* * Execute the query asynchronously, but don't check for a result. We * will check the result next time we pause for a monitor step. */ log_debug("WitnessMonitor: %s\n", sqlquery); if (PQsendQuery(primaryConn, sqlquery) == 0) log_warning(_("Query could not be sent to primary. %s\n"), PQerrorMessage(primaryConn)); } /* * Insert monitor info, this is basically the time and xlog replayed, * applied on standby and current xlog location in primary. * Also do the math to see how far are we in bytes for being uptodate */ static void StandbyMonitor(void) { PGresult *res; char monitor_standby_timestamp[MAXLEN]; char last_wal_primary_location[MAXLEN]; char last_wal_standby_received[MAXLEN]; char last_wal_standby_applied[MAXLEN]; unsigned long long int lsn_primary; unsigned long long int lsn_standby_received; unsigned long long int lsn_standby_applied; int connection_retries; /* * Check if the master is still available, if after 5 minutes of retries * we cannot reconnect, try to get a new master. */ CheckPrimaryConnection(); // this take up to local_options.reconnect_attempts * local_options.reconnect_intvl seconds if (PQstatus(primaryConn) != CONNECTION_OK) { if (local_options.failover == MANUAL_FAILOVER) { log_err(_("We couldn't reconnect to master. Now checking if another node has been promoted.\n")); for (connection_retries = 0; connection_retries < 6; connection_retries++) { primaryConn = getMasterConnection(myLocalConn, repmgr_schema, local_options.cluster_name, &primary_options.node, NULL); if (PQstatus(primaryConn) == CONNECTION_OK) { /* Connected, we can continue the process so break the loop */ log_err(_("Connected to node %d, continue monitoring.\n"), primary_options.node); break; } else { log_err(_("We haven't found a new master, waiting before retry...\n")); /* wait 5 minutes before retries, after 6 failures (30 minutes) we stop trying */ sleep(300); } } if (PQstatus(primaryConn) != CONNECTION_OK) { log_err(_("We couldn't reconnect for long enough, exiting...\n")); exit(ERR_DB_CON); } } else if (local_options.failover == AUTOMATIC_FAILOVER) { /* * When we returns from this function we will have a new primary and * a new primaryConn */ do_failover(); return; } } /* Check if we still are a standby, we could have been promoted */ if (!is_standby(myLocalConn)) { log_err(_("It seems like we have been promoted, so exit from monitoring...\n")); CloseConnections(); exit(ERR_PROMOTED); } /* Fast path for the case where no history is requested */ if (!monitoring_history) return; /* * Cancel any query that is still being executed, * so i can insert the current record */ if (!CancelQuery(primaryConn, local_options.master_response_timeout)) return; if (wait_connection_availability(primaryConn, local_options.master_response_timeout) != 1) return; /* Get local xlog info */ sqlquery_snprintf( sqlquery, "SELECT CURRENT_TIMESTAMP, pg_last_xlog_receive_location(), " "pg_last_xlog_replay_location()"); res = PQexec(myLocalConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s\n"), PQerrorMessage(myLocalConn)); PQclear(res); /* if there is any error just let it be and retry in next loop */ return; } strncpy(monitor_standby_timestamp, PQgetvalue(res, 0, 0), MAXLEN); strncpy(last_wal_standby_received , PQgetvalue(res, 0, 1), MAXLEN); strncpy(last_wal_standby_applied , PQgetvalue(res, 0, 2), MAXLEN); PQclear(res); /* Get primary xlog info */ sqlquery_snprintf(sqlquery, "SELECT pg_current_xlog_location() "); res = PQexec(primaryConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s\n"), PQerrorMessage(primaryConn)); PQclear(res); return; } strncpy(last_wal_primary_location, PQgetvalue(res, 0, 0), MAXLEN); PQclear(res); /* Calculate the lag */ lsn_primary = walLocationToBytes(last_wal_primary_location); lsn_standby_received = walLocationToBytes(last_wal_standby_received); lsn_standby_applied = walLocationToBytes(last_wal_standby_applied); /* * Build the SQL to execute on primary */ sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_monitor " "VALUES(%d, %d, '%s'::timestamp with time zone, " " '%s', '%s', " " %lld, %lld)", repmgr_schema, primary_options.node, local_options.node, monitor_standby_timestamp, last_wal_primary_location, last_wal_standby_received, (lsn_primary - lsn_standby_received), (lsn_standby_received - lsn_standby_applied)); /* * Execute the query asynchronously, but don't check for a result. We * will check the result next time we pause for a monitor step. */ log_debug("StandbyMonitor: %s\n", sqlquery); if (PQsendQuery(primaryConn, sqlquery) == 0) log_warning(_("Query could not be sent to primary. %s\n"), PQerrorMessage(primaryConn)); } static void do_failover(void) { PGresult *res; char sqlquery[8192]; int total_nodes = 0; int visible_nodes = 0; int ready_nodes = 0; bool find_best = false; int i; int r; uint32 uxlogid; uint32 uxrecoff; XLogRecPtr xlog_recptr; char last_wal_standby_applied[MAXLEN]; PGconn *nodeConn = NULL; /* * will get info about until 50 nodes, * which seems to be large enough for most scenarios */ nodeInfo nodes[50]; /* initialize to keep compiler quiet */ nodeInfo best_candidate = {-1, "", InvalidXLogRecPtr, false, false, false}; /* get a list of standby nodes, including myself */ sprintf(sqlquery, "SELECT id, conninfo, witness " " FROM %s.repl_nodes " " WHERE cluster = '%s' " " ORDER BY priority, id ", repmgr_schema, local_options.cluster_name); res = PQexec(myLocalConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("Can't get nodes' info: %s\n"), PQerrorMessage(myLocalConn)); PQclear(res); PQfinish(myLocalConn); exit(ERR_DB_QUERY); } /* * total nodes that are registered */ total_nodes = PQntuples(res); log_debug(_("%s: there are %d nodes registered\n"), progname, total_nodes); /* Build an array with the nodes and indicate which ones are visible and ready */ for (i = 0; i < total_nodes; i++) { nodes[i].nodeId = atoi(PQgetvalue(res, i, 0)); strncpy(nodes[i].conninfostr, PQgetvalue(res, i, 1), MAXLEN); nodes[i].is_witness = (strcmp(PQgetvalue(res, i, 2), "t") == 0) ? true : false; /* Initialize on false so if we can't reach this node we know that later */ nodes[i].is_visible = false; nodes[i].is_ready = false; XLAssignValue(nodes[i].xlog_location, 0, 0); log_debug(_("%s: node=%d conninfo=\"%s\" witness=%s\n"), progname, nodes[i].nodeId, nodes[i].conninfostr, (nodes[i].is_witness) ? "true" : "false"); nodeConn = establishDBConnection(nodes[i].conninfostr, false); /* if we can't see the node just skip it */ if (PQstatus(nodeConn) != CONNECTION_OK) continue; visible_nodes++; nodes[i].is_visible = true; PQfinish(nodeConn); } PQclear(res); log_debug(_("Total nodes counted: registered=%d, visible=%d\n"), total_nodes, visible_nodes); /* * am i on the group that should keep alive? * if i see less than half of total_nodes then i should do nothing */ if (visible_nodes < (total_nodes / 2.0)) { log_err(_("Can't reach most of the nodes.\n" "Let the other standby servers decide which one will be the primary.\n" "Manual action will be needed to readd this node to the cluster.\n")); exit(ERR_FAILOVER_FAIL); } /* Query all the nodes to determine which ones are ready */ for (i = 0; i < total_nodes; i++) { /* if the node is not visible, skip it */ if (!nodes[i].is_visible) continue; if (nodes[i].is_witness) continue; nodeConn = establishDBConnection(nodes[i].conninfostr, false); /* XXX * This shouldn't happen, if this happens it means this is a major problem * maybe network outages? anyway, is better for a human to react */ if (PQstatus(nodeConn) != CONNECTION_OK) { log_err(_("It seems new problems are arising, manual intervention is needed\n")); exit(ERR_FAILOVER_FAIL); } sqlquery_snprintf(sqlquery, "SELECT pg_last_xlog_receive_location()"); res = PQexec(nodeConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_info(_("Can't get node's last standby location: %s\n"), PQerrorMessage(nodeConn)); log_info(_("Connection details: %s\n"), nodes[i].conninfostr); PQclear(res); PQfinish(nodeConn); exit(ERR_FAILOVER_FAIL); } if (sscanf(PQgetvalue(res, 0, 0), "%X/%X", &uxlogid, &uxrecoff) != 2) log_info(_("could not parse transaction log location \"%s\"\n"), PQgetvalue(res, 0, 0)); log_debug("XLog position of node %d: log id=%u (%X), offset=%u (%X)\n", nodes[i].nodeId, uxlogid, uxlogid, uxrecoff, uxrecoff); /* If position is 0/0, error */ if (uxlogid == 0 && uxrecoff == 0) { PQclear(res); PQfinish(nodeConn); log_info(_("InvalidXLogRecPtr detected in a standby\n")); exit(ERR_FAILOVER_FAIL); } XLAssignValue(nodes[i].xlog_location, uxlogid, uxrecoff); PQclear(res); PQfinish(nodeConn); } /* last we get info about this node, and update shared memory */ sprintf(sqlquery, "SELECT pg_last_xlog_receive_location()"); res = PQexec(myLocalConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s.\nReport an invalid value to not be considered as new primary and exit.\n"), PQerrorMessage(myLocalConn)); PQfinish(myLocalConn); PQclear(res); sprintf(last_wal_standby_applied, "'%X/%X'", 0, 0); update_shared_memory(last_wal_standby_applied); exit(ERR_DB_QUERY); } /* write last location in shared memory */ update_shared_memory(PQgetvalue(res, 0, 0)); PQclear(res); for (i = 0; i < total_nodes; i++) { while (!nodes[i].is_ready) { /* * the witness will always be masked as ready if it's still * not marked that way and avoid a useless query */ if (nodes[i].is_witness) { if (!nodes[i].is_ready) { nodes[i].is_ready = true; ready_nodes++; } break; } /* if the node is not visible, skip it */ if (!nodes[i].is_visible) break; /* if the node is ready there is nothing to check, skip it too */ if (nodes[i].is_ready) break; nodeConn = establishDBConnection(nodes[i].conninfostr, false); /* XXX * This shouldn't happen, if this happens it means this is a major problem * maybe network outages? anyway, is better for a human to react */ if (PQstatus(nodeConn) != CONNECTION_OK) { /* XXX */ log_info(_("At this point, it could be some race conditions that are acceptable, assume the node is restarting and starting failover procedure\n")); break; } sqlquery_snprintf(sqlquery, "SELECT %s.repmgr_get_last_standby_location()", repmgr_schema); res = PQexec(nodeConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s.\nReport an invalid value to not be considered as new primary and exit.\n"), PQerrorMessage(nodeConn)); PQclear(res); PQfinish(nodeConn); exit(ERR_DB_QUERY); } if (sscanf(PQgetvalue(res, 0, 0), "%X/%X", &uxlogid, &uxrecoff) != 2) log_info(_("could not parse transaction log location \"%s\"\n"), PQgetvalue(res, 0, 0)); PQclear(res); PQfinish(nodeConn); /* If position is 0/0, keep checking */ if (uxlogid == 0 && uxrecoff == 0) continue; XLAssignValue(xlog_recptr, uxlogid, uxrecoff); if (XLByteLT(nodes[i].xlog_location, xlog_recptr)) { XLAssignValue(nodes[i].xlog_location, uxlogid, uxrecoff); } log_debug("Last XLog position of node %d: log id=%u (%X), offset=%u (%X)\n", nodes[i].nodeId, uxlogid, uxlogid, uxrecoff, uxrecoff); ready_nodes++; nodes[i].is_ready = true; } } /* Close the connection to this server */ PQfinish(myLocalConn); /* * determine which one is the best candidate to promote to primary */ for (i = 0; i < total_nodes; i++) { /* witness is never a good candidate */ if (nodes[i].is_witness) continue; if (!nodes[i].is_ready || !nodes[i].is_visible) continue; if (!find_best) { /* start with the first ready node, and then move on to the next one */ best_candidate.nodeId = nodes[i].nodeId; XLAssign(best_candidate.xlog_location, nodes[i].xlog_location); best_candidate.is_ready = nodes[i].is_ready; best_candidate.is_witness = nodes[i].is_witness; find_best = true; } /* we use the macros provided by xlogdefs.h to compare XLogRecPtr */ /* * Nodes are retrieved ordered by priority, so if the current * best candidate is lower than the next node's wal location * then assign next node as the new best candidate. */ if (XLByteLT(best_candidate.xlog_location, nodes[i].xlog_location)) { best_candidate.nodeId = nodes[i].nodeId; XLAssign(best_candidate.xlog_location, nodes[i].xlog_location); best_candidate.is_ready = nodes[i].is_ready; best_candidate.is_witness = nodes[i].is_witness; } } /* once we know who is the best candidate, promote it */ if (find_best && (best_candidate.nodeId == local_options.node)) { if (best_candidate.is_witness) { log_err(_("%s: Node selected as new master is a witness. Can't be promoted.\n"), progname); exit(ERR_FAILOVER_FAIL); } /* wait */ sleep(5); if (verbose) log_info(_("%s: This node is the best candidate to be the new primary, promoting...\n"), progname); log_debug(_("promote command is: \"%s\"\n"), local_options.promote_command); r = system(local_options.promote_command); if (r != 0) { log_err(_("%s: promote command failed. You could check and try it manually.\n"), progname); exit(ERR_BAD_CONFIG); } } else if (find_best) { /* wait */ sleep(10); if (verbose) log_info(_("%s: Node %d is the best candidate to be the new primary, we should follow it...\n"), progname, best_candidate.nodeId); log_debug(_("follow command is: \"%s\"\n"), local_options.follow_command); /* * New Primary need some time to be promoted. * The follow command should take care of that. */ r = system(local_options.follow_command); if (r != 0) { log_err(_("%s: follow command failed. You could check and try it manually.\n"), progname); exit(ERR_BAD_CONFIG); } } else { log_err(_("%s: Did not find candidates. You should check and try manually.\n"), progname); exit(ERR_FAILOVER_FAIL); } /* to force it to re-calculate mode and master node */ failover_done = true; /* and reconnect to the local database */ myLocalConn = establishDBConnection(local_options.conninfo, true); } static bool CheckPrimaryConnection(void) { int connection_retries; /* * Check if the master is still available * if after local_options.reconnect_attempts * local_options.reconnect_intvl seconds of retries * we cannot reconnect * return false */ for (connection_retries = 0; connection_retries < local_options.reconnect_attempts; connection_retries++) { if (!is_pgup(primaryConn, local_options.master_response_timeout)) { log_warning(_("%s: Connection to master has been lost, trying to recover... %i seconds before failover decision\n"), progname, (local_options.reconnect_intvl * (local_options.reconnect_attempts - connection_retries))); /* wait local_options.reconnect_intvl seconds between retries */ sleep(local_options.reconnect_intvl); } else { if ( connection_retries > 0) { log_info(_("%s: Connection to master has been restored.\n"), progname); } return true; } } if (!is_pgup(primaryConn, local_options.master_response_timeout)) { log_err(_("%s: We couldn't reconnect for long enough, exiting...\n"), progname); /* XXX Anything else to do here? */ return false; } return true; } static void checkClusterConfiguration(PGconn *conn, PGconn *primary) { PGresult *res; log_info(_("%s Checking cluster configuration with schema '%s'\n"), progname, repmgr_schema); sqlquery_snprintf(sqlquery, "SELECT oid FROM pg_class " " WHERE oid = '%s.repl_nodes'::regclass", repmgr_schema); res = PQexec(conn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s\n"), PQerrorMessage(conn)); PQclear(res); CloseConnections(); exit(ERR_DB_QUERY); } /* * If there isn't any results then we have not configured a primary node * yet in repmgr or the connection string is pointing to the wrong * database. * * XXX if we are the primary, should we try to create the tables needed? */ if (PQntuples(res) == 0) { log_err(_("The replication cluster is not configured\n")); PQclear(res); CloseConnections(); exit(ERR_BAD_CONFIG); } PQclear(res); } static void checkNodeConfiguration(char *conninfo) { PGresult *res; /* * Check if we have my node information in repl_nodes */ log_info(_("%s Checking node %d in cluster '%s'\n"), progname, local_options.node, local_options.cluster_name); sqlquery_snprintf(sqlquery, "SELECT * FROM %s.repl_nodes " " WHERE id = %d AND cluster = '%s' ", repmgr_schema, local_options.node, local_options.cluster_name); res = PQexec(myLocalConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_err(_("PQexec failed: %s\n"), PQerrorMessage(myLocalConn)); PQclear(res); CloseConnections(); exit(ERR_BAD_CONFIG); } /* * If there isn't any results then we have not configured this node yet * in repmgr, if that is the case we will insert the node to the cluster, * except if it is a witness */ if (PQntuples(res) == 0) { PQclear(res); if (myLocalMode == WITNESS_MODE) { log_err(_("The witness is not configured\n")); CloseConnections(); exit(ERR_BAD_CONFIG); } /* Adding the node */ log_info(_("%s Adding node %d to cluster '%s'\n"), progname, local_options.node, local_options.cluster_name); sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes " "VALUES (%d, '%s', '%s', '%s', 0, 'f')", repmgr_schema, local_options.node, local_options.cluster_name, local_options.node_name, local_options.conninfo); if (!PQexec(primaryConn, sqlquery)) { log_err(_("Cannot insert node details, %s\n"), PQerrorMessage(primaryConn)); CloseConnections(); exit(ERR_BAD_CONFIG); } } else { PQclear(res); } } static unsigned long long int walLocationToBytes(char *wal_location) { unsigned int xlogid; unsigned int xrecoff; if (sscanf(wal_location, "%X/%X", &xlogid, &xrecoff) != 2) { log_err(_("wrong log location format: %s\n"), wal_location); return 0; } return (( (long long) xlogid * 16 * 1024 * 1024 * 255) + xrecoff); } void usage(void) { log_err(_("%s: Replicator manager daemon \n"), progname); log_err(_("Try \"%s --help\" for more information.\n"), progname); } void help(const char *progname) { printf(_("Usage: %s [OPTIONS]\n"), progname); printf(_("Replicator manager daemon for PostgreSQL.\n")); printf(_("\nOptions:\n")); printf(_(" --help show this help, then exit\n")); printf(_(" --version output version information, then exit\n")); printf(_(" --verbose output verbose activity information\n")); printf(_(" --monitoring-history track advance or lag of the replication in every standby in repl_monitor\n")); printf(_(" -f, --config_file=PATH configuration file\n")); printf(_("\n%s monitors a cluster of servers.\n"), progname); } #ifndef WIN32 static void handle_sigint(SIGNAL_ARGS) { CloseConnections(); logger_shutdown(); exit(1); } /* SIGHUP: set flag to re-read config file at next convenient time */ static void handle_sighup(SIGNAL_ARGS) { got_SIGHUP = true; } static void setup_event_handlers(void) { pqsignal(SIGHUP, handle_sighup); pqsignal(SIGINT, handle_sigint); } #endif static void update_shared_memory(char *last_wal_standby_applied) { PGresult *res; sprintf(sqlquery, "SELECT %s.repmgr_update_standby_location('%s')", repmgr_schema, last_wal_standby_applied); /* If an error happens, just inform about that and continue */ res = PQexec(myLocalConn, sqlquery); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_warning(_("Cannot update this standby's shared memory: %s\n"), PQerrorMessage(myLocalConn)); /* XXX is this enough reason to terminate this repmgrd? */ } PQclear(res); } static void update_registration(void) { PGresult *res; sqlquery_snprintf(sqlquery, "UPDATE %s.repl_nodes " " SET conninfo = '%s', " " priority = %d " " WHERE id = %d", repmgr_schema, local_options.conninfo, local_options.priority, local_options.node); res = PQexec(primaryConn, sqlquery); if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_err(_("Cannot update registration: %s\n"), PQerrorMessage(primaryConn)); CloseConnections(); exit(ERR_DB_CON); } PQclear(res); } repmgr-2.0beta2/sql/000077500000000000000000000000001225461504400143675ustar00rootroot00000000000000repmgr-2.0beta2/sql/Makefile000066400000000000000000000005711225461504400160320ustar00rootroot00000000000000# # Makefile # Copyright (c) 2ndQuadrant, 2010 # MODULE_big = repmgr_funcs DATA_built=repmgr_funcs.sql DATA=uninstall_repmgr_funcs.sql OBJS=repmgr_funcs.o ifdef USE_PGXS PGXS := $(shell pg_config --pgxs) include $(PGXS) else subdir = contrib/repmgr/sql top_builddir = ../../.. include $(top_builddir)/src/Makefile.global include $(top_srcdir)/contrib/contrib-global.mk endif repmgr-2.0beta2/sql/repmgr_funcs.c000066400000000000000000000103021225461504400172210ustar00rootroot00000000000000/* * repmgr_funcs.c * Copyright (c) 2ndQuadrant, 2010 * * Shared memory state management and some backend functions in SQL */ #include "postgres.h" #include "fmgr.h" #include "access/xlog.h" #include "miscadmin.h" #include "storage/ipc.h" #include "storage/lwlock.h" #include "storage/procarray.h" #include "storage/shmem.h" #include "storage/spin.h" #include "utils/builtins.h" /* same definition as the one in xlog_internal.h */ #define MAXFNAMELEN 64 PG_MODULE_MAGIC; /* * Global shared state */ typedef struct repmgrSharedState { LWLockId lock; /* protects search/modification */ char location[MAXFNAMELEN]; /* last known xlog location */ } repmgrSharedState; /* Links to shared memory state */ static repmgrSharedState *shared_state = NULL; static shmem_startup_hook_type prev_shmem_startup_hook = NULL; void _PG_init(void); void _PG_fini(void); static void repmgr_shmem_startup(void); static Size repmgr_memsize(void); static bool repmgr_set_standby_location(char *locationstr); Datum repmgr_update_standby_location(PG_FUNCTION_ARGS); Datum repmgr_get_last_standby_location(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(repmgr_update_standby_location); PG_FUNCTION_INFO_V1(repmgr_get_last_standby_location); /* * Module load callback */ void _PG_init(void) { /* * In order to create our shared memory area, we have to be loaded via * shared_preload_libraries. If not, fall out without hooking into any of * the main system. (We don't throw error here because it seems useful to * allow the repmgr functions to be created even when the * module isn't active. The functions must protect themselves against * being called then, however.) */ if (!process_shared_preload_libraries_in_progress) return; /* * Request additional shared resources. (These are no-ops if we're not in * the postmaster process.) We'll allocate or attach to the shared * resources in repmgr_shmem_startup(). */ RequestAddinShmemSpace(repmgr_memsize()); RequestAddinLWLocks(1); /* * Install hooks. */ prev_shmem_startup_hook = shmem_startup_hook; shmem_startup_hook = repmgr_shmem_startup; } /* * Module unload callback */ void _PG_fini(void) { /* Uninstall hooks. */ shmem_startup_hook = prev_shmem_startup_hook; } /* * shmem_startup hook: allocate or attach to shared memory, */ static void repmgr_shmem_startup(void) { bool found; if (prev_shmem_startup_hook) prev_shmem_startup_hook(); /* reset in case this is a restart within the postmaster */ shared_state = NULL; /* * Create or attach to the shared memory state, including hash table */ LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE); shared_state = ShmemInitStruct("repmgr shared state", sizeof(repmgrSharedState), &found); if (!found) { /* First time through ... */ shared_state->lock = LWLockAssign(); snprintf(shared_state->location, sizeof(shared_state->location), "%X/%X", 0, 0); } LWLockRelease(AddinShmemInitLock); } /* * Estimate shared memory space needed. */ static Size repmgr_memsize(void) { return MAXALIGN(sizeof(repmgrSharedState)); } static bool repmgr_set_standby_location(char *locationstr) { /* Safety check... */ if (!shared_state) return false; LWLockAcquire(shared_state->lock, LW_EXCLUSIVE); strncpy(shared_state->location, locationstr, MAXFNAMELEN); LWLockRelease(shared_state->lock); return true; } /* SQL Functions */ /* Read last xlog location reported by this standby from shared memory */ Datum repmgr_get_last_standby_location(PG_FUNCTION_ARGS) { char location[MAXFNAMELEN]; /* Safety check... */ if (!shared_state) PG_RETURN_NULL(); LWLockAcquire(shared_state->lock, LW_SHARED); strncpy(location, shared_state->location, MAXFNAMELEN); LWLockRelease(shared_state->lock); PG_RETURN_TEXT_P(cstring_to_text(location)); } /* Set update last xlog location reported by this standby to shared memory */ Datum repmgr_update_standby_location(PG_FUNCTION_ARGS) { text *location = PG_GETARG_TEXT_P(0); char *locationstr; /* Safety check... */ if (!shared_state) PG_RETURN_BOOL(false); locationstr = text_to_cstring(location); PG_RETURN_BOOL(repmgr_set_standby_location(locationstr)); } repmgr-2.0beta2/sql/repmgr_funcs.sql.in000066400000000000000000000006021225461504400202050ustar00rootroot00000000000000/* * repmgr_function.sql * Copyright (c) 2ndQuadrant, 2010 * */ -- SET SEARCH_PATH TO 'repmgr'; CREATE FUNCTION repmgr_update_standby_location(text) RETURNS boolean AS 'MODULE_PATHNAME', 'repmgr_update_standby_location' LANGUAGE C STRICT; CREATE FUNCTION repmgr_get_last_standby_location() RETURNS text AS 'MODULE_PATHNAME', 'repmgr_get_last_standby_location' LANGUAGE C STRICT; repmgr-2.0beta2/sql/uninstall_repmgr_funcs.sql000066400000000000000000000001461225461504400216740ustar00rootroot00000000000000DROP FUNCTION repmgr_update_standby_location(text); DROP FUNCTION repmgr_get_last_standby_location(); repmgr-2.0beta2/strutil.c000066400000000000000000000040131225461504400154400ustar00rootroot00000000000000/* * strutil.c * * Copyright (C) 2ndQuadrant, 2010-2012 * * 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 . * */ #include #include #include #include "log.h" #include "strutil.h" static int xvsnprintf(char *str, size_t size, const char *format, va_list ap); /* Add strnlen on platforms that don't have it, like OS X */ #ifndef strnlen size_t strnlen(const char *s, size_t n) { const char *end = (const char *) memchr(s, '\0', n); return(end ? end - s : n); } #endif static int xvsnprintf(char *str, size_t size, const char *format, va_list ap) { int retval; retval = vsnprintf(str, size, format, ap); if (retval >= size) { log_err(_("Buffer of size not large enough to format entire string '%s'\n"), str); exit(ERR_STR_OVERFLOW); } return retval; } int xsnprintf(char *str, size_t size, const char *format, ...) { va_list arglist; int retval; va_start(arglist, format); retval = xvsnprintf(str, size, format, arglist); va_end(arglist); return retval; } int sqlquery_snprintf(char *str, const char *format, ...) { va_list arglist; int retval; va_start(arglist, format); retval = xvsnprintf(str, QUERY_STR_LEN, format, arglist); va_end(arglist); return retval; } int maxlen_snprintf(char *str, const char *format, ...) { va_list arglist; int retval; va_start(arglist, format); retval = xvsnprintf(str, MAXLEN, format, arglist); va_end(arglist); return retval; } repmgr-2.0beta2/strutil.h000066400000000000000000000024101225461504400154440ustar00rootroot00000000000000/* * strutil.h * Copyright (C) 2ndQuadrant, 2010-2012 * * * 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 . * */ #ifndef _STRUTIL_H_ #define _STRUTIL_H_ #include #include #define QUERY_STR_LEN 8192 #define MAXLEN 1024 #define MAXLINELENGTH 4096 #define MAXVERSIONSTR 16 #define MAXCONNINFO 1024 extern int xsnprintf(char *str, size_t size, const char *format, ...); extern int sqlquery_snprintf(char *str, const char *format, ...); extern int maxlen_snprintf(char *str, const char *format, ...); /* Add strnlen on platforms that don't have it, like OS X */ #ifndef strnlen extern size_t strnlen(const char *s, size_t n); #endif #endif /* _STRUTIL_H_ */ repmgr-2.0beta2/uninstall_repmgr.sql000066400000000000000000000003321225461504400176740ustar00rootroot00000000000000/* * uninstall_repmgr.sql * * Copyright (C) 2ndQuadrant, 2010-2012 * */ DROP TABLE IF EXISTS repl_nodes; DROP TABLE IF EXISTS repl_monitor; DROP VIEW IF EXISTS repl_status; DROP SCHEMA repmgr; DROP USER repmgr; repmgr-2.0beta2/version.h000066400000000000000000000001211225461504400154200ustar00rootroot00000000000000#ifndef _VERSION_H_ #define _VERSION_H_ #define REPMGR_VERSION "2.0beta1" #endif