Toshihito Kon
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # isuconチートシート ## vscode ssh https://www.tweeeety.blog/entry/20140121/1390275336 vim ssh `:e scp://[user@][host][:port]/` ## 定番設定 (各ミドルウェア欄に移動しました) ### OS - https://kazeburo.hatenablog.com/entry/2014/10/14/170129 ```shell $ cat /etc/sysctl.conf net.ipv4.tcp_max_tw_buckets = 2000000 net.ipv4.ip_local_port_range = 10000 65000 net.core.somaxconn = 32768 net.core.netdev_max_backlog = 8192 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_fin_timeout = 10 ``` - `fs.file-max = 100000` もありかも - `cat /etc/sysctl.d/99-sysctl.conf` のパターンもある - `sudo /sbin/sysctl -p` とかで反映 ### ベンチ時 ​ 以下のようなスクリプトで再起動しつつスローログなど移動するの大事 設定ファイルの更新後再起動忘れがちなので注意 ​ ```bash set -ex ​ if [ -f /var/lib/mysql/mysqld-slow.log ]; then sudo mv /var/lib/mysql/mysqld-slow.log /var/lib/mysql/mysqld-slow.log.$(date "+%Y%m%d_%H%M%S") fi if [ -f /var/log/nginx/access.log ]; then sudo mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date "+%Y%m%d_%H%M%S") fi sudo systemctl restart mysql # sudo service memcached restart sudo systemctl restart nginx ``` ​ ​ ### mysqldumpslow ​ - 基本 pt-query-digest でいいが、使えなかった場合こっちでも代用できる - `mysqldumpslow /var/log/mysql/slow.log` でとりあえず OK ​ ​ ## kataribe ​ アクセスプロファイラ。今回は alp でいいかなと思うが一応。 https://github.com/matsuu/kataribe ​ ```bash wget https://github.com/matsuu/kataribe/releases/download/v0.4.1/kataribe-v0.4.1_linux_amd64.zip -O kataribe.zip unzip -o kataribe.zip sudo mv kataribe /usr/local/bin/ sudo chmod +x /usr/local/bin/kataribe rm kataribe.zip kataribe -generate ``` ​ ## Go のプロファイラ ​ ```go import ( _ "net/http/pprof" ) ​ go func() { log.Println(http.ListenAndServe("0.0.0.0:6060", nil)) }() ``` ​ - png で結果を吐き出す `GO111MODULE=on go tool pprof -png -output pprof.png http://localhost:6060/debug/pprof/profile` - WebUI 情報量が多いので良さそう `GO111MODULE=on go tool pprof -http=":8888" http://localhost:6060/debug/pprof/profile` - すでに一回実行するとファイルが生成されるのでそれ指定してもいい `GO111MODULE=on go tool pprof -http=":8888" /Users/miyamura-koyo/pprof/pprof.samples.cpu.005.pb.gz` - `sudo yum install graphviz` か `sudo apt install graphviz` しないと動かないかも ​ --- ​ - go のプロファイラ pprof を利用してパフォーマンスを計測する (GAE + gin もあり) - https://chidakiyo.hatenablog.com/entry/go-pprof-gae-and-gin - webapp なので `_ "net/http/pprof"` を import するのがラクそう - Go のプロファイラを使おう! その1 - http://tech.innovation.co.jp/2018/09/10/Go.html - web app のようにシグナルで実行停止するやつだとこれではうまくいかなさそうなので上記の Web 版の方がいい - https://qiita.com/ikawaha/items/e3b35f09fb49e9217924#%E3%83%97%E3%83%AD%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AA%E3%83%B3%E3%82%B0%E7%94%A8%E3%81%AE%E3%82%B3%E3%83%BC%E3%83%89%E3%81%AE%E5%9F%8B%E3%82%81%E8%BE%BC%E3%81%BF - 見方の参考に - https://medium.com/eureka-engineering/go%E8%A8%80%E8%AA%9E%E3%81%AE%E3%83%97%E3%83%AD%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AA%E3%83%B3%E3%82%B0%E3%83%84%E3%83%BC%E3%83%AB-pprof%E3%81%AEweb-ui%E3%81%8C%E3%82%81%E3%81%A1%E3%82%83%E3%81%8F%E3%81%A1%E3%82%83%E4%BE%BF%E5%88%A9%E3%81%AA%E3%81%AE%E3%81%A7%E7%B4%B9%E4%BB%8B%E3%81%99%E3%82%8B-6a34a489c9ee # ミドルウェア毎のTips ## nginx [公式config reference](https://nginx.org/en/docs/) ### 設定チェック ``` nginx -t -c /path/to/nginx.conf ``` ### access_log を出す ``` log_format ltsv "time:$time_local" "\thost:$remote_addr" "\tforwardedfor:$http_x_forwarded_for" "\treq:$request" "\tstatus:$status" "\tmethod:$request_method" "\turi:$request_uri" "\tsize:$body_bytes_sent" "\treferer:$http_referer" "\tua:$http_user_agent" "\treqtime:$request_time" "\tcache:$upstream_http_x_cache" "\truntime:$upstream_http_x_runtime" "\tapptime:$upstream_response_time" "\tvhost:$host"; access_log /var/log/nginx/access.log ltsv; ``` https://kazeburo.hatenablog.com/entry/2014/10/14/170129 ここら辺参考資料によってかなり違うので要検討 ```conf $ cat /etc/nginx/nginx.conf worker_processes auto; events { worker_connections 10000; } http { include mime.types; sendfile on; tcp_nopush on; tcp_nodelay on; etag off; # アプリケーションがUNIXドメインソケットであれば upstream app { server unix:/dev/shm/app.sock; } server { location / { proxy_pass http://app; } location ~ ^/(stylesheets|images)/ { open_file_cache max=100; root /home/isucon/webapp/public; } } } ``` - https://diary.sorah.jp/2017/10/23/isucon7q によると - `add_header Cache-Control "public, max-age=86400";` とか`client_max_body_size 20M;` とかもあっていいかも? - `worker_processes auto;` `worker_rlimit_nofile 4096;` `keepalive_timeout 120s;` とかもあるかも - https://qiita.com/ihsiek/items/11106ce7a13e09b61547 にはたくさんあるのでここら辺検討してもいい - 再起動(環境に合わせて1つ) - `sudo service nginx restart` (ほぼコレ) - `sudo systemctl restart nginx` (systemdでserviceエイリアスが無い場合) - `sudo nginx -s reload` (systemd以外で動いてる場合) ### worker_process > 同時クライアント数はworker_process * worker_connectionとなる https://qiita.com/toshihirock/items/f3aac142882c9c320b7f ``` worker_processes auto; worker_rlimit_nofile; events { worker_connections 10000; multi_accept on; use epoll; accept_mutex on; } ``` ```bash # OSがいくつファイルディスクリプタを使えるか確認 cat /proc/sys/fs/file-max ulimit -n ``` 設定参考 https://qiita.com/hclo/items/35f00b266506a707447e ### 最後にやること confから消すもの - access_log - slow_query_logs ## mysql ### slowlogの出し方 [参考](http://naoberry.com/tech/slowquery/) ロック待ちは `long_query_time` の算出時間に含まれない #### my.conf に書く場合 ``` [mysqld] slow_query_log=1 slow_query_log_file=’/var/lib/mysql/slow.log’ long_query_time=0.1 ``` `long_query_time` は 0.1 くらいがいいのではないか(持論) #### 一時的な設定をクエリで行う **再起後に消えるので用法用量チェック** ```sql set global slow_query_log=1; set global slow_query_log_file='/var/lib/mysql/slow.log'; set global long_query_time=0.1; ``` ### MySQL パーティショニング https://qiita.com/taroshin/items/608076c9f8e09497c4b1 要約:TODO ### indexの貼り直しが必要な場合の参考 https://dev.mysql.com/doc/refman/5.6/ja/rebuilding-tables.html 要約:dump取って入れ直す ### :thinking_face: なんの設定か確認、多分バッファ取って余計な書き込みしないみたいな ```sql $ cat /etc/my.cnf innodb_buffer_pool_size = 1G innodb_flush_log_at_trx_commit = 0 innodb_flush_method=O_DIRECT ``` https://kazeburo.hatenablog.com/entry/2014/10/14/170129 ### データサイズ確認 打つべし ```sql SELECT table_name, engine, table_rows, avg_row_length, floor((data_length+index_length)/1024/1024) as allMB, floor((data_length)/1024/1024) as dMB, floor((index_length)/1024/1024) as iMB FROM information_schema.tables WHERE table_schema=database() ORDER BY (data_length+index_length) DESC; ``` ### max_connections https://qiita.com/kenjiszk/items/c3d46ac837845281e62b ## redis ### TODO:何の設定かあとで確認します ```redis tcp-keepalive 60 save 900 1 save 300 10 save 120 20000 maxclients 10000 appendonly yes appendfsync everysec no-appendfsync-on-rewrite no ``` https://blog.yuuk.io/entry/web-operations-isucon # 利用できる便利ツール ## サーバーサイド ### tmux [Qiitaチートシート](https://qiita.com/nmrmsys/items/03f97f5eabec18a3a18b) ### vim いらんかもしれん ### top/htop (tui) リソースモニタ cpu使用率/メモリ使用率でsort出来たりする 要操作確認 ### bmon (tui) ネットワークトラフィックモニタ NIC毎のネットワーク通信量が見れる、無駄に多かったり不通になったりするのが見れる ネットワーク通信量見るツールの中で一番好き(て) ### dstat リソースモニタ 標準出力に吐かれ続けるので、時間毎の推移が見れる #### 便利alias(ワンショット登録済み) ```bash if [ -x /usr/bin/dstat ]; then alias dstat-full='dstat -tclmdrn' alias dstat-mem='dstat -tclm' alias dstat-cpu='dstat -tclr' alias dstat-net='dstat -tclnd' alias dstat-disk='dstat -tcldr' fi ``` #### 参考リンク達 https://christina04.hatenablog.com/entry/2015/04/10/101737 https://hirose31.hatenablog.jp/entry/20120229/1330501968 https://www.tweeeety.blog/entry/20140121/1390275336 ### alp nginxのアクセスプロファイラ http://kazuki229.hatenablog.com/entry/2017/09/29/003314 `cat /var/log/nginx/access.log | alp ltsv` | オプション | 説明 | | :--------: | :-------------------------: | | t | 時間表示 | | T | epoch time 表示する | | c | CPU 使用率 | | l | ロードアベレージ | | m | メモリ使用量 | | r | IO 回数 | | n | ネットワーク IO(単位は B/s) | | d | Disk IO | | c | CPU 使用率 | #### 以下のようにすると出力もできる $ `dstat-full --output /home/hoge/dstat_ $(date +%Y-%m-%d).csv` ### lsof (cmd) ### rsync - https://qiita.com/cakipy/items/46ac77534952c786a937 ### pt-query-digest mysql logの集計ツール ```shell= pt-query-digest /var/lib/mysql/mysql-slow.sql ``` インストール方法など https://thinkit.co.jp/article/9617 ### その他 - Linux サーバにログインしたらいつもやっているオペレーション - https://blog.yuuk.io/entry/linux-server-operations - top コマンドの使い方とか全般で困ったことあれば # 作業の流れchecklist ## 最初にやること 問題文を熟読し、スキーマ/アプリをざっくり把握! SQL 使ってるとこ抜き出しとかしてもいいかもね。 - [ ] アプリを触る - [ ] システム構成 - フロントアプリ - SPAかどうかくらいはみても良いかも - 静的ファイルの構成確認してnginxで配信できそうかチェック - サーバーサイド - 環境 - ネットワークのスループット - メモリ使用状況 - ps auxで動いてるプロセス一覧、目grep - proxyはあるか(nginxなど) - 無いなら噛ませる - :thinking_face:後から噛ませるなら生nginxよりunitとかのほうが良いのかもしれない - app(参考実装と呼ばれるらしい) - 配られる? - DB - :thinking_face:SQLのテーブル定義をみんな簡単に見れる状態でどこかに乗せておくと良い? - `mysql -d -p` テーブル定義のみdump - [mysqldump -d サンプル](https://gist.github.com/ToshihitoKon/63144777654979d180e964f857330cb1) - :thinking_face:ER図とかにしたい - slow log確認 - conf書いて再起動 - pt-query-digestの結果をぺっと貼る - 遅いクエリのテーブル定義見る - 静的ファイル配信 - lighthouse?(いらない?) - 画像がクソデカい!みたいなのはパッと見つけられるので回すだけ回すのはアリ? ## 序盤 - ベンチマーク - サーバーでdstat、bmon、htop辺りを眺めてみる - sqlのログをどうやって取るか確認 ## 中盤 ## 終盤 - ログ出力をやめる `access.log` とか特に - プロファイラ噛ませてたら外す - 再起動試験する ## その他よくあるパターン集 ​ - 再起動試験忘れるのあるあるなので、最後はそれ - HTTP/2 にする - 問題によっては難しい場合もある - 複数台構成 - DB サーバを分けるのが定番 - 変わり種としては重い API だけ特定のサーバに振り分けるとかもあるっぽい - bcrypt みたいな特定の重い処理を緩和する - コスト(ストレッチング回数) 減らしていいんなら減らす - MySQL コネクションを使い回す - N+1 - メモリにのせる # 自作便利ツールシリーズ いい感じにセットアップするくん https://github.com/ToshihitoKon/iikanji-setupper # 参考リンク ## ISUCON 過去問ブログ ### 第 9 回 - ISUCON9 過去問 - http://isucon.net/archives/53805209.html - ISUCON9 予選問題の解説と講評 : ISUCON 公式 Blog http://isucon.net/archives/53789931.html - ISUCON9 予選 1 日目で最高スコアを出しました https://to-hutohu.com/2019/09/09/isucon9-qual/#%E5%BD%93%E6%97%A5 ### 第 8 回 - ISUCON8 本選出題記 あるいは ISUCON ベンチマーカー負荷調整の歴史 - 酒日記 はてな支店 https://sfujiwara.hatenablog.com/entry/2018/10/25/084543 - ISUCON8 予選問題の解説と講評 : ISUCON 公式 Blog http://isucon.net/archives/52520045.html - 死闘の果てに ISUCON 8 予選を全体7位で突破した記録 https://qiita.com/najeira/items/527e1f54fa417fd20b65#measure - https://github.com/najeira/measure - ↑ ある範囲だけの関数呼び出しログだけ知りたいならこれでも良さそう https://qiita.com/ihsiek/items/11106ce7a13e09b61547 isucon7サーバーサイド覚書、初期設定からnginx confなど https://blog.yuuk.io/entry/web-operations-isucon ISUCON競技中の流れがざっくり書いてある、わかりやすい https://gist.github.com/south37/d4a5a8158f49e067237c17d13ecab12a#max-connections isucon6当日の流れと作業内容 # ぼやき欄 わけわからんクエリの意味を理解してよしなにする力が求められる 参考リンクをここに置いておくと行数がかさむのでどこか別のところに避難させていいかもしれない、閉じれれば便利なんだけどhackmdにはない # isucon10予選感想欄 CPU1コアでアプリとhttp serverとapiとDBクソ重クエリ動かす問題 - DBレプリ - レプリは出来たけどアプリからwriterに向けてreaderから読むみたいなのわからなくて断念 - テーブル毎にDBインスタンス分ける - なるほど -

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully