page_adsence

2015年2月12日木曜日

MacからAWSで作成したWindows8のマシンにリモートデスクトップで接続出来ない

AWSで作ったWindows8のマシンを手に入れたのですが、Macから直接リモートデスクトップで接続しようとすると、
以下の様なエラーが出てきて接続出来なかった。

「接続先のコンピューターのIDを確認できません。」

そのせいで、MacbookPro→Parallels上のWindows7→Windows8見たいな感じで接続しないと使えなかった。
Macから直接使えないと意味ない(Macbook Airから主に使いたいため)と思い、調べてみたら案外あっさり見つかった。

AWSに作ったWindowsマシンに接続する為に使っていたアプリは、

「Microsoft Remote Desktop Connection Client for Mac」

どうやらこれがいけないというか、このアプリだとWindows8側で設定を諸々変更する必要があるらしい。
ちょっと面倒だったのですが、何個か別の記事を読んでみると、どうやら別のアプリを落とすだけでいけるらしい事がわかった。
そのアプリはApple Storeで公開されている「Microsoft Remote Desktop」を使えば問題ない。

早速試してみた。
Apple Storeにいって「Microsoft Remote Desktop」で検索すると、一発で出てきた。
赤いアイコンで目立つ感じ。

早速インストールして接続。
全部英語ですが、そんなに難しい単語は使われていないので、特に問題ないと思います。
※入力した内容を保存するボタンが無いので、ちょっと不安な気持ちになりますが、閉じるボタンを押したタイミングで勝手に保存されるようです。


Windows8側の設定を変える方法として、以下の様な方法があります。
新しくアプリ落とす方が面倒だという方はこちらの方法を試してみてください。
設定を変更することで接続出来ることは確認しました。

1.検索で「gpedit.msc」を入力。
2.下記のようにツリーを辿って、セキュリティを選択。
ローカルコンピューターポリシー
 │
 └ コンピューターの構成
    │
    └ 管理者用テンプレート
      │
      └ Windowsコンポーネント
         │
         └ リモート デスクトップ サービス
           │
           └ リモート デスクトップ セッションホスト
               │
              └ セキュリティ ← ここを選択


「リモート(RDP)接続に特定のセキュリティレイヤーの使用を必要とする」を有効にし、セキュリティレイヤーをRDPに変更する

「リモート接続にネットワークレベル認証を使用したユーザー認証を必要とする」を無効にする

以上の設定が終わったら再起動して、再接続してみるとつながった。

AWSアカウントを作って、Windowsマシンを手に入れる

1年間無料で使えるので、AWSでどこからでも使えるWindowsマシンを手に入れようかと思い、アカウントを作ってみた。

登録フローは公式サイトに書かれているので、そちらを参考に。

で、Windowsマシンを作ってみる。
まず、以下のサイトにアクセス。

http://aws.amazon.com/jp/
コンソールへサインインボタンをクリック

Emailアドレスとパスワードを入力してログイン

ログインが完了すると、マネージメントコンソールという画面が開く。
画面左上のEC2をクリック

Launch Instanceボタンをクリック

作りたいOSを選ぶ
但し、無料で使えるOSの種類は限られているので、「Free tier only」にチェックを付けて無料で使えるやつのみをリスト上に表示させるとよい。

インスタンスタイプを選ぶ
無料のものは一番上のもののみなので、自動的にこれを選ぶ事になる。

作成するインスタンスの詳細を選択する。
基本的には赤線で囲ってある部分を両方チェックしておく。

ストレージのサイズを決める
特に問題がなければそのままにしておく。
30GBまでは無料で使えるので、30GBにした。

インスタンスの名前を決める

セキュリティグループを選ぶ。
Windowsマシンを選択した場合、自動でここがRDPになっているので、基本的には何もしなくてもOK。

作成されるマシンの内容を確認し、起動ボタンを押す。

鍵を作成してダウンロード後、インスタンスを起動させる。

これでとりあえずマシンの作成は完了。
次に作成したマシンにログインするまでの方法。
マネージメントコンソールTOPから、Instancesをクリック

起動させたいマシンを選んで、Connectボタンを押す。(ここからVMに繋がるわけではない。)

ログインパスワードを取得する。

マシンを作った時にダウンロードした鍵ファイルをアップロードして、パスワードを抽出する。

リモートデスクトップファイルをダウンロードして、
ユーザー名、抽出されたパスワードやIPが表示されているので、これを元にリモートデスクトップで接続する。

※MacからWindows8系にリモートデスクトップ接続する場合に接続できない事があるが、それは別の記事で。
結論としては、Apple Storeに公開されているMicrosoft Remote Desktopを使えば問題なく接続出来るということです。

2015年2月5日木曜日

AnsibleでSELinuxをOFFにする方法

AnsibleでSELinuxをOFFにするための方法を調べてみた。

ググってみると下記の記事が見つかった。

Ansibleの事例とちょっとしたTips

この部分を見ながらやってみたが、どうもうまく行かない。
ymlの記述を全く同じにしてみてもうまくいかない。

-bash: sudo: コマンドが見つかりません

なんで記事中ではうまくいってるのに、自分の環境じゃダメなのかと思ったのですが、
原因は自分の環境がCygwin環境だからでした。
なので、下記のように修正してやってみる。

---
- name: Install libselinux-python
  yum: name=libselinux-python state=present

- name: Check status of selinux
  shell: getenforce

- name: Permissive selinux
  selinux: policy=targeted state=permissive

- name: reboot after change selinux
  shell: sleep 2s && /sbin/reboot &

- name: wait for the server to go down (reboot)
  local_action: wait_for host={{ inventory_hostname }} port=22 state=stopped
  sudo: no

- name: wait for the server to come up
  local_action: wait_for host={{ inventory_hostname }} port=22 delay=30
  sudo: no

- name: Check status of selinux
  shell: getenforce

再起動自体は行われたが、後続が続かない。
何をやってもダメで、他の方法を探してみた。

で、見つけた記事がこれ。

Ansible で Vagrant ホストを再起動する

「wait_for で待つ方法だと ansible-playbook が再起動以降でコケたり共有フォルダーがマウントされなくなったりとダメ。」
という記述を見つけて愕然。
今まで色々と試行錯誤してみたけど、無駄だったことが発覚。
とりあえず、この方法で出来るのかを検証してみることにした。

$ vi selinux-off.yml

---
- name: Install libselinux-python
  yum: name=libselinux-python state=installed

- name: disable SELinux
  sudo: yes
  selinux: state=disabled

- include: reboot.yml

$ vi reboot.yml

---
- name: reboot vagrant host
  command: 'vagrant reload'
  delegate_to: 127.0.0.1
  changed_when: false

この様な感じでファイルを用意して試してみたら、見事成功。
ということで、この方法を採用してplaybookを作っていきたいと思います。

2015年2月3日火曜日

vagrantコマンドでよく使うもの

vagrantのコマンドでよく使うものを中心にメモしておく。
vagrant box add
boxの追加。
boxを追加しておくと、すでにあるLinuxイメージをローカルにダウンロードし、登録しておくイメージ。
追加されたboxは初期化することですぐに利用出来る様になる。
boxのダウンロードはある程度時間が掛かる。
boxファイルは色々な所に落ちているが、下記の様にまとめサイト的なものもある。

http://www.vagrantbox.es/

$ vagrant box add [box-name] [box-url]

例)
$ vagrant box add centos6.4 https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box

vagrant box list
すでに追加されているboxの一覧を確認する。
今までbox addコマンドで追加したboxの一覧が確認出来る。

$ vagrant box list

例)
$ vagrant box list
centos6.4       (virtualbox, 0)
centos6.4-30gb  (virtualbox, 0)
centos6.4-nomal (virtualbox, 0)
centos6.5       (virtualbox, 0)
centos7.0       (virtualbox, 0)
test            (virtualbox, 0)

vagrant box remove
すでに追加してあるboxファイルを削除する。

$ vagrant box remove [box name]

例)
$ vagrant box remove test
Removing box 'test' (v0) with provider 'virtualbox'...

$ vagrant box list
centos6.4       (virtualbox, 0)
centos6.4-30gb  (virtualbox, 0)
centos6.4-nomal (virtualbox, 0)
centos6.5       (virtualbox, 0)
centos7.0       (virtualbox, 0)

vagrant init
boxを初期化する。
これをする事でVagrantfileが作成され、VMの細かい設定が出来るようになる。

$ vagrant init [box-name]

例)
$ vagrant init centos6.4
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

vagrant up
VMを起動する。Vagrantfileに書かれた内容に基づいたVMが作成され、起動する。

$ vagrant up

例)
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos6.4'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: test-vm
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => C:/cygwin64/home/username/VirtualBoxMachines/test-vm

vagrant halt
VMを停止する。

$ vagrant halt
==> default: Attempting graceful shutdown of VM...

vagrant suspend
VMを一時停止する

$ vagrant suspend
==> default: Saving VM state and suspending execution...

vagrant resume
一時停止されているVMを再開させる

$ vagrant resume
==> default: Resuming suspended VM...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
==> default: Machine booted and ready!

vagrant status
VMのステータスを確認出来る

$ vagrant status
Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.

vagrant ssh
vagrant経由で起動させたVMにsshでログインする

$ vagrant ssh
Last login: Tue Feb  3 10:49:53 2015 from 192.168.33.100
[vagrant@vagrant ~]$

vagrant global-status
vagrant全体の状況が確認出来る。1度起動したVMはIDが振られる。
このIDを指定することで、対象のVMディレクトリ配下に移動しなくても起動出来る。

$ vagrant global-status
id       name    provider   state    directory
--------------------------------------------------------------------------------------------------
6dd4f19  default virtualbox saved    C:/cygwin64/home/user-name/vbox-cent64
b735130  default virtualbox poweroff C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1

The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date. To interact with any of the machines, you can go to
that directory and run Vagrant, or you can use the ID directly
with Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"

vagrant global-status --prune
global-statusで確認した時、本来削除したはずのVMの管理情報が残っている場合がある。
そういった不要情報を綺麗にした状態にするためのオプションが「prune」

■通常のコマンドでステータス確認
$ vagrant global-status
id       name    provider   state    directory
------------------------------------------------------------------------------------------------------
17033d9  default virtualbox poweroff C:/cygwin64/home/user-name/virtualBox                            ← 削除済みなのに表示されている
754da86  default virtualbox poweroff C:/cygwin64/home/user-name/virtualBox_CentOS6.5                  ← 削除済みなのに表示されている
6dd4f19  default virtualbox poweroff C:/cygwin64/home/user-name/vbox-cent64
e8c4ab5  default virtualbox poweroff C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1-tmp  ← 削除済みなのに表示されている
2de0695  default virtualbox running  C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1

The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date. To interact with any of the machines, you can go to
that directory and run Vagrant, or you can use the ID directly
with Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"

■削除済み情報を綺麗にして表示させる。
$ vagrant global-status --prune
C:/cygwin64/home/user-name/vbox-cent64/Vagrantfile:5: warning: already initialized constant VAGRANTFILE_API_VERSION
C:/cygwin64/home/user-name/virtualBox_CentOS6.5/Vagrantfile:5: warning: previous definition of VAGRANTFILE_API_VERSION was here
C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1/Vagrantfile:5: warning: already initialized constant VAGRANTFILE_API_VERSION
C:/cygwin64/home/user-name/vbox-cent64/Vagrantfile:5: warning: previous definition of VAGRANTFILE_API_VERSION was here
id       name    provider   state    directory
--------------------------------------------------------------------------------------------------
6dd4f19  default virtualbox poweroff C:/cygwin64/home/user-name/vbox-cent64
2de0695  default virtualbox running  C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1

The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date. To interact with any of the machines, you can go to
that directory and run Vagrant, or you can use the ID directly
with Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"
C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1/Vagrantfile:5: warning: already initialized constant VAGRANTFILE_API_VERSION
C:/cygwin64/home/user-name/VirtualBoxMachines/vbox-cent64-1/Vagrantfile:5: warning: previous definition of VAGRANTFILE_API_VERSION was here

vagrant destroy
作成されているVMを削除する。このコマンドを実行することで、VirtualBox上からもマシンが消える。
また、global-statusに出てくるIDを末尾につけることで、該当のVMのディレクトリに移動しなくても削除する事が可能。

$ vagrant destroy

vagrant box repackage
既に追加済みのBoxをカレントディレクトリにpackage.boxファイルとして出力する。

$ vagrant box repackage [provider_name] [version]

providerやversionはvagrant box listコマンドを打つと出てくる
$ vagrant box list
centos6.4       (virtualbox, 0)

この場合、コマンドは下記の様になる。
$ vagrant box repackage virtualbox 0


※下記のURLに綺麗にまとまっている。但しglobal-statusに関しては記載なし。
http://lab.raqda.com/vagrant/cli/

2015年1月30日金曜日

Windwosマシンからsambaへのアクセスでハマった

vagrant + ansibleを使ってVMのセットアップをして、いざ共有ディレクトリにアクセスしたら、アクセス拒否。
原因がいまいちよくわからなかった。
結論から先に言うと、全ての原因はSELinuxだったということ。
playbookにSELinuxをオフにする記述を追加して、設定ファイルを確認。

$ view /etc/selinux/config
SELINUX=disabled

と書かれていたので、安心しきっていたのですが、実際には設定ファイルだけ書き換わっていて再起動されていなかったため、
SELinuxが普通に動いている状態でした。

$ getenforce

や

$ sestatus

で確認した所、ガンガン動いていた。
以下、ハマった事象に関しての詳細。

起こっていた現象

\\サーバのIP

にはアクセス出来る。

\\サーバのIP\public

にもアクセス出来る。

\\サーバのIP\vagrant

にはアクセス出来ない。

sambaの設定色々いじったり、VM側のディレクトリのパーミッション弄ってみたりと色々試しましたが全てダメ。
何がダメなのかわからなかったのですが、こんな記事を教えてもらって試してみた。
VM上で、下記のコマンドを実行したら見れる様になりました。

$ setsebool -P samba_enable_home_dirs on

これで問題なくなったと思っていたら、今度はフォルダとシェルスクリプトだけsamba上で見えていて、ファイルが一切見えないという状態に。
VM上で同じディレクトリを参照すると、特に問題なくファイルもあり、中身も閲覧出来る。
何が原因なんだと思って調べていた所、このサイトが引っかかった。
原因はSELinuxだと書かれていて、SELinuxはオフにしてあるはずなのになぁと思いつつ、確認してみた。

$ getenforce
Enforcing

普通に動いてました・・・。
なので

$ setenforce 0

で一時的に無効化してから、もう一度samba経由で対象のディレクトリにアクセス。
普通に見れました。

2015年1月23日金曜日

MySQLからMongoDBへのデータ移行 まとめ

MySQLからMongoへのデータ移行手法に関してはほぼFixしたのでメモ。
過去記事に関しては以下を参照。

MySQLからMongoDBへのデータ移行
MySQLからMongoDBへのデータ移行 その2
MySQLからMongoDBへのデータ移行 その3

今回移行対象のデータ件数は4000万件程度。
件数としてはビックデータとは言えない微妙な件数・・・。

まず結論から。
  • MySQLからデータを抽出する方法に関してはeオプションを使って、標準出力をファイルにリダイレクトさせる。BSON形式っぽいTSVファイルにして出力する。
  • ちゃんとしたBSON形式に変換する。ダブルクォーテーションのエスケープとか、改行コードをCRLFに変換とか、変な文字列の削除とか諸々必要
  • mongoimportは決して早くない。と思う。(チューニングしてないので。)
  • BSON形式以外のインポートはお勧めできない。型変換に異常に時間がかかるため。
  • mongoimport中に重複があったとしてもエラーメッセージは出てこない。すでに重複するデータがmongoに入っていた場合はエラーが出る。

mongoimportの速度に関して

これに関してはあまり書くことはないが、とりあえず4000万件のデータを入れるのに7.5時間位掛かりました。
2.1系から2.6.5にバージョンアップしたら倍位遅くなりました。原因はまだ不明です。
上の時間はバージョンアップ後の時間です。
ちなみにサーバ構成はこんな感じです。
mongos×3台、mongod×6台(うちマスター3台、スレーブ3台)

mongoimportのファイル形式に関して

結果的にはファイル形式に関してはBSON形式一択でした。
CSVやTSV形式だと、データ型を定義することが出来ないため、
純粋な数値以外は全てテキスト型になってしまうので、日付のデータやNULLに関しては書き換えが必要になる。
データ量が多くなるとその書き換えに非常に時間がかかる。

mongoimportのエラーに関して

これに関しては色々調べたんですけど、結局良くわからず・・・。
エラーが出たらインポート止めるっていうオプションもあるらしいのですが、そのオプションをつけても重複エラーに関しては止まらないらしいです。

MySQLからMongoDBへのデータ移行 その3

前回MySQLの標準をファイルに出力する方法を採っていたが、
これより更に楽になるというか、処理が終わったかどうか分かるようになるやり方があったので紹介する。

mysql --quick -u root --password=password -h localhost mysql_databasename -e "SET NAMES utf8;" > "output.tsv"

このような記述で処理を実行すると、前回同様のメリットを得られる上に、デメリットだった処理の終わりが分かりづらいということも解消される。

ちなみに、「--quick」というオプションは出力結果をメモリ上に溜めずに、どんどんファイルに書き出す様にするためのオプション。
でかいデータを抽出する場合は、メモリ不足で処理が途中で終わってしまうことがあるので、このオプションをつけた。

「-e」オプションはMySQLにログイン後に実行するSQLを書くことが出来る。
ここに必要なSQLを書いておき、実行結果をファイルに出力することが可能になる。
セミコロン区切りで何個もSQLを記述することも可能なので、下記のような方法も可能。

mysql --quick -u root --password=password -h localhost mysql_databasename -e "SET NAMES utf8;
SELECT * FROM table_name_A;
SELECT * FROM table_name_B;" > "output.tsv"

2014年12月26日金曜日

ログアウト後もコマンドを実行し続ける。または今動いているコマンドを後からログアウトしても実行し続けるようにする。

ログアウトした後も継続してコマンドを実行し続けるためには、nohupコマンドを使う必要がある。
通常はログアウトしたタイミングでkillされてしまうのだが、そのシグナルを無視するようになります。
また、標準出力や標準エラーはファイルに出力されるようになります。

■使ってみる
$ nohup ./test.sh &

test.shをバックグラウンドで実行する。
「test.sh」の標準出力、標準エラー出力に送られたデータはプログラムを実行したディレクトリに「nohup.out」というファイル名で保存される。
もしプログラムを実行したディレクトリに書き込み権限が無ければ「$HOME/nohup.out」に保存される。

■標準出力先を指定する
$ nohup ./test.sh > stdout.log &

「test.sh」の標準出力が「stdout.log」になる。標準エラー出力は「nohup.out」で保存先は先ほどと同様にプログラムを実行したディレクトリか、$HOME配下に作られる。

■標準エラー出力先を指定する
$ nohup ./test.sh > stdout.log 2 > stderr.log &

「test.sh」の標準出力が「stdout.log」になる。標準エラー出力は「stderr.log」です。


nohupコマンドで実行する前に普通にコマンドを打ってしまった場合、 または思った以上に時間が掛かってしまってもう帰らないと行けなくなってしまった時の対応方法。


1.処理中にCtrl + zで一旦閉じる

2.バックグラウンドにする
$ bg

3.SIGHUBが送られないようにする
$ disown %1 ← %の後の数値はjob番号。jobsで調べた時に出てくる番号を入れる。

ここまででログアウトしても問題なくなる。
しかし標準出力や標準エラーが取れない。
それを取るためにする方法が以下の方法

4.プロセス番号を調べる
$ ps aux
user   5791  3.6  0.1 194640 32136 ?        S    15:36   0:21 ./test.sh
上記の場合だとプロセス番号は5791。

5.標準出力や標準エラーを保存するためのファイルを用意する。
$ touch stdout
$ touch stderr
※カレントディレクトリに作成

6.gdbで繋ぐ
$ gdb -p 5791

(gdb) p dup2(open("stdout",1),1) ← カレントディレクトリにあるstdoutというファイルに標準出力を入れる

(gdb) p dup2(open("stderr",1),2) ← カレントディレクトリにあるstdoutというファイルに標準エラーを入れる

(gdb) detach

(gdb) quit

以上で完了。
後は実際にファイルに書き込まれているかを確認する。
$ tail -f stdout
$ tail -f stderr

2014年12月5日金曜日

MongoDBでシャーディングの設定をしてみる

Mongodbでシャーディングを使ってみた。
シャーディングが何たるかはググってもらえればわかると思います。

以前、yum経由でmongoをインストールして起動させていたが、
とりあえずシャーディングの設定するので、そのプロセスは停止させる。

$ sudo service mongod stop

1.各シャード用のディレクトリを作成する。

ここで作成したディレクトリにjournalファイルとか諸々が作成される。
私は下記のディレクトリにディレクトリを作成した。
$ cd /var/lib/mongo/
$ sudo mkdir -p data/config ← configサーバ用のディレクトリ
$ sudo mkdir data/node1      ← シャード1用のディレクトリ
$ sudo mkdir data/node2      ← シャード2用のディレクトリ
$ sudo mkdir log             ← 各サーバのログのディレクトリ
$ sudo chown -R mongod:mongod data log

2.シャードを起動させる

シャードを起動させるコマンドは以下の通り。
ポート番号は使っていないポート番号を指定して、dbpathやlogpathは先ほど作成したディレクトリを指定する。
forkオプションを使用することでバックグラウンドで起動するようになる。

$ sudo -u mongod mongod --shardsvr --port 30000 --dbpath data/node0 --logpath log/node0.log --fork
$ sudo -u mongod mongod --shardsvr --port 30001 --dbpath data/node1 --logpath log/node1.log --fork

※エラーにlogpathを指定しておくと、そこにログファイルが出力されるが、
エラーがあった時にわかりにくいので、最初は--logpath以降は記述しないで試しに起動させてみるほうがいいかもしれない。
こんな感じ。

$ sudo -u mongod --shardsvr --port 30000 --dbpath data/node0

仮想環境とかでディスクの容量が少ないサーバを使っている人はjournalファイルを生成するだけでディスクが一杯になってしまう可能性があるので、
下記のようなsmallfilesオプションをつけてやるとよい。
smallfilesオプションを指定するとjournalファイルが1GB→128MBになる。
mongodbはjournalファイル自体を3ファイル位作成されるので、3GBから384MBに減らすことができるので、大分節約できる。

$ sudo -u mongod mongod --smallfiles --shardsvr --port 30000 --dbpath data/node0 --logpath log/node0.log --fork
$ sudo -u mongod mongod --smallfiles --shardsvr --port 30001 --dbpath data/node1 --logpath log/node1.log --fork

3.コンフィグサーバの起動

$ sudo -u mongod mongod --configsvr --port 20001 --dbpath data/config --logpath log/config.log --fork

4.mongosの起動

sudo -u mongod mongos --configdb localhost:20001 --port 20000 --logpath log/mongos.log --chunkSize 1 --fork

※ここで指定しているチャンクサイズとは分割させる際に、この値に達したら分割というためのしきい値のようなもの。
今回はきちんとチャンクが分割されるかを調べるために、1MBに設定した。

5.プロセスがきちんと立ち上がっているか確認

$ ps aux | grep mongo

6.mongosにログイン

mongosのプロセスを起動させるときに指定したポート番号を指定する。
$ mongo localhost:20000/admin

7.シャードの追加

mongos> sh.addShard("localhost:30000")    // ←30000ポートのmongodを追加
{ "shardAdded" : "shard0000", "ok" : 1 }  // ←okの値が1であれば問題なし

mongos> sh.addShard("localhost:30001")   // ←30001ポートのmongodを追加
{ "shardAdded" : "shard0001", "ok" : 1 }

8.シャードが追加されたか確認

mongos> sh.status()
--- Sharding Status ---
  sharding version: {
        "_id" : 1,
        "version" : 4,
        "minCompatibleVersion" : 4,
        "currentVersion" : 5,
        "clusterId" : ObjectId("547fc2e1390feaa447bb7a48")
}
  shards:
        {  "_id" : "shard0000",  "host" : "localhost:30000" }
        {  "_id" : "shard0001",  "host" : "localhost:30001" }
  databases:
        {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
        {  "_id" : "freegame_platform_message",  "partitioned" : true,  "primary" : "shard0000" }

9.シャーディングを有効化する

mongos> use admin
switched to db admin
mongos> sh.enableSharding("データベース名")

10.シャードキーを設定する

mongos> sh.shardCollection("freegame_platform_message.message" , { _id : 1, user_id : 1 })
{ "collectionsharded" : "freegame_platform_message.message", "ok" : 1 }

11.シャーディングの状態を確認する

MongoDB shell version: 2.6.5
connecting to: localhost:20000/freegame_platform_message
mongos> sh.status()
--- Sharding Status ---
  sharding version: {
        "_id" : 1,
        "version" : 4,
        "minCompatibleVersion" : 4,
        "currentVersion" : 5,
        "clusterId" : ObjectId("547fc2e1390feaa447bb7a48")
}
  shards:
        {  "_id" : "shard0000",  "host" : "localhost:30000" }
        {  "_id" : "shard0001",  "host" : "localhost:30001" }
  databases:
        {  "_id" : "admin",  "partitioned" : false,  "primary" : "config" }
        {  "_id" : "freegame_platform_message",  "partitioned" : true,  "primary" : "shard0000" }
                freegame_platform_message.message
                        shard key: { "_id" : 1, "user_id" : 1 }
                        chunks:
                                shard0000       1
                        { "_id" : { "$minKey" : 1 }, "user_id" : { "$minKey" : 1 } } -->> { "_id" : { "$maxKey" : 1 }, "user_id" : { "$maxKey" : 1 } } on : shard0000 Timestamp(1, 0)
        {  "_id" : "logdb",  "partitioned" : false,  "primary" : "shard0001" }

以上でシャーディングの設定は完了。

■補足
コレクションの内容を削除したい場合、dropとremoveがあるが、
MySQL的に言うと、dropはDROP TABLEで、removeはDELETE FROMといった感じ。
truncate的な動きをするメソッドはなさげ。

・コレクションを削除
db.collection.drop()
※コレクションを削除したタイミングでシャードの設定も削除されてしまうので注意。

・コレクション内のデータを削除
db.collection.remove({})
※dropより削除には時間がかかる。

ちなみに、シャードの設定はデータを入れる前でも後でも問題なく振り分けられる。

VagrantのVirtualBox用BaseBoxファイルを一から作ってみる

前提条件として、VirtualBoxがインストールされており、動く状態になっていること。

VirtualBox 4.3.12
Vagrant 1.6.5
VirtualBoxにインストールするOSはCentOS 6.4とする。

0.事前準備

■CentOS 6.4のisoファイルをダウンロードしてくる。
http://vault.centos.org/

上記のサイトに各バージョンが落ちているので、そこから必要なものを選んでダウンロードしてくる。
ちなみに今回落としてきたファイルは以下の2ファイル
http://vault.centos.org/6.4/isos/x86_64/CentOS-6.4-x86_64-bin-DVD1.iso
http://vault.centos.org/6.4/isos/x86_64/CentOS-6.4-x86_64-bin-DVD2.iso

■VirtualBox Guest Additionsのisoファイルをダウンロードしてくる。

http://download.virtualbox.org/virtualbox/

インストールされているVirtualBoxに対応したものを落とす必要がある。
今回の場合は4.3.12なので、それ用のファイルをダウンロードする。
http://download.virtualbox.org/virtualbox/4.3.12/VBoxGuestAdditions_4.3.12.iso


1.VirtualBoxを起動させ、新規ボタンを押して、新しい仮想マシンを作成しCentOSをインストールする。

http://blog.livedoor.jp/yoka3/archives/3861638.html

2.CentOS側の初期設定をする

■minimalでインストールすると初期状態ではNICが起動時にupしていないので、まずはそこを直す。eth0をDHCPで動作させる。
# sed -i -e "s:^ONBOOT=no$:ONBOOT=yes:" /etc/sysconfig/network-scripts/ifcfg-eth0
# service network restart
# ip addr show eth0

■MAC アドレスの記憶を無効化して、NIC に振られた UUID も消しておく。 これは Vagrant のドキュメントには無いものの、忘れると NIC のナンバリングが eth1 からになったりして苦労する。
# ln -f -s /dev/null /etc/udev/rules.d/70-persistent-net.rules 
# sed -i -e "s:HWADDR=.*::g" /etc/sysconfig/network-scripts/ifcfg-eth0
# sed -i -e "s:UUID=.*::g" /etc/sysconfig/network-scripts/ifcfg-eth0

■ssh デーモンの設定を行う。 UseDNS を無効にして起動する。
# sed -i -e "s:^#UseDNS yes:UseDNS no:" /etc/ssh/sshd_config
# service sshd start
# chkconfig sshd on

■これ以降は SSH を使って VirtualBox を動作させているホスト経由で操作できる。
※但し、VirtualBoxでポートフォワードの設定が必要。(VMを一度停止させて、設定→ネットワーク→高度→ポートフォワーディング)
名前にssh、プロトコルはTCP、ホストポートは適当なポート(2222とか)、ゲストポートは22として保存する。
$ ssh root@127.0.0.1 -p 2222

■vagrant グループ&ユーザを追加してノーパスワードで sudo できるようにする。 ついでに requiretty を無効にする。
# groupadd vagrant
# useradd vagrant -g vagrant -G wheel
# echo "vagrant ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
# sed -i -e "s:^.*requiretty:#Defaults requiretty:" /etc/sudoers

■vagrant ユーザが公開鍵を使ってログインできるように鍵を設置する。 パーミッションには注意する。
# su - vagrant
$ mkdir ~/.ssh
$ chmod 0700 ~/.ssh
$ curl -L -o ~/.ssh/authorized_keys  https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub
$ chmod 0600 ~/.ssh/authorized_keys

ここまでは流れ作業だったが、ここからが大変だった。

3.VirtualBoxのGuest Additionsをインストールする

最後に VirtualBox の Guest Additions をインストールするのだが、なかなかうまくいかなかった。

■VirtualBoxにVBoxGuestAdditions_4.3.12.isoをセットする。
CentOSをインストールした時と同様で、該当のVMの光学ドライブにダウンロードしてきたVBoxGuestAdditionsのisoファイルをセットする。

■まずディスクをマウントするためのディレクトリを作成。
一応Vagrantの公式サイトの手順を参考にやった。
http://docs.vagrantup.com/v2/virtualbox/boxes.html

To install via the command line:の部分を参照

$ sudo mkdir /media/VBoxGuestAdditions
$ sudo mount -o loop,ro /dev/cdrom /media/VBoxGuestAdditions
$ sudo sh /media/VBoxGuestAdditions/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.12 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
The make utility was not found. If the following module compilation fails then
this could be the reason and you should try installing it.

The gcc utility was not found. If the following module compilation fails then
this could be the reason and you should try installing it.

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-2.6.32-358.el6.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  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.

「The missing package can be probably installed with yum install kernel-devel-2.6.32-358.el6.x86_64」
と出ていたので、以下のファイルをインストール

$ sudo yum install http://vault.centos.org/6.4/os/x86_64/Packages/kernel-devel-2.6.32-358.el6.x86_64.rpm
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: www.ftp.ne.jp
* extras: www.ftp.ne.jp
* updates: www.ftp.ne.jp
Setting up Install Process
kernel-devel-2.6.32-358.el6.x86_64.rpm                                                                                                                                                                                                                                                                | 8.2 MB     00:13
Examining /var/tmp/yum-root-UTuUDk/kernel-devel-2.6.32-358.el6.x86_64.rpm: kernel-devel-2.6.32-358.el6.x86_64
Marking /var/tmp/yum-root-UTuUDk/kernel-devel-2.6.32-358.el6.x86_64.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package kernel-devel.x86_64 0:2.6.32-358.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================================================================================================================================================================================================================
Package                                                                 Arch                                                              Version                                                                      Repository                                                                                      Size
=============================================================================================================================================================================================================================================================================================================================
Installing:
kernel-devel                                                            x86_64                                                            2.6.32-358.el6                                                               /kernel-devel-2.6.32-358.el6.x86_64                                                             24 M

Transaction Summary
=============================================================================================================================================================================================================================================================================================================================
Install       1 Package(s)

Total size: 24 M
Installed size: 24 M
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : kernel-devel-2.6.32-358.el6.x86_64                                                                                                                                                                                                                                                                        1/1
  Verifying  : kernel-devel-2.6.32-358.el6.x86_64                                                                                                                                                                                                                                                                        1/1

Installed:
  kernel-devel.x86_64 0:2.6.32-358.el6

Complete!

もう一回インストールしてみたが、結局失敗。
ログファイルを確認してみると、今度は下記のようなエラーが出ていた。
$ less /var/log/vboxadd-install.log
/opt/VBoxGuestAdditions-4.3.12/src/vboxguest-4.3.12/build_in_tmp: line 62: make: コマンドが見つかりません
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.

ググってみたら下記のサイトがあった。
dkmsが必要そうな雰囲気があったので、インストールしてみる。
https://forums.virtualbox.org/viewtopic.php?f=7&t=50786

既存のリポジトリにはなかったので、リポジトリを追加
まずはファイルをダウンロード
$ wget http://ftp-srv2.kddilabs.jp/Linux/distributions/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
--2014-11-06 15:37:56--  http://ftp-srv2.kddilabs.jp/Linux/distributions/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
ftp-srv2.kddilabs.jp をDNSに問いあわせています... 202.255.47.226
ftp-srv2.kddilabs.jp|202.255.47.226|:80 に接続しています... 接続しました。
HTTP による接続要求を送信しました、応答を待っています... 200 OK
長さ: 14540 (14K) [application/octet-stream]
`epel-release-6-8.noarch.rpm' に保存中

100%[===================================================================================================================================================================================================================================================================================>] 14,540      --.-K/s 時間 0s

2014-11-06 15:37:56 (1.01 GB/s) - `epel-release-6-8.noarch.rpm' へ保存完了 [14540/14540]

インストール。
$ sudo rpm -ivh epel-release-6-8.noarch.rpm
警告: epel-release-6-8.noarch.rpm: ヘッダ V3 RSA/SHA256 Signature, key ID 0608b895: NOKEY
準備中...                ########################################### [100%]
   1:epel-release           ########################################### [100%]

dkmsがあるか確認。
$ yum info dkms
Loaded plugins: fastestmirror
Determining fastest mirrors
Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again

エラー・・・。
ミラーサイトの証明書が変わったかららしい。
とりあえず本家のサイトから取ってくるように修正する。

$ sudo vi /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 6 - $basearch
baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

問題ないか確認。
$ sudo yum info dkms
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: www.ftp.ne.jp
* extras: www.ftp.ne.jp
* updates: www.ftp.ne.jp
epel                                                                                                                                                                                                                                                                                                  | 4.4 kB     00:00
epel/primary_db                                                                                                                                                                                                                                                                                       | 6.3 MB     00:02
Available Packages
Name        : dkms
Arch        : noarch
Version     : 2.2.0.3
Release     : 28.git.7c3e7c5.el6
Size        : 77 k
Repo        : epel
Summary     : Dynamic Kernel Module Support Framework
URL         : http://linux.dell.com/dkms
License     : GPLv2+
Description : This package contains the framework for the Dynamic Kernel Module Support (DKMS)
            : method for installing module RPMS as originally developed by Dell.

行けたので、インストール
$ sudo yum install dkms
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: www.ftp.ne.jp
* extras: www.ftp.ne.jp
* updates: www.ftp.ne.jp
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package dkms.noarch 0:2.2.0.3-28.git.7c3e7c5.el6 will be installed
--> Processing Dependency: gcc for package: dkms-2.2.0.3-28.git.7c3e7c5.el6.noarch
--> Running transaction check
---> Package gcc.x86_64 0:4.4.7-11.el6 will be installed
--> Processing Dependency: libgomp = 4.4.7-11.el6 for package: gcc-4.4.7-11.el6.x86_64
--> Processing Dependency: cpp = 4.4.7-11.el6 for package: gcc-4.4.7-11.el6.x86_64
--> Processing Dependency: libgcc >= 4.4.7-11.el6 for package: gcc-4.4.7-11.el6.x86_64
--> Processing Dependency: glibc-devel >= 2.2.90-12 for package: gcc-4.4.7-11.el6.x86_64
--> Processing Dependency: cloog-ppl >= 0.15 for package: gcc-4.4.7-11.el6.x86_64
--> Processing Dependency: libgomp.so.1()(64bit) for package: gcc-4.4.7-11.el6.x86_64
--> Running transaction check
---> Package cloog-ppl.x86_64 0:0.15.7-1.2.el6 will be installed
--> Processing Dependency: libppl_c.so.2()(64bit) for package: cloog-ppl-0.15.7-1.2.el6.x86_64
--> Processing Dependency: libppl.so.7()(64bit) for package: cloog-ppl-0.15.7-1.2.el6.x86_64
---> Package cpp.x86_64 0:4.4.7-11.el6 will be installed
--> Processing Dependency: libmpfr.so.1()(64bit) for package: cpp-4.4.7-11.el6.x86_64
---> Package glibc-devel.x86_64 0:2.12-1.149.el6 will be installed
--> Processing Dependency: glibc-headers = 2.12-1.149.el6 for package: glibc-devel-2.12-1.149.el6.x86_64
--> Processing Dependency: glibc = 2.12-1.149.el6 for package: glibc-devel-2.12-1.149.el6.x86_64
--> Processing Dependency: glibc-headers for package: glibc-devel-2.12-1.149.el6.x86_64
---> Package libgcc.x86_64 0:4.4.7-3.el6 will be updated
---> Package libgcc.x86_64 0:4.4.7-11.el6 will be an update
---> Package libgomp.x86_64 0:4.4.7-11.el6 will be installed
--> Running transaction check
---> Package glibc.x86_64 0:2.12-1.107.el6 will be updated
--> Processing Dependency: glibc = 2.12-1.107.el6 for package: glibc-common-2.12-1.107.el6.x86_64
---> Package glibc.x86_64 0:2.12-1.149.el6 will be an update
---> Package glibc-headers.x86_64 0:2.12-1.149.el6 will be installed
--> Processing Dependency: kernel-headers >= 2.2.1 for package: glibc-headers-2.12-1.149.el6.x86_64
--> Processing Dependency: kernel-headers for package: glibc-headers-2.12-1.149.el6.x86_64
---> Package mpfr.x86_64 0:2.4.1-6.el6 will be installed
---> Package ppl.x86_64 0:0.10.2-11.el6 will be installed
--> Running transaction check
---> Package glibc-common.x86_64 0:2.12-1.107.el6 will be updated
---> Package glibc-common.x86_64 0:2.12-1.149.el6 will be an update
---> Package kernel-headers.x86_64 0:2.6.32-504.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================================================================================================================================================================================================================
Package                                                                        Arch                                                                   Version                                                                                    Repository                                                            Size
=============================================================================================================================================================================================================================================================================================================================
Installing:
dkms                                                                           noarch                                                                 2.2.0.3-28.git.7c3e7c5.el6                                                                 epel                                                                  77 k
Installing for dependencies:
cloog-ppl                                                                      x86_64                                                                 0.15.7-1.2.el6                                                                             base                                                                  93 k
cpp                                                                            x86_64                                                                 4.4.7-11.el6                                                                               base                                                                 3.7 M
gcc                                                                            x86_64                                                                 4.4.7-11.el6                                                                               base                                                                  10 M
glibc-devel                                                                    x86_64                                                                 2.12-1.149.el6                                                                             base                                                                 983 k
glibc-headers                                                                  x86_64                                                                 2.12-1.149.el6                                                                             base                                                                 611 k
kernel-headers                                                                 x86_64                                                                 2.6.32-504.el6                                                                             base                                                                 3.3 M
libgomp                                                                        x86_64                                                                 4.4.7-11.el6                                                                               base                                                                 133 k
mpfr                                                                           x86_64                                                                 2.4.1-6.el6                                                                                base                                                                 157 k
ppl                                                                            x86_64                                                                 0.10.2-11.el6                                                                              base                                                                 1.3 M
Updating for dependencies:
glibc                                                                          x86_64                                                                 2.12-1.149.el6                                                                             base                                                                 3.8 M
glibc-common                                                                   x86_64                                                                 2.12-1.149.el6                                                                             base                                                                  14 M
libgcc                                                                         x86_64                                                                 4.4.7-11.el6                                                                               base                                                                 102 k

Transaction Summary
=============================================================================================================================================================================================================================================================================================================================
Install      10 Package(s)
Upgrade       3 Package(s)

Total download size: 39 M
Is this ok [y/N]: y
Downloading Packages:
(1/13): cloog-ppl-0.15.7-1.2.el6.x86_64.rpm                                                                                                                                                                                                                                                           |  93 kB     00:00
(2/13): cpp-4.4.7-11.el6.x86_64.rpm                                                                                                                                                                                                                                                                   | 3.7 MB     00:00
(3/13): dkms-2.2.0.3-28.git.7c3e7c5.el6.noarch.rpm                                                                                                                                                                                                                                                    |  77 kB     00:00
(4/13): gcc-4.4.7-11.el6.x86_64.rpm                                                                                                                                                                                                                                                                   |  10 MB     00:00
(5/13): glibc-2.12-1.149.el6.x86_64.rpm                                                                                                                                                                                                                                                               | 3.8 MB     00:00
(6/13): glibc-common-2.12-1.149.el6.x86_64.rpm                                                                                                                                                                                                                                                        |  14 MB     00:01
(7/13): glibc-devel-2.12-1.149.el6.x86_64.rpm                                                                                                                                                                                                                                                         | 983 kB     00:00
(8/13): glibc-headers-2.12-1.149.el6.x86_64.rpm                                                                                                                                                                                                                                                       | 611 kB     00:00
(9/13): kernel-headers-2.6.32-504.el6.x86_64.rpm                                                                                                                                                                                                                                                      | 3.3 MB     00:00
(10/13): libgcc-4.4.7-11.el6.x86_64.rpm                                                                                                                                                                                                                                                               | 102 kB     00:00
(11/13): libgomp-4.4.7-11.el6.x86_64.rpm                                                                                                                                                                                                                                                              | 133 kB     00:00
(12/13): mpfr-2.4.1-6.el6.x86_64.rpm                                                                                                                                                                                                                                                                  | 157 kB     00:00
(13/13): ppl-0.10.2-11.el6.x86_64.rpm                                                                                                                                                                                                                                                                 | 1.3 MB     00:00
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                                                                                                                                        8.9 MB/s |  39 MB     00:04
warning: rpmts_HdrFromFdno: Header V3 RSA/SHA256 Signature, key ID 0608b895: NOKEY
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
Importing GPG key 0x0608B895:
Userid : EPEL (6) <epel@fedoraproject.org>
Package: epel-release-6-8.noarch (installed)
From   : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6
Is this ok [y/N]: y
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
  Updating   : libgcc-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                               1/16
  Updating   : glibc-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                              2/16
  Updating   : glibc-common-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                       3/16
  Installing : libgomp-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                              4/16
  Installing : mpfr-2.4.1-6.el6.x86_64                                                                                                                                                                                                                                                                                  5/16
  Installing : cpp-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                                  6/16
  Installing : ppl-0.10.2-11.el6.x86_64                                                                                                                                                                                                                                                                                 7/16
  Installing : cloog-ppl-0.15.7-1.2.el6.x86_64                                                                                                                                                                                                                                                                          8/16
  Installing : kernel-headers-2.6.32-504.el6.x86_64                                                                                                                                                                                                                                                                     9/16
  Installing : glibc-headers-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                     10/16
  Installing : glibc-devel-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                       11/16
  Installing : gcc-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                                 12/16
  Installing : dkms-2.2.0.3-28.git.7c3e7c5.el6.noarch                                                                                                                                                                                                                                                                  13/16
  Cleanup    : glibc-2.12-1.107.el6.x86_64                                                                                                                                                                                                                                                                             14/16
  Cleanup    : glibc-common-2.12-1.107.el6.x86_64                                                                                                                                                                                                                                                                      15/16
  Cleanup    : libgcc-4.4.7-3.el6.x86_64                                                                                                                                                                                                                                                                               16/16
  Verifying  : glibc-common-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                       1/16
  Verifying  : gcc-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                                  2/16
  Verifying  : glibc-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                              3/16
  Verifying  : dkms-2.2.0.3-28.git.7c3e7c5.el6.noarch                                                                                                                                                                                                                                                                   4/16
  Verifying  : glibc-headers-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                      5/16
  Verifying  : glibc-devel-2.12-1.149.el6.x86_64                                                                                                                                                                                                                                                                        6/16
  Verifying  : libgcc-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                               7/16
  Verifying  : libgomp-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                              8/16
  Verifying  : mpfr-2.4.1-6.el6.x86_64                                                                                                                                                                                                                                                                                  9/16
  Verifying  : cpp-4.4.7-11.el6.x86_64                                                                                                                                                                                                                                                                                 10/16
  Verifying  : kernel-headers-2.6.32-504.el6.x86_64                                                                                                                                                                                                                                                                    11/16
  Verifying  : ppl-0.10.2-11.el6.x86_64                                                                                                                                                                                                                                                                                12/16
  Verifying  : cloog-ppl-0.15.7-1.2.el6.x86_64                                                                                                                                                                                                                                                                         13/16
  Verifying  : glibc-2.12-1.107.el6.x86_64                                                                                                                                                                                                                                                                             14/16
  Verifying  : libgcc-4.4.7-3.el6.x86_64                                                                                                                                                                                                                                                                               15/16
  Verifying  : glibc-common-2.12-1.107.el6.x86_64                                                                                                                                                                                                                                                                      16/16

Installed:
  dkms.noarch 0:2.2.0.3-28.git.7c3e7c5.el6

Dependency Installed:
  cloog-ppl.x86_64 0:0.15.7-1.2.el6        cpp.x86_64 0:4.4.7-11.el6        gcc.x86_64 0:4.4.7-11.el6        glibc-devel.x86_64 0:2.12-1.149.el6        glibc-headers.x86_64 0:2.12-1.149.el6        kernel-headers.x86_64 0:2.6.32-504.el6        libgomp.x86_64 0:4.4.7-11.el6        mpfr.x86_64 0:2.4.1-6.el6
  ppl.x86_64 0:0.10.2-11.el6

Dependency Updated:
  glibc.x86_64 0:2.12-1.149.el6                                                                          glibc-common.x86_64 0:2.12-1.149.el6                                                                          libgcc.x86_64 0:4.4.7-11.el6

Complete!

もう一度インストールしてみる。
$ sudo sh /media/VBoxGuestAdditions/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.12 Guest Additions for Linux............
VirtualBox Guest Additions installer
Removing installed version 4.3.12 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox DKMS kernel modules           [  OK  ]
Removing existing VirtualBox non-DKMS kernel modules       [  OK  ]
Building the VirtualBox Guest Additions kernel modules
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  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.

さっきとちょっと変わったけど、またしてもエラー・・・。

エラーログを確認してみると、
Uninstalling modules from DKMS
Attempting to install using DKMS

Creating symlink /var/lib/dkms/vboxguest/4.3.12/source ->
                 /usr/src/vboxguest-4.3.12

DKMS: add completed.

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:
cleaning build area...
make KERNELRELEASE=2.6.32-358.el6.x86_64 -C /lib/modules/2.6.32-358.el6.x86_64/build M=/var/lib/dkms/vboxguest/4.3.12/build...(bad exit status: 2)
Error! Bad return status for module build on kernel: 2.6.32-358.el6.x86_64 (x86_64)
Consult /var/lib/dkms/vboxguest/4.3.12/build/make.log for more information.
Failed to install using DKMS, attempting to install without
make KBUILD_VERBOSE=1 CONFIG_MODULE_SIG= -C /lib/modules/2.6.32-358.el6.x86_64/build SUBDIRS=/tmp/vbox.0 SRCROOT=/tmp/vbox.0 modules
test -e include/linux/autoconf.h -a -e include/config/auto.conf || (            \
        echo;                                                           \
        echo "  ERROR: Kernel configuration is invalid.";               \
        echo "         include/linux/autoconf.h or include/config/auto.conf are missing.";      \
        echo "         Run 'make oldconfig && make prepare' on kernel src to fix it.";  \
        echo;                                                           \
        /bin/false)
mkdir -p /tmp/vbox.0/.tmp_versions ; rm -f /tmp/vbox.0/.tmp_versions/*
make -f scripts/Makefile.build obj=/tmp/vbox.0
  gcc -Wp,-MD,/tmp/vbox.0/.VBoxGuest-linux.o.d  -nostdinc -isystem /usr/lib/gcc/x86_64-redhat-linux/4.4.7/include -Iinclude  -I/usr/src/kernels/2.6.32-358.el6.x86_64/arch/x86/include -include include/linux/autoconf.h -D__KERNEL__ -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Wno-format-security -fno-delete-null-pointer-checks -O2 -m64 -mtune=generic -mno-red-zone -mcmodel=kernel -funit-at-a-time -maccumulate-outgoing-args -fstack-protector -DCONFIG_AS_CFI=1 -DCONFIG_AS_CFI_SIGNAL_FRAME=1 -DCONFIG_AS_CFI_SECTIONS=1 -pipe -Wno-sign-compare -fno-asynchronous-unwind-tables -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -Wframe-larger-than=2048 -Wno-unused-but-set-variable -fno-omit-frame-pointer -fno-optimize-sibling-calls -g -pg -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fno-dwarf2-cfi-asm -fconserve-stack -include /tmp/vbox.0/include/VBox/VBoxGuestMangling.h -I/lib/modules/2.6.32-358.el6.x86_64/build/include -I/tmp/vbox.0/ -I/tmp/vbox.0/include -I/tmp/vbox.0/r0drv/linux -I/tmp/vbox.0/vboxguest/ -I/tmp/vbox.0/vboxguest/include -I/tmp/vbox.0/vboxguest/r0drv/linux -D__KERNEL__ -DMODULE -DVBOX -DRT_OS_LINUX -DIN_RING0 -DIN_RT_R0 -DIN_GUEST -DIN_GUEST_R0 -DIN_MODULE -DRT_WITH_VBOX -DVBGL_VBOXGUEST -DVBOX_WITH_HGCM -DRT_ARCH_AMD64 -DVBOX_WITH_64_BITS_GUESTS  -DMODULE -D"KBUILD_STR(s)=#s" -D"KBUILD_BASENAME=KBUILD_STR(VBoxGuest_linux)"  -D"KBUILD_MODNAME=KBUILD_STR(vboxguest)" -D"DEBUG_HASH=24" -D"DEBUG_HASH2=60" -c -o /tmp/vbox.0/.tmp_VBoxGuest-linux.o /tmp/vbox.0/VBoxGuest-linux.c
  set -e ; perl /usr/src/kernels/2.6.32-358.el6.x86_64/scripts/recordmcount.pl "x86_64" "64" "objdump" "objcopy" "gcc" "ld" "nm" "" "" "1" "/tmp/vbox.0/VBoxGuest-linux.o";
/bin/sh: perl: コマンドが見つかりません
make[2]: *** [/tmp/vbox.0/VBoxGuest-linux.o] エラー 127
make[1]: *** [_module_/tmp/vbox.0] エラー 2
make: *** [vboxguest] エラー 2
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.

なんかkernelのバージョンが一致していないことが問題らしい。

$ rpm -qa | grep kernel
dracut-kernel-004-303.el6.noarch
kernel-2.6.32-358.el6.x86_64
kernel-devel-2.6.32-358.el6.x86_64
kernel-firmware-2.6.32-358.el6.noarch
kernel-headers-2.6.32-504.el6.x86_64

どうやら
kernel-headers-2.6.32-504.el6.x86_64
ってやつだけあってないので、これだけダウングレードする。

$ sudo yum downgrade http://vault.centos.org/6.4/os/x86_64/Packages/kernel-headers-2.6.32-358.el6.x86_64.rpm
Loaded plugins: fastestmirror
Setting up Downgrade Process
Loading mirror speeds from cached hostfile
 * base: www.ftp.ne.jp
 * extras: www.ftp.ne.jp
 * updates: www.ftp.ne.jp
kernel-headers-2.6.32-358.el6.x86_64.rpm                                                                                                                                                                                                                                                              | 2.3 MB     00:02
Examining /var/tmp/yum-root-UTuUDk/kernel-headers-2.6.32-358.el6.x86_64.rpm: kernel-headers-2.6.32-358.el6.x86_64
Resolving Dependencies
--> Running transaction check
---> Package kernel-headers.x86_64 0:2.6.32-358.el6 will be a downgrade
---> Package kernel-headers.x86_64 0:2.6.32-504.el6 will be erased
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================================================================================================================================================================================================================
 Package                                                                  Arch                                                             Version                                                                     Repository                                                                                       Size
=============================================================================================================================================================================================================================================================================================================================
Downgrading:
 kernel-headers                                                           x86_64                                                           2.6.32-358.el6                                                              /kernel-headers-2.6.32-358.el6.x86_64                                                           2.5 M

Transaction Summary
================================================================================
Downgrade     1 Package(s)

Total size: 2.5 M
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : kernel-headers-2.6.32-358.el6.x86_64
  Cleanup    : kernel-headers-2.6.32-504.el6.x86_64
  Verifying  : kernel-headers-2.6.32-358.el6.x86_64
  Verifying  : kernel-headers-2.6.32-504.el6.x86_64

Removed:
  kernel-headers.x86_64 0:2.6.32-504.el6

Installed:
  kernel-headers.x86_64 0:2.6.32-358.el6

Complete!

カーネル合わせた後に再びやってみる。
# sh /media/VBoxGuestAdditions/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.12 Guest Additions for Linux............
VirtualBox Guest Additions installer
Removing installed version 4.3.12 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox DKMS kernel modules           [  OK  ]
Removing existing VirtualBox non-DKMS kernel modules       [  OK  ]
Building the VirtualBox Guest Additions kernel modules
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  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.

またしてもエラー。
$ less /var/log/vboxadd-install.log

Uninstalling modules from DKMS
Attempting to install using DKMS

Creating symlink /var/lib/dkms/vboxguest/4.3.12/source ->
                 /usr/src/vboxguest-4.3.12

DKMS: add completed.

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:
cleaning build area...
make KERNELRELEASE=2.6.32-358.el6.x86_64 -C /lib/modules/2.6.32-358.el6.x86_64/build M=/var/lib/dkms/vboxguest/4.3.12/build...(bad exit status: 2)
Error! Bad return status for module build on kernel: 2.6.32-358.el6.x86_64 (x86_64)
Consult /var/lib/dkms/vboxguest/4.3.12/build/make.log for more information.
Failed to install using DKMS, attempting to install without
make KBUILD_VERBOSE=1 CONFIG_MODULE_SIG= -C /lib/modules/2.6.32-358.el6.x86_64/build SUBDIRS=/tmp/vbox.0 SRCROOT=/tmp/vbox.0 modules
test -e include/linux/autoconf.h -a -e include/config/auto.conf || (            \
        echo;                                                           \
        echo "  ERROR: Kernel configuration is invalid.";               \
        echo "         include/linux/autoconf.h or include/config/auto.conf are missing.";      \
        echo "         Run 'make oldconfig && make prepare' on kernel src to fix it.";  \
        echo;                                                           \
        /bin/false)
mkdir -p /tmp/vbox.0/.tmp_versions ; rm -f /tmp/vbox.0/.tmp_versions/*
make -f scripts/Makefile.build obj=/tmp/vbox.0
  gcc -Wp,-MD,/tmp/vbox.0/.VBoxGuest-linux.o.d  -nostdinc -isystem /usr/lib/gcc/x86_64-redhat-linux/4.4.7/include -Iinclude  -I/usr/src/kernels/2.6.32-358.el6.x86_64/arch/x86/include -include include/linux/autoconf.h -D__KERNEL__ -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Wno-format-security -fno-delete-null-pointer-checks -O2 -m64 -mtune=generic -mno-red-zone -mcmodel=kernel -funit-at-a-time -maccumulate-outgoing-args -fstack-protector -DCONFIG_AS_CFI=1 -DCONFIG_AS_CFI_SIGNAL_FRAME=1 -DCONFIG_AS_CFI_SECTIONS=1 -pipe -Wno-sign-compare -fno-asynchronous-unwind-tables -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -Wframe-larger-than=2048 -Wno-unused-but-set-variable -fno-omit-frame-pointer -fno-optimize-sibling-calls -g -pg -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fno-dwarf2-cfi-asm -fconserve-stack -include /tmp/vbox.0/include/VBox/VBoxGuestMangling.h -I/lib/modules/2.6.32-358.el6.x86_64/build/include -I/tmp/vbox.0/ -I/tmp/vbox.0/include -I/tmp/vbox.0/r0drv/linux -I/tmp/vbox.0/vboxguest/ -I/tmp/vbox.0/vboxguest/include -I/tmp/vbox.0/vboxguest/r0drv/linux -D__KERNEL__ -DMODULE -DVBOX -DRT_OS_LINUX -DIN_RING0 -DIN_RT_R0 -DIN_GUEST -DIN_GUEST_R0 -DIN_MODULE -DRT_WITH_VBOX -DVBGL_VBOXGUEST -DVBOX_WITH_HGCM -DRT_ARCH_AMD64 -DVBOX_WITH_64_BITS_GUESTS  -DMODULE -D"KBUILD_STR(s)=#s" -D"KBUILD_BASENAME=KBUILD_STR(VBoxGuest_linux)"  -D"KBUILD_MODNAME=KBUILD_STR(vboxguest)" -D"DEBUG_HASH=24" -D"DEBUG_HASH2=60" -c -o /tmp/vbox.0/.tmp_VBoxGuest-linux.o /tmp/vbox.0/VBoxGuest-linux.c
  set -e ; perl /usr/src/kernels/2.6.32-358.el6.x86_64/scripts/recordmcount.pl "x86_64" "64" "objdump" "objcopy" "gcc" "ld" "nm" "" "" "1" "/tmp/vbox.0/VBoxGuest-linux.o";
/bin/sh: perl: コマンドが見つかりません
make[2]: *** [/tmp/vbox.0/VBoxGuest-linux.o] エラー 127
make[1]: *** [_module_/tmp/vbox.0] エラー 2
make: *** [vboxguest] エラー 2
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.

perlコマンドがないらしいので、perlをインストール

$ sudo yum install perl

もう一回試してみた。
# sh /media/VBoxGuestAdditions/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.12 Guest Additions for Linux............
VirtualBox Guest Additions installer
Removing installed version 4.3.12 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox DKMS kernel modules           [  OK  ]
Removing existing VirtualBox non-DKMS kernel modules       [  OK  ]
Building the VirtualBox Guest Additions kernel modules     [  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.

出来た!!!!
Building the VirtualBox Guest Additions kernel modulesの所でやたら時間掛かってたみたいで心配でしたが出来てました。
以上で仮想マシンの設定は完了。
マシンはシャットダウンしておく。

4.BaseBoxファイルにパッケージする


今度はホスト側で作業を行う。
■仮想マシンが保存されているディレクトリに移動してBase Boxファイルにパッケージする。
$ cd ~/VirtualBox\ VMs/vagrant-centos64/
$ vagrant package --base vagrant-centos64

■完成したBase BoxファイルをVagrantに登録する。
$ cd ~/VirtualBox VMs/box新規作成用/vagrant-centos64
$ vagrant box add centos64_30gb package.box
C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/box_add.rb:44:in `file?': "\x88\x90" from Windows-31J to UTF-8 (Encoding::UndefinedConversionError)
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/box_add.rb:44:in `block in call'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/box_add.rb:29:in `map'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/box_add.rb:29:in `call'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/commands/box/command/add.rb:85:in `execute'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/commands/box/command/root.rb:61:in `execute'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/cli.rb:42:in `execute'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:292:in `cli'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.6.5/bin/vagrant:174:in `
'

出来たboxを追加しようとしたらエラーになった・・・。
日本語があやしい気がしたので、とりあえずVirtualBox上で作っていたグループから移動させた。
$ mv ~/VirtualBox VMs/box新規作成用/vagrant-centos64 ~/VirtualBox VMs\vagrant-centos64

で、新しいディレクトリへ移動

$ cd ~/VirtualBox VMs\vagrant-centos64

もう一回addしてみる。

$ vagrant box add centos64_30gb package.box
==> box: Adding box 'centos64_30gb' (v0) for provider:
    box: Downloading: file://C:/Users/kusagaya-naoki/VirtualBox%20VMs/vagrant-centos64/package.box
    box:
==> box: Successfully added box 'centos64_30gb' (v0) for 'virtualbox'!

出来た!

box追加して起動させてみたら、エラーが出た。(エラー内容のログ取り忘れた・・・。)
内容的にはSCPインストールしろよって感じのエラーだったので、VirtualBoxをもう一度起動して、サーバにログイン。 openssh-clientsをyum経由でインストールし、再度シャットダウンしてみたらうまく行った。