Tải bản đầy đủ (.pdf) (231 trang)

IT training effective MySQL backup and recovery practical knowledge for business continuity bradford 2012 06 19

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.52 MB, 231 trang )


EffectiveMySQL
BackupandRecovery


AbouttheAuthor
RonaldBradfordhasworkedintherelationaldatabasefieldforover20years.Withhis
professional background and a decade of working knowledge in database architecture,
performancetuning,andmanagementoflargeenterprisesystemsusingIngresandOracle,
Ronaldhasforthepast13yearsworkedprimarilywithMySQL,theworld’smostpopular
open source database. He has worked both at Oracle Corporation (1996–1999) as an
Oracle Consultant and MySQL, Inc. (2006–2008) as a senior MySQL Consultant. His
contributions to the MySQL community include being recognized as the all-time top
individual MySQL blog contributor at Planet MySQL (2010), and international
recognitions include being named an Oracle ACE Director (2010) and MySQL
CommunityMemberoftheYear(2009).
Ronald combines his extensive consulting expertise with a passion to share the
knowledge and benefits of using MySQL. Starting in 2006, his many public speaking
engagementshaveincludedover60presentationsin20countriesin2010–2011.


AbouttheTechnicalEditors
HansForbrichhasbeenworkingwithcomputerssincetheearly1970s,inparticularwith
entity-relationship and relational databases starting in 1979 using an engine on IBM
mainframescalledGERM(GeneralEntityRelationshipModel).Sincethattime,Hanshas
been a DBA, an operations architect for a number of organizations, and an Oracle
Universityinstructorbutalwaysheavilyinvolvedinhighavailabilityandrecoverability.
As a fellow ACE Director, Hans is pleased and honored to have been a technical
reviewerforthisbook.Backupandrecoveryisanimportantandoftenoverlookedareaof
MySQL,andRonald’sexpertiseandexperienceinthisareashinesthrough.
ChrisSchneiderhasbeenaMySQLcommunitymember,user,andevangelistforthepast


tenyears.Throughouthiscareerhehasdesigned,implemented,andmaintainedsmallto
large scale MySQL installations while training and mentoring teams of DBAs. This has
included building architecture from the ground up and improving on those that are
currently in place while emphasizing scalability, performance, and ease of use. Since
2009,ChrishasbeenanexpertspeakeratmanyU.S.conferencesincludingtheMySQL
ConferenceandExpo,ODTUGKScope,andOracleOpenWorld.
LenzGrimmerfirstencounteredMySQLin1995,whenhehadhisfirstjobasasystems
administrator in a small Internet startup company, which already used what was later
calledthe“LAMPstack”toprovidewebhostingservicesforcustomers.Hethenworked
asadistributiondeveloperatSUSELinuxfrom1998–2002,beforehejoinedMySQLAB
asaReleaseEngineerinchargeofproducingtheofficialMySQLbuildsforallplatforms.
AfterhavingbeenwiththeMySQLteamfornineyears,herecentlyreturnedtoLinux,asa
memberoftheOracleLinuxproductmanagementteamatOracle.Lenzisthemaintainer
ofthemylvmbackupscriptandhasgivennumeroustalksonthetopicsofMySQLbackup
and recovery. In his spare time, Lenz enjoys spending time with his family or tinkering
withremotecontrolledquadrocopters,poweredbytheArduinoplatform.


EffectiveMySQL
BackupandRecovery
RonaldBradford



NewYorkChicagoSanFranciscoLisbonLondonMadridMexicoCityMilanNewDelhiSanJuanSeoulSingaporeSydneyToronto


EffectiveMySQL:BackupandRecovery
Copyright © 2012 by The McGraw-Hill Companies, Inc. All rights reserved. Except as
permittedundertheUnitedStatesCopyrightActof1976,nopartofthispublicationmay

be reproduced or distributed in any form or by any means, or stored in a database or
retrievalsystem,withoutthepriorwrittenpermissionofthepublisher.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. All other
trademarksarethepropertyoftheirrespectiveowners,andMcGraw-Hillmakesnoclaim
ofownershipbythementionofproductsthatcontainthesemarks.
Screen displays of copyrighted Oracle software programs have been reproduced herein
withthepermissionofOracleCorporationand/oritsaffiliates.
ISBN:978-0-07-178858-8
MHID:0-07-178858-1
ThematerialinthiseBookalsoappearsintheprintversionofthistitle:ISBN978-0-07178857-1,MHID0-07-178857-3.
McGraw-HilleBooksareavailableatspecialquantitydiscountstouseaspremiumsand
sales promotions, or for use in corporate training programs. To contact a representative
pleasee-mailusat
All trademarks are trademarks of their respective owners. Rather than put a trademark
symbol after every occurrence of a trademarked name, we use names in an editorial
fashiononly,andtothebenefitofthetrademarkowner,withnointentionofinfringement
of the trademark. Where such designations appear in this book, they have been printed
withinitialcaps.
SponsoringEditor
PaulCarlstroem
EditorialSupervisor
PattyMon
ProjectManager
SapnaRastogi,CenveoPublisherServices
AcquisitionsCoordinator
RyanWillard
TechnicalEditors
HansForbrich
ChrisSchneider
LenzGrimmer

CopyEditor


LisaMcCoy
Proofreader
PaulTyler
Indexer
KarinArrigoni
ProductionSupervisor
JeanBodeaux
Composition
CenveoPublisherServices
Illustration
CenveoPublisherServices
ArtDirector,Cover
JeffWeeks
CoverDesigner
PattieLee
InformationhasbeenobtainedbyPublisherfromsourcesbelievedtobereliable.However,becauseofthepossibilityof
humanormechanicalerrorbyoursources,Publisher,orothers,Publisherdoesnotguaranteetotheaccuracy,adequacy,
orcompletenessofanyinformationincludedinthisworkandisnotresponsibleforanyerrorsoromissionsortheresults
obtainedfromtheuseofsuchinformation.
OracleCorporationdoesnotmakeanyrepresentationsorwarrantiesastotheaccuracy,adequacy,orcompletenessof
anyinformationcontainedinthisWork,andisnotresponsibleforanyerrorsoromissions.

TERMSOFUSE
ThisisacopyrightedworkandTheMcGraw-HillCompanies,Inc.(“McGraw-Hill”)and
its licensors reserve all rights in and to the work. Use of this work is subject to these
terms. Except as permitted under the Copyright Act of 1976 and the right to store and
retrieve one copy of the work, you may not decompile, disassemble, reverse engineer,

reproduce,modify,createderivativeworksbasedupon,transmit,distribute,disseminate,
sell,publishorsublicensetheworkoranypartofitwithoutMcGraw-Hill’spriorconsent.
Youmayusetheworkforyourownnoncommercialandpersonaluse;anyotheruseofthe
work is strictly prohibited. Your right to use the work may be terminated if you fail to
complywiththeseterms.
THEWORKISPROVIDED“ASIS.”McGRAW-HILLANDITSLICENSORSMAKE
NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR
COMPLETENESSOFORRESULTSTOBEOBTAINEDFROMUSINGTHEWORK,
INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE
WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY
WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee


thatthefunctionscontainedintheworkwillmeetyourrequirementsorthatitsoperation
willbeuninterruptedorerrorfree.NeitherMcGraw-Hillnoritslicensorsshallbeliableto
youoranyoneelseforanyinaccuracy,errororomission,regardlessofcause,inthework
orforanydamagesresultingtherefrom.McGraw-Hillhasnoresponsibilityforthecontent
of any information accessed through the work. Under no circumstances shall McGrawHill and/or its licensors be liable for any indirect, incidental, special, punitive,
consequentialorsimilardamagesthatresultfromtheuseoforinabilitytousethework,
evenifanyofthemhasbeenadvisedofthepossibilityofsuchdamages.Thislimitationof
liabilityshallapplytoanyclaimorcausewhatsoeverwhethersuchclaimorcausearises
incontract,tortorotherwise.


ForMySQLculture,past,present,andfuture.
TomanyintheMySQLandgrowingOraclecommunity:
youaremorethancolleagues;
youare,andalwayswillremain,greatfriends.



CONTENTS

Acknowledgments
Introduction
1TheFiveMinuteDBA
ApproachingaMySQLBackup
DeterminingYourDatabaseSize
ChoosingaLockingStrategy
ExecutionTime
CombiningInformation
PerformingaMySQLBackup
Runningmysqldump
SecuringYourBackup
Benefitswithmysqldump
MoreInformation
OtherOptions
Conclusion
2UnderstandingBackupOptions
Terminology
ChoosingaBackupStrategy
DatabaseAvailability
StorageEngines
LockingStrategies
MySQLTopology
StaticBackupOptions
FilesystemBackup
SQLDump
TableExtract

FilesystemSnapshot
InnoDBHotBackup
OptionsNotDiscussed


PointinTimeRequirements
BinaryLogs
BinaryLogPosition
BinaryLogBackupOptions
HardwareConsiderations
DataSourceConsistency
BackupSecurity
Conclusion
3UnderstandingBusinessRequirementsforDisasterRecovery
DefiningRequirements
DefiningResponsibilities
Terminology
TechnicalResourceResponsibilities
DecisionMakerResponsibilities
IdentifyingDependencies
CaseStudy
TheMySQLTopology
YourBackupandRecoveryStrategy
ARealLifeDisaster
TechnicalOutcomes
TheDecisionProcess
EssentialExternalCommunication
PlanningfortheWorstSituation
TotalSANFailure
PowerDisruption

Explosion
FBISeizure
Blackout
HumanFactors
HumanResources
DevelopingaStrategicPlan
Conclusion


4UsingMySQLReplication
MySQLReplicationArchitecture
MySQLReplicationCharacteristics
MySQLReplicationLimitations
ReplicationLag
Consistency
Completeness
ReplicationDesignConsiderations
BinaryLogRowFormat
Semi-synchronousReplication
ReplicationBackupConsiderations
AdditionalPrerequisiteChecks
ColdBackupOptions
mysqldumpOptions
FilesystemSnapshotOptions
MySQLEnterpriseBackup(MEB)Options
XtraBackupOptions
ArchitectureDesignConsiderations
UpcomingReplicationFunctionality
Conclusion
5UsingRecoveryOptions

AWordAboutTesting
DeterminingtheTypeofRecoveryNecessary
MySQLSoftwareFailure
CrashRecovery
MyISAMTableRecovery
OtherStorageEngines
TableDefinitionRecovery
PerformingaStaticRecovery
MySQLSoftwareInstallation
MySQLData
PerformingaPointinTimeRecovery


BinaryLogPosition
StandaloneRecovery
LeveragingtheReplicationStream
BinaryLogMirroring
RecoveryVerification
TheBackupandRecoveryQuiz
OtherImportantComponents
Conclusion
6MySQLConfigurationOptions
DataManagement
DataLocations
DataConsistency
BinaryLogging
MySQLReplication
Recovery
Conclusion
7DisasterScenarios

HandlingaMySQLDisaster
NotableMySQLDisasters
Magnolia
CouchSurfing
JournalSpace
Percona
OtherNotableDataDisasters
TheSidekick/MicrosoftDataLoss
Github
TDBank
GeneralMySQLDisasterSituations
BinaryLoggingNotEnabled
ASingleServer
AppropriateMySQLSecurity
AppropriateMySQLConfiguration


DeletingMySQLData
DeletingtheInnoDBDataFile
DeletingMySQLBinaryLogs
ExistingBackupandRecoveryProcedureDisasters
MySQLSoftwareUpgrades
OperatingSystemSecurityPatchUpgrade
HandlingMyISAMCorruption
MissingDatabaseSchemas
RestoringaBackuponaRunningMySQLInstance
HandlingInnoDBSpecificSituations
AutomaticRecovery
InnoDBDataDictionaryInconsistency
AutomaticRecoveryCrashestheDatabaseServer.

OtherMySQLSituations
ReplicationInconsistency
RDSRecoveryFailure
CommonDowntimeCauses
ExternalHelp
Conclusion
8OptimizingBackupandRecovery
ExampleBackupEnvironment
UsingCompression
mysqldump
MySQLEnterpriseBackup(MEB)
XtraBackup
StreamingBackups
UsingSSH
Usingnc
MySQLEnterpriseBackup(MEB)
XtraBackup
RemoteBackups
mysqldump


MySQLEnterpriseBackup(MEB)
XtraBackup
ParallelProcessing
mydumper
XtraBackup
IncrementalBackups
MySQLEnterpriseBackup(MEB)
XtraBackup
PartialBackups

mysqldump
MySQLEnterpriseBackup(MEB)
XtraBackup
MySQLBackupSecurity
EncryptionwithezNcrypt
ArchitecturalConsiderations
Conclusion
9MySQLintheCloud
AmazonRelationalDatabaseService(RDS)
ExampleDatabaseCreation
MySQLVersions
BackupOptions
RecoveryOptions
GoogleCloudSQL
ExampleDatabaseCreation
BackupOptions
RestoreOptions
HPCloudDatabaseasaService(DBaaS)
MySQLVersions
ExampleDatabaseCreation
BackupOptions
RecoveryOptions
CloudImpactonBackupandRecovery


Conclusion


ACKNOWLEDGMENTS



ThankstothereaderswhohavealreadyenjoyedthefirstbookoftheEffectiveMySQL
seriesforprovidingvaluablefeedback,bothgoodandbad.ApositivecommenttellsmeI
am meeting your needs; a negative one means I need to continue to do better. Both are
important to ensure continued improvements in this series. It is also a great feeling to
receiveane-mailaskingwhenthenextbookwillbeavailable.
As I write my acknowledgments for this book, I realize the timeline of my own
changingimmediatefamily.Inmyfirstbookfrom2010Iacknowledgedmyfiancé,Cindy,
and in my second book my now wife Cindy. For this third book my family has again
increased with Chance, our two-year-old dachshund rescue. In such a short time he has
become integral to our daily routine and in finding a balance between work, life, and
writing. Significant time, effort, and support from family is needed to create a book;
however,Iwritethismaterialforthebenefitofallwhohaveadesiretolearn,appreciate,
andmasterusingMySQLeffectively.
WithoutthetechnicalabilitiesoftheteamatMcGraw-Hillthispublicationwouldnotbe
possible. Many thanks to Ryan Willard, my coordinating editor; Paul Carlstroem, my
sponsoring editor; and the production team, who all remained very patient during some
significantunforeseendelays.
Mytechnicaleditors,Hans,Chris,andLenz,andtheextendedreviewteamhavebeen
invaluableforthisbook.
ThemanyyearsofdatabasewisdomandextensivetrainingexpertiseofHansForbrich
bringsthenecessaryOracleexpertisetotheteamandensuresthismaterialmeetstheneeds
of an experienced Oracle DBA for understanding and learning to master backup and
recoveryforMySQL.
I am indebted to Chris Schneider, who in addition to being a technical editor of this
bookandco-authorforthenextbookinthisEffectiveMySQLseries,wasabletoassist
greatlyinsupplementingcontentinthelaterchaptersandperformadditionalreviewsasI
was overcoming illness. His expertise as an operational MySQL DBA working with the
demanding needs of systems requiring real life disaster recovery needs in his daily role
ensuresthesyntax,examples,andoptionsdescribedinthisbookmirrortheneedsofmany

MySQLproductionsystems.
LenzGrimmer,longtimeMySQLcommunityadvocate,goodfriend,andsponsorofthe
open source MySQL backup tool mylvmbackup, has added another well rounded
perspective and technical validation with his many years of database and system
administrationknowledge.
Whilethewordswritteninthistextaremine,thisdoesnotbecomeapublishedbook
withoutthehelp,input,clarification,anddiscussionofthesetrustedandrespectedsenior
technicaladvisors.
Several others have also contributed to making this a great reference. Thanks to the


MySQL Enterprise Backup (MEB) team at Oracle including Sagar Jauhari, Lars
Thalmann,andSanjayManwaniintheirreviewofallthingsMEB.AlsotoKenAshcraft
fromGoogleandVipuSabhayafromHPfortheirfeedbackontherespectiveofferingsof
MySQL in the cloud. Mark Leith contributed an actual code patch to mysqldump in one
dayastheresultofablogpostprovidinganexamplehackforaworkaround.Greatwork,
Mark.ThatistheMySQLcommunityspiritandopensourceinaction.Furtherthanksto
Patrick Galbraith who provided early input around MySQL replication. Finally, several
individualsandcompaniesnamedoranonymoushelpedtoprovidemanycolorfuldisaster
scenariosdetailedinChapter7.


INTRODUCTION


Disasterisinevitable.Totalfailureisavoidable.
While many organizations plan, practice, and invest for scalability, few plan and
practiceforbusinessresilienceastheresultofadisasterora“ChoasMonkey*”.Oneof
themostcriticaltasksofanoperationaldatabaseadministrator(DBA)istoperform,test,
document, and verify adequate backup and recovery procedures to ensure business

continuity.Whilethismaybeconsideredamuchloathedandlessprioritizedtask,thisis
the single most comforting element in a well functioning and stable production
environment. Backups are not just used for recovery. Other uses of backups that can be
incorporated into daily operations to assist in the verification process can include
additionalscalabilityandhigheravailabilityinfrastructure,testing,andbenchmarking.
UnderstandingwhatlimitationsandquirksexistwiththevariousapproachestoMySQL
backupsisimportantinbeingconfidentthatthecrucialbusinessinformationisbackedup.
Themethodsyouhaveusedtorecoveryourinformationmustmeetyourbusinessneedsto
obtainameantimetorecovery(MTTR)andtherecoverypointobjective(RPO).
MySQLprovidesnoonesingleunbreakablesolutionasyet.TheuseofMySQLstorage
engines,MySQLreplication,configurationsettingsfordurability,hardwareconfiguration,
database uptime, and locking requirements are all factors in choosing an applicable
approach matching your business requirements. This book will cover these approaches
detailing the relative strengths and weaknesses and leading the reader to identify and
implementanappropriatebackupandrecoverystrategy.
The final chapter of this book also discusses advancements in MySQL availability in
thecloudandthebenefitsandrisksforanoptimalbackupandrecoverystrategy.
Conventions
Allcodeexamplesareprovidedinaproportionalfont.Forexample:


AnySQLsyntaxwithintextorcodeexampleswillbeinuppercase.Forexample,the
FLUSH TABLES WITH READ LOCK statement will hold a global read lock. These
statementsarenotprovidedinadifferentfont.Ifaspecificsyntaxorvaluefromacode
exampleisdescribedingeneraltext,thisisprovidedinaproportionalfont,forexample,


the--log-binconfigurationoption.
ForanyUnix/Linuxcommand,thisisprefixedwitha $toindicateashellprompt.For
example:


Any MySQL SQL statement that can be executed is prefixed with mysql>toindicate
execution with the mysql command line client that is included with a full MySQL
distribution.Forexample:

AllSQLstatementslistedwiththisprefixcangenerallybeperformedinanyalternative
MySQL client GUI tool; however, some additional syntax may not be applicable—for
example:\Gforverticaldisplayisamysqlcommandlineclientspecificdirective.
AboutMySQL
TheMySQLdatabaseserverisanopensourceproductreleasedundertheGPLV2license.
More
information
about
the
GPL
license
can
be
found
at
ThecopyrightownerofMySQL
at the time of this publication is Oracle Corporation. Oracle Corporation provides
continuedproductdevelopmentandalsoprovidescommerciallicensesforOEMproviders
andcomprehensivesubscriptionservicesforwebsitesandenterprises.
More information about MySQL can be found at the official MySQL website at
andtheMySQLdeveloperzoneat.
The current generally available (GA) version of MySQL is version 5.5. This book is
writtentosupportMySQLversions5.0andbetterwithspecificversiondifferencesnoted
when applicable. The current development version of MySQL 5.6 is also referenced to
indicateexpectednewfunctionalityinanupcomingrelease;however,thesefeaturesmay

operatedifferentlyornotbeprovidedinanyfinalfutureMySQLproduct.
CodeExamples
AllexamplesdetailedinthisbookareavailablefordownloadfromtheEffectiveMySQL
site at Code, scripts, and sample data
arealsoavailableatGitHub.
A separate text document of all URLs used is also included on the website to enable
quickaccesstothesereferences.
References
TheMySQLReferenceManualontheMySQLdeveloperzoneisaninvaluableresource.
Thiscanbefoundat />Access to manuals for older MySQL versions can also be found at
/>The Planet MySQL website at provides an aggregation of


thousandsofMySQLbloggersdetailinggreatinsightonallthingsMySQL.
Additional open source products referenced in this book including Xtra-Backup and
Percona Toolkit from Percona, mylvmbackup, and mydumper have various sources of
additionalonlineinformation.Thesearedetailedattheappropriatetime.
*The“ChoasMonkey”andthe“SimianArmy”createdbyNetflixhighlightthatproactivelycreatingdisastersesuresthe
bestapproachforbeingprepared.Moreat />

1
TheFiveMinuteDBA


YouhavejustinheritedaproductionMySQLsystemandthereisnoconfirmationthatan
existingMySQLbackupstrategyisinoperation.Whatistheleastyouneedtodo?Before
undertaking any backup strategy there are some necessary prerequisites about your
databasesizeandstorageengineusagethathaveadirecteffectonyoursystemavailability
duringanybackupapproach.
In this chapter we will discuss the approach necessary to identify a minimum

functionalitybackup,including:
•Determineyourdatabasesize
•Determineyourstorageengineusage
•Lockinganddowntimeimplications

ApproachingaMySQLBackup
ThereismorethanonestrategytobackupaMySQLenvironment.Thesestrategiesalso
dependonthenumberofserversintheMySQLtopology.Thereareanumberofvarious
opensourceandcommercialtoolsavailabletoperformbackups.InChapter2wewillbe
discussingindetailallthesepossibleoptions.
At this time you have an environment with a single server and you want to create a
consistentbackup.YouhaveatyourdisposalforallMySQLenvironmentstwoimmediate
options.ThefirstoptionistostopyourMySQLinstanceandtakeafullfilesystemcold
backup.Thiswouldresultinyoursystembeingunavailableforanundeterminedtime,and
youwouldneedtoensureyoumakeacopyofalltherightinformationincludingMySQL
data,transactionandbinarylogsifapplicable,andthecurrentMySQLconfiguration.
Your second option is to use a client tool included with the standard MySQL


installation.The mysqldump command can produce a consistent MySQL backup without
stopping the MySQL instance. However, before running mysqldump, several important
decisionsarerequiredtomakeaninformeddecisionofthebestoptionstouse.Theseare:
•Whatisthesizeofthedatabasetobackup?
•Whatlockingstrategyisnecessarytoproduceaconsistentbackup?
•Howlongwillthebackuptake?

DeterminingYourDatabaseSize
An important consideration for performing a MySQL backup is the size of your backup
whenbackinguptolocaldisk.Thisisrequiredtoensureyouhaveavailablediskspaceto
storeyourbackupfile.

The following SQL statement provides the total size in MB of your current data and
indexes:


Your mysqldump backup will be approximately the same size as your data with an
appropriate safety margin of 10 to 15 percent. There is no precise calculation; however,
yourbackupproducesatextbasedoutputofyourdata.Forexample,a4byteintegerin
thedatabasemaybe10characterbyteslongina mysqldumpbackupfile.Itispossibleto
compress your backup concurrently or to transfer to a different network device. These
optionsandtheirlimitationsarediscussedinChapters2and8.
FromthisSQLstatementthedatabasedatasizeis847MB.Forlaterreference,thesize
ofthebackupfileasdescribedinthesectionrunning mysqldumpreportsasizeof818MB
usingthecommondefaultoptions.TheexampledatabaseinChapter8withadatasizeof
4.5GBproducesabackupfileof2.9GB.

ChoosingaLockingStrategy
Thelockingstrategychosenwilldetermineifyourapplicationcanperformdatabasewrite
operationsduringtheexecutionofabackup.Bydefault,mysqldumpperformsatablelevel
locktoensureaconsistentversionofalldatausingtheLOCKTABLEScommand.This
occurs with the --lock-tables command line option, which is not enabled by default.
Thisoptionispartofthe--optoptionthatisenabledbydefault.Youcanelecttonotlock
tables; however, this may not ensure a consistent backup. When using the MyISAM
storageengine,--lock-tablesisnecessarytoensureaconsistentbackup.
Alternatively, mysqldump provides the --single-transaction option that creates a
consistent version snapshot of all tables in a single transaction. This option is only


applicablewhenusingastorageenginethatsupportsmultiversioning.InnoDBistheonly
storage engine included in a default MySQL installation that is applicable. When
specified,thisoptionautomaticallyturnsoff--lock-tables.

ThefollowingSQLstatementwillconfirmthestorageenginesinuseforyourMySQL
instance:


Inthisexample,theMySQLinstancehasseveraldifferentschemasthatsupportvarious
functions including a shopping cart, newsletter, and administration tool. An all InnoDB
applicationmaylooklike:


Asyouseeintheexamplethemysqlmeta-schemausesMyISAM.Thereisnoabilityto
change this. If your database is all InnoDB you will have two options regarding the
MyISAMmysqltablesthatwewilldiscusslaterinthischapter.

ExecutionTime
Themostimportantrequirementistodeterminehowlongyourbackupwilltake.Thereis
nocalculationthatcangiveanaccurateanswer.Thesizeofyourdatabase,theamountof
system RAM, the storage engine(s) in use, the MySQL configuration, the hard drive
speed,andthecurrentworkloadallcontributeinthecalculation.Whatisimportantwhen
performingabackupisthatyoucollectthistypeofinformationforfuturereference.The
executiontimeisimportant,asthisisaneffectivemaintenancewindowforyourdatabase.
During a database backup there may be a limitation of application functionality, a
performance overhead during the backup, and your backup may limit other operations
includingbatchprocessingorsoftwaremaintenance.

CombiningInformation


ThefollowingisarecommendedSQLstatementthatcombinesallinformationforanaudit
ofyourdatabasesize:




PerformingaMySQLBackup
Now that you have gathered prerequisite information, you have the details necessary to
makeaninformeddecision.
The choice of how to perform a backup, when to perform, and how you monitor and
verifyisamorecomplexprocessthatisdiscussedinmoredetailstartingwithChapter2.
One additional consideration during a backup process is to disable any cron or batch
processesduringthebackuptominimizeadditionalworkload.Thiscanminimizedatabase
contentionandshortenthewindowoftimeneeded.

Runningmysqldump
In the simplest form, you can perform a backup using mysqldump with the following
syntax:


•ThefirstcommandrunsthemysqldumpforalldatabasesproducinganASCIIdumpin
thebackup.sqlfile.
•Thesecondcommandconfirmstheexitstatusofthefirstcommand.Anon-zeroresultis
anindicationofaproblemduringthebackupprocess.Ifanyerrorsoccur,theseare
generallyshowninthescreenoutput.
•Thethirdcommandshowsthesizeofyourbackupfileforlaterreference.


×