Pacemakerクラスタ管理コマンドまとめ

Pacemakerにて構成したクラスタを管理する際によく使用するpcsコマンドについて纏めてみた。

1. pcsバージョン確認

[root@centos01 ~]# pcs --version
0.9.137

2. クラスタ起動

全ノードのpacemaker/corosyncサービスを同時に起動する場合は以下の通り。

[root@centos01 ~]# pcs cluster start --all
centos01: Starting Cluster...
centos02: Starting Cluster...

ノード個別にサービスを起動したい場合は以下の通り。

[root@centos01 ~]# pcs cluster start centos02
centos02: Starting Cluster...

3. クラスタ停止

全ノードのpacemaker/corosyncサービスを同時に停止する場合は以下の通り。

[root@centos01 ~]# pcs cluster stop --all
centos01: Stopping Cluster (pacemaker)...
centos02: Stopping Cluster (pacemaker)...
centos01: Stopping Cluster (corosync)...
centos02: Stopping Cluster (corosync)...

ノード個別にサービスを停止したい場合は以下の通り。

[root@centos01 ~]# pcs cluster stop centos02 --force
centos02: Stopping Cluster (pacemaker)...
centos02: Stopping Cluster (corosync)...

また、クラスタを強制的に停止させる場合は以下の通り。

pcs cluster kill

4. クラスタ状態取得

[root@centos01 ~]# pcs status
Cluster name:
Last updated: Thu Jun 25 14:08:44 2015
Last change: Wed Jun 24 19:20:03 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
10 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:

 Resource Group: GroupPostgreSQL
     FilesystemForPostgreSQL    (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForPostgreSQL    (ocf::heartbeat:IPaddr2):       Started centos01
     PostgreSQL    (ocf::heartbeat:pgsql): Started centos01
 Resource Group: GroupNFS
     FilesystemForNFS   (ocf::heartbeat:Filesystem):    Started centos02
     VirtualIPForNFS   (ocf::heartbeat:IPaddr2):       Started centos02
     NFS   (ocf::heartbeat:nfsserver):     Started centos02
 Clone Set: MonitorGateway-clone [MonitorGateway]
     Started: [ centos01 centos02 ]
 StonithForCentos01    (stonith:fence_ipmilan):        Started centos02
 StonithForCentos02    (stonith:fence_ipmilan):        Started centos01

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

5. クラスタ設定取得

[root@centos01 ~]# pcs config
Cluster Name:
Corosync Nodes:
 centos01 centos02
Pacemaker Nodes:
 centos01 centos02

...

6. 特定ノードをスタンバイモードに移行

下記コマンドにて、特定ノードまたは全ノードをスタンバイモードへ移行できる。スタンバイモードに移行したノードではリソース実行が不可となるため、移行前にリソースが実行されていた場合はリソース実行可能なノードへフェールオーバーする。

pcs cluster standby <node name> [--all]

実際の操作例は以下の通り。

[root@centos01 ~]# pcs status
Cluster name:
Last updated: Thu Jun 25 14:16:41 2015
Last change: Thu Jun 25 14:16:39 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
10 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:

 Resource Group: GroupPostgreSQL
     FilesystemForPostgreSQL    (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForPostgreSQL    (ocf::heartbeat:IPaddr2):       Started centos01
     PostgreSQL    (ocf::heartbeat:pgsql): Started centos01
 Resource Group: GroupNFS
     FilesystemForNFS   (ocf::heartbeat:Filesystem):    Started centos02
     VirtualIPForNFS   (ocf::heartbeat:IPaddr2):       Started centos02
     NFS   (ocf::heartbeat:nfsserver):     Started centos02
 Clone Set: MonitorGateway-clone [MonitorGateway]
     Started: [ centos01 centos02 ]
 StonithForCentos01    (stonith:fence_ipmilan):        Started centos02
 StonithForCentos02    (stonith:fence_ipmilan):        Started centos01

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled
[root@centos01 ~]#
[root@centos01 ~]# pcs cluster standby centos02
[root@centos01 ~]#
[root@centos01 ~]# pcs status
Cluster name:
Last updated: Thu Jun 25 14:17:16 2015
Last change: Thu Jun 25 14:17:13 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
10 Resources configured


Node centos02 (2): standby
Online: [ centos01 ]

Full list of resources:

 Resource Group: GroupPostgreSQL
     FilesystemForPostgreSQL    (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForPostgreSQL    (ocf::heartbeat:IPaddr2):       Started centos01
     PostgreSQL    (ocf::heartbeat:pgsql): Started centos01
 Resource Group: GroupNFS
     FilesystemForNFS   (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForNFS   (ocf::heartbeat:IPaddr2):       Started centos01
     NFS   (ocf::heartbeat:nfsserver):     Started centos01
 Clone Set: MonitorGateway-clone [MonitorGateway]
     Started: [ centos01 ]
     Stopped: [ centos02 ]
 StonithForCentos01    (stonith:fence_ipmilan):        Stopped
 StonithForCentos02    (stonith:fence_ipmilan):        Started centos01

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

7. 特定ノードをスタンバイモードから復帰

pcs cluster unstandby <node name>

実際の操作例は以下の通り。

[root@centos01 ~]# pcs cluster unstandby centos02
[root@centos01 ~]#
[root@centos01 ~]# pcs status
Cluster name:
Last updated: Thu Jun 25 14:18:14 2015
Last change: Thu Jun 25 14:18:13 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
10 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:

 Resource Group: GroupPostgreSQL
     FilesystemForPostgreSQL    (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForPostgreSQL    (ocf::heartbeat:IPaddr2):       Started centos01
     PostgreSQL    (ocf::heartbeat:pgsql): Started centos01
 Resource Group: GroupNFS
     FilesystemForNFS   (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForNFS   (ocf::heartbeat:IPaddr2):       Started centos01
     NFS   (ocf::heartbeat:nfsserver):     Started centos01
 Clone Set: MonitorGateway-clone [MonitorGateway]
     Started: [ centos01 centos02 ]
 StonithForCentos01    (stonith:fence_ipmilan):        Started centos02
 StonithForCentos02    (stonith:fence_ipmilan):        Started centos01

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

8. 特定リソースの手動フェールオーバー

pcs resource move <resource id> [destination node name]

実際の操作例は以下の通り。

[root@centos01 ~]# pcs status
Cluster name:
Last updated: Thu Jun 25 14:15:38 2015
Last change: Wed Jun 24 19:20:03 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
10 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:

 Resource Group: GroupPostgreSQL
     FilesystemForPostgreSQL    (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForPostgreSQL    (ocf::heartbeat:IPaddr2):       Started centos01
     PostgreSQL    (ocf::heartbeat:pgsql): Started centos01
 Resource Group: GroupNFS
     FilesystemForNFS   (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForNFS   (ocf::heartbeat:IPaddr2):       Started centos01
     NFS   (ocf::heartbeat:nfsserver):     Started centos01
 Clone Set: MonitorGateway-clone [MonitorGateway]
     Started: [ centos01 centos02 ]
 StonithForCentos01    (stonith:fence_ipmilan):        Started centos02
 StonithForCentos02    (stonith:fence_ipmilan):        Started centos01

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled
[root@centos01 ~]#
[root@centos01 ~]#
[root@centos01 ~]# pcs resource move GroupNFS
[root@centos01 ~]#
[root@centos01 ~]# pcs status
Cluster name:
Last updated: Thu Jun 25 14:15:56 2015
Last change: Thu Jun 25 14:15:51 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
10 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:

 Resource Group: GroupPostgreSQL
     FilesystemForPostgreSQL    (ocf::heartbeat:Filesystem):    Started centos01
     VirtualIPForPostgreSQL    (ocf::heartbeat:IPaddr2):       Started centos01
     PostgreSQL    (ocf::heartbeat:pgsql): Started centos01
 Resource Group: GroupNFS
     FilesystemForNFS   (ocf::heartbeat:Filesystem):    Started centos02
     VirtualIPForNFS   (ocf::heartbeat:IPaddr2):       Started centos02
     NFS   (ocf::heartbeat:nfsserver):     Started centos02
 Clone Set: MonitorGateway-clone [MonitorGateway]
     Started: [ centos01 centos02 ]
 StonithForCentos01    (stonith:fence_ipmilan):        Started centos02
 StonithForCentos02    (stonith:fence_ipmilan):        Started centos01

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

9. 特定リソースのフェールオーバー履歴の削除

主系にて障害が発生しリソースが自動でフェールオーバーした場合、主系を復旧後にリソースをフェールバックしたい場合は事前にフェールオーバー履歴の削除が必要となる。(過去に障害が検出されたノードにはリソースを移動できないため)

pcs resoruce clear <resource id>

10. 手動でのフェンシング(STONITH機能によるサーバー再起動)

pcs stonith fence <node name>

CentOS7.1でPacemaker+corosyncによるクラスタを構成する

CentOS7.1でPacemaker+corosyncを使用したクラスタを構成してみた。RHEL/CentOS7におけるPacemaker+corosyncの日本語情報が少ないので、参考情報として記載する。

1. 動作確認環境

[仮想化ホスト環境]

[仮想マシン環境]

  • CentOS 7.1.1503
  • Pacemaker 1.1.12
  • corosync 2.3.4
  • fence-agents-all 4.0.11
  • httpd 2.4.6

2. 検証環境構成

以下の様な構成で検証を行った。

f:id:kanno_s:20150605113553j:plain

構成のポイントは以下の通り。

  • デスクトップPC(Windows7)をVirtualBox+Vagrantにより仮想化ホスト(VHost)として動作させ、仮想マシン(VM)として"centos01"、"centos02"の2台を構築。
  • VM間を内部ネットワークで接続し、これをcorosyncのハートビートLANとして使用。
  • VMとインターネット等の外部ネットワークとの接続は、NATネットワークを介して行う。
  • VHostとVMとの通信は、HostOnlyネットワークを介して行う。

3. 検証手順(概要)

今回は以下の様な流れで検証を行った。

  1. VM初期構成
  2. Pacemaker+corosync初期構成
  3. リソース(仮想IP)追加・動作確認
  4. リソース(httpd)追加・動作確認

4. VM初期構成手順

(1) VM作成

まずはVagrantにて、予め用意したBox(CentOS7.1)から新規VMを作成する。CentOS7.1のBox作成手順については、下記を参照のこと。

kan3aa.hatenablog.com

今回は新規に2台VMを作成するため、下記の様に予めフォルダを作成した。

C:\vm>dir

 C:\vm のディレクトリ

2015/06/04  17:24    <DIR>          .
2015/06/04  17:24    <DIR>          ..
2015/06/04  11:57    <DIR>          basebox
2015/05/28  16:11    <DIR>          centos01
2015/06/03  12:18    <DIR>          centos02

新規VM用に、Vagrantfileを2つ作成し、上記のVM用フォルダ(centos01, centos02)にそれぞれ配置する。"centos01"用のVagrantfileは以下の通りとした。

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|

  config.vm.hostname = "centos01"
  config.vm.box = "CentOS-7.1-x86_64-minimal-ja-20150528"

  config.vm.provider "virtualbox" do |vb|
    # vb.gui = true
    vb.memory = "512"
    vb.customize ["modifyvm", :id, "--nic2", "hostonly"]
    vb.customize ["modifyvm", :id, "--nictype2", "82540EM"]
    vb.customize ["modifyvm", :id, "--nicpromisc2", "allow-all"]
    vb.customize ["modifyvm", :id, "--cableconnected2", "on"]
    vb.customize ["modifyvm", :id, "--nic3", "intnet"]
    vb.customize ["modifyvm", :id, "--nictype3", "82540EM"]
    vb.customize ["modifyvm", :id, "--nicpromisc3", "allow-all"]
    vb.customize ["modifyvm", :id, "--cableconnected3", "on"]
  end

  config.vm.network "private_network", ip: "192.168.56.11"

end

NATネットワーク用NICはBoxの時点で構成済みのため、上記ではHostOnlyネットワーク用の"nic2"と、内部ネットワーク用の"nic3"を追加している。追加nic設定に関する記載方法はVirtualBoxのVBoxManageコマンド仕様(Chapter 8. VBoxManage)に従う。

HostOnlyネットワーク用のIPアドレスは"private_network"で指定している。VagrantVMにHostOnlyアダプタが存在する場合、そこに"private_network"で指定したIPアドレスを設定する。HostOnlyアダプタが存在しなければ、Vagrantが自動的に作成するが、上記ではあえて明示的に追加している。

Vagrantfileの配置が完了したら、"vagrant up"コマンドによりVMを作成する。以下に"centos01"の例を示す。

C:\vm>cd C:\vm\centos01
C:\vm\centos01>vagrant up
(2) OS設定

基本的な設定はBox作成時点で実施済みのため、ここではネットワーク周りの設定を行う。

まずIPv6は使用しないため、無効化しておく。

[root@centos01 ~]# vim /etc/sysctl.conf
# System default settings live in /usr/lib/sysctl.d/00-system.conf.
# To override those settings, enter new settings here, or in an /etc/sysctl.d/<name>.conf file
#
# For more information, see sysctl.conf(5) and sysctl.d(5).

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

[root@centos01 ~]# sysctl -p
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

次に、内部ネットワーク用NIC(enp0s9)に対してIPアドレスを設定する。確認すると、デバイスとしては認識されているが、NetworkManagerには認識されていない。network-scripts配下に設定ファイルが存在しないためである。

[root@centos01 ~]# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:60:8c:4e brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 86184sec preferred_lft 86184sec
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:45:cc:99 brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.11/24 brd 192.168.56.255 scope global enp0s8
       valid_lft forever preferred_lft forever
4: enp0s9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:f0:5f:8a brd ff:ff:ff:ff:ff:ff

[root@centos01 ~]# nmcli c show
名前        UUID                                  タイプ          デバイス 
有線接続 1  4c5bd390-a059-43d1-a109-de3802e9e842  802-3-ethernet  --       
enp0s3      d28eb2ae-0fef-4869-b984-ee7eaf640499  802-3-ethernet  enp0s3   

[root@centos01 ~]# 
[root@centos01 ~]# cd /etc/sysconfig/network-scripts/
[root@centos01 network-scripts]# 
[root@centos01 network-scripts]# ls -l
合計 236
-rw-r--r--. 1 root root   310  528 14:06 ifcfg-enp0s3
-rw-r--r--  1 root root   217  64 17:37 ifcfg-enp0s8
-rw-r--r--. 1 root root   254  115 17:57 ifcfg-lo
...

そのため、内部ネットワーク用NIC(enp0s9)の設定ファイル(ifcfg-enp0s9)を新規作成し、NetworkManagerサービスを再起動する。

[root@centos01 network-scripts]# vim ifcfg-enp0s9
TYPE="Ethernet"
BOOTPROTO="none"
IPV4_FAILURE_FATAL="no"
NAME="enp0s9"
DEVICE="enp0s9"
ONBOOT="yes"

[root@centos01 network-scripts]# systemctl restart NetworkManager
[root@centos01 network-scripts]# nmcli c show
名前    UUID                                  タイプ          デバイス 
enp0s3  0f338d9d-cdb7-420a-988a-21e03f6f1ae4  802-3-ethernet  enp0s3   
enp0s3  d28eb2ae-0fef-4869-b984-ee7eaf640499  802-3-ethernet  --       
enp0s9  93d13955-e9e2-a6bd-df73-12e3c747f122  802-3-ethernet  enp0s9   

無事NetworkManagerに内部ネットワーク用NIC(enp0s9)が認識された。(この時点では"nmcli c show"の表示がおかしい。NetworkManager管理外となっているHostOnlyネットワーク用NIC(enp0s8)がなぜかenp0s3として表示されている?)

次に、nmcliでIPアドレスを設定し、NICの再起動を行う。

[root@centos01 network-scripts]# nmcli c mod enp0s9 ipv4.method manual ipv4.addresses "172.16.0.1/24"

[root@centos01 network-scripts]# nmcli c down enp0s9; nmcli c up enps0s9
Connection 'enp0s9' successfully deactivated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/1)
接続が正常にアクティベートされました (D-Bus アクティブパス: /org/freedesktop/NetworkManager/ActiveConnection/2)

[root@centos01 network-scripts]# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:60:8c:4e brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 86186sec preferred_lft 86186sec
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:45:cc:99 brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.11/24 brd 192.168.56.255 scope global enp0s8
       valid_lft forever preferred_lft forever
4: enp0s9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:f0:5f:8a brd ff:ff:ff:ff:ff:ff
    inet 172.16.0.1/24 brd 172.16.0.255 scope global enp0s9
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fef0:5f8a/64 scope link 
       valid_lft forever preferred_lft forever

最後に、hostsを設定しておく。(corosync設定用)

[root@centos01 ~]# vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

172.16.0.1      centos01
172.16.0.2      centos02

以上でネットワーク設定は完了。"centos02"も同様に設定しておく。

5. Pacemaker+corosync初期構成

(1) Pacemaker+corosyncインストール

yumにて必要パッケージをインストールする。"pcs"と"fence-agents-all"を指定しておくと、依存関係の解決により必要パッケージがすべてインストールされる。pcsは旧来のcrmshに代わるPacemakerクラスタ管理ツールであり、RHEL/CentOS7においてはpcsの使用が推奨されている。

[root@centos01 ~]# yum -y install pcs fence-agents-all
...
依存性を解決しました

================================================================================
 Package                      アーキテクチャー
                                        バージョン             リポジトリー
                                                                           容量
================================================================================
インストール中:
 fence-agents-all             x86_64    4.0.11-11.el7_1        updates    8.9 k
 pcs                          x86_64    0.9.137-13.el7_1.2     updates    5.4 M
依存性関連でのインストールをします:
 OpenIPMI-modalias            x86_64    2.0.19-11.el7          base        15 k
 autogen-libopts              x86_64    5.18-5.el7             base        66 k
 bc                           x86_64    1.06.95-13.el7         base       115 k
 corosync                     x86_64    2.3.4-4.el7_1.1        updates    205 k
 corosynclib                  x86_64    2.3.4-4.el7_1.1        updates    119 k
 fence-agents-apc             x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-apc-snmp        x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-bladecenter     x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-brocade         x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-cisco-mds       x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-cisco-ucs       x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-common          x86_64    4.0.11-11.el7_1        updates     52 k
 fence-agents-drac5           x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-eaton-snmp      x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-eps             x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-hpblade         x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-ibmblade        x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-ifmib           x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-ilo-mp          x86_64    4.0.11-11.el7_1        updates     11 k
 fence-agents-ilo-ssh         x86_64    4.0.11-11.el7_1        updates     14 k
 fence-agents-ilo2            x86_64    4.0.11-11.el7_1        updates     14 k
 fence-agents-intelmodular    x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-ipdu            x86_64    4.0.11-11.el7_1        updates     13 k
 fence-agents-ipmilan         x86_64    4.0.11-11.el7_1        updates     19 k
 fence-agents-kdump           x86_64    4.0.11-11.el7_1        updates     22 k
 fence-agents-rhevm           x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-rsb             x86_64    4.0.11-11.el7_1        updates     12 k
 fence-agents-scsi            x86_64    4.0.11-11.el7_1        updates     15 k
 fence-agents-vmware-soap     x86_64    4.0.11-11.el7_1        updates     14 k
 fence-agents-wti             x86_64    4.0.11-11.el7_1        updates     13 k
 fence-virt                   x86_64    0.3.2-1.el7            base        41 k
 gnutls-dane                  x86_64    3.3.8-12.el7           base        32 k
 gnutls-utils                 x86_64    3.3.8-12.el7           base       227 k
 ipmitool                     x86_64    1.8.13-8.el7_1         updates    367 k
 ldns                         x86_64    1.6.16-7.el7           base       473 k
 libevent                     x86_64    2.0.21-4.el7           base       214 k
 libqb                        x86_64    0.17.1-1.el7_1.2       updates     91 k
 libtool-ltdl                 x86_64    2.4.2-20.el7           base        49 k
 libxslt                      x86_64    1.1.28-5.el7           base       242 k
 libyaml                      x86_64    0.1.4-11.el7_0         base        55 k
 nano                         x86_64    2.3.1-10.el7           base       440 k
 net-snmp-libs                x86_64    1:5.7.2-20.el7         base       745 k
 net-snmp-utils               x86_64    1:5.7.2-20.el7         base       195 k
 pacemaker                    x86_64    1.1.12-22.el7_1.2      updates    436 k
 pacemaker-cli                x86_64    1.1.12-22.el7_1.2      updates    240 k
 pacemaker-cluster-libs       x86_64    1.1.12-22.el7_1.2      updates     90 k
 pacemaker-libs               x86_64    1.1.12-22.el7_1.2      updates    514 k
 perl-TimeDate                noarch    1:2.30-2.el7           base        52 k
 pexpect                      noarch    2.3-11.el7             base       142 k
 psmisc                       x86_64    22.20-8.el7            base       140 k
 python-chardet               noarch    2.0.1-7.el7            base       222 k
 python-clufter               x86_64    0.9.137-13.el7_1.2     updates    270 k
 python-lxml                  x86_64    3.2.1-4.el7            base       758 k
 python-requests              noarch    1.1.0-8.el7            base        70 k
 python-six                   noarch    1.3.0-4.el7            base        18 k
 python-suds                  noarch    0.4.1-5.el7            base       204 k
 python-urllib3               noarch    1.5-8.el7              base        41 k
 resource-agents              x86_64    3.9.5-40.el7_1.3       updates    299 k
 ruby                         x86_64    2.0.0.598-24.el7       base        67 k
 ruby-irb                     noarch    2.0.0.598-24.el7       base        88 k
 ruby-libs                    x86_64    2.0.0.598-24.el7       base       2.8 M
 rubygem-bigdecimal           x86_64    1.2.0-24.el7           base        79 k
 rubygem-io-console           x86_64    0.4.2-24.el7           base        50 k
 rubygem-json                 x86_64    1.7.7-24.el7           base        75 k
 rubygem-psych                x86_64    2.0.0-24.el7           base        77 k
 rubygem-rdoc                 noarch    4.0.0-24.el7           base       318 k
 rubygems                     noarch    2.0.14-24.el7          base       212 k
 sbd                          x86_64    1.2.1-3                base        32 k
 sg3_utils                    x86_64    1.37-5.el7             base       640 k
 sg3_utils-libs               x86_64    1.37-5.el7             base        63 k
 telnet                       x86_64    1:0.17-59.el7          base        63 k
 unbound-libs                 x86_64    1.4.20-19.el7          base       294 k

トランザクションの要約
================================================================================
インストール  2 パッケージ (+72 個の依存関係のパッケージ)

...
完了しました!

この時点でサーバを再起動する。

次に、corosyncによるサーバ間通信の認証で使用される"hacluster"ユーザのパスワードを設定する。上記のパッケージインストール時に自動的にユーザが作成されているため、パスワード変更のみ行う。パスワードはクラスタを構成するすべてのサーバにて同一とする。

[root@centos01 ~]# passwd hacluster
ユーザー hacluster のパスワードを変更。
新しいパスワード:
新しいパスワードを再入力してください:
passwd: すべての認証トークンが正しく更新できました。

次に、pcsdサービスを起動および有効化する。pcsdはPacemakerやcorosyncとは独立したサービスであり、これが起動していないとクラスタ構成時に使用するpcsコマンドが使えないため。

[root@centos01 ~]# systemctl start pcsd
[root@centos01 ~]# systemctl enable pcsd
ln -s '/usr/lib/systemd/system/pcsd.service' '/etc/systemd/system/multi-user.target.wants/pcsd.service'
[root@centos01 ~]# 
[root@centos01 ~]# systemctl status pcsd
pcsd.service - PCS GUI and remote configuration interface
   Loaded: loaded (/usr/lib/systemd/system/pcsd.service; enabled)
   Active: active (running) since 木 2015-06-04 18:10:11 JST; 15s ago
 Main PID: 3921 (pcsd)
   CGroup: /system.slice/pcsd.service
           tq3921 /bin/sh /usr/lib/pcsd/pcsd start
           tq3925 /bin/bash -c ulimit -S -c 0 >/dev/null 2>&1 ; /usr/bin/ruby...
           mq3926 /usr/bin/ruby -I/usr/lib/pcsd /usr/lib/pcsd/ssl.rb

 604 18:10:11 centos01 systemd[1]: Starting PCS GUI and remote configur.....
 604 18:10:11 centos01 systemd[1]: Started PCS GUI and remote configura...e.
Hint: Some lines were ellipsized, use -l to show in full.

以上の手順をcentos02に対しても同様に行う。

次に、corosync設定として、"pcs cluster auth"コマンドによりノードの認証を行う。これにより、corosyncによるサーバ間通信が可能となる。

[root@centos01 ~]# pcs cluster auth centos01 centos02 -u hacluster -p <password> --force
centos01: Authorized
centos02: Authorized

次に、"pcs cluster setup"コマンドにより、初期クラスタの作成を行う。

[root@centos01 ~]# pcs cluster setup --name testcluster centos01 centos02
Shutting down pacemaker/corosync services...
Redirecting to /bin/systemctl stop  pacemaker.service
Redirecting to /bin/systemctl stop  corosync.service
Killing any remaining services...
Removing all cluster configuration files...
centos01: Succeeded
centos02: Succeeded

上記が成功したら、下記コマンドによりクラスタを起動する。

[root@centos01 ~]# pcs cluster start --all
centos01: Starting Cluster...
centos02: Starting Cluster...
(2) 初期状態確認

まず、"corosync-cfgtool -s"コマンドにより、corosyncによるサーバ間通信の状況を確認する。

[root@centos01 ~]# corosync-cfgtool -s
Printing ring status.
Local node ID 1
RING ID 0
	id	= 172.16.0.1
	status	= ring 0 active with no faults

"status"が"active"かつ"no faults"であれば、問題なく通信が行えている。同様に、以下のコマンドでもcorosyncの動作状況を確認できる。

[root@centos01 ~]# corosync-cpamapctl | grep members
runtime.totem.pg.mrp.srp.members.1.config_version (u64) = 0
runtime.totem.pg.mrp.srp.members.1.ip (str) = r(0) ip(172.16.0.1) 
runtime.totem.pg.mrp.srp.members.1.join_count (u32) = 1
runtime.totem.pg.mrp.srp.members.1.status (str) = joined
runtime.totem.pg.mrp.srp.members.2.config_version (u64) = 0
runtime.totem.pg.mrp.srp.members.2.ip (str) = r(0) ip(172.16.0.2) 
runtime.totem.pg.mrp.srp.members.2.join_count (u32) = 1
runtime.totem.pg.mrp.srp.members.2.status (str) = joined

[root@centos01 ~]# pcs status corosync

Membership information
----------------------
    Nodeid      Votes Name
         1          1 centos01 (local)
         2          1 centos02

次に、Pacemakerとcorosyncのプロセス群が正常に起動しているかを確認する。下記プロセスが起動していれば問題ない。

[root@centos01 ~]# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
...
root      2258  1.5  7.5 191512 37656 ?        Ssl  18:39   0:01 corosync
root      2273  0.0  1.4 130424  7236 ?        Ss   18:39   0:00 /usr/sbin/pacemakerd -f
haclust+  2274  0.0  2.7 132772 13788 ?        Ss   18:39   0:00 /usr/libexec/pacemaker/cib
root      2275  0.0  1.5 133892  8004 ?        Ss   18:39   0:00 /usr/libexec/pacemaker/stonithd
root      2276  0.0  0.9 102872  5008 ?        Ss   18:39   0:00 /usr/libexec/pacemaker/lrmd
haclust+  2277  0.0  1.5 124700  7612 ?        Ss   18:39   0:00 /usr/libexec/pacemaker/attrd
haclust+  2278  0.0  4.1 150932 20904 ?        Ss   18:39   0:00 /usr/libexec/pacemaker/pengine
haclust+  2279  0.1  2.2 184088 11216 ?        Ss   18:39   0:00 /usr/libexec/pacemaker/crmd
...

次に、"pcs status"コマンドでクラスタ状態を確認する。

[root@centos01 ~]# pcs status
Cluster name: testcluster
WARNING: no stonith devices and stonith-enabled is not false
Last updated: Thu Jun  4 18:40:43 2015
Last change: Thu Jun  4 18:32:41 2015
Stack: corosync
Current DC: centos01 (1) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
0 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:


PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

両ノードともOnlineであり、リソースはまだ定義されていないことが確認できる。また、この時点ではstonithに関するWARNINGが表示されている。そこで、"crm_verify"コマンドで設定を確認してみる。

[root@centos01 ~]# crm_verify -L -V
   error: unpack_resources: 	Resource start-up disabled since no STONITH resources have been defined
   error: unpack_resources: 	Either configure some or disable STONITH with the stonith-enabled option
   error: unpack_resources: 	NOTE: Clusters with shared data need STONITH to ensure data integrity
Errors found during check: config not valid

Pacemakerでは規定でstonith機能が有効となっているが、まだstonithリソースが定義されていないため、上記のエラーが表示されている。今回はstonith機能は使用しないので、無効化しておく。

[root@centos01 ~]# pcs property set stonith-enabled=false
[root@centos01 ~]# crm_verify -L -V
[root@centos01 ~]# 

以上により、クラスタの初期状態が正常であることが確認できた。

6. リソース追加(仮想IP)

(1) リソース追加

次に、リソースとして仮想IPを追加する。リソース追加時は"pcs resource create"コマンドを使用する。リソースのパラメータは以下の通り。

  • リソースID:VIP
  • リソースエージェント(RA):"ocf:heartbeat:IPaddr2"
  • IPアドレス:192.168.56.10/24(HostOnlyネットワークアドレス)
  • 監視間隔:10sec
[root@centos01 ~]# pcs resource create VIP ocf:heartbeat:IPaddr2 \
    ip=192.168.56.10 cidr_netmask=24 op monitor interval=10s

そもそもリソースとは、クラスタが提供するサービスの構成要素である。今回構成する仮想IPやapache HTTP serverがこれにあたる。リソースを定義する際は、必ずリソースエージェント(RA)の指定が必要となる。RAとは、Pacemakerがリソースを起動・停止・監視するために用いるプログラムであり、実態はシェルスクリプトになっている*1。RAのソースコードのうち、特に正常性判定条件については、どういった状況下でリソースがフェールオーバーするのかを理解する意味で、一読しておくことをおすすめする。

RAの実装は基本的にOCF(Open Cluster Framework*2)に従っている。サーバ上では、RAスクリプトは"/lib/ocf/resource.d/"配下に格納されている。

"pcs status"でクラスタの状態を確認してみる。

[root@centos01 ~]# pcs status
Cluster name: testcluster
Last updated: Thu Jun  4 18:59:36 2015
Last change: Thu Jun  4 18:59:21 2015
Stack: corosync
Current DC: centos02 (2) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
1 Resources configured


Online: [ centos01 centos02 ]

Full list of resources:

 VIP	(ocf::heartbeat:IPaddr2):	Started centos01 

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

リソースとして"VIP"が追加され、centos01で動作していることがわかる。"ip addr show"を実行すると、HostOnlyアダプタのセカンダリIPとして仮想IPが設定されている。

[root@centos01 ~]# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:60:8c:4e brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 84670sec preferred_lft 84670sec
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:45:cc:99 brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.11/24 brd 192.168.56.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet 192.168.56.10/24 brd 192.168.56.255 scope global secondary enp0s8
       valid_lft forever preferred_lft forever
4: enp0s9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:f0:5f:8a brd ff:ff:ff:ff:ff:ff
    inet 172.16.0.1/24 brd 172.16.0.255 scope global enp0s9
       valid_lft forever preferred_lft forever
(2) リソースフェールオーバー

ここで、動作確認としてcentos01のPacemakerとcorosyncを停止し、リソースをフェールオーバーさせてみる。

[root@centos01 ~]# pcs cluster stop centos01
centos01: Stopping Cluster (pacemaker)...
centos01: Stopping Cluster (corosync)...

[root@centos01 ~]# pcs status
Error: cluster is not currently running on this node

centos02でクラスタの状態を確認すると、仮想IPリソースがフェールオーバーしているのがわかる。

[root@centos02 ~]# pcs status
Cluster name: testcluster
Last updated: Thu Jun  4 19:27:55 2015
Last change: Thu Jun  4 18:59:20 2015
Stack: corosync
Current DC: centos02 (2) - partition with quorum
Version: 1.1.12-a14efad
2 Nodes configured
1 Resources configured


Online: [ centos02 ]
OFFLINE: [ centos01 ]

Full list of resources:

 VIP	(ocf::heartbeat:IPaddr2):	Started centos02 

PCSD Status:
  centos01: Online
  centos02: Online

Daemon Status:
  corosync: active/disabled
  pacemaker: active/disabled
  pcsd: active/enabled

インストールメディアをyumリポジトリとして登録・使用する

タイトルの通り。

1. 動作確認環境

2. 事前準備

  • RHELインストールメディア(ISO)をredhat.comからダウンロードする。
  • VM等にRHELをインストールし、初期設定を実施する。
  • RHELインストールメディアをサーバのDVD-ROMドライブ等にセットする。

3. yumリポジトリ設定

まず、RHELインストールメディアを読み取り専用で/mediaにマウントする。

[root@localhost ~]# mount -r /dev/sr0 /media

次に、yumリポジトリ設定を行う。

[root@localhost ~]# vi /etc/yum.repos.d/rheldvd.repo
[rhel-iso]
name=Red Hat Enterprise Linux 7.0 ISO media
baseurl=file:///media
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release

上記ファイルの設定内容は以下の通り。

  • "[...]"はリポジトリ識別子(任意の文字列)
  • "name"はリポジトリ名(任意の文字列)
  • "baseurl"はリポジトリベースディレクトリ。"/repodata/repomd.xml"が存在しない場合、エラーとなる。
  • "enabled"はリポジトリの有効(1)/無効(0)設定。
  • "gpgcheck"はGPGを使用した署名確認の有効(1)/無効(0)設定。
  • "gpgkey"はGPG公開鍵ファイルパス。

後は、yumコマンドで各種パッケージをインストールする。

[root@localhost ~]# yum search vim
読み込んだプラグイン:product-id, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
rhel-iso                                                   | 4.1 kB   00:00
(1/2): rhel-iso/group_gz                                   | 134 kB   00:00
(2/2): rhel-iso/primary_db                                 | 3.4 MB   00:00
=============================== N/S matched: vim ===============================
vim-X11.x86_64 : The VIM version of the vi editor for the X Window System
vim-common.x86_64 : The common files needed by any version of the VIM editor
vim-enhanced.x86_64 : A version of the VIM editor which includes recent
                    : enhancements
vim-filesystem.x86_64 : VIM filesystem layout
vim-minimal.x86_64 : A minimal version of the VIM editor

  Name and summary matches only, use "search all" for everything.

インストール完了後はISOメディアをアンマウントして、リポジトリを無効化しておく。

[root@localhost ~]# umount /media
[root@localhost ~]# vi /etc/yum.repos.d/rheldvd.repo
[rhel-iso]
name=Red Hat Enterprise Linux 7.0 ISO
baseurl=file:///media
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release

[root@localhost ~]# yum clean all

CentOS7.1にてVagrant Base Boxを作成する

CentOS7.1でVagrant Base Boxを自作する方法について。

1. 動作確認環境

2. 前提条件

  • Vagrantがインストール済であること
  • VirtualBoxがインストール済であること
  • TeraTerm等のターミナルソフトがインストール済であること

3. Vagrant Base Box作成手順

(1) CentOS7.1 ISOファイルのダウンロード

下記URLからCentOS 7.1.1503のISOファイル(minimal)をダウンロードする。

http://ftp.riken.jp/Linux/centos/7.1.1503/isos/x86_64/
→"CentOS-7-x86_64-Minimal-1503-01.iso"

(2) VirtualBoxにてVM作成

VirtualBoxを起動し、メニューの[新規]を選択して新規VMを作成する。

  • VM名:任意*1
  • OS :Linux, Red Hat (64 bit)
  • CPU :1コア以上*2
  • MEM :512MB以上*3
  • HDD :サイズ可変, 8GB以上*4, VDI*5
(3) VM設定

Vagrantの公式ドキュメント(Creating a Base Box - Vagrant Documentation)に従い、下記のVM設定を行う。(VM設定は、該当VMを右クリックし、メニューから[設定]を選択)

  • "オーディオ"設定にて、[オーディオを有効化]のチェックを外す。
  • "USB"設定にて、[USBコントローラーを有効化]のチェックを外す。

また、OSインストール後にターミナルソフトからSSHにてログオン可能となるよう、ポートフォワーディングの設定を行う。

  1. "ネットワーク"設定にて、[アダプター1]を選択し、[高度]タブを展開する。
  2. [ポートフォワーディング]ボタンを押下する。
  3. [新規ルールを追加]ボタンを押下し、ポートフォワーディングルールを設定する。設定内容は以下の通り。
  • 名前    :任意(ssh等)
  • プロトコル :TCP
  • ホストIP  :127.0.0.1
  • ホストポート:任意(2222等)
  • ゲストポート:22
(4) CentOS7.1インストール

VM設定にて、予めDLしたISOイメージを対象VMにマウントし、VMを起動する。インストール時の設定は以下の通り。

  1. インストーラの初期画面にて、[Install CentOS 7.1]を選択する。
  2. [CentOSへようこそ]画面にて、[日本語]を選択する。
  3. [地域設定]は規定値とする。*6
  4. [ソフトウェア]は規定値とする。*7
  5. "システム"の"インストール先"を選択し、先ほど作成した仮想HDDが選択されていることを確認。また、"自動構成のパーティション構成"を選択。*8
  6. "システム"の"ネットワークとホスト名"を選択し、[イーサネット(enpOs3)]を有効化する。*9また、任意のホスト名を設定する。
  7. [インストールの開始]ボタンを押下する。
  8. "rootパスワード"を選択し、パスワードとして"vagrant"を設定する。*10
  9. "ユーザの作成"を選択し、非管理者ユーザとして、"vagrant"を作成する。パスワードは"vagrant"とする。*11
  10. インストールが正常に完了することを確認する。
(5) OS設定
a) 不要サービスの停止・無効化

最少インストール直後に動作しているサービス一覧は以下の通り。

[root@centos71 ~]# systemctl list-units --type=service
UNIT                               LOAD   ACTIVE SUB     DESCRIPTION
auditd.service                     loaded active running Security Auditing Service
crond.service                      loaded active running Command Scheduler
dbus.service                       loaded active running D-Bus System Message Bus
firewalld.service                  loaded active running firewalld - dynamic firewall daemon
getty@tty1.service                 loaded active running Getty on tty1
kdump.service                      loaded failed failed  Crash recovery kernel arming
kmod-static-nodes.service          loaded active exited  Create list of required static device nodes for the current kernel
lvm2-lvmetad.service               loaded active running LVM2 metadata daemon
lvm2-monitor.service               loaded active exited  Monitoring of LVM2 mirrors, snapshots etc. using dmeventd or progress
lvm2-pvscan@8:2.service            loaded active exited  LVM2 PV scan on device 8:2
network.service                    loaded active exited  LSB: Bring up/down networking
NetworkManager.service             loaded active running Network Manager
polkit.service                     loaded active running Authorization Manager
postfix.service                    loaded active running Postfix Mail Transport Agent
rhel-dmesg.service                 loaded active exited  Dump dmesg to /var/log/dmesg
rhel-import-state.service          loaded active exited  Import network configuration from initramfs
rhel-readonly.service              loaded active exited  Configure read-only root support
rsyslog.service                    loaded active running System Logging Service
sshd.service                       loaded active running OpenSSH server daemon
systemd-journald.service           loaded active running Journal Service
systemd-logind.service             loaded active running Login Service
systemd-random-seed.service        loaded active exited  Load/Save Random Seed
systemd-remount-fs.service         loaded active exited  Remount Root and Kernel File Systems
systemd-sysctl.service             loaded active exited  Apply Kernel Variables
systemd-tmpfiles-setup-dev.service loaded active exited  Create static device nodes in /dev
systemd-tmpfiles-setup.service     loaded active exited  Create Volatile Files and Directories
systemd-udev-trigger.service       loaded active exited  udev Coldplug all Devices
systemd-udevd.service              loaded active running udev Kernel Device Manager
systemd-update-utmp.service        loaded active exited  Update UTMP about System Reboot/Shutdown
systemd-user-sessions.service      loaded active exited  Permit User Sessions
systemd-vconsole-setup.service     loaded active exited  Setup Virtual Console
tuned.service                      loaded active running Dynamic System Tuning Daemon

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

32 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

今回は、firewalldとpostfixを無効化する。firewalld無効化の例を以下に示す。

[root@centos71 ~]# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
   Active: active (running) since 金 2015-05-29 10:56:27 JST; 3min 39s ago
 Main PID: 542 (firewalld)
   CGroup: /system.slice/firewalld.service
           mq542 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

 529 10:56:27 centos71 systemd[1]: Started firewalld - dynamic firewall daemon.
[root@centos71 ~]# systemctl stop firewalld
[root@centos71 ~]# systemctl disable firewalld
rm '/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service'
rm '/etc/systemd/system/basic.target.wants/firewalld.service'
[root@centos71 ~]# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled)
   Active: inactive (dead)

 529 10:56:22 centos71 systemd[1]: Starting firewalld - dynamic firewall daemon...
 529 10:56:27 centos71 systemd[1]: Started firewalld - dynamic firewall daemon.
 529 11:00:15 centos71 systemd[1]: Stopping firewalld - dynamic firewall daemon...
 529 11:00:15 centos71 systemd[1]: Stopped firewalld - dynamic firewall daemon.
b) SELinuxの無効化

開発時は不要なため、SELinuxを無効化しておく。

[root@centos71 ~]# vi /etc/selinux/config

編集内容は以下の通り。

[root@centos71 ~]# diff selinux_config_before selinux_config_after
< SELINUX=enforcing
---
> SELINUX=disabled
c) sudo設定

vagrantユーザがパスワード無しでsudo実行可能とする。

インストール時にvagrantユーザを作成した場合、規定でvagrantグループに所属しているため、以下ではvagrantグループに対して設定を行っている。

[root@centos71 ~]# visudo

編集内容は以下の通り。

[root@centos71 ~]# diff sudoers_before sudoers_after
56c56
< Defaults    requiretty
---
> #Defaults    requiretty
108a109
> %vagrant      ALL=(ALL)       NOPASSWD: ALL
d) SSH設定

vagrantユーザにてSSHする際に使用するInsecure Private Keyを登録しておく。

[root@centos71 ~]# mkdir /home/vagrant/.ssh
[root@centos71 ~]# chmod 700 /home/vagrant/.ssh
[root@centos71 ~]# curl https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub >> /home/vagrant/.ssh/authorized_keys
[root@centos71 ~]# chmod 600 /home/vagrant/.ssh/authorized_keys
[root@centos71 ~]# chown -R vagrant:vagrant /home/vagrant/.ssh

Insecure Private KeyをDLする際は必要に応じてhttps_proxyの設定を行う。

[root@centos71 ~]# export https_proxy=https://<user>:<pass>@<proxyserver>:<port>/
e) 既存パッケージのアップデート

既存パッケージを最新化しておく。

[root@centos71 ~]# yum -y update
f) 追加パッケージのインストール

開発で必要な追加パッケージをインストールする。
下記最後の1行はrubyインストール時に必要となるパッケージ群。

[root@centos71 ~]# yum -y groupupdate "Development Tools"
[root@centos71 ~]# yum -y install man-pages-ja wget vim-enhanced
[root@centos71 ~]# yum -y install gcc zlib-devel openssl-devel sqlite sqlite-devel mysql-devel readline-devel libffi-devel
g) rubyインストール

ruby(最新安定板)をソースコードからインストールする。

[root@centos71 ~]# wget http://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.2.tar.gz
[root@centos71 ~]# tar xzvf ./ruby-2.2.2.tar.gz
[root@centos71 ~]# cd ./ruby-2.2.2
[root@centos71 ~]# ./configure
[root@centos71 ~]# make
[root@centos71 ~]# make install
h) VirtualBox Guest Additionsのインストール

VirtualBoxのメニューから、[デバイス] > [Guest Additions のCDイメージを挿入...]を選択し、以下の手順でインストールする。

[root@centos71 ~]# mkdir /media/cdrom
[root@centos71 ~]# mount -r /dev/cdrom /media/cdrom
[root@centos71 ~]# sh /media/cdrom/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.28 Guest Additions for Linux............
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox non-DKMS kernel modules       [  OK  ]
Building the VirtualBox Guest Additions kernel modules
Building the main Guest Additions module                   [  OK  ]
Building the shared folder support module                  [  OK  ]
Building the OpenGL support module                         [  OK  ]
Doing non-kernel setup of the Guest Additions              [  OK  ]
Starting the VirtualBox Guest Additions                    [  OK  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.

[root@centos71 ~]# umount /media/cdrom
i) udevルールの削除

OS起動時にネットワークデバイスのエラーが発生するのを防ぐため、以下のudevルールを削除する。

[root@centos71 ~]# rm /etc/udev/rules.d/70-persistent-ipoib.rules
j) GRUB設定

CentOS7起動時に"Fast TSC calibration failed"エラーが表示されるのを防止するため、GRUB設定を行う。*12

[root@centos71 ~]# vi /etc/default/grub

編集内容は以下の通り。

[root@centos71 ~]# diff grub_before grub_after
5c5
< GRUB_CMDLINE_LINUX="rd.lvm.lv=centos/root rd.lvm.lv=centos/swap crashkernel=auto rhgb quiet"
---
> GRUB_CMDLINE_LINUX="rd.lvm.lv=centos/root rd.lvm.lv=centos/swap crashkernel=auto rhgb quiet clocksource=tsc"
6a7
> GRUB_CMDLINE_LINUX="clocksource=tsc"
k) yum cleanの実施とシャットダウン

OS設定の最後にyum cleanを実行し、シャットダウンする。

(6) Base Box作成
a) ポートフォワーディング設定削除

事前に設定したポートフォワーディング設定を削除する。

b) Base Box作成

コマンドプロンプトから、下記の手順でBase Boxを作成及び登録する。

C:\tmp> vagrant package --base centos71 package.box
C:\tmp> vagrant box add --name centos7.1 package.box
==> box: Adding box 'centos7.1' (v0) for provider:
    box: Downloading: file://C:/tmp/package.box
    box: Progress: 100% (Rate: 75.3M/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'centos7.1' (v0) for 'virtualbox'!

C:\tmp> vagrant box list
centos7.1 (virtualbox, 0)

トラブルシュート

作成したBase Boxから新規VMを作成して起動したら、起動シーケンスで以下のエラーが表示された。

(略)

==> default: Machine booted and ready!
GuestAdditions seems to be installed (4.3.28) correctly, but not running.
Starting vboxadd (via systemctl):  Job for vboxadd.service failed. See 'systemct
l status vboxadd.service' and 'journalctl -xn' for details.
[??????]
Removing existing VirtualBox non-DKMS kernel modules[  OK  ]
Building the VirtualBox Guest Additions kernel modules
The headers for the current running kernel were not found. If the following
module compilation fails then this could be the reason.
The missing package can be probably installed with
yum install kernel-devel-3.10.0-229.el7.x86_64

Building the main Guest Additions module[??????]
(Look at /var/log/vboxadd-install.log to find out what went wrong)
Doing non-kernel setup of the Guest Additions[  OK  ]
Restarting VM to apply changes...

GuestAdditionsがnot runningなので、vboxaddサービスの起動に失敗している。その後、予め導入しておいたVagrantプラグイン"vagrant-vbguest"がGuestAdditionsの再構成を試みているものの、失敗している。

そこで、"/var/log/vboxadd-install.log"を確認してみる。

(略)

/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  中止.
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.

なるほど、Linux kernelのソースコードが見つからないと。原因を探ってみると、"uname -r"の結果と、"/usr/src/kernels"配下のディレクトリ名が異なっているため、上記のエラーが出ているらしい。

[root@centos01 ~]# uname -r
3.10.0-229.el7.x86_64
[root@centos01 ~]#
[root@centos01 ~]# ls -l /usr/src/kernels/
合計 4
drwxr-xr-x. 22 root root 4096  5月 28 14:50 3.10.0-229.4.2.el7.x86_64

"3.10.0-229"までは同一だが、kernelソースコードディレクトリ名ではその後に".4.2"とある。これが原因。

なぜこういうことになっているかよくわからないが、パッチレベルまで一致しているし、とにかくVirtualBox的には"uname -r"の結果と同一名のディレクトリが存在していないといけないようなので、シンボリックリンクを貼っておく。その上で、"vboxadd setup"を実行。

[root@centos01 ~]# ln -s /usr/src/kernels/3.10.0-229.4.2.el7.x86_64 /usr/src/kernels/3.10.0-229.el7.x86_64
[root@centos01 ~]# /etc/init.d/vboxadd setup
Removing existing VirtualBox non-DKMS kernel modules       [  OK  ]
Building the VirtualBox Guest Additions kernel modules
The headers for the current running kernel were not found. If the following
module compilation fails then this could be the reason.
The missing package can be probably installed with
yum install kernel-devel-3.10.0-229.el7.x86_64

Building the main Guest Additions module                   [  OK  ]
Building the shared folder support module                  [  OK  ]
Building the OpenGL support module                         [  OK  ]
Doing non-kernel setup of the Guest Additions              [  OK  ]
Starting the VirtualBox Guest Additions                    [  OK  ]

エラーメッセージは出力されているものの、無事正常終了。ちなみに、"kernel-devel-3.10.0-229.el7.x86_64"はインストール済。"vagrant reload"でVMを再起動すると、正常にVMが起動した。

(略)

GuestAdditions 4.3.28 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => C:/vm/centos01

*1:VirtualBox上でVMを識別する際に使用される名称。OSのホスト名ではない。

*2:VM作成ウィザードではコア数を指定できない(1固定)。VM作成後に設定画面にてコア数を変更可能。

*3:最低サイズ以上で任意の値を指定。

*4:最低サイズ以上で任意のサイズを指定

*5:要件に合わせてファイルタイプを選択

*6:ようこそ画面で日本語を選択したため、自動的に設定される。

*7:一旦最小構成でインストールし、開発ツール等の必要パッケージはインストール後に導入する。

*8:要件に応じてパーティション構成を手動設定する。

*9:ここで有効化しない場合、インストール後にVirtualBoxのコンソールからログインし、有効化する。また、IPv4アドレスはdhcpによる取得(規定)とする。

*10:Vagrant公式ドキュメントの指示に従う。

*11:Vagrant公式ドキュメントの指示に従う。このタイミングでは作成せず、インストール後に作成しても良い。

*12:ぷにおちゃん ~ CentOS 7起動時のTSC calibration failedを消す方法

Powershellで実行中のプロセスを取得・分析する

Windows上で実行中のプロセスを取得・分析する方法について。

1. 動作確認環境

2. プロセス一覧を取得する

単純に実行中のプロセス一覧を取得する場合、以下の2つの方法があります。

  1. "Get-Process"コマンドレットで取得
  2. WMI(Win32_Process)で取得

上記2つの結果はそれぞれ異なるため、用途に合わせて使い分ける必要があります。
具体的に結果がどう異なるかは以下に記載します。

(1)"Get-Process"でプロセス一覧を取得した場合

以下の通り、Get-Processの返却値は"System.Diagnostics.Process"型になります。
メソッドやプロパティの詳細はMSDNを参照してください。
Process クラス (System.Diagnostics)

PS > Get-Process | Get-Member | ft -Wrap


   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize
PM                         AliasProperty  PM = PagedMemorySize
VM                         AliasProperty  VM = VirtualMemorySize
WS                         AliasProperty  WS = WorkingSet
Disposed                   Event          System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Object,
                                          System.Diagnostics.DataReceivedEventArgs)
Exited                     Event          System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Object,
                                           System.Diagnostics.DataReceivedEventArgs)
BeginErrorReadLine         Method         void BeginErrorReadLine()
BeginOutputReadLine        Method         void BeginOutputReadLine()
CancelErrorRead            Method         void CancelErrorRead()
CancelOutputRead           Method         void CancelOutputRead()
Close                      Method         void Close()
CloseMainWindow            Method         bool CloseMainWindow()
CreateObjRef               Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                    Method         void Dispose(), void IDisposable.Dispose()
Equals                     Method         bool Equals(System.Object obj)
GetHashCode                Method         int GetHashCode()
GetLifetimeService         Method         System.Object GetLifetimeService()
GetType                    Method         type GetType()
InitializeLifetimeService  Method         System.Object InitializeLifetimeService()
Kill                       Method         void Kill()
Refresh                    Method         void Refresh()
Start                      Method         bool Start()
ToString                   Method         string ToString()
WaitForExit                Method         bool WaitForExit(int milliseconds), void WaitForExit()
WaitForInputIdle           Method         bool WaitForInputIdle(int milliseconds), bool WaitForInputIdle()
__NounName                 NoteProperty   System.String __NounName=Process
BasePriority               Property       int BasePriority {get;}
Container                  Property       System.ComponentModel.IContainer Container {get;}
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;set;}
ExitCode                   Property       int ExitCode {get;}
ExitTime                   Property       datetime ExitTime {get;}
Handle                     Property       System.IntPtr Handle {get;}
HandleCount                Property       int HandleCount {get;}
HasExited                  Property       bool HasExited {get;}
Id                         Property       int Id {get;}
MachineName                Property       string MachineName {get;}
MainModule                 Property       System.Diagnostics.ProcessModule MainModule {get;}
MainWindowHandle           Property       System.IntPtr MainWindowHandle {get;}
MainWindowTitle            Property       string MainWindowTitle {get;}
MaxWorkingSet              Property       System.IntPtr MaxWorkingSet {get;set;}
MinWorkingSet              Property       System.IntPtr MinWorkingSet {get;set;}
Modules                    Property       System.Diagnostics.ProcessModuleCollection Modules {get;}
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize {get;}
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize64 {get;}
PagedMemorySize            Property       int PagedMemorySize {get;}
PagedMemorySize64          Property       long PagedMemorySize64 {get;}
PagedSystemMemorySize      Property       int PagedSystemMemorySize {get;}
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64 {get;}
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;}
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {get;}
PeakVirtualMemorySize      Property       int PeakVirtualMemorySize {get;}
PeakVirtualMemorySize64    Property       long PeakVirtualMemorySize64 {get;}
PeakWorkingSet             Property       int PeakWorkingSet {get;}
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {get;set;}
PriorityClass              Property       System.Diagnostics.ProcessPriorityClass PriorityClass {get;set;}
PrivateMemorySize          Property       int PrivateMemorySize {get;}
PrivateMemorySize64        Property       long PrivateMemorySize64 {get;}
PrivilegedProcessorTime    Property       timespan PrivilegedProcessorTime {get;}
ProcessName                Property       string ProcessName {get;}
ProcessorAffinity          Property       System.IntPtr ProcessorAffinity {get;set;}
Responding                 Property       bool Responding {get;}
SessionId                  Property       int SessionId {get;}
Site                       Property       System.ComponentModel.ISite Site {get;set;}
StandardError              Property       System.IO.StreamReader StandardError {get;}
StandardInput              Property       System.IO.StreamWriter StandardInput {get;}
StandardOutput             Property       System.IO.StreamReader StandardOutput {get;}
StartInfo                  Property       System.Diagnostics.ProcessStartInfo StartInfo {get;set;}
StartTime                  Property       datetime StartTime {get;}
SynchronizingObject        Property       System.ComponentModel.ISynchronizeInvoke SynchronizingObject {get;set;}
Threads                    Property       System.Diagnostics.ProcessThreadCollection Threads {get;}
TotalProcessorTime         Property       timespan TotalProcessorTime {get;}
UserProcessorTime          Property       timespan UserProcessorTime {get;}
VirtualMemorySize          Property       int VirtualMemorySize {get;}
VirtualMemorySize64        Property       long VirtualMemorySize64 {get;}
WorkingSet                 Property       int WorkingSet {get;}
WorkingSet64               Property       long WorkingSet64 {get;}
PSConfiguration            PropertySet    PSConfiguration {Name, Id, PriorityClass, FileVersion}
PSResources                PropertySet    PSResources {Name, Id, Handlecount, WorkingSet, NonPagedMemorySize, PagedMemo
                                          rySize, PrivateMemorySize, VirtualMemorySize, Threads.Count, TotalProcessorTi
                                          me}
Company                    ScriptProperty System.Object Company {get=$this.Mainmodule.FileVersionInfo.CompanyName;}
CPU                        ScriptProperty System.Object CPU {get=$this.TotalProcessorTime.TotalSeconds;}
Description                ScriptProperty System.Object Description {get=$this.Mainmodule.FileVersionInfo.FileDescripti
                                          on;}
FileVersion                ScriptProperty System.Object FileVersion {get=$this.Mainmodule.FileVersionInfo.FileVersion;}
Path                       ScriptProperty System.Object Path {get=$this.Mainmodule.FileName;}
Product                    ScriptProperty System.Object Product {get=$this.Mainmodule.FileVersionInfo.ProductName;}
ProductVersion             ScriptProperty System.Object ProductVersion {get=$this.Mainmodule.FileVersionInfo.ProductVer
                                          sion;}
(2)WMI(Win32_Process)でプロセス一覧を取得した場合

以下の通り、WMI(Win32_Process)の返却値は"System.Management.ManagementObject#root\cimv2\Win32_Process"型になります。
メソッドやプロパティの詳細はMSDNを参照してください。
Win32_Process class (Windows)

PS > Get-WmiObject Win32_Process | Get-Member


   TypeName: System.Management.ManagementObject#root\cimv2\Win32_Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
ProcessName                AliasProperty  ProcessName = Name
PSComputerName             AliasProperty  PSComputerName = __SERVER
VM                         AliasProperty  VM = VirtualSize
WS                         AliasProperty  WS = WorkingSetSize
AttachDebugger             Method         System.Management.ManagementBaseObject AttachDebugger()
GetOwner                   Method         System.Management.ManagementBaseObject GetOwner()
GetOwnerSid                Method         System.Management.ManagementBaseObject GetOwnerSid()
SetPriority                Method         System.Management.ManagementBaseObject SetPriority(System.Int32 Priority)
Terminate                  Method         System.Management.ManagementBaseObject Terminate(System.UInt32 Reason)
Caption                    Property       string Caption {get;set;}
CommandLine                Property       string CommandLine {get;set;}
CreationClassName          Property       string CreationClassName {get;set;}
CreationDate               Property       string CreationDate {get;set;}
CSCreationClassName        Property       string CSCreationClassName {get;set;}
CSName                     Property       string CSName {get;set;}
Description                Property       string Description {get;set;}
ExecutablePath             Property       string ExecutablePath {get;set;}
ExecutionState             Property       uint16 ExecutionState {get;set;}
Handle                     Property       string Handle {get;set;}
HandleCount                Property       uint32 HandleCount {get;set;}
InstallDate                Property       string InstallDate {get;set;}
KernelModeTime             Property       uint64 KernelModeTime {get;set;}
MaximumWorkingSetSize      Property       uint32 MaximumWorkingSetSize {get;set;}
MinimumWorkingSetSize      Property       uint32 MinimumWorkingSetSize {get;set;}
Name                       Property       string Name {get;set;}
OSCreationClassName        Property       string OSCreationClassName {get;set;}
OSName                     Property       string OSName {get;set;}
OtherOperationCount        Property       uint64 OtherOperationCount {get;set;}
OtherTransferCount         Property       uint64 OtherTransferCount {get;set;}
PageFaults                 Property       uint32 PageFaults {get;set;}
PageFileUsage              Property       uint32 PageFileUsage {get;set;}
ParentProcessId            Property       uint32 ParentProcessId {get;set;}
PeakPageFileUsage          Property       uint32 PeakPageFileUsage {get;set;}
PeakVirtualSize            Property       uint64 PeakVirtualSize {get;set;}
PeakWorkingSetSize         Property       uint32 PeakWorkingSetSize {get;set;}
Priority                   Property       uint32 Priority {get;set;}
PrivatePageCount           Property       uint64 PrivatePageCount {get;set;}
ProcessId                  Property       uint32 ProcessId {get;set;}
QuotaNonPagedPoolUsage     Property       uint32 QuotaNonPagedPoolUsage {get;set;}
QuotaPagedPoolUsage        Property       uint32 QuotaPagedPoolUsage {get;set;}
QuotaPeakNonPagedPoolUsage Property       uint32 QuotaPeakNonPagedPoolUsage {get;set;}
QuotaPeakPagedPoolUsage    Property       uint32 QuotaPeakPagedPoolUsage {get;set;}
ReadOperationCount         Property       uint64 ReadOperationCount {get;set;}
ReadTransferCount          Property       uint64 ReadTransferCount {get;set;}
SessionId                  Property       uint32 SessionId {get;set;}
Status                     Property       string Status {get;set;}
TerminationDate            Property       string TerminationDate {get;set;}
ThreadCount                Property       uint32 ThreadCount {get;set;}
UserModeTime               Property       uint64 UserModeTime {get;set;}
VirtualSize                Property       uint64 VirtualSize {get;set;}
WindowsVersion             Property       string WindowsVersion {get;set;}
WorkingSetSize             Property       uint64 WorkingSetSize {get;set;}
WriteOperationCount        Property       uint64 WriteOperationCount {get;set;}
WriteTransferCount         Property       uint64 WriteTransferCount {get;set;}
__CLASS                    Property       string __CLASS {get;set;}
__DERIVATION               Property       string[] __DERIVATION {get;set;}
__DYNASTY                  Property       string __DYNASTY {get;set;}
__GENUS                    Property       int __GENUS {get;set;}
__NAMESPACE                Property       string __NAMESPACE {get;set;}
__PATH                     Property       string __PATH {get;set;}
__PROPERTY_COUNT           Property       int __PROPERTY_COUNT {get;set;}
__RELPATH                  Property       string __RELPATH {get;set;}
__SERVER                   Property       string __SERVER {get;set;}
__SUPERCLASS               Property       string __SUPERCLASS {get;set;}
ConvertFromDateTime        ScriptMethod   System.Object ConvertFromDateTime();
ConvertToDateTime          ScriptMethod   System.Object ConvertToDateTime();
Path                       ScriptProperty System.Object Path {get=$this.ExecutablePath;}

3. プロセスを実行中のユーザ一覧を取得する

現在プロセスを実行しているユーザの一覧を取得したい場合は、WMI(Win32_Process)を用いて、以下の様に実現可能です。

PS > Get-WmiObject Win32_Process | Group-Object {$_.getowner().Domain},{$_.getowner().User} | Sort-Object Count -Descending | ft -Wrap

Count Name                      Group
----- ----                      -----
   20 NT AUTHORITY, SYSTEM      {\\testserver\root\cimv2:Win32_Process.Handle="252", \\testserver\root\cimv2:Win32_Process.Handle
                                ="352", \\testserver\root\cimv2:Win32_Process.Handle="416", \\testserver\root\cimv2:Win32_Process
                                .Handle="424"...}
   10 CONTOSO, Administrator    {\\testserver\root\cimv2:Win32_Process.Handle="2476", \\testserver\root\cimv2:Win32_Process.Handl
                                e="572", \\testserver\root\cimv2:Win32_Process.Handle="1048", \\testserver\root\cimv2:Win32_Proce
                                ss.Handle="2996"...}
    5 NT AUTHORITY, NETWORK SER {\\testserver\root\cimv2:Win32_Process.Handle="692", \\testserver\root\cimv2:Win32_Process.Handle
      VICE                      ="60", \\testserver\root\cimv2:Win32_Process.Handle="1916", \\testserver\root\cimv2:Win32_Process
                                .Handle="2744"...}
    3 NT AUTHORITY, LOCAL SERVI {\\testserver\root\cimv2:Win32_Process.Handle="876", \\testserver\root\cimv2:Win32_Process.Handle
      CE                        ="952", \\testserver\root\cimv2:Win32_Process.Handle="588"}
    2                           {\\testserver\root\cimv2:Win32_Process.Handle="0", \\testserver\root\cimv2:Win32_Process.Handle="
                                4"}
    1 Window Manager, DWM-1     {\\testserver\root\cimv2:Win32_Process.Handle="784"}


Win32_Processクラスでは、"getowner"メソッドを用いて、各プロセス実行ユーザのドメイン名とユーザ名を取得可能です。

上記の例では、"Group-Object"コマンドレットにて"ドメイン名($_.getowner().Domain)+ユーザ名($_.getowner().User)"を軸にグループ化し、更に"Sort-Object"コマンドレットで実行プロセス数が多い順に降順で表示するようにしています。

その他

他にも、メモリ使用量順にプロセスを並べ替えて表示するなど、様々な切り口で情報取得・分析が可能です。また、分析結果に応じて、特定プロセスの優先度を上げ下げすることもできます。

Powershellスクリプトにてログローテーションを行う

Powershellスクリプトにてログローテーションを行う方法について。

1. 動作確認環境

2. やりたいこと

  • copytruncate方式でログローテーションを行いたい
  • 指定した保存期間を経過したログファイルを削除したい

3. 実装例

ログローテーションに際して色々と考慮点はあるが、今回は可能な限りシンプルに実装してみた。

処理を加えることで、特定サイズに達した場合にローテーション、などといった制御も可能。

(1) ログローテーション

引数に対象ログファイルパスを渡すと、ログファイルが存在し、かつサイズが0でない場合、copytruncate方式でローテーションを行う。*1ローテーション後のログファイル名には接尾語として".yyyyMMddHHmmss"(ローテーション日時)が付与される。

Function Rotate-Log([string]$log)
{
    $today = Get-Date
    if (Test-Path($log)) {
        $item = Get-Item $log
        if ($item.Length -ne 0) {
            $old = $log + "." + $today.ToString("yyyyMMddHHmmss")
            Copy-Item $log $old -Force
            $null | Out-File $log -Encoding default -Force
        } 
    }
}
(2) ログ削除

引数にログ保管先ディレクトリパスとログ保管日数を渡すと、保管日数を超過したログを削除する。

Function Delete-Log([string]$log_dir, [int]$saving_days)
{
    $today = Get-Date
    if (Test-Path($log_dir)) {
        $logs = Get-ChildItem $log_dir
        foreach ($log in $logs) {
            if ($log.lastWriteTime -lt $today.AddDays(-$saving_days)) {
                Remove-Item $log.FullName -Force
            }
        }
    }
}

*1:copytruncate方式の一般的な留意事項として、copy処理とtruncate処理の間に出力されたログは保存されないため、常時大量のログが書込まれるファイルに対しては適用しないようにする

Powershellスクリプトにてインターネットからファイルをダウンロードする(プロキシ対応)

Powershellスクリプトでインターネットからファイルをダウンロードする方法について。

1. 動作確認環境

2. やりたいこと

  • インターネットから任意のファイルをダウンロードしたい
  • プロキシサーバ(認証有り)を利用したい
  • ファイル名や格納先は都度指定したい

3. 処理方式

.Net Frameworkの"System.Net.WebClient"クラスを用いて実装する。
具体的には下記の3つのクラスを使用する。

WebClient クラス (System.Net)
WebProxy クラス (System.Net)
NetworkCredential クラス (System.Net)

4. 実装例

以下の様に実装可能。(例外処理は省略)

プロキシサーバが存在しない場合、存在するが認証が不要な場合などはそれぞれ該当処理を削ればOK。

# DL対象ファイルのURL
$target_url = "http://www.hoge.co.jp/test.txt"
# ローカルでの保存先
$file_path = "C:\tmp\test.txt"
# プロキシサーバ
$proxy_url = "http://proxy.hoge.co.jp:8080"
# プロキシ認証アカウント
$user = "testuser"
$pass = "testpass"

# WebClient設定
$web_client = New-Object System.Net.WebClient
$proxy_server = New-Object System.Net.WebProxy($proxy_url, $true)
$credential = New-Object System.Net.NetworkCredential($user, $pass)
$proxy_server.Credentials = $credential
$web_client.Proxy = $proxy_server

# ファイルダウンロード
$web_client.DownloadFile($target_url, $file_path)