....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 217.79.180.202  /  Your IP : 216.73.216.163
Web Server : Apache
System : Linux vps2460721.fastwebserver.de 5.15.0-122-generic #132-Ubuntu SMP Thu Aug 29 13:45:52 UTC 2024 x86_64
User : tecnoelite ( 1001)
PHP Version : 8.1.2-1ubuntu2.18
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /bin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /bin/pg_backupcluster
#!/usr/bin/perl -wT

# simple pg_basebackup front-end
#
# Copyright (C) 2021-2024 Christoph Berg <myon@debian.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

use strict;
use warnings;
use Fcntl qw(LOCK_EX);
use Getopt::Long;
use JSON;
use PgCommon;
use POSIX qw(strftime);

my ($version, $cluster);

# untaint environment
$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
chdir '/';
umask 027;

sub help () {
    print "Syntax: $0 [options] <version> <cluster> <action>
Actions:
  createdirectory        Create /var/backups/version-cluster
  basebackup             Backup using pg_basebackup
  dump                   Backup using pg_dump
  expiredumps <N>        Remove all but last N dumps
  expirebasebackups <N>  Remove all but last N basebackups
  receivewal             Launch pg_receivewal
  compresswal            Compress WAL files in archive
  archivecleanup         Remove obsolete WAL files from archive
  list                   Show dumps, basebackups, and WAL
Options:
  -c --checkpoint <spread|fast>  Passed to pg_basebackup
  -k --keep-on-error     Keep faulty backup directory on error
  -v --verbose           Verbose output
";
}

my $checkpoint = 'spread';
my $keep_on_error;
my $verbose;

exit 1 unless GetOptions (
    'c|checkpoint=s' => sub { $checkpoint = $_[1] =~ /^f/ ? "fast" : "spread" },
    'k|keep-on-error' => \$keep_on_error,
    'v|verbose' => \$verbose,
);

$verbose = 1 if (-t 1); # verbose output when running on terminal

# accept both "version cluster action" and "version[-/]cluster action"
if (@ARGV >= 2 and $ARGV[0] =~ m!^(\d+\.?\d)[-/]([^/]+)$!) {
    ($version, $cluster) = ($1, $2);
    shift @ARGV;
} elsif (@ARGV >= 3 and $ARGV[0] =~ /^(\d+\.?\d)$/) {
    $version = $1;
    ($cluster) = ($ARGV[1]) =~ m!^([^/]+)$!;
    shift @ARGV;
    shift @ARGV;
} else {
    help();
    exit 1;
}
my $action = $ARGV[0];

error "specified cluster $version $cluster does not exist" unless $version && $cluster && cluster_exists $version, $cluster;

my %info = cluster_info($version, $cluster);
validate_cluster_owner \%info;

my $rootdir = "/var/backups/postgresql";
my $clusterdir = "$rootdir/$version-$cluster";
my $waldir = "$clusterdir/wal";

# functions to be run as root

sub create_directory() {
    if (! -d $rootdir) {
        my ($pg_uid, $pg_gid) = (getpwnam 'postgres')[2,3];
        ($pg_uid and $pg_gid) or error "getpwnam postgres: $!";
        mkdir $rootdir, 0755 or error "mkdir $rootdir: $!";
        chown $pg_uid, $pg_gid, $rootdir or error "chown $rootdir: $!";
    }
    if (! -d $clusterdir) {
        mkdir($clusterdir, 0750) or error "mkdir $clusterdir: $!";
        chown $info{owneruid}, $info{ownergid}, $clusterdir or error "chown $clusterdir: $!";
    }
}

sub switch_to_cluster_owner() {
    change_ugid $info{owneruid}, $info{ownergid};
}

# backup functions

sub get_backupdir($$) {
    my ($starttime, $suffix) = @_;
    my $timestamp = strftime("%FT%H%M%SZ", gmtime($starttime));
    my $backupdir = "$clusterdir/$timestamp.$suffix";
    error "$backupdir already exists" if (-d $backupdir);
    print "Creating $suffix in $backupdir\n" if ($verbose);
    return $backupdir;
}

sub remove_backup_on_error($) {
    my $backupdir = shift;
    if ($keep_on_error) {
        print "Not removing $backupdir (--keep-on-error)\n";
    } else {
        print "Removing $backupdir ...\n" if ($verbose);
        system_or_error "rm", "-rf", $backupdir;
    }
}

sub create_basebackup($) {
    my $backupdir = shift;

    system_or_error "pg_basebackup",
        "--cluster", "$version/$cluster",
        "--verbose",
        (-t 2 ? "--progress" : ()),
        "--checkpoint=$checkpoint",
        "--format", "tar", "--gzip",
        ($version < 10 ? "--xlog" : ()),
        "-D", $backupdir;
}

sub create_dumpall($) {
    my $backupdir = shift;
    mkdir($backupdir, 0750) or error "mkdir $backupdir: $!";

    my $icu = "";
    if ($version >= 15) {
        $icu = "CASE datlocprovider::text
            WHEN 'c' THEN '--locale-provider libc'
            WHEN 'b' THEN '--locale-provider builtin'
            WHEN 'i' THEN '--locale-provider icu'";
        if ($version < 17) {
            $icu .= " || ' --icu-locale ' || daticulocale";
        }
        if ($version >= 16) {
            $icu .= " || ' --icu-rules ' || daticurules";
        }
        $icu .= "\nEND,";
    }
    my $clusterquery = "SELECT
  '--encoding', pg_catalog.pg_encoding_to_char(encoding),
  '--lc-collate', datcollate,
  '--lc-ctype', datctype,
  $icu
  CASE WHEN current_setting('data_checksums')::boolean THEN '-- --data-checksums' END
FROM pg_database WHERE datname = 'template0'";
    system_or_error "psql",
        "--cluster", "$version/$cluster",
        "-XAtF", " ", "-c", $clusterquery,
        "-o", "$backupdir/createcluster.opts";

    system_or_error "pg_dumpall",
        "--cluster", "$version/$cluster",
        "--globals-only",
        "--file", "$backupdir/globals.sql";

    my $dblist = 'SELECT datname FROM pg_database WHERE datallowconn ORDER BY datname';
    my $databases = `psql --cluster '$version/$cluster' -XAtc '$dblist'`;
    for my $datname ($databases =~ /(.+)/g) {
        print "Dumping $datname to $backupdir/$datname.dump ...\n" if ($verbose);
        system_or_error "pg_dump",
            "--cluster", "$version/$cluster",
            "--format=custom",
            "--file", "$backupdir/$datname.dump",
            $datname;
    }
}

sub create_configbackup($) {
    my $backupdir = shift;
    $info{configdir} or error "cluster has no configdir";
    system_or_error "tar",
        "-C", $info{configdir},
        "-cz", "-f", "$backupdir/config.tar.gz",
        ".";
}

sub create_status($$$$) {
    my ($type, $starttime, $backupdir, $status) = @_;
    my $statusfile = "$backupdir/status";
    my $endtime = time;
    my $statusjson = {
        cluster => $cluster,
        duration => $endtime - $starttime,
        end => strftime("%FT%H%M%SZ", gmtime($endtime)),
        start => strftime("%FT%H%M%SZ", gmtime($starttime)),
        status => $status,
        type => $type,
        version => $version,
    };
    if (my $hostname = `hostname`) {
        chomp $hostname;
        $statusjson->{hostname} = $hostname;
    }
    if (-e '/etc/machine-id') {
        open my $fh, '/etc/machine-id';
        my $machine_id = <$fh>;
        close $fh;
        if ($machine_id) {
            chomp $machine_id;
            $statusjson->{'machine-id'} = $machine_id;
        }
    }
    if (-e '/etc/machine-info') {
        open my $fh, '/etc/machine-info';
        while (<$fh>) {
            if (/^DEPLOYMENT=(.*)/) {
                $statusjson->{'machine-deployment'} = $1;
            }
        }
        close $fh;
    }

    my $json = JSON->new->canonical;
    open F, '>', $statusfile or error "$statusfile: $!";
    print F $json->encode($statusjson) . "\n" or error "$statusfile: $!";
    close F or error "$$statusfile: $!";
}

sub sync($) {
    my $backupdir = shift;
    system_or_error "sync $backupdir/*";
}

sub expire_backups($$) {
    my ($suffix, $number) = @_;
    my @backups = glob("$clusterdir/*.$suffix");
    my $found = 0;
    for my $backup (reverse @backups) {
        # iterate reversely over backups until we have found enough valid ones
        if ($found >= $number) {
            print "Removing $backup ...\n" if ($verbose);
            $backup =~ /(.*)/; # untaint
            system_or_error "rm", "-rf", $1;
        } else {
            if (-f "$backup/status") {
                $found++;
            }
        }
    }
}

sub delete_broken() {
    my @backups = (glob("$clusterdir/*.backup"), glob("$clusterdir/*.dump"));
    for my $backup (@backups) {
        if (! -f "$backup/status") {
            print "Removing $backup ...\n" if ($verbose);
            $backup =~ /(.*)/; # untaint
            system_or_error "rm", "-rf", $1;
        }
    }
}

# wal handling

sub create_wal_directory() {
    if (! -d $waldir) {
        mkdir($waldir, 0750) or error "mkdir $waldir: $!";
    }
}

sub receivewal() {
    my $pg_receivewal = $version >= 10 ? 'pg_receivewal' : 'pg_receivexlog';

    # create slot
    system_or_error $pg_receivewal, "--cluster=$version/$cluster", "--slot", "pg_receivewal_service", "--create-slot", "--if-not-exists";

    # launch pg_receivewal
    $ENV{PGAPPNAME} = "pg_receivewal\@$version-$cluster.service";
    my @cmd = ($pg_receivewal, "--cluster", "$version/$cluster",
        "-D", $waldir, "--slot", "pg_receivewal_service");
    push @cmd, "--compress=5" if ($version >= 10);
    exec {$pg_receivewal} @cmd or error "exec $pg_receivewal: $!";
}

sub compresswal() {
    chdir $waldir or return; # ok if not yet created
    open my $lock, $waldir or error "open $waldir: $!"; # protect against concurrent runs
    flock $lock, LOCK_EX or error "flock $waldir: $!";

    for my $wal (glob "0???????????????????????") {
        $wal =~ /^([0-9A-F]+)$/ or continue;
        $wal = $1; # untaint
        if (-f "$wal.gz") {
            print STDERR "$waldir/$wal.gz already exists, skipping compression\n";
            next;
        }
        system_or_error "if ! gzip < $wal > $wal.tmp.gz; then rm -f $wal.tmp.gz; exit 1; fi";
        system_or_error "touch --reference=$wal $wal.tmp.gz";
        system_or_error "mv $wal.tmp.gz $wal.gz";
        system_or_error "sync", "$wal.gz";
        unlink $wal;
    }

    close $lock;
}

sub archivecleanup() {
    chdir $waldir or return; # ok if not yet created
    my @backups = sort glob "$clusterdir/*.backup";
    for my $backup (@backups) {
        next unless (-f "$backup/status");

        $backup =~ /(.*)/; # untaint
        my $basetar = "$1/base.tar.gz";
        my $backup_label = `tar --extract --occurrence=1 --to-stdout --file '$basetar' backup_label` or error "failed to extract backup_label from $basetar";

        # START WAL LOCATION: 0/2B000028 (file 00000001000000000000002B)
        $backup_label =~ /^START WAL LOCATION: .* \(file ([0-9A-F]+)\)/ or error "no start wal location in $basetar";
        my $keep_file = $1;
        system_or_error "pg_archivecleanup", "-x", ".gz", $waldir, $keep_file;

        return 0; # process first backup only
    }
    error "no valid basebackups found in $clusterdir";
}

# info functions

sub dirsize($) {
    my $dir = shift;
    my $size = 0;
    my $files = 0;
    for my $f (glob "$dir/*") {
        $size += (stat $f)[7];
        $files++;
    }
    return $size, $files;
}

sub list() {
    print "Cluster $version $cluster backups in $clusterdir:\n";
    my $totalsize = 0;
    print "Dumps:\n";
    for my $dir (sort glob "$clusterdir/*.dump") {
        my ($size, $files) = dirsize($dir);
        my $status = -f "$dir/status" ? '' : ' BROKEN';
        print "  $dir: $size Bytes$status\n";
        $totalsize += $size;
    }
    print "Basebackups:\n";
    for my $dir (sort glob "$clusterdir/*.backup") {
        my ($size, $files) = dirsize($dir);
        my $status = -f "$dir/status" ? '' : ' BROKEN';
        print "  $dir: $size Bytes$status\n";
        $totalsize += $size;
    }
    if (-d "$clusterdir/wal") {
        print "WAL:\n";
        my ($size, $files) = dirsize("$clusterdir/wal");
        print "  $clusterdir/wal: $size Bytes, $files Files\n";
        $totalsize += $size;
    }
    print "Total: $totalsize Bytes\n";
}

# main

if ($action eq 'createdirectory') {
    create_directory();

} elsif ($action eq 'basebackup') {
    error "basebackups of pre-9.1 servers are not supported" if ($version < 9.1);
    my $starttime = time;
    create_directory();
    switch_to_cluster_owner();
    my $backupdir = get_backupdir($starttime, 'backup');
    $SIG{__DIE__} = sub { remove_backup_on_error($backupdir) };
    create_basebackup($backupdir);
    create_configbackup($backupdir);
    create_status($action, $starttime, $backupdir, 'ok');
    $SIG{__DIE__} = undef;
    sync($backupdir);
    compresswal();

} elsif ($action eq 'dump') {
    error "dumps of pre-9.3 servers are not supported" if ($version < 9.3);
    my $starttime = time;
    create_directory();
    switch_to_cluster_owner();
    my $backupdir = get_backupdir($starttime, 'dump');
    $SIG{__DIE__} = sub { remove_backup_on_error($backupdir) };
    create_dumpall($backupdir);
    create_configbackup($backupdir);
    create_status($action, $starttime, $backupdir, 'ok');
    $SIG{__DIE__} = undef;
    sync($backupdir);

} elsif ($action eq 'expiredumps' and @ARGV == 2 and $ARGV[1] =~ /^(\d+)$/) {
    switch_to_cluster_owner();
    expire_backups('dump', $1);

} elsif ($action eq 'expirebasebackups' and @ARGV == 2 and $ARGV[1] =~ /^(\d+)$/) {
    switch_to_cluster_owner();
    expire_backups('backup', $1);
    archivecleanup();
    compresswal();

} elsif ($action eq 'deletebroken') {
    switch_to_cluster_owner();
    delete_broken();

} elsif ($action eq 'receivewal') {
    create_directory();
    switch_to_cluster_owner();
    create_wal_directory();
    compresswal();
    receivewal();

} elsif ($action eq 'compresswal') {
    switch_to_cluster_owner();
    compresswal();

} elsif ($action eq 'archivecleanup') {
    switch_to_cluster_owner();
    archivecleanup();
    compresswal();

} elsif ($action eq 'list') {
    switch_to_cluster_owner();
    list();

} else {
    help();
    exit(1);
}

__END__

=head1 NAME

pg_backupcluster - simple pg_basebackup and pg_dump front-end

=head1 SYNOPSIS

B<pg_backupcluster> [I<options>] I<version> I<cluster> I<action>

=head1 DESCRIPTION

B<pg_backupcluster> provides a simple interface to create PostgreSQL cluster
backups using L<pg_basebackup(1)> and L<pg_dump(1)>.

To ease integration with B<systemd> operation, the alternative syntax
"B<pg_basebackup> I<version>B<->I<cluster> I<action>" is also supported.

=head1 ACTIONS

=over 4

=item B<createdirectory>

Create /var/backups and /var/backups/I<version>-I<cluster>.
This action can be run as root to create the directories required for backups.
All other actions will also attempt to create the directories when missing, but
can of course only do that when running as root. They will switch to the
cluster owner after this step.

=item B<basebackup>

Backup using L<pg_basebackup(1)>. The resulting basebackup contains the WAL
files required to run recovery on startup.

=item B<dump>

Backup using L<pg_dump(1)>. Global objects (users, tablespaces) are dumped
using L<pg_dumpall(1)> B<--globals-only>. Individual databases are dumped into
PostgreSQL's custom format.

=item B<expirebasebackups> I<N>

Remove all but last the I<N> basebackups.

=item B<expiredumps> I<N>

Remove all but last the I<N> dumps.

=item B<receivewal>

Launch pg_receivewal. WAL files are gzip-compressed in PG 10+.

=item B<compresswal>

Compress WAL files in archive.

=item B<archivecleanup>

Remove obsolete WAL files from archive using L<pg_archivecleanup(1)>.

=item B<list>

Show dumps, basebackups, and WAL, with size.

=back

=head1 OPTIONS

=over 4

=item B<-c --checkpoint=spread|fast>

Passed to B<pg_basebackup>. Default is B<spread>.

=item B<-k --keep-on-error>

Keep faulty backup directory on error. By default backups are delete on error.

=item B<-v --verbose>

Verbose output, even when not running on a terminal.

=back

=head1 FILES

=over 4

=item /var/backups

Default root directory for cluster backup directories.

=item /var/backups/I<version>-I<cluster>

Default directory for cluster backups.

=item /var/backups/I<version>-I<cluster>/I<timestamp>B<.basebackup>

Backup from B<pg_backupcluster ... basebackup>.

=over 4

=item C<config.tar.gz>

Tarball of cluster configuration directory (postgresql.conf, pg_hba.conf, ...)
in /etc/postgresql.

=item I<tablespace>C<.tar.gz>, C<pg_wal.tar.gz>, C<backup_manifest>

Tablespace and WAL tarballs and backup info written by B<pg_basebackup>.

=item C<status>

Completion timestamp of backup run.

=back

=item /var/backups/I<version>-I<cluster>/I<timestamp>B<.dump>

Backup from B<pg_backupcluster ... dump>.

=over 4

=item C<config.tar.gz>

Tarball of cluster configuration directory (postgresql.conf, pg_hba.conf, ...)
in /etc/postgresql.

=item C<createcluster.opts>

Options (encoding, locale, data checksums) to be passed to B<pg_createcluster>
for restoring this cluster.

=item C<globals.sql>

Global objects (roles, tablespaces) from B<pg_dumpall --globals-only>.

=item C<databases.sql>

SQL commands to create databases and restore database-level options.

=item I<database>C<.dump>

Database dumps from B<pg_dump --format=custom>.

=item C<status>

Completion timestamp of backup run.

=back

=item /var/backups/I<version>-I<cluster>/B<wal>

WAL files from B<pg_receivewal>.

=back

=head1 CAVEATS

For dump-style backups, not all properties of the original cluster are preserved:

=over 2

=item * In PostgreSQL 10 and earlier, ALTER ROLE ... IN DATABASE is not supported.

=item * Not all B<initdb> options are carried over. Currently supported are B<--encoding>,
B<--lc-collate>, B<--lc-collate>, and B<-k --data-checksums>.

=back

The earliest PostgreSQL version supported for dumps is 9.3.
For basebackups, the earliest supported version is 9.1.
B<receivewal> (and hence archive recovery) are supported in 9.5 and later.

=head1 SEE ALSO

L<pg_restorecluster(1)>,
L<pg_dump(1)>, L<pg_dumpall(1)>,
L<pg_basebackup(1)>, L<pg_receivewal(1)>, L<pg_archivecleanup(1)>.

=head1 AUTHOR

Christoph Berg L<E<lt>myon@debian.orgE<gt>>

Youez - 2016 - github.com/yon3zu
LinuXploit