page_adsence

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経由でインストールし、再度シャットダウンしてみたらうまく行った。

2014年11月20日木曜日

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

前回、MySQLからMongoDBへの移行作業を書いたが、実際に作業を行うMySQLユーザーにはFILE権限がなかった。
そのため、INTO OUTFILEコマンドが使用出来ず、別の方法を模索することになった。
で、同僚の方から標準出力をファイルに吐きだすという手法を使ってやってみることにした。
やり方自体はすごく簡単で、下記のようにするだけ。

mysql -u ユーザー名 データベース名 -p > output.tsv

これだけで、SQLの結果をTSV形式でファイルに出力することが出来る。
上のコマンドだけというのは少し語弊があるが、上のコマンドを入力すると、パスワードを入力後に入力待ちの状態になる。
この状態で結果をTSV出力したいSQLを流してやると、結果がTSVファイルに出力される。
自分なりにこれをやることでのメリット、デメリットを紹介

■メリット
・MySQLのデータ内に改行やタブが存在していたとしても、\tや\nといった文字列で出力されるため、ファイル上は必ず1レコード1列となっているため、
普通にSQL流した結果の件数と異なっているかどうかをwcコマンドですぐに確認出来る。
また、TSVで出力されるため、MySQLデータ内部にタブが入っていた場合、普通ならずれてしまうが「\t」という文字として出力されるためにそういった問題が起きない。
・ヘッダ行にフィールド名が出力されるため、mongoimportする時に別にファイルを用意する必要が無くなる。

■デメリット
・処理が終わったかどうかがわかりずらい。
入力待ち状態になった後、SQLを入力し、Enterキーを押下するが、改行された後は何も反応がない。
そのため、画面上でSQLが処理を終えたかどうかの判断がつけられない。
対象のコンソール上でわからないだけで、mysqlのSHOW PROCESSLISTコマンドを使用すれば処理が実行されているかどうかはすぐにわかる。
とはいえ、いちいち確認のためにMySQLにログインしてSHOW PROCESSLISTコマンドを打つのは面倒である。
SHOW PROCESSLISTコマンドで、該当のSQLが無くなりSLEEP状態になったら終了しても問題ない。
終了方法としてはexitコマンドを打つだけ。
exitの後にセミコロンをつけると抜けれないらしい。

それ以外の移行方法はほとんど変わらず。
置換の処理方法が異なるので、一応それだけ記載しておく。

cat test.tsv | sed -e 's/"/""/g' | sed -e 's/\t/","/g' | sed -e 's/\(^\|$\)/"/g' | sed -e 's/\(^Z^Z.*app_id=""\([0-9]\+\)"">^Z^Z\|^Z^Z.*^Z^Z\)/\2/g' | sed -e 's/\(^Z\(.*\)^Z\|^Z\(.*\)^Z\)/\2/g' | sed -e 's/\\n/\n/g' | sed -e 's/\\t/\t/g' | sed -e 's/^M//g' | sed -e 's/$/\r/' > convert.csv


あとはmongoimportするだけ。(ヘッダ行が出力されているので、ヘッダファイルは作らなくてもよい)
mongoimport -d freegame_message -c message --type csv --file convert.csv --headerline

とりあえずこんな感じでした。

MySQLからMongoDBへのデータ移行

MySQLからMongoDBへの移行案件があったので、その時に調べたことをメモ。
今回の移行案件は、ただ単純にMySQLのテーブルをMongoDBのコレクション(MySQLでいうテーブルのこと)に変えるというわけではなかった。
MySQLの4テーブルを条件によってJOINし、その結果をMongoDBのコレクションとして保存するというもので、
データの移行件数はおおよそ3億件~4億件。
文字コードはEUC-JP

まず移行方法に関して検討してみた。
過去に行った移行案件では、基本的にPHPを介して移行するといったイメージ。
今回はPHPは介さずにMySQL→CSVやTSV→mongoimportといった手順で出来るように色々と検討してみた。

まず、MySQLでの出力形式だが、mongoimportの仕様により、区切り文字(カンマ)、囲み文字(ダブルクォーテーションが)、改行(CRLF)に関しては自動的に決まる。
エスケープに関しては、移行データにどういった文字が入っているかによる。

・日本語あり
・TEXT型あり
・改行あり
・入力チェックは最低限(セキュリティ的な部分のみ)
・NULLもあり

こういった場合のデータが含まれていると、普通の文字でエスケープすると、
入力データ内部に存在している可能性が高く、うまく移行出来ない可能性が高くなってしまう。

ちなみに今回試しに移行してみたデータは

・日本語あり
・TEXT型あり
・入力チェックは最低限
・改行コードも混在(LFとCRLF)
・NULLもあり
・HTMLのタグも入っている

なんでこんなデータが存在しているのかというと、テストデータとして以前作成したものをそのまま利用しているからである。
こういった場合でもきちんとエスケープ出来る可能性を探した結果、
最終的に行きついたのが以下のSQLになる。

FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY "\Z" LINES TERMINATED BY "\r\n";

とりあえず"\Z"ならそうそう入ってこないであろうという推測の元、エスケープを行ってみた。
いろいろと加工は必要だが、とりあえずコマンドのみで目視する必要なく置換出来るのではないかと思う。
なお、エスケープに使える文字は以下の通り(MySQL公式サイトから抜粋)

Escape SequenceCharacter Represented by Sequence
\0An ASCII NUL (0x00) character.
\'A single quote (“'”) character.
\"A double quote (“"”) character.
\bA backspace character.
\nA newline (linefeed) character.
\rA carriage return character.
\tA tab character.
\ZASCII 26 (Control+Z). See note following the table.
\\A backslash (“\”) character.
\%A “%” character. See note following the table.
\_A “_” character. See note following the table.

とりあえずファイルの出力自体は上記の方法でやってみた。
11111,11111,"Test","テストメッセージ^Z
^Z
<link test_id=^Z"1^Z">",^ZN

NULLや改行部分もエスケープされてしまい、意図した感じにはなっていないが、ググってみるとこのような感じにならざるを得ないっぽい。
ということで、ここからmongoimport出来るまで置換処理を行っていく。

1.まず^ZNとなっているNULLを置換(^ZはCtrl+V Ctrl+Zの順番で入力すると出せる)
sed -i -e 's/^ZN,/"NULL",/g' test.csv

2.ダブルクォーテーションのエスケープ文字を修正
sed -i -e 's/^Z"/""/g' test.csv

3.LF、CRLFが混ざっているため、一度全てLFに変えてからCRLFに戻す(^MはCtrl+V Ctrl+Mの順番で入力すると出せる)
sed -i -e 's/^Z^M//g' test.csv

sed -i -e 's/^M//g' test.csv

sed -i -e 's/$/\r/' test.csv

4.文字コードを変換(mongoはUTF-8じゃないと読み込まないため)
iconv -f EUCJP -t UTF8 test.csv > test2.csv
※nkfコマンドは作業サーバに入っていなかったためiconvで代用

以上で変換作業は完了。
あとはmongoimportコマンドでインポート処理を行うだけ。
出力したCSVにはヘッダ行がないので、別で用意してやる。
$ vi header.txt
id
field_nameA
field_nameB
field_nameC
field_nameD

で、インポートコマンドは以下のような感じ。
mongoimport -d データベース名 -c コレクション名 --type csv --file test.csv --fieldFile header.txt


mongoimportでの注意点
1.csvの囲み文字は必ずダブルクォーテーションであること。シングルクォーテーションだと改行を含んだデータがある場合に、うまく取り込まれない。
2.元々のデータにダブルクォーテーションがあった場合は、""と記述することで、文中のダブルクォーテーションをエスケープすることが出来る。
3.改行コードは必ずCRLFである必要がある。空白行があった場合にLFだとうまく取り込まれない。

2014年11月19日水曜日

MySQLのお手軽インポート&エクスポート

MySQLのデータインポートやエクスポートのやり方色々。

■ローカルに書き出す
mysqldump -u ユーザー名 -p データベース名 テーブル名 > テーブル名.sql


■ローカルから読み込む
mysql -u ユーザー名 -p データベース名 < テーブル名.sql


■リモートサーバーに直接インポート
これが便利。コマンド1発で後は待つだけ。
mysqldump -u ユーザー名 -p データベース名 テーブル名 | ssh リモートユーザー@リモートホスト "mysql -u ユーザー名 -pパスワード データベース名"


■ローカルに書き出す(要FILE権限)
ここに指定してある条件は任意なので、気にしないように。
SELECT ~ FROM テーブル名 INTO OUTFILE '/tmp/dump.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY "\Z" LINES TERMINATED BY "\r\n";


■ローカル(MySQL Serverが動いているサーバ)から読み込む(要FILE権限)
IGNORE 1 LINESはヘッダ行を無視するための指定。
この方法だとMySQL Serverが動いているサーバ内の'/tmp/dump.csv'のファイルを読み込む。
$ mysql -uroot -p
LOAD DATA INFILE '/tmp/exittestmysql.csv' INTO TABLE テーブル名 IGNORE 1 LINES;


■ローカル(MySQL Clientが動いているサーバから、MySQL Serverが動いているサーバにログイン)から読み込む(FILE権限不要)
MySQL ClientでリモートのDBサーバへログインし、MySQL Clientが動いているサーバ上のファイルを取り込む。
$ mysql -uroot -h XXX.XXX.XXX.XXX -p
LOAD DATA LOCAL INFILE '/tmp/dump.csv' INTO TABLE テーブル名 IGNORE 1 LINES;


■MySQLの標準出力をファイルに書き込み。
処理がどうなっているかが確認するのが面倒だが、FILE権限がなくてデータを出力したい場合に使える。
処理中かどうかを確認するには別画面を立ち上げてshow processlistを見る。
sleepになったら処理終了。
exitする時には最後にセミコロンをつけてはいけない。

$ mysql -uroot -p DB名 > output.tsv
SELELCT * FROM テーブル名;
exit

2014年11月6日木曜日

Laravel用のライブラリをインストール

Sentryというユーザ管理用のライブラリがあり、そのライブラリの出来がいいらしいので、
試しにインストールしてみる。

Sentryのインストール方法
追加するライブラリ名とバージョンを記載する
$ vi プロジェクト名/composer.json
/* 省略 */
"require": {
    "laravel/framework": "4.1.*", //カンマを忘れずに
    "cartalyst/sentry": "2.1.*" //この行を追加
},
/* 省略 */

編集が終わったらインストール

$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing cartalyst/sentry (v2.1.4)
    Downloading: 100%

cartalyst/sentry suggests installing happydemon/txt (Required Text helpers when using the Kohana implementation)
Writing lock file
Generating autoload files
{"error":{"type":"ErrorException","message":"date_default_timezone_set(): Timezone ID 'JST' is invalid","file":"\/home\/kusagaya\/sites\/n.jp\/test\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/start.php","line":167}}{"error":{"type":"ErrorException","message":"date_default_timezone_set(): Timezone ID 'JST' is invalid","file":"\/home\/kusagaya\/sites\/n.jp\/test\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/start.php","line":167}}

タイムゾーンをJSTに変えていたらエラーが出たので、UTCに戻した。
もっかいアップデート

$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
Generating optimized class loader
Compiling common classes
Compiling views

出来たっぽい。
とりあえずインストール自体は完了。
使い始めたらまた記事にしようと思います。

Laravelのインストール

比較的あたらしめのフレームワークであるLaravelを開発環境にインストールしてみた。

システム要件としては以下の通り。
PHP5.4.0以上
Mcrypt
PDO

さっそくインストールしてみる。
まずはcomposerのインストールから。

インストールコマンドは以下の通り。
$ curl -sS https://getcomposer.org/installer | php
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: /Users/phpuser/tmp/composer.phar
Use it: php composer.phar

あとはパスが通っているディレクトリへ移動させる。
$ sudo mv composer.phar /usr/local/bin/composer

これでcomposerのインストールは完了。

続いてLaravelのインストール、というかプロジェクトの初期化をする。

$ composer create-project laravel-ja/laravel プロジェクト名 --prefer-dist
Installing laravel-ja/laravel (v4.2.8)
  - Installing laravel-ja/laravel (v4.2.8)
    Downloading: 100%

Created project in test
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing symfony/translation (v2.5.5)
    Downloading: 100%

  - Installing symfony/security-core (v2.5.5)
    Downloading: 100%

  - Installing symfony/routing (v2.5.5)
    Downloading: 100%

  - Installing symfony/process (v2.5.5)
    Downloading: 100%

  - Installing psr/log (1.0.0)
    Downloading: 100%

  - Installing symfony/debug (v2.5.5)
    Downloading: 100%

  - Installing symfony/http-foundation (v2.5.5)
    Downloading: 100%

  - Installing symfony/event-dispatcher (v2.5.5)
    Downloading: 100%

  - Installing symfony/http-kernel (v2.5.5)
    Downloading: 100%

  - Installing symfony/finder (v2.5.5)
    Downloading: 100%

  - Installing symfony/dom-crawler (v2.5.5)
    Downloading: 100%

  - Installing symfony/css-selector (v2.5.5)
    Downloading: 100%

  - Installing symfony/console (v2.5.5)
    Downloading: 100%

  - Installing symfony/browser-kit (v2.5.5)
    Downloading: 100%

  - Installing swiftmailer/swiftmailer (v5.3.0)
    Downloading: 100%

  - Installing stack/builder (v1.0.2)
    Downloading: 100%

  - Installing predis/predis (v0.8.7)
    Downloading: 100%

  - Installing phpseclib/phpseclib (0.3.8)
    Downloading: 100%

  - Installing patchwork/utf8 (v1.1.25)
    Downloading: 100%

  - Installing nesbot/carbon (1.13.0)
    Downloading: 100%

  - Installing monolog/monolog (1.11.0)
    Downloading: 100%

  - Installing nikic/php-parser (v0.9.5)
    Downloading: 100%

  - Installing jeremeamia/superclosure (1.0.1)
    Downloading: connection...
Could not fetch https://api.github.com/repos/jeremeamia/super_closure/zipball/d05400085f7d4ae6f20ba30d36550836c0d061e8, enter your GitHub credentials to go over the API rate limit
The credentials will be swapped for an OAuth token stored in /home/username/.composer/auth.json, your password will not be stored
To revoke access to this token you can visit https://github.com/settings/applications
Username: git_username
Password:
Token successfully created
Failed to download jeremeamia/SuperClosure from dist: The "https://api.github.com/authorizations" file could not be downloaded (HTTP/1.1 404 Not Found)
Now trying to download from source
  - Installing jeremeamia/superclosure (1.0.1)
    Cloning d05400085f7d4ae6f20ba30d36550836c0d061e8

  - Installing filp/whoops (1.1.2)
    Downloading: 100%

  - Installing ircmaxell/password-compat (1.0.3)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Downloading: 100%

  - Installing symfony/filesystem (v2.5.5)
    Downloading: 100%

  - Installing classpreloader/classpreloader (1.0.2)
    Downloading: 100%

  - Installing laravel/framework (v4.2.11)
    Downloading: 100%

symfony/translation suggests installing symfony/config ()
symfony/translation suggests installing symfony/yaml ()
symfony/security-core suggests installing symfony/validator (For using the user password constraint)
symfony/security-core suggests installing symfony/expression-language (For using the expression voter)
symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)
symfony/routing suggests installing symfony/yaml (For using the YAML loader)
symfony/routing suggests installing symfony/expression-language (For using expression matching)
symfony/routing suggests installing doctrine/annotations (For using the annotation loader)
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/http-kernel suggests installing symfony/class-loader ()
symfony/http-kernel suggests installing symfony/config ()
symfony/http-kernel suggests installing symfony/dependency-injection ()
predis/predis suggests installing ext-phpiredis (Allows faster serialization and deserialization of the Redis protocol)
phpseclib/phpseclib suggests installing ext-mcrypt (Install the Mcrypt extension in order to speed up a wide variety of cryptographic operations.)
phpseclib/phpseclib suggests installing pear-pear/PHP_Compat (Install PHP_Compat to get phpseclib working on PHP < 4.3.3.)
patchwork/utf8 suggests installing ext-intl (Use Intl for best performance)
patchwork/utf8 suggests installing ext-mbstring (Use Mbstring for best performance)
monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)
monolog/monolog suggests installing raven/raven (Allow sending log messages to a Sentry server)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)
monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)
monolog/monolog suggests installing videlalvaro/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)
monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)
monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)
d11wtq/boris suggests installing ext-posix (*)
laravel/framework suggests installing doctrine/dbal (Allow renaming columns and dropping SQLite columns.)
Writing lock file
Generating autoload files
Mcrypt PHP extension required.
Script php artisan clear-compiled handling the post-install-cmd event returned with an error



  [RuntimeException]
  Error Output:



create-project [-s|--stability="..."] [--prefer-source] [--prefer-dist] [--repository-url="..."] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-scripts] [--no-progress] [--keep-vcs] [--no-install] [package] [directory] [version]

mcryptがないのでエラーになった。
mcryptをインストール。
$ sudo yum install php-mcrypt
もう一回試す。
$ composer create-project laravel-ja/laravel test --prefer-dist
Installing laravel-ja/laravel (v4.2.8)
  - Installing laravel-ja/laravel (v4.2.8)
    Loading from cache

Created project in test2
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing symfony/translation (v2.5.5)
    Loading from cache

  - Installing symfony/security-core (v2.5.5)
    Loading from cache

  - Installing symfony/routing (v2.5.5)
    Loading from cache

  - Installing symfony/process (v2.5.5)
    Loading from cache

  - Installing psr/log (1.0.0)
    Loading from cache

  - Installing symfony/debug (v2.5.5)
    Loading from cache

  - Installing symfony/http-foundation (v2.5.5)
    Loading from cache

  - Installing symfony/event-dispatcher (v2.5.5)
    Loading from cache

  - Installing symfony/http-kernel (v2.5.5)
    Loading from cache

  - Installing symfony/finder (v2.5.5)
    Loading from cache

  - Installing symfony/dom-crawler (v2.5.5)
    Loading from cache

  - Installing symfony/css-selector (v2.5.5)
    Loading from cache

  - Installing symfony/console (v2.5.5)
    Loading from cache

  - Installing symfony/browser-kit (v2.5.5)
    Loading from cache

  - Installing swiftmailer/swiftmailer (v5.3.0)
    Loading from cache

  - Installing stack/builder (v1.0.2)
    Loading from cache

  - Installing predis/predis (v0.8.7)
    Loading from cache

  - Installing phpseclib/phpseclib (0.3.8)
    Loading from cache

  - Installing patchwork/utf8 (v1.1.25)
    Loading from cache

  - Installing nesbot/carbon (1.13.0)
    Loading from cache

  - Installing monolog/monolog (1.11.0)
    Loading from cache

  - Installing nikic/php-parser (v0.9.5)
    Loading from cache

  - Installing jeremeamia/superclosure (1.0.1)
    Downloading: 100%

  - Installing filp/whoops (1.1.2)
    Loading from cache

  - Installing ircmaxell/password-compat (1.0.3)
    Loading from cache

  - Installing d11wtq/boris (v1.0.8)
    Loading from cache

  - Installing symfony/filesystem (v2.5.5)
    Loading from cache

  - Installing classpreloader/classpreloader (1.0.2)
    Loading from cache

  - Installing laravel/framework (v4.2.11)
    Loading from cache

symfony/translation suggests installing symfony/config ()
symfony/translation suggests installing symfony/yaml ()
symfony/security-core suggests installing symfony/validator (For using the user password constraint)
symfony/security-core suggests installing symfony/expression-language (For using the expression voter)
symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)
symfony/routing suggests installing symfony/yaml (For using the YAML loader)
symfony/routing suggests installing symfony/expression-language (For using expression matching)
symfony/routing suggests installing doctrine/annotations (For using the annotation loader)
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/http-kernel suggests installing symfony/class-loader ()
symfony/http-kernel suggests installing symfony/config ()
symfony/http-kernel suggests installing symfony/dependency-injection ()
predis/predis suggests installing ext-phpiredis (Allows faster serialization and deserialization of the Redis protocol)
phpseclib/phpseclib suggests installing pear-pear/PHP_Compat (Install PHP_Compat to get phpseclib working on PHP < 4.3.3.)
patchwork/utf8 suggests installing ext-intl (Use Intl for best performance)
patchwork/utf8 suggests installing ext-mbstring (Use Mbstring for best performance)
monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)
monolog/monolog suggests installing raven/raven (Allow sending log messages to a Sentry server)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)
monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)
monolog/monolog suggests installing videlalvaro/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)
monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)
monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)
d11wtq/boris suggests installing ext-posix (*)
laravel/framework suggests installing doctrine/dbal (Allow renaming columns and dropping SQLite columns.)
Writing lock file
Generating autoload files
PHP Fatal error:  Class 'PDO' not found in /home/username/sites/n.jp/test2/app/config/database.php on line 16
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'PDO' not found","file":"\/home\/username\/sites\/n.jp\/test2\/app\/config\/database.php","line":16}}Script php artisan clear-compiled handling the post-install-cmd event returned with an error



  [RuntimeException]
  Error Output: PHP Fatal error:  Class 'PDO' not found in /home/username/sites/n.jp/test2/app/config/database.php on line 16




create-project [-s|--stability="..."] [--prefer-source] [--prefer-dist] [--repository-url="..."] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-scripts] [--no-progress] [--keep-vcs] [--no-install] [package] [directory] [version]

今度はPDOがないって怒られた
PDOをインストール
$ sudo yum install php-pdo

PDOをインストール後にもう一回
$ composer create-project laravel-ja/laravel test --prefer-dist
Installing laravel-ja/laravel (v4.2.8)
  - Installing laravel-ja/laravel (v4.2.8)
    Loading from cache

Created project in test2
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing symfony/translation (v2.5.5)
    Loading from cache

  - Installing symfony/security-core (v2.5.5)
    Loading from cache

  - Installing symfony/routing (v2.5.5)
    Loading from cache

  - Installing symfony/process (v2.5.5)
    Loading from cache

  - Installing psr/log (1.0.0)
    Loading from cache

  - Installing symfony/debug (v2.5.5)
    Loading from cache

  - Installing symfony/http-foundation (v2.5.5)
    Loading from cache

  - Installing symfony/event-dispatcher (v2.5.5)
    Loading from cache

  - Installing symfony/http-kernel (v2.5.5)
    Loading from cache

  - Installing symfony/finder (v2.5.5)
    Loading from cache

  - Installing symfony/dom-crawler (v2.5.5)
    Loading from cache

  - Installing symfony/css-selector (v2.5.5)
    Loading from cache

  - Installing symfony/console (v2.5.5)
    Loading from cache

  - Installing symfony/browser-kit (v2.5.5)
    Loading from cache

  - Installing swiftmailer/swiftmailer (v5.3.0)
    Loading from cache

  - Installing stack/builder (v1.0.2)
    Loading from cache

  - Installing predis/predis (v0.8.7)
    Loading from cache

  - Installing phpseclib/phpseclib (0.3.8)
    Loading from cache

  - Installing patchwork/utf8 (v1.1.25)
    Loading from cache

  - Installing nesbot/carbon (1.13.0)
    Loading from cache

  - Installing monolog/monolog (1.11.0)
    Loading from cache

  - Installing nikic/php-parser (v0.9.5)
    Loading from cache

  - Installing jeremeamia/superclosure (1.0.1)
    Loading from cache

  - Installing filp/whoops (1.1.2)
    Loading from cache

  - Installing ircmaxell/password-compat (1.0.3)
    Loading from cache

  - Installing d11wtq/boris (v1.0.8)
    Loading from cache

  - Installing symfony/filesystem (v2.5.5)
    Loading from cache

  - Installing classpreloader/classpreloader (1.0.2)
    Loading from cache

  - Installing laravel/framework (v4.2.11)
    Loading from cache

symfony/translation suggests installing symfony/config ()
symfony/translation suggests installing symfony/yaml ()
symfony/security-core suggests installing symfony/validator (For using the user password constraint)
symfony/security-core suggests installing symfony/expression-language (For using the expression voter)
symfony/routing suggests installing symfony/config (For using the all-in-one router or any loader)
symfony/routing suggests installing symfony/yaml (For using the YAML loader)
symfony/routing suggests installing symfony/expression-language (For using expression matching)
symfony/routing suggests installing doctrine/annotations (For using the annotation loader)
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/http-kernel suggests installing symfony/class-loader ()
symfony/http-kernel suggests installing symfony/config ()
symfony/http-kernel suggests installing symfony/dependency-injection ()
predis/predis suggests installing ext-phpiredis (Allows faster serialization and deserialization of the Redis protocol)
phpseclib/phpseclib suggests installing pear-pear/PHP_Compat (Install PHP_Compat to get phpseclib working on PHP < 4.3.3.)
patchwork/utf8 suggests installing ext-intl (Use Intl for best performance)
patchwork/utf8 suggests installing ext-mbstring (Use Mbstring for best performance)
monolog/monolog suggests installing graylog2/gelf-php (Allow sending log messages to a GrayLog2 server)
monolog/monolog suggests installing raven/raven (Allow sending log messages to a Sentry server)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages to a CouchDB server)
monolog/monolog suggests installing ruflin/elastica (Allow sending log messages to an Elastic Search server)
monolog/monolog suggests installing videlalvaro/php-amqplib (Allow sending log messages to an AMQP server using php-amqplib)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an AMQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a MongoDB server)
monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages to AWS services like DynamoDB)
monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages to Rollbar)
d11wtq/boris suggests installing ext-posix (*)
laravel/framework suggests installing doctrine/dbal (Allow renaming columns and dropping SQLite columns.)
Writing lock file
Generating autoload files
Generating optimized class loader
Compiling common classes
Compiling views
Application key [XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX] set successfully.

出来た。

インストール完了後は
プロジェクトルート/app/storage
のパーミッションを777に変更する

$ chmod -R 777 app/storage

app/storageの権限を変えていない場合、「Error in exception handler.」と表示される。

これらの作業が完了後にサイトを確認してみると、
「You have arrived.」というページが表示されている

Laravelは2回目以降のインストールはキャッシュから読み込むようになっているので、
一回サーバ内でインストールしておけば、毎回プロジェクトを作るたびにダウンロードする必要はない。
キャッシュはプロジェクトとは関係ない場所に保存されているので、Laravelのプロジェクトを全部消したとしても、
インストールに影響はない。

一番最初に行うのは、アプリケーションとデータベースの設定。
app/config/app.phpに書かれているArtisan(アルチザン)はコマンドラインインターフェイス。
app/config/database.phpには、SQL別に設定が書けるようになっている。とりあえず自分の使うタイプであるMySQL部分の設定だけ変更。

Vagrantでmountに失敗した時の対処方法

Vagrant経由でVirtualBoxを起動しようとしたら、下記のようなエラーが。

$ vagrant up

Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:
mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` vagrant /vagrant
The error output from the last command was:
/sbin/mount.vboxsf: mounting failed with the error: No such device

セットアップとかいろいろやっていたので、
どの作業がこういった現象に結びついたかは不明。。。
調べたらとりあえずvboxをリビルドする必要があるらしい。

まずはCygwin上で

$ vagrant ssh

vagrant sshでログインした後に

[vagrant@localhost ~]$ sudo /etc/init.d/vboxadd setup
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  ]

vagrantを再起動

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

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> 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: Warning: Remote connection disconnect. 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/virtualBox_CentOS

解決!
先ほどのエラーはでなくなりました。

2014年10月29日水曜日

MongoDBをCentOS6.4にインストールから起動、PHPで利用するまで

1.リポジトリの追加(64bitの場合)
$ sudo vi /etc/yum.repos.d/mongodb.repo

[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1

32bit版の場合はURLの「x86_64」を「i686」に書き換えれば出来る。
2.yumコマンドでインストール
$ sudo yum install mongodb-org


3.起動
$ sudo /etc/init.d/mongod start
Starting mongod:                                           [FAILED]


4.起動失敗した原因を調べる
sudo view /var/log/mongodb/mongod.log

2014-10-29T11:58:37.248+0900 [initandlisten] ERROR: Insufficient free space for journal files
2014-10-29T11:58:37.248+0900 [initandlisten] Please make at least 3379MB available in /var/lib/mongo/journal or use --smallfiles

どうやら原因はディスクの空きが足りないことらしい。
調べてみると、MongoDBのデフォルト設定ではジャーナルファイルというものを作るようになっており、 そのファイルを作成するにあたって3.5GB近い空き容量が必要になるみたいです。
なので、自分のサーバの空き容量を確認してみます。

5.自分のサーバの空き容量を調べる。
$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda1             7.9G  5.2G  2.4G  69% /
tmpfs                 499M     0  499M   0% /dev/shm

確かに容量が足りていなかった。
容量追加しないといけないのかとも思ったが、ジャーナルファイルなるものは開発環境では特に必要ないんじゃないかということで、このファイルを作成しないように設定を変えました。

6.ジャーナルファイルを生成しないように設定を変える
$ vi /etc/mongod.conf

# Disables write-ahead journaling
# nojournal=true
       ↓
# Disables write-ahead journaling
nojournal=true

7.再度起動させてみる
$ sudo /etc/init.d/mongod stop
Stopping mongod:                                           [  OK  ]

無事起動しました。

続いてPHPで使用出来るようにします。
まずインストールに必要なものをあらかじめインストールしておきます。
$ sudo yum -y install gcc php-pear php-devel

続いてpecl経由でmongoのExtentionをインストール
途中で質問があるが、そのままEnterでOK。
$ sudo pecl install mongo
WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
downloading mongo-1.5.6.tgz ...
Starting to download mongo-1.5.6.tgz (193,219 bytes)
.........................................done: 193,219 bytes
116 source files, building
running: phpize
Configuring for:
PHP Api Version:         20100412
Zend Module Api No:      20100525
Zend Extension Api No:   220100525
Build with Cyrus SASL (MongoDB Enterprise Authentication) support? [no] :Enter
building in /var/tmp/pear-build-roottRXj7r/mongo-1.5.6

mongo用にiniファイルを新規作成
$ sudo vi /etc/php.d/mongo.ini
extension=mongo.so ← これを書く

apacheを再起動させます。
$ sudo /etc/init.d/httpd restart

mongoが使用出来る状態になっているか確認します。
下記のように「mongo」と出てきたら成功です。
$ php -m | grep -i mongo
mongo


おまけ
ジャーナルファイルに関して調べてみました。
ここでは簡単にしか記載しませんが、ざっくりとまとめると、

・Mongoは書き込み処理の結果を気にしないので、高速に書き込める。
・Mongoは、まずメモリ上に スタックされ、60秒に1回の間隔でディスクに書き込む。
・ディスクに書き込まれていないデータは、サーバダウンによって消えるため、最大60秒間のデータを失う可能性がある。
・ver1.7までの対応策として用意されている機能は2つあるが、いずれもパフォーマンスを著しく低下させるものである。
・ver1.8にジャーナリング機能が実装され、100ミリ秒に1回ジャーナルファイルに書き込むことで、データ損失のリスクが低減された。しかしパフォーマンスはある程度低下する(30%程度)

ジャーナルファイルに関しては以下の記事に詳しく書いてある。
http://doryokujin.hatenablog.jp/entry/20110614/1308010072

2014年8月13日水曜日

Macを指定した時間に起動・スリープ・再起動・システム終了する方法

よる寝る前に結構大きめのファイルをダウンロードしはじめて、そのまま朝までつけっ放しということがよくあったのですが、電気代が勿体無いので設定した時間にシャットダウン出来ないか調べてみたらありました。

・出来る事
設定出来るスケジュールは2つまでで、「起動、スリープ解除」で1つ。「スリープ、再起動、システム終了」で1つと最初から決まっている。
選択出来るスケジューリングは毎日、平日、休日、曜日毎の指定した時間(1分単位)。

・設定方法
1.りんごマーク→システム環境設定→省エネルギーを選択
2.省エネルギーページの一番右下にあるスケジュールボタンを押下
3.やりたい行動にチェックを付けて、曜日と時間を選択すれば完了。

※注意点
シャットダウンとか選んでいる時に、アプリ終了時に「終了しますか?」とか選択肢がある場合のアプリが起動していると、それのせいでシャットダウンしないことがあるので注意が必要。

2014年7月8日火曜日

Macで同一アプリでの画面切り替え

MacはWindowsの様にAlt + Tabでウィンドウ切り替えを行おうとすると、同一アプリケーションで複数ウィンドウ開いている場合に対応出来ない。
Windowsは立ち上がっているウィンドウをAlt + Tabで切り替えられるが、Macはcommand + Tabでアプリケーションを切り替えるようになっている。
アプリケーション内の複数ウィンドウを切り替える場合にはcommand + F1を押す必要がある。
若干遠いので、Option + Tabに設定を変更することにした。

1.リンゴマーク→システム環境設定→キーボードを選択
2.キーボード内のショートカットタブをクリック
3.左側の一覧の中の「キーボード」を選択
4.「次のウィンドウを操作対象にする」の右側のキー入力部分を選択
5.変更したいキーを入力

以上で完了。
とりあえず別アプリのショーットカットとかと競合しないことを祈る。

2014年5月20日火曜日

プログラミング作法(名前の付け方編)

プログラムを書いている時によく頭を悩ますのが変数や関数等々の名前の付け方。
Google翻訳みたいな感じで最適な名前を返してくれるサービスが欲しいと何度思ったことか。

「名前は情報を含み、簡潔で覚えやすく、できれば発音可能な名前が望ましい。」

とか言われても正直そんないい名前ほいほい思いつかないです。
でも、訓練次第ではいい名前が付けられるようになると思うので、自戒の意味を込めて記載しておきます。

1.グローバルとローカルの名前の付け分け


「グローバルにはわかりやすい名前を、ローカルには短い名前をつける。」

グローバル変数は定義上プログラムのどこにでも出現する可能性があるため、読む人がその意味を思い出せる程度に長く、説明的な名前をつける必要がある。
個々のグローバル変数の宣言に短いコメントを入れておくとよい。
変数だけでなく、グローバルな関数、クラス、構造体にも、プログラム中での役割を表す説明的な名前をつける必要がある。

逆にローカル変数は短い名前で十分。
あまり長い名前は逆にプログラムの可読性を下げる。

2.統一性を出し、コードを文章に


「関連性のあるものには関連性のある名前をつけ、関係を示すと共に違いを際立たせるようにする。」

class UserQueue {
    int noOfItemsInQ, frontOnTheQueue, queueCapacity;
    public int noOfUsersInQueue() {…}
}

上記のプログラムではQueueという単語がQ、Queue、queueとして登場している。
しかしキューはUserQueue型の変数からしかアクセス出来ないので、メンバ名に"queue"を入れる必要はない。
文脈だけで十分に理解出来るので、下記の文は冗長である。
queue.queueCapacity

そのため、下記のプログラムの方が優れていると言える。
class userQueue {
    int nitems, front, capacity;
    public int nusers() {…}
}

このように記述することで、下記のように文を書けるようになる。
queue.capacity++;
n = queue.nusers();

3.関数名の付け方


「関数には能動的な名前をつけ、問題がなければそのあとに名詞をつける。」

now = date.getTime();
putchar('¥n');

ブール値を返す場合は、戻り値が不明確にならないような名前をつける必要がある。
わかりにくい
if (checkoctal(c)) ...

わかりやすい
if (isoctal(c))...

とりあえず今回はここまで。
今後もこの内容を意識してプログラミングしていきたいと思います。

2014年5月19日月曜日

Parallels上のWindowsマシンでGoogleIMEのON/OFF切り替え

MacOSでは、日本語入力と英字入力をそれぞれ「かな」キーと「英数」キーに割り当てられている。
しかし、Parallels上のWindowsで「かな」キーと「英数」キーを押すと、MacOSと同様の挙動はしてくれない。
そこでMacOSと同様に「かな」キーと「英数」キーで日本語入力と英字入力を切り替える方法のメモ。

1.Parallels上のWindows環境で、テキストサービスと入力言語画面を開く。(言語バー内で右クリック→設定)
2.全般タブの「Google日本語入力」を選択し、プロパティボタンを押下。

2014年5月16日金曜日

MacOSのプレビュー機能でアクセス権があるのに開けない(未解決)

Macで画像を大量に開く場合、フォルダ内の全画像を選択してダブルクリックで開くのですが、この作業を続けていると

「ファイル”XXXXXX”を表示するためのアクセス権がないため、開けませんでした。」

と出てくる。
以前から何度か経験している現象だ。

・パーミッションに問題がないにも関わらず、画像が開けない。
・別のアプリを使って画像を開くことは可能。

以上の2点から画像自体に問題はなさそう。
では何が問題なのか?
最初は普通に開けるので、メモリの問題かと思って検証してみた。
以下の1〜4の手順を繰り返し行う。
なお、以下の手順の間はプレビューアプリ自体は起動しっぱなし。

1.200枚くらいの画像をまとめて開く。
2.ウィンドウを閉じる。
3.同じ画像200枚をまとめて開く。
4.ウィンドウを閉じる。

これに関しては問題なかった。
最初に全ての画像を開くのにかかった時間と、
2回目以降に全ての画像を開くのにかかった時間では、明らかに2回目以降の方が早かった。
普通に考えたら最近開いた画像に関してはキャッシュか何かしているんだろうと想像出来る。
では次に毎回違う画像を開いて見たらどうか検証してみた。
以下の1〜4の手順を繰り返し行う。
なお、以下の手順の間はプレビューアプリ自体は起動しっぱなし。

1.200枚くらいの画像をまとめて開く。
2.ウィンドウを閉じる。
3.違う画像200枚をまとめて開く。
4.ウィンドウを閉じる。

結果1912枚の画像を開くことが出来たが、1913枚目からは全て開けなかった。
以降プレビューアプリでは1枚も画像が開けなかった。

アクティビティモニタでメモリの使用量とかを確認してみたが、
画像を大量に開いたからといって、メモリ使用量が増えているわけではなかった。
現在の所、原因は不明だが、プレビューアプリを再起動するとまた問題なく見れるようになる。

普通に考えるとプレビューアプリにキャッシュ出来る画像容量に達したから開けなくなったのかと思ったのですが、アクティビティモニタを見た限りではそうじゃないらしい。

謎。

2014年2月8日土曜日

アクセサメソッド

Objective-Cに限らず、オブジェクト指向言語では外部からクラスのインスタンス変数に直接アクセスすることはしません。
一般的にはインスタンス変数の値の取得や、設定にはアクセス用のメソッドを作成し、使用します。
このアクセス用のメソッドのことをアクセサメソッドと呼びます。
また、取得用のメソッドをgetter、設定用のメソッドをsetterと呼びます。

getterの作り方
getterを作成するにはインスタンス変数と同じ名前のメソッドを定義します。 例えばint型の「hoge」というインスタンス変数に対応するgetterを作成するには以下のように記述します。
// ヘッダファイル(XXXX.h)
- (int)hoge;
 
// 実装ファイル(XXXX.m)
- (int)hoge
{
    return hoge;
}


setterの作り方
setterを作成するにはインスタンス変数と同じ名前の前にsetを付けた名前のメソッドを定義します。
// ヘッダファイル(XXXX.h)
- (void)setHoge:(int)value;

//実装ファイル(XXXX.m)
- (void)setHoge:(int)value
{
    hoge = value;
}


アクセサへのアクセス方法
定義したアクセサへアクセスするためにはC言語の構造体のメンバへのアクセスのように,ドット演算子(.)を使用します。
例えば「myClass」というクラスのインスタンスの「hoge」というアクセサにアクセスするには以下のように記述します。

// getterを利用して値を取得している
int intHoge = myClass.hoge;
 
// setterを利用して値を設定している
myClass.hoge = 10;

// 通常の関数として利用することも可能
[myClass setHoge:10]


ここで1つ注意点。
setterはsetHogeというメソッドで用意したのですが、実際に使用する場合はインスタンス名にインスタンス変数名をドット演算子で繋いでいるだけという点。
ちなみに普通の関数として利用することも出来るので、上記の例のようにメッセージ式の書き方で記述することで、setterを利用することが出来る。(面倒ですが・・・)
ここまで書いて初めてPHPとかJavascriptの様に、クラスを作ってインスタンス変数にアクセスすることが出来るようになる。
Objective-Cってなんて面倒くさいんだと思った方はたくさんいると思います。
こんな面倒なことがそのままにされているはずがありません。
Objective-C2.0からはちゃんと自動で生成してくれるための機能が用意されています。
その機能というのがプロパティなのですが、それは次回にしたいと思います。

2014年2月7日金曜日

EmEditor Pro版からFree版へ変更する方法

EmEditorのPro(有償)版からFree(無償)版へとダウングレードする方法のメモ。
最近のEmEditorはPro版とFree版が同じインストーラーで配布されており、インストールするとPro版がインストールされる。
評価版なので、アプリを起動する度に、買うか評価版として使い続けるかのメッセージが出てくるのが嫌だったので、早々にFree版にダウングレードする。
やり方は以下の通り。

1.EmEditorを起動
2.メニュー欄のツール→クイック起動を選択
3.クイック起動画面左上の検索欄でダウングレードと検索するか、リスト上から分類「ヘルプ」のコマンド「ダウングレード」を探す。
4.リスト上のコマンド「ダウングレード」をダブルクリック。
5.確認メッセージが出てくるので、「はい」を選択。

以上でダウングレード完了。

2014年2月6日木曜日

Objective-Cのクラス周りの書き方

Objective-Cの勉強を始めたものの、今までPHPやJSしかやってこなかった自分にとってはとても分かりにくい書き方だった。
演算子とか条件分岐やループ処理といった部分に関しては、今までやってきた言語同様の書き方だったが、クラス関連の書き方が全然違ったので激しく違和感を感じるとともに、慣れていないので非常に書きづらい。
忘れそうなので、ここにまとめておく。

ファイル構造
ヘッダファイル及び実装ファイルのファイル内の構造は以下の通り。

ヘッダファイルのファイル構造
#import <フレームワーク/ファイル>
#import ソースファイル

@interface クラス名;スーパークラス名 <プロトコル>
{
    インスタンス変数宣言;
}
プロパティ宣言;
メソッド宣言;
@end

実装ファイルのファイル構造
#import ヘッダファイル

@interface クラス名() <プロトコル>
{
    インスタンス変数宣言;
}
プロパティ宣言;
メソッドの定義;
@end

@implementation クラス名
メソッド定義;
@end

クラスの宣言
  • クラス宣言は必ず必要
  • クラス宣言はヘッダファイル(XXX.h)に記載する
  • 親クラスは必ず指定しておく(継承すべき親クラスがない場合はNSObjectクラスを指定)
※継承すべき親クラスがない場合にNSObjectクラスを指定する理由は、オブジェクトのしての振る舞いをするために必要な機能がこのクラスに書かれているため。
そのため、用意されている全てのクラスはこのNSObjectクラスが基底クラスとなっている。

書き方
@interface クラス名:親クラス{
    インスタンス変数の定義
}

メソッドの定義

@end

インスタンス変数のスコープの種類 Objective-Cのスコープの種類は以下の3種類で、他の言語と同様。
スコープを省略した場合は自動的にprotectedになる。
  • @private 宣言したクラス内からのみアクセス可能
  • @protected 宣言したクラス内及び継承されたサブクラスからアクセス可能(デフォルト)
  • @public どこからでもアクセス可能

クラスメソッドとインスタンスメソッドの書き分け
  • +から書き出した場合はクラスメソッド
  • -から書きだした場合はインスタンスメソッド
クラスメソッドの書き方
+(返り値のデータ型)メソッド名
クラスメソッドの書き方(引数あり)
+(返り値のデータ型)メソッド名:(引数1のデータ型)引数1 ラベル2:(引数2のデータ型)引数2 ・・・

インスタンスメソッドは先頭の+を-に変更するだけなので省略。
ここまでが主にヘッダファイルに記載する内容。

以下は簡単なサンプル
@interface myClass:NSObject {
    NSInteger aaa; //自動的にprotectedとなる
    @private NSString *bbb;
    @protected BOOL isTrue;
    @public NSString *ddd;
}

+(void)myClassMethod;
-(void)myInstanceMethod;
@end



クラスの実装
  • クラスの実装は必ず実装ファイル(XXX.m)に書く

書き方
#import "クラス名.h";

@implementation クラス名
    ヘッダファイルで宣言したメソッドの実装コード
@end

以下は簡単なサンプル
#import myClass.h;

@implementation myClass

+(void)myClassMethod
{
    NSLog(@"myClassMethod");
}

-(void)myInstanceMethod
{
    NSLog(@"myInstanceMethod");
}

@end



クラスのインスタンス化及び初期化
  • クラスのインスタンス化を行った後に初期化をする。
  • インスタンス化にはNSObjectに定義されているallocメソッドを使う。
  • 初期化にはNSObjectに定義されているinitメソッドを使う。
書き方
変数 = [[クラス名 alloc]init];

以下は簡単なサンプル
MyClass *myClass = [[myClass alloc]init];

以上がクラスの基本的な書き方や使い方。
以下は書いてて気持ち悪かった部分。

クラスメソッドを実行したい場合
[オブジェクト メソッド名];

例)
[myClass myfunc];


クラスメソッドを実行したい場合(引数が1つ)
[オブジェクト メソッド名:引数];

例)
[myObj myfunc:a];


クラスメソッドを実行したい場合(引数が複数)
[オブジェクト メソッド名:引数1 ラベル2:引数2 ラベル3:引数3・・・];

例)
[myObj myfunc:a label2:b label3:c];

※尚、ここに記載されているのはクラスメソッドを実行したい場合で、インスタンスメソッドを実行する場合はインスタンス化して初期化してから下記の書き方でメソッドを実行して下さい。

この書き方だが、メッセージ式の書き方らしい。
[〜]の間で1つのメッセージとして判断される。
1つ納得いかない点は引数の1つ目のラベルがメソッド名になってしまう点だ。
なんか気持ち悪いけど慣れていくしかないか・・・。