page_adsence

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枚も画像が開けなかった。

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

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

謎。