├── .travis.yml ├── Dockerfile ├── ISSUE_TEMPLATE.md ├── LICENSE.txt ├── README.fr.md ├── README.md ├── documentation └── postgresqltuner.png └── postgresqltuner.pl /.travis.yml: -------------------------------------------------------------------------------- 1 | language: "perl" 2 | perl: 3 | - "5.30" 4 | - "5.28" 5 | - "5.26" 6 | - "5.24" 7 | - "5.22" 8 | 9 | services: 10 | - postgresql 11 | 12 | addons: 13 | postgresql: "9.4" 14 | 15 | before_install: 16 | - cpanm DBD::Pg 17 | 18 | install: 19 | - true 20 | 21 | before_script: 22 | - psql -c 'create database travis_ci_test;' -U postgres 23 | 24 | script: "./postgresqltuner.pl --host=localhost --user=postgres --database=travis_ci_test --password=''" 25 | 26 | notifications: 27 | recipients: 28 | - julien-postgresqltunertravis@francoz.net 29 | email: 30 | on_success: change 31 | on_failure: always 32 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | MAINTAINER Julien Francoz 3 | RUN apk add perl-dbd-pg openssh-client 4 | ADD postgresqltuner.pl /usr/bin/ 5 | ENTRYPOINT ["/usr/bin/postgresqltuner.pl"] 6 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Expected Behavior 4 | 5 | 6 | 7 | ## Current Behavior 8 | 9 | 10 | 11 | ## Possible Solution 12 | 13 | 14 | 15 | ## Steps to Reproduce (for bugs) 16 | 17 | 18 | 1. 19 | 2. 20 | 3. 21 | 4. 22 | 23 | ## Context 24 | 25 | 26 | 27 | ## Your Environment 28 | 29 | * Version used: 30 | * PostgreSQL version: 31 | * Operating System and version: 32 | 33 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.fr.md: -------------------------------------------------------------------------------- 1 | # postgresqltuner.pl 2 | 3 | [![Build Status](https://travis-ci.org/jfcoz/postgresqltuner.svg?branch=master)](https://travis-ci.org/jfcoz/postgresqltuner) 4 | 5 | `postgresqltuner.pl` analyse la configuration d'un serveur PostgreSQL et produit un rapport préconisant des améliorations. 6 | 7 | C'est un script Perl dont l'auteur s'est inspiré de [mysqltuner.pl](https://github.com/major/MySQLTuner-perl) 8 | 9 | ## Démonstration 10 | 11 | Voici un exemple de rapport: 12 | ~~~ 13 | postgresqltuner.pl version 1.0.1 14 | Checking if OS commands are available on /var/run/postgresql... 15 | [OK] I can run OS commands 16 | Connecting to /var/run/postgresql:5432 database template1 with user postgres... 17 | [OK] The user account used for reporting has superuser rights on this PostgreSQL instance 18 | ===== OS information ===== 19 | [INFO] OS: linux Version: 4.9.0 Arch: x86_64-linux-gnu-thread-multi 20 | [INFO] OS total memory: 94.36 GB 21 | [OK] vm.overcommit_memory is good: no memory overcommitment 22 | [INFO] Running (probably) directly on a physical machine 23 | [INFO] Currently used I/O scheduler(s): mq-deadline 24 | ===== General instance informations ===== 25 | ----- Version ----- 26 | [OK] You are using the latest major version (11.5 (Debian 11.5-1+deb10u1)) of PostreSQL 27 | ----- Uptime ----- 28 | [INFO] Service uptime: 01h 41m 13s 29 | [WARN] Uptime less than 1 day. My report may be inaccurate 30 | ----- Databases ----- 31 | [INFO] Database count (except templates): 3 32 | [INFO] Database list (except templates): postgres wikistats adrenalib 33 | ----- Extensions ----- 34 | [INFO] Number of activated extensions: 1 35 | [INFO] Activated extensions: plpgsql 36 | [WARN] Extension pg_stat_statements is disabled in database template1 37 | ----- Users ----- 38 | [OK] No user account will expire in less than 7 days 39 | [OK] No user with password=username 40 | [OK] Password encryption enabled 41 | ----- Connection information ----- 42 | [INFO] max_connections: 20 43 | [INFO] Current used connections: 8 (40.00%) 44 | [INFO] 2 connections are reserved for super user (10.00%) 45 | [INFO] Average connection age: 01h 08m 18s 46 | ----- Memory usage ----- 47 | [INFO] Configured work_mem: 128.00 MB 48 | [INFO] Using an average ratio of work_mem buffers by connection of 150% (use --wmp to change it) 49 | [INFO] Total work_mem (per connection): 192.00 MB 50 | [INFO] shared_buffers: 40.00 GB 51 | [INFO] Track activity reserved size: 0.00 B 52 | [INFO] maintenance_work_mem=2.00 GB 53 | [INFO] Max memory usage: 54 | shared_buffers (40.00 GB) 55 | + max_connections * work_mem * average_work_mem_buffers_per_connection (20 * 128.00 MB * 150 / 100 = 3.75 GB) 56 | + autovacuum_max_workers * maintenance_work_mem (2 * 2.00 GB = 4.00 GB) 57 | + track activity size (0.00 B) 58 | = 47.75 GB 59 | [INFO] effective_cache_size: 85.00 GB 60 | [INFO] Cumulated size of all databases: 2.17 TB 61 | [INFO] PostgreSQL maximum amount of memory used: 50.60% of system RAM 62 | [WARN] PostgreSQL will not use more than 60% of the amount of RAM. On a dedicated host you may increase PostgreSQL shared_buffers, as it may improve performances. 63 | [INFO] max memory+effective_cache_size (less shared_buffers) is 98.29% of the amount of RAM 64 | [WARN] The sum of max_memory and effective_cache_size is too high, the planner may create bad plans because the system buffercache will probably be smaller than expected, especially if the machine is NOT dedicated to PostgreSQL 65 | ----- Huge Pages ----- 66 | [OK] huge_pages enabled in PostgreSQL 67 | [INFO] Hugepagesize is 2048 kB 68 | [INFO] HugePages_Total 21000 pages 69 | [INFO] HugePages_Free 18004 pages 70 | [INFO] Suggested number of Huge Pages: 21001 (Consumption peak: 43009080 / Huge Page size: 2048) 71 | ----- Logs ----- 72 | [OK] log_hostname is off: no reverse DNS lookup latency 73 | [WARN] Log of long queries deactivated. It will be more difficult to optimize query performance 74 | [OK] log_statement=none 75 | ----- Two-phase commit ----- 76 | [OK] Currently no two-phase commit transactions 77 | ----- Autovacuum ----- 78 | [OK] autovacuum is activated. 79 | [INFO] autovacuum_max_workers: 2 80 | ----- Checkpoint ----- 81 | [OK] checkpoint_completion_target(0.9) OK 82 | ----- Disk access ----- 83 | [BAD] fsync is off. You may lose data after a crash, DANGER! 84 | [OK] synchronize_seqscans is on 85 | ----- WAL ----- 86 | ----- Planner ----- 87 | [OK] I/O cost settings are set at their default values 88 | [BAD] Some plan features are disabled: enable_partitionwise_aggregate,enable_partitionwise_join 89 | ===== Database information for database template1 ===== 90 | ----- Database size ----- 91 | [INFO] Database template1 total size: 8.02 MB 92 | [INFO] Database template1 indexes size: 4.91 MB (61.21%) 93 | [INFO] Database template1 indexes size: 3.11 MB (38.79%) 94 | ----- Tablespace location ----- 95 | [OK] No tablespace in PGDATA 96 | ----- Shared buffer hit rate ----- 97 | [INFO] shared_buffer_heap_hit_rate: 99.98% 98 | [INFO] shared_buffer_toast_hit_rate: 97.31% 99 | [INFO] shared_buffer_tidx_hit_rate: 98.97% 100 | [INFO] shared_buffer_idx_hit_rate: 99.95% 101 | [OK] This is very good (if this PostgreSQL instance was recently used as it usually is, and was not stopped since) 102 | ----- Indexes ----- 103 | [OK] No invalid index 104 | [OK] No unused indexes 105 | ----- Procedures ----- 106 | [OK] No procedures with default costs 107 | 108 | ===== Configuration advice ===== 109 | ----- checkpoint ----- 110 | [URGENT] set fsync to on! 111 | ----- extension ----- 112 | [LOW] Enable pg_stat_statements in database template1 to collect statistics on all queries (not only those longer than log_min_duration_statement) 113 | ----- hugepages ----- 114 | [LOW] Change Huge Pages size from 2MB to 1GB 115 | [MEDIUM] set vm.nr_hugepages=21001 in /etc/sysctl.conf and run sysctl -p to reload it. This will allocate Huge Pages (it may require a system reboot). 116 | ~~~ 117 | 118 | 119 | ## Utilisation 120 | 121 | ### Installation 122 | 123 | Des modules Perl sont requis: 124 | 125 | - Sur Debian et dérivées: 126 | ``` 127 | apt-get install libdbd-pg-perl libdbi-perl perl-modules 128 | ``` 129 | - Sur Fedora et dérivées: 130 | ``` 131 | yum install perl-DBD-Pg perl-DBI perl-Term-ANSIColor 132 | ``` 133 | - Sur Arch et dérivées: 134 | ``` 135 | pacman -S perl-dbi perl-dbd-pg 136 | ``` 137 | 138 | 139 | - Sur MacOS avec Homebrew: 140 | ``` 141 | brew install perl 142 | cpan DBD-pg 143 | ``` 144 | 145 | Téléchargement du script: 146 | 147 | ``` 148 | wget -O postgresqltuner.pl postgresqltuner.pl 149 | wget -O postgresqltuner.pl https://postgresqltuner.pl 150 | curl -o postgresqltuner.pl postgresqltuner.pl 151 | curl -o postgresqltuner.pl https://postgresqltuner.pl 152 | ``` 153 | 154 | Établissement des droits : 155 | ``` 156 | chmod +x postgresqltuner.pl 157 | ``` 158 | 159 | Invocation, en tant qu'utilisateur "postgres": 160 | - Connexion à PostgreSQL par TCP: 161 | ``` 162 | postgresqltuner.pl --host=dbhost --database=testdb --user=username --password=qwerty 163 | ``` 164 | - Connexion via le socket unix: 165 | ``` 166 | postgres$ postgresqltuner.pl --host=/var/run/postgresql # PostgreSQL socket directory 167 | ``` 168 | 169 | ### Avec Docker 170 | 171 | - Connexion par le réseau: 172 | ``` 173 | docker run -it --rm jfcoz/postgresqltuner --host=dbhost --user=username --password=pass --database=testdb 174 | ``` 175 | - Connexion via SSH: 176 | ``` 177 | docker run -it --rm -v $HOME/.ssh:/root/.ssh jfcoz/postgresqltuner --host=dbhost --user=username --password=pass --database=testdb 178 | ``` 179 | - Connexion via un lien Docker: 180 | ``` 181 | docker run -it --rm --link your-postgresql-container:dbhost jfcoz/postgresqltuner --host=dbhost --user=username --password=pass --database=testdb 182 | ``` 183 | 184 | ### SSH 185 | 186 | Si le script analyse un serveur distant il utilise SSH pour s'y connecter afin de collecter quelques informations décrivant le système. Pour cela vous devez configurer SSH de sorte que le script puisse se connecter au serveur avec une authentification par clef. 187 | 188 | ## Options 189 | 190 | - Nombre moyen de buffers work_mem par connection : 191 | 192 | Une requête SQL compliquée peut utiliser de nombreux tampons de travail (work_mem). Vous pouvez configurer le nombre moyen de buffers work_mem par connection (en pourcentage) avec l'option : 193 | ``` 194 | --wmp 300 195 | ``` 196 | La valeur par défaut est 150% 197 | 198 | - SSD et hyperviseurs: 199 | 200 | Le script ne détecte pas toujours parfaitement l'éventuel hyperviseur ou le stockage SSD. 201 | ``` 202 | --ssd 203 | ``` 204 | Indique que le stockage employé par PostreSQL est SSD. Utile si PostgreSQL est dans une VM, car je ne peux en ce cas déterminer le type de stockage physique employé. 205 | 206 | - Couleur 207 | 208 | ``` 209 | --nocolor 210 | ``` 211 | Le report ne sera pas colorisé. Utile afin de le sauver dans un fichier, grâce à une redirection shell (postgresqltuner.pl>rapport_pg_$(date +%Y%m%d_%H%M%S).txt). 212 | 213 | - Désactiver SSH 214 | 215 | Lors de l'utilisation sur une instance RDS, ou équivalente, il n'est pas possible d'avoir une connection SSH. L'option `--skip-ssh` permet de désactiver les tests utilisant cette connection. Comme il n'est plus possible de connaître la RAM totale du serveur, l'option `--memory` permet de passer cette information, en **octets**. 216 | 217 | ``` 218 | --skip-ssh --memory=8219082752 219 | ``` 220 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # postgresqltuner.pl 2 | 3 | [![Build Status](https://travis-ci.org/jfcoz/postgresqltuner.svg?branch=master)](https://travis-ci.org/jfcoz/postgresqltuner) 4 | [![Donate](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/CoCoZ/donate) 5 | 6 | `postgresqltuner.pl` analyses your PostgreSQL instance and produces a report, giving hints. It is inspired by [mysqltuner.pl](https://github.com/major/MySQLTuner-perl) 7 | 8 | ## Demo 9 | 10 | Here is a sample output: 11 | 12 | ~~~ 13 | postgresqltuner.pl version 1.0.1 14 | Checking if OS commands are available on /var/run/postgresql... 15 | [OK] I can run OS commands 16 | Connecting to /var/run/postgresql:5432 database template1 with user postgres... 17 | [OK] The user acount used for reporting has superuser rights on this PostgreSQL instance 18 | ===== OS information ===== 19 | [INFO] OS: linux Version: 4.9.0 Arch: x86_64-linux-gnu-thread-multi 20 | [INFO] OS total memory: 94.36 GB 21 | [OK] vm.overcommit_memory is good: no memory overcommitment 22 | [INFO] Running (probably) directly on a physical machine 23 | [INFO] Currently used I/O scheduler(s): mq-deadline 24 | ===== General instance informations ===== 25 | ----- Version ----- 26 | [OK] You are using the latest major version (11.5 (Debian 11.5-1+deb10u1)) of PostreSQL 27 | ----- Uptime ----- 28 | [INFO] Service uptime: 01h 41m 13s 29 | [WARN] Uptime less than 1 day. My report may be inaccurate 30 | ----- Databases ----- 31 | [INFO] Database count (except templates): 3 32 | [INFO] Database list (except templates): postgres wikistats adrenalib 33 | ----- Extensions ----- 34 | [INFO] Number of activated extensions: 1 35 | [INFO] Activated extensions: plpgsql 36 | [WARN] Extension pg_stat_statements is disabled in database template1 37 | ----- Users ----- 38 | [OK] No user account will expire in less than 7 days 39 | [OK] No user with password=username 40 | [OK] Password encryption enabled 41 | ----- Connection information ----- 42 | [INFO] max_connections: 20 43 | [INFO] Current used connections: 8 (40.00%) 44 | [INFO] 2 connections are reserved for super user (10.00%) 45 | [INFO] Average connection age: 01h 08m 18s 46 | ----- Memory usage ----- 47 | [INFO] Configured work_mem: 128.00 MB 48 | [INFO] Using an average ratio of work_mem buffers by connection of 150% (use --wmp to change it) 49 | [INFO] Total work_mem (per connection): 192.00 MB 50 | [INFO] shared_buffers: 40.00 GB 51 | [INFO] Track activity reserved size: 0.00 B 52 | [INFO] maintenance_work_mem=2.00 GB 53 | [INFO] Max memory usage: 54 | shared_buffers (40.00 GB) 55 | + max_connections * work_mem * average_work_mem_buffers_per_connection (20 * 128.00 MB * 150 / 100 = 3.75 GB) 56 | + autovacuum_max_workers * maintenance_work_mem (2 * 2.00 GB = 4.00 GB) 57 | + track activity size (0.00 B) 58 | = 47.75 GB 59 | [INFO] effective_cache_size: 85.00 GB 60 | [INFO] Cumulated size of all databases: 2.17 TB 61 | [INFO] PostgreSQL maximum amount of memory used: 50.60% of system RAM 62 | [WARN] PostgreSQL will not use more than 60% of the amount of RAM. On a dedicated host you may increase PostgreSQL shared_buffers, as it may improve performances. 63 | [INFO] max memory+effective_cache_size (less shared_buffers) is 98.29% of the amount of RAM 64 | [WARN] The sum of max_memory and effective_cache_size is too high, the planner may create bad plans because the system buffercache will probably be smaller than expected, especially if the machine is NOT dedicated to PostgreSQL 65 | ----- Huge Pages ----- 66 | [OK] huge_pages enabled in PostgreSQL 67 | [INFO] Hugepagesize is 2048 kB 68 | [INFO] HugePages_Total 21000 pages 69 | [INFO] HugePages_Free 18004 pages 70 | [INFO] Suggested number of Huge Pages: 21001 (Consumption peak: 43009080 / Huge Page size: 2048) 71 | ----- Logs ----- 72 | [OK] log_hostname is off: no reverse DNS lookup latency 73 | [WARN] Log of long queries deactivated. It will be more difficult to optimize query performance 74 | [OK] log_statement=none 75 | ----- Two-phase commit ----- 76 | [OK] Currently no two-phase commit transactions 77 | ----- Autovacuum ----- 78 | [OK] autovacuum is activated. 79 | [INFO] autovacuum_max_workers: 2 80 | ----- Checkpoint ----- 81 | [OK] checkpoint_completion_target(0.9) OK 82 | ----- Disk access ----- 83 | [BAD] fsync is off. You may lose data after a crash, DANGER! 84 | [OK] synchronize_seqscans is on 85 | ----- WAL ----- 86 | ----- Planner ----- 87 | [OK] I/O cost settings are set at their default values 88 | [BAD] Some plan features are disabled: enable_partitionwise_aggregate,enable_partitionwise_join 89 | ===== Database information for database template1 ===== 90 | ----- Database size ----- 91 | [INFO] Database template1 total size: 8.02 MB 92 | [INFO] Database template1 indexes size: 4.91 MB (61.21%) 93 | [INFO] Database template1 indexes size: 3.11 MB (38.79%) 94 | ----- Tablespace location ----- 95 | [OK] No tablespace in PGDATA 96 | ----- Shared buffer hit rate ----- 97 | [INFO] shared_buffer_heap_hit_rate: 99.98% 98 | [INFO] shared_buffer_toast_hit_rate: 97.31% 99 | [INFO] shared_buffer_tidx_hit_rate: 98.97% 100 | [INFO] shared_buffer_idx_hit_rate: 99.95% 101 | [OK] This is very good (if this PostgreSQL instance was recently used as it usually is, and was not stopped since) 102 | ----- Indexes ----- 103 | [OK] No invalid index 104 | [OK] No unused indexes 105 | ----- Procedures ----- 106 | [OK] No procedures with default costs 107 | 108 | ===== Configuration advice ===== 109 | ----- checkpoint ----- 110 | [URGENT] set fsync to on! 111 | ----- extension ----- 112 | [LOW] Enable pg_stat_statements in database template1 to collect statistics on all queries (not only those longer than log_min_duration_statement) 113 | ----- hugepages ----- 114 | [LOW] Change Huge Pages size from 2MB to 1GB 115 | [MEDIUM] set vm.nr_hugepages=21001 in /etc/sysctl.conf and run sysctl -p to reload it. This will allocate Huge Pages (it may require a system reboot). 116 | ~~~ 117 | 118 | ## To use it 119 | 120 | ### Install it 121 | 122 | It needs Perl with various modules, mainly `DBD::Pg` 123 | 124 | 125 | - On Debian or a derivative: 126 | ``` 127 | apt install libdbd-pg-perl libdbi-perl perl-modules 128 | ``` 129 | - On Fedora or a derivative: 130 | ``` 131 | dnf install perl-DBD-Pg perl-DBI perl-Term-ANSIColor perl-Memoize 132 | ``` 133 | - On Arch or a derivative: 134 | ``` 135 | pacman -S perl-dbi perl-dbd-pg 136 | ``` 137 | 138 | - On MacOS with Homebrew: 139 | ``` 140 | brew install perl 141 | cpan DBD-pg 142 | ``` 143 | 144 | Download the script. Invoke one of: 145 | 146 | ``` 147 | wget -O postgresqltuner.pl postgresqltuner.pl 148 | wget -O postgresqltuner.pl https://postgresqltuner.pl 149 | curl -Lo postgresqltuner.pl postgresqltuner.pl 150 | curl -Lo postgresqltuner.pl https://postgresqltuner.pl 151 | ``` 152 | 153 | Set permissions: 154 | 155 | ``` 156 | chmod +x postgresqltuner.pl 157 | ``` 158 | 159 | Then invoke on the command line, as the "postgres" user, either: 160 | 161 | - By connecting to the PostgreSQL server via TCP: 162 | ``` 163 | postgresqltuner.pl --host=dbhost --database=testdb --user=username --password=qwerty 164 | ``` 165 | - ... or via an Unix socket: 166 | ``` 167 | postgres$ postgresqltuner.pl --host=/var/run/postgresql # PostgreSQL socket directory 168 | ``` 169 | 170 | If available, postgresqltuner.pl will use standard PostgreSQL variables like `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSERNAME`, and password from the `~/.pgpass` file. 171 | 172 | ### From package 173 | 174 | - On Fedora: 175 | ``` 176 | dnf install postgresqltuner 177 | ``` 178 | 179 | - On RHEL/CentOS it is available in EPEL. 180 | 181 | 182 | ### With Docker 183 | 184 | Invoke on the command-line either: 185 | - via the plain network: 186 | ``` 187 | docker run -it --rm jfcoz/postgresqltuner --host=dbhost --user=username --password=pass --database=testdb 188 | ``` 189 | - ... or via ssh: 190 | ``` 191 | docker run -it --rm -v $HOME/.ssh:/root/.ssh jfcoz/postgresqltuner --host=dbhost --user=username --password=pass --database=testdb 192 | ``` 193 | - ... or via a docker link: 194 | ``` 195 | docker run -it --rm --link your-postgresql-container:dbhost jfcoz/postgresqltuner --host=dbhost --user=username --password=pass --database=testdb 196 | ``` 197 | 198 | ### SSH 199 | 200 | When using postgresqltuner.pl to inspect a remote PostgreSQL instance, it will use ssh to collect OS informations. You should configure ssh to connect to the remote host with private key authentication. 201 | 202 | You can provide adequate options to ssh: 203 | 204 | - ... as commend-line options: 205 | ``` 206 | --sshopt=Port=2200 --sshopt=IdentityFile=... 207 | ``` 208 | 209 | - or in the configuration file "~/.ssh/config": 210 | ``` 211 | Host my-database-host 212 | IdentityFile=... 213 | Port=2200 214 | ``` 215 | 216 | ### PostgreSQL passwords 217 | 218 | For better security use a `~/.pgpass` file containing passwords, so no password will be saved in your shell history nor visible in a process complete name. [.pgpass documentation](https://www.postgresql.org/docs/current/static/libpq-pgpass.html) 219 | 220 | ``` 221 | host:port:database:username:password 222 | ``` 223 | 224 | ## Options 225 | 226 | - Average number of work_mem buffer per connection: 227 | 228 | A complex query can use many work_mem buffers. You can configure the average number of work_mem buffers per connection (in percent): 229 | 230 | ``` 231 | --wmp 300 232 | ``` 233 | The default in 150% 234 | 235 | - SSD storage: 236 | 237 | If the PostgreSQL instance runs in an hypervisor or with SSD storage, I cannot detect it accurately. 238 | ``` 239 | --ssd 240 | ``` 241 | Allow to specify that storage is on SSD. Especially useful if PostgreSQL runs in a VM using an underlying (on the physical machine) SSD. 242 | 243 | - No color 244 | 245 | The report will not be colorized. Useful to save it in a file by using shell redirection. 246 | ``` 247 | --nocolor 248 | ``` 249 | 250 | - Skip ssh 251 | 252 | When running against an RDS, it is not possible to have a ssh connection to the instance. The option `skip-ssh` option skips the ssh connection and related checks. However, without ssh the script won't be able to search for total_memory. In this case it is possible to manually inform it by using the `memory` parameter. This way we can still have the memory ratio warnings. The memory value should be in **bytes**. 253 | ``` 254 | --skip-ssh --memory=8219082752 255 | ``` 256 | 257 | ## Special FreeBSD settings 258 | 259 | FreeBSD has support for virtual memory over-commit, using vm.overcommit configuration setting. 260 | 261 | This setting is configured via /etc/sysctl.conf. 262 | 263 | Change 'vm.overcommit: 0 ' to 'vm.overcommit: 1'. 264 | 265 | Also, install [freecolor](https://kukunotes.wordpress.com/2014/11/17/freebsd-view-memory-usage/). 266 | -------------------------------------------------------------------------------- /documentation/postgresqltuner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jfcoz/postgresqltuner/288bce8ff4ffedfbc454163924132f36a9401332/documentation/postgresqltuner.png -------------------------------------------------------------------------------- /postgresqltuner.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env perl 2 | 3 | # The postgresqltuner.pl is Copyright (C) 2016-2019 Julien Francoz , 4 | # https://github.com/jfcoz/postgresqltuner 5 | # 6 | # new relase : 7 | # wget postgresqltuner.pl 8 | # 9 | # postgresqltuner.pl is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # postgresqltuner.pl is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with postgresqltuner.pl. If not, see . 21 | # 22 | 23 | #todo: for each major parameter create a code block reserved to a PG version 24 | #todo: thx to PG stats obtain the amount of active data, selects, updates, deletes... and mix/match it with PG parameters, esp. (WAL and cache)-related 25 | #todo: not vacuum'ed tables (in need of it) 26 | 27 | use strict; 28 | use warnings; 29 | use Config; 30 | 31 | my $os={}; 32 | $os->{name}=$Config{osname}; 33 | $os->{arch}=$Config{archname}; 34 | $os->{version}=$Config{osvers}; 35 | 36 | #$SIG{__WARN__} = sub { die @_ }; 37 | 38 | my $nmmc=0; # needed missing modules count 39 | $nmmc+=try_load("Getopt::Long",{}); 40 | $nmmc+=try_load("DBD::Pg", 41 | { 42 | '/usr/local/bin/cpan' => 'cpan DBD:Pg', 43 | '/etc/debian_version'=>'apt-get install -y libdbd-pg-perl', 44 | '/etc/redhat-release'=>'yum install -y perl-DBD-Pg' 45 | }); 46 | $nmmc+=try_load("DBI", 47 | { 48 | '/usr/local/bin/cpan' => 'cpan DBI', 49 | '/etc/debian_version'=>'apt-get install -y libdbi-perl', 50 | '/etc/redhat-release'=>'yum install -y perl-DBI' 51 | }); 52 | $nmmc+=try_load("Term::ANSIColor", 53 | { 54 | '/usr/local/bin/cpan' => 'cpan install Term::ANSIColor', 55 | '/etc/debian_version'=>'apt-get install -y perl-modules', 56 | '/etc/redhat-release'=>'yum install -y perl-Term-ANSIColor' 57 | }); 58 | if ($nmmc > 0) { 59 | die "# Please install any missing Perl module"; 60 | } 61 | 62 | my $script_version="1.0.1"; 63 | my $script_name="postgresqltuner.pl"; 64 | my $min_s=60; 65 | my $hour_s=60*$min_s; 66 | my $day_s=24*$hour_s; 67 | 68 | my $host=undef; # at declaration time assigning to undef seems useless to me (perl -e 'my $host; print "OK\n" if (! defined $host);' ) , is it necessary on a given environment? 69 | my $username=undef; 70 | my $password=undef; 71 | my $database=undef; 72 | my $port=undef; 73 | my $pgpassfile=$ENV{HOME}.'/.pgpass'; 74 | my $help=0; 75 | my $work_mem_per_connection_percent=150; 76 | my @Ssh_opts=('BatchMode=yes'); 77 | my $ssh_user=undef; 78 | my $ssd=0; 79 | my $nocolor=0; 80 | my $skip_ssh=0; 81 | my $memory=undef; 82 | 83 | # functions prototypes (the perl interpreter will enforce them) 84 | # todo: enforce each and every non varargs function, iff jfcoz accepts it 85 | sub preserve_only_digits($); 86 | sub min_version($); 87 | 88 | GetOptions ( 89 | "host=s" => \$host, 90 | "user=s" => \$username, 91 | "username=s" => \$username, 92 | "pass:s" => \$password, 93 | "password:s" => \$password, 94 | "db=s" => \$database, 95 | "database=s" => \$database, 96 | "port=i" => \$port, 97 | "help" => \$help, 98 | "wmp=i" => \$work_mem_per_connection_percent, 99 | "sshopt=s" => \@Ssh_opts, 100 | "sshuser=s" => \$ssh_user, 101 | "ssd" => \$ssd, 102 | "nocolor" => \$nocolor, 103 | "skip-ssh" => \$skip_ssh, 104 | "memory" => \$memory, 105 | #todo: option --dedicated, refined as a percentage (100:full dedicated, 50: half...). Refinement: dedication per resource (storage, RAM, CPU...) 106 | #todo: option --interactive 107 | ) or usage(1); 108 | 109 | $ENV{"ANSI_COLORS_DISABLED"}=1 if $nocolor; 110 | 111 | print "$script_name version $script_version\n"; 112 | usage(0) if ($help); 113 | 114 | # ssh options 115 | my $ssh_opts=''; 116 | foreach my $ssh_opt (@Ssh_opts) { 117 | $ssh_opts.=' -o '.$ssh_opt; 118 | } 119 | 120 | # host 121 | if (!defined($host)) { 122 | if (defined($ENV{PGHOST})) { 123 | $host=$ENV{PGHOST}; 124 | } else { 125 | $host='/var/run/postgresql'; 126 | } 127 | } 128 | 129 | # port 130 | if (!defined($port)) { 131 | if (defined($ENV{PGPORT})) { 132 | $port=$ENV{PGPORT}; 133 | } else { 134 | $port=5432; 135 | } 136 | } 137 | 138 | # database 139 | if (!defined($database)) { 140 | if (defined($ENV{PGDATABASE})) { 141 | $database=$ENV{PGDATABASE}; 142 | } else { 143 | $database='template1'; 144 | } 145 | } 146 | 147 | # user 148 | if (!defined($username)) { 149 | if (defined($ENV{PGUSER})) { 150 | $username=$ENV{PGUSER}; 151 | } else { 152 | $username='postgres'; 153 | } 154 | } 155 | 156 | # if needed, get password from ~/.pgpass 157 | if (!defined($password)) { 158 | if (defined($ENV{PGPASSWORD})) { 159 | $password=$ENV{PGPASSWORD}; 160 | } else { 161 | if (defined($ENV{PGPASSFILE})) { 162 | $pgpassfile=$ENV{PGPASSFILE}; 163 | } 164 | } 165 | 166 | if (open(PGPASS,'<',$pgpassfile)) 167 | { 168 | while (my $line=) { 169 | chomp($line); 170 | next if $line =~ /^\s*#/; 171 | my ($pgp_host,$pgp_port,$pgp_database,$pgp_username,$pgp_password,$pgp_more)=split(/(?connect("dbi:Pg:dbname=$database;host=$host;port=$port;",$username,$password,{AutoCommit=>1,RaiseError=>1,PrintError=>0}); 259 | 260 | system("/usr/bin/env perl -e 'use Memoize' 1>/dev/null 2>/dev/null"); # is the Perl module 'Memoize' installed? 261 | if ( ($? >> 8) == 0) { 262 | use Memoize; 263 | memoize('get_nonvolatile_setting'); 264 | } 265 | 266 | #todo: this will be necessary when this script will analyze DB-related activity 267 | #print_report_warn("I will analyze the database $database. For more complete reports please re-run me on each database") 268 | # if ($database =~ '^template[0-9]+$'); 269 | 270 | # Collect data 271 | my $users=select_all_hashref("select * from pg_user","usename"); 272 | my $i_am_super=$users->{$username}->{usesuper}; 273 | my $settings=select_all_hashref("select * from pg_settings","name"); 274 | my $rotational_storage=undef; 275 | my @Extensions; 276 | if (min_version('9.1')) { 277 | @Extensions=select_one_column("select extname from pg_extension"); 278 | } else { 279 | print_report_warn("pg_extension does not exist in PostgreSQL version ".get_nonvolatile_setting('server_version')); 280 | } 281 | my %advices; 282 | 283 | if ($i_am_super) { 284 | print_report_ok("The user account used by me for reporting has superuser rights on this PostgreSQL instance"); 285 | } else { 286 | print_report_bad("The user account used by me for reporting does not have Postgres superuser rights. My report will be incomplete"); 287 | add_advice("reporting","high","Use an account with Postgres superuser privileges to get a more complete report"); 288 | } 289 | 290 | # Report 291 | print_header_1("OS information"); 292 | 293 | { 294 | if (! $can_run_os_cmd) { 295 | print_report_unknown("Unable to run OS commands on $host. You will obtain no OS-related information"); 296 | } else { 297 | print_report_info("OS: $os->{name} Version: $os->{version} Arch: $os->{arch}"); 298 | 299 | # OS Memory 300 | if ($os->{name} eq 'darwin') { 301 | my $os_mem=os_cmd("top -l 1 -S -n 0"); 302 | $os->{mem_used} = standard_units($os_mem =~ /PhysMem: (\d+)([GMK])/); 303 | $os->{mem_free} = standard_units($os_mem =~ /(\d+)([GMK]) unused\./); 304 | $os->{mem_total} = $os->{mem_free} + $os->{mem_used}; 305 | $os->{swap_used} = standard_units($os_mem =~ /Swap:\W+(\d+)([GMK])/); 306 | $os->{swap_free} = standard_units($os_mem =~ /Swap:\W+\d+[GMK] \+ (\d+)([GMK]) free/); 307 | $os->{swap_total} = $os->{swap_free} + $os->{swap_used}; 308 | } else { 309 | my $os_mem=""; 310 | if ($os->{name} =~ 'bsd') 311 | { 312 | $os_mem=os_cmd("freecolor -ob"); 313 | } 314 | else 315 | { 316 | $os_mem=os_cmd("free -b"); 317 | } 318 | ($os->{mem_total},$os->{mem_used},$os->{mem_free},$os->{mem_shared},$os->{mem_buffers},$os->{mem_cached})=($os_mem =~ /Mem:\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/); 319 | ($os->{swap_total},$os->{swap_used},$os->{swap_free})=($os_mem =~ /Swap:\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)/); 320 | } 321 | undef $os->{mem_total} if ( 0 == $os->{mem_total}); # paranoid 322 | print_report_info("OS total memory: ".format_size($os->{mem_total})) if (defined($os->{mem_total})); 323 | 324 | # Overcommit 325 | if ($os->{name} eq 'darwin') { 326 | print_report_unknown("No information on memory overcommitment on MacOS"); 327 | } else { 328 | my $overcommit_memory=get_sysctl('vm.overcommit_memory'); 329 | if ($overcommit_memory != 2) { 330 | print_report_bad("Memory overcommitment is allowed on the system. This may lead the OOM Killer to kill at least one PostgreSQL process, DANGER!"); 331 | add_advice('system','high',"set vm.overcommit_memory=2 in /etc/sysctl.conf and invoke sysctl -p /etc/sysctl.conf to enforce it. This will disable memory overcommitment and avoid having a PostgreSQL process killed by the OOM killer"); 332 | my $overcommit_ratio=get_sysctl('vm.overcommit_ratio'); # expressed as a percentage 333 | print_report_info("sysctl vm.overcommit_ratio=$overcommit_ratio"); 334 | if ($overcommit_ratio <= 50) { 335 | print_report_bad("vm.overcommit_ratio is too low, you will not be able to use more than (${overcommit_ratio}/100)*RAM+SWAP for applications"); 336 | } elsif ($overcommit_ratio > 90) { 337 | print_report_bad("vm.overcommit_ratio is too high, you need to keep free memory"); 338 | } 339 | } else { 340 | print_report_ok("vm.overcommit_memory is adequate: no memory overcommitment"); 341 | } 342 | } 343 | 344 | # Hardware 345 | my $hypervisor=undef; 346 | if ($os->{name} ne 'darwin') { 347 | my $systemd = os_cmd('systemd-detect-virt --vm'); 348 | if (defined($systemd)) { 349 | if ($systemd =~ m/(\S+)/) { 350 | $hypervisor = $1 if ($1 ne 'none'); 351 | } 352 | } else { 353 | my @dmesg=os_cmd("dmesg");# the ring buffer used by dmesg forgets any sufficiently 'ancient' logline. But let's try! 354 | if ((scalar @dmesg) > 1) { # on any recent Linux kernel dmesg is reserved to root. Any other user obtains "dmesg: read kernel buffer failed: Operation not permitted". We may try to use "sudo dmesg" but it will probably fail and may trip some alarm or pollute a log. We may explore by invoking "sudo -nl dmesg", then forfeit if the exitcode is 1 or otherwise search for \ in the produced lines, it may be useful if the system admin sudo-enables the 'postgres' user to run "dmesg" 355 | foreach my $line (@dmesg) { 356 | if ($line =~ /vmware/i) { 357 | $hypervisor='VMware'; 358 | last; 359 | } elsif ($line =~ /kvm/i) { 360 | $hypervisor='KVM'; 361 | last; 362 | } elsif ($line =~ /xen/i) { 363 | $hypervisor='XEN'; 364 | last; 365 | } elsif ($line =~ /vbox/i) { 366 | $hypervisor='VirtualBox'; 367 | last; 368 | } elsif ($line =~ /hyper-v/i) { 369 | $hypervisor='Hyper-V'; 370 | last; 371 | } 372 | } 373 | } 374 | } 375 | } 376 | if (defined($hypervisor)) { 377 | print_report_info("Running under a $hypervisor hypervisor"); 378 | } else { 379 | print_report_info("Running (probably) directly on a physical machine"); 380 | } 381 | 382 | # I/O scheduler 383 | my %active_schedulers; 384 | if ($os->{name} eq 'darwin') { 385 | print_report_unknown("No I/O scheduler information on MacOS"); 386 | } else { 387 | my $storage_units_list=os_cmd("ls /sys/block/"); 388 | if (!defined $storage_units_list) { 389 | print_report_unknown("Unable to explore storage unit(s) system attributes"); 390 | } else { 391 | foreach my $unit (split(/\n/,$storage_units_list)) { 392 | next if ($unit eq '.' or $unit eq '..'); 393 | next if ($unit =~ /^sr/); # exclude cdrom 394 | 395 | # Scheduler 396 | my $unit_schedulers=os_cmd("cat /sys/block/$unit/queue/scheduler"); 397 | if (! defined($unit_schedulers)) { 398 | print_report_unknown("Unable to identify the scheduler used for the storage unit $unit"); 399 | } else { 400 | chomp($unit_schedulers); 401 | next if ($unit_schedulers eq 'none'); 402 | foreach my $scheduler (split(/ /,$unit_schedulers)) { 403 | if ($scheduler =~ /^\[([a-z-]+)\]$/) { 404 | $active_schedulers{$1}++; 405 | } 406 | } 407 | } 408 | 409 | # Detect SSD or rotational disks 410 | my $unit_is_rotational=1; # Default 411 | if ($ssd) { 412 | $unit_is_rotational=0; 413 | } else { 414 | my $unit_is_rotational=os_cmd("cat /sys/block/$unit/queue/rotational"); 415 | if (!defined($unit_is_rotational)) { 416 | print_report_unknown("Unable to identify if the storage unit $unit is rotational"); 417 | } else { 418 | chomp($unit_is_rotational); 419 | } 420 | } 421 | $rotational_storage+=$unit_is_rotational; 422 | } 423 | } 424 | print_report_info("Currently used I/O scheduler(s): ".join(',',keys(%active_schedulers))); 425 | } 426 | if (defined($hypervisor) && defined($rotational_storage) && $rotational_storage>0) { 427 | print_report_warn("If PostgreSQL runs in a virtual machine, I cannot know the underlying physical storage type. Use the --ssd arg if the VM only uses SSD storage"); 428 | add_advice("storage","high","Use the --ssd arg if PostgreSQL only uses a SSD storage"); 429 | } 430 | if (defined($hypervisor) && $active_schedulers{'cfq'}) { 431 | print_report_bad("The CFQ scheduler is inadequate on a virtual machine (because the hypervisor and/or underlying kernel is already in charge of the I/O scheduling)"); 432 | add_advice("system","high","Configure your virtual machine system to use the noop or deadline io scheduler:\necho deadline > /sys/block/sdX/queue/scheduler\nupdate your kernel parameters line with elevator=deadline to restore this parameter after each reboot"); 433 | } 434 | } 435 | } 436 | 437 | print_header_1("General instance informations"); 438 | 439 | ## PostgreSQL version 440 | { 441 | print_header_2("PostgreSQL version"); 442 | my $version=get_nonvolatile_setting('server_version'); 443 | if ($version=~/(devel|rc|beta)/) { 444 | print_report_bad("You are using PostreSQL version $version which is a Development Snapshot, Beta or Release Candidate"); 445 | add_advice("version","high","If this instance is a production server, then only use stable versions"); 446 | } 447 | my $pg_upgrade="Upgrade to the latest stable PostgreSQL version"; 448 | my $pg_supportdates="Check https://www.postgresql.org/support/versioning/ for upstream support dates"; 449 | if (min_version('13.0')) { 450 | print_report_ok("You are using the latest PostreSQL major version ($version)"); 451 | } elsif (min_version('12.0')) { 452 | print_report_ok($pg_upgrade); 453 | add_advice("version","low",$pg_upgrade); 454 | } elsif (min_version('11.0')) { 455 | print_report_ok($pg_upgrade); 456 | add_advice("version","low",$pg_upgrade); 457 | } elsif (min_version('10.0')) { 458 | print_report_warn($pg_upgrade); 459 | add_advice("version","low",$pg_upgrade); 460 | add_advice("version","low",$pg_supportdates); 461 | } elsif (min_version('9.5')) { 462 | print_report_warn($pg_upgrade); 463 | add_advice("version","medium",$pg_upgrade); 464 | add_advice("version","medium",$pg_supportdates); 465 | } elsif (min_version('8.1')) { 466 | print_report_bad("You are using PostreSQL version $version, which is unsupported upstream"); 467 | add_advice("version","high",$pg_upgrade); 468 | add_advice("version","high",$pg_supportdates); 469 | } else { 470 | print_report_bad("You are using PostreSQL version $version, which is very old and not supported by this script"); 471 | add_advice("version","high",$pg_upgrade); 472 | } 473 | } 474 | 475 | ## Uptime 476 | { 477 | print_header_2("Uptime"); 478 | my $uptime=select_one_value("select extract(epoch from now()-pg_postmaster_start_time())"); 479 | print_report_info("Service uptime: ".format_epoch_to_time($uptime)); 480 | if ($uptime < $day_s) { 481 | print_report_warn("Uptime less than 1 day. This report may be inaccurate"); 482 | } 483 | } 484 | 485 | ## Database count (except template) 486 | { 487 | print_header_2("Databases"); 488 | my @Databases=select_one_column("SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn;"); 489 | print_report_info("Database count (except templates): ".scalar(@Databases)); 490 | print_report_info("Database list (except templates): @Databases"); 491 | } 492 | 493 | ## Extensions 494 | { 495 | print_header_2("Extensions"); 496 | print_report_info("Number of activated extensions: ".scalar(@Extensions)); 497 | print_report_info("Activated extensions: @Extensions"); 498 | if (grep(/pg_stat_statements/,@Extensions)) { 499 | print_report_ok("Extension pg_stat_statements is enabled"); 500 | } else { 501 | print_report_warn("Extension pg_stat_statements is disabled in database $database"); 502 | add_advice("extension","low","Enable pg_stat_statements in database $database to collect statistics on all queries (not only those longer than log_min_duration_statement)"); 503 | } 504 | } 505 | 506 | ## Users 507 | { 508 | print_header_2("Users"); 509 | my @ExpiringSoonUsers = select_one_column("select usename from pg_user where valuntil < now()+interval'7 days'"); 510 | if (@ExpiringSoonUsers > 0) { 511 | print_report_warn("Some user account will expire in less than 7 days: ".join(',',@ExpiringSoonUsers)); 512 | } else { 513 | print_report_ok("No user account will expire in less than 7 days"); 514 | } 515 | if ($i_am_super) { 516 | my @BadPasswordUsers = select_one_column("select usename from pg_shadow where passwd='md5'||md5(usename||usename)"); 517 | if (@BadPasswordUsers > 0) { 518 | print_report_warn("Some user account password is the username: ".join(',',@BadPasswordUsers)); 519 | } else { 520 | print_report_ok("No user with password=username"); 521 | } 522 | } else { 523 | print_report_warn("Unable to check users passwords, please use a super user instead"); 524 | } 525 | my $password_encryption=get_nonvolatile_setting('password_encryption'); 526 | if ($password_encryption eq 'off') { 527 | print_report_bad("Password encryption is disabled by default. Passwords will not be encrypted until explicitely asked"); 528 | } else { 529 | print_report_ok("Password encryption enabled"); 530 | } 531 | } 532 | 533 | ## Connections and Memory 534 | { 535 | print_header_2("Connection information"); 536 | # max_connections 537 | my $max_connections=get_nonvolatile_setting('max_connections'); 538 | print_report_info("max_connections: $max_connections"); 539 | 540 | # current connections + ratio 541 | my $current_connections=select_one_value("select count(1) from pg_stat_activity"); 542 | my $current_connections_percent=$current_connections*100/$max_connections; 543 | print_report_info("Current used connections: $current_connections (".format_percent($current_connections_percent).")"); 544 | if ($current_connections_percent > 70) { 545 | print_report_warn("You are using more than 70% of the connections slots. Increase max_connections to avoid saturation of connection slots"); 546 | } elsif ($current_connections_percent > 90) { 547 | print_report_bad("You are using more than 90% of the connection slots. Increase max_connections to avoid saturation of connection slots"); 548 | } 549 | # superuser_reserved_connections 550 | my $superuser_reserved_connections=get_nonvolatile_setting("superuser_reserved_connections"); 551 | my $superuser_reserved_connections_ratio=$superuser_reserved_connections*100/$max_connections; 552 | if ($superuser_reserved_connections == 0) { 553 | print_report_bad("No connection slot is reserved for the superuser. In case of connection saturation you will not be able to connect to investigate or kill connections"); 554 | } else { 555 | print_report_info("$superuser_reserved_connections connections are reserved for super user (".format_percent($superuser_reserved_connections_ratio).")"); 556 | } 557 | if ($superuser_reserved_connections_ratio > 20) { 558 | print_report_warn(format_percent($superuser_reserved_connections_ratio)." of connections are reserved for super user. This is too much and may limit other users connections"); 559 | } 560 | # average connection age 561 | my $connection_age_average=select_one_value("select extract(epoch from avg(now()-backend_start)) as age from pg_stat_activity"); 562 | print_report_info("Average connection age: ".format_epoch_to_time($connection_age_average)); 563 | if ($connection_age_average < 1 * $min_s) { 564 | print_report_bad("The average connection age is less than 1 minute. Use a connection pooler to limit new connections/second"); 565 | } elsif ($connection_age_average < 10 * $min_s) { 566 | print_report_warn("The average connection age is less than 10 minutes. Use a connection pooler to limit new connections/second"); 567 | } 568 | # pre_auth_delay 569 | my $pre_auth_delay=get_nonvolatile_setting('pre_auth_delay'); 570 | $pre_auth_delay=~s/s//; 571 | if ($pre_auth_delay > 0) { 572 | print_report_bad("pre_auth_delay=$pre_auth_delay: this is a developer feature for debugging and decrease connection delay of $pre_auth_delay seconds"); 573 | } 574 | # post_auth_delay 575 | my $post_auth_delay=get_nonvolatile_setting('post_auth_delay'); 576 | $post_auth_delay=~s/s//; 577 | if ($post_auth_delay > 0) { 578 | print_report_bad("post_auth_delay=$post_auth_delay: this is a developer feature for debugging and decrease connection delay of $post_auth_delay seconds"); 579 | } 580 | 581 | print_header_2("Memory usage"); 582 | # work_mem 583 | my $work_mem=get_nonvolatile_setting('work_mem'); 584 | my $work_mem_total=$work_mem*$work_mem_per_connection_percent/100*$max_connections; 585 | print_report_info("Configured work_mem: ".format_size($work_mem)); 586 | print_report_info("Using an average ratio of work_mem buffers by connection of $work_mem_per_connection_percent% (use --wmp to change it)"); 587 | print_report_info("Total work_mem (per connection): ".format_size($work_mem*$work_mem_per_connection_percent/100)); 588 | my $shared_buffers=get_nonvolatile_setting('shared_buffers'); 589 | # shared_buffers 590 | print_report_info("shared_buffers: ".format_size($shared_buffers)); 591 | # track activity 592 | my $max_processes=get_nonvolatile_setting('max_connections')+get_nonvolatile_setting('autovacuum_max_workers'); 593 | if (min_version('9.4')) { 594 | $max_processes+=get_nonvolatile_setting('max_worker_processes'); 595 | } 596 | my $track_activity_size=get_nonvolatile_setting('track_activity_query_size')*$max_processes; 597 | print_report_info("Track activity reserved size: ".format_size($track_activity_size)); 598 | # maintenance_work_mem 599 | my $maintenance_work_mem=get_nonvolatile_setting('maintenance_work_mem'); 600 | my $autovacuum_max_workers=get_nonvolatile_setting('autovacuum_max_workers'); 601 | my $maintenance_work_mem_total=$maintenance_work_mem*$autovacuum_max_workers; 602 | if ($maintenance_work_mem<=64*1024*1024) { 603 | print_report_warn("maintenance_work_mem is less or equal to its default value. Increase it to reduce maintenance tasks duration"); 604 | } else { 605 | print_report_info("maintenance_work_mem=".format_size($maintenance_work_mem)); 606 | } 607 | # total 608 | my $max_memory=$shared_buffers+$work_mem_total+$maintenance_work_mem_total+$track_activity_size; 609 | 610 | print_report_info("Max memory usage:\n\t\t shared_buffers (".format_size($shared_buffers).")\n\t\t+ max_connections * work_mem * average_work_mem_buffers_per_connection ($max_connections * ".format_size($work_mem)." * $work_mem_per_connection_percent / 100 = ".format_size($max_connections*$work_mem*$work_mem_per_connection_percent/100).")\n\t\t+ autovacuum_max_workers * maintenance_work_mem ($autovacuum_max_workers * ".format_size($maintenance_work_mem)." = ".format_size($autovacuum_max_workers*$maintenance_work_mem).")\n\t\t+ track activity size (".format_size($track_activity_size).")\n\t\t= ".format_size($max_memory)); 611 | # effective_cache_size 612 | my $effective_cache_size=get_nonvolatile_setting('effective_cache_size'); 613 | print_report_info("effective_cache_size: ".format_size($effective_cache_size)); 614 | # total database size 615 | my $all_databases_size=select_one_value("select sum(pg_database_size(datname)) from pg_database"); 616 | print_report_info("Cumulated size of all databases: ".format_size($all_databases_size)); 617 | # shared_buffer usage 618 | my $shared_buffers_usage=$all_databases_size/$shared_buffers; 619 | if ($shared_buffers_usage < 0.7) { # todo: may shared_buffers also contain various non-data, for example indexes? In such a case the total (cumulated) database size is only one parameter here. The question now is: do shared_buffers cache anything other than tables contents, especially does it caches indices (indexes)? I experimented while exploring thanks to pg_buffercache and it seems (PG11) that index-only access indeed load shared_buffers, however PG may be loading some/each data (corresponding to a conditon-satisfying index hit)?). If it doesn't it may be part of the reason why maxing shared_buffers at 40% of the RAM is realistic, as (even if shared_buffer is more efficient than the kernel when it comes to caching DB data) a fair kernel buffercache containing some intensively-used indices (indexes) pages is far better than having no cached index. It seems that shared_buffers only caches data 620 | print_report_warn("shared_buffer is too big for the total databases size, uselessly using memory"); 621 | } 622 | if ($effective_cache_size < $shared_buffers) { 623 | print_report_warn("effective_cache_size < shared_buffer. This is inadequate, as effective_cache_size value must be (shared buffers) + (size in bytes of the kernel's storage buffercache that will be used for PostgreSQL data files)"); 624 | } 625 | my $buffercache_declared_size = $effective_cache_size - $shared_buffers; 626 | if ( $buffercache_declared_size < 4000000000) { 627 | print_report_warn("The declared buffercache size ( effective_cache_size - shared_buffers ) is less than 4GB. effective_cache_size value is probably inadequate. It must be (shared buffers) + (size in bytes of the kernel's storage buffercache that will be used for PostgreSQL data files)"); 628 | } 629 | 630 | # ratio of total RAM 631 | if (! defined($os->{mem_total})) { 632 | if (defined($memory)) { 633 | $os->{mem_total} = $memory; 634 | } 635 | } 636 | if (! defined($os->{mem_total})) { 637 | print_report_unknown("OS total mem unknown: unable to analyse PostgreSQL memory usage"); 638 | } else { 639 | #todo: shared_buffers MAX: 40% RAM 640 | my $percent_postgresql_max_memory=$max_memory*100/$os->{mem_total}; 641 | print_report_info("PostgreSQL maximum amount of memory used: ".format_percent($percent_postgresql_max_memory)." of system RAM"); 642 | if ($percent_postgresql_max_memory > 100) { 643 | print_report_bad("PostgreSQL may try to use more than the amount of RAM. Add more RAM or reduce PostgreSQL memory requirements"); 644 | } elsif ($percent_postgresql_max_memory > 80) { 645 | print_report_warn("PostgreSQL may try to use more than 80% of the amount of RAM"); 646 | } elsif ($percent_postgresql_max_memory < 60) { 647 | print_report_info("PostgreSQL will not use more than 60% of the amount of RAM. On a dedicated host you may increase PostgreSQL shared_buffers, as it may improve performance"); 648 | } else { 649 | print_report_ok("The potential max memory usage of PostgreSQL is adequate if the host is dedicated to PostgreSQL"); 650 | } 651 | print_report_warn("PostgreSQL may try to use more than 40% of the amount of RAM for shared_buffers. This is probably too much, reduce shared_buffers") 652 | if ( $shared_buffers / $os->{mem_total} > .4); 653 | # track activity ratio 654 | my $track_activity_ratio=$track_activity_size*100/$os->{mem_total}; 655 | if ($track_activity_ratio > 1) { 656 | print_report_warn("Track activity reserved size is more than 1% of your RAM"); 657 | add_advice("track_activity","low","Your track activity reserved size is too high. Reduce track_activity_query_size and/or max_connections"); 658 | } 659 | # total ram usage with effective_cache_size 660 | my $percent_mem_usage=($max_memory+$effective_cache_size-$shared_buffers)*100/$os->{mem_total}; 661 | print_report_info("max memory usage + effective_cache_size - shared_buffers is ".format_percent($percent_mem_usage)." of the amount of RAM"); 662 | if ($percent_mem_usage < 60 and $shared_buffers_usage > 1) { 663 | print_report_warn("Increase shared_buffers to let PostgreSQL directly use more memory, especially if the machine is dedicated to PostgreSQL"); 664 | } elsif ($percent_mem_usage > 90) { 665 | print_report_warn("The sum of max_memory and effective_cache_size is too high, the planner may create bad plans because the system buffercache will probably be smaller than expected, especially if the machine is NOT dedicated to PostgreSQL"); 666 | } 667 | } 668 | # Hugepages 669 | print_header_2("Huge Pages"); 670 | if (($os->{name} ne 'linux') && ($os->{name} ne 'freebsd')) { # not sure about FreeBSD 671 | print_report_unknown("No Huge Pages on this OS"); 672 | } else { 673 | my $nr_hugepages=get_sysctl('vm.nr_hugepages'); 674 | if (!defined $nr_hugepages || $nr_hugepages == 0) { 675 | print_report_warn("No Huge Pages available on the system"); 676 | last; 677 | } 678 | if (get_nonvolatile_setting('huge_pages') eq 'on') { 679 | print_report_warn("huge_pages=on, therefore PostgreSQL needs Huge Pages and will not start if the kernel doesn't provide them"); 680 | } 681 | elsif (get_nonvolatile_setting('huge_pages') eq 'try') { 682 | print_report_info("huge_pages=on, therefore PostgreSQL will try to use Huge Pages, if they are enabled"); 683 | } 684 | else { 685 | add_advice("hugepages","medium","Enable huge_pages to enhance memory allocation performance, and if necessary also enable them at OS level"); 686 | } 687 | my $os_huge=os_cmd("grep ^Huge /proc/meminfo"); 688 | ($os->{HugePages_Total})=($os_huge =~ /HugePages_Total:\s+([0-9]+)/); 689 | ($os->{HugePages_Free})=($os_huge =~ /HugePages_Free:\s+([0-9]+)/); 690 | ($os->{Hugepagesize})=($os_huge =~ /Hugepagesize:\s+([0-9]+)/); 691 | print_report_info("Hugepagesize is ".$os->{Hugepagesize}." kB"); 692 | print_report_info("HugePages_Total ".$os->{HugePages_Total}." pages"); 693 | print_report_info("HugePages_Free ".$os->{HugePages_Free}." pages"); 694 | 695 | my $pg_pid=select_one_value("SELECT pg_backend_pid();"); 696 | my $peak=os_cmd("grep ^VmPeak /proc/".$pg_pid."/status | awk '{ print \$2 }'"); 697 | chomp($peak); 698 | my $suggesthugepages=$peak/$os->{Hugepagesize}; 699 | print_report_info("Suggested number of Huge Pages: ".int($suggesthugepages + 0.5)." (Consumption peak: ".$peak." / Huge Page size: ".$os->{Hugepagesize}.")"); 700 | if ($os->{HugePages_Total} < int($suggesthugepages + 0.5)) { 701 | add_advice("hugepages","medium","set vm.nr_hugepages=".int($suggesthugepages + 0.5)." in /etc/sysctl.conf and invoke sysctl -p /etc/sysctl.conf to reload it. This will allocate Huge Pages (it may require a system reboot)"); 702 | } 703 | 704 | if ($os->{Hugepagesize} == 2048) { 705 | add_advice("hugepages","low","Change Huge Pages size from 2MB to 1GB if the machine is dedicated to PostgreSQL"); 706 | } 707 | } 708 | } 709 | 710 | ## Logs 711 | { 712 | print_header_2("Logs"); 713 | # log hostname 714 | my $log_hostname=get_nonvolatile_setting('log_hostname'); 715 | if ($log_hostname eq 'on') { 716 | print_report_bad("log_hostname is on: this will decrease connection performance (because PostgreSQL has to do DNS lookups)"); 717 | } else { 718 | print_report_ok("log_hostname is off: no reverse DNS lookup latency"); 719 | } 720 | 721 | # log_min_duration_statement 722 | my $log_min_duration_statement=get_nonvolatile_setting('log_min_duration_statement'); 723 | $log_min_duration_statement=~s/ms//; 724 | if ($log_min_duration_statement == -1 ) { 725 | print_report_warn("Log of long queries deactivated. It will be more difficult to optimize query performance"); 726 | } elsif ($log_min_duration_statement < 1000 ) { 727 | print_report_bad("log_min_duration_statement=$log_min_duration_statement: any request during less than 1 sec will be written in log. It may be storage-intensive (I/O and space)"); 728 | } else { 729 | print_report_ok("Long queries will be logged"); 730 | } 731 | 732 | # log_statement 733 | my $log_statement=get_nonvolatile_setting('log_statement'); 734 | if ($log_statement eq 'all') { 735 | print_report_bad("log_statement=all is very storage-intensive and only usefull for debuging"); 736 | } elsif ($log_statement eq 'mod') { 737 | print_report_warn("log_statement=mod is storage-intensive"); 738 | } else { 739 | print_report_ok("log_statement=$log_statement"); 740 | } 741 | } 742 | 743 | ## Two-phase commit 744 | { 745 | print_header_2("Two-phase commit"); 746 | if (min_version('9.2')) { 747 | my $prepared_xact_count=select_one_value("select count(1) from pg_prepared_xacts"); 748 | if ($prepared_xact_count == 0) { 749 | print_report_ok("Currently there is no two-phase commit transaction"); 750 | } else { 751 | print_report_warn("Currently $prepared_xact_count two-phase commit prepared transactions exist. If they stay for too long they may lock objects for too long"); 752 | my $prepared_xact_lock_count=select_one_value("select count(1) from pg_locks where transactionid in (select transaction from pg_prepared_xacts)"); 753 | if ($prepared_xact_lock_count > 0) { 754 | print_report_bad("Two-phase commit transactions have $prepared_xact_lock_count locks!"); 755 | } else { 756 | print_report_ok("No locks for theses $prepared_xact_count transactions"); 757 | } 758 | } 759 | } else { 760 | print_report_warn("This PostgreSQL version does not support two-phase commit"); 761 | } 762 | } 763 | 764 | ## Autovacuum 765 | { 766 | print_header_2("Autovacuum"); 767 | if (get_nonvolatile_setting('autovacuum') eq 'on') { 768 | print_report_ok('autovacuum is activated'); 769 | my $autovacuum_max_workers=get_nonvolatile_setting('autovacuum_max_workers'); 770 | print_report_info("autovacuum_max_workers: $autovacuum_max_workers"); 771 | } else { 772 | print_report_bad('autovacuum is not activated. This is bad except if you known what you do'); 773 | } 774 | } 775 | 776 | ## Checkpoint 777 | { 778 | print_header_2("Checkpoint"); 779 | my $checkpoint_completion_target=get_nonvolatile_setting('checkpoint_completion_target'); # no dimension 780 | my $checkpoint_warning=get_nonvolatile_setting('checkpoint_warning'); # unit: s 781 | $checkpoint_warning=~s/s$//; 782 | my $checkpoint_timeout=get_nonvolatile_setting('checkpoint_timeout'); # unit: s 783 | $checkpoint_timeout=~s/s$//; 784 | print_report_warn("checkpoint_warning value is 0. This is rarely adequate") if ( 0 == $checkpoint_warning ); 785 | if ($checkpoint_completion_target == 0) { 786 | print_report_bad("checkpoint_completion_target value is 0. This is absurd"); 787 | } 788 | else { 789 | my $msg_CCT="checkpoint_completion_target is low. Some checkpoints may abruptly overload the storage with write commands for a long time, slowing running queries down. To avoid such temporary overload you may balance checkpoint writes using a higher value"; 790 | if ($checkpoint_completion_target < 0.5) { 791 | print_report_warn("Checkpoint_completion_target ($checkpoint_completion_target) is lower than its default value (0.5)"); 792 | add_advice("checkpoint","high", $msg_CCT); 793 | } elsif ($checkpoint_completion_target >= 0.5 and $checkpoint_completion_target <= 0.7) { 794 | print_report_warn("checkpoint_completion_target ($checkpoint_completion_target) is low"); 795 | add_advice("checkpoint","medium", $msg_CCT); 796 | } elsif ($checkpoint_completion_target > 0.7 and $checkpoint_completion_target <= 0.9) { 797 | print_report_ok("checkpoint_completion_target ($checkpoint_completion_target) OK"); 798 | } elsif ($checkpoint_completion_target > 0.9 and $checkpoint_completion_target < 1) { 799 | print_report_warn("checkpoint_completion_target($checkpoint_completion_target) is too near to 1"); 800 | add_advice("checkpoint","medium", "Reduce checkpoint_completion_target"); 801 | } else { 802 | print_report_bad("checkpoint_completion_target too high ($checkpoint_completion_target)"); 803 | } 804 | my $checkpoint_dirty_writing_time_window=$checkpoint_timeout * $checkpoint_completion_target; 805 | print_report_warn("(checkpoint_timeout / checkpoint_completion_target) is probably too low") 806 | if ($checkpoint_dirty_writing_time_window < 10); 807 | if (min_version('9.5')) { # too much work for us, given all settings and PG versions. For now let's neglect 'old' PG versions 808 | my $max_wal_size=get_nonvolatile_setting('max_wal_size'); # Maximum size to let the WAL grow to between automatic WAL checkpoints 809 | my $average_w=$max_wal_size/$checkpoint_dirty_writing_time_window; 810 | my $aw_msg="Given those settings PostgreSQL may (depending on its workload) ask the kernel to write (to the storage) up to " . format_size($max_wal_size) . " in a timeframe lasting " . $checkpoint_dirty_writing_time_window . " seconds <=> " . format_size($average_w) . " bytes/second during this timeframe. You may want to check that your storage is able to cope with this, along with all other I/O (non-writing queries, other software...) operations potentially active during this timeframe. If this seems inadequate check max_wal_size, checkpoint_timeout and checkpoint_completion_target"; 811 | ($average_w < ($ssd ? 2e8 : 3e7)) ? print_report_info($aw_msg) : print_report_warn($aw_msg); 812 | } 813 | } 814 | } 815 | 816 | ## Storage 817 | { 818 | print_header_2("Storage"); 819 | my $fsync=get_nonvolatile_setting('fsync'); 820 | my $wal_sync_method=get_nonvolatile_setting('wal_sync_method'); 821 | if ($fsync eq 'on') { 822 | print_report_ok("fsync is on"); 823 | } else { 824 | print_report_bad("fsync is off. You may lose data after a crash, DANGER!"); 825 | add_advice("storage","high","set fsync to on!"); 826 | } 827 | if ($os->{name} eq 'darwin') { 828 | if ($wal_sync_method ne 'fsync_writethrough') { 829 | print_report_bad("wal_sync_method is $wal_sync_method. Settings other than fsync_writethrough may lead to loss of data after a crash, DANGER!"); 830 | add_advice("storage","high","set wal_sync_method to fsync_writethrough to on. Otherwise, the write-back cache may prevent recovery after a crash"); 831 | } else { 832 | print_report_ok("wal_sync_method is $wal_sync_method"); 833 | } 834 | } 835 | if (get_nonvolatile_setting('synchronize_seqscans') eq 'on') { 836 | print_report_ok("synchronize_seqscans is on"); 837 | } else { 838 | print_report_warn("synchronize_seqscans is off"); 839 | add_advice("seqscan","medium","set synchronize_seqscans to synchronize seqscans and reduce I/O load"); 840 | } 841 | } 842 | 843 | ## WAL / PITR 844 | { 845 | print_header_2("WAL"); 846 | if (min_version('9.0')) { 847 | my $wal_level=get_nonvolatile_setting('wal_level'); 848 | if ($wal_level eq 'minimal') { 849 | print_report_bad("The \'minimal\' wal_level does not allow PITR backup and recovery"); 850 | add_advice("backup","high","Configure your wal_level to a level which allows PITR backup and recovery"); 851 | } 852 | } else { 853 | print_report_warn("wal_level not supported, please upgrade PostgreSQL"); 854 | } 855 | } 856 | 857 | ## Planner 858 | { 859 | print_header_2("Planner"); 860 | # Modified cost settings 861 | my @ModifiedCosts=select_one_column("select name from pg_settings where name like '%cost%' and setting<>boot_val;"); 862 | if (@ModifiedCosts > 0) { 863 | print_report_warn("Some I/O cost settings are not set to their default value: ".join(',',@ModifiedCosts).". This may lead the planner to create suboptimal plans"); 864 | } else { 865 | print_report_ok("I/O cost settings are set at their default values"); 866 | } 867 | 868 | # random vs seq page cost on SSD 869 | if (!defined($rotational_storage)) { 870 | print_report_unknown("I have no information about the rotational/SSD storage: I'm unable to check random_page_cost and seq_page_cost settings"); 871 | } else { 872 | if ($rotational_storage == 0 and get_nonvolatile_setting('random_page_cost')>get_nonvolatile_setting('seq_page_cost')) { 873 | print_report_warn("With SSD storage, set random_page_cost=seq_page_cost to help the planner prefer index scans"); 874 | add_advice("planner","medium","Set random_page_cost=seq_page_cost on SSD storage"); 875 | } elsif ($rotational_storage > 0 and get_nonvolatile_setting('random_page_cost')<=get_nonvolatile_setting('seq_page_cost')) { 876 | print_report_bad("Without SSD storage, the random_page_cost value must be superior than the seq_page_cost value"); 877 | add_advice("planner","high","If you don't use SSD storage then set random_page_cost to 2-4 times more than seq_page_cost/ Reduce the factor if you use multiple rotating disks"); 878 | } 879 | } 880 | 881 | # disabled plan functions 882 | my @DisabledPlanFunctions=select_one_column("select name,setting from pg_settings where name like 'enable_%' and setting='off';"); 883 | if (@DisabledPlanFunctions > 0) { 884 | print_report_bad("Some plan features are disabled: ".join(',',@DisabledPlanFunctions)); 885 | } else { 886 | print_report_ok("All plan features are enabled"); 887 | } 888 | 889 | } 890 | 891 | # Database information 892 | print_header_1("Database information for database $database"); 893 | 894 | ## Database size 895 | { 896 | print_header_2("Database size"); 897 | my $sum_total_relation_size=select_one_value("select sum(pg_total_relation_size(schemaname||'.'||quote_ident(tablename))) from pg_tables"); 898 | print_report_info("Database $database total size: ".format_size($sum_total_relation_size)); 899 | if (min_version('9.0')) { 900 | my $sum_table_size=select_one_value("select sum(pg_table_size(schemaname||'.'||quote_ident(tablename))) from pg_tables"); 901 | my $sum_index_size=$sum_total_relation_size-$sum_table_size; 902 | #print_report_debug("sum_total_relation_size: $sum_total_relation_size"); 903 | #print_report_debug("sum_table_size: $sum_table_size"); 904 | #print_report_debug("sum_index_size: $sum_index_size"); 905 | my $table_percent=$sum_table_size*100/$sum_total_relation_size; 906 | my $index_percent=$sum_index_size*100/$sum_total_relation_size; 907 | print_report_info("Database $database tables size: ".format_size($sum_table_size)." (".format_percent($table_percent).")"); 908 | print_report_info("Database $database indexes size: ".format_size($sum_index_size)." (".format_percent($index_percent).")"); 909 | } 910 | } 911 | 912 | ## Tablespace location 913 | { 914 | print_header_2("Tablespace location"); 915 | if (min_version('9.2')) { 916 | my $tablespaces_in_pgdata=select_all_hashref("select spcname,pg_tablespace_location(oid) from pg_tablespace where pg_tablespace_location(oid) like (select setting from pg_settings where name='data_directory')||'/%'",'spcname'); 917 | if (keys(%{$tablespaces_in_pgdata}) == 0) { 918 | print_report_ok("No tablespace in PGDATA"); 919 | } else { 920 | print_report_bad("Some tablespaces defined in PGDATA: ".join(' ',keys(%{$tablespaces_in_pgdata}))); 921 | add_advice('tablespaces','high','Some tablespaces are in PGDATA. Move them outside of this folder'); 922 | } 923 | } else { 924 | print_report_unknown("This check is only possible with PostgreSQL version 9.2 and above"); 925 | } 926 | } 927 | 928 | ## Shared buffer usage 929 | { 930 | print_header_2("Shared buffer hit rate"); 931 | ### Heap hit rate 932 | { 933 | my $shared_buffer_heap_hit_rate=select_one_value("select sum(heap_blks_hit)*100/(sum(heap_blks_read)+sum(heap_blks_hit)+1) from pg_statio_all_tables ;"); 934 | print_report_info("shared_buffer_heap_hit_rate: ".format_percent($shared_buffer_heap_hit_rate)); 935 | } 936 | ### TOAST hit rate 937 | { 938 | my $shared_buffer_toast_hit_rate=select_one_value("select sum(toast_blks_hit)*100/(sum(toast_blks_read)+sum(toast_blks_hit)+1) from pg_statio_all_tables ;"); 939 | print_report_info("shared_buffer_toast_hit_rate: ".format_percent($shared_buffer_toast_hit_rate)); 940 | } 941 | # Tidx hit rate 942 | { 943 | my $shared_buffer_tidx_hit_rate=select_one_value("select sum(tidx_blks_hit)*100/(sum(tidx_blks_read)+sum(tidx_blks_hit)+1) from pg_statio_all_tables ;"); 944 | print_report_info("shared_buffer_tidx_hit_rate: ".format_percent($shared_buffer_tidx_hit_rate)); 945 | } 946 | # Idx hit rate 947 | { 948 | my $shared_buffer_idx_hit_rate=select_one_value("select sum(idx_blks_hit)*100/(sum(idx_blks_read)+sum(idx_blks_hit)+1) from pg_statio_all_tables ;"); 949 | print_report_info("shared_buffer_idx_hit_rate: ".format_percent($shared_buffer_idx_hit_rate)); 950 | if ($shared_buffer_idx_hit_rate > 99.99) { 951 | print_report_info("This is too high. If this PostgreSQL instance was recently used as it usually is and was not stopped since, then you may reduce shared_buffer"); # todo: even on a dedicated server, because it may benefit to the kernel's buffercache 952 | } elsif ($shared_buffer_idx_hit_rate>98) { 953 | print_report_ok("This is very good (if this PostgreSQL instance was recently used as it usually is, and was not stopped since)"); 954 | # todo: however it is not so good if PG is on a non-dedicated machine and not heavily used: it wastes RAM 955 | } elsif ($shared_buffer_idx_hit_rate>90) { 956 | print_report_warn("This is quite good. Increase shared_buffer memory to increase hit rate"); 957 | } else { 958 | print_report_bad("This is too low. Increase shared_buffer memory to increase hit rate"); 959 | } 960 | } 961 | } 962 | 963 | ## Indexes 964 | { 965 | print_header_2("Indexes"); 966 | # Invalid indexes 967 | { 968 | my @Invalid_indexes=select_one_column("SELECT 969 | concat(n.nspname, '.', c.relname) as index 970 | FROM 971 | pg_catalog.pg_class c, 972 | pg_catalog.pg_namespace n, 973 | pg_catalog.pg_index i 974 | WHERE 975 | i.indisvalid = false AND 976 | i.indexrelid = c.oid AND 977 | c.relnamespace = n.oid;"); 978 | if (@Invalid_indexes > 0) { 979 | print_report_bad("List of invalid index in the database: ". join(',', @Invalid_indexes)); 980 | add_advice("index","high","Please check/reindex any invalid index"); 981 | } else { 982 | print_report_ok("No invalid index"); 983 | } 984 | } 985 | # Unused indexes 986 | { 987 | my @Unused_indexes; 988 | if (min_version('9.0')) { 989 | @Unused_indexes=select_one_column("select relname||'.'||indexrelname from pg_stat_user_indexes where idx_scan=0 and not exists (select 1 from pg_constraint where conindid=indexrelid) ORDER BY relname, indexrelname"); 990 | } else { 991 | @Unused_indexes=select_one_column("select relname||'.'||indexrelname from pg_stat_user_indexes where idx_scan=0 ORDER BY relname, indexrelname"); 992 | } 993 | if (@Unused_indexes > 0) { 994 | print_report_warn(@Unused_indexes . " indexes were not used since the last statistics run"); 995 | add_advice("index","medium","You have unused indexes in the database since the last statistics run. Please remove them if they are rarely or not used"); # this is especially useful if the table is frequently updated (insert/delete, or updates hitting indexed columns). todo: checking this? 996 | } else { 997 | print_report_ok("No unused indexes"); 998 | } 999 | } 1000 | } 1001 | 1002 | ## Procedures 1003 | { 1004 | print_header_2("Procedures"); 1005 | # Procedures with default cost 1006 | { 1007 | my @Default_cost_procs=select_one_column("select n.nspname||'.'||p.proname from pg_catalog.pg_proc p left join pg_catalog.pg_namespace n on n.oid = p.pronamespace where pg_catalog.pg_function_is_visible(p.oid) and n.nspname not in ('pg_catalog','information_schema','sys') and p.prorows<>1000 and p.procost<>10 and p.proname not like 'uuid_%' and p.proname != 'pg_stat_statements_reset'"); 1008 | if (@Default_cost_procs > 0) { 1009 | print_report_warn(@Default_cost_procs . " user procedures do not have custom cost and rows settings"); 1010 | add_advice("proc","low","You have custom procedures with default cost and rows setting. Reconfigure them with specific values to help the planner"); 1011 | } else { 1012 | print_report_ok("No procedures with default costs"); 1013 | } 1014 | } 1015 | } 1016 | 1017 | $dbh->disconnect(); 1018 | 1019 | print_advices(); 1020 | 1021 | exit(0); 1022 | 1023 | 1024 | sub preserve_only_digits($) { 1025 | my $str=shift; 1026 | return 0 if (!defined $str); 1027 | $str=~/(\d+)/; # neglect any non-num ('devel', 'RC', 'beta', 'Debian'...) 1028 | return (defined $1) ? $1 : 0; 1029 | } 1030 | 1031 | sub min_version($) { 1032 | my $min_version=shift; 1033 | # die("This script has a bug. min_version called without minor version, line ". [caller(0)]->[2]) # commented out: let's use prototypes! 1034 | # if (!defined $min_version); 1035 | my $cur_version=get_nonvolatile_setting('server_version'); 1036 | my ($min_major,$min_minor)=split(/\./,$min_version); 1037 | my ($cur_major,$cur_minor)=split(/\./,$cur_version); 1038 | die "This script has a bug" if (!defined $cur_major or !defined $cur_minor); 1039 | $cur_major=preserve_only_digits($cur_major); 1040 | $cur_minor=preserve_only_digits($cur_minor); 1041 | return 1 if ($cur_major > $min_major); 1042 | return ($cur_minor >= $min_minor) if ($cur_major == $min_major); 1043 | return 0; 1044 | } 1045 | 1046 | # execute SELECT query, return result as hashref on key 1047 | sub select_all_hashref { 1048 | my ($query,$key)=@_; 1049 | if (!defined($query) or !defined($key)) { 1050 | print { $nocolor ? *STDOUT : *STDERR } "ERROR: Missing query or key\n"; 1051 | exit 1; 1052 | } 1053 | my $sth = $dbh->prepare($query); 1054 | $sth->execute(); 1055 | return $sth->fetchall_hashref($key); 1056 | } 1057 | 1058 | # execute SELECT query, return only one value 1059 | sub select_one_value { 1060 | my ($query)=@_; 1061 | if (!defined($query)) { 1062 | print { $nocolor ? *STDOUT : *STDERR } "ERROR: Missing query\n"; 1063 | exit 1; 1064 | } 1065 | my $sth = $dbh->prepare($query); 1066 | $sth->execute(); 1067 | if (my $result=$sth->fetchrow_arrayref()) { 1068 | return @{$result}[0]; 1069 | } else { 1070 | return undef; 1071 | } 1072 | } 1073 | 1074 | # execute SELECT query, return only one column as array 1075 | sub select_one_column { 1076 | my ($query)=@_; 1077 | if (!defined($query)) { 1078 | print { $nocolor ? *STDOUT : *STDERR } "ERROR: Missing query\n"; 1079 | exit 1; 1080 | } 1081 | my $sth = $dbh->prepare($query); 1082 | $sth->execute(); 1083 | my @Result; 1084 | while (my $result=$sth->fetchrow_arrayref()) { 1085 | push(@Result,@{$result}[0]); 1086 | } 1087 | return @Result; 1088 | } 1089 | 1090 | sub print_report_ok { print_report('ok', shift); } 1091 | sub print_report_warn { print_report('warn', shift); } 1092 | sub print_report_bad { print_report('bad', shift); } 1093 | sub print_report_info { print_report('info', shift); } 1094 | sub print_report_todo { print_report('todo', shift); } 1095 | sub print_report_unknown { print_report('unknown', shift); } 1096 | sub print_report_debug { print_report('debug', shift); } 1097 | 1098 | sub print_report { 1099 | my ($type,$message)=@_; 1100 | if ($type eq "ok") { 1101 | print STDOUT color('green') ."[OK] ".color('reset').$message."\n"; 1102 | } elsif ($type eq "warn") { 1103 | print STDOUT color('yellow') ."[WARN] ".color('reset').$message."\n"; 1104 | } elsif ($type eq "bad") { 1105 | print { $nocolor ? *STDOUT : *STDERR } color('red') ."[BAD] ".color('reset').$message."\n"; 1106 | } elsif ($type eq "info") { 1107 | print { $nocolor ? *STDOUT : *STDERR } color('white') ."[INFO] ".color('reset').$message."\n"; 1108 | } elsif ($type eq "todo") { 1109 | print { $nocolor ? *STDOUT : *STDERR } color('magenta')."[TODO] ".color('reset').$message."\n"; 1110 | } elsif ($type eq "unknown") { 1111 | print STDOUT color('cyan') ."[UNKNOWN] ".color('reset').$message."\n"; 1112 | } elsif ($type eq "debug") { 1113 | print { $nocolor ? *STDOUT : *STDERR } color('magenta')."[DEBUG] ".color('reset').$message."\n"; 1114 | } else { 1115 | die("This script has a bug. Unknown report type ($type) line ". [caller(0)]->[2]); 1116 | } 1117 | } 1118 | 1119 | sub print_header_1 { print_header(1,shift); } 1120 | sub print_header_2 { print_header(2,shift); } 1121 | 1122 | sub print_header { 1123 | my ($level,$title)=@_; 1124 | my $sep=''; 1125 | if ($level == 1) { 1126 | print color('white'); 1127 | $sep='='; 1128 | } elsif ($level == 2) { 1129 | print color('white'); 1130 | $sep='-'; 1131 | } else { 1132 | warn("Unknown level $level for title $title"); 1133 | } 1134 | print $sep x 5 ." $title ". $sep x 5; 1135 | print color('reset'); 1136 | print "\n"; 1137 | } 1138 | 1139 | sub get_setting { 1140 | my $name=shift; 1141 | if (!defined($settings->{$name})) { 1142 | print { $nocolor ? *STDOUT : *STDERR } "ERROR: the setting $name does not exist in this PostgreSQL version, please upgrade\n"; 1143 | die "Aborting"; 1144 | } else { 1145 | return standard_units($settings->{$name}->{setting}, $settings->{$name}->{unit}); 1146 | } 1147 | } 1148 | 1149 | sub get_nonvolatile_setting { 1150 | return get_setting(shift); 1151 | } 1152 | 1153 | sub standard_units { 1154 | my $value=shift; 1155 | my $unit=shift; 1156 | return $value if !$unit; 1157 | return $value*1024 if $unit eq 'kB' or $unit eq 'K'; 1158 | return $value*8*1024 if $unit eq '8kB'; 1159 | return $value*16*1024 if $unit eq '16kB'; 1160 | return $value*1024*1024 if $unit eq 'M' or $unit eq 'MB'; 1161 | return $value*1024*1024*1024 if $unit eq 'G' or $unit eq 'GB'; 1162 | return $value*1024*1024*1024*1024 if $unit eq 'T' or $unit eq 'TB'; 1163 | return $value*1024*1024*1024*1024*1024 if $unit eq 'P' or $unit eq 'PB'; 1164 | return $value.'s' if $unit eq 's'; 1165 | return $value.'ms' if $unit eq 'ms'; 1166 | } 1167 | 1168 | sub format_size { 1169 | my $size=shift; 1170 | my @units=('B','KB','MB','GB','TB','PB'); 1171 | my $unit_index=0; 1172 | return 0 if !defined($size); 1173 | while ($size>1024) { 1174 | $size=$size/1024; 1175 | $unit_index++; 1176 | } 1177 | return sprintf("%.2f %s",$size,$units[$unit_index]); 1178 | } 1179 | 1180 | sub format_percent { 1181 | my $value=shift; 1182 | return sprintf("%.2f%%",$value); 1183 | } 1184 | 1185 | sub format_epoch_to_time { 1186 | my $epoch=shift; 1187 | my $time=''; 1188 | if ($epoch > $day_s) { 1189 | my $days=sprintf("%d",$epoch/$day_s); 1190 | $epoch=$epoch%$day_s; 1191 | $time.=$days.'d'; 1192 | } 1193 | if ($epoch > $hour_s) { 1194 | my $hours=sprintf("%d",$epoch/$hour_s); 1195 | $epoch=$epoch%$hour_s; 1196 | $time.=' '.sprintf("%02d",$hours).'h'; 1197 | } 1198 | if ($epoch > $min_s) { 1199 | my $mins=sprintf("%d",$epoch/$min_s); 1200 | $epoch=$epoch%$min_s; 1201 | $time.=' '.sprintf("%02d",$mins).'m'; 1202 | } 1203 | $time.=' '.sprintf("%02d",$epoch).'s'; 1204 | return $time; 1205 | } 1206 | 1207 | sub os_cmd { 1208 | my $command=$os_cmd_prefix.shift; 1209 | local $SIG{__WARN__} = sub {}; 1210 | my $result=`$command 2>&1`; 1211 | if ( $? == 0 ) { 1212 | return $result; 1213 | } else { 1214 | warn("Command $command failed"); 1215 | return undef; 1216 | } 1217 | } 1218 | 1219 | sub try_load { 1220 | my ($mod,$package_cmd)=@_; 1221 | eval("use $mod"); 1222 | if ($@) { 1223 | print { $nocolor ? *STDOUT : *STDERR } "# Missing Perl module '$mod'. Please install it\n"; 1224 | for my $check (keys %$package_cmd) { 1225 | print $package_cmd->{$check}."\n" if -f $check; 1226 | } 1227 | return 1; 1228 | } else { 1229 | return 0; 1230 | } 1231 | } 1232 | 1233 | sub get_sysctl { 1234 | my $name=shift; 1235 | $name=~s/\./\//g; 1236 | my $value=os_cmd("cat /proc/sys/$name"); 1237 | if (!defined($value)) { 1238 | print_report_unknown("Unable to read sysctl $name"); 1239 | return undef; 1240 | } else { 1241 | chomp($value); 1242 | return $value; 1243 | } 1244 | } 1245 | 1246 | sub add_advice { 1247 | my ($category,$priority,$advice)=@_; 1248 | $priority='high' if ($priority eq 'urgent'); 1249 | die("This script has a bug. Unknown priority '$priority', line ". [caller(0)]->[2]) if ($priority !~ /(high|medium|low)/); 1250 | die("This script has a bug. No advice text, line ". [caller(0)]->[2]) if (! defined $advice); 1251 | push(@{$advices{$category}{$priority}},$advice); 1252 | } 1253 | 1254 | sub print_advices { 1255 | print "\n"; 1256 | print_header_1("Configuration advice"); 1257 | my $advice_count=0; 1258 | foreach my $category (sort(keys(%advices))) { 1259 | print_header_2($category); 1260 | foreach my $priority (sort(keys(%{$advices{$category}}))) { 1261 | if ($priority eq "high") { 1262 | print color("red") 1263 | } elsif ( $priority eq "medium") { 1264 | print color("yellow") 1265 | } elsif ( $priority eq "low" ) { 1266 | print color("magenta") 1267 | } 1268 | foreach my $advice (@{$advices{$category}{$priority}}) { 1269 | print "[".uc($priority)."] $advice\n"; 1270 | $advice_count++; 1271 | } 1272 | print color("reset"); 1273 | } 1274 | } 1275 | if ($advice_count == 0) { 1276 | print color("green")."Everything is OK".color("reset")."\n"; 1277 | } 1278 | } 1279 | 1280 | sub pgpass_match { 1281 | my ($type,$var,$pgp_var)=@_; 1282 | $pgp_var=pgpass_unescape($pgp_var); 1283 | return 1 if $pgp_var eq '*'; 1284 | return 1 if $pgp_var eq $var; 1285 | return 1 if $type eq 'host' and $pgp_var eq 'localhost' and $var=~m/^\//; # allow sockets if host=localhost 1286 | return 0; 1287 | } 1288 | 1289 | sub pgpass_unescape { 1290 | my ($value)=@_; 1291 | $value=~s/\\(.)/$1/g; 1292 | return $value; 1293 | } 1294 | --------------------------------------------------------------------------------