page_adsence

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))...

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