忘備録

日々の調べ物をまとめる。アウトプットする。基本自分用。

rbenvでRubyのバージョンを管理する

rbenvを利用して、Rubyのバージョンを切り替える方法のメモ。

当方の環境

Homebrewでrbenvをインストール

$ ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14] # プリセットのrubyバージョン
# Homebrewの更新
$ brew update
Updated Homebrew from 9185c50 to dde20cd.
==> Migrating Homebrew to v0.9.9
remote: Counting objects: 271, done.
remote: Compressing objects: 100% (219/219), done.
remote: Total 271 (delta 142), reused 124 (delta 38), pack-reused 0
Receiving objects: 100% (271/271), 445.51 KiB | 413.00 KiB/s, done.
Resolving deltas: 100% (142/142), completed with 140 local objects.
From https://github.com/Homebrew/brew
 + dde20cd...2ca6dbb master     -> origin/master  (forced update)
HEAD is now at 2ca6dbb brew.rb: Don’t ask `xcrun` for output if no CLT is installed (#334)
==> Homebrew has enabled anonymous aggregate user behaviour analytics
Read the analytics documentation (and how to opt-out) here:
  https://git.io/brew-analytics
==> Tapping homebrew/core
Cloning into '/usr/local/Library/Taps/homebrew/homebrew-core'...
remote: Counting objects: 3710, done.
remote: Compressing objects: 100% (3593/3593), done.
remote: Total 3710 (delta 13), reused 2375 (delta 8), pack-reused 0
Receiving objects: 100% (3710/3710), 2.88 MiB | 224.00 KiB/s, done.
Resolving deltas: 100% (13/13), done.
Checking connectivity... done.
Tapped 3588 formulae (3,736 files, 9.0M)
==> Cleaning up /Library/Caches/Homebrew...
Removing: /Library/Caches/Homebrew/binutils-2.25.1.yosemite.bottle.tar.gz... (44.2M)
Removing: /Library/Caches/Homebrew/coreutils-8.24.yosemite.bottle.1.tar.gz... (3.3M)
Removing: /Library/Caches/Homebrew/nmap-7.00.yosemite.bottle.tar.gz... (6M)
Removing: /Library/Caches/Homebrew/openssl-1.0.2d_1.yosemite.bottle.tar.gz... (3.6M)
==> Migrating /Library/Caches/Homebrew to /Users/makoto/Library/Caches/Homebrew.
==> Deleting /Library/Caches/Homebrew...
Already up-to-date.
# rbenvのインストール
$ brew install rbenv
==> Installing dependencies for rbenv: autoconf, pkg-config, openssl, rub
==> Installing rbenv dependency: autoconf
==> Downloading https://homebrew.bintray.com/bottles/autoconf-2.69.yosemite.bott
######################################################################## 100.0%
==> Pouring autoconf-2.69.yosemite.bottle.4.tar.gz
==> Caveats
Emacs Lisp files have been installed to:
  /usr/local/share/emacs/site-lisp/autoconf
==> Summary
🍺  /usr/local/Cellar/autoconf/2.69: 70 files, 3.0M
==> Installing rbenv dependency: pkg-config
==> Downloading https://homebrew.bintray.com/bottles/pkg-config-0.29.1.yosemite.
######################################################################## 100.0%
==> Pouring pkg-config-0.29.1.yosemite.bottle.tar.gz
🍺  /usr/local/Cellar/pkg-config/0.29.1: 10 files, 627.2K
==> Installing rbenv dependency: openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2h_1.yosemite.b
######################################################################## 100.0%
==> Pouring openssl-1.0.2h_1.yosemite.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you’ll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.2h_1: 1,691 files, 12.0M
==> Installing rbenv dependency: ruby-build
==> Downloading https://github.com/rbenv/ruby-build/archive/v20160602.tar.gz
==> Downloading from https://codeload.github.com/rbenv/ruby-build/tar.gz/v201606
######################################################################## 100.0%
==> ./install.sh
🍺  /usr/local/Cellar/ruby-build/20160602: 282 files, 155.5K, built in 9 seconds
==> Installing rbenv
==> Downloading https://homebrew.bintray.com/bottles/rbenv-1.0.0.yosemite.bottle
######################################################################## 100.0%
==> Pouring rbenv-1.0.0.yosemite.bottle.tar.gz
==> Caveats
Rbenv stores data under ~/.rbenv by default. If you absolutely need to
store everything under Homebrew’s prefix, include this in your profile:
  export RBENV_ROOT=/usr/local/var/rbenv

To enable shims and autocompletion, run this and follow the instructions:
  rbenv init
==> Summary
🍺  /usr/local/Cellar/rbenv/1.0.0: 36 files, 61.9K

rbenvの使い方

# インストールできるバージョンの確認
$ rbenv install -l
Available versions:
  1.8.5-p113
  1.8.5-p114
  1.8.5-p115
  1.8.5-p231
  1.8.5-p52
  1.8.6-p110
  1.8.6-p111
  1.8.6-p114
  1.8.6-p230
  1.8.6-p286
  1.8.6-p287
  1.8.6-p36
  1.8.6-p368
  1.8.6-p369
  1.8.6-p383
  1.8.6-p388
  1.8.6-p398
  1.8.6-p399
  1.8.6-p420
  1.8.6
  1.8.7-preview1
  1.8.7-preview2
  1.8.7-preview3
  1.8.7-preview4
  1.8.7-p160
  1.8.7-p17
  1.8.7-p173
  1.8.7-p174
  1.8.7-p22
  1.8.7-p248
  1.8.7-p249
  1.8.7-p299
  1.8.7-p301
  1.8.7-p302
  1.8.7-p330
  1.8.7-p334
  1.8.7-p352
  1.8.7-p357
  1.8.7-p358
  1.8.7-p370
  1.8.7-p371
  1.8.7-p373
  1.8.7-p374
  1.8.7-p375
  1.8.7-p71
  1.8.7-p72
  1.8.7
  1.9.0-0
  1.9.0-1
  1.9.0-2
  1.9.0-3
  1.9.0-4
  1.9.0-5
  1.9.1-preview1
  1.9.1-preview2
  1.9.1-rc1
  1.9.1-rc2
  1.9.1-p0
  1.9.1-p129
  1.9.1-p243
  1.9.1-p376
  1.9.1-p378
  1.9.1-p429
  1.9.1-p430
  1.9.1-p431
  1.9.2-preview1
  1.9.2-preview3
  1.9.2-rc1
  1.9.2-rc2
  1.9.2-p0
  1.9.2-p136
  1.9.2-p180
  1.9.2-p290
  1.9.2-p318
  1.9.2-p320
  1.9.2-p326
  1.9.2-p330
  1.9.3-dev
  1.9.3-preview1
  1.9.3-rc1
  1.9.3-p0
  1.9.3-p105
  1.9.3-p125
  1.9.3-p194
  1.9.3-p286
  1.9.3-p327
  1.9.3-p362
  1.9.3-p374
  1.9.3-p385
  1.9.3-p392
  1.9.3-p426
  1.9.3-p429
  1.9.3-p448
  1.9.3-p484
  1.9.3-p545
  1.9.3-p547
  1.9.3-p550
  1.9.3-p551
  2.0.0-dev
  2.0.0-preview1
  2.0.0-preview2
  2.0.0-rc1
  2.0.0-rc2
  2.0.0-p0
  2.0.0-p195
  2.0.0-p247
  2.0.0-p353
  2.0.0-p451
  2.0.0-p481
  2.0.0-p576
  2.0.0-p594
  2.0.0-p598
  2.0.0-p643
  2.0.0-p645
  2.0.0-p647
  2.0.0-p648
  2.1.0-dev
  2.1.0-preview1
  2.1.0-preview2
  2.1.0-rc1
  2.1.0
  2.1.1
  2.1.2
  2.1.3
  2.1.4
  2.1.5
  2.1.6
  2.1.7
  2.1.8
  2.1.9
  2.1.10
  2.2.0-dev
  2.2.0-preview1
  2.2.0-preview2
  2.2.0-rc1
  2.2.0
  2.2.1
  2.2.2
  2.2.3
  2.2.4
  2.2.5
  2.3.0-dev
  2.3.0-preview1
  2.3.0-preview2
  2.3.0
  2.3.1
  2.4.0-dev
  jruby-1.5.6
  jruby-1.6.3
  jruby-1.6.4
  jruby-1.6.5
  jruby-1.6.5.1
  jruby-1.6.6
  jruby-1.6.7
  jruby-1.6.7.2
  jruby-1.6.8
  jruby-1.7.0-preview1
  jruby-1.7.0-preview2
  jruby-1.7.0-rc1
  jruby-1.7.0-rc2
  jruby-1.7.0
  jruby-1.7.1
  jruby-1.7.2
  jruby-1.7.3
  jruby-1.7.4
  jruby-1.7.5
  jruby-1.7.6
  jruby-1.7.7
  jruby-1.7.8
  jruby-1.7.9
  jruby-1.7.10
  jruby-1.7.11
  jruby-1.7.12
  jruby-1.7.13
  jruby-1.7.14
  jruby-1.7.15
  jruby-1.7.16
  jruby-1.7.16.1
  jruby-1.7.16.2
  jruby-1.7.17
  jruby-1.7.18
  jruby-1.7.19
  jruby-1.7.20
  jruby-1.7.20.1
  jruby-1.7.21
  jruby-1.7.22
  jruby-1.7.23
  jruby-1.7.24
  jruby-1.7.25
  jruby-9.0.0.0.pre1
  jruby-9.0.0.0.pre2
  jruby-9.0.0.0.rc1
  jruby-9.0.0.0.rc2
  jruby-9.0.0.0
  jruby-9.0.1.0
  jruby-9.0.3.0
  jruby-9.0.4.0
  jruby-9.0.5.0
  jruby-9.1.0.0-dev
  jruby-9.1.0.0
  jruby-9.1.1.0
  jruby-9.1.2.0
  maglev-1.0.0
  maglev-1.1.0-dev
  maglev-2.0.0-dev
  mruby-dev
  mruby-1.0.0
  mruby-1.1.0
  mruby-1.2.0
  rbx-2.2.2
  rbx-2.2.3
  rbx-2.2.4
  rbx-2.2.5
  rbx-2.2.6
  rbx-2.2.7
  rbx-2.2.8
  rbx-2.2.9
  rbx-2.2.10
  rbx-2.3.0
  rbx-2.4.0
  rbx-2.4.1
  rbx-2.5.0
  rbx-2.5.1
  rbx-2.5.2
  rbx-2.5.3
  rbx-2.5.4
  rbx-2.5.5
  rbx-2.5.6
  rbx-2.5.7
  rbx-2.5.8
  rbx-2.6
  rbx-2.7
  rbx-2.8
  rbx-2.9
  rbx-2.10
  rbx-2.11
  rbx-2.71828182
  rbx-3.0
  rbx-3.1
  rbx-3.2
  rbx-3.3
  rbx-3.4
  rbx-3.5
  rbx-3.6
  rbx-3.7
  rbx-3.8
  rbx-3.9
  rbx-3.10
  rbx-3.11
  rbx-3.12
  rbx-3.13
  rbx-3.14
  rbx-3.15
  rbx-3.16
  rbx-3.17
  rbx-3.18
  rbx-3.19
  rbx-3.20
  rbx-3.21
  rbx-3.22
  rbx-3.23
  rbx-3.24
  rbx-3.25
  rbx-3.26
  rbx-3.27
  rbx-3.28
  rbx-3.29
  rbx-3.30
  rbx-3.31
  rbx-3.32
  rbx-3.33
  ree-1.8.7-2011.03
  ree-1.8.7-2011.12
  ree-1.8.7-2012.01
  ree-1.8.7-2012.02
  topaz-dev
# 任意のバージョンをインストール
$ rbenv install 2.2.5
Downloading ruby-2.2.5.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.5.tar.bz2
Installing ruby-2.2.5...
Installed ruby-2.2.5 to /Users/makoto/.rbenv/versions/2.2.5
# 利用できるバージョンの確認
$ rbenv versions
* system (set by /Users/makoto/.rbenv/version)
  2.2.5
# 有効になっているバージョンの確認
$ rbenv version
system (set by /Users/makoto/.rbenv/version)
# 環境全体のバージョンを変更
$ rbenv global 2.2.5
# ディレクトリ固有のバージョン変更
$ rbenv local 2.2.5
# バージョン確認
$ rbenv version
2.2.5 (set by /Users/makoto/.rbenv/version)
# rubyコマンドでもバージョン確認
$ ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14] # 。。。っ!!?

バージョンの切り替えが上手くいかなかった原因

~/.bash_profileに以下を追記する必要があった。

eval "$(rbenv init -)"

これをしないと、rbenvでインストールしたrubyのPATHが反映されない。

$ vi ~/.bash_profile # eval "$(rbenv init -)"を追記
$ source ~/.bash_profile # .bash_profileを読み込み、追記した設定を反映
# 改めてバージョンを確認
$ ruby -v
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin14]

参考サイト

rbenvでRubyのバージョンアップをする(for Mac) - Qiita

rbenv を利用した Ruby 環境の構築 | Developers.IO

rbenvでバージョンがうまく切り替わらなかった時にやったこと - Qiita

『初めてのRuby』

0 3 * * 1 /root/bin/clamdscan.sh > /dev/null 2>&1

http://mktktmr.hatenablog.jp/entry/

初めてのRuby

を読み始めたので、ちょっとずつ、要点をメモってく。 自分がJava屋出身なので、Javaとの違いとか書いてくかも(書くとは言っていない)

読み始めて気付いたこと

この記事を書いてる時点(2016/06/08)でこの書籍はまだ初版なのですが、これからRubyを始める人にとっては情報が古くてしんどいかも。

というのも、この書籍がカバーしているRubyのバージョンは1.9までで、現時点での最新の安定版は2.2.5。

著者はバージョン2.0で大きな変化があるはずと予言(実際にそうなったかは、今後調べる)していて、もし本当なら、この書籍を通して勉強して大丈夫なのかと不安に駆られる。

まあ、Rubyの歴史を勉強するというつもりで読めば良いかも 笑

1章

バージョン体系

バージョンの書式

(Major).(Minor).(Teeny)(Patch Level)
  • Minor
    • 偶数のバージョンが安定版
      ※ 1.9は例外で1.9.0が開発版で1.9.1以降は安定版
  • Path Level
    • 1.9以降に導入された形式でバグ修正のカウント数
    • 非互換性は含まれない
  • Teeny
    • ライブラリへの新機能の追加やAPIのdeprecateが含まれる場合がある
    • 互換性に対する注意が必要

例)バージョンの確認

ruby -v
ruby 2.0.0p481

構成

言語本体

変数やクラス定義、メソッド定義、制御構造などを含む言語本体の仕様。
この仕様に基づいて、プログラムやライブラリを解釈、実行することを処理系と呼ぶ。

組み込みライブラリ

入出力や文字列、配列など、処理系に組み込まれている基本的なライブラリで、明示的にライブラリをロードしなくても利用できる。
また、以下のように細分化できる。

  • 組み込み定数
  • 組み込み変数
  • 組み込み関数
  • 組み込みクラス

標準添付ライブラリ

処理系に付属して配布される外部ライブラリで、明示的にライブラリをロードしないと利用できない。

RubyGems

Ruby1.9から標準添付ライブラリに入り、デファクトスタンダードとなっているRubyのパッケージ管理システム。

Rubyの処理系実装

MRI (Matz's Ruby Implementation)

オリジナルのRuby実装。C言語で書かれているためCRubyとも呼ばれる。

JRuby

MRIJavaで書き直して実装されていて、JVM上で動作する。

IronRuby

.NET Dynamic Language Runtime上で動作する実装。

実行モデル

MRIの場合、インタプリタ
1.9以降は、

解析 => バイトコード変換 => 実行  

という流れ。
解析フェーズでは構文上の妥当性のみ検証されるので、存在しないクラスの継承などは実行時にエラーとなる。

ガベージコレクション

が、実装されているので、プログラマがメモリ管理をする必要はない。

実行時ロード

外部ライブラリをロードする際は実行時にロードされる

main.rb

require 'exlib.rb'

# メイン処理

上記ソースの場合、

  1. main.rbの解析(この時点でexlib.rbの解析は行われない)
  2. main.rbの実行
    2.1. main.rbの実行開始
    2.2. exlib.rbの解析(この時点でまだメイン処理は実行されていない)
    2.3. exlib.rbの実行
    2.4. main.rbの実行に戻る(メイン処理の実行)

という順番で処理が行われる。

文法と機能

式の区切り

入出力

制御式

ブロック付きメソッド

イテレータ
リソース管理
コールバック

OOP

クラス
特異メソッド
演算子ポリモフィズム

2

章 配列とハッシュ

配列

参照

  • まず知っておくべきことは、添字参照はArray#[]メソッドのシンタックスシュガーであること
    • array[0] => array.
  • 範囲外の要素を参照するとnilを返す
array = [0, 1, 2, 3]
puts array[4] # nil. JavaのListクラスの場合、範囲外の要素を参照しようとすると例外(IndexOutOfBoundsException)が発生する
  • 負の添字
    末尾から逆順に要素を取得する
array = [0, 1, 2, 3]
puts array[-1] # 3. array[array.length-1]と等価
puts array[-2] # 2
  • 位置と長さを指定して取得
array = [0, 1, 2, 3]
puts array[2, 2] # [2, 3]. 2番目の要素から2個の要素を取得.
puts array[2, 100] # [2, 100]. 範囲内の要素が含まれていればそれだけを返す
puts array[100, 1] # nil. 範囲内の要素が含まれていなければ、nilを返す
puts array[-3, 3] # [1, 2, 3]. 位置の指定には負の値が利用できる(長さには使えない)
  • 範囲の指定
array = [0, 1, 2, 3]
puts array[1..3] # [1, 2, 3]
puts array[1...3] # [1, 2]. 末端を含まない範囲指定には「...」を利用する
puts array[-4..-3] # [0, 1]. 負の値を範囲の指定に利用できる
puts array[-4..1] # [0, 1]

代入

  • 添字代入はArray#[]=メソッドのシンタックスシュガー
  • 添字代入のいろいろ
array = [1,2]
array[0] = 3 # [3, 2]
array[4] = 4 # [3, 2, nil, nil, 4]. 範囲外を指定して代入した場合、配列が自動的に拡張され、空白の部分にはnilが挿入される
array[0, 3] = 'a', 'b', 'c' # ["a", "b", "c", nil, 4]. 位置と長さによる指定で代入もできる
array[0, 3] = 'a', 'b', 'c', 'd' # ["a", "b", "c", "d", nil, 4]. 左辺で指定した要素数よりも右辺の式が多い場合、配列が拡張されて代入される
array[1..2] = 1, 2 # ["a", 1, 2, "d", nil, 4]
array[0, 2] = '?' # ["?", 2, "d", nil, 4]. #左辺で指定した要素数よりも、右辺の式が少ない場合、配列が詰められて代入される
array[0..2] = 'A' # ["A", nil, 4]
array[-1] = 'Z' # ["A", nil, "Z"]

【Ubuntu】Hubotの開発環境構築をVagrantで自動化

Hubotを開発するための環境構築用のVagrantfile作りました。

github.com

ホストOSで起動しているクライアントからのリクエストがゲストOSで起動したHubotに飛ぶようになっています。

Slackがクライアントの場合でしか試せてませんが、他のクライアントでもいけると思います。

また、node-inspectorとChromeがインストールされるようプロビジョニングしているので、GUIデバッグすることもできます。

なお、前提としてゲストOSはUbuntuデスクトップです。

以前上げた記事のBoxファイルをベースにしてます。

mktktmr.hatenablog.jp

はまったこと

nodeのバージョンが古い

最初、下記の記事とか類似の記事がたくさんあったので参考にnodeを入れたのですが、最新が入りませんでした。

Ubuntu 14.04 に Node.jsをインストールする - Qiita

結局、公式に行ったら答えがありました。

Installing Node.js via package manager | Node.js

curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash - sudo apt-get install -y nodejs

npmのバージョンが古い

Node.jsとnpmをアップデートする方法 – Rriver

npm update -g npm

で解決。

再起動するとiptablesの設定が吹っ飛ぶ

Ubuntuは再起動するたびにiptablesの設定がリセットされてしまうみたい。

iptables-persistentというツールを使うと永続化できます。

$ sudo apt-get install -y iptables-persistent

これで解決だと思いきや、プロビジョニングで、エラーが発生。。。

$ sudo apt-get install -y iptables-persistent
・
・
・
==> default: dpkg-preconfigure: 標準入力を再オープンできません: そのようなファイルやディレクトリはありません

環境変数DEBIAN_FRONTENDnoninteractiveにしてインストールすることで解決できました。

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y iptables-persistent

DEBIAN_FRONTEND=noninteractive ってなんだ - Qiita

これは、インストーラで使うユーザインタフェースを制御するものらしい。 DEBIAN_FRONTEND=noninteractive のときは、インタラクティブな設定をしなくなる(=入力待ちでブロックしなくなる)ので、自動インストールの際には便利だとか。

Chromeのインストールでエラーが発生する

sudo wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
sudo apt-get update
sudo apt-get install -y google-chrome-stable
・
・
・
==> default: W
==> default: : 
==> default: http://dl.google.com/linux/chrome/deb/dists/stable/Release の取得に失敗しました  期待されるエントリ 'main/binary-i386/Packages' が Release ファイル内に見つかりません (誤った sources.list エントリか、壊れたファイル)
==> default: E
==> default: : 
==> default: いくつかのインデックスファイルのダウンロードに失敗しました。これらは無視されるか、古いものが代わりに使われます。

Google Chromeのリポジトリ取得に失敗しましたエラーを修正する | Ubuntuアプリのいいところ

これは、2016年3月に、32bit-LinuxへのGoogle Chromeのサポートが終了した後に発生しているエラーで、64bit版のUbuntuにおいても同じ現象が発生します。

というわけで、

sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'

というふうに、アーキテクチャを64bitに指定することでエラーを回避できます。

参考

Hubotインストール

slackと連携するhubotを3分でインストールする(動画付き)

nodeインストール

Installing Node.js via package manager | Node.js

redisインストール

Ubuntu Linux 14.04 LTSにRedis 3をインストールする - CLOVER

iptables

mysql - Vagrant and MariaDB (provision) - Server Fault

Ubuntu 14.04 で OpenVPN - BLOG EX MACHINA

ubuntu - dpkg-reconfigure: unable to re-open stdin: No file or directory - Server Fault

Chromeのインストール

Ubuntu 14.04:Google Chrome インストール | よしまさのブログ

【Vagrant】日本語環境に設定したUbutuデスクトップをBoxファイルにする

環境

  • ホストOS:OSX
  • ゲストOS:Ubuntu14.02
  • Vagrant :1.8.1
  • プロバイダ:VirtualBox 5.0.16
  • Packer:0.10.0

※最終的に行うBoxファイルの作成はVirtualBoxのみ対応しているので、ご注意を。

手順

PackerによるBoxファイルの作成

VagrantとPackerについては過去記事でも上げてます。

mktktmr.hatenablog.jp

mktktmr.hatenablog.jp

まずはベースとなるBoxファイルをPackerを利用して作成します。

Packerのテンプレートを一から作るのは大変なため、boxcutterをフォークして作成しています。

ubuntu/ubuntu1404-desktop.json at master · mktktmr/ubuntu · GitHub

ubuntu1404-desktop.json

{
  "_comment": "Build with `packer build -var-file=ubuntu1404-desktop.json ubuntu.json`",
  "vm_name": "ubuntu1404-desktop",
  "desktop": "true",
  "cpus": "1",
  "disk_size": "130048",
  "iso_checksum": "3ffb7a3690ce9a07ac4a4d1b829f990681f7e47d",
  "iso_checksum_type": "sha1",
  "iso_name": "ubuntu-14.04.4-server-amd64.iso",
  "iso_path": "iso",
  "iso_url": "http://ftp.riken.jp/Linux/ubuntu-releases/14.04.2/ubuntu-14.04.4-server-amd64.iso",
  "memory": "2048",
  "preseed": "preseed.cfg",
  "vagrantfile_template": "tpl/vagrantfile-ubuntu1404-desktop.tpl"
}

boxcutterのテンプレートからの主な変更点は、ISOイメージの取得先をオリジナルから、理研のミラーサーバに変更しています。

多分日本でダウンロードするならそのほうが早いかなと。

また、試行錯誤するために何度かpacker buildを繰り返したのですが、そのたびにISOイメージをダウンロードしてると時間かかるし、通信料がばかになりません。

PackerのビルドはローカルにISOイメージがあればダウンロードせずにそちらを参照する仕組みになっています。

その際に参照するディレクトリのPATHの設定が「iso_path」で、そこの値も変えています。

というわけであらかじめ理研ミラーサイトからISOファイルを入手して、gitのクローン先にisoディレクトリ掘って、突っ込んでおきます。

テンプレートの作成が終わったら、packer buildでテンプレートファイルを元にBoxファイルを作成します。

$ packer build -only=virtualbox-iso -var-file=ubuntu1404-desktop.json ubuntu.json
virtualbox-iso output will be in this color.

==> virtualbox-iso: Downloading or copying Guest additions
    virtualbox-iso: Downloading or copying: file:///Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
==> virtualbox-iso: Downloading or copying ISO
    virtualbox-iso: Downloading or copying: file:///Users/hoge/Documents/%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%A9/iso/ubuntu-14.04.4-server-amd64.iso
==> virtualbox-iso: Creating floppy disk...
    virtualbox-iso: Copying: http/preseed.cfg
==> virtualbox-iso: Creating virtual machine...
==> virtualbox-iso: Creating hard drive...
==> virtualbox-iso: Attaching floppy disk...
==> virtualbox-iso: Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port 3667)
==> virtualbox-iso: Executing custom VBoxManage commands...
    virtualbox-iso: Executing: modifyvm ubuntu1404-desktop --memory 2048
    virtualbox-iso: Executing: modifyvm ubuntu1404-desktop --cpus 1
==> virtualbox-iso: Starting the virtual machine...
==> virtualbox-iso: Waiting 10s for boot...
==> virtualbox-iso: Typing the boot command...
==> virtualbox-iso: Waiting for SSH to become available...
==> virtualbox-iso: Connected to SSH!
==> virtualbox-iso: Uploading VirtualBox version info (5.0.16)
==> virtualbox-iso: Uploading VirtualBox guest additions ISO...
==> virtualbox-iso: Provisioning with shell script: script/update.sh
    virtualbox-iso: ==> Disabling the release upgrader
    virtualbox-iso: ==> Updating list of repositories
    virtualbox-iso: Ign http://us.archive.ubuntu.com trusty InRelease
    virtualbox-iso: Get:1 http://us.archive.ubuntu.com trusty-updates InRelease [65.9 kB]
    virtualbox-iso: Get:2 http://security.ubuntu.com trusty-security InRelease [65.9 kB]
    virtualbox-iso: Get:3 http://us.archive.ubuntu.com trusty-backports InRelease [65.9 kB]
    virtualbox-iso: Hit http://us.archive.ubuntu.com trusty Release.gpg
    ・
    ・
    中略
    ・
    ・
    virtualbox-iso: zenity-common                   install
    virtualbox-iso: zip                     install
    virtualbox-iso: zlib1g:amd64                    install
    virtualbox-iso: ==> Clearing last login information
    virtualbox-iso: 118528571+0 records in
    virtualbox-iso: 118528571+0 records out
    virtualbox-iso: 121373256704 bytes (121 GB) copied, 425.23 s, 285 MB/s
    virtualbox-iso: 189336+0 records in
    virtualbox-iso: 189336+0 records out
    virtualbox-iso: 193880064 bytes (194 MB) copied, 0.478528 s, 405 MB/s
    virtualbox-iso: ==> Clear out swap and disable until reboot
    virtualbox-iso: dd: error writing ‘/dev/dm-1’: No space left on device
    virtualbox-iso: 2049+0 records in
    virtualbox-iso: 2048+0 records out
    virtualbox-iso: 2147483648 bytes (2.1 GB) copied, 3.58034 s, 600 MB/s
    virtualbox-iso: dd exit code 1 is suppressed
    virtualbox-iso: mkswap: /dev/dm-1: warning: don't erase bootbits sectors
    virtualbox-iso: on whole disk. Use -f to force.
    virtualbox-iso: Setting up swapspace version 1, size = 2097148 KiB
    virtualbox-iso: no label, UUID=b604802c-0ad0-41a1-ade1-aa8d8d81dce5
    virtualbox-iso: dd: error writing ‘/EMPTY’: No space left on device
    virtualbox-iso: 122139+0 records in
    virtualbox-iso: 122138+0 records out
    virtualbox-iso: 128071090176 bytes (128 GB) copied, 287.836 s, 445 MB/s
    virtualbox-iso: dd exit code 1 is suppressed
    virtualbox-iso: ==> Disk usage before cleanup
    virtualbox-iso: Filesystem Size Used Avail Use% Mounted on udev 990M 4.0K 990M 1% /dev tmpfs 201M 476K 200M 1% /run /dev/mapper/vagrant--vg-root 123G 3.4G 114G 3% / none 4.0K 0 4.0K 0% /sys/fs/cgroup none 5.0M 0 5.0M 0% /run/lock none 1001M 0 1001M 0% /run/shm none 100M 0 100M 0% /run/user /dev/sda1 236M 39M 185M 18% /boot
    virtualbox-iso: ==> Disk usage after cleanup
    virtualbox-iso: Filesystem                    Size  Used Avail Use% Mounted on
    virtualbox-iso: udev                          990M  8.0K  990M   1% /dev
    virtualbox-iso: tmpfs                         201M  476K  200M   1% /run
    virtualbox-iso: /dev/mapper/vagrant--vg-root  123G  3.4G  114G   3% /
    virtualbox-iso: none                          4.0K     0  4.0K   0% /sys/fs/cgroup
    virtualbox-iso: none                          5.0M     0  5.0M   0% /run/lock
    virtualbox-iso: none                         1001M     0 1001M   0% /run/shm
    virtualbox-iso: none                          100M     0  100M   0% /run/user
    virtualbox-iso: /dev/sda1                     236M   39M  185M  18% /boot
==> virtualbox-iso: Gracefully halting virtual machine...
    virtualbox-iso: Removing floppy drive...
==> virtualbox-iso: Preparing to export machine...
    virtualbox-iso: Deleting forwarded port mapping for the communicator (SSH, WinRM, etc) (host port 3667)
==> virtualbox-iso: Exporting virtual machine...
    virtualbox-iso: Executing: export ubuntu1404-desktop --output output-ubuntu1404-desktop-virtualbox-iso/ubuntu1404-desktop.ovf
==> virtualbox-iso: Unregistering and deleting virtual machine...
==> virtualbox-iso: Running post-processor: vagrant
==> virtualbox-iso (vagrant): Creating Vagrant box for 'virtualbox' provider
    virtualbox-iso (vagrant): Copying from artifact: output-ubuntu1404-desktop-virtualbox-iso/ubuntu1404-desktop-disk1.vmdk
    virtualbox-iso (vagrant): Copying from artifact: output-ubuntu1404-desktop-virtualbox-iso/ubuntu1404-desktop.ovf
    virtualbox-iso (vagrant): Renaming the OVF to box.ovf...
    virtualbox-iso (vagrant): Using custom Vagrantfile: tpl/vagrantfile-ubuntu1404-desktop.tpl
    virtualbox-iso (vagrant): Compressing: Vagrantfile
    virtualbox-iso (vagrant): Compressing: box.ovf
    virtualbox-iso (vagrant): Compressing: metadata.json
    virtualbox-iso (vagrant): Compressing: ubuntu1404-desktop-disk1.vmdk
Build 'virtualbox-iso' finished.

==> Builds finished. The artifacts of successful builds are:
--> virtualbox-iso: 'virtualbox' provider box: box/virtualbox/ubuntu1404-desktop-nocm-0.1.0.box

Boxファイルの登録

作成したBoxファイルをvagrantに登録します。

登録のためのコマンドはvagrant box add {登録名} {Boxファイルのパス | URL}です。

登録名は任意ですが、今回は「ubuntu1404-desktop」にしておきます。

$ vagrant box add ubuntu1404-desktop box/virtualbox/ubuntu1404-desktop-nocm-0.1.0.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box '1404-desktop' (v0) for provider: 
    box: Unpacking necessary files from: file:///Users/hoge/Documents/git/boxcutter/ubuntu/box/virtualbox/ubuntu1404-desktop-nocm-0.1.0.box
==> box: Successfully added box '1404-desktop' (v0) for 'virtualbox'!

仮想マシンの起動

vagrant initをすることでVagrantfileのテンプレートファイルが作成されます。

引数には先ほど登録したBoxファイルの名前を指定します。

$ vagrant init ubuntu1404-desktop
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.
$ ls
Vagrantfile

Vagrantファイルの中身を確認。

Vagrantfile

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

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "ubuntu1404-desktop"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   sudo apt-get update
  #   sudo apt-get install -y apache2
  # SHELL
end

今回立ち上げるゲストOSは日本語化のベースにするだけで、特にプロビジョニングなどはしないため、修正は行わずそのまま使います。

config.vm.boxの値のが正しく設定されていることだけ確認できればOKです。

というわけで、vagrant initに続けてvagrant up仮想マシンを立ち上げます。

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu1404-desktop'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: ubuntu1404-desktop_default_1459864237341_70016
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (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: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: 
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/hoge/Documents/vagrant/ubuntu1404-desktop

f:id:mktktmr:20160405225501p:plain

日本語環境の設定

以下、ゲストOSのUbuntuでの作業になります。

ソフトウェアアップデート

初めてUbuntuを立ち上げるとソフトウェアアップデートの通知が来るので、アップデートしておきます。

f:id:mktktmr:20160328123142p:plain

f:id:mktktmr:20160328123153p:plain

f:id:mktktmr:20160328123203p:plain

再起動が必要な設定がこの後もあるので、ここでは再起動しないことにします。

f:id:mktktmr:20160328123213p:plain

日付のローカライズ

タイムゾーンをTokyoに設定します。

System Settings > Time&Date を選択します。

f:id:mktktmr:20160406194942p:plain

f:id:mktktmr:20160328123223p:plain

地図をクリックしたり、フォームに直接入力するなどしてLocationをTokyoに設定。

f:id:mktktmr:20160328123232p:plain

f:id:mktktmr:20160328123242p:plain

ついでにClockの設定も好みに合わせて設定しておきます。

f:id:mktktmr:20160328123251p:plain

言語のローカライズ

System Settings > Language Support を選択します。

f:id:mktktmr:20160328123258p:plain

Language Supportを開くと、「言語サポートに必要なソフトウェアのインストールが完了していないので、インストールしてください」的なことを言われます。

英語のサポートなので必要ないかもしれませんが、一応インストールします。

f:id:mktktmr:20160328123306p:plain

f:id:mktktmr:20160328123312p:plain

f:id:mktktmr:20160328123319p:plain

本題の日本語化の作業に入ります。

Install / Remove Languages を選択します。

f:id:mktktmr:20160328123326p:plain

Japaneseにチェックを入れて、Apply Changesをクリック。

f:id:mktktmr:20160328123333p:plain

日本語の言語サポートに必要なソフトウェアのインストールが始まります。

f:id:mktktmr:20160328123340p:plain

インストールが終了したら、日本語の優先度を上げるため言語のリストの一番上に「日本語」が来るようにドラッグします。

日本語を一番上にしたら、Apply System-Wideをクリックし、システム全体に適用します。

f:id:mktktmr:20160328123347p:plain

次に通貨や日付のフォーマットを日本に合わせる設定を行います。

Regional Format タブを選択します。

f:id:mktktmr:20160328123356p:plain

日本語を選択し、Apply System-Wideをクリックし、システム全体に適用します。

設定直後はExampleが正しく反映されません。

Language Supportを開き直すと正しく反映されるので、開き直して確認します。

f:id:mktktmr:20160328123405p:plain

f:id:mktktmr:20160328123412p:plain

ここまで設定したら、仮想マシンを再起動します。

再起動はホストOSのコンソールからvagrant reloadを叩いて行います。

再起動が済むとフォルダ名を日本語にリネームするか聞かれますので、好みでリネームするかどうか選択してください。

f:id:mktktmr:20160328123421p:plain

ちなみに私はしませんでした。

キーマップのローカライズ

キーボードのレイアウトがUS配列になっているので、日本語配列に設定します。

システム設定 > テキスト入力を選択。

f:id:mktktmr:20160328123430p:plain

日本語(Anthy)を選択して右下に現れるツールアイコンをクリックします。

f:id:mktktmr:20160406230541p:plain

IBus-Anthyの設定ダイアログが開くので、入力タイプを選択します。

f:id:mktktmr:20160328123437p:plain

キーボードレイアウトをデフォルトからjpに変更します。

f:id:mktktmr:20160407193512p:plain

f:id:mktktmr:20160407193521p:plain

ibusを再起動してくださいと表示されますが、一度ログアウトしてログインしなおすだけで大丈夫です。

f:id:mktktmr:20160328123500p:plain

ここまでで日本語化の作業は終わりになります。

ホストOSに戻ってvagrant halt仮想マシンを止めてください。

日本語環境にした仮想環境のBoxファイルの出力

日本語設定を行った仮想マシンのVagrantfileがあるディレクトリでvagrant packageを実行することで、日本語設定がされた状態のBoxファイルを作成することができます。

下記例では--output オプションで出力されるBoxファイルのファイル名を指定しています。

指定しないとデフォルトの package.boxというファイル名で出力されます。

$ vagrant package --output ubuntu1404-ja-desktop-nocm-0.1.0.box
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: /Users/hoge/Documents/vagrant/ubuntu1404-desktop/ubuntu1404-ja-desktop-nocm-0.1.0.box

ここまでの作業で日本語環境になったUbuntuが使えるようになりました。

利用のする際はBoxファイルの登録で行ったようにvagrant box addをしてvagrant initvagrant upをするだけです。

今後はこのBoxファイルをベースに、Vagrantfileでプロビジョニングして色々と開発環境を作ってみようと思います。

参考

Vagrantの既存Boxに日本語環境 + GuestAdditions + Chefを入れ、新しいBoxとして追加する - メモ的な思考的な

Ubuntu 13.10 その7 - 日本語環境の構築・Ubuntu Japanese Teamのリポジトリーを追加する - kledgeb

【Vagrant】Packerでboxファイルの作成

以前、vagrantの初歩的な使い方について記事を挙げましたが、その際に利用したBoxファイルはvagrantboxからダウンロードしていました。

mktktmr.hatenablog.jp

今回は他人が作ったBoxファイルを拝借していたのを、自作にしようというのが趣旨です。

環境

Packerの入手

Boxファイルを作成するツールは幾つかあるみたいですが、一番メジャーそうなPackerを使います。

Packer by HashiCorp

公式サイトからツールをダウンロードしてきます。

ダウンロードしたファイル(packer_0.10.0_darwin_amd64.zip)を解凍すると"packer"になります。

自分は上記pakerを"/usr/local/bin/"ディレクトリに移動しました。

テンプレートの入手

一からBoxファイルのテンプレート(設定ファイル)を作成するのは大変なためboxcutterからテンプレートを入手します。

今回はUbuntuのBoxファイルを作るので、Ubuntuリポジトリをgitクローンしておきます。

テンプレートの設定値を変えることで、作成する仮想マシンのディスク容量やメモリ量、ISOファイルのダウンロード先などを変更できますが、今回はいじらず、デフォルトで作成します。

$ git clone https://github.com/boxcutter/ubuntu.git
Cloning into 'ubuntu'...
remote: Counting objects: 1790, done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 1790 (delta 3), reused 0 (delta 0), pack-reused 1776
Receiving objects: 100% (1790/1790), 323.25 KiB | 21.00 KiB/s, done.
Resolving deltas: 100% (1178/1178), done.
Checking connectivity... done.
$ cd ubuntu
$ ls -la
-rw-r--r--   1 hoge  staff   9630  3 21 03:04 ubuntu1510.json
-rw-r--r--   1 hoge  staff    421  3 21 03:04 ubuntu1404.json
-rw-r--r--   1 hoge  staff    544  3 21 03:04 ubuntu1404-i386.json
-rw-r--r--   1 hoge  staff    455  3 21 03:04 ubuntu1404-docker.json
-rw-r--r--   1 hoge  staff    421  3 21 03:04 ubuntu1204.json
-rw-r--r--   1 hoge  staff    544  3 21 03:04 ubuntu1204-i386.json
-rw-r--r--   1 hoge  staff    455  3 21 03:04 ubuntu1204-docker.json
-rw-r--r--   1 hoge  staff    547  3 21 03:04 ubuntu1204-desktop.json
drwxr-xr-x   6 hoge  staff    204  3 21 03:04 tpl
drwxr-xr-x   5 hoge  staff    170  3 21 03:04 test
drwxr-xr-x  14 hoge  staff    476  3 21 03:04 script
drwxr-xr-x   5 hoge  staff    170  3 21 03:04 floppy
-rw-r--r--   1 hoge  staff    218  3 21 03:04 custom-script.sh
drwxr-xr-x  10 hoge  staff    340  3 21 03:04 bin
-rw-r--r--   1 hoge  staff      7  3 21 03:04 VERSION
-rw-r--r--   1 hoge  staff   8381  3 21 03:04 README.md
-rw-r--r--   1 hoge  staff   4170  3 21 03:04 Makefile
-rw-r--r--   1 hoge  staff  11335  3 21 03:04 LICENSE
-rw-r--r--   1 hoge  staff   4528  3 21 03:04 CHANGELOG.md
-rw-r--r--   1 hoge  staff    887  3 21 03:04 AUTHORS
drwxr-xr-x   2 hoge  staff     68  3 23 07:29 tmp
-rw-r--r--   1 hoge  staff   8580  3 23 19:08 ubuntu.json
drwxr-xr-x   6 hoge  staff    204  3 25 21:41 iso
drwxr-xr-x   3 hoge  staff    102  3 25 21:46 packer_cache
drwxr-xr-x   6 hoge  staff    204  3 25 21:50 http
-rw-r--r--   1 hoge  staff    565  3 27 10:48 ubuntu1404-desktop.json
drwxr-xr-x   5 hoge  staff    170  3 27 15:26 box

boxファイルの作成

packer buildでbuildを実行。

boxcutterのテンプレートはpacker buildの-var-fileオプションで設定するテンプレートを組み合わせることで、 様々なOSバージョンやアーキテクチャに対応できるように構成されています。

今回はUbuntu14.04のデスクトップ版のBoxファイルを作成するため、ubuntu1404-desktop.jsonubuntu.jsonを組み合わせてbuildします。

ちなみに、packer buildはISOファイルのダウンロードなどあるためかなり時間がかかります(1時間くらい)。

気長に待ちましょう。

# 今回作成するBoxファイルはVirtualBox向けのものだけなので、オプションに-only=virtualbox-isoを設定しています
$ packer build -only=virtualbox-iso -var-file=ubuntu1404-desktop.json ubuntu.json
virtualbox-iso output will be in this color.

==> virtualbox-iso: Downloading or copying Guest additions
    virtualbox-iso: Downloading or copying: file:///Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso
==> virtualbox-iso: Downloading or copying ISO
    virtualbox-iso: Downloading or copying: file:///Users/hoge/Documents/ubuntu-14.04.4-server-amd64.iso
==> virtualbox-iso: Creating floppy disk...
    virtualbox-iso: Copying: http/preseed.cfg
==> virtualbox-iso: Creating virtual machine...
==> virtualbox-iso: Creating hard drive...
==> virtualbox-iso: Attaching floppy disk...
==> virtualbox-iso: Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port 2590)
==> virtualbox-iso: Executing custom VBoxManage commands...
    virtualbox-iso: Executing: modifyvm ubuntu1404-desktop --memory 2048
    virtualbox-iso: Executing: modifyvm ubuntu1404-desktop --cpus 1
==> virtualbox-iso: Starting the virtual machine...
==> virtualbox-iso: Waiting 10s for boot...
==> virtualbox-iso: Typing the boot command...
==> virtualbox-iso: Waiting for SSH to become available...
==> virtualbox-iso: Connected to SSH!
==> virtualbox-iso: Uploading VirtualBox version info (5.0.16)
==> virtualbox-iso: Uploading VirtualBox guest additions ISO...
==> virtualbox-iso: Provisioning with shell script: script/update.sh
    virtualbox-iso: ==> Disabling the release upgrader
    virtualbox-iso: ==> Updating list of repositories
    virtualbox-iso: Ign http://us.archive.ubuntu.com trusty InRelease
    virtualbox-iso: Hit http://security.ubuntu.com trusty-security InRelease
    virtualbox-iso: Hit http://us.archive.ubuntu.com trusty-updates InRelease
#〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜(中略)〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
    virtualbox-iso: 0 upgraded, 1296 newly installed, 0 to remove and 26 not upgraded.
    virtualbox-iso: Need to get 549 MB of archives.
    virtualbox-iso: After this operation, 2,093 MB of additional disk space will be used.
    virtualbox-iso: Get:1 http://us.archive.ubuntu.com/ubuntu/ trusty/main libavahi-common-data amd64 0.6.31-4ubuntu1 [21.2 kB]
    virtualbox-iso: Get:2 http://us.archive.ubuntu.com/ubuntu/ trusty/main libavahi-common3 amd64 0.6.31-4ubuntu1 [21.7 kB]
    virtualbox-iso: Get:3 http://us.archive.ubuntu.com/ubuntu/ trusty/main libavahi-client3 amd64 0.6.31-4ubuntu1 [25.1 kB]
    virtualbox-iso: Get:4 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main libcups2 amd64 1.7.2-0ubuntu1.7 [179 kB]
    virtualbox-iso: Get:5 http://us.archive.ubuntu.com/ubuntu/ trusty-updates/main libcupsmime1 amd64 1.7.2-0ubuntu1.7 [12.1 kB]
    virtualbox-iso: Get:6 http://us.archive.ubuntu.com/ubuntu/ trusty/main libpaper1 amd64 1.1.24+nmu2ubuntu3 [13.4 kB]
#〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜(中略)〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
    virtualbox-iso: Get:1292 http://us.archive.ubuntu.com/ubuntu/ trusty/main unity-lens-friends amd64 0.1.3+14.04.20140317-0ubuntu1 [22.9 kB]
    virtualbox-iso: Get:1293 http://us.archive.ubuntu.com/ubuntu/ trusty/main unity-scope-gdrive all 0.9+13.10.20130723-0ubuntu1 [11.6 kB]
    virtualbox-iso: Get:1294 http://us.archive.ubuntu.com/ubuntu/ trusty/main usb-modeswitch-data all 20140327-1 [27.0 kB]
    virtualbox-iso: Get:1295 http://us.archive.ubuntu.com/ubuntu/ trusty/main usb-modeswitch amd64 2.1.1+repack0-1ubuntu1 [50.0 kB]
    virtualbox-iso: Get:1296 http://us.archive.ubuntu.com/ubuntu/ trusty/main xfonts-mathml all 6ubuntu1 [42.5 kB]
    virtualbox-iso: [sudo] password for vagrant: debconf: unable to initialize frontend: Dialog
    virtualbox-iso: debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
    virtualbox-iso: debconf: falling back to frontend: Readline
    virtualbox-iso: debconf: unable to initialize frontend: Readline
    virtualbox-iso: debconf: (This frontend requires a controlling tty.)
    virtualbox-iso: debconf: falling back to frontend: Teletype
    virtualbox-iso: dpkg-preconfigure: unable to re-open stdin:
    virtualbox-iso: Fetched 549 MB in 34min 7s (268 kB/s)
    virtualbox-iso: Selecting previously unselected package libavahi-common-data:amd64.
    virtualbox-iso: (Reading database ... 61160 files and directories currently installed.)
    virtualbox-iso: Preparing to unpack .../libavahi-common-data_0.6.31-4ubuntu1_amd64.deb ...
    virtualbox-iso: Unpacking libavahi-common-data:amd64 (0.6.31-4ubuntu1) ...
#〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜(中略)〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
    virtualbox-iso: zenity-common                   install
    virtualbox-iso: zip                     install
    virtualbox-iso: zlib1g:amd64                    install
    virtualbox-iso: ==> Clearing last login information

    virtualbox-iso: 118528559+0 records in
    virtualbox-iso: 118528559+0 records out
    virtualbox-iso: 121373244416 bytes (121 GB) copied, 438.839 s, 277 MB/s
    virtualbox-iso: 189341+0 records in
    virtualbox-iso: 189341+0 records out
    virtualbox-iso: 193885184 bytes (194 MB) copied, 0.553525 s, 350 MB/s
    virtualbox-iso: ==> Clear out swap and disable until reboot
    virtualbox-iso: dd: error writing ‘/dev/dm-1’: No space left on device
    virtualbox-iso: 2049+0 records in
    virtualbox-iso: 2048+0 records out
    virtualbox-iso: 2147483648 bytes (2.1 GB) copied, 3.58726 s, 599 MB/s
    virtualbox-iso: dd exit code 1 is suppressed
    virtualbox-iso: mkswap: /dev/dm-1: warning: don't erase bootbits sectors
    virtualbox-iso: on whole disk. Use -f to force.
    virtualbox-iso: Setting up swapspace version 1, size = 2097148 KiB
    virtualbox-iso: no label, UUID=a02f609d-1d2e-4086-8ed6-b3c1340a89cc
    virtualbox-iso: dd: error writing ‘/EMPTY’: No space left on device
    virtualbox-iso: 122139+0 records in
    virtualbox-iso: dd exit code 1 is suppressed
    virtualbox-iso: 122138+0 records out
    virtualbox-iso: 128071041024 bytes (128 GB) copied, 292.316 s, 438 MB/s
    virtualbox-iso: ==> Disk usage before cleanup
    virtualbox-iso: Filesystem Size Used Avail Use% Mounted on udev 990M 4.0K 990M 1% /dev tmpfs 201M 476K 200M 1% /run /dev/mapper/vagrant--vg-root 123G 3.4G 114G 3% / none 4.0K 0 4.0K 0% /sys/fs/cgroup none 5.0M 0 5.0M 0% /run/lock none 1001M 0 1001M 0% /run/shm none 100M 0 100M 0% /run/user /dev/sda1 236M 39M 185M 18% /boot
    virtualbox-iso: ==> Disk usage after cleanup
    virtualbox-iso: Filesystem                    Size  Used Avail Use% Mounted on
    virtualbox-iso: udev                          990M  8.0K  990M   1% /dev
    virtualbox-iso: tmpfs                         201M  476K  200M   1% /run
    virtualbox-iso: /dev/mapper/vagrant--vg-root  123G  3.4G  114G   3% /
    virtualbox-iso: none                          4.0K     0  4.0K   0% /sys/fs/cgroup
    virtualbox-iso: none                          5.0M     0  5.0M   0% /run/lock
    virtualbox-iso: none                         1001M     0 1001M   0% /run/shm
    virtualbox-iso: none                          100M     0  100M   0% /run/user
    virtualbox-iso: /dev/sda1                     236M   39M  185M  18% /boot
==> virtualbox-iso: Gracefully halting virtual machine...
    virtualbox-iso: Removing floppy drive...
==> virtualbox-iso: Preparing to export machine...
    virtualbox-iso: Deleting forwarded port mapping for the communicator (SSH, WinRM, etc) (host port 2590)
==> virtualbox-iso: Exporting virtual machine...
    virtualbox-iso: Executing: export ubuntu1404-desktop --output output-ubuntu1404-desktop-virtualbox-iso/ubuntu1404-desktop.ovf
==> virtualbox-iso: Unregistering and deleting virtual machine...
==> virtualbox-iso: Running post-processor: vagrant
==> virtualbox-iso (vagrant): Creating Vagrant box for 'virtualbox' provider
    virtualbox-iso (vagrant): Copying from artifact: output-ubuntu1404-desktop-virtualbox-iso/ubuntu1404-desktop-disk1.vmdk
    virtualbox-iso (vagrant): Copying from artifact: output-ubuntu1404-desktop-virtualbox-iso/ubuntu1404-desktop.ovf
    virtualbox-iso (vagrant): Renaming the OVF to box.ovf...
    virtualbox-iso (vagrant): Using custom Vagrantfile: tpl/vagrantfile-ubuntu1404-desktop.tpl
    virtualbox-iso (vagrant): Compressing: Vagrantfile
    virtualbox-iso (vagrant): Compressing: box.ovf
    virtualbox-iso (vagrant): Compressing: metadata.json
    virtualbox-iso (vagrant): Compressing: ubuntu1404-desktop-disk1.vmdk
Build 'virtualbox-iso' finished.

==> Builds finished. The artifacts of successful builds are:
--> virtualbox-iso: 'virtualbox' provider box: box/virtualbox/ubuntu1404-desktop-nocm-0.1.0.box

ここまででBoxファイルの作成は完了です。

box/virtualboxディレクトリ下に

ubuntu1404-desktop-nocm-0.1.0.boxというBoxファイルが出来上がっているはずなので、確認してみてください。

vagrantへのbox追加

これ以降は以前挙げたVagrantの使い方と同じなのですが、一応手順載せておきます。

作業は適当なディレクトリを掘って行ってください。

vagrant box addでboxファイルを登録

$ vagrant box add test box/virtualbox/ubuntu1404-desktop-nocm-0.1.0.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'test' (v0) for provider: 
    box: Unpacking necessary files from: file:///Users/hoge/Documents/ubuntu/box/virtualbox/ubuntu1404-desktop-nocm-0.1.0.box
==> box: Successfully added box 'test' (v0) for 'virtualbox'!

Vagrantfileの作成

vagrant initでVagrantfaileファイルを生成

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

vagrantの実行

vagrant up仮想マシン起動

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'test2'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: ubuntu1404-desktop_default_1458702162155_73549
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (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: 
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/hoge/Documents/vagrant/ubuntu1404-desktop

うまく起動したでしょうか?

f:id:mktktmr:20160406192511p:plain

Boxファイルを自作しておけば、中身が分かるし、Boxファイルを余所からダウンロードする時間も省けるため、Boxファイルの登録が気軽にできて良いかと思います。

参考

Appendix B. Automating the installation using preseeding

Packerをつかって3ステップでVagrantのBoxを作る - Qiita

PreseedによるUbuntuの自動インストール入門 - Qiita

日本人向け Packer スクリプト差分 for Ubuntu Trusty - 来年読む。

「Packer」でDocker用のイメージファイルを作ってみよう - さくらのナレッジ

Packerを使ったISOイメージからの仮想マシン自動デプロイ - さくらのナレッジ

【Vagrant】インストールと基本コマンド

環境

用語

プロバイダ

Virtual Boxとか、VM Wareとか仮想マシン本体のこと。 EC2なんかもプロバイダとして利用出来るらしい。

プロビジョニング

Chefとか。 ミドルウェアのインストールや設定を行うツールシェルスクリプトでも出来るみたいで、Chefを使う気満々だったのが少し削がれた。

Boxファイル

仮想マシンを起動する際のベースとなるイメージファイル。 通常、OSイメージをベースにvagrantユーザの作成・sshd起動・プロビジョニングツールのインストールなど最小限の設定を行う。

Vagrantfile

仮想マシンのスペックやプロビジョニングツールの指定などの構成を記述するファイル。 Rubyで記述する。 こいつさえあれば、どんな環境でも同じ仮想マシンが構築できる。

Vagrantインストール

公式サイトからインストーラを入手、ポチポチしてインストールします。

Vagrant by HashiCorp

バージョン確認

$ vagrant -v
Vagrant 1.8.1

ヘルプ

$ vagrant -h
Usage: vagrant [options] <command> [<args>]

    -v, --version                    Print the version and exit.
    -h, --help                       Print this help.

Common commands:
     box             manages boxes: installation, removal, etc.
     connect         connect to a remotely shared Vagrant environment
     destroy         stops and deletes all traces of the vagrant machine
     global-status   outputs status Vagrant environments for this user
     halt            stops the vagrant machine
     help            shows the help for a subcommand
     init            initializes a new Vagrant environment by creating a Vagrantfile
     login           log in to HashiCorp's Atlas
     package         packages a running vagrant environment into a box
     plugin          manages plugins: install, uninstall, update, etc.
     port            displays information about guest port mappings
     powershell      connects to machine via powershell remoting
     provision       provisions the vagrant machine
     push            deploys code in this environment to a configured destination
     rdp             connects to machine via RDP
     reload          restarts vagrant machine, loads new Vagrantfile configuration
     resume          resume a suspended vagrant machine
     share           share your Vagrant environment with anyone in the world
     snapshot        manages snapshots: saving, restoring, etc.
     ssh             connects to machine via SSH
     ssh-config      outputs OpenSSH valid configuration to connect to the machine
     status          outputs status of the vagrant machine
     suspend         suspends the machine
     up              starts and provisions the vagrant environment
     version         prints current and latest Vagrant version

For help on any individual command run `vagrant COMMAND -h`

Additional subcommands are available, but are either more advanced
or not commonly used. To see all subcommands, run the command
`vagrant list-commands`.

# vagrant [subcmd] -h でサブコマンドのヘルプも参照できる
$ vagrant box -h
Usage: vagrant box <subcommand> [<args>]

Available subcommands:
     add
     list
     outdated
     remove
     repackage
     update

For help on any individual subcommand run `vagrant box <subcommand> -h`

Boxファイルのインストール

Boxファイルは自分で作成可能ですが、vagrantbox.esで配布もされています。

自作は必要ができたら取り組むとして今回はvagrantboxから入手します。

Boxファイルの追加

# vagrant box add [box名(任意)] [URL or PATH]
$ vagrant box add Ubuntu14.04_daily_Cloud_Image_amd64 https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'Ubuntu14.04_daily_Cloud_Image_amd64' (v0) for provider: 
    box: Downloading: https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box
==> box: Successfully added box 'Ubuntu14.04_daily_Cloud_Image_amd64' (v0) for 'virtualbox'!

# 確認
$ vagrant box list
Ubuntu14.04_daily_Cloud_Image_amd64 (virtualbox, 0)

Boxファイルの削除

# vagrant box remove [box名]
$ vagrant box remove Ubuntu14.04_daily_Cloud_Image_amd64

Vagrantfileの作成

Vagrantfileは"vagrant init [box名]"を叩くと作成されます。

# vagrant init [box名]
$ vagrant init Ubuntu14.04_daily_Cloud_Image_amd64
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.

# 確認
$ ls
Vagrantfile

vagrant init で作成されたvagrantファイルにはデフォルトで色々書かれているので、それを参考に設定を記述してみた。

ちなみに今回設定していることは以下

  1. 仮想マシンのウィンドウを開く
  2. プロビジョニングの設定
    • パッケージの更新
    • ubuntu-desktopのインストール

Vagrantfile

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

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "Ubuntu14.04_daily_Cloud_Image_amd64"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    ### (1)仮想マシンをGUIで起動する(ウィンドウを立ち上げる)
    vb.gui = true
  
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  ### (2)起動時にパッケージの更新とデスクトップのインストールをする
  ### プロビジョニングは初回のvagrant upでしか走らないので注意
  config.vm.provision "shell", inline: <<-SHELL
    sudo apt-get update
    sudo apt-get install -y ubuntu-desktop
  SHELL
end

仮想マシンの起動と停止

起動

vagrant仮想マシンを起動するには、Vagrantfileがあるディレクトリでvagrant upを叩きます。

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'Ubuntu14.04_daily_Cloud_Image_amd64'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: Ubuntu1404_daily_Cloud_Image_amd64_default_1458397444446_89786
==> 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: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> 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: Remote connection disconnect. Retrying...
    default: 
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default: 
    default: Guest Additions Version: 4.3.36
    default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
    default: /vagrant => /Users/hoge/Documents/vagrant/Ubuntu14.04_daily_Cloud_Image_amd64

Vagrantファイルにて"vb.gui = true"と設定しているので、VirtualBoxのウィンドウで立ち上がる。

VirtualBox

f:id:mktktmr:20160319233308p:plain

初期ユーザは

id: vagrant
pass: vagrant

となってます。

停止

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

廃棄

"vagrant destroy"を叩くと、仮想マシンを廃棄できます。

プロビジョニングの設定などは初期起動時のみしか読み込まれないので、Vagrantfileを書き直した時などは一度仮想マシンを廃棄したほうが良いです。

$ vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] y
==> default: Destroying VM and associated drives...

参考

vagrant

ubuntu

【Python】websocketクライアントの実装

やっつけ。

環境

前提

  • websocket-clientパッケージをインストールしていること

websocket-client 0.35.0 : Python Package Index

Type “python setup.py install” or “pip install websocket-client” to install.

自分はpipでインストールしました。

  • 別途websocketサーバがあること

ソース

wsclient.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import websocket
import thread
import time

def on_message(ws, message):
    print "debug: called on_message"
    print message

def on_error(ws, error):
    print "debug: called on_error"
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        print("debug: websocket is opened")

        while(True):
            line = sys.stdin.readline()
            if line != "":
                print "debug: sending value is " + line
                ws.send(line)

    thread.start_new_thread(run, ())


if __name__ == "__main__":

    param = sys.argv

    url = "デフォルトの接続先";

    if len(param) == 2:
        url = param[1]
        print "debug: param[1] is " + param[1]

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(url,
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

使い方

スクリプトとして実行することを想定しています。

接続

ターミナルを開いて上記ファイルを実行

$ ./wsclient.py

接続先に誤りがなければ、以下のようにハンドシェイクのリクエストとレスポンスが帰ってきます。

正常

--- request header ---
GET /hoge HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com:443
Origin: http://example.com
Sec-WebSocket-Key: JOtIu/5xaswrI2a5IRh/Wg==
Sec-WebSocket-Version: 13


-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Sec-WebSocket-Accept: CjFvo17ay0vliMi8Pdgm8Ve7LME=
Upgrade: WebSocket
-----------------------
debug: websocket is opened

接続先に誤りがある場合は以下のようになります。

接続先に誤りがある場合

$ ./wsclient.py ほげ
debug: param[1] is ほげ
debug: called on_error
url is invalid

ちなみにスクリプトの第一引数にURLを渡せるようにしてあります。渡さない場合はソースに直書きしてあるURLをデフォルトの接続先として接続するようになってます。

メッセージ送信

標準入力からメッセージを投げることができます。

適当にタイプして、エンターを叩くとタイプされたテキストをサーバに送信します。

ターミナル

--- response header ---
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Sec-WebSocket-Accept: CjFvo17ay0vliMi8Pdgm8Ve7LME=
Upgrade: WebSocket
-----------------------
debug: websocket is opened
this is test message
debug: sending value is this is test message

send: '\x81\x95J\x0c5\xad>d\\\xdejeF\x8d>iF\xd9jaP\xde9mR\xc8@'
hoge
debug: sending value is hoge

send: '\x81\x85\x9f"[\xea\xf7M<\x8f\x95'

分かりにくいですが、「this is test message」と「hoge」が入力した文字です。

使い道

あるのかな? 笑

自分はサクッとサーバのレスポンスをテストしたかったので作ってみました。

参考

websocket-client 0.35.0 : Python Package Index

Pythonで学ぶ 基礎からのプログラミング入門 (8) ユーザーからプログラムへの入力をする方法 | マイナビニュース

WebSocket サーバの実装とプロトコル解説 - Block Rockin’ Codes