Задача: Сделать бекап (резервное копирование) образа жесткого диска, для дальнейшего его восстановления, если чё.
Дано: диск на сервере должен (желательно) каждые 4 года меняться на новый, поэтому наличие бед-блоков на диске игнорируем. Вначале конечно же неплохо бы прочитать смарт этого диска, например так:
[root@hyper1 ~]# smartctl -a /dev/sda
smartctl 5.42 2011-10-20 r3458 [x86_64-linux-2.6.18-348.12.1.el5.centos.plusxen] (local build)
Copyright (C) 2002-11 by Bruce Allen, http://smartmontools.sourceforge.net=== START OF INFORMATION SECTION ===
Device Model: WDC WD1000DHTZ-04N21V0
Serial Number: WD-WX61E62UZ134
LU WWN Device Id: 5 0014ee 7aab03e30
Firmware Version: 04.06A00
User Capacity: 1 000 204 886 016 bytes [1,00 TB]
Sector Sizes: 512 bytes logical, 4096 bytes physical
Device is: Not in smartctl database [for details use: -P showall]
ATA Version is: 8
ATA Standard is: Exact ATA specification draft version not indicated
Local Time is: Thu Sep 15 22:28:54 2016 MSK
SMART support is: Available — device has SMART capability.
SMART support is: Enabled=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSEDGeneral SMART Values:
Offline data collection status: (0x84) Offline data collection activity
was suspended by an interrupting command from host.
Auto Offline Data Collection: Enabled.
Self-test execution status: ( 0) The previous self-test routine completed
without error or no self-test has ever
been run.
Total time to complete Offline
data collection: ( 9180) seconds.
Offline data collection
capabilities: (0x7b) SMART execute Offline immediate.
Auto Offline data collection on/off support.
Suspend Offline collection upon new
command.
Offline surface scan supported.
Self-test supported.
Conveyance Self-test supported.
Selective Self-test supported.
SMART capabilities: (0x0003) Saves SMART data before entering
power-saving mode.
Supports SMART auto save timer.
Error logging capability: (0x01) Error logging supported.
General Purpose Logging supported.
Short self-test routine
recommended polling time: ( 2) minutes.
Extended self-test routine
recommended polling time: ( 103) minutes.
Conveyance self-test routine
recommended polling time: ( 5) minutes.
SCT capabilities: (0x30bd) SCT Status supported.
SCT Error Recovery Control supported.
SCT Feature Control supported.
SCT Data Table supported.SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE
1 Raw_Read_Error_Rate 0x002f 200 200 051 Pre-fail Always — 0
3 Spin_Up_Time 0x0027 199 198 021 Pre-fail Always — 3008
4 Start_Stop_Count 0x0032 100 100 000 Old_age Always — 64
5 Reallocated_Sector_Ct 0x0033 200 200 140 Pre-fail Always — 0
7 Seek_Error_Rate 0x002e 200 200 000 Old_age Always — 0
9 Power_On_Hours 0x0032 055 055 000 Old_age Always — 33261
10 Spin_Retry_Count 0x0032 100 253 000 Old_age Always — 0
11 Calibration_Retry_Count 0x0032 100 253 000 Old_age Always — 0
12 Power_Cycle_Count 0x0032 100 100 000 Old_age Always — 64
192 Power-Off_Retract_Count 0x0032 200 200 000 Old_age Always — 33
193 Load_Cycle_Count 0x0032 200 200 000 Old_age Always — 72
194 Temperature_Celsius 0x0022 119 106 000 Old_age Always — 31
196 Reallocated_Event_Count 0x0032 200 200 000 Old_age Always — 0
197 Current_Pending_Sector 0x0032 200 200 000 Old_age Always — 0
198 Offline_Uncorrectable 0x0030 200 200 000 Old_age Offline — 0
199 UDMA_CRC_Error_Count 0x0032 200 200 000 Old_age Always — 0
200 Multi_Zone_Error_Rate 0x0008 200 200 000 Old_age Offline — 0SMART Error Log Version: 1
No Errors LoggedSMART Self-test log structure revision number 1
No self-tests have been logged. [To run self-tests, use: smartctl -t]SMART Selective self-test log data structure revision number 1
SPAN MIN_LBA MAX_LBA CURRENT_TEST_STATUS
1 0 0 Not_testing
2 0 0 Not_testing
3 0 0 Not_testing
4 0 0 Not_testing
5 0 0 Not_testing
Selective self-test flags (0x0):
After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.
Обращаем внимание на эту строчку смарта:
5 Reallocated_Sector_Ct 0x0033 200 200 140 Pre-fail Always — 0
Здесь говорится, что бедблоков нет, поэтому продолжаем делать резервную копию. Если все таки бед блоки есть, то немедленно менять диск на новый, как я понимаю на Вашем сервере должна быть как минимум зеркалка, т.е. raid 1. А старые диски продаем или ставим в десктопы.
Идем дальше.
Решение №1:
На помощь приходит специализированная программа ddrescue. Вот ее help:
[root@hyper1 tmp]# ddrescue —help
GNU ddrescue — Data recovery tool.
Copies data from one file or block device to another,
trying hard to rescue data in case of read errors.Usage: ddrescue [options] infile outfile [logfile]
You should use a logfile unless you know what you are doing.Options:
-h, —help display this help and exit
-V, —version output version information and exit
-a, —min-read-rate=<bytes> minimum read rate of good areas in bytes/s
-A, —try-again mark non-split, non-trimmed blocks as non-tried
-b, —block-size=<bytes> sector size of input device [default 512]
-B, —binary-prefixes show binary multipliers in numbers [SI]
-c, —cluster-size=<sectors> sectors to copy at a time [128]
-C, —complete-only do not read new data beyond logfile limits
-d, —direct use direct disc access for input file
-D, —synchronous use synchronous writes for output file
-e, —max-errors=[+]<n> maximum number of [new] error areas allowed
-E, —max-error-rate=<bytes> maximum allowed rate of read errors per second
-f, —force overwrite output device or partition
-F, —fill=<types> fill given type blocks with infile data (?*/-+)
-g, —generate-logfile generate approximate logfile from partial copy
-i, —input-position=<bytes> starting position in input file [0]
-I, —verify-input-size verify input file size with size in logfile
-K, —skip-size=<bytes> initial size to skip on read error [64 KiB]
-m, —domain-logfile=<file> restrict domain to finished blocks in file
-M, —retrim mark all failed blocks as non-trimmed
-n, —no-split do not try to split or retry failed blocks
-o, —output-position=<bytes> starting position in output file [ipos]
-p, —preallocate preallocate space on disc for output file
-q, —quiet suppress all messages
-r, —max-retries=<n> exit after given retries (-1=infinity) [0]
-R, —reverse reverse direction of copy operations
-s, —max-size=<bytes> maximum size of input data to be copied
-S, —sparse use sparse writes for output file
-t, —truncate truncate output file to zero size
-T, —timeout=<interval> maximum time since last successful read
-v, —verbose be verbose (a 2nd -v gives more)
-x, —extend-outfile=<bytes> extend outfile size to be at least this long
Numbers may be followed by a multiplier: b = blocks, k = kB = 10^3 = 1000,
Ki = KiB = 2^10 = 1024, M = 10^6, Mi = 2^20, G = 10^9, Gi = 2^30, etc…
Time intervals have the format 1[.5][smhd] or 1/2[smhd].
Report bugs to bug-ddrescue@gnu.org
Ddrescue home page: http://www.gnu.org/software/ddrescue/ddrescue.html
General help using GNU software: http://www.gnu.org/gethelp
Вот пример запуска резервного копирования:
[root@hyper1 tmp]# ddrescue -S /dev/vg/lvbilling /tmp/billing.img /tmp/billing.img.log
Из названия параметров я думаю все понятно.
Вот пример запуска восстановления раздела из резервной копии:
[root@hyper1 tmp]# ddrescue -fn /tmp/billing.img /dev/vg/lvbilling
Решение №2:
Используем старый дедовский способ с утилитой дд:
dd if=/dev/vg/lvbilling of=/tmp/billing.img conv=sync,noerror bs=64K
conv=sync,noerror — указывает dd не читать блок, если при этом происходит ошибка, но записать в архивируемый файл-образ данные, чтобы размер блока не менялся.
bs=64K — это размер блока в килобайтах — использование такого большого размера блока ускоряет процесс копирования.
Восстановление копии:
dd if=/tmp/billing.img of=/dev/vg/lvbilling bs=64K
Решение №3:
Лучшее на мой взгляд, так как диск может быть заполнен на 30%, а резервный образ получается равный полному объему диска, как то не экономно получается… Поэтому здесь не обойтись без сжатия.
Копирование резервное сразу со сжатием:
[root@hyper1 tmp]# dd if=/dev/vg/lvbilling conv=sync,noerror bs=64M | gzip -c >/tmp/billing.img.gz
256+0 записей считано
256+0 записей написано
17179869184 bytes (17 GB) copied, 560,443 секунд, 30,7 MB/s
Здесь буфер bs=64M должен равняться буферу кеша копируемого диска — для более быстрого конвеерного сжатия | gzip -c >
Восстановление диска — такое же.
Спасибо за внимание.
P.S. Если я допустил ошибку, поправьте меня в комментариях.