Ubuntu でのログ肥大化で Django が 502 エラー

Django アプリで 502 エラー

VPS でホストしている Django アプリの挙動がおかしくなりました。

トップページには問題なくアクセス出来るものの、ログインをしようとすると「502 Bad Gateway」のエラーが発生。

どれか一つのアプリではなく、同じサーバーでホストしている複数のアプリで同じ挙動(トップページは表示されるがログイン機能で 502 エラー)が出たので調べました。

サーバーの容量が限界に近い

Ubuntu にログインした所、下記の様に表示されました。

Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-137-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu Mar 30 17:12:11 JST 2023

  System load:  0.02               Processes:             142
  Usage of /:   95.0% of 94.40GB   Users logged in:       0
  Memory usage: 35%                IPv4 address for ens3: 133.125.39.81
  Swap usage:   28%

  => / is using 95.0% of 94.40GB

「Usage of /: 95.0% of 94.40GB」との表示で、どうやら容量の 95.0 % を使ってしまっているらしい。

原因はログファイルの肥大化

「sudo du -sh /* | sort -hr」でルートディレクトリ直下をチェック。

$ sudo du -sh /* | sort -hr
du: cannot access '/proc/905133/task/905133/fd/4': No such file or directory
du: cannot access '/proc/905133/task/905133/fdinfo/4': No such file or directory
du: cannot access '/proc/905133/fd/3': No such file or directory
du: cannot access '/proc/905133/fdinfo/3': No such file or directory
85G	/var
4.2G	/usr
701M	/home
306M	/boot
7.9M	/root
6.6M	/etc
728K	/run
56K	/tmp
16K	/lost+found
8.0K	/srv
4.0K	/opt
4.0K	/mnt
4.0K	/media
4.0K	/cdrom
0	/sys
0	/sbin
0	/proc
0	/libx32
0	/lib64
0	/lib32
0	/lib
0	/dev
0	/bin

なるほど「/var」で 85 GB も使っていると。

$ sudo du -sh /var/* | sort -hr
81G	/var/log
2.7G	/var/lib
1.3G	/var/www
103M	/var/cache
2.4M	/var/spool
2.1M	/var/backups
36K	/var/tmp
4.0K	/var/opt
4.0K	/var/mail
4.0K	/var/local
4.0K	/var/crash
0	/var/run
0	/var/lock

「/var/log」で 81 GB か。

$ sudo du -sh /var/log/* | sort -hr
45G	/var/log/syslog
31G	/var/log/syslog.1
4.1G	/var/log/journal
325M	/var/log/syslog.2.gz
193M	/var/log/syslog.5.gz
190M	/var/log/syslog.6.gz
188M	/var/log/syslog.7.gz
164M	/var/log/syslog.4.gz
159M	/var/log/syslog.3.gz
126M	/var/log/btmp
122M	/var/log/btmp.1
104M	/var/log/nginx
27M	/var/log/auth.log.1
21M	/var/log/auth.log
2.7M	/var/log/auth.log.4.gz
2.1M	/var/log/auth.log.3.gz
2.0M	/var/log/auth.log.2.gz
1.4M	/var/log/mail.log.1
1.3M	/var/log/mail.log
776K	/var/log/vsftpd.log

「/var/log/syslog」と「/var/log/syslog.1」が大きい。

けどこれって定期的に gz に圧縮されているのか?

ログファイルの容量を下げてみる

とりあえず「sudo logrotate -f /etc/logrotate.conf」を実行し、logrotate を強制的に実行してみました。

$ sudo logrotate -f /etc/logrotate.conf
error: destination /var/log/mysql/error.log.1.gz already exists, renaming to /var/log/mysql/error.log.1.gz-2023040500.backup

上記の様にエラーメッセージは出たものの、「syslog.1.gz-2023031800.backup」が作成され、サーバーにログインし直すと容量に空きができました。

「Usage of /: 30.9% of 94.40GB」となっています。

Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-137-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed Apr  5 07:34:52 JST 2023

  System load:  0.3                Processes:             140
  Usage of /:   30.9% of 94.40GB   Users logged in:       0
  Memory usage: 46%                IPv4 address for ens3: 133.125.39.81
  Swap usage:   22%

Django アプリ復活で解決

ログイン機能が 502 エラーを返していた状況はなくなり、問題なく動く様になりました。

原因は Django のコードに print 文がコメントアウトされずに残っていて、自然言語処理に関する冗長なログがそのまま Gunicorn 経由で出力されていたためでした。

Certbot で新ドメインに Let's Encrypt SSL を適用

サーバー上で使っている複数のドメインの内、一部に対して Let's Encrypt が適用されていなかったので、追加適用しました。

Ubuntu 20.04 で Web サーバーとして Nginx を使っています。

すでに Certbot はインストール済みです。

自動更新タイマーの確認

「sudo systemctl status certbot.timer」を実行して、Certbot の自動更新のタイマーが動いているか確認します。

$ sudo systemctl status certbot.timer
[sudo] password for ユーザー名: 
● certbot.timer - Run certbot twice daily
     Loaded: loaded (/lib/systemd/system/certbot.timer; enabled; vendor preset: enabled)
     Active: active (waiting) since Wed 2022-05-18 22:15:43 JST; 5 months 2 days ago
    Trigger: Fri 2022-10-21 07:14:04 JST; 9h left
   Triggers: ● certbot.service

「Active: active (waiting) since Wed 2022-05-18 22:15:43 JST; 5 months 2 days ago」となっている通り、タイマー自体は動いています。

新ドメインへの Let's Encrypt 適用

Nginx の設定ファイルに新ドメインの設定がされている状態で、「$ sudo certbot」を実行します。

$ sudo certbot
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx

Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: www.graffuhs.com
2: example.com
3: sub1.example.com
4: sub2.example.com
5: sub3.example.com
6: www.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 

どのドメインに対して HTTPS を有効にするか聞かれます。

今回は「sub3.example.com」に適用したいので「5」と入力しました。

Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 5
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for sub3.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/example.com

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):

Web サーバーの設定に対して HTTP → HTTPS へのリダイレクトを行うか聞かれますが、実は設定ファイル上ではすでにリダイレクト設定はしておいたので、今回は「1」(リダイレクトなし)とします。

Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1
Future versions of Certbot will automatically configure the webserver so that all requests redirect to secure HTTPS access. You can control this behavior and disable this warning with the --redirect and --no-redirect flags.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://sub3.example.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=sub3.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

特にエラーもなく、これで完了です。ブラウザで確認してみても鍵マークがついていますね。

ちなみに

もう特にする事はないですが、上記メッセージの最後の行にサイトをテストできる URL が貼ってあったので飛んでみました。

こんな感じです。

それから、証明書と chain(?)、そして鍵ファイルの場所が書いてありました。直接アクセスはできませんでしたが、システム上こんな感じで管理されている様です。

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/sub3.example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/sub3.example.com/privkey.pem
   Your cert will expire on 2023-01-18. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

Homebrew の Failed to download resource 系エラーの確認方法

Homebrew がファイルをダウンロードする必要がある際、何らかの理由でダウンロードに失敗した場合「Failed to download resource 〜」というエラーが表出されます。

Failed to download resource 系エラーの例

  • Failed to download resource "gdbm"
  • Failed to download resource "gdbm_bottle_manifest"
  • Failed to download resource "openssl@1.1_bottle_manifest"

何らかの理由でファイルがダウンロード出来なかったということですが、ご想像の通り理由は多岐にわたります。

一つ共通の解決方法があるわけではないので、エラーメッセージの周辺のヒントを頼りに確認出来ます。

curl エラーコードの確認

上記の様な文言の直前に「curl: 〜」で始まる部分があると思います。

「curl: (7) Couldn't connect to server」や「curl: (22) The requested URL returned error: 403 Forbidden」、「curl: (22) The requested URL returned error: 404 Not Found」など、() の中に数字が入っているのでそれをエラーコードのリストで確認し、大きな意味で何が起きているのかを確認出来ます。

参照:libcurl error codes

エラー「Failed to download resource 〜」での検索と同時に「curl: 〜」の文言でも検索すると良いかと思います。

番外編 Bintray.com の終了に伴うエラー

エラーメッセージの直後にダウンロード元の URL が書いてあると思いますが、そのダウンロード元 URL が「https://homebrew.bintray.com/ 〜」で始まる場合は brew update で Homebrew を更新してください。

バイナリ共有のプラットフォームとして Homebrew のファイルも配置されていた Bintray ですが、サービスを終了するということで Homebrew のパッケージは Github へ統合されています。

「authenticating for org.freedesktop.systemd1.〜」の意味

Linux OS で作業しているとたまに表示される「authenticating for org.freedesktop.systemd1.〜」という文言。

直訳すると「org.freedesktop.systemd1.〜 のために認証を行なっています」となりますが、どういう意味なのでしょうか。

Polkit によるアクセス管理

このメッセージは Polkit という認証 API から発されているのですが、Linux 系 OS の起動処理やシステム管理に関する機能を提供する systemd は、基本的に Polkit によって特権プロセスへのアクセスを管理しています。

その上で、非特権プロセスが特権プロセスと通信する必要がある際、Polkit によって認証を行い、問題がない場合に許可を与えます。

参照:freedesktop.org - polkit

特権の種類

リクエストされた処理の種類によって、Polkit によって与えられる特権の種類が変わります。

  • ユニットの状態を変更するプロセス
    • org.freedesktop.systemd1.manage-units
  • ユニットファイルの Enable/Disable 状態を変更するプロセス
    • org.freedesktop.systemd1.manage-unit-files
  • 環境変数を変更するプロセス
    • org.freedesktop.systemd1.set-environment
  • Reload と Reexecute
    • org.freedesktop.systemd1.reload-daemon

systemd に対して変更する際に表示される

つまり、systemd のユニットの状態を変更するプロセスが行われる際にアクセス認証として「authenticating for org.freedesktop.systemd1.〜」が表示され、ユーザー名とパスワードが求められます。

参照:freedesktop.org - org.freedesktop.systemd1

【Ubuntu】sudo ユーザーを作成する方法

ユーザーの作成

root ユーザーに昇格します。

ubuntu@xx1-234-56789:~$ sudo su -

「adduser ユーザー名」でユーザーを作成します。

root@xx1-234-56789:~# adduser adminvps
Adding user `adminvps' ...
Adding new group `adminvps' (1002) ...
Adding new user `adminvps' (1002) with group `adminvps' ...
Creating home directory `/home/adminvps' ...
Copying files from `/etc/skel' ...
New password: 
Retype new password: 
passwd: password updated successfully
Changing the user information for adminvps
Enter the new value, or press ENTER for the default
	Full Name []: 
	Room Number []: 
	Work Phone []: 
	Home Phone []: 
	Other []: 
Is the information correct? [Y/n] Y
root@xx1-234-56789:~#

sudo グループに追加

このユーザーで sudo コマンドが使える様、sudo グループに追加します。

root@xx1-234-56789:~# gpasswd -a adminvps sudo
Adding user adminvps to group sudo
root@xx1-234-56789:~#

「exit」で root から出ます。

root@xx1-234-56789:~# exit
logout
ubuntu@xx1-234-56789:~$

今追加したユーザーで接続してみます。質問に「yes」と回答してパスワードを入力すると無事新ユーザーで接続ができます。

ubuntu@xx1-234-56789:~$ ssh adminvps@xx1-234-56789.vs.sakura.ne.jp
The authenticity of host '@xx1-234-56789 (127.0.1.1)' can't be established.
ECDSA key fingerprint is QWE123:QWERTYUIOPASD+QWERTYUIOP+ZXCVBNM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'xx1-234-56789' (ECDSA) to the list of known hosts.
adminvps@xx1-234-56789's password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-70-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Apr  9 19:43:32 JST 2021

  System load:  0.0               Processes:             119
  Usage of /:   2.6% of 94.43GB   Users logged in:       1
  Memory usage: 18%               IPv4 address for ens3: 133.125.39.81
  Swap usage:   0%

 * Introducing self-healing high availability clusters in MicroK8s.
   Simple, hardened, Kubernetes for production, from RaspberryPi to DC.

     https://microk8s.io/high-availability

0 updates can be installed immediately.
0 of these updates are security updates.



The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.


SAKURA internet [Virtual Private Server SERVICE]

To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

adminvps@xx1-234-56789:~$