2013年1月17日木曜日

CentOS6 の cron.daily 実行時刻を CentOS5 以前と同様に設定する

CentOS6 の cron.daily 実行時刻は、CentOS5 以前とは異なります。
※この記事に書いた手順は、RHEL8 / RHEL7 / RHEL6でも通用します。末尾参照
CentOS5 以前であれば、デフォルトでは午前4:02にスケジュールされていましたが、CentOS6 のデフォルトでは、ある幅の範囲内でランダム化されています。
まずは、このランダム化の内容を確認してみます。

最初に /etc/crontab を見てみますと、次のように空っぽです。
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed

CentOS5 以前であれば、次のようにエントリーされていました。
02 4 * * * root run-parts /etc/cron.daily

ランダム化は、anacron (cronie-anacron) により行われており、設定内容は /etc/anacrontab に記述されています。デフォルトの /etc/anacrontab は、次の通りです。
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days   delay in minutes   job-identifier   command
1       5       cron.daily              nice run-parts /etc/cron.daily
7       25      cron.weekly             nice run-parts /etc/cron.weekly
@monthly 45     cron.monthly            nice run-parts /etc/cron.monthly
いくつかのパラメータがあり、man anacrontab(5) に解説がありますが、概説しますと、赤字の 1 (左端) が実行周期 (日次実行=1) で、次の数字 5 は、実行開始タイミングになってから、5 分間の遅延を入れる指定です。実行開始する時間帯は START_HOURS_RANGE で制御され、3-22 とは、3時から22時までの範囲 (3:00 ≦ t < 22:00) を指定しています。ランダム化の幅は RANDOM_DELAY で制御され、45 とは 0~45 分の範囲 (乱数計算の実装上、正確には 44 分まで) でランダムに遅延を行うことを指定しています。
やや複雑ですが、このデフォルト設定で 24H 運用した場合、cron.daily は午前3:06から3:50の間でランダム実行されることになります。ここで 3:06 なのは、そもそも anacron が動作する周期が毎時01分であるためです。/etc/cron.d/0hourly および /etc/cron.hourly/0anacron 参照。
また、もし毎日シャットダウン電源OFF運用を行う場合、例えば、午前6:00にブートすると、その直後の午前6:06から6:50の間でランダムに cron.daily が実行されることになります。
もしも、1日以上シャットダウンしていて、午後23:00にブートした場合には、START_HOURS_RANGE の範囲外であるため、cron.daily の実行は、翌日の午前3:06から3:50の間ということになります。

このランダム化は、仮想化環境を考慮してのこと (ゲストOSの cron.daily が重ならないようにする意図) とは思いますが、ランダムに動作されるのは運用上よろしくない (混乱要因となる) と考える方も居るかと思います。CentOS6 では、CentOS5 以前のように固定の時刻に cron.daily を行わせるようにする方法も用意されており、デフォルトでインストールされる cronie-anacron パッケージの代わりに、cronie-noanacron をインストールすればよいです。

パッケージの依存関係のため、事前に cronie-noanacron をインストールし、その後に cronie-anacron を削除するという手順を踏みます。
# yum install cronie-noanacron
...途中省略...
Installed:
  cronie-noanacron.x86_64 0:1.4.4-7.el6

Complete!

# rpm -e cronie-anacron
この cronie-noanacron は、ちっぽけなパッケージで、/etc/cron.d/dailyjobs ファイルだけを含んでいます。
# rpm -qi cronie-noanacron                                                   
Name        : cronie-noanacron             Relocations: (not relocatable)
Version     : 1.4.4                             Vendor: CentOS
Release     : 7.el6                         Build Date: Tue 19 Jul 2011 01:55:56 PM JST
Install Date: Thu 17 Jan 2013 12:02:39 AM JST      Build Host: c6b5.bsys.dev.centos.org
Group       : System Environment/Base       Source RPM: cronie-1.4.4-7.el6.src.rpm
Size        : 326                              License: MIT and BSD and ISC and GPLv2
Signature   : RSA/SHA1, Mon 26 Sep 2011 01:17:22 PM JST, Key ID 0946fca2c105b9de
Packager    : CentOS BuildSystem 
URL         : https://fedorahosted.org/cronie
Summary     : Utility for running simple regular jobs in old cron style
Description :
Old style of {hourly,daily,weekly,monthly}.jobs without anacron. No features.

# rpm -ql cronie-noanacron
/etc/cron.d/dailyjobs    ※パッケージの中身はこれ1個
/etc/cron.d/dailyjobs の中身は次のようになっています。
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
02 4 * * * root [ ! -f /etc/cron.hourly/0anacron ] && run-parts /etc/cron.daily
22 4 * * 0 root [ ! -f /etc/cron.hourly/0anacron ] && run-parts /etc/cron.weekly
42 4 1 * * root [ ! -f /etc/cron.hourly/0anacron ] && run-parts /etc/cron.monthly
CentOS5 以前での運用経験があれば、見慣れた実行時刻かと思います。ただし、0anacron の存在チェックが行われており、cronie-anacron パッケージを削除しないと有効化されないようにガードされています。ご注意を。

すでにお分かりかとは思いますが、cron.weekly および cron.monthly も同様です。ただ、cron.hourly はランダム化されておらず、次のように /etc/cron.d/0hourly に設定が書かれています。
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
01 * * * * root run-parts /etc/cron.hourly

最後に、いわずもがなですが、RHEL6 でも同様です :-p

2013-01-18追記
境界値がはっきりしないので、いちおう cronie-1.4.4-7.el6 のソースを見てみました。

START_HOURS_RANGE に対応する処理は、次の通りです。こちらは簡単ですね。
    422             t = localtime(&jobtime);
    423             if (range_start != -1 && range_stop != -1 &&
    424                 (t->tm_hour < range_start || t->tm_hour >= range_stop))
    425             {
    426                 Debug(("The job `%s' falls out of the %02d:00-%02d:00 hours range, skipping.",
    427                         job_array[j]->ident, range_start, range_stop));
    428                 job_array[j]->drop_job = 1;
    429             }
    430             else
"anacron/main.c"

RANDOM_DELAY に対応する処理は、次の通りです。
    279         if (strncmp(env_var, "RANDOM_DELAY", 12) == 0) {
    280             r = match_rx("^([[:digit:]]+)$", value, 0);
    281             if (r != -1) {
    282                 int i = random();
    283                 double x = 0;
    284                 x = (double) i / (double) RAND_MAX * (double) (atoi(value));
    285                 random_number = (int)x;    ※ここで小数点以下切捨てだからvalueは含まない?
    286                 Debug(("Randomized delay set: %d", random_number));
    287             }
    288         else goto reg_invalid;
    289         }
"anacron/readtab.c"
これを見ても、生成される random_number の範囲に value が含まれるのか否か、頭の中だけでは判然とせず。手間ですが、実験プログラムを一筆書いてみました。
/*
        test_random.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>

get_random_number(char *value)
{
        int random_number;

        // next 4 lines are copied from anacron/readtab.c:parse_tab_line()
        int i = random();
        double x = 0;
        x = (double) i / (double) RAND_MAX * (double) (atoi(value));
        random_number = (int)x;

        return random_number;
}

main(int argc, char* argv[])
{
        int i ;
        int random_number ;
        struct timeval tv ;
        struct timezone tz ;

        if (argc <= 1) exit(1) ;

        gettimeofday(&tv, &tz) ;
        // cronie uses this method
        srandom(getpid()+tv.tv_usec) ;

        for (i = 0; i < 10000; i++) {
                random_number = get_random_number(argv[1]) ;
                printf("%d\n", random_number) ;
        }
}
# gcc -o test_random test_random.c 
# ./test_random 10 | sort -n | uniq -c
    993 0
   1028 1
   1006 2
   1011 3
    998 4
   1030 5
    999 6
    966 7
    985 8
    984 9
# ./test_random 45 | sort -n | uniq -c | tail 
    210 35
    207 36
    218 37
    250 38
    197 39
    221 40
    217 41
    217 42
    209 43
    233 44
というわけで、0 ≦ random_number < value ですね。

2014-05-05追記
RHEL7.0 RC を試しましたが、RHEL6/CentOS6 と同様で、もし cron.daily 実行時刻を固定化したい場合は、cronie-noanacron と入れ替えれば良いようです。デフォルトの /etc/anacrontab の設定にも変更は無いようです。

2014-07-21追記
いちいち書くまでもないと思いつつ、RHEL7/CentOS7 でも同様です。

2019-05-26追記
CentOS8 は、現在のところ準備中のようです。
https://wiki.centos.org/About/Building_8
確認したところ RHEL8 でも、cronie-noanacron は存在しており、ここに書いた手順が通用するようです。

2012年12月10日月曜日

3TB ディスクから CentOS 6.3 をブート

バックアップ用に 3TB のディスク (WD30EZRX/K) を購入しました。

まずは、Windows 7 で採取した CrystalDiskInfo の結果です。
ZALMAN ZM-HE350 U3E というケースに格納し、ThinkPad T510 に eSATA 接続しています。WD30EZRX/K は NCQ に対応していますが、このケース経由だと NCQ が使えません (他のドライブでも確認・経験済み) 。その点はちょっと残念。

さて、CentOS 6.3 ならば、UEFI 非対応のマシン (ThinkPad T510 も勿論非対応) でも、3TB ディスクからブート可能という情報がありましたので、実際にやってみました。他のドライブが繋がっているとヤヤコシイので、一旦 3TB ディスク以外は外してインストールしました。その後に、内臓 SSD などを戻しています。また、ThinkPad の BIOS でブートオーダーを変更して起動しました。
# parted -s /dev/sdc print
Model: ATA WDC WD30EZRX-00D (scsi)
Disk /dev/sdc: 3001GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start   End     Size    File system     Name                  Flags
 1      1049kB  211MB   210MB   ext4                                  boot
 2      211MB   21.2GB  21.0GB  ext4
 3      21.2GB  23.3GB  2097MB  linux-swap(v1)
 4      23.3GB  3001GB  2977GB  ntfs            Basic data partition

# df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sdc2             20158332   4737476  14396856  25% /
tmpfs                  3986236       260   3985976   1% /dev/shm
/dev/sdc1               198337     51449    136648  28% /boot

# ls -l /dev/root
lrwxrwxrwx. 1 root root 4 Dec  9 22:10 /dev/root -> sdc2

# uname -a
Linux xxxx 2.6.32-279.14.1.el6.i686 #1 SMP Tue Nov 6 21:05:14 UTC 2012 i686 i686 i386 GNU/Linux
このように、うまく動作しました。
Fedora 16 以降なら、grub2 を使って GPT ラベルを付与したディスクからブート可能とは知ってましたが、grub1 でも対応パッチがあるようで、CentOS 6.3 の grub に取り込まれていたようです。

2012年12月1日土曜日

中古 SSD の SecureErase

某ショップにて中古の Intel SSD 320 600G を入手しました。GB単価が安かった(約50円)ため、思わず衝動買い。

中古ということで、総書き込み量はそれなりかと思っていたのですが、初回接続時にWindows7からCrystalDiskInfoで見てみると、次のような具合でした。
注: DeLOCK 42492 という eSATA/USB3.0 両対応のケースを使ったのですが、そのケース経由だと NCQ が使えないようです。下の CentOS6 のデータは、ケースから取り出して eSATA-SATA ケーブルで接続した場合です。SATA 電源は USB から供給。DeLOCK ケースはちょっと残念。

次は、CentOS6 で起動後の smartctl および hdparm のデータです。
# uname -a
Linux xxx 2.6.32-279.14.1.el6.x86_64 #1 SMP Tue Nov 6 23:43:09 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

# dmesg | egrep 'ata5|sdc'
ata5: SATA max UDMA/133 irq_stat 0x00400040, connection status changed irq 29
ata5: SATA link up 3.0 Gbps (SStatus 123 SControl 300)
ata5.00: ACPI cmd ef/02:00:00:00:00:a0 (SET FEATURES) succeeded
ata5.00: ACPI cmd f5/00:00:00:00:00:a0 (SECURITY FREEZE LOCK) filtered out
ata5.00: ATA-8: INTEL SSDSA2CW600G3, 4PC10362, max UDMA/133
ata5.00: 1172123568 sectors, multi 16: LBA48 NCQ (depth 31/32)
ata5.00: ACPI cmd ef/02:00:00:00:00:a0 (SET FEATURES) succeeded
ata5.00: ACPI cmd f5/00:00:00:00:00:a0 (SECURITY FREEZE LOCK) filtered out
ata5.00: configured for UDMA/133
ata5.00: configured for UDMA/133
ata5: EH complete
sd 5:0:0:0: [sdc] 1172123568 512-byte logical blocks: (600 GB/558 GiB)
sd 5:0:0:0: [sdc] Write Protect is off
sd 5:0:0:0: [sdc] Mode Sense: 00 3a 00 00
sd 5:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
 sdc:
sd 5:0:0:0: [sdc] Attached SCSI disk

# smartctl -a /dev/sdc
smartctl 5.42 2011-10-20 r3458 [x86_64-linux-2.6.32-279.14.1.el6.x86_64] (local build)
Copyright (C) 2002-11 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF INFORMATION SECTION ===
Model Family:     Intel 320 Series SSDs
Device Model:     INTEL SSDSA2CW600G3
Serial Number:    CVPR??????????????
LU WWN Device Id: 5 001517 bb28?????
Firmware Version: 4PC10362
User Capacity:    600,127,266,816 bytes [600 GB]
Sector Size:      512 bytes logical/physical
Device is:        In smartctl database [for details use: -P show]
ATA Version is:   8
ATA Standard is:  ATA-8-ACS revision 4
Local Time is:    Fri Nov 30 22:03:19 2012 JST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

Error SMART Thresholds Read failed: scsi error aborted command
Smartctl: SMART Read Thresholds failed.

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x00) Offline data collection activity
     was never started.
     Auto Offline Data Collection: Disabled.
Self-test execution status:      (  17) The self-test routine was aborted by
     the host.
Total time to complete Offline 
data collection:   (    1) seconds.
Offline data collection
capabilities:     (0x75) SMART execute Offline immediate.
     No Auto Offline data collection support.
     Abort Offline collection upon new
     command.
     No 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:   (   1) minutes.
Extended self-test routine
recommended polling time:   (   1) minutes.
Conveyance self-test routine
recommended polling time:   (   1) minutes.
SCT capabilities:         (0x003d) SCT Status supported.
     SCT Error Recovery Control supported.
     SCT Feature Control supported.
     SCT Data Table supported.

SMART Attributes Data Structure revision number: 5
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  3 Spin_Up_Time            0x0020   100   100   ---    Old_age   Offline      -       0
  4 Start_Stop_Count        0x0030   100   100   ---    Old_age   Offline      -       0
  5 Reallocated_Sector_Ct   0x0032   100   100   ---    Old_age   Always       -       0
  9 Power_On_Hours          0x0032   100   100   ---    Old_age   Always       -       1
 12 Power_Cycle_Count       0x0032   100   100   ---    Old_age   Always       -       5
170 Reserve_Block_Count     0x0033   100   100   ---    Pre-fail  Always       -       0
171 Program_Fail_Count      0x0032   100   100   ---    Old_age   Always       -       0
172 Erase_Fail_Count        0x0032   100   100   ---    Old_age   Always       -       0
183 Runtime_Bad_Block       0x0030   100   100   ---    Old_age   Offline      -       0
184 End-to-End_Error        0x0032   100   100   ---    Old_age   Always       -       0
187 Reported_Uncorrect      0x0032   100   100   ---    Old_age   Always       -       0
192 Unsafe_Shutdown_Count   0x0032   100   100   ---    Old_age   Always       -       1
199 UDMA_CRC_Error_Count    0x0030   100   100   ---    Old_age   Offline      -       0
225 Host_Writes_32MiB       0x0032   100   100   ---    Old_age   Always       -       17887
226 Workld_Media_Wear_Indic 0x0032   100   100   ---    Old_age   Always       -       20
227 Workld_Host_Reads_Perc  0x0032   100   100   ---    Old_age   Always       -       94
228 Workload_Minutes        0x0032   100   100   ---    Old_age   Always       -       116
232 Available_Reservd_Space 0x0033   100   100   ---    Pre-fail  Always       -       0
233 Media_Wearout_Indicator 0x0032   100   100   ---    Old_age   Always       -       0
241 Host_Writes_32MiB       0x0032   100   100   ---    Old_age   Always       -       17887
242 Host_Reads_32MiB        0x0032   100   100   ---    Old_age   Always       -       3

SMART Error Log Version: 1
No Errors Logged

SMART Self-test log structure revision number 1
No self-tests have been logged.  [To run self-tests, use: smartctl -t]


Note: selective self-test log revision number (0) not 1 implies that no selective self-test has ever been run
SMART Selective self-test log data structure revision number 0
Note: revision number not 1 implies that no selective self-test has ever been run
 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.

# hdparm -I /dev/sdc

/dev/sdc:

ATA device, with non-removable media
 Model Number:       INTEL SSDSA2CW600G3                     
 Serial Number:      CVPR??????????????  
 Firmware Revision:  4PC10362
 Transport:          Serial, ATA8-AST, SATA 1.0a, SATA II Extensions, SATA Rev 2.5, SATA Rev 2.6
Standards:
 Used: unknown (minor revision code 0x0029) 
 Supported: 8 7 6 5 
 Likely used: 8
Configuration:
 Logical  max current
 cylinders 16383 16383
 heads  16 16
 sectors/track 63 63
 --
 CHS current addressable sectors:   16514064
 LBA    user addressable sectors:  268435455
 LBA48  user addressable sectors: 1172123568
 Logical  Sector size:                   512 bytes
 Physical Sector size:                   512 bytes
 device size with M = 1024*1024:      572325 MBytes
 device size with M = 1000*1000:      600127 MBytes (600 GB)
 cache/buffer size  = unknown
 Nominal Media Rotation Rate: Solid State Device
Capabilities:
 LBA, IORDY(can be disabled)
 Queue depth: 32
 Standby timer values: spec'd by Standard, no device specific minimum
 R/W multiple sector transfer: Max = 16 Current = 16
 DMA: mdma0 mdma1 mdma2 udma0 udma1 udma2 udma3 udma4 udma5 *udma6 
      Cycle time: min=120ns recommended=120ns
 PIO: pio0 pio1 pio2 pio3 pio4 
      Cycle time: no flow control=120ns  IORDY flow control=120ns
Commands/features:
 Enabled Supported:
    * SMART feature set
      Security Mode feature set
    * Power Management feature set
    * Write cache
    * Look-ahead
    * Host Protected Area feature set
    * WRITE_BUFFER command
    * READ_BUFFER command
    * NOP cmd
    * DOWNLOAD_MICROCODE
      SET_MAX security extension
    * 48-bit Address feature set
    * Device Configuration Overlay feature set
    * Mandatory FLUSH_CACHE
    * FLUSH_CACHE_EXT
    * SMART error logging
    * SMART self-test
    * General Purpose Logging feature set
    * WRITE_{DMA|MULTIPLE}_FUA_EXT
    * 64-bit World wide name
    * IDLE_IMMEDIATE with UNLOAD
    * WRITE_UNCORRECTABLE_EXT command
    * {READ,WRITE}_DMA_EXT_GPL commands
    * Segmented DOWNLOAD_MICROCODE
    * Gen1 signaling speed (1.5Gb/s)
    * Gen2 signaling speed (3.0Gb/s)
    * Native Command Queueing (NCQ)
    * Phy event counters
      Device-initiated interface power management
    * Software settings preservation
    * SMART Command Transport (SCT) feature set
    * SCT LBA Segment Access (AC2)
    * SCT Error Recovery Control (AC3)
    * SCT Features Control (AC4)
    * SCT Data Tables (AC5)
    * Data Set Management TRIM supported
    * reserved 69[5]
    * Deterministic read after TRIM
Security: 
 Master password revision code = 65534
  supported
 not enabled
 not locked
 not frozen
 not expired: security count
  supported: enhanced erase
 2min for SECURITY ERASE UNIT. 2min for ENHANCED SECURITY ERASE UNIT.
Logical Unit WWN Device Identifier: 5001517bb28?????
 NAA  : 5
 IEEE OUI : 001517
 Unique ID : bb28?????
Integrity word not set (found 0x0000, expected 0x4fa5)


おそらくは、ゼロ書き込みによるデータ消去後であろう?とは思いましたが、せっかくの機会 (中古SSDは初挑戦) なので、オールゼロになっているのか確認してみたところ、SSD 上に残っていた文字列は、次の3行のみでした。
Delete End
2012/09/21/11:46:19
某ショップの会社名
さて、それなら SecureErase を実施したほうが、性能上良いはずなので、実際やりました。
# cat /sys/block/sdc/device/model 
INTEL SSDSA2CW60

# hdparm --user-master u --security-set-pass password /dev/sdc
security_password="password"

/dev/sdc:
 Issuing SECURITY_SET_PASS command, password="password", user=user, mode=high
# hdparm --user-master u --security-erase-enhanced password /dev/sdc
security_password="password"

/dev/sdc:
 Issuing SECURITY_ERASE command, password="password", user=user
SecureErase は1分ぐらい (ちょっとよそ見している間) で終わってしまいました。

ちなみに、Win7 上の Intel SSD Toolbox も試してみたのですが、わたしの環境では、どうしても frozen 状態が解除できず、実行できませんでした。

ThinkPad T510 に eSATA 接続の環境ですが、Toolbox の指示に従って、eSATA の先の SSD 電源を落としたり、刺しなおしたりしてみましたが、ダメでした。それなのに、デュアルブートにしてある CentOS6 では、frozen にはならず、簡単に SecureErase できました。

■関連記事
SecureErase を実施してみた
SecureErase のために frozen 状態を解除する方法
人気ブログランキングへ にほんブログ村 IT技術ブログへ