ローカルのkubectlにGKEクラスターを追加
gcloud container clusters get-credentials [CLUSTER_NAME]
【NOTE】Prometheus
This is a note taken when investigating Prometheus.
- https://prometheus.io/docs/
- monitoring and alerting
- built at SoundCloud
- pull model via HTTP
- for short-lived jobs, push gateway is available
- similar services: Graphite, InfluxDB, OpenTSDB, Nagios, Sensu
- OpenMetrics format (WIP)
- resources: https://prometheus.io/docs/introduction/media/
- prerecord expressions to improve performance = recording rules
- PromQL for querying
- https://blog.alexellis.io/prometheus-monitoring/
- cloud native time-series database and monitoring solution
- time-series database with UI and querying language (PromQL)
- stand alone process which provides /metrics endpoint = exporter
- NodeExporter to send system data
- /metrics endpoint is default
- It's possible to set up side car process which has /metrics endpoint and exposes data of the application
- Prometheus exposition format to expose your own metrics
- https://www.digitalocean.com/community/tutorials/how-to-use-prometheus-to-monitor-your-ubuntu-14-04-server
- There used to be a combination of Prometheus + PromDash
- https://dzone.com/articles/monitoring-with-prometheus
- monitoring targets can be anything
- prometheus server collects metrics from targets over HTTP
- exporters to monitor third party systems
- three components: server, targets, and visualisation layer
- https://www.katacoda.com/courses/prometheus/getting-started
- Another dashboard by Weave Works: https://www.weave.works/features/prometheus-monitoring/
- AlertManager
- https://pagertree.com/2017/12/01/prometheus-tutorial/
- https://www.digitalocean.com/community/tutorials/how-to-use-alertmanager-and-blackbox-exporter-to-monitor-your-web-server-on-ubuntu-16-04
- black box exporter
- adding user to sudo group allows them to have privilege access (but no a root user)
- prometheus server sends alerts to AlertManager based on rules
- you can silence the alert and get it expired using amtool
- Prometheus + Grafana
- awesome Prometheus: https://github.com/roaldnefs/awesome-prometheus
TODO
- get familiar with Grafana
- setup mail server and send alert via email as well as Slack
【NOTES】Consul
The followings are the notes taken when spiking Consul.
- host-based to service-based
- service discovery for connectivity
- service registry
- health check
- DNS and HTTP
- keep the real time list of services, location and health
- service segmentation for security
- new approach to secure the service rather than relying on the network
- all the communication is encrypted with TLS
- service configuration for runtime configuration
- let's see the examples...
- static IPs to service discovery
- https://learn.hashicorp.com/consul/getting-started/
- member discovery
- gossip protocol: https://www.consul.io/docs/internals/gossip.html
- eventually consistent
- registration
- service definition
- API call
- DNS
- you can also use tag based domain name lookup
- by sending SIGHUP signal, you can update service definitions, or API calls
- Connect connects with service using TLS
- connect command starts TLS proxy sidecar for registered service
- use intentions to define service communications = service segmentation
- Connect looks very complicated: https://learn.hashicorp.com/consul/getting-started/connect
- To run VM on GCE
- https://cloud.google.com/compute/docs/instances/enable-nested-virtualization-vm-instances
- https://github.com/hashicorp/vagrant/issues/9608
- Enable Intel VT-x instructions for virtualisation
- Only KVM-based hypervisor is supported
- Available for all Linux VM with using Haswell or newer
- Stack in SSHing to VM: https://github.com/hashicorp/vagrant/issues/8157
- node can auto-join on startup
- health check runs as the same user as the Consul process
- exit code >= 2 -> failure
- = 1 -> warning
- member discovery
- https://www.digitalocean.com/community/tutorials/an-introduction-to-using-consul-a-service-discovery-system-on-ubuntu-14-04
- system wide K/V store
- servers and clients (aka agent). and clients contains service monitored by consul
- start one server with bootstrap mode <- leader without election
- after joining all the servers, stop bootstrap mode and re-join as regular member
- place service definition file on service-providing server and run consul agent
- https://www.tutorialspoint.com/consul/
- similar service: etcd, zookeeper
- two modes: client/server
- leader election -> raft algorithm https://raft.github.io/
- RPC is used for server <> client communication
- gossip algorithm: for managing membership
- consul template is a daemon to query and update the system
- it allows you to template configuration files using HCL
- rkt is more secure than Docker?
- DNS default TTL is 0
- consul-alerts daemon to send health check notifications/reminders
- https://sreeninet.wordpress.com/2016/04/17/service-discovery-with-consul/
- In micro-services, services are 1) dynamic and 2) distributed
- Service discovery
- roles: discovery, health check, load balancing
- components: service registry, registrator, health checker, load balancer
- Consul: service-wide KV store, health checking, API and DNS, load balancing, multi datacenter support
- 8400 -> RPC, 8500 -> http, 8600 -> DNS
- http://www.mammatustech.com/consul-service-discovery-and-health-for-microservices-architecture-tutorial
- "service topology"
- servers use WAN to communicate with other servers in different data-centres
- built on top of Serf
- three to five server agents per data-centre
- server agents are the information hub
- http://www.mammatustech.com/Microservice-Service-Discovery-with-Consul
- https://devopscube.com/consul-service-discovery-beginners-guide/
- Consul with Docker-Machine and Swarm
- https://www.javacodegeeks.com/2016/04/service-discovery-docker-consul-part-1.html
- register services by calling API to the nearest agent
- Consul and k8s?
- Deploying a Consul cluster on AWS
miscs
- gossip protocol – Gossip Protocol - Consul by HashiCorp and Serf – Serf by HashiCorp
- Raft algorithm – Raft Consensus Algorithm
MySQLでレプリケーションを設定する
レプリケーションはMySQLで最も重要な機能の一つで、その用途は多岐に渡ります。それゆえ素早くセットアップできることが好ましいです。ここではその手順をまとめておきます。
方法はいくつかありますがここではマスターからmysqldumpでデータを取ってくる方法を使います。
1. マスターサーバーのコンフィギュレーション
マスターでは以下のようにオプションを設定します。
[mysqld] bind-address = 10.132.0.2 server_id = 1 log_bin = /var/log/mysql/mysql-bin.log sync_binlog = 1
server_id
はレプリケーションするグループ内で一意である必要があります。デフォルトが1なので他のインスタンスと衝突しないように違う値を割り当てるのが安全ですがここではデフォルトのままにしておきます。今回はローカルネットワーク内にマスター・レプリカを立てるのでbind-address
にはローカルIPを書いておきます。log_bin
にはバイナリログの位置を指定、sync_binlog
フラグを立てることでトランザクション毎にバイナリログが同期することを保証します。
2. マスターにレプリケーションユーザーを作成する
レプリケーションではマスターがサーバーでレプリカがクライアントの役割を果たします。よってマスター側にレプリカがアクセスする用のユーザーを作成します。
GRANT REPLICATION SLAVE ON *.* TO 'slave_user'@'%' IDENTIFIED BY 'password'; FLUSH PRIVILEGES;
ここではクライアントホストに%を指定することで複数のレプリカでユーザーを使い回す想定で作成します。
3. マスターのデータをmysqldumpで取得する
バックアップをとる方法でまとめたのと同様にmysqldumpコマンドによりデータの論理バックアップを取得します。
$ sudo mysqldump --all-databases --master-data=2 --single-transaction --flush-logs > backup/dumpfile.sql
--all-databases
により全てのデータベースを対象にし、--master-data=2
によりダンプデータにレプリケーションの開始位置を書き込ませます。--single-transaction
は複数データベースのデータを取得する際の不整合を防ぐオプション(InnoDB専用)、--flush-logs
によりバイナリログのローテートを指示します。
4. スレーブのコンフィギュレーション
スレーブのmysql.confファイルを以下のように設定します。
[mysqld] bind-address = 10.132.0.3 server-id = 2 relay-log = /var/log/mysql/mysql-relay-bin.log
スレーブはserver-id
に2を割り当て、ローカルIPの設定もします。マスターから取得するバイナリログはまずリレーログという領域に置かれます。その後マスター接続するのとは別のスレッドがリレーログの内容をデータに書き込みます。relay-log
の値にリレーログを書き込む場所を指定しておきます。
5. ダンプしたデータのリストア
先ほどマスターから取得したダンプファイルをスレーブに適用します。
$ sudo mysql < dumpfile.sql
6. スレーブでレプリケーションの設定をする
スレーブでマスターとバイナリログ上のレプリケーションの開始位置を指定します。レプリケーションの開始位置は以下のようにダンプデータから取得できます。
$ cat dumpfile.sql | head -n30 | grep CHANGE -- CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000002', MASTER_LOG_POS=154;
mysqlに以下のクエリを流します。
CHANGE MASTER TO MASTER_HOST='10.132.0.2', MASTER_USER='slave_user', MASTER_PASSWORD='password', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.000002', MASTER_LOG_POS=154, MASTER_CONNECT_RETRY=10;
7. マスターに更新クエリをかける
レプリケーションがうまくいってることを確認するためにマスターのデータを更新してみましょう。
8. レプリケーションの開始
スレーブ側でレプリケーションを開始します。
START SLAVE;
9. レプリケーションの確認
スレーブ側では以下のように確認します。
SHOW SLAVE STATUS\G
またマスター側での確認は
SHOW MASTER STATUS; SHOW SLAVE HOSTS;
です。
先ほどマスターで更新したデータがスレーブに書き込まれていること、マスターへの更新クエリがスレーブに反映されることも確認しましょう。
参考
MySQLで差分バックアップをとる
リストア処理においてフルバックアップと合わせて必要になるのが差分バックアップです。ということで備忘録。
1. バイナリログを記録する
まずはこれをしないと始まりません。設定ファイルのlog-bin
の項目をコメントインし、サーバーを再起動しておきましょう。
2. フルバックアップをとる
--flush-logs
オプションをつけてログをローテートしておきます。こうしておくとリストア時にファイルの先頭から復元すればよいため手順がシンプルになります。
$ sudo mysqldump --flush-logs --lock-all-tables --all-databases > backup/full-$(date +%Y%m%d).sql
3. バイナリログを保存しておく
$ sudo mysqlbinlog /var/log/mysql/mysql-bin.000005 > binlog/diff-$(date +%H%M%S).sql
これで保存した分まで復元できるので常に最新のものを安全な場所に保管できるようにしておきましょう。
バックアップの処理はここまでで以降リストアの処理です。緊張感が欲しい方はDROP DATABASE
しましょう。
4. フルバックアップを復元する
$ sudo mysql < backup/full-20181030.sql
フルバックアップ取得時まで復元しました。次にバイナリログ分を適用します。
5. バイナリログの適用
フルバックアップと同じようにmysqlコマンドに流すだけです。
$ sudo mysql < binlog/diff-193632.sql
これで完了です。
ログをローテートしたくないとき
バックアップ時に--master-data=2
オプションをつけましょう。こうすることでダンプデータにどのバイナリログのどの位置からリストアすればいいかがわかります。
sudo mysqldump --lock-all-tables --all-databases --master-data=2 > backup/full-$(date +%Y%m%d).sql
$ head -n30 backup/full-20181030.sql | grep 'CHANGE MASTER' -- CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000005', MASTER_LOG_POS=831724;
位置を指定してリストアする
mysqlbinlog時に--start-position
を指定して展開します。
$ sudo mysqlbinlog --start-position=831724 /var/log/mysql/mysql-bin.000005 > binlog/diff-$(date +%H%M%S).sql
あとは同じリストア手順。(ということはバイナリログはmysqlbinlogを通さずそのまま保管したほうがいいのか......。)
参考
- 4.6.8.3 Using mysqlbinlog to Back Up Binary Log Files
- 1.3.1 Establishing a Backup Policy
- 7.5 Point-in-Time (Incremental) Recovery Using the Binary Log
- Incremental MySQL Backup with Binary Log
- MySQLのバイナリログを活用しリストア&リカバリで障害時でもDB完全復旧可能な体制を整える。
- MySQLのバイナリログを使った復旧手順 - Denet Tech Lib.
- MySQLバックアップの基礎 - 日常メモ
mysqldumpでフルバックアップとリストア
MySQLのバックアップにはいくつか方法があります。その中でも最もオーソドックスな方法であるmysqldumpを使った方法についてまとめておきます。
mysqldumpを使った方法の特徴としては
- 手軽である
- 無停止でバックアップが取れる(オンラインバックアップ)
- データのダンプを出力する(論理バックアップ)
- リストアに時間がかかる
などがあります。
1. セットアップ
2. ダンプの取得
以下のようにmysqldumpコマンドを使いダンプデータを取得します。
$ sudo mysqldump example > backup/backup-$(date +%Y%m%d).sql
以上です。簡単。
リストア
リストアのためDROP TABLE
しておきます。
リストアの際には先ほどのダンプデータをリダイレクトで入力するだけ。
$ sudo mysql example < backup/backup-20181029.sql
リストアも簡単。
全てのデータベースをバックアップしたい
--all-databases
オプションを使います。
$ sudo mysqldump --all-databases > backup/backup-$(date +%Y%m%d).sql
これならDROP DATABASE
した状態でも以下でリストア可能。
$ sudo mysql < backup/backup-20181029.sql
バックアップを圧縮して取りたい
gzip
にパイプすれば圧縮も簡単。
$ sudo mysqldump --all-databases | gzip > backup/backup-$(date +%Y%m%d).sql.gz
リストアもgunzip経由で。
$ gunzip < backup/backup-20181029.sql.gz | sudo mysql
cronで定期的にバックアップしたい
最後にcronの設定をしてみます。MySQL接続のため.my.cnf
は事前に設定しておきましょう。
例えば毎日午前3時にバックアップを取りたかったらcrontab -e
に以下を追加します。
0 3 * * * /usr/bin/mysqldump -u root --all-databases > /path/to/home/backup/full-$(date +\%Y\%m\%d).sql
参考
MySQLサーバーの設置
チュートリアルなどでMySQLサーバーが欲しいことがよくあるので手順をまとめておきます。OSはUbuntu18.04TLSです。
【参考】
1. インスタンスの作成
自分の環境に合わせてインスタンスをセットアップします。今回はGCP上に設置します。
$ gcloud compute instances create mysql-example3 --machine-type=f1-micro --image=ubuntu-1804-bionic-v20181029 --image-project=ubuntu-os-cloud Created [https://www.googleapis.com/compute/v1/projects/playground-192621/zones/europe-west1-b/instances/mysql-example3]. NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS mysql-example3 europe-west1-b f1-micro 10.132.0.5 35.205.118.215 RUNNING
2. 作成したインスタンスにSSHする
$ gcloud computh ssh mysql-example3
3. mysqlのダウンロード
$ sudo apt-get update && sudo apt-get install -y mysql-server
これだけ。一応ps aux | grep mysql
で確認しておきます。
4. .my.cnf
の設置
便利のためにホームディレクトリに.my.cnf
ファイルを設置しておきます。中身はこんな感じ(userとpassは適宜変えてね)。
[client] user = root password =
5. ダミーデータの作成と導入
ここのサイトでダミーのデータを簡単に作れます。
6. .sql
ファイルを作成したらインスタンスに送る。
$ gcloud compute scp data.sql mysql-example3:~
7. データベースの作成
$ sudo mysql -e 'create database example;'
7. リダイレクトでmysql
コマンドに繋ぐ
$ sudo mysql -- example < data.sql
ここまで5分でできるようになろう。