備忘録 Tomcatのサービス起動をchefで作成してみた

[備忘録 CentOS7, Tomcat8.5.11をsystemctlコマンドで起動/停止したい](http://qiita.com/brighton0725/items/532a4d1f6a647e7f85cf)と頑張ってみたので、今度はserviceファイルをchefで作成してみました。


# 最初はtempalteリソースを使用してやっていた！

```ruby:当初の環境
 (Chef Server) OS: REHL 7.2 , Chef Server:12.6.0.1
 (Chef Client) OS: CentOS 7.2 , Chef Client:chef-12.10.24-1 , Tomcat:8.5.11
```
芸がないというか、なんというか。
最初にやっていたやり方は以下のとおり。

### 1. レシピを作成
とりあえず、templateファイルからserviceファイルを作成するレシピを作成してみた。
templatesにサービスファイルを置いておいて、そこから/etc/systemd/systemに送りつける。
そして、bashコマンドでsystemctlコマンドを実行するという。

```ruby:crt_service.rb
# create tomcat.service file
svc_file = File.join(node['tomcat']['systemd_dir'],node['tomcat']['service_file'])
template " create #{node['tomcat']['service_file']} " do
    source "#{node['tomcat']['service_file']}.erb"
    path "#{svc_file}"
    mode '0644'
    action :create
end

# enable tomcat.service
bash " systemctl enable #{node['tomcat']['service_file']} " do
    code <<-EOH
    systemctl disable #{node['tomcat']['service_file']}
    systemctl enable #{node['tomcat']['service_file']}
    EOH
    action :run
end
```

### 2. templateファイルの作成
cookbook名/templates/defaultに以下のようなファイルを作成。

```ruby:tomcat.service.erb
[Unit]
Description=<%=node['tomcat']['description']%>
After=<%=node['tomcat']['after']%>

[Service]
User=<%=node['tomcat']['user']%>
Group=<%=node['tomcat']['group']%>
Type=<%=node['tomcat']['type']%>

ExecStart=<%=node['tomcat']['execstart']%>
ExecStop=<%=node['tomcat']['execstop']%>
RemainAfterExit=yes

[Install]
WantedBy=<%=node['tomcat']['wantedby']%>
```
### 3. attributesファイルの作成
変数の中身は、attributesのdefault.rbに書いておく。

```ruby:default.rb
default['tomcat']['user'] = 'tomcat'
default['tomcat']['group'] = 'tomcat'

# set tomcat.service
default['tomcat']['systemd_dir'] = '/etc/systemd/system'
default['tomcat']['service_file'] = 'tomcat.service'

## Unit
default['tomcat']['description'] = default['tomcat']['prd_dir_name']
default['tomcat']['after'] = 'network.target remote-fs.target nss-lookup.target'
## Service
#default['tomcat']['user'] = 'tomcat'
#default['tomcat']['group'] = 'tomcat'
default['tomcat']['type'] = 'oneshot'
default['tomcat']['start'] = 'startup.sh'
default['tomcat']['stop'] = 'shutdown.sh'
default['tomcat']['execstart'] = File.join(default['tomcat']['prd_home'],"bin",default['tomcat']['start'])
default['tomcat']['execstop'] = File.join(default['tomcat']['prd_home'],"bin",default['tomcat']['stop'])
## Install
default['tomcat']['wantedby'] = 'multi-user.target'
```

### 4. レシピを実行してみる
ファイルも無事できて、サービスも実行されているようですね～

```ruby:
[root@test00 recipes]# knife ssh name:test01 "chef-client -o recipe[tomcat::crt_service]" -x root
root@test01's password:
test01 Starting Chef Client, version 12.10.24-1
test01 [2017-04-07T13:43:26+09:00] WARN: Run List override has been provided.
test01 [2017-04-07T13:43:26+09:00] WARN: Original Run List: [recipe[user]]
test01 [2017-04-07T13:43:26+09:00] WARN: Overridden Run List: [recipe[tomcat::crt_service]]
test01 resolving cookbooks for run list: ["tomcat::crt_service"]
test01 Synchronizing Cookbooks:
test01   - tomcat (0.1.0)
test01 Installing Cookbook Gems:
test01 Compiling Cookbooks...
test01 Converging 2 resources
test01 Recipe: tomcat::crt_service
test01   * template[ create tomcat.service ] action create
test01     - create new file /etc/systemd/system/tomcat.service
test01     - update content in file /etc/systemd/system/tomcat.service from none to becd83
test01     --- /etc/systemd/system/tomcat.service  2017-04-07 13:43:27.124318984 +0900
test01     +++ /etc/systemd/system/.chef-tomcat20170407-3360-1a9o4el.service       2017-04-07 13:43:27.123318975 +0900
test01     @@ -1 +1,17 @@
test01     +[Unit]
test01     +Description=apache-tomcat-8.5.12
test01     +After=network.target remote-fs.target nss-lookup.target
test01     +
test01     +[Service]
test01     +User=tomcat
test01     +Group=tomcat
test01     +Type=oneshot
test01     +
test01     +ExecStart=/usr/local/apache-tomcat-8.5.12/bin/startup.sh
test01     +ExecStop=/usr/local/apache-tomcat-8.5.12/bin/shutdown.sh
test01     +RemainAfterExit=yes
test01     +
test01     +[Install]
test01     +WantedBy=multi-user.target
test01     +
test01     - change mode from '' to '0644'
test01   * bash[ systemctl enable tomcat.service ] action run
test01     - execute "bash"  "/tmp/chef-script20170407-3360-mpr7ud"
test01 [2017-04-07T13:43:27+09:00] WARN: Skipping final node save because override_runlist was given
test01
test01 Running handlers:
test01 Running handlers complete
test01 Chef Client finished, 2/2 resources updated in 03 seconds
```

### 5.確認してみる

確認してみた。うまくいったようだ。

```ruby:
[root@test01 system]# systemctl start tomcat
[root@test01 system]# ps -ef |grep tomcat
tomcat    2917     1  0 11:13 ?        00:00:21 /usr/bin/java -Djava.util.logging.config.file=/usr/local/apache-tomcat-8.5.12/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -classpath /usr/local/apache-tomcat-8.5.12/bin/bootstrap.jar:/usr/local/apache-tomcat-8.5.12/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/apache-tomcat-8.5.12 -Dcatalina.home=/usr/local/apache-tomcat-8.5.12 -Djava.io.tmpdir=/usr/local/apache-tomcat-8.5.12/temp org.apache.catalina.startup.Bootstrap start
root      3665  2476  0 13:45 pts/0    00:00:00 grep --color=auto tomcat
```


だが、ださい。。。。

調べてみると、chefクライアントのバージョンをあげると、[systemd_unit](https://docs.chef.io/resource_systemd_unit.html)リソースを使えば、こんなことはしないでもよいみたいだ。

# なので、環境を変えてテストをしてみる！

```ruby:今回の環境
 (Chef Client) OS: CentOS 7.3 , Chef Client:chef-12.18.31, Tomcat:8.5.12
```

### 1.レシピを作成

systemd_unitを利用して、レシピを書いてみる。
systemd_unitのリソース内で、そのまま必要事項を記述する感じですね。

```ruby:crt_service.rb
systemd_unit "#{node['tomcat']['svc_name']}" do
    content <<-EOU.gsub(/^\s+/, '')

    [Unit]
    Description=#{node['tomcat']['prd_dir_name']}
    After=#{node['tomcat']['after']}

    [Service]
    User=#{node['tomcat']['user']}
    Group=#{node['tomcat']['group']}
    Type=#{node['tomcat']['type']}

    ExecStart=#{node['tomcat']['execstart']}
    ExecStop=#{node['tomcat']['execstop']}
    RemainAfterExit=#{node['tomcat']['remain']}

    [Install]
    WantedBy=#{node['tomcat']['wantedby']}

    EOU
    action [:create, :enable]
end
```
### 2.attributeファイルの作成

```ruby:qiita.rb
# set tomcat.service
default['tomcat']['svc_name'] = 'tomcat.service'

## Unit
default['tomcat']['description'] = default['tomcat']['prd_dir_name']
default['tomcat']['after'] = 'network.target remote-fs.target nss-lookup.target'
## Service
default['tomcat']['user'] = 'tomcat'    
default['tomcat']['group'] = 'tomcat'  
default['tomcat']['type'] = 'oneshot'
default['tomcat']['pidfile'] = File.join(default['tomcat']['prd_home'],"conf","tomcat.pid")
default['tomcat']['start'] = 'startup.sh'
default['tomcat']['stop'] = 'shutdown.sh'
#default['tomcat']['killmode'] = 'none'
default['tomcat']['execstart'] = File.join(default['tomcat']['prd_home'],"bin",default['tomcat']['start'])
default['tomcat']['execstop'] = File.join(default['tomcat']['prd_home'],"bin",default['tomcat']['stop'])
default['tomcat']['remain'] = 'yes'
## Install
default['tomcat']['wantedby'] = 'multi-user.target'
```

これで終わり。あとは実行のみ。

###3.レシピを実行

```ruby:
[chef@test01 ~]$ sudo chef-solo -c /home/chef/chef-repo/solo.rb -o "recipe[tomcat::crt_service]"
Starting Chef Client, version 12.18.31
[2017-04-07T13:17:41+09:00] WARN: Run List override has been provided.
[2017-04-07T13:17:41+09:00] WARN: Original Run List: []
[2017-04-07T13:17:41+09:00] WARN: Overridden Run List: [recipe[tomcat::crt_service]]
resolving cookbooks for run list: ["tomcat::crt_service"]
[2017-04-07T13:17:41+09:00] WARN: Cookbook 'local-mode-cache' is empty or entirely chefignored at /home/chef/chef-repo/site-cookbooks/local-mode-cache
Synchronizing Cookbooks:
  - tomcat (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: tomcat::crt_service
  * systemd_unit[tomcat.service] action create                           
  Recipe: <Dynamically Defined Resource>
    * file[/etc/systemd/system/tomcat.service] action create
      - create new file /etc/systemd/system/tomcat.service
      - update content in file /etc/systemd/system/tomcat.service from none to 98a2ef
      --- /etc/systemd/system/tomcat.service    2017-04-07 13:17:42.027250932 +0900
      +++ /etc/systemd/system/.chef-tomcat20170407-10867-1xcpwum.service        2017-04-07 13:17:42.027250932 +0900
      @@ -1 +1,13 @@
      +[Unit]
      +Description=apache-tomcat-8.5.12
      +After=network.target remote-fs.target nss-lookup.target
      +[Service]
      +User=tomcat
      +Group=tomcat
      +Type=oneshot
      +ExecStart=/usr/local/apache-tomcat-8.5.12/bin/startup.sh
      +ExecStop=/usr/local/apache-tomcat-8.5.12/bin/shutdown.sh
      +RemainAfterExit=yes
      +[Install]
      +WantedBy=multi-user.target
      - change mode from '' to '0644'
      - change owner from '' to 'root'
      - change group from '' to 'root'
    - creating unit: tomcat.service
Recipe: tomcat::crt_service
  * systemd_unit[tomcat.service] action enable                          
    - enabling unit: tomcat.service
[2017-04-07T13:17:42+09:00] WARN: Skipping final node save because override_runlist was given

Running handlers:
Running handlers complete
Chef Client finished, 3/3 resources updated in 07 seconds
```

あっというまに完成!

### 4.実際に実行

起動してみるぞ

```ruby:
[tomcat@test01 ~]$ sudo systemctl start tomcat
[sudo] password for tomcat:
```

起動したぞ。

```ruby:
[tomcat@test01 ~]$ ps -ef | grep tom
root     13638  2807  0 13:57 pts/1    00:00:00 su - tomcat
tomcat   13639 13638  0 13:57 pts/1    00:00:00 -bash
tomcat   13680     1 77 13:57 ?        00:00:03 /usr/bin/java -Djava.util.logging.config.file=/usr/local/apache-tomcat-8.5.12/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -classpath /usr/local/apache-tomcat-8.5.12/bin/bootstrap.jar:/usr/local/apache-tomcat-8.5.12/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/apache-tomcat-8.5.12 -Dcatalina.home=/usr/local/apache-tomcat-8.5.12 -Djava.io.tmpdir=/usr/local/apache-tomcat-8.5.12/temp org.apache.catalina.startup.Bootstrap start
tomcat   13696 13639  0 13:57 pts/1    00:00:00 ps -ef
tomcat   13697 13639  0 13:57 pts/1    00:00:00 grep --color=auto tom
[tomcat@sistest01 ~]$ sudo systemctl status tomcat
● tomcat.service - apache-tomcat-8.5.12
   Loaded: loaded (/etc/systemd/system/tomcat.service; enabled; vendor preset: disabled)
   Active: active (exited) since Fri 2017-04-07 13:57:46 JST; 9s ago
  Process: 13666 ExecStart=/usr/local/apache-tomcat-8.5.12/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 13666 (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/tomcat.service
           └─13680 /usr/bin/java -Djava.util.logging.config.file=/usr/local/apache-tomcat-8.5.12/conf/logging.properties -Djava.util.logging.man...

Apr 07 13:57:46 test01.com systemd[1]: Starting apache-tomcat-8.5.12...
Apr 07 13:57:46 test01.com systemd[1]: Started apache-tomcat-8.5.12.
```

停止してみるか。

```ruby:
[tomcat@test01 ~]$ sudo systemctl stop tomcat
[tomcat@test01 ~]$
```

停止も確認するか。

```ruby:
[tomcat@test01 ~]$ ps -ef | grep tom
root     13638  2807  0 13:57 pts/1    00:00:00 su - tomcat
tomcat   13639 13638  0 13:57 pts/1    00:00:00 -bash
tomcat   13915 13639  0 14:00 pts/1    00:00:00 ps -ef
tomcat   13916 13639  0 14:00 pts/1    00:00:00 grep --color=auto tom
[tomcat@test01 ~]$ sudo systemctl status tomcat
● tomcat.service - apache-tomcat-8.5.12
   Loaded: loaded (/etc/systemd/system/tomcat.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Fri 2017-04-07 14:00:00 JST; 33s ago
  Process: 13825 ExecStop=/usr/local/apache-tomcat-8.5.12/bin/shutdown.sh (code=exited, status=0/SUCCESS)
  Process: 13666 ExecStart=/usr/local/apache-tomcat-8.5.12/bin/startup.sh (code=exited, status=0/SUCCESS)
 Main PID: 13666 (code=exited, status=0/SUCCESS)

Apr 07 13:57:46 sistest01.sis.tvc.com systemd[1]: Starting apache-tomcat-8.5.12...
Apr 07 13:57:46 sistest01.sis.tvc.com systemd[1]: Started apache-tomcat-8.5.12.
Apr 07 13:59:59 sistest01.sis.tvc.com systemd[1]: Stopping apache-tomcat-8.5.12...
Apr 07 14:00:00 sistest01.sis.tvc.com systemd[1]: Stopped apache-tomcat-8.5.12.
[tomcat@test01 ~]$
```

うまくいった。
標準のリソースをできるだけ使おうと、強く思う日でした。


# 参考
[Chef manlual systmd_unit](https://docs.chef.io/resource_systemd_unit.html)