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

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

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

Snappy Ubuntuを試す

Snappy Ubuntu Coreがリリースされたので、Vagrant上で起動してみる。それだけの記事。

Boxを探す

Ubuntu Snappyのイメージを探す。オフィシャルなものが2つほど見つかる。 ubuntu-15.04-snappy-core-stableというのが安定版のようなのでそちらを使うことにする。

Discover Vagrant Boxes | Atlas by HashiCorp

インストール、起動

$ cd [任意のディレクトリ]
$ vagrant init ubuntu/ubuntu-15.04-snappy-core-stable
...output 省略
$ vagrant up
...output 省略

これで起動した。

確認

SSHで接続してみる。

$ vagrant ssh
Welcome to Ubuntu 15.04 (GNU/Linux 3.19.0-15-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
Welcome to snappy Ubuntu Core, a transactionally updated Ubuntu.

 * See https://ubuntu.com/snappy

It's a brave new world here in snappy Ubuntu Core! This machine
does not use apt-get or deb packages. Please see 'snappy --help'
for app installation and transactional updates.

apt-get はもう使わないんだぜとかいてある。 snappy --help 見ろというので確認してみることにしよう。

snappyコマンド

snappy コマンドを使って色々とやるらしい。

$ which snappy
/usr/bin/snappy
$ snappy --help
Usage:
  snappy [OPTIONS] <command>

Help Options:
  -h, --help  Show this help message

Available commands:
  booted              Flag that rootfs booted successfully
  build               Builds a snap package (aliases: bu)
  config              Set configuraion for a installed package.
  firstboot           internal
  hw-assign           Assign a hardware device to a package
  hw-info             List assigned hardware device for a package
  hw-unassign         Unassign a hardware device to a package
  info                Display a summary of key attributes of the snappy system.
  install             Install a snap package
  internal-run-hooks  internal
  internal-unpack     internal
  list                List active components installed on a snappy system (aliases: li)
  login               Log into the store
  purge               Remove all the data from the listed packages
  remove              Remove a snapp part
  rollback            Rollback to a previous version of a package
  search              Search for packages to install (aliases: se)
  set                 Set properties of system or package
  update              Update all installed parts
  versions            (deprecated) please use "list"

各コマンドのヘルプは snappy [command] --help で確認できる。

$ snappy list --help
Usage:
  snappy [OPTIONS] list [list-OPTIONS]

Provides a list of all active components installed on a snappy system

If requested, the command will find out if there are updates for any of the
components and indicate that by appending a * to the date. This will be slower as it requires a round trip to the app store on the network.

The
developer information refers to non-mainline versions of a package (much like PPAs in deb-based Ubuntu). If the package is the primary version of that
package in Ubuntu then the developer info is not shown. This allows one to identify packages which have custom, non-standard versions installed. As a
special case, the “sideload” developer refers to packages installed manually on the system.

When a verbose listing is requested, information
about the channel used is displayed; which is one of alpha, beta, rc or stable, and all fields are fully expanded too. In some cases, older (inactive)
versions of snappy packages will be installed, these will be shown in the verbose output and the active version indicated with a * appended to the
name of the component.

Help Options:
  -h, --help         Show this help message

[list command options]
      -u, --updates  Show available updates (requires network)
      -v, --verbose  Show channel information and expand all fields

snappy search

ストアか利用可能なパッケージを探すコマンド。

$ snappy search --help
Usage:
  snappy [OPTIONS] search [search-OPTIONS]

Query the store for available packages

Help Options:
  -h, --help          Show this help message
[search command options]
          --show-all  Show all available forks of a package

--show-all で全て表示してくれるっぽいので実行してみる。

$ snappy search --show-all
Name                     Version   Summary                        
crossbar.crossbar        0.10.4    Crossbar.io                    
gumstix-overo.ash        0.1       gumstix-overo                  
webcam-demo              1.0.1     webcam-demo                    
pi2.lool                 0.11      pi2                            
go-example-webserver     1.0.6     go-example-webserver           
config-example           1.0.5     config-example                 
pastebinit.mvo           1.4.0.0.2 pastebinit                     
hello-dbus-fwk.canonical 1.0.0     hello-dbus-fwk                 
docker                   1.6.0.003 Docker                         
8nzc1x4iim2xj1g2ul64     43        Returns for store credit only. 
system-status.victor     1.0.3     System status web portal       
webdm                    0.5       webdm                          
beagleblack              1.7       beagleblack                    
hello-world              1.0.14    hello-world                    
hello-world.jdstrand     1.5.1     hello-world                    
generic-amd64            1.1       generic-amd64                  
xkcd-webserver           0.4       xkcd-webserver              

dockerがいるな。Docker Imageで使用するためにSnappyを使おうと思っていたけどSnappy自身もDockerのホストとして使えるのか。 他には hello-worldgo-example-webserver あたりが気になったので入れてみる。

$ sudo snappy install docker
sudo: unable to resolve host ubuntu-core-stable-2
Installing docker
Starting download of docker
8.36 MB / 8.36 MB [==============================================================================================================] 100.00 % 79.07 KB/s 
Done
Name          Date       Version   Developer 
ubuntu-core   2015-04-23 2         ubuntu    
docker        2015-05-02 1.6.0.003           
generic-amd64 2015-04-23 1.1                 

sudoコマンドを使うとhost名解決ができないといって怒られるがインストールはできる。 上記3点を入れた後の状態。

$ snappy list
Name                 Date       Version   Developer 
ubuntu-core          2015-04-23 2         ubuntu    
docker               2015-05-02 1.6.0.003           
go-example-webserver 2015-05-02 1.0.6     canonical 
hello-world          2015-05-02 1.0.14    canonical 
generic-amd64        2015-04-23 1.1

とりあえずdocker入れたのであとはどうとでもなりそうだけど、 Snappy自体がなんのこっちゃか分かってないので続きはまた今度。

/* Responsive: yes */