StupidDog's blog

IT関連の手近な所で、疑問に思った事を調べた記録

「ubuntu12.10+tmux+vim、できるだけ少ない手順で256色表示にする」

はじめに

GNOMEのターミナルでVimを使用して256色表示を行っていました。
tmuxの記事のスクリーンショットを見て、これは…と、導入したら256色表示がされない。
あまり時間をかけたくないので、設定でどうにかならないかと探した結果です。

条件

「tmuxをインストールする前に、GNOMEのターミナルとVimで256色表示を行えている」

一応、自身の環境では以下の設定で256色表示させてます。

  • 環境変数「TERM」が「xterm」
  • 「~/.vimrc」で「set t_Co=256」を記述

解決のために行ったこと

「.bashrc」に「alias tmux='tmux -2'」を追加しました。

解決までの経緯

「.tmux.conf」でオプションを設定する方法が見つかったが、
「set-option -g default-screen screen-256color」としても256色表示はできなかった。
「screen」をインストールしてみたが状況は変わらず。
tmuxの起動オプションを調べていたら、tmuxに端末が256色サポートしていると強制的に指定するオプションがあったので試したところ256色となりました。
毎回、オプションを指定するのは大変なのでエイリアス設定をしています。

まとめ

追加したのはエイリアスだけ。

「Vagrantの裏方では何が作られているのか?」

はじめに

Vagrant仮想マシンを作成しつつRuby on Rails開発環境を構築していました。
Vagrantの本家サイトのガイドに従って作成していたのですが、各コマンドが自分の環境にどんな変化を与えるのかが知りたくなりました。
コマンドで状態を確認する方法はあるのですが、どこに何のファイルが、いつ作られるのかが気になり、作成されるファイルを中心に調べてみた結果が以下の通りです。

概要

環境
software version
Ubuntu(ホストOS) 12.10 LTS 32bit
Ubuntu(ゲストOS) 13.10 Server 32bit
VirtualBox 4.3.6.r91406
Vagrant 1.4.3
項目
  1. "vagrant box add"は何をする?
  2. "vagrant init"は何をする?
  3. "vagrant up"は何をする?
  4. おまけ

1."vagrant box add"は何をする?

$ vagrant box add <name> <url>

このコマンドで、論理名とBOXファイルの場所(ローカルならパス,リモートならURL)を指定してBOXファイルを追加する。
追加するとはどうなることか、論理名ってなんの名前か?

BOXファイルは仮想マシンのひな型となるファイルを配布可能な状態にまとめたものです。
vagrantは、まとめられたBOXファイルから直接には仮想マシンを作成しません。
一度、ローカルへ展開してキャッシュしたものを使います。
指定した論理名とは、このキャッシュしたBOXファイルを識別するために付ける名前です。

キャッシュされているBOXファイルはどこに保存されているのか?
「~/.vagrant.d/boxes」以下にディレクトリが作成されて保存されます。

実際に実行して結果を確認すると、<name>/<provider>*1でサブディレクトリが作成されてBOXファイルの中身が展開されているのが分かります。

stupiddog@pc02:~$ vagrant box add ubuntu1310 ~/Downloads/box/ubuntu-1310-i386-virtualbox-puppet.box
Downloading box from URL: file:/home/stupiddog/Downloads/box/ubuntu-1310-i386-virtualbox-puppet.box
Extracting box...te: 59.0M/s, Estimated time remaining: 0:00:01)
Successfully added box 'ubuntu1310' with provider 'virtualbox'!

stupiddog@pc02:~$ tree -aFh ~/.vagrant.d/boxes
/home/stupiddog/.vagrant.d/boxes/
└── [4.0K]  ubuntu1310/
    └── [4.0K]  virtualbox/
        ├── [ 258]  Vagrantfile
        ├── [ 11K]  box.ovf
        ├── [ 120]  info.json
        ├── [  26]  metadata.json
        └── [400M]  ubuntu1310-i386-disk1.vmdk

2 directories, 5 files

stupiddog@pc02:~$ vagrant box list
ubuntu1310 (virtualbox)

※ BOXファイルは毎回ネットから取得すると大変なので、先にダウンロードしています。

2."vagrant init"は何をする?

仮想マシンを作成するための準備をします…何をするの?
設定ファイル(Vagrantfile)のひな型を、このコマンドを実行したカレントディレクトリに作成します。
なので、管理単位で新規にディレクトリを作成して実行します。

実行した結果が以下の通りです。

stupiddog@pc02:~$ mkdir -p ~/vm/z001; cd ~/vm/z001
stupiddog@pc02:~/vm/z001$ ls -a
.  ..
stupiddog@pc02:~/vm/z001$ vagrant init ubuntu1310
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

stupiddog@pc02:~/vm/z001$ tree -aFh ~/vm/z001
/home/stupiddog/vm/z001
└── [4.5K]  Vagrantfile

0 directories, 1 file

まだ、この段階では仮想マシンは構築されていません。
VirtualBox仮想マシンは、「~/VirtualBox VMs/」以下にサブディレクトリが作成されて保存されます。

stupiddog@pc02:~/vm/z001$ vboxmanage list vms
stupiddog@pc02:~/vm/z001$

stupiddog@pc02:~/vm/z001$ tree -aFh ~/VirtualBox VMs/
/home/stupiddog/VirtualBox VMs/

0 directories, 0 files

stupiddog@pc02:~/vm/z001$ vagrant status
Current machine states:

default                   not created (virtualbox)

The environment has not yet been created. Run `vagrant up` to
create the environment. If a machine is not created, only the
default provider will be shown. So if a provider is not listed,
then the machine is not created for that environment.

んむ、"not created"です。

3."vagrant up"は何をする?

このコマンドの初回起動時に、仮想マシンが構築されます。
"vagrant init <name>"で作成した設定ファイルの「config.vm.box=<name>」から、ひな型にするBOXファイルのキャッシュを決定して仮想マシンを構築します。

実行した結果が以下の通りです。

stupiddog@pc02:~/vm/z001$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Importing base box 'ubuntu1310'...
[default] Matching MAC address for NAT networking...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Booting VM...
[default] Waiting for machine to boot. This may take a few minutes...
[default] Machine booted and ready!
[default] Mounting shared folders...
[default] -- /vagrant

stupiddog@pc02:~/vm/z001$ vagrant status
Current machine states:

default                   running (virtualbox)

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

stupiddog@pc02:~/vm/z001$ vboxmanage list vms
"z001_default_1392779981693_33350" {52c768b7-4c06-4a1e-95a1-0b7d885bbdac}

stupiddog@pc02:~/vm/z001$ tree -aFh ~/VirtualBox VMs/
/home/stupiddog/VirtualBox VMs/
└── [4.0K]  z001_default_1392779981693_33350/
    ├── [4.0K]  Logs/
    │   └── [ 42K]  VBox.log
    ├── [1.2G]  ubuntu1310-i386-disk1.vmdk
    ├── [7.6K]  z001_default_1392779981693_33350.vbox
    └── [7.6K]  z001_default_1392779981693_33350.vbox-prev

2 directories, 4 files

stupiddog@pc02:~/vm/z001$ tree -aFh ~/vm/z001/
/home/stupiddog/vm/z001/
├── [4.0K]  .vagrant/
│   └── [4.0K]  machines/
│       └── [4.0K]  default/
│           └── [4.0K]  virtualbox/
│               ├── [  10]  action_provision
│               ├── [  10]  action_set_name
│               └── [  36]  id
└── [4.5K]  Vagrantfile

4 directories, 4 files

カレントディレクトリに管理用の隠しディレクトリ(.vagrant)が作成されています。
また、仮想マシンのファイルも「~/VirtualBox VMs/」に作成されています…仮想マシンの名前にカレントディレクトリ名が付いていますね。

4.おまけ

作成した結果は分かったので、削除した結果も追ってみました。

ひな型から構築した仮想マシンより先に、キャッシュされているBOXファイルを消すと仮想マシンの削除が Vagrantからできなくなるので注意です

2014.2.27 訂正
"vagrant destroy"による削除時に、元になったBOXファイルがなくても仮想マシンの削除できました。検証ミスです。

まず、仮想マシンを削除します。
「~/VirtualBox VMs/」以下にあった仮想マシンのディレクトリが削除されています。
"vagrant status"の結果も"no created"になってますが、カレントの管理用ディレクトリは残ってます。

[default] Attempting graceful shutdown of VM...
stupiddog@pc02:~/vm/z001$ vagrant destroy
Are you sure you want to destroy the 'default' VM? [y/N] y
[default] Destroying VM and associated drives...

stupiddog@pc02:~/vm/z001$ vagrant status
Current machine states:

default                   not created (virtualbox)

The environment has not yet been created. Run `vagrant up` to
create the environment. If a machine is not created, only the
default provider will be shown. So if a provider is not listed,
then the machine is not created for that environment.

stupiddog@pc02:~/vm/z001$ vboxmanage list vms 
stupiddog@pc02:~/vm/z001$ 

stupiddog@pc02:~/vm/z001$ tree -aFh ~/VirtualBox VMs/
/home/stupiddog/VirtualBox VMs/

0 directories, 0 files

stupiddog@pc02:~/vm/z001$ tree -aFh ~/vm/z001/
/home/stupiddog/vm/z001/
├── [4.0K]  .vagrant/
│   └── [4.0K]  machines/
│       └── [4.0K]  default/
│           └── [4.0K]  virtualbox/
└── [4.5K]  Vagrantfile

4 directories, 1 file

次に、キャッシュしているBOXファイルを削除します。
結果は「~/.vagrant/boxes」以下に作成されてたサブディレクトリは残り中身だけが削除されました。
でも、"vagrant box list"コマンドでリストされないので、実行時に見ているのはディレクトリの有無だけではないようです。

stupiddog@pc02:~/vm/z001$ vagrant box remove ubuntu1310
Removing box 'ubuntu1310' with provider 'virtualbox'...

stupiddog@pc02:~/vm/z001$ vagrant box list
There are no installed boxes! Use `vagrant box add` to add some.

stupiddog@pc02:~/vm/z001$ tree -aFh ~/.vagrant.d/boxes/
/home/stupiddog/.vagrant.d/boxes/
└── [4.0K]  ubuntu1310/

1 directory, 0 files
さて、キャッシュのBOXファイルが無い状態で"Vagrant up"をしたらどうなるか?

当然、エラーとなります。

stupiddog@pc02:~/vm/z001$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
There are errors in the configuration of this machine. Please fix
the following errors and try again:

vm:
* The box 'ubuntu1310' could not be found.

しかし、設定ファイルの「Vagrantfile」にある「config.vm.box_url」パラメータを有効にして<url>を設定すると"vagrant up"の実行時にBOXファイルの追加を行い仮想マシンの構築まで行ってくれます。

VAGRANTFILE_API_VERSION = "2"
 
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "ubuntu1310"
  config.vm.box_url = "~/Downloads/box/ubuntu-1310-i386-virtualbox-puppet.box"
end

設定ファイルを上記の設定にしてから"vagrant up"を実行した結果が以下の通りです。

stupiddog@pc02:~/vm/z001$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Box 'ubuntu1310' was not found. Fetching box from specified URL for
the provider 'virtualbox'. Note that if the URL does not have
a box for this provider, you should interrupt Vagrant now and add
the box yourself. Otherwise Vagrant will attempt to download the
full box prior to discovering this error.
Downloading box from URL: file:/home/stupiddog/Downloads/box/ubuntu-1310-i386-virtualbox-puppet.box
Extracting box...te: 59.7M/s, Estimated time remaining: --:--:--)
Successfully added box 'ubuntu1310' with provider 'virtualbox'!
[default] Importing base box 'ubuntu1310'...
[default] Matching MAC address for NAT networking...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Booting VM...
[default] Waiting for machine to boot. This may take a few minutes...
[default] Machine booted and ready!
[default] Mounting shared folders...
[default] -- /vagrant

stupiddog@pc02:~/vm/z001$ vboxmanage list vms
"z001_default_1392781885035_69804" {bfe3c1d7-a02e-405a-ad0d-10d8b9094463}

stupiddog@pc02:~/vm/z001$ tree -aFh ~/VirtualBox VMs/
/home/stupiddog/VirtualBox VMs/
└── [4.0K]  z001_default_1392781885035_69804/
    ├── [4.0K]  Logs/
    │   └── [ 42K]  VBox.log
    ├── [1.2G]  ubuntu1310-i386-disk1.vmdk
    ├── [7.6K]  z001_default_1392781885035_69804.vbox
    └── [7.6K]  z001_default_1392781885035_69804.vbox-prev

2 directories, 4 files
stupiddog@pc02:~/vm/z001$ vagrant box list
ubuntu1310 (virtualbox)
stupiddog@pc02:~/vm/z001$ tree -aFh ~/.vagrant.d/boxes/
/home/stupiddog/.vagrant.d/boxes/
└── [4.0K]  ubuntu1310/
    └── [4.0K]  virtualbox/
        ├── [ 258]  Vagrantfile
        ├── [ 11K]  box.ovf
        ├── [ 106]  info.json
        ├── [  26]  metadata.json
        └── [400M]  ubuntu1310-i386-disk1.vmdk

2 directories, 5 files

仮想マシンのファイルだけでなく、BOXファイルのキャッシュも作成されています。
この方法が、「vagrant init 」で作成した設定ファイルからの仮想マシン構築の動作と同じになります。
キャッシュが既にある場合は、BOXファイルの追加は行われません。

まとめ

"vagrant box add"や"vagrant init"、"vagrant up"が何をするために何を作るのかが分かりました。
仮想マシン構築までにローカルに作成されるファイルが明確になったので、意識しながらコマンドを実行できます。
また、使わなくなったキャッシュは消した方が良さそうですね。
今回は、vagrantのソースを覗いてて見つけたファイルの処理を確認しました。
やっぱり自分が使う道具の理解度があがると落ち着きます。

補足

仮想マシン作成のために利用したBOXファイルは、Puppet Labsで公開しているpuppet導入済みのものです。
Puppet Vagrant Boxes

*1:vagrantでは仮想マシンの環境を提供しているものをproviderと呼んでます。VirtualBoxVMWareなど

「Ubuntu12.10にVagrant/PuppetでRailsの環境を作成する(その2)」|ただいまRubyの修行中

はじめに

前回のその1では、Vagrantにより仮想マシンを立ち上げるところまで行いました。
今回は仮想マシン上にRailsの環境を作成していきます。
最終的な環境が決まったところでPuppetによる自動化を行うとして、とりあえず手動で環境を確定していきます。

参考にしているサイト
Rails開発環境の構築(rbenvでRuby導入からBundler、Rails導入まで) - Qiita

作成したい環境(仮)

ただ、必要なソフトウェアを入れてサンプルが動いて終わるのではなく、実務で開発を行えるような環境の構築がしたいので目標を立てます。

  1. ソース管理を行える(Githubを使用します)
  2. RubyRailsのバージョンが変わっても対応できる(rbenvとbundlerを使用します)
  3. 実機へのデプロイを考えたファイルの構成(目標はherokuへのデプロイ)

まぁ、ゴールは大きく遠ければ色々できるでしょう(^ワ^)ノ

Vagrantにより作成された仮想マシンとネットワークの構成を確認する

自動で作成できたのですが、まったく環境を把握せずに使用するのでは応用が効きません。
概要だけでも調べておきます。

仮想マシンの情報
$ virtualbox

により、VirtualBoxGUIが起動します。ツールバー上の「設定(S)」ボタンで設定画面を表示して詳細を確認します。
有効になっている項目のみ一覧にしました。これが構築直後の仮想マシンの設定です。

システム
メインメモリー 512MB
起動順序 ハードディスク、CD/DVD
プロセッサー数 1
使用率制限 100%(制限なし)
ディスプレイ
ビデオメモリー 8MB
ストレージ
デバイス ハードディスク
タイプ(形式) 通常(VMDK)
仮想的なサイズ 9.90GB
実際のサイズ 1.32GB
詳細 可変サイズのストレージ
場所 ~/VirtualBox VMs/ubuntu1310-i386_1391024958454_21530/ubuntu1310-i386-disk1.vmdk
割り当て ubuntu1310-i386_1391024958454_21530
ネットワーク
アダプター(1) アダプター1:有効
割り当て 割り当て:NAT
アダプタータイプ アダプタータイプ:Intel PRO/1000MT Desktop(82540EM)
プロミスキャストモード プロミスキャストモード:拒否
MACアドレス MACアドレス:08002730A32F
接続 ケーブル接続
ポートフォワーディング
名前 ssh
プロトコル TCP
ホストIP 127.0.01
ホストポート 2222
ゲストポート 22
共有フォルダー
名前 /vagrant
パス ~/vm/001
アクセス権 完全
状態 永久化
ネットワークの構成
vagrant@ubuntu1310-i386:~$ ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 08:00:27:30:a3:2f  
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe30:a32f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1875 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1730 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:165262 (165.2 KB)  TX bytes:159853 (159.8 KB)

vagrant@ubuntu1310-i386:~$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         10.0.2.2        0.0.0.0         UG    0      0        0 eth0
10.0.2.0        *               255.255.255.0   U     0      0        0 eth0

vagrant@ubuntu1310-i386:~$ nslookup
> server 
Default server: 10.0.2.3
Address: 10.0.2.3#53
> exit

ホストの環境も含めて図にしてみました。

f:id:StupidDog:20140201133306p:plain

構築作業の再開

環境の把握も大体できたところで、開発に必要なツールをインストールしていきます。

  1. gitのインストール
  2. rbenvのインストール
  3. Rubyのインストール
  4. bundlerのインストール
  5. Ruby on Railsのインストール

gitのインストール

少々、バージョンが低いのですがコンパイルから導入するのは敷居が高いので、とりあえずaptに頼ります。

$ sudo apt-cache install git
E: Invalid operation install
vagrant@ubuntu1310-i386:~$ sudo apt-get install git
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  git-man liberror-perl
Suggested packages:
  git-daemon-run git-daemon-sysvinit git-doc git-el git-email git-gui gitk gitweb git-arch git-bzr git-cvs git-svn
The following NEW packages will be installed:
  git git-man liberror-perl
0 upgraded, 3 newly installed, 0 to remove and 4 not upgraded.
Need to get 8,487 kB of archives.
After this operation, 19.7 MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://us.archive.ubuntu.com/ubuntu/ saucy/main liberror-perl all 0.17-1 [23.8 kB]
Get:2 http://us.archive.ubuntu.com/ubuntu/ saucy/main git-man all 1:1.8.3.2-1 [670 kB]
Get:3 http://us.archive.ubuntu.com/ubuntu/ saucy/main git i386 1:1.8.3.2-1 [7,793 kB]                                                                                                                  
Fetched 8,487 kB in 42s (198 kB/s)                                                                                                                                                                     
Selecting previously unselected package liberror-perl.
(Reading database ... 62328 files and directories currently installed.)
Unpacking liberror-perl (from .../liberror-perl_0.17-1_all.deb) ...
Selecting previously unselected package git-man.
Unpacking git-man (from .../git-man_1%3a1.8.3.2-1_all.deb) ...
Selecting previously unselected package git.
Unpacking git (from .../git_1%3a1.8.3.2-1_i386.deb) ...
Processing triggers for man-db ...
Setting up liberror-perl (0.17-1) ...
Setting up git-man (1:1.8.3.2-1) ...
Setting up git (1:1.8.3.2-1) ...

rbenvのインストール

apt-getでインストールしようとした場合

rubyのインストールも提案してくれるのですが古いので、githubから最新をインストールすることにします。
(2014.2.1 rbenv は 0.4.0-89-g14bc162 が最新)

しかし、rbenv自体はbashスクリプトで書かれているので実行にrubyを必要としません。
何故、rubyのインストールまでしちゃうのか…。

$ sudo apt-get install rbenv
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libruby1.8 ruby1.8
Suggested packages:
  ruby1.8-examples ri1.8 ruby-switch
The following NEW packages will be installed:
  libruby1.8 rbenv ruby1.8
0 upgraded, 3 newly installed, 0 to remove and 4 not upgraded.
Need to get 1,826 kB of archives.
After this operation, 6,782 kB of additional disk space will be used.
Do you want to continue [Y/n]? n
Abort.

$ sudo apt-cache show rbenv
Package: rbenv
Priority: optional
Section: universe/ruby
Installed-Size: 102
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Debian Ruby Extras Maintainers <pkg-ruby-extras-maintainers@lists.alioth.debian.org>
Architecture: all
Version: 0.3.0-1
...

rbenvをgithubから取得してインストール

sstephenson/rbenv · GitHubのREADME.mdで、Installation以下に書いてあるBasic GitHub Checkoutの手順に従ってインストールします。

ファイルの取得
vagrant@ubuntu1310-i386:~$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
Cloning into '/home/vagrant/.rbenv'...
remote: Reusing existing pack: 1857, done.
remote: Total 1857 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1857/1857), 290.90 KiB | 111.00 KiB/s, done.
Resolving deltas: 100% (1162/1162), done.
Checking connectivity... done
パスを通す

次回の起動時からも使用できるように、ログインシェルの環境設定ファイルへパスの設定を追加します。
環境設定ファイルは、~/.bash_profile ではなく ~/.bashrc になります。

$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
$ echo 'eval "$(rbenv init -)"' >> ~/.bashrc
$ source ~/.bashrc
確認する

「rbenvは関数です」となれば成功です。

$ type rbenv
vagrant@ubuntu1310-i386:~$ type rbenv
rbenv is a function
rbenv () 
{ 
    local command;
    command="$1";
    if [ "$#" -gt 0 ]; then
        shift;
    fi;
    case "$command" in 
        rehash | shell)
            eval "`rbenv "sh-$command" "$@"`"
        ;;
        *)
            command rbenv "$command" "$@"
        ;;
    esac
}

rbenvのバージョンが上がりアップグレードを行う場合は「git pull」でアップグレードできます。

$ cd ~/.rbenv
$ git pull
必須プラグイン(ruby-build)をインストールする

インストール可能なrubyのバージョンをリストしたり、インストールするためにプラグインを追加します。

vagrant@ubuntu1310-i386:~$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
Cloning into '/home/vagrant/.rbenv/plugins/ruby-build'...
remote: Reusing existing pack: 2856, done.
remote: Total 2856 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (2856/2856), 472.89 KiB | 144.00 KiB/s, done.
Resolving deltas: 100% (1254/1254), done.
Checking connectivity... done

これで、「rbenv install」コマンドが使用できます。

Rubyのインストール

インストール可能なバージョンをリスト
$ rbenv install -l
...
  2.0.0-rc1
  2.0.0-rc2
  2.1.0
  2.1.0-dev
  2.1.0-preview1
  2.1.0-preview2
  2.1.0-rc1
  2.2.0-dev
  jruby-1.5.6
  jruby-1.6.3
  jruby-1.6.4
  jruby-1.6.5
...
Rubyをインストール

ファイルは「~/.rbenv/versions/<バージョン番号>/」にインストールされます。
折角なのでファイルが配置されるディレクトリを観察します。

vagrant@ubuntu1310-i386:~$ ll -R .rbenv/versions/ .rbenv/shims/
.rbenv/shims/:
total 8
drwxrwxr-x 2 vagrant vagrant 4096 Jan 31 21:28 ./
drwxrwxr-x 9 vagrant vagrant 4096 Jan 31 11:29 ../

.rbenv/versions/:
total 8
drwxrwxr-x 2 vagrant vagrant 4096 Jan 31 11:29 ./
drwxrwxr-x 9 vagrant vagrant 4096 Jan 31 11:29 ../

初期状態で何も無いことを確認…無いですね。

$ rbenv install 2.1.0
vagrant@ubuntu1310-i386:~$ rbenv install 2.1.0
Downloading ruby-2.1.0.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/9e6386d53f5200a3e7069107405b93f7
Installing ruby-2.1.0...

BUILD FAILED

Inspect or clean up the working tree at /tmp/ruby-build.20140131214001.1434
Results logged to /tmp/ruby-build.20140131214001.1434.log

Last 10 log lines:
                              io-console 0.4.2
                              json 1.8.1
                              minitest 4.7.5
                              psych 2.0.2
                              rake 10.1.0
                              rdoc 4.1.0
                              test-unit 2.1.0.0
installing rdoc:              /home/vagrant/.rbenv/versions/2.1.0/share/ri/2.1.0/system
installing capi-docs:         /home/vagrant/.rbenv/versions/2.1.0/share/doc/ruby
The Ruby openssl extension was not compiled. Missing the OpenSSL lib?

…エラーですよノДT)
(実は一度、既存のRubyをpurgeしました。関連してるpackageも一緒に…)
Setting up and installing rbenv, ruby-build, rubies, rbenv-gemset, and bundlerInstall rubiesで、
rbenv-buildに必要なパッケージをリストしているので、参考にさせてもらいます。
余計なpurgeが無ければ必要ないはずの作業です

パッケージを追加して再度、Rubyインストール

vagrant@ubuntu1310-i386:~$ sudo apt-get install libssl-dev zlib1g-dev libreadline-dev libyaml-dev flex gettext
vagrant@ubuntu1310-i386:~$ rbenv install 2.1.0
Downloading ruby-2.1.0.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/9e6386d53f5200a3e7069107405b93f7
Installing ruby-2.1.0...
Installed ruby-2.1.0 to /home/vagrant/.rbenv/versions/2.1.0

vagrant@ubuntu1310-i386:~$ rbenv rehash

そして観察です。
「.rbenv/versions/」の下には 2.1.0の新しいディレクトリが作成されています。
中には大量のファイルが143MBほどあるようです。

vagrant@ubuntu1310-i386:~$ ll .rbenv/versions/ 
total 12
drwxrwxr-x  3 vagrant vagrant 4096 Jan 31 22:27 ./
drwxrwxr-x 10 vagrant vagrant 4096 Jan 31 21:37 ../
drwxr-xr-x  6 vagrant vagrant 4096 Jan 31 22:39 2.1.0/

vagrant@ubuntu1310-i386:~$ du -sh .rbenv/versions/2.1.0/
143M	.rbenv/versions/2.1.0/

「.rbenv/shims/」の下には幾つかのスクリプトが作成されています。
ruby」コマンドを実行した場合、このディレクトリにある「rubyスクリプトが呼び出されるようです。
ここで、バージョンを切り替えているみたいです。
そして、お約束として「rbenv」コマンドで何か変更した場合は、必ず「rbenv rehash」コマンドを実行して「.rbenv/shims/」を更新します。

vagrant@ubuntu1310-i386:~$ ll -R .rbenv/shims/
.rbenv/shims/:
total 40
drwxrwxr-x  2 vagrant vagrant 4096 Jan 31 22:39 ./
drwxrwxr-x 10 vagrant vagrant 4096 Jan 31 21:37 ../
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 erb*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 gem*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 irb*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 rake*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 rdoc*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 ri*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 ruby*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 testrb*

vagrant@ubuntu1310-i386:~$ which ruby
/home/vagrant/.rbenv/shims/ruby
インストールしたrubyのバージョンを使えるようにする

rbenvは初期状態で、システム上にあるrubyを呼び出す設定になっています。
「rbenv versions」により選択できるバージョンと、選択されているバージョン(*が付いてる)が分かります。
「rbenv global 2.1.0」により切り替えることができます。

vagrant@ubuntu1310-i386:~$ rbenv versions
* system (set by /home/vagrant/.rbenv/version)
  2.1.0

vagrant@ubuntu1310-i386:~$ rbenv global 2.1.0 
vagrant@ubuntu1310-i386:~$ rbenv versions
  system
* 2.1.0 (set by /home/vagrant/.rbenv/version)

vagrant@ubuntu1310-i386:~$ ruby -v
ruby 2.1.0p0 (2013-12-25 revision 44422) [i686-linux]

これで、やっと希望バージョンのRubyが使用可能になりました。

bundlerのインストール

RubyGemsは、現在有効にしているRubyのバージョン毎にインストールすることになります。
「rbenv exec gem install bundler」コマンドでインストールします。

2014.02.11 追記
「rbenv」導入により「gem」コマンドが「.rbenv/shims/gem」スクリプトの呼出しになる。
このスクリプトは、最終的に「rbenv exec xxx」の呼出しを行うように作られているので、「rbenv exec」を付ける必要はありせん。

rbenvの切り替えの仕組み…と、他言語での実験 - すぎゃーんメモ

vagrant@ubuntu1310-i386:~$ rbenv exec gem install bundler
Fetching: bundler-1.5.2.gem (100%)
Successfully installed bundler-1.5.2
Parsing documentation for bundler-1.5.2
Installing ri documentation for bundler-1.5.2
Done installing documentation for bundler after 3 seconds
1 gem installed

vagrant@ubuntu1310-i386:~$ rbenv rehash
vagrant@ubuntu1310-i386:~$ ll -R .rbenv/shims/
.rbenv/shims/:
total 48
drwxrwxr-x  2 vagrant vagrant 4096 Feb  1 00:36 ./
drwxrwxr-x 10 vagrant vagrant 4096 Jan 31 23:45 ../
-rwxrwxr-x  2 vagrant vagrant  401 Feb  1 00:36 bundle*
-rwxrwxr-x  2 vagrant vagrant  401 Feb  1 00:36 bundler*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 erb*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 gem*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 irb*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 rake*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 rdoc*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 ri*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 ruby*
-rwxrwxr-x  8 vagrant vagrant  401 Jan 31 22:39 testrb*

またまた観察です。「rbenv rehash」コマンドにより「bundle」と「bundler」が増えています。

実験
vagrant@ubuntu1310-i386:~$ rbenv global system 
vagrant@ubuntu1310-i386:~$ bundle
rbenv: bundle: command not found

The `bundle' command exists in these Ruby versions:
  2.1.0

別バージョンへ切り替えて、インストールしていないGemを呼び出そうとすると怒られます。

まとめ

残るはRuby on Railsのインストールだけですが、RailsのバージョンをRubyのバージョン毎に対応させるか、Railsアプリ毎に対応させるかが問題になります。
対応のさせかたによりディレクトリの構成や手順が変わるので方針を決めるために、ここで休憩します。
だんだん具体的なイメージがつかめてきましたぞっと!

「Ubuntu12.10にVagrant/PuppetでRailsの環境を作成する(その1)」|ただいまRubyの修行中

はじめに

フィルタ系プログラムばかり作っていては勿体ないので、Ruby on Railsにも手を出すことにします。
実行環境を作成するにあたり毎回手探りで調節するのは嫌なので、以前から気になっていたVagrant/Puppetを使用することにします。

Vagrantとは?

  • 仮想マシンの作成や環境構築、仮想マシンの破棄までを自動化するツール
  • 違う環境に移行可能な開発環境を簡単に構築・管理し、配布することができる開発環境作成ツール

詳しい説明はリンク先のサイトが分かりやすいので、自分が欲しいと思った利点だけまとめると

  • 誰かが作成したベースの環境を利用でき、ベースのダウンロードから自動化することができる。
  • 環境に適用する設定を、ファイルに定義し自動で設定できる。
  • ベースから作成した環境は簡単に破棄し、再作成できる。
  • 自分で作成した環境を配布用にまとめる事もできるので、現場固有の開発環境や、開発後の保守の為に環境を保存する事もできる。

Puppetとは?

Puppetを使ったLinuxシステムの設定自動管理

  • あらかじめ用意しておいた設定ファイルに基づいてサーバーのさまざまな設定を自動的に行うソフトウェア

Vagrantがハード(仮想マシン)環境の構築ツールとして、Puppetはソフト環境の構築ツールみたいな感じかなぁ。
Puppetは、Vagrantと合わせなくても単体で利用できる運用ツール。
同じ用途にChefなるものがあります。

Chefでサーバ管理を楽チンにしよう!(第1回)
を流し読みした結果から、今回はPuppetを選択しました。

  • 使用するまでにChefの方が構成要素が多い
  • Puppet の開発元である Puppet Labs が Puppet Labs Vagrant BoxesというサイトでVagrantで使用できるBoxファイルを公開している。

余計な物を入れたくないし、自動化して楽に構築をしたいのにツール自体を動かすための環境構築や維持が難しいのは嫌です。
まぁ、今回の選択理由は、Puppetの開発元がVagrantで使用できるPuppet入りのイメージを公開しているからです。

構築手順

  1. VirtualBoxのインストール
  2. Vagrantのダウンロードとインストール
  3. ベースとなる仮想環境の構築 (Ubuntu Server 13.10 LTS i386)
  4. 構築した環境の確認 (起動/接続/終了)

VirtualBoxのインストール

Download VirtualBox for Linux Hosts
Debian-based Linux distributionsに記載されている手順どおりに、apt-getによりインストールします。

「/etc/apt/sources.list」ファイルに以下の行を追加。(※ 一番最後に追加しました)

deb http://download.virtualbox.org/virtualbox/debian saucy contrib
deb http://download.virtualbox.org/virtualbox/debian raring contrib
deb http://download.virtualbox.org/virtualbox/debian quantal contrib
deb http://download.virtualbox.org/virtualbox/debian precise contrib
deb http://download.virtualbox.org/virtualbox/debian lucid contrib non-free
deb http://download.virtualbox.org/virtualbox/debian wheezy contrib
deb http://download.virtualbox.org/virtualbox/debian squeeze contrib non-free

署名確認のための公開鍵を設定。(※ wgetにより公開鍵ファイルを取得し設定)

$ wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add -

良く分かってないけど、apt-get upgradeなどでカーネル更新後、VirtualBoxのホスト・カーネル・モジュールの対応をしてくれるのでdkms入れておいた方がいいよ。
とのことなので、dkms(Dynamic Kernel Modules Support)のインストールも行う。

sudo apt-get install dkms

VirtualBoxのインストール。(※ 現行最新の4.3系)

$ sudo apt-get update
$ sudo apt-get install virtualbox-4.3

Vagrantのダウンロードとインストール

Vertion1.0.xの頃はRubyGemでインストールできたけど、今はインストーラ/パッケージのみに統一されているらしい。
なので、パッケージをダウンロードする必要があります。

注意
以下のようにすると…「なーんだaptでインストールできるじゃん♪」ってなるけど罠です。
先にいれたVirtualBoxはパージされ、VirtualBox4.1.18とVagrant1.0.3-1がねじ込まれます。

$ sudo apt-get install vagrant

もし、これをしてしまったら、ねじ込まれた物をパージしてVirtualBoxのインストールからやり直しです。

パッケージは公式サイトのダウンロードページから環境に合わせて最新をダウンロードします。
(2014.1.29現在、Debian/Ubuntu 32-bit版は"vagrant_1.4.3_i686.deb"でした)

deb形式のパッケージなのでdpkgでインストールします。

$ sudo dpkg -i vagrant_1.4.3_i686.deb

ベースとなる仮想環境の構築 (Ubuntu Server 13.10 LTS i386)

Vagrantでは、OSのインストーラを使って仮想マシンにOSをインストールするのではなく、あらかじめOSがインストールされたディスクイメージを使用して仮想マシンを作成する。VagrantではディスクイメージやVirtualBoxの設定ファイル、メタデータなどを「box」(複数形は「boxes」)という形式のファイルにまとめて取り扱う

で、欲しい環境のBoxファイルを探すことになります。
今回は、Puppet Labs がBoxファイルを公開しているので利用させてもらいます。
Puppet Labs Vagrant Boxes

Current Boxs のページの一番下にある Ubuntu Server 13.10 i386 が目的のファイルです。
右端のplainリンクからアドレスをコピーしてコマンドへ貼り付けます。

下記のコマンドで設定ファイル「Vagrantfile」の雛形を作成します。

$ vagrant init ubuntu_server-13_10-i386 http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-1310-i386-virtualbox-puppet.box
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

コメントがいっぱいな設定ファイル(Vagratfile)が作成されますが、不要なコメントを省くと、これだけの内容です。

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

VAGRANTFILE_API_VERSION = "2" 

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "ubuntu_server-13_10-i386"
  config.vm.box_url = "http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-1310-i386-virtualbox-puppet.box"
end

そして、環境の構築と起動ですが、BoxファイルのダウンロードはVagrantが行ってくれます。

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Box 'ubuntu_server-13_10-i386' was not found. Fetching box from specified URL for
the provider 'virtualbox'. Note that if the URL does not have
a box for this provider, you should interrupt Vagrant now and add
the box yourself. Otherwise Vagrant will attempt to download the
full box prior to discovering this error.
Downloading box from URL: http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-1310-i386-virtualbox-puppet.box
Extracting box...te: 5678k/s, Estimated time remaining: --:--:--)
Successfully added box 'ubuntu_server-13_10-i386' with provider 'virtualbox'!
[default] Importing base box 'ubuntu_server-13_10-i386'...
[default] Matching MAC address for NAT networking...
[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Booting VM...
[default] Waiting for machine to boot. This may take a few minutes...
[default] Machine booted and ready!
[default] Mounting shared folders...
[default] -- /vagrant
[default] VM already provisioned. Run `vagrant provision` or use `--provision` to force it

構築した環境の確認

仮想マシンの画面が表示されないので、良く分かりませんが「vagrant status」で状態を確認できます。

$ vagrant status
Current machine states:

default                   running (virtualbox)

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


構築した環境にはSSHで接続できます。
ターミナルから「vagrant ssh」でログインできます。

$ vagrant ssh
Last login: Thu Jan 16 16:37:07 2014 from 10.0.2.2
vagrant@ubuntu1310-i386:~$ exit
logout
Connection to 127.0.0.1 closed.

127.0.0.1で接続してたのか~。


起動した仮想マシンを停止するには「vagrant halt」とします。

$ vagrant halt
[default] Attempting graceful shutdown of VM...
$ vagrant status
Current machine states:

default                   poweroff (virtualbox)

The VM is powered off. To restart the VM, simply run `vagrant up`

まとめ

今回の環境構築を自動化したいノДT)
とりあえずベースとなる環境が出来たので、次はRails環境の構築と、その構築をPuppetで自動化する。

「string#matchが返すのは配列じゃなかったよ」|ただいまRubyの修行中です

はじめに

ちょこちょこと、String#match正規表現とグループを使って文字列の切り出しをしていたのです。
でも、$1とか$2だと処理しずらいな~と思い、ちらっとサンプルコードを見たところ

s = "<hello> <world>"
if md = s.match(/<(\w+)>/)
  puts md[0]
  puts md[1]
end

「$1とか$2じゃなくて配列を返すのか~」と安易に判断してArray#mapを繋げてみたところ…

puts "123,456,789,987".match(/(\d+),(\d+)/).map(&:to_i)

mapメソッドなんて無いと怒られましたっ

code.rb:3:in `<main>': undefined method `map' for #<MatchData "123,456" 1:"123" 2:"456"> (NoMethodError)

メッセージを見るとMatchDataクラスのオブジェクトが返って来てる。

MatchDataクラスとは?

Ruby 2.1.0 リファレンスマニュアル class MatchData
正規表現のマッチに関する情報を扱うためのクラスで、配列のように[]でも値が取得できるように定義されています。
折角なので、面白そうなメソッドが無いかリファレンスを眺めて、どんなメソッドがあるのか個人用に一覧化してみたり。

メソッド 戻り値 説明
マッチした文字列とその前後の取得
to_s  String マッチした文字列全体を返す
pre_match  String マッチした部分より前の文字列を返す($`と同じ)
post_match  String マッチした部分より後ろの文字列を返す($'と同じ)
グループにマッチした文字列の取得
captures  [String] $1, $2,...を格納した配列を返す。
to_a  [String] $&, $1, $2,...を格納した配列を返す。
values_at(*index) [String] 正規表現中のn番目の括弧にマッチした部分文字列の配列を返す(0番目は$&)
マッチした文字列の位置取得
begin(n) Fixnum n番目の部分文字列先頭のオフセット。マッチしていなければnil
end(n) Fixnum n番目の部分文字列終端のオフセット。マッチしていなければnil
offset(n) [Fixnum] n番目の部分文字列のオフセットの配列[start,end]を返す。
比較結果の情報取得
regexp Regexp 自身の元になった正規表現オブジェクトを返す
string  String マッチ対象になった文字列の複製を返す
names [Array] 名前付きキャプチャの名前を文字列配列で返す(=self.regexp.names)
length/size Fixnum 部分文字列の数を返す(=self.to_a.size,$&も含も含まれると言うこと)

values_at(*index)メソッドなんかは面白いかも。

irb(main):001:0> "2014,1,24".match(/(\d+),(\d+),(\d+)/).values_at(2,3,1).join("/")
=> "1/24/2014"

「Ubuntu 12.10、起動時にChecking battery state...で停止する」の調査(3)

はじめに

前回の続きで、どこまで起動の処理ができているのか起動スクリプトを確認して原因を探した。

対象の起動スクリプトを抽出する

正常起動した場合のランレベルが2だったので、「/etc/rc2.d」以下の起動スクリプトが対象となる。

ランレベル
$ runlevel
N 2
起動スクリプト
$ ls -al /etc/rc2.d
drwxr-xr-x   2 root root  4096 11 00:00 ./
drwxr-xr-x 145 root root 12288 11 00:00 ../
lrwxrwxrwx   1 root root    15 11 00:00 K20saned -> ../init.d/saned*
lrwxrwxrwx   1 root root    27 11 00:00 K20speech-dispatcher -> ../init.d/speech-dispatcher*
lrwxrwxrwx   1 root root    18 11 00:00 K30pppd-dns -> ../init.d/pppd-dns*
-rw-r--r--   1 root root   677 11 00:00 README
lrwxrwxrwx   1 root root    14 11 00:00 S20avgd -> ../init.d/avgd*
lrwxrwxrwx   1 root root    20 11 00:00 S20kerneloops -> ../init.d/kerneloops*
lrwxrwxrwx   1 root root    17 11 00:00 S20postfix -> ../init.d/postfix*
lrwxrwxrwx   1 root root    15 11 00:00 S50rsync -> ../init.d/rsync*
lrwxrwxrwx   1 root root    19 11 00:00 S70dns-clean -> ../init.d/dns-clean*
lrwxrwxrwx   1 root root    14 11 00:00 S75sudo -> ../init.d/sudo*
lrwxrwxrwx   1 root root    22 11 00:00 S99acpi-support -> ../init.d/acpi-support*
lrwxrwxrwx   1 root root    21 11 00:00 S99grub-common -> ../init.d/grub-common*
lrwxrwxrwx   1 root root    18 11 00:00 S99ondemand -> ../init.d/ondemand*
lrwxrwxrwx   1 root root    18 11 00:00 S99rc.local -> ../init.d/rc.local*

S99である S99acpi-supportまで実行されているが分かっているので、残りの同じ実行順の起動スクリプトを確認する。

対象の起動スクリプトの処理を確認する

No Script Description
1 /etc/init.d/grub-common Record successful boot for GRUB
2 /etc/init.d/ondemand CPU周波数が動的に変化する設定にする
3 /etc/init.d/acpi-support 省電力モードの切り替えスクリプト
4 /etc/init.d/rc.local 特定サイトに特化したコマンドを記述するスクリプト
grub-commonは何をしている?

OSの起動まで正常に行えた事をGRUB*1の環境ファイル「/boot/grub/grubenv」に記録している。
OSの起動で問題があり次回の起動時にGRUBのメニュー画面を表示する必要がある場合「grubenv」に「recordfail」が設定される。
このスクリプトでは「grubenv」から「recordfail」の設定を取り消して次回の起動でGRUBのメニューが表示されないようにしている。
Manual grub

ondemandは何をしている?

負荷によりCPU周波数を切り替える機能があり、その設定を強制的にondemandに設定している。
処理としては「/sys/devices/system/cpu/cpu*/cpufreq/scaling_governor」に「ondemand」を設定している。
cpu*はコアの分だけ(0~)繰り返して全コアを同じ設定にしている。

rc.localは何をしている?

自身の環境では「/etc/rc.local」が存在したら実行するだけの処理になっていた。
「/etc/rc.local」は何も追加していないので正常を返すだけの「exit 0」のみ。

今回の調査結果

起動スクリプトには障害や常駐するような処理は無かった。
では、どこで障害が発生しているのか?
表示されないログイン画面はどこで起動しているのか?
改めて、Ubuntuの起動の仕組みを調べる必要がある。

おまけ

「rc.local」の説明には最後に実行されるスクリプトになっている。
起動スクリプトの実行順が「Knn」「Snn」の"nn"が小さい順であることは分かるが同じ番号の場合、それ以降の名前で昇順になるのだろうか…
実際に各起動スクリプトを呼び出している「/etc/init.d/rc」では「for s in /etc/rc$runlevel.d/S*」でファイルリストを取得している。

$ bash <<< 'for s in /etc/rc2.d/S*; do echo $s; done'
/etc/rc2.d/S20avgd
/etc/rc2.d/S20kerneloops
/etc/rc2.d/S20postfix
/etc/rc2.d/S50rsync
/etc/rc2.d/S70dns-clean
/etc/rc2.d/S75sudo
/etc/rc2.d/S91apache2
/etc/rc2.d/S99acpi-support
/etc/rc2.d/S99grub-common
/etc/rc2.d/S99ondemand
/etc/rc2.d/S99rc.local

この結果を見る限りでは番号順・名前順で昇順である。
しかし「rc.local」より後にくる名前を付けた場合はどうなるのか?

*1:GRnad Unified Bootloader

「Ubuntu 12.10、起動時にChecking battery state...で停止する」の調査(2)

はじめに

前回の調査で、あたりを付けていた「power.sh」を調べる。

対象のファイル

/etc/power.sh

#!/bin/sh

test -f /usr/share/acpi-support/key-constants || exit 0

. /usr/share/acpi-support/policy-funcs

if [ -z "$*" ] && ( [ `CheckPolicy` = 0 ] || CheckUPowerPolicy ); then
    exit;
fi

pm-powersave $*

/usr/share/acpi-support/policy-funcs

#!/bin/sh

test -f /usr/share/acpi-support/key-constants || exit 0

. /usr/share/acpi-support/policy-funcs

if [ -z "$*" ] && ( [ `CheckPolicy` = 0 ] || CheckUPowerPolicy ); then
    exit;
fi

pm-powersave $*
usazukinchan@pc02:/etc/acpi$ cat /usr/share/acpi-support/policy-funcs 
CheckUPowerPolicy() {
	if pidof upowerd > /dev/null; then
		return 0;
	else
		return 1;
	fi
}
CheckPolicy() {
	local PMS
	PMS="gnome-power-manager kpowersave xfce4-power-manager"
	PMS="$PMS guidance-power-manager.py dalston-power-applet"
	if pidof -x $PMS > /dev/null ||
	   (pidof dcopserver > /dev/null && test -x /usr/bin/dcop && /usr/bin/dcop kded kded loadedModules | grep -q klaptopdaemon) ||
	   PowerDevilRunning ; then
		echo 0;
	else
		echo 1;
	fi
}

PowerDevilRunning() {
	test -x /usr/bin/dbus-send || return 1
	
	for p in $(pidof kded4); do
		test -r /proc/$p/environ || continue
		local DBUS_SESS=$(cat /proc/$p/environ | grep -z "DBUS_SESSION_BUS_ADDRESS=")
		test "$DBUS_SESS" != "" || continue
		(su - $(ps -o user= $p) -c "$DBUS_SESS dbus-send --print-reply --dest=org.kde.kded /kded org.kde.kded.loadedModules" | grep -q powerdevil) && return 0
	done
	
	return 1
}

「power.sh」は何をしてる?

「power.sh」は、何かをチェックして、最後に「pm-powersave」を実行している。

$ type `file -p pm-powersave`
/usr/sbin/pm-powersave: POSIX shell script, ASCII text executable
$ file 

「pm-powersave」は省電力モードへの移行と復帰を行うスクリプトらしい。
「/usr/lib/pm-utils/*.d/」以下のスクリプトを順次呼び出し、ログを「/var/log/pm-powersave.log」へ出力している。

今回の目的では無いので詳細は省き、「pm-powersave」が実行され終了しているか否かを確認した。
呼び出されたスクリプトをログで確認する限り、待ち状態で停止していない。

今回の調査結果

コンソール画面で表示されていた「Checking battery state...」は、まったく無関係である事が分かった。
この起動スクリプトより後で、障害が起こっていることが分かったので、今後は次に処理される起動スクリプトを突き止める。

おまけ

スクリプトを確認している際に、プロセスIDを調べる「pidof」コマンドが使われていたけど「-x」オプションで指定したスクリプトを実行しているシェルのプロセスIDを取得できるとの事。
スクリプトばかり追っているので、後々使えそう・・・コマンド覚えるだけで一苦労だな。