├── LICENSE.md ├── META.json ├── Makefile ├── README.md ├── TODO.md ├── pg_kaboom--0.0.1.sql ├── pg_kaboom.c ├── pg_kaboom.control ├── static └── pg_kaboom_logo.png └── t └── 001_basic.pl /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | Copyright 2022-2024 Crunchy Data Solutions, Inc. 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /META.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pg_kaboom", 3 | "abstract": "Devious SQL-based SQL tools to crash your PostgreSQL server", 4 | "description": "Fault Injection Software to generate specific types of crashes in your Postgres server", 5 | "version": "0.0.1", 6 | "maintainer": [ 7 | "David Christensen " 8 | ], 9 | "license": "apache_2_0", 10 | "provides": { 11 | "pg_kaboom": { 12 | "abstract": "Blow things up in interesting and useful^W^W ways", 13 | "file": "pg_kaboom.c", 14 | "docfile": "README.md", 15 | "version": "0.0.1" 16 | } 17 | }, 18 | "prereqs": { 19 | "runtime": { 20 | "requires": { 21 | "PostgreSQL": "12.0.0" 22 | } 23 | } 24 | }, 25 | "resources": { 26 | "bugtracker": { 27 | "web": "https://github.com/pgguru/pg_kaboom/issues/" 28 | }, 29 | "repository": { 30 | "url": "git://github.com/pgguru/pg_kaboom.git", 31 | "web": "https://github.com/pgguru/pg_kaboom/", 32 | "type": "git" 33 | } 34 | }, 35 | "generated_by": "David Christensen", 36 | "meta-spec": { 37 | "version": "1.0.0", 38 | "url": "https://pgxn.org/meta/spec.txt" 39 | }, 40 | "tags": [ 41 | "kaboom", 42 | "crash", 43 | "testing", 44 | "failover" 45 | ] 46 | } 47 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | EXTENSION = pg_kaboom 2 | MODULE_big = pg_kaboom 3 | DATA = pg_kaboom--0.0.1.sql 4 | OBJS = pg_kaboom.o 5 | TAP_TESTS = t/001_basic.pl 6 | PG_CONFIG ?= pg_config 7 | PG_CFLAGS := -Wno-missing-prototypes -Wno-deprecated-declarations -Wno-unused-result 8 | PGXS := $(shell $(PG_CONFIG) --pgxs) 9 | include $(PGXS) 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pg_kaboom 2 | 3 | [![pg_kaboom logo](https://github.com/pgguru/pg_kaboom/raw/main/static/pg_kaboom_logo.png)](https://github.com/pgguru/pg_kaboom/) 4 | [![PGXN version](https://badge.fury.io/pg/pg_kaboom.svg)](https://badge.fury.io/pg/pg_kaboom) 5 | 6 | > Where's the kaboom?! There's supposed to be an Earth-shattering kaboom! 7 | 8 | This extension serves to crash postgresql in multiple varied and destructive ways. 9 | 10 | ## But why? 11 | 12 | Testing of failover can be hard to do from SQL; some things are nice to expose via SQL functions. This is one of those things. 13 | 14 | ## Is this safe? 15 | 16 | **Hell, no**. Under no circumstances should you use this extension on a production cluster; this is purely for testing things out in a development environment. 17 | 18 | We require you to set a GUC variable `pg_kaboom.disclaimer` to a magic value in order for any of these functions to do anything. That said, there are often times where simulating different breakage scenarios are useful. Under no way are we liable for anything you do with this software. This is provided without warranty and complete disclaimer. 19 | 20 | This is your final warning! You *will* lose data! 21 | 22 | ## Installation 23 | 24 | ```console 25 | $ git clone git@github.com:CrunchyData/pg_kaboom.git 26 | $ cd pg_kaboom 27 | $ make PG_CONFIG=path/to/pg_config && make install PG_CONFIG=path/to/pg_config 28 | $ psql -c 'CREATE EXTENSION pg_kaboom' -U -d 29 | ``` 30 | 31 | ## Usage 32 | 33 | Once this extension is installed in the database you wish to ~~destroy~~ use, you will just need to run the function `pg_kaboom(text)` with the given weapon of breakage. 34 | 35 | That said, we want to make sure that you are *really sure* you want to do these **destructive** operations. You should **never** install this extension on a production server. And you are **required** to issue the following per-session statement in order to do anything with this extension: 36 | 37 | ```sql 38 | SET pg_kaboom.disclaimer = 'I can afford to lose this data and server'; 39 | SET pg_kaboom.execute = on; -- required for shell command-based running; additional safety value. Not all weapons respect this. 40 | SELECT pg_kaboom('segfault'); 41 | 42 | -- backend segfaults, exeunt 43 | ``` 44 | 45 | ## Available Weapons 46 | 47 | Currently defined weapons (more to come) are: 48 | 49 | - `break-archive` :: install a broken `archive_command` and force a restart 50 | 51 | - `fill-log` :: allocate all of the space inside the logs directory 52 | 53 | - `fill-pgdata` :: allocate all of the space inside the $PGDATA directory 54 | 55 | - `fill-pgwal` :: allocate all of the space inside the $PGDATA/pg_wal directory 56 | 57 | - `mem` :: allocate some memory 58 | 59 | - `restart` :: do an immediate restart of the server 60 | 61 | - `rm-pgdata` :: do a `rm -Rf $PGDATA` 62 | 63 | - `segfault` :: cause a segfault in the running backend process 64 | 65 | - `signal` :: send a `SIGKILL` to the Postmaster process 66 | 67 | - `xact-wrap` :: force the database to run an xact-wraparound vacuum 68 | 69 | You can also use the following "special" weapons: 70 | 71 | - `random` :: choose a random weapon 72 | 73 | - `null` :: don't do anything, just go through the normal flow 74 | 75 | 76 | Contributions welcome! Let's get creative in testing how PostgreSQL can recover/respond to various systems meddling! 77 | 78 | ## Author 79 | 80 | David Christensen , 81 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | ## weapons 4 | - shmem corruption 5 | - clog truncation/corruption 6 | - random system backend killing 7 | - chmod 000 on random files 8 | - checksum invalidation 9 | - other random page corruption 10 | - delayed WAL application 11 | - more! 12 | 13 | ## testing 14 | - get some testing going 15 | - hard to test failures for failing the right way, but come up with ways to do this safely 16 | - to test fill_log, etc, without hurting host machine will need to setup loopback filesystems 17 | - can this be done inside the Pg `make check` target, or do we need our own custom harness? 18 | -------------------------------------------------------------------------------- /pg_kaboom--0.0.1.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION pg_kaboom(method text, payload jsonb default NULL) 2 | RETURNS boolean AS 'MODULE_PATHNAME', 'pg_kaboom' 3 | LANGUAGE C VOLATILE; 4 | 5 | CREATE FUNCTION pg_kaboom_arsenal() 6 | RETURNS TABLE (weapon_name text, description text) 7 | AS 'MODULE_PATHNAME', 'pg_kaboom_arsenal' 8 | LANGUAGE C STRICT; 9 | -------------------------------------------------------------------------------- /pg_kaboom.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022-2024 Crunchy Data Solutions, Inc. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | #include "postgres.h" 15 | #include "fmgr.h" 16 | #include "funcapi.h" 17 | #include "miscadmin.h" 18 | #include "utils/guc.h" 19 | #include "utils/numeric.h" 20 | #include "utils/jsonb.h" 21 | #include "tcop/tcopprot.h" 22 | #include "utils/builtins.h" 23 | #include "storage/ipc.h" 24 | #include "pgstat.h" 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | #define PG_KABOOM_DISCLAIMER "I can afford to lose this data and server" 31 | 32 | #define PG_MAJOR_VERSION (PG_VERSION_NUM / 100) 33 | 34 | /* compatibility macros */ 35 | #if PG_MAJOR_VERSION < 1600 36 | #define GET_BEENTRY(i) pgstat_fetch_stat_beentry(i); 37 | #else 38 | #define GET_BEENTRY(i) pgstat_get_beentry_by_backend_id(i); 39 | #endif 40 | 41 | 42 | #define WPN_ARGS Jsonb *payload, char *arg 43 | 44 | /* function signature for the weapon implementation; "payload" is for weapon customization; "arg" is 45 | static so can expose multiple weapons with same function implementation */ 46 | 47 | typedef void (*wpn_impl)(WPN_ARGS); 48 | 49 | typedef struct Weapon { 50 | char *wpn_name; 51 | wpn_impl wpn_impl; 52 | char *wpn_arg; 53 | char *wpn_desc; 54 | } Weapon; 55 | 56 | /* weapon prototypes */ 57 | static void wpn_special(WPN_ARGS); 58 | static void wpn_break_archive(WPN_ARGS); 59 | static void wpn_fill_log(WPN_ARGS); 60 | static void wpn_fill_pgdata(WPN_ARGS); 61 | static void wpn_fill_pgwal(WPN_ARGS); 62 | static void wpn_mem(WPN_ARGS); 63 | static void wpn_restart(WPN_ARGS); 64 | static void wpn_segfault(WPN_ARGS); 65 | static void wpn_signal(WPN_ARGS); 66 | static void wpn_rm_pgdata(WPN_ARGS); 67 | static void wpn_xact_wrap(WPN_ARGS); 68 | 69 | Weapon weapons[] = { 70 | /* "special" weapons */ 71 | { "random" , &wpn_special , "random" , "select a random non-special weapon" }, 72 | { "null" , &wpn_special , "null" , "noop" }, 73 | 74 | { "break-archive" , &wpn_break_archive , NULL, "force archive failures" }, 75 | { "fill-log" , &wpn_fill_log , NULL, "use all the space in the log directory" }, 76 | { "fill-pgdata" , &wpn_fill_pgdata , NULL, "use all the space in the pgdata directory" }, 77 | { "fill-pgwal" , &wpn_fill_pgwal , NULL, "use all the space in the pg_wal directory" }, 78 | { "mem" , &wpn_mem , NULL, "allocate memory in different contexts" }, 79 | { "restart" , &wpn_restart , NULL, "force an immediate restart" }, 80 | { "segfault" , &wpn_segfault , NULL, "segfault inside a backend process" }, 81 | { "signal" , &wpn_signal , NULL, "send a signal to the postmaster (KILL by default)" }, 82 | { "rm-pgdata" , &wpn_rm_pgdata , NULL, "remove the pgdata directory" }, 83 | { "xact-wrap" , &wpn_xact_wrap , NULL, "force wraparound autovacuum" }, 84 | { NULL, NULL, NULL, NULL } 85 | }; 86 | 87 | #define NUM_WEAPONS (sizeof(weapons)/sizeof(Weapon) - 1) 88 | 89 | /* global variables */ 90 | static char *disclaimer; 91 | static char *pgdata_path = NULL; 92 | static bool execute = false; 93 | 94 | /* sanity/utility routines */ 95 | static void validate_we_can_blow_up_things(); 96 | static void validate_we_can_restart(); 97 | static void restart_database(); 98 | static void load_pgdata_path(); 99 | static void fill_disk_at_path(char *path, char *subpath); 100 | static void command_with_path(char *command, char *path, bool detach); 101 | static void command_with_path_internal(char *command, char *arg1, char *arg2, bool detach); 102 | static void force_settings_and_restart(char **setting, char **value); 103 | static char *quoted_string(char * setting); 104 | static char *missing_weapon_hint(); 105 | static char *simple_get_json_str(Jsonb *in, char *key); 106 | static int simple_get_json_int(Jsonb *in, char *key); 107 | static pid_t find_random_pid_of_type(char *type); 108 | 109 | /* constants snarfed from postmaster.c; no include */ 110 | #define BACKEND_TYPE_NORMAL 0x0001 /* normal backend */ 111 | #define BACKEND_TYPE_AUTOVAC 0x0002 /* autovacuum worker process */ 112 | #define BACKEND_TYPE_WALSND 0x0004 /* walsender process */ 113 | #define BACKEND_TYPE_BGWORKER 0x0008 /* bgworker process */ 114 | #define BACKEND_TYPE_ALL 0x000F /* OR of all the above */ 115 | 116 | 117 | PG_MODULE_MAGIC; 118 | 119 | void _PG_init(void); 120 | void _PG_fini(void); 121 | 122 | Datum pg_kaboom(PG_FUNCTION_ARGS); 123 | Datum pg_kaboom_arsenal(PG_FUNCTION_ARGS); 124 | 125 | PG_FUNCTION_INFO_V1(pg_kaboom); 126 | PG_FUNCTION_INFO_V1(pg_kaboom_arsenal); 127 | 128 | void _PG_init(void) 129 | { 130 | /* ... C code here at time of extension loading ... */ 131 | DefineCustomStringVariable("pg_kaboom.disclaimer", 132 | gettext_noop("Disclaimer variable you must set for the pg_kaboom extension to work. Required value is: '" 133 | PG_KABOOM_DISCLAIMER "'"), 134 | NULL, 135 | &disclaimer, 136 | "", 137 | PGC_USERSET, 0, 138 | NULL, NULL, NULL); 139 | 140 | DefineCustomStringVariable("pg_kaboom.saved_archive_command", 141 | gettext_noop("Storage for the old archive_command if we have replaced this one"), 142 | NULL, 143 | &disclaimer, 144 | "", 145 | PGC_USERSET, 0, 146 | NULL, NULL, NULL); 147 | 148 | DefineCustomBoolVariable("pg_kaboom.execute", 149 | gettext_noop("Whether to actually run the commands that are generated"), 150 | NULL, 151 | &execute, 152 | 0, 153 | PGC_USERSET, 0, 154 | NULL, NULL, NULL); 155 | 156 | load_pgdata_path(); 157 | } 158 | 159 | void _PG_fini(void) 160 | { 161 | /* ... C code here at time of extension unloading ... */ 162 | } 163 | 164 | #define UNKNOWN_HINT_MESSAGE_PREFIX "must be one of: " 165 | 166 | Datum pg_kaboom(PG_FUNCTION_ARGS) 167 | { 168 | char *op = TextDatumGetCString(PG_GETARG_DATUM(0)); 169 | Jsonb *payload = NULL; 170 | Weapon *weapon = weapons; 171 | 172 | /* special gating function check; will abort if everything isn't allowed */ 173 | validate_we_can_blow_up_things(); 174 | 175 | /* check for payload */ 176 | if (!PG_ARGISNULL(1)) 177 | payload = PG_GETARG_JSONB_P(1); 178 | 179 | /* now check how we want to blow things up; linear search for matching name ... */ 180 | while (weapon->wpn_name && pg_strcasecmp(weapon->wpn_name, op) != 0) 181 | weapon++; 182 | 183 | if (weapon->wpn_name) { 184 | /* we matched a weapon name */ 185 | weapon->wpn_impl(payload, weapon->wpn_arg); 186 | PG_RETURN_BOOL(1); 187 | } else { 188 | ereport(NOTICE, errmsg("unrecognized operation: '%s'", op), errhint("%s", missing_weapon_hint())); 189 | PG_RETURN_BOOL(0); 190 | } 191 | } 192 | 193 | static char *missing_weapon_hint() { 194 | char *hint, *p; 195 | int i; 196 | size_t weapon_size = 0; 197 | Weapon *weapon; 198 | 199 | /* calculate the sum of all of the weapon names */ 200 | weapon = weapons; 201 | while (weapon->wpn_name) { 202 | weapon_size += strlen(weapon->wpn_name); 203 | weapon++; 204 | } 205 | 206 | /* leading text, the word "or " and trailing newline, 207 | additional padding for formatting - 4 bytes per, quote quote comma space */ 208 | weapon_size += sizeof(UNKNOWN_HINT_MESSAGE_PREFIX) + 4 + NUM_WEAPONS * 4; 209 | 210 | /* now allocate the message buffer */ 211 | p = hint = palloc(weapon_size); 212 | 213 | /* start with the hint prefix */ 214 | p = stpcpy(p, UNKNOWN_HINT_MESSAGE_PREFIX); 215 | 216 | /* do our individual copy now of each weapon name, stopping before the last one for the "OR" */ 217 | for (i = 0; i < NUM_WEAPONS - 1; i++) { 218 | *p++ = '\''; 219 | p = stpcpy(p, weapons[i].wpn_name); 220 | *p++ = '\''; 221 | if (i != NUM_WEAPONS - 2) 222 | *p++ = ','; 223 | *p++ = ' '; 224 | } 225 | 226 | /* final item; only do the " or " if we have more than one */ 227 | if (NUM_WEAPONS > 1) { 228 | p = stpcpy(p, "or "); 229 | } 230 | 231 | *p++ = '\''; 232 | p = stpcpy(p, weapons[NUM_WEAPONS - 1].wpn_name); 233 | *p++ = '\''; 234 | *p++ = '.'; 235 | *p++ = '\0'; 236 | 237 | return hint; 238 | } 239 | 240 | static void validate_we_can_blow_up_things() { 241 | #ifdef WIN32 242 | /* bail out on windows */ 243 | ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 244 | errmsg("function not supported on Windows (aren't things already broken enough?)"))); 245 | #endif 246 | 247 | /* check that we are running as a superuser */ 248 | if (!session_auth_is_superuser) 249 | ereport(ERROR, 250 | (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), 251 | errmsg("must run this function as a superuser"))); 252 | 253 | /* check disclaimer for matching value */ 254 | if (!disclaimer || strcmp(disclaimer, PG_KABOOM_DISCLAIMER)) 255 | ereport(ERROR, 256 | (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), 257 | errmsg("for safety, pg_kaboom.disclaimer must be explicitly set to '%s'", 258 | PG_KABOOM_DISCLAIMER))); 259 | } 260 | 261 | static void load_pgdata_path() { 262 | if (!pgdata_path) { 263 | MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext); 264 | pgdata_path = pstrdup(GetConfigOptionByName("data_directory", NULL, false)); 265 | MemoryContextSwitchTo(oldcontext); 266 | 267 | if (!pgdata_path || !strlen(pgdata_path)) 268 | ereport(ERROR, 269 | (errcode_for_file_access(), 270 | errmsg("data directory not found"))); 271 | } 272 | } 273 | 274 | #define fill_disk_format "/bin/dd if=/dev/zero of=%s/pg_kaboom_space_filler bs=1m" 275 | static void fill_disk_at_path(char *path, char *subpath) { 276 | /* we control the callers, so path will always be non-null */ 277 | struct stat buf; 278 | 279 | /* if subpath is set, append to original path */ 280 | if (subpath && *subpath) { 281 | int len = strlen(path); 282 | char *p = palloc(len + strlen(subpath) + 2); /* separator + newline */ 283 | strcpy(p, path); 284 | p[len] = '/'; 285 | strcpy(p + len + 1, subpath); 286 | path = p; 287 | } 288 | 289 | /* ensure path is an actual directory */ 290 | if (stat(path, &buf) < 0 || !S_ISDIR(buf.st_mode) || access(path, W_OK) < 0) 291 | ereport(ERROR, 292 | (errcode_for_file_access(), 293 | errmsg("'%s' is not a writable directory", path))); 294 | 295 | command_with_path(fill_disk_format, path, false); 296 | } 297 | 298 | /* helper to run a command with a path substitute */ 299 | static void command_with_path(char *template, char *path, bool detach) { 300 | /* sanity-check our path here ... */ 301 | if (!path || !*path) 302 | ereport(ERROR, errmsg("can't run with empty path")); 303 | 304 | if (path[0] != '/') 305 | ereport(ERROR, errmsg("cowardly not running with relative path")); 306 | 307 | command_with_path_internal(template, path, "", detach); 308 | } 309 | 310 | static void command_with_path_internal(char *template, char *arg1, char *arg2, bool detach) { 311 | /* even when crashing things, proper memory offsets are still classy; note we do waste a byte or 312 | two (with '%s'), which when filling up entire disks is a venial sin at best */ 313 | 314 | char *command = palloc(strlen(template) + strlen(arg1) + strlen(arg2)); 315 | sprintf(command, template, arg1, arg2); 316 | ereport(NOTICE, errmsg("%srunning command: '%s'", (execute ? "" : "(dry-run) "), command)); 317 | if (execute) { 318 | if (detach) { 319 | /* this is yucky, and probably not that good, however it appears to work */ 320 | daemon(0,0); /* deprecated warnings, but appears to function */ 321 | 322 | if (fork()) /* extra fork needed due to only one level of fork() + setsid() */ 323 | proc_exit(0); /* exit cleanly for pg -- such that it matters */ 324 | setsid(); 325 | system(command); 326 | } else 327 | system(command); 328 | } 329 | } 330 | 331 | static void validate_we_can_restart() { 332 | /* check and error out early if it looks like we can't force a restart */ 333 | 334 | /* for now do nothing */ 335 | } 336 | 337 | static void restart_database() { 338 | /* run pg_ctl to restart this database cluster */ 339 | 340 | /* it is definitely possible this will not work in all cases (systemd overrides, etc) */ 341 | /* TODO: read/parse /proc invocation of postmaster and just issue that instead? */ 342 | 343 | /* for now, we will just force an immediate shutdown and then run pg_ctl -D $pgdata start */ 344 | #define template_template "bash -c 'kill -9 %d; sleep 1; %s -D %%s start -l /tmp/pg_kaboom_startup.log'" 345 | char pg_ctl_path[MAXPGPATH]; 346 | char command_template[MAXPGPATH + sizeof(template_template)]; 347 | if (find_other_exec(my_exec_path, "pg_ctl", PG_BACKEND_VERSIONSTR, 348 | pg_ctl_path) < 0) 349 | ereport(FATAL, 350 | (errmsg("%s: could not locate matching pg_ctl executable", 351 | my_exec_path))); 352 | 353 | snprintf(command_template, MAXPGPATH + sizeof(template_template), template_template, PostmasterPid, pg_ctl_path); 354 | command_with_path(command_template, pgdata_path, true); 355 | } 356 | 357 | static void force_settings_and_restart(char **settings, char **values) { 358 | char sql[255]; 359 | List *raw_parsetree_list; 360 | ListCell *lc1; 361 | 362 | validate_we_can_restart(); 363 | 364 | while (*settings && *values) { 365 | char *setting = settings[0]; 366 | char *value = values[0]; 367 | 368 | settings++; 369 | values++; 370 | 371 | /* tried using ALTER SYSTEM directly via SPI, but won't run in a function block */ 372 | /* so we are trying to hack the parser and invoke directly */ 373 | 374 | snprintf(sql, 255, "ALTER SYSTEM SET %s = %s", setting, value); 375 | 376 | raw_parsetree_list = pg_parse_query((const char*)sql); 377 | 378 | if (raw_parsetree_list && list_length(raw_parsetree_list) == 1) { 379 | foreach(lc1, raw_parsetree_list) { 380 | RawStmt *parsetree = lfirst_node(RawStmt, lc1); 381 | AlterSystemSetConfigFile((AlterSystemStmt*)parsetree->stmt); 382 | } 383 | } else { 384 | ereport(ERROR, 385 | (errcode(ERRCODE_SYNTAX_ERROR), 386 | errmsg("error running ALTER SYSTEM"))); 387 | } 388 | } 389 | 390 | sleep(1); 391 | restart_database(); 392 | } 393 | 394 | static char *quoted_string (char *setting) { 395 | size_t size = strlen(setting) + 3; 396 | char *qstring = palloc(size); /* start quote, end quote, newline */ 397 | snprintf(qstring, size, "'%s'", setting); 398 | 399 | return qstring; 400 | } 401 | 402 | /* simple handlers for pulling expected values from JSON type */ 403 | /* returns NULL if missing, or -1 if an int */ 404 | static char *simple_get_json_str(Jsonb *in, char *key) { 405 | JsonbValue *jsonkey, *jsonval; 406 | char *str = NULL; 407 | 408 | Assert(in != NULL); 409 | Assert(key != NULL); 410 | Assert(JB_ROOT_IS_OBJECT(in)); 411 | 412 | jsonkey = palloc(sizeof(JsonbValue)); 413 | jsonkey->type = jbvString; 414 | jsonkey->val.string.len = strlen(key); 415 | jsonkey->val.string.val = key; 416 | 417 | jsonval = findJsonbValueFromContainer(&in->root, JB_FOBJECT, jsonkey); 418 | 419 | if (!jsonval) 420 | return NULL; 421 | 422 | /* check if it is a simple scalar value, which it should be */ 423 | if (jsonval->type != jbvString) 424 | ereport(ERROR, errmsg("expected string type")); 425 | 426 | str = palloc(jsonval->val.string.len + 1); 427 | strncpy(str, jsonval->val.string.val, jsonval->val.string.len); 428 | str[jsonval->val.string.len] = '\0'; 429 | 430 | pfree(jsonkey); 431 | pfree(jsonval); 432 | 433 | return str; 434 | } 435 | 436 | static int simple_get_json_int(Jsonb *in, char *key) { 437 | JsonbValue *jsonkey, *jsonval; 438 | char *str; 439 | int ret; 440 | 441 | Assert(in != NULL); 442 | Assert(key != NULL); 443 | Assert(JB_ROOT_IS_OBJECT(in)); 444 | 445 | jsonkey = palloc(sizeof(JsonbValue)); 446 | jsonkey->type = jbvString; 447 | jsonkey->val.string.len = strlen(key); 448 | jsonkey->val.string.val = key; 449 | 450 | jsonval = findJsonbValueFromContainer(&in->root, JB_FOBJECT, jsonkey); 451 | 452 | if (!jsonval) 453 | return -1; 454 | 455 | /* check if it is a simple scalar value, which it should be */ 456 | if (jsonval->type != jbvNumeric) 457 | ereport(ERROR, errmsg("expected integer type")); 458 | 459 | str = numeric_normalize(jsonval->val.numeric); 460 | 461 | pfree(jsonkey); 462 | pfree(jsonval); 463 | 464 | if (str && parse_int(str, &ret, 0, NULL)) 465 | return ret; 466 | 467 | ereport(ERROR, errmsg("expected integer type")); 468 | 469 | return -1; 470 | } 471 | 472 | /* find a backend of the given type randomly; if picking a client backend, excludes this specific 473 | backend for obvious reasons. returns the pid of the process or 0 if not found */ 474 | 475 | static pid_t find_random_pid_of_type(char *type) { 476 | int i, 477 | startIdx, 478 | num_procs = pgstat_fetch_stat_numbackends(), 479 | backend_type; 480 | pid_t pid = 0; 481 | bool is_first = true; 482 | 483 | /* first calculate the backend_type based on "type" param */ 484 | backend_type = 485 | !pg_strcasecmp("backend", type) ? BACKEND_TYPE_NORMAL : 486 | !pg_strcasecmp("autovac", type) ? BACKEND_TYPE_AUTOVAC : 487 | !pg_strcasecmp("walsender", type) ? BACKEND_TYPE_WALSND : 488 | !pg_strcasecmp("bgworker", type) ? BACKEND_TYPE_BGWORKER : 489 | 0 490 | ; 491 | 492 | /* TODO: add Auxilary Procs handling to allow you to target them too */ 493 | if (!backend_type) 494 | ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 495 | errmsg("can't find backend of type %s", type))); 496 | 497 | /* pick a start index based on a random entry point into the ProcArray */ 498 | i = startIdx = random() % num_procs; 499 | 500 | /* do a linear wrapping search through the array starting at the random offset */ 501 | for (i = startIdx; i != startIdx || is_first; i = ((i + 1) >= num_procs ? 0 : i + 1), is_first = false) { 502 | PgBackendStatus *st = GET_BEENTRY(i); 503 | if (st && st->st_procpid > 0 && st->st_procpid != MyProcPid) { 504 | /* check for correct backend type and exit loop if so */ 505 | if (st->st_backendType == backend_type) { 506 | pid = st->st_procpid; 507 | break; 508 | } 509 | } 510 | } 511 | 512 | return pid; 513 | } 514 | 515 | /* Weapon definitions */ 516 | 517 | static void wpn_special(WPN_ARGS) { 518 | /* this is a "special" metaweapon, not a weapon itself */ 519 | if (!pg_strcasecmp(arg, "random")) { 520 | int wpn_idx; 521 | 522 | do { 523 | /* doesn't need to be secure, just pseudo-random is fine */ 524 | wpn_idx = rand() % NUM_WEAPONS; 525 | 526 | /* exclude "null" and "random" from random selection */ 527 | } while (!strcmp(weapons[wpn_idx].wpn_name, "null") || 528 | !strcmp(weapons[wpn_idx].wpn_name, "random")); 529 | 530 | ereport(NOTICE, errmsg("deviously selecting the random weapon '%s'", 531 | weapons[wpn_idx].wpn_name)); 532 | 533 | weapons[wpn_idx].wpn_impl(payload, weapons[wpn_idx].wpn_arg); 534 | } else if (!pg_strcasecmp(arg, "null")) { 535 | ereport(NOTICE, errmsg("intentionally doing nothing")); 536 | } 537 | } 538 | 539 | static void wpn_break_archive(WPN_ARGS) { 540 | char *bad_archive_command = payload ? simple_get_json_str(payload, "archive_command") : "/usr/bin/false"; 541 | char *archive_command = GetConfigOptionByName("archive_command", NULL, false); 542 | char *settings[] = { "archive_mode", "archive_command", "pg_kaboom.saved_archive_command", NULL }; 543 | char *values[] = { "on", quoted_string(bad_archive_command), quoted_string(archive_command), NULL }; 544 | 545 | force_settings_and_restart(settings, values); 546 | } 547 | 548 | static void wpn_fill_log(WPN_ARGS) { 549 | char *log_destination = GetConfigOptionByName("log_destination", NULL, false); 550 | char *log_directory = GetConfigOptionByName("log_directory", NULL, false); 551 | 552 | if (pg_strcasecmp(log_destination, "stderr") || !*log_directory) 553 | ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 554 | errmsg("can only fill up log_directory if stderr and set"))); 555 | 556 | /* if an absolute path, just use that, otherwise append to the data directory */ 557 | if (*log_directory == '/') 558 | fill_disk_at_path(log_directory, NULL); 559 | else 560 | fill_disk_at_path(pgdata_path, log_directory); 561 | } 562 | 563 | static void wpn_fill_pgdata(WPN_ARGS) { 564 | fill_disk_at_path(pgdata_path, NULL); 565 | } 566 | 567 | static void wpn_fill_pgwal(WPN_ARGS) { 568 | fill_disk_at_path(pgdata_path, "pg_wal"); 569 | } 570 | 571 | static void wpn_restart(WPN_ARGS) { 572 | validate_we_can_restart(); 573 | restart_database(); 574 | } 575 | 576 | static void wpn_segfault(WPN_ARGS) { 577 | volatile char *segfault = NULL; 578 | *segfault = '\0'; 579 | } 580 | 581 | static void wpn_signal(WPN_ARGS) { 582 | int sig = SIGKILL; 583 | pid_t sig_pid = PostmasterPid; 584 | 585 | if (payload) { 586 | int raw_sig; 587 | /* maybe pull out a signal and a backend to target */ 588 | char *type = simple_get_json_str(payload, "type"); 589 | 590 | /* look for the pid of a random backend of the given type */ 591 | if (type) { 592 | sig_pid = find_random_pid_of_type(type); 593 | if (!sig_pid) 594 | ereport(NOTICE, errmsg("couldn't find pid of type '%s'", type)); 595 | } 596 | raw_sig = simple_get_json_int(payload, "signal"); 597 | if (raw_sig != -1) 598 | sig = raw_sig; 599 | } 600 | 601 | kill(sig_pid, sig); 602 | } 603 | 604 | static void wpn_rm_pgdata(WPN_ARGS) { 605 | command_with_path("/bin/rm -Rf %s", pgdata_path, false); 606 | } 607 | 608 | static void wpn_xact_wrap(WPN_ARGS) { 609 | char *settings[] = { "autovacuum_freeze_max_age", NULL }; 610 | char *values[] = { "100000", NULL }; 611 | 612 | force_settings_and_restart(settings, values); 613 | } 614 | 615 | static void wpn_mem(WPN_ARGS) { 616 | char *size = payload ? simple_get_json_str(payload, "size") : "1GB"; 617 | //char *context = payload ? simple_get_json_str(payload, "context") : "Current"; /* TODO */ 618 | 619 | int64 alloc_size = DatumGetInt64(DirectFunctionCall1(pg_size_bytes, CStringGetDatum(size))); 620 | pfree(palloc(alloc_size)); 621 | } 622 | 623 | /* SRF to return information about the available weapons */ 624 | Datum pg_kaboom_arsenal(PG_FUNCTION_ARGS) 625 | { 626 | ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; 627 | TupleDesc tupdesc; 628 | Tuplestorestate *tupstore; 629 | MemoryContext per_query_ctx; 630 | MemoryContext oldcontext; 631 | Weapon *weapon = weapons; 632 | 633 | /* check to see if caller supports us returning a tuplestore */ 634 | if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo)) 635 | ereport(ERROR, 636 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 637 | errmsg("set-valued function called in context that cannot accept a set"))); 638 | if (!(rsinfo->allowedModes & SFRM_Materialize)) 639 | ereport(ERROR, 640 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 641 | errmsg("materialize mode required, but it is not allowed in this context"))); 642 | 643 | /* Build a tuple descriptor for our result type */ 644 | if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE) 645 | elog(ERROR, "return type must be a row type"); 646 | 647 | per_query_ctx = rsinfo->econtext->ecxt_per_query_memory; 648 | oldcontext = MemoryContextSwitchTo(per_query_ctx); 649 | 650 | tupstore = tuplestore_begin_heap(true, false, work_mem); 651 | rsinfo->returnMode = SFRM_Materialize; 652 | rsinfo->setResult = tupstore; 653 | rsinfo->setDesc = tupdesc; 654 | 655 | MemoryContextSwitchTo(oldcontext); 656 | 657 | while (weapon->wpn_name) 658 | { 659 | /* for each row */ 660 | Datum values[2]; 661 | bool nulls[2]; 662 | 663 | MemSet(values, 0, sizeof(values)); 664 | MemSet(nulls, 0, sizeof(nulls)); 665 | 666 | values[0] = CStringGetTextDatum(weapon->wpn_name); 667 | values[1] = CStringGetTextDatum(weapon->wpn_desc); 668 | 669 | tuplestore_putvalues(tupstore, tupdesc, values, nulls); 670 | weapon++; 671 | } 672 | 673 | /* clean up and return the tuplestore */ 674 | tuplestore_donestoring(tupstore); 675 | 676 | return (Datum) 0; 677 | } 678 | -------------------------------------------------------------------------------- /pg_kaboom.control: -------------------------------------------------------------------------------- 1 | comment = 'Blow things up in interesting and useful^W^W ways' 2 | default_version = '0.0.1' 3 | relocatable = true 4 | module_pathname = '$libdir/pg_kaboom' 5 | -------------------------------------------------------------------------------- /static/pg_kaboom_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pgguru/pg_kaboom/5b1cae3fdc85ce056861b53b834b18176d574327/static/pg_kaboom_logo.png -------------------------------------------------------------------------------- /t/001_basic.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env perl 2 | use strict; 3 | use warnings; 4 | use PostgreSQL::Test::Cluster; 5 | use Test::More qw/no_plan/; 6 | 7 | my $node = PostgreSQL::Test::Cluster->new('primary'); 8 | 9 | $node->init(); 10 | $node->start(); 11 | 12 | $node->safe_psql('postgres','CREATE EXTENSION IF NOT EXISTS pg_kaboom'); 13 | 14 | is ($node->safe_psql('postgres',"select extname from pg_extension where extname = 'pg_kaboom'"), 15 | 'pg_kaboom', 16 | 'successfully created the extension' 17 | ); 18 | --------------------------------------------------------------------------------