LoginSignup
0
0

More than 5 years have passed since last update.

固定IPルーティング設定でハマった時の回避策

Last updated at Posted at 2019-01-26

環境は、Google Cloud Platform上のDebian GNU/Linux9 (stretch)です。NetworkManagerとかは導入していません。

ネットで調べる限りでは、

/etc/network/interfaces
auto eth0
iface eth0 inet dhcp
    # mainテーブルよりも高い(=小さい)優先度を設定
    up ip rule add from 10.8.0.0/24 priority 100 table vpn
    up ip route add default via 172.16.0.1 protocol static table vpn
    # デバッグ用
    up ip route show table vpn 2>&1 > /tmp/log

で設定できるはずなのですが、上手くいきませんでした。詳しい状況としては、ruleは反映されている一方で、routeが反映されていませんでした。デバッグ用に取った、/tmp/logを見る限りでは上手くいっているので、実はこの後に一度リセットが入るとかのトラップ(バグ)が有るのでしょうか?

さらには、

systemctl restart networking

もしくは

ifdown eth0
ifup eth0

を実行すると正しく設定されるので、もう意味不明です。googleの独自設定の影響かな?

調べて見ると、ifupdown2とかifupdown-extraとかを使えば可能性はありそうでしたが、面倒なので諦めました。

通常の方法が使えないため、別の方法として、DHCPのhookを作ってそのなかでルーティングを行うことにしました。

/etc/dhcp/dhclient-exit-hooks.d/vpn-routes
if [ "$reason" = "BOUND" ] || [ "$reason" = "REBOOT" ]; then
    ip rule add from 10.8.0.0/24 priority 100 table vpn
    ip route add default via 172.16.0.2 protocol static table vpn
fi

こちらは上手く動作しています。

原因がわかる方はコメントを残していただけると幸いです。

追記

systemdを使って、以下のようにルーティングの設定をしようとしましたが、やはり同じように失敗しました。

デフォルトのサービスファイルをコピーします。この方法は、デフォルトの設定を変えたい時に行います。

cp /lib/systemd/system/networking.service /etc/systemd/system

以下の内容を追加します。

/etc/systemd/system/networking.service
[Service]
Type=oneshot
...
ExecStartPost=/opt/bin/my-route-up # 追加
ExecStart=/sbin/ifup -a --read-environment
...
ExecStop=/opt/bin/my-route-down # 追加
ExecStop=/sbin/ifdown -a --read-environment --exclude=lo # この上に追加
...
/opt/bin/my-route-up
#!/bin/bash
ip rule add from 10.8.0.0/24 priority 100 table vpn
ip route add default via 172.16.0.1 table vpn
/opt/bin/my-route-down
#!/bin/bash
ip route flush table vpn
ip rule delete table vpn

これで、networkingサービスが起動した後に、/opt/bin/my-route-upを実行してくれます。また、終了する前には、/opt/bin/my-route-downを実行してくれます。Typeがoneshotなので、ifup -a --read-environmentの実行が終了した時に、サービスの起動が完了したとみなされます。

the service manager will consider the unit started after the main process exits.
(https://www.freedesktop.org/software/systemd/man/systemd.service.html より引用)

ExecStopPreは実装されていないそうなので、ExecStopで対応します。そのため、ExecStopの順番が大切です。

この方法が、全く同じように失敗する(ruleの追加はされている)ので、おそらくifupdown自体の問題ではないのだと思います。

ちなみに、networkingサービスが起動した後に起動するサービスは、

systemctl list-units --before networking

で確認できます。この中に、ルーティングテーブルをいじっているサービスがあるのでしょうか。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0