前人未踏の領域へ WEB・インフラ・プログラミング全般編

フロントエンド、バックエンド、インフラ、言語など、アプリ開発、IOT以外の記録

Vagrant 環境にmysql-5.6をインストールする

Vagrant環境にMySQLをインストールする。

Vagrant セットアップ

$ mkdir vagrant-mysql-5.6
$ cd vagrant-mysql-5.6
$ vagrant init ubuntu/trusty64

Vagrantfile編集

やることは2つ

  • ポート開け
  • メモリ拡張
$ vim Vagrantfile

ポートを開放

  config.vm.network "forwarded_port", guest: 3306, host: 3306

メモリを拡張する

メモリが不足していると起動できないので

  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

Vagrant 起動&接続

$ vagrant up
$ vagrant ssh

MySQLインストール

パッケージを探す

$ sudo aptitude search ^mysql-.*5.6
p   mysql-client-5.6                                          - MySQL database client binaries                                                                
p   mysql-client-core-5.6                                 - MySQL database core client binaries                                                           
p   mysql-common-5.6                                     - MySQL 5.6 specific common files, e.g. /etc/mysql/conf.d/my-5.6.cnf                            
p   mysql-server-5.6                                         - MySQL database server binaries and system database setup                                      
p   mysql-server-core-5.6                                - MySQL database server binaries                                                                
p   mysql-source-5.6                                        - MySQL source                                                                                  
p   mysql-testsuite-5.6             

mysql-sourceとmysql-testsuiteはいらなそうなのでその他を入れる

インストール

$sudo aptitude install -y mysql-client-5.6 mysql-client-core-5.6 mysql-common-5.6 mysql-server-5.6 mysql-server-core-5.6

途中でrootのパスワードを聞かれるので入力する

確認

vagrant@vagrant-ubuntu-trusty-64:~$ service mysql status
mysql start/running, process 7262

start/running になっていればOK

MySQL設定

外部からの接続を許可(MySQL)

$ sudo vim /etc/mysql/my.cnf
bind-address            = 0.0.0.0

再起動

$ sudo service mysql restart
mysql stop/waiting
mysql start/running, process 7440

外部からの接続を許可(ユーザー)

ユーザーに対しても同様。パスワードは任意のものを

vagrant@vagrant-ubuntu-trusty-64:~$ mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 44
Server version: 5.6.30-0ubuntu0.14.04.1 (Ubuntu)

mysql> grant all privileges on *.* to 'root'@'%' identified by '*****' with grant option;
Query OK, 0 rows affected (0.00 sec)

ホストから接続

$ mysql -h 127.0.0.1 -P3306 -u root -p

接続エラーがでなければ成功。ChefやらAnsibleやらDocker使ったほうが後々は楽かなと。

www.amazon.co.jp

dockerイメージのリポジトリ名とタグを設定する

Dockerの設定が完了したのでImageにタグをつけたい、またはDockerfileからビルドしたものの名前を付け忘れた、そんな時に。

$ docker images
REPOSITORY            TAG               IMAGE ID            CREATED             SIZE
<none>                <none>            a1e05daa2311        2 minutes ago       428.8 MB
ubuntu                14.04             90d5884b1ee0        9 hours ago         188 MB

<none> は困るね、ということでイメージID a1e05daa2311 に対して

$ docker tag a1e05daa2311 hoge/ubuntu-mongodb:latest

とかやっておく。すると

$ docker images
REPOSITORY            TAG               IMAGE ID            CREATED             SIZE
hoge/ubuntu-mongodb   latest            a1e05daa2311        3 minutes ago       428.8 MB
ubuntu                14.04             90d5884b1ee0        9 hours ago         188 MB

当然ながら変更もできる...... わけではない。

$ docker tag a1e05daa2311 fuga/ubuntu-mongodb:3.2.6
$ docker images
REPOSITORY            TAG               IMAGE ID            CREATED             SIZE
fuga/ubuntu-mongodb   3.2.6             a1e05daa2311        10 minutes ago      428.8 MB
hoge/ubuntu-mongodb   latest            a1e05daa2311        10 minutes ago      428.8 MB

IMAGE_IDに対してタグをつけているだけなので、増殖する。 不要なIMAGEは docker rmi で消してしまおう。

$ docker rmi hoge/ubuntu-mongodb:latest

MongoDBコマンドあれこれ

利用頻度が低くて毎度コマンドを忘れるのでメモ。
カッコが必要だったり必要なかったり間違いがち。

$ mongo
> help

help系

コマンド 説明
db.help() dbのメソッドを表示
db.mycoll.help() コレクションメソッドを表示
sh.help() シャーディングのヘルパーメソッドを表示
rs.help() レプリカセットのヘルパーメソッドを表示
help admin 管理コマンドのヘルプ
help connect db接続に関するヘルプ
help keys ショートカットキー
help misc
help mr map reduce

情報表示系

コマンド 説明
show dbs データベース名を表示
show collections データベース内のコレクションを表示
show users
show profile
show logs
show log

ケーススタディ(やってみる)

ucというDBスキーマがある想定

DB一覧

> show dbs
local  0.078GB
uc     0.078GB

DB切り替え

> use uc
switched to db uc

コレクション一覧

> show collections
item
item_image
item_impression
item_video
rss_article
rss_site
system.indexes
tag
user
user_item
user_ranking
user_relationship

item一覧を取得

登場コマンド find, limit, pretty, count

#整形なし
> db.item.find().limit(1)
{ "_id" : ObjectId("55f6b62f95e39671f4000000"), "id" : 1, "name" : "Xperia(TM) Tablet Z", "catch_copy" : "", "parent_id" : null, "category" : "ガジェット", "tag_name" : [ "Xperia", "Android", "Tablet", "Sony" ], "short_description" : "", "description" : "", "data" : null, "stats" : { "rating" : 0, "user_count" : 0, "page_view" : 0 }, "image" : "/2013/04/16/08/1366060785000_3", "links" : [ { "name" : "official", "url" : null }, { "name" : "amazon", "url" : null } ]} }

#pretty()で整形
> db.item.find().limit(1).pretty()
{
    "_id" : ObjectId("55f6b62f95e39671f4000000"),
    "id" : 1,
    "name" : "Xperia(TM) Tablet Z",
    "catch_copy" : "",
    "parent_id" : null,
    "category" : "ガジェット",
    "tag_name" : [
        "Xperia",
        "Android",
        "Tablet",
        "Sony"
    ],
    "short_description" : "",
    "description" : "",
    "data" : null,
    "stats" : {
        "rating" : 0,
        "user_count" : 0,
        "page_view" : 0
    },
    "image" : "/2013/04/16/08/1366060785000_3",
    "links" : [
        {
            "name" : "official",
            "url" : null
        },
        {
            "name" : "amazon",
            "url" : null
        }
    ]
}

件数取得

# item件数
> db.item.find().count()
1627
# categoryがガジェットなitem
> db.item.find({category:"ガジェット"}).count()
23
# category == ガジェット and tag_name == HHKB
> db.item.find({category:"ガジェット", tag_name:"HHKB"}).count()
1

size とcountの違い

  • count()はfind()結果の総件数
  • size()はskipやlimitを考慮したレスポンス数
> db.tag.find().size()
2496
> db.tag.find().count()
2496
> db.tag.find().skip(1000).size()
1496
> db.tag.find().skip(1000).count()
2496
> db.tag.find().skip(1000).limit(1000).size()
1000
> db.tag.find().skip(1000).limit(1000).count()
2496
> 

以下順次更新

GoからMongodbに接続

MongoDBにGo言語でアクセスする。

Go向けの公式Driverは提供されておらず、mgoを使うよう案内される。

labix.org

インストール

go get gopkg.in/mgo.v2

Import

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

接続

Dial関数にURLを渡して接続する。他にDialWithTimeoutというタイムアウト付きのものがある。

session, err := mgo.Dial("192.168.33.13:27017")
if err != nil {
        panic(err)
}
defer session.Close() //遅延実行。先に書いておく

Collectionを取得

mymovieというdbにfilmsというコレクションがあったとする。

type Film struct {
    Title string `json:"title"`
}

//コレクションを検索して値をセット
c := session.DB("mymovie").C("films")
result := Film{}
err = c.Find(bson.M{"title": "Rocky"}).One(&result) //titleがRockeyのものを1件取得してresultに格納

//jsonにして標準出力
text, err := json.Marshal(result)
fmt.Println(string(text))

コード

サンプル様にそれっぽく書き直してるので動かなかったら申し訳ない。

package main

import (
    "encoding/json"
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Film struct {
    Title string `json:"title"`
}

func main() {
    PrintItems()
}

func PrintItems() {
    session, err := mgo.Dial("192.168.33.13:27017")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    c := session.DB("mymovie").C("films")
    result := Item{}
    err = c.Find(bson.M{"title": "Rocky"}).One(&result)

    text, err := json.Marshal(result)
    fmt.Println(string(text))
}

参考

Ubuntuに最新版Redisをインストールする

Vagrant上に構築したUbuntu 14.04にRedisをソースからコンパイル,インストールする

ダウンロード、解凍

$ sudo apt-get update
$ sudo apt-get install gcc python-dev tcl
$ wget http://download.redis.io/releases/redis-3.0.4.tar.gz
$ tar zxvf redis-3.0.4.tar.gz

コンパイル、インストール

Virtualboxの割り当てメモリが少ないとmake testがこけるので注意

$ cd redis-3.0.4
$ make
$ make test
\o/ All tests passed without errors!

起動

$ src/redis-server
11589:C 13 Sep 08:34:15.898 # Warning: no config file specified, using the default config. In order to specify a config file use src/redis-server /path/to/redis.conf
11589:M 13 Sep 08:34:15.899 # You requested maxclients of 10000 requiring at least 10032 max file descriptors.
11589:M 13 Sep 08:34:15.899 # Redis can't set maximum open files to 10032 because of OS error: Operation not permitted.
11589:M 13 Sep 08:34:15.899 # Current maximum open files is 4096. maxclients has been reduced to 4064 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'.
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 3.0.4 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 11589
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

11589:M 13 Sep 08:34:15.901 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
11589:M 13 Sep 08:34:15.902 # Server started, Redis version 3.0.4
11589:M 13 Sep 08:34:15.902 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
11589:M 13 Sep 08:34:15.902 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
11589:M 13 Sep 08:34:15.902 * The server is now ready to accept connections on port 6379

接続

$ src/redis-cli
127.0.0.1:6379> set foo bar
OK
127.0.0.1:6379> get foo
"bar"
127.0.0.1:6379> 

続き

Webチュートリアルがあるのでそれをやってみると良さそう。 Try Redis

参考

http://redis.io/download#installation

www.amazon.co.jp

UbuntuにMongoDBをインストール

しばらくすると忘れるのでメモ。

Install

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

Start

sudo service mongod start

Stop

sudo service mongod stop

Restart

sudo service mongod restart

参考

docs.mongodb.org

/* Responsive: yes */