2024年9月14日土曜日

Oracle VM VirtualBox (Windows版)&Guest Additionsインストール手順 (6.1、7.1対応)

WindowsやMACのPCにて手軽にLinuxなどの検証を行いたい場合がある。そのような場合には、PCにインストール可能なホスト側仮想化ソフトウェアを利用し、Linuxの仮想マシンを構築することができる。

ホスト型仮想化ソフトウェアとして利用可能なものは、以下のようなものがある。

製品名 プラットフォーム 説明
Oracle VM VirtualBox Windows, macOS, Linuxなど 様々なプラットフォームで動作し、無償であるにも関わらずかなり柔軟に仮想マシンの設定が可能。また、Vagrantを使えば構築の自動化も可能。
VMware Workstation Player Windows vSphereでおなじみのVMwareのホスト型仮想化ソフトウェア。
VMware Fusion Player macOS macOSを所有していないため評価不可。

今回は、「Oracle VM VirtualBox」をWindows環境にインストールし、VirtualBox上にWindows Server 2019とRHEL 8.4をインストールする手順を記載する。

環境

VirtualBoxをインストールする手ごろなWindowsクライアントがすぐに用意できなかったため、たまたまインストールしていたWindows Server 2022 PreviewにVirtualBoxをインストールしたが、他Windows環境でも手順に差異はないだろう。

また、VirtualBoxは6.1.24と7.1.0の二種類でインストールを確認しているが、本記事の画面は6.1.24のものを記載する。

  • Windows Server 2022 Preview
  • Oracle VM VirtualBox 6.1.24 / 7.1.0

なお、私の環境はESXi上のOSにVirtualBoxをインストールする構成となる。このような構成の場合は、ESXiのCPUの設定にて「ハードウェア アシストによる仮想化をゲスト OS に公開」を有効にすること。

Oracle VM VirtualBoxインストール手順

1. Oracle VM VirtualBoxのダウンロード

VirtualBox本家とOracle 日本のいずれかからVirtualBoxのダウンロードができる。Oracle 日本でダウンロードできるバージョンは少し古くなってしまうことから、特に理由がなければ本家からダウンロードすれば問題ない。

また、同じサイトでダウンロードできるOracle VM VirtualBox Extension Packもダウンロードしておく。Extension Packをインストールすることで、USBコントローラやディスク暗号化などの拡張機能を利用することができる。

2. (VirtualBox 7以降)Pythonのインストール

VirtualBoxの前提として、Pythonとpywin32のインストールが必要となる。Pythonは以下からダウンロードしてインストールする。Pythonは管理者として実行してインストールすること。

Pythonインストール後、PowerShellを開き、pywin32をインストールする。

pip install pywin32 --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org

3. VirtualBox本体のインストール

ダウンロードしたexeファイルをダブルクリックすれば、インストールウィザードを起動する。基本的には、すべてを「次へ」を押して進めばよい。

インストールが開始されると、「このデバイスをインストールしますか?」と表示されるので、「インストール」を選んでおく。

4. Extension Packのインストール

VitualBoxをインストールしたのち、Extension Packのファイル (vbox-extpack) をダブルクリックすることでインストールを開始することができる。

ライセンス規約が表示されるので、一番下までスクロールしたのち、「同意します」を選択する。

インストールが成功すると、以下のような「拡張機能パッケージ Oracle VM Virtual Box Extension Pack のインストールに成功しました。」のメッセージが表示される。
※完了メッセージが表示されない場合もある模様。

VirtualBox上にWindows Server 2019をインストール

1. 仮想マシンを作成

「新規」ボタンをクリックすることで、仮想マシンの作成ウィザードが表示される。以下のように設定を行い仮想マシンを作成する。

設定値 説明
名前 任意で指定。今回はwin2019とする。
タイプ Microsoft Windows
バージョン Windows 2019 (64-bit)
メモリーサイズ 任意で指定。デフォルトは2048MB
ハードディスク 「仮想ハードディスクを作成する」を選択
ハードディスクのファイルタイプ デフォルトの「VDI (VirtualBox Disk Image)」を選択する。なお、「VHD」 (Hyper-Vで使用) や「VMDK」 (ESXiで使用) も選択可能。
物理ハードディスクにあるストレージ 可変サイズと固定サイズが選択できる。いわゆるシックプロビジョニングとシンプロビジョニングに対応する。「固定」の場合はディスク作成時にすべての容量が割り当てられてしまい効率が悪いので、使用した分だけディスクサイズを割り当てていく「可変」を選択する。
ファイルの場所とサイズ 任意で指定。デフォルトは50GB

2. OSをインストールメディアから起動

作成した仮想マシンの「設定」を開き、「ストレージ」→「光学ドライブ」を選択する。CDマークを選択し、「ディスクファイルを選択」を選択し、Windows Server 2019のISOイメージを選択する。

仮想マシンの起動モードは以下3種類ある。VirtualBox用語となっており、初見では動作の違いが判らないため、それぞれの違いを以下に記載する。

起動モード 説明
通常起動 起動時に仮想マシンのコンソールが開く。コンソールを閉じる際は、「状態保存 (いわゆるサスペンド)」または「仮想マシンの停止」のみ選択が可能。
ヘッドレス起動 起動時に仮想マシンのコンソールが開かない。起動後に「表示」を選択することで仮想マシンのコンソールを開くことができる。コンソールを閉じる際に「バックグラウンドで動作を継続」を選択することで、仮想マシンのコンソールを閉じても起動状態を継続させることが可能。
デタッチモード起動 起動時に仮想マシンのコンソールが開く。それ以外は「ヘッドレス起動」と同様となり、「バックグラウンドで動作を継続」を選択可能。

通常は、仮想マシンのバックグラウンドでの起動が選択可能な、「デタッチモード起動」を選択しておけば問題ないだろう。

3. OSインストール

Windows Serverのインストールメディアを読み込むので、Enterを押しインストールを開始させる。インストール手順自体は特に通常と変更は不要であるため割愛する。

インストール完了後はインストールメディアは不要となることから、「デバイス」→「光学ドライブ」→「仮想ドライブからディスクを除去」を選択しインストールメディアを取り出しておこう。

4. Guest Additionsをインストール

VirtualBoxでは「Guest Additions」と呼ばれる、ESXiでいうところのVMware Toolsと同様の機能を待つエージェントのインストールが推奨される。

「デバイス」→「Guest Additions CDイメージの挿入…」を選択する。

すると、仮想CDドライブに「VirtualBox Guest Additions」というメディアがマウントされるので、これをダブルクリックすることでインストールウィザードが開始される。インストールウィザードでは、基本的には、すべてを「次へ」を押して進めばよい。

インストールが開始されると、「このデバイスをインストールしますか?」と表示されるので、「インストール」を選んでおく。

最後に再起動を求められるため、再起動して完了となる。

Guest Additionsが正常にインストールされていることの確認は、「仮想マシン」→「セッション情報」→「ランタイム情報」から確認することができる。


VirtualBox上にRHEL 8.4をインストール

1. 仮想マシンを作成~OSインストール

Windows Serverと同様の手順となるため割愛する。

2. Guest Additionsをインストール

RHELに対してGuest Additionsをインストールする場合は、GUIではなくCLIによるインストールを行う。

まず、前提パッケージとして以下が必要となる。

  • kernel-headers
  • kernel-devel
  • tar
  • bzip2
  • gcc
  • make
  • perl
  • elfutils-libelf-devel

上記パッケージをdnfまたはyumを使ってインストールを行うのだが、インターネット経由でインストールする場合、ネットワーク設定やサブスクリプション登録など手順が多くなる。そこで、今回はRHELのOSインストールメディアに含まれるパッケージを用いてインストールを行う。

まず、OSインストールメディアのパッケージが含まれるディレクトリをリポジトリとして登録する。

# cat << EOF > /etc/yum.repos.d/dvd-base.repo
[dvd-base]
baseurl=file:///media/BaseOS/
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
EOF

# cat << EOF > /etc/yum.repos.d/dvd-appstream.repo
[dvd-appstream]
baseurl=file:///media/AppStream/
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
EOF

次にOSインストールメディアをマウントし、dnfにてパッケージのインストールを行う。

# mount /dev/cdrom /media/
mount: /media: 警告: デバイスは書き込み禁止です、読み込み専用でマウントします.
# dnf install kernel-headers kernel-devel -y
# dnf install tar bzip2 gcc make perl elfutils-libelf-devel -y
# eject /dev/sr0

次に、OSインストールメディアを「Guest Additions」のメディアに変更する。Windows Serverの手順と同様、「デバイス」→「Guest Additions CDイメージの挿入…」を選択したのち、VBoxLinuxAdditions.runを実行すると、自動的にGuest Additionsがインストールされる。

# mount /dev/cdrom /media/
mount: /media: 警告: デバイスは書き込み禁止です、読み込み専用でマウントします.

# /media/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 6.1.24 Guest Additions for Linux........
VirtualBox Guest Additions installer
Removing installed version 6.1.24 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
VirtualBox Guest Additions: Starting.
VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel
modules.  This may take a while.
VirtualBox Guest Additions: To build modules for other installed kernels, run
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup <version>
VirtualBox Guest Additions: or
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup all
VirtualBox Guest Additions: Building the modules for kernel
4.18.0-305.el8.x86_64.
ValueError: File context for /opt/VBoxGuestAdditions-6.1.24/other/mount.vboxsf already defined

最後に再起動をしておく。

# reboot

再起動後、Guest Additionsのサービスvboxaddの正常起動を確認できれば完了となる。

# systemctl status vboxadd
● vboxadd.service
     Loaded: loaded (/opt/VBoxGuestAdditions-7.1.0/init/vboxadd; enabled; preset: disabled)
     Active: active (exited) since Fri 2024-09-13 22:13:12 JST; 56s ago
    Process: 43447 ExecStart=/opt/VBoxGuestAdditions-7.1.0/init/vboxadd start (code=exited, status=0/SUCCESS)
   Main PID: 43447 (code=exited, status=0/SUCCESS)
        CPU: 483ms

 9月 13 22:13:12 localhost.localdomain systemd[1]: Starting vboxadd.service...
 9月 13 22:13:12 localhost.localdomain vboxadd[43447]: VirtualBox Guest Additions: Starting.
 9月 13 22:13:12 localhost.localdomain systemd[1]: Finished vboxadd.service.

更新履歴

  • 2021/8/14 新規作成
  • 2024/9/14 VirtualBox 7.1.0のインストール結果を反映
2024年9月4日水曜日

Fluentdを使ってKubernetesのログをsyslogで送信する

KubernetesのPodのログはファイルに出力はされているが、1台のサーバーにログ集約を行い一元管理をしたい場合がある。そのような用途で利用されるソフトウェアとしてFluentdがある。

本記事では、Fluentdを使ってKubernetesのログをsyslogで送信する手順を記載する。

環境

今回の環境の構成概要図を以下に記載する。赤枠個所が本記事の設定個所となる。

以下に今回構築する各種ソフトウェアのバージョンを記載する。

  • ホストOS : AlmaLinux 8.6
  • Docker : 24.0.6
  • cri-dockerd: 0.3.4
  • Kubernetes: v1.29.4

Fluentd導入

1. fluentd-kubernetes-daemonsetのマニフェストファイルをダウンロード

FluentdをKubernetesで動作させるため、fluentd-kubernetes-daemonsetを導入する。マニフェストファイルは以下からダウンロードできる。

今回はsyslogによるログ送信をしたいことから、fluentd-daemonset-syslog.yamlをダウンロードする。ダウンロード方法は任意となるが、curlを使う場合は以下の通り行う。

# curl -LO https://raw.githubusercontent.com/fluent/fluentd-kubernetes-daemonset/master/fluentd-daemonset-syslog.yaml

2. マニフェストファイルを修正

マニフェストファイルそのままではsyslogファイルを正常に送ることができないため、以下の★箇所の修正を行う。

fluentd-daemonset-syslog.yaml

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: fluentd
  namespace: kube-system
  labels:
    k8s-app: fluentd-logging
    version: v1

~(中略)~

---
apiVersion: apps/v1
kind: DaemonSet

~(中略)~

      containers:
      - name: fluentd
        image: fluent/fluentd-kubernetes-daemonset:v1-debian-syslog
        env:
          - name: K8S_NODE_NAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName
          - name:  SYSLOG_HOST
            value: "192.168.1.1" # ★ログ送信先のsyslogサーバーを指定
          - name:  SYSLOG_PORT
            value: "514" # ★ポート番号を変更する場合は修正
          - name:  SYSLOG_PROTOCOL
            value: "tcp" # ★udpまたはtcpを指定
          - name:  FLUENTD_SYSTEMD_CONF
            value: "disable" # ★"No such file or directory retrying in 1s"のエラーログ抑止のため指定
          - name:  TZ
            value: "Asia/Tokyo" # ★Fluentdのログのタイムゾーンを指定(デフォルトはUTC)
        resources:
          limits:
            memory: 200Mi
          requests:
            cpu: 100m
            memory: 200Mi
        volumeMounts:
        - name: varlog
          mountPath: /var/log
        # When actual pod logs in /var/lib/docker/containers, the following lines should be used.
        - name: dockercontainerlogdirectory     # ★アンコメント
          mountPath: /var/lib/docker/containers # ★アンコメント
          readOnly: true                        # ★アンコメント
        # When actual pod logs in /var/log/pods, the following lines should be used.
        #- name: dockercontainerlogdirectory    # ★コメントアウト
        #  mountPath: /var/log/pods             # ★コメントアウト
        #  readOnly: true                       # ★コメントアウト
      terminationGracePeriodSeconds: 30
      volumes:
      - name: varlog
        hostPath:
          path: /var/log
      # When actual pod logs in /var/lib/docker/containers, the following lines should be used.
      - name: dockercontainerlogdirectory  # ★アンコメント
        hostPath:                          # ★アンコメント
          path: /var/lib/docker/containers # ★アンコメント
      # When actual pod logs in /var/log/pods, the following lines should be used.
      #- name: dockercontainerlogdirectory # ★コメントアウト
      #  hostPath:                         # ★コメントアウト
      #    path: /var/log/pods             # ★コメントアウト

3. マニフェストファイルをapply

修正したマニフェストファイルapplyする。

# kubectl apply -f fluentd-daemonset-syslog.yaml
serviceaccount/fluentd created
clusterrole.rbac.authorization.k8s.io/fluentd created
clusterrolebinding.rbac.authorization.k8s.io/fluentd created
daemonset.apps/fluentd created

成功すると、fluentdのPodが各KubernetesノードでRunningとなるはずだ。

# kubectl get pod -n=kube-system
NAME                                READY   STATUS    RESTARTS      AGE
coredns-76f75df574-dntsp            1/1     Running   1 (51d ago)   105d
coredns-76f75df574-lswd4            1/1     Running   1 (51d ago)   105d
etcd-t1051kube                      1/1     Running   1 (51d ago)   105d
etcd-t1052kube                      1/1     Running   1 (51d ago)   105d
etcd-t1053kube                      1/1     Running   1 (51d ago)   105d
fluentd-k98t7                       1/1     Running   0             18s
fluentd-pn55s                       1/1     Running   0             18s
fluentd-xq6rb                       1/1     Running   0             18s
kube-apiserver-t1051kube            1/1     Running   1 (51d ago)   105d
kube-apiserver-t1052kube            1/1     Running   1 (51d ago)   105d
kube-apiserver-t1053kube            1/1     Running   1 (51d ago)   105d
kube-controller-manager-t1051kube   1/1     Running   3 (20d ago)   105d
kube-controller-manager-t1052kube   1/1     Running   2 (51d ago)   105d
kube-controller-manager-t1053kube   1/1     Running   2 (19d ago)   105d
kube-proxy-7lhj5                    1/1     Running   1 (51d ago)   105d
kube-proxy-gx8rj                    1/1     Running   1 (51d ago)   105d
kube-proxy-krjfz                    1/1     Running   1 (51d ago)   105d
kube-scheduler-t1051kube            1/1     Running   3 (51d ago)   105d
kube-scheduler-t1052kube            1/1     Running   1 (51d ago)   105d
kube-scheduler-t1053kube            1/1     Running   3 (19d ago)   105d

4. 動作確認

ログ送信先となるsyslogサーバーにてログの受信状況を確認する。以下は私の環境の例となる。Fluentd経由でSquidのPodの標準出力に対して出力された接続ログが出力されている。
※Podのログを収集する場合、標準出力に対して出力させるようコンテナを構成する必要があるため注意する。

Aug 31 18:07:00 fluentd-72t29 fluentd: log:1725095215.225  83353 10.244.1.0 TCP_TUNNEL/200 6767 CONNECT www.googleapis.com:443 - HIER_DIRECT/172.217.175.234 -
Aug 31 18:07:00 fluentd-72t29 fluentd: log:1725095215.225  63309 10.244.3.0 TCP_TUNNEL/200 2408 CONNECT play.google.com:443 - HIER_DIRECT/142.251.222.14 -
Aug 31 18:07:00 fluentd-72t29 fluentd: log:1725095215.225 138131 10.244.0.1 TCP_TUNNEL/200 28279 CONNECT apis.google.com:443 - HIER_DIRECT/172.217.175.238 -
Aug 31 18:07:00 fluentd-72t29 fluentd: log:1725095215.226  63194 10.244.0.1 TCP_TUNNEL/200 4006 CONNECT play.google.com:443 - HIER_DIRECT/142.251.222.14 -
Aug 31 18:07:00 fluentd-72t29 fluentd: log:1725095215.224  56514 10.244.1.0 TCP_TUNNEL/200 2491 CONNECT ogs.google.com:443 - HIER_DIRECT/142.250.196.110 -

以上で、Fluentdを使ってKubernetesのログをsyslogで送信する手順は完了となる。

2024年8月31日土曜日

rsyslogでリモートサーバーのログを集約管理する

大半のLinuxディストリビューションに導入されているrsyslogはリモートサーバーへログを送信したり、受信したりする機能がある。この機能を活用すると、1台のサーバーにてログの集約管理が実現できる。

本記事では、rsyslogでリモートサーバーのログを集約管理する手順を記載する。

環境

今回の環境の構成概要図を以下に記載する。赤枠個所が本記事の設定個所となる。

設定手順はAlmaLinux 9にて確認しているが、他のディストリビューションのrsyslogでも、同じ設定で対応が可能と思われる。

受信側設定

1. ログ保管用ディレクトリの作成

リモートサーバーのログを保管するディレクトリとして、/remotelogを作成する。また、ローテーションしたファイルを保管するディレクトリとして、配下に_oldディレクトリを作成する。

# mkdir /remotelog
# mkdir /remotelog/_old

2. rsyslogの設定

/etc/rsyslog.confの以下個所をアンコメントし、TCP及びUDPにてsyslog受信をできるよう設定する。

/etc/rsyslog.conf

module(load="imudp") # needs to be done just once
input(type="imudp" port="514")

module(load="imtcp") # needs to be done just once
input(type="imtcp" port="514")

次に、受信したsyslogに記載されているホスト名の情報をもとに、個別のファイルを作成する設定をrsyslogに対して行う。

templateにて動的にファイル名を設定するルールを作成し、それをactionのDynaFile(動的ファイル名)にて指定することで、リモートサーバーからsyslogを受信すると、自動的に/remotelog/[ホスト名].logというファイルを作成しログが保存される。

なお、ログ集約サーバー自身のログは、通常通り/var/log配下に出力させるため、if文で127.0.0.1のIPアドレスを除外するように設定した。

/etc/rsyslog.d/41-recieve-log.conf

# Template
template(name="TmplRemoteLogFile" type="string"
  string="/remotelog/%HOSTNAME%.log"
)

# Other remote servers
if $fromhost-ip != '127.0.0.1' then {
  action(type="omfile" DynaFile="TmplRemoteLogFile")
  stop
}

3. 設定反映

rsyslogの設定内容に問題がないことを以下コマンドで確認する。-Nオプションはコンフィグチェックのオプションとなる。

# rsyslogd -N 1
rsyslogd: version 8.2310.0-4.el9, config validation run (level 1), master config /etc/rsyslog.conf
rsyslogd: End of config validation run. Bye.

問題なければrsyslogのサービス再起動を行い、設定を反映させる。

# systemctl restart rsyslog

設定反映後、TCP/514、UDP/514のポートでLISTENされていることを確認しておこう。

# ss -nl | grep 514
udp   UNCONN 0      0            0.0.0.0:514            0.0.0.0:*
udp   UNCONN 0      0            [::]:514               [::]:*
tcp   LISTEN 0      25           0.0.0.0:514            0.0.0.0:*
tcp   LISTEN 0      25           [::]:514               [::]:*

4. logrotateの設定

ファイルを日次でログローテートするよう、以下の通りlogrotateの設定を行う。olddirにてローテーション先のディレクトリを同一ディレクトリから変更している。

/etc/logrotate.d/remotelog

/remotelog/*.log
{
    daily
    rotate 7
    dateext
    compress
    delaycompress
    create 644 root root
    missingok
    olddir=/remotelog/_old
    sharedscripts
    postrotate
        /usr/bin/systemctl -s HUP kill rsyslog.service >/dev/null 2>&1 || true
    endscript
}

送信側設定

1. rsyslogの設定

先ほど設定したrsyslogサーバーにログを送信するため、以下ファイルを作成する。TCP送信とUDP送信で、微妙に記載方法が異なる。syslogというとUDPによる送信というイメージが強いが、ログの欠落が発生しづらい点からTCPによる送信が個人的にはお勧めの設定となる。

/etc/rsyslog.d/40-send-log.conf

TCPで送信する場合

*.* @@[rsyslogサーバーのIPアドレス]:514

UDPで送信する場合。

*.* @[rsyslogサーバーのIPアドレス]:514

2. 設定反映

rsyslogの設定内容に問題がないことを以下コマンドで確認する。-Nオプションはコンフィグチェックのオプションとなる。

# rsyslogd -N 1
rsyslogd: version 8.2310.0-4.el9, config validation run (level 1), master config /etc/rsyslog.conf
rsyslogd: End of config validation run. Bye.

問題なければrsyslogのサービス再起動を行い、設定を反映させる。

# systemctl restart rsyslog

動作確認

送信元サーバーにてloggerコマンドを実行し、想定通りログが送信させることを確認する。

# logger "test syslog message"

rsyslogサーバーにてログが表示されれば成功となる。

# tail /remotelog/test-server.log
Aug 31 07:29:06 test-server root[605149]: test syslog message

以上で、rsyslogでリモートサーバーのログを集約管理する手順は完了となる。

2024年8月25日日曜日

Splunk本体とUniversal ForwarderをAlmaLinux 9にインストールする手順

自宅環境にてログ集約と解析ができるようにログ管理基盤を作ることにした。ログ解析にはSplunk を利用する方針とした。本記事では、Splunk本体とUniversal ForwarderをAlmaLinux 9にインストールする手順を記載する。

以下は自宅のログ管理基盤の構成概要図となる。赤枠個所が本記事の範囲となる。

環境

環境は以下の通りとなる。Splunk本体とUniversal Forwarderを導入するサーバーは別サーバーとしている。

  • OS : AlmaLinux 9.4
  • Splunk : 9.0.3
  • Splunk Universal Forwarder : 9.0.3

Splunkのインストール

1. Splunkインストーラのダウンロード

Splunkは以下URLからダウンロードできる。ダウンロードするためにはアカウント作成が必要となる。

https://www.splunk.com/ja_jp/download/splunk-enterprise.html

Linux版は、.deb、.rpm、.tgzの3点が選べるが、個人的お勧めは.tgzとなる。本手順も.tgzによるインストールを記載する。

2. インストール

ダウンロードしたファイル(本手順ではsplunk-9.3.0-51ccf43db5bd-Linux-x86_64.tgzというファイル名となる)をサーバーに配置し、以下コマンドで展開するのみでインストールは完了する。

tar xvzf splunk-9.3.0-51ccf43db5bd-Linux-x86_64.tgz -C /opt

3. Splunkの初回起動と初期設定

/opt/splunk/binディレクトリにSplunk本体の実行ファイルがあるので、以下の通り実行することで、初回起動時の以下処理が実行される。

  • ライセンス条項に同意
  • 管理ユーザ名の設定 (デフォルトはadmin)
  • 管理ユーザのパスワードの設定
# cd /opt/splunk/bin/
# ./splunk start
SPLUNK GENERAL TERMS

Last Updated: August 12, 2021

These Splunk General Terms ("General Terms") between Splunk Inc., a Delaware
corporation, with its principal place of business at 270 Brannan Street, San
Francisco, California 94107, U.S.A ("Splunk" or "we" or "us" or "our") and you
("Customer" or "you" or "your") apply to the purchase of licenses and
subscriptions for Splunk's Offerings. By clicking on the appropriate button,
or by downloading, installing, accessing or using the Offerings, you agree to
these General Terms. If you are entering into these General Terms on behalf of
Customer, you represent that you have the authority to bind Customer. If you
do not agree to these General Terms, or if you are not authorized to accept
the General Terms on behalf of the Customer, do not download, install, access,
or use any of the Offerings.

~(中略)~

Do you agree with this license? [y/n]: y ←★"y"を入力

This appears to be your first time running this version of Splunk.

Splunk software must create an administrator account during startup. Otherwise, you cannot log in.
Create credentials for the administrator account.
Characters do not appear on the screen when you type in credentials.

Please enter an administrator username: admin ←★管理者ユーザ名を入力
Password must contain at least:
   * 8 total printable ASCII character(s).
Please enter a new password:     ←★パスワードを入力
Please confirm new password:     ←★パスワードを再入力
Copying '/opt/splunk/etc/openldap/ldap.conf.default' to '/opt/splunk/etc/openldap/ldap.conf'.

~(中略)~

The Splunk web interface is at http://example:8000

5. 自動起動設定

.tgzファイルを解凍しただけなので、これだけではサーバ再起動時に自動起動してくれないため、コマンドで自動起動するよう設定する。ただし、AlmaLinux 9などのRHEL 9系においてchkconfigパッケージがインストールされていない場合、以下の通りエラーが発生する。

# /opt/splunk/bin/splunk enable boot-start
Can't create RC file "/etc/init.d/splunk": No such file or directory

そのため、chkconfigパッケージがインストールされていない場合はインストールを事前に行っておく。

# dnf install chkconfig -y

chkconfigインストール後、以下の通り実行し、自動起動設定を行う。

# /opt/splunk/bin/splunk enable boot-start
Init script installed at /etc/init.d/splunk.
Init script is configured to run at boot.

試しに再起動を行ったのちステータスを確認したところ、問題なくSplunkが「running」ステータスとなっていた。

# reboot

# uptime
 10:26:23 up 0 min,  1 user,  load average: 0.14, 0.03, 0.01
# /opt/splunk/bin/splunk status
splunkd is running (PID: 1411).
splunk helpers are running (PIDs: 1412 1565 1570 1799 1864).

6. 管理Web画面にアクセス

以上を実施したのち「http://<インストールしたホスト名 or IPアドレス>:8000」にアクセスすると、管理画面が表示されるはずなので、初回起動時に設定した管理者ユーザとパスワードでログインしてみよう。

ログインに成功すると、以下のようなSplunk の管理画面が表示される。

7. Splunk Universal Forwarderからの受信許可設定

管理画面の右上の「設定」 > 「転送と受信」を選択し、「受信の設定」の「+新規追加」ボタンを押しておく。

受信ポートは9997を設定し、「保存」を選択する。

Splunk Universal Forwarderのインストール

1. Splunk Universal Forwarderインストーラのダウンロード

Splunk Universal Forwarderは以下URLからダウンロードできる。ダウンロードするためにはアカウント作成が必要となる。

https://www.splunk.com/ja_jp/download/universal-forwarder.html

Linux版は、.deb、.rpm、.tgzの3点が選べるが、個人的お勧めは.tgzとなる。本手順も.tgzによるインストールを記載する。

2. インストール

ダウンロードしたファイル(本手順ではsplunkforwarder-9.3.0-51ccf43db5bd-Linux-x86_64.tgzというファイル名となる)をサーバーに配置し、以下コマンドで展開するのみでインストールは完了する。

# tar xvzf splunkforwarder-9.3.0-51ccf43db5bd-Linux-x86_64.tgz -C /opt/

3. Splunkの初回起動と初期設定

/opt/splunk/binディレクトリにSplunk本体の実行ファイルがあるので、以下の通り実行することで、初回起動時の以下処理が実行される。

  • ライセンス条項に同意
  • 管理ユーザ名の設定 (デフォルトはadmin)
  • 管理ユーザのパスワードの設定
# cd /opt/splunkforwarder/bin/
# ./splunk start
SPLUNK GENERAL TERMS

Last Updated: August 12, 2021

These Splunk General Terms ("General Terms") between Splunk Inc., a Delaware
corporation, with its principal place of business at 270 Brannan Street, San
Francisco, California 94107, U.S.A ("Splunk" or "we" or "us" or "our") and you
("Customer" or "you" or "your") apply to the purchase of licenses and
subscriptions for Splunk's Offerings. By clicking on the appropriate button,
or by downloading, installing, accessing or using the Offerings, you agree to
these General Terms. If you are entering into these General Terms on behalf of
Customer, you represent that you have the authority to bind Customer. If you
do not agree to these General Terms, or if you are not authorized to accept
the General Terms on behalf of the Customer, do not download, install, access,
or use any of the Offerings.

~(中略)~

Do you agree with this license? [y/n]: y ←★"y"を入力

This appears to be your first time running this version of Splunk.

Splunk software must create an administrator account during startup. Otherwise, you cannot log in.
Create credentials for the administrator account.
Characters do not appear on the screen when you type in credentials.

Please enter an administrator username: admin ←★管理者ユーザ名を入力
Password must contain at least:
   * 8 total printable ASCII character(s).
Please enter a new password:      ←★パスワードを入力
Please confirm new password:      ←★パスワードを再入力
Creating unit file...
Initd script /etc/init.d/splunk exists. splunk is currently enabled as init.d bootstart service.
Please run "splunk disable boot-start" first to disable it as init.d boot-start service
Failed to create the unit file. Please do it manually later.

~(中略)~

All preliminary checks passed.

Starting splunk server daemon (splunkd)...  
PYTHONHTTPSVERIFY is set to 0 in splunk-launch.conf disabling certificate validation for the httplib and urllib libraries shipped with the embedded Python interpreter; must be set to "1" for increased security
Done

5. 自動起動設定

.tgzファイルを解凍しただけなので、これだけではサーバ再起動時に自動起動してくれないため、コマンドで自動起動するよう設定する。Splunk本体と異なり、-user rootによる起動時の実行ユーザー指定が必要であり、かつsystemdによる登録となっており、chkconfigパッケージの導入は不要となる。

# /opt/splunkforwarder/bin/splunk stop
# /opt/splunkforwarder/bin/splunk enable boot-start -user root
Systemd unit file installed by user at /etc/systemd/system/SplunkForwarder.service.
Configured as systemd managed service.
# systemctl status SplunkForwarder
○ SplunkForwarder.service - Systemd service file for Splunk, generated by 'splunk enable boot-start'
     Loaded: loaded (/etc/systemd/system/SplunkForwarder.service; enabled; preset: disabled)
     Active: inactive (dead)
# systemctl start SplunkForwarder

6. 送信先のサーバ (インデクサー) を設定

Splunkのログ受信および解析を行う機能を「インデクサー」と呼ぶ。Universal Forwarderのログ送信先としてインデクサーを指定する必要があるため、splunk add forward-server <インデクサーのIPアドレス or ホスト名>:<ポート番号>コマンドにて行う。

# cd /opt/splunkforwarder/bin/
# ./splunk add forward-server 192.168.1.1:9997
Splunk username: admin
Password:
Added forwarding to: 192.168.1.1:9997.
# ./splunk list forward-server
Active forwards:
        None
Configured but inactive forwards:
        192.168.1.1:9997

本設定は、/opt/splunkforwarder/etc/system/local/outputs.confに記述される。

# cat /opt/splunkforwarder/etc/system/local/outputs.conf
[tcpout]
defaultGroup = default-autolb-group

[tcpout:default-autolb-group]
server = 192.168.1.1:9997

[tcpout-server://192.168.1.1:9997]

7. モニター対象のログを追加

今回は例として/var/log配下のログをすべて監視対象として、Splunk本体のインデクサーに送信する。splunk add monitor <モニター対象のファイル or ディレクトリ>コマンドで設定する。なお、本設定は再起動は不要で反映される。

# cd /opt/splunkforwarder/bin/
# ./splunk add monitor /var/log
Added monitor of '/var/log'.

splunk list monitorで設定確認を行う。ディレクトリが登録され、ディレクトリ内の各ファイルが表示されていれば問題ない。

# ./splunk list monitor
Monitored Directories:
	$SPLUNK_HOME/var/log/splunk
		/opt/splunkforwarder/var/log/splunk/audit.log
		/opt/splunkforwarder/var/log/splunk/btool.log
		/opt/splunkforwarder/var/log/splunk/conf.log

~(中略)~
	$SPLUNK_HOME/var/run/splunk/search_telemetry/*search_telemetry.json
	$SPLUNK_HOME/var/spool/splunk/tracker.log*
		/opt/splunkforwarder/var/spool/splunk/tracker.log
	/var/log ←★/var/log配下のログが追加されている。
		/var/log/anaconda
		/var/log/anaconda/anaconda.log
		/var/log/anaconda/dbus.log

~(以下略)~

8. 受信確認

Splunkにログインし「Search & Reporting」にて、index=*にてサーチを行い、ログが表示されることを確認しよう。

以上で、Splunk本体とUniversal ForwarderをAlmaLinux 9にインストールする手順は完了となる。

2024年8月11日日曜日

OpenAI APIを使ってZabbixの障害イベントを生成AIに連携する

ChatGPTでおなじみのOpenAIは、OpenAI APIと呼ばれるAPIによる利用が可能となっている。APIを利用することで、curlコマンドなどを用いて手軽に生成AIの機能をシステムに組み込んで利用することができる。

本記事では、OpenAI APIを使ってZabbixの障害アラートを生成AIに連携する手順を記載する。

具体的には、OpenAI APIを用いて以下のプロンプトを連携し、Zabbixの障害アラートの原因の問い合わせを行う。問い合わせで得られた生成AIの応答をZabbixのメッセージとして表示できるようにする。

Please tell me the cause of the error message below.
[障害アラートの内容]

なお、本記事の作成にあたり、以下の記事も参考にさせていただいた。

環境

今回の環境は以下の通り。

  • Zabbix 7.0

OpenAIのアカウントを作成していない場合は、事前に作成をしておこう。ChatGPTを利用している場合は、すでにアカウント作成済みとなるため、新たにアカウント作成は不要となる。

OpenAI APIのAPI keyを取得

1. OpenAI API keyの作成画面にログイン

以下URLにアクセスすると、OpenAI API keyの作成画面が表示される。

2. API keyを作成

「Create new secret key」ボタンを押し、API keyを作成する。

作成時にkeyの名前の入力を求められるが、未入力でも問題ない。

作成完了後、API keyが表示されるので、必ずコピーして控えること。ここでコピーしておかないと、以降確認することができないため、API keyを再作成する必要がある。

3. OpenAI APIの利用状況を確認

OpenAI APIはリクエストや応答に含まれるトークンの数によって課金される。トークンは英語の場合は1単語がおおよそ1トークンとなるようだが、日本語の場合は1文字が1トークン以上の場合があるとの情報があるので注意する。

トークンの使用状況は以下URLから確認することができる。

なお、アカウントを新規作成した際は、5.00 USD分の無料利用枠がある(3か月の期限付き)。テストする際にかなりAPIを使用してみたが、それでも0.03 USDしか消費しなかったので、5.00 USDあれば検証用途としては十分だろう。

OpenAI API連携用スクリプトの作成

1. curlによるOpenAI API実行方法

curlを使う場合は以下の通り実行すればOpenAI APIによる問い合わせができる。

# API keyを設定
export OPENAI_API_KEY='sk-********'

header='Content-Type: application/json'
apiurl='https://api.openai.com/v1/chat/completions'
prompt="ここに問い合わせしたい内容を記載。"
json='{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "'${prompt}'"}]}'

# API実行
curl ${apiurl} -sS -H "Authorization: Bearer ${OPENAI_API_KEY}" -H "${header}" -d "${json}"

実行結果は以下の通り。.choices[0].message.contentがAIの回答となる。

# curl ${apiurl} -sS -H "Authorization: Bearer ${OPENAI_API_KEY}" -H "${header}" -d "${json}"
{
  "id": "chatcmpl-xxxxxxxx",
  "object": "chat.completion",
  "created": 1723324974,
  "model": "gpt-4o-mini-2024-07-18",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "もちろんです!問い合わせ内容をお知らせいただければ、適切な回答やアドバイスをお伝えいたします。どのようなことについてお尋ねですか?",
        "refusal": null
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 17,
    "completion_tokens": 40,
    "total_tokens": 57
  },
  "system_fingerprint": "fp_48196bc67a"
}

2. スクリプト作成

curlによるOpenAI APIの実行方法を用いて、Zabbixの障害アラートを連携するスクリプトを以下の通り作成した。各環境に合わせて、OpenAIのAPI keyやZabbix API実行用のユーザとパスワードを設定すること。

障害アラートへのメッセージ追加はZabbix APIを使用する。Zabbix APIの使い方は、以下別記事を参考にしていただきたい。

また、OpenAI APIで同時に多数のリクエストを実行すると、応答がうまく得られずnullが返ってくる場合があったため、負荷分散を目的として、実行間隔制御の待機時間(最小10秒~最大120秒)を設定した。

send_chatgpt_api.sh

#!/bin/bash

# アラート内容を引数に代入
eventid=$1
alert=$(echo $2 | sed -e 's/"/\\"/g')

# 実行間隔制御 (10秒+ランダム時間)
sleep $(( 10 + ($RANDOM % 110) ))

# API keyを設定
export OPENAI_API_KEY='sk-********'

# モデルを選択
#model="gpt-3.5-turbo"
model="gpt-4o-mini"

header='Content-Type: application/json'
apiurl='https://api.openai.com/v1/chat/completions'
prompt="Zabbixで検知した以下イベントメッセージの原因及び解消方法を簡潔に教えてください。\n\n${alert}"
json='{"model": "'${model}'", "messages": [{"role": "user", "content": "'${prompt}'"}]}'

# API実行
result=$(curl ${apiurl} -sS -H "Authorization: Bearer ${OPENAI_API_KEY}" -H "${header}" -d "${json}")

# 出力
result_message=$(echo $result | jq -r '.choices[0].message.content')

# Zabbix APIログイン
header='Content-Type:application/json-rpc'
apiurl='http://[ZabbixサーバのURL]/zabbix/api_jsonrpc.php'
json='{"jsonrpc": "2.0","method": "user.login","params": {"username": "Admin","password": "********"},"id": 1,"auth": null}'
zbxauth=$(curl -sS -X POST -H "${header}" -d "${json}" ${apiurl} | jq -r ".result")

# Zabbix APIでイベントにメッセージ追加
json='{"jsonrpc": "2.0","method": "event.acknowledge","params": {"eventids": "'${eventid}'","action": 4,"message": "'$(echo ${result_message} | sed -e 's/"/\\"/g')'"},"auth": "'${zbxauth}'","id": 1}'
curl -sS -X POST -H "${header}" -d "${json}" ${apiurl} | jq

# Zabbix APIログオフ
json='{"jsonrpc": "2.0","method": "user.logout","params": [],"id": 4,"auth": "'$zbxauth'"}'
curl -sS -X POST -H "${header}" -d "${json}" ${apiurl} | jq

exit 0

3. スクリプトをZabbixサーバに配置

本スクリプトは、Zabbixサーバの/usr/local/binに配置し、実行権限を付与しておく。

# cp send_chatgpt_api.sh /usr/local/bin/
# chmod +x /usr/local/bin/send_chatgpt_api.sh
# ls -l /usr/local/bin/send_chatgpt_api.sh
-rwxr-xr-x 1 root root 1753  9月 23 07:41 /usr/local/bin/send_chatgpt_api.sh

実行方法は以下の通りとなる。

/usr/local/bin/send_chatgpt_api.sh '[イベントID]' '[アラート内容]'

Zabbixのトリガーアクションを設定

1. スクリプト設定

Zabbixのスクリプト設定を以下の通り行う。

設定項目 設定値
名前 Send ChatGPT
タイプ スクリプト
次で実行 Zabbixサーバー
コマンド /usr/local/bin/send_chatgpt_api.sh '{EVENT.ID}' '{ITEM.VALUE}'

2. トリガーアクション設定

Zabbixのトリガーアクション設定を以下の通り行う。今回は、「軽度の障害」以上の場合にスクリプトを実行するよう設定する。

設定項目 設定値
名前 Send ChatGPT
実行条件 「メンテナンス期間外」 AND 「トリガーの深刻度 以上 軽度の障害」

アクションの実行内容は以下の通り、先ほど作成したスクリプトを指定する。

設定項目 設定値
処理内容 Send ChatGPT
ターゲットリスト Zabbix server

動作確認

実際に障害アラートを発生させて、動作を確認してみよう。

例として、以下の障害アラートを発生させてみた。ポートチャネルPo1からgi3が除外されたアラートとなる。

SNMP Trap from t1250c250 : 2024/02/10 15:11:26. .1.3.6.1.4.1.9.6.1.101.0.161 
Normal General event UNKNOWN - %TRUNK-W-PORTREMOVED: Port gi3 removed from Po1 1

しばらくするとスクリプトが実行され、以下の通りOpenAI APIで取得した生成AIの回答がメッセージとして表示された。

このイベントメッセージの原因は、ポートgi3がPo1 1から削除されたことです。 
解決方法は、次のいずれかです。

  1. ネットワーク上でポートを再接続し、Po1 1にgi3を再度追加します。
  2. システムの設定を確認し、ポートが正しく構成されていることを確認します。
  3. 他のネットワークデバイスとの接続に問題がある場合は、接続を確認し、
     必要に応じて修正します。

これらの手順を実行することで、問題が解決する可能性があります。
ただし、具体的な状況に応じて解決方法が異なる場合もあるため、
詳細な情報があれば助かります。

以上で、OpenAI APIを使ってZabbixの障害アラートを生成AIに連携する手順は完了となる。

参考

更新履歴

  • 2023/9/23 新規作成
  • 2024/2/10 OpenAI APIに送るプロンプトを日本語に変更
  • 2024/6/24 send_chatgpt_api.shをZabbix 7.0に対応するように修正
  • 2024/8/11 生成AIモデルをgpt-3.5-turboからgpt-4o-miniに変更

人気の投稿