From a1c091bc7f8b6d1a8d28b47d8cf22068608051ef Mon Sep 17 00:00:00 2001
From: Simon Backx <simonbbackx@gmail.com>
Date: Sun, 7 Jun 2020 20:51:47 +0200
Subject: [PATCH] Added LimitNOFILE option in systemd configuration (#94)

Co-authored-by: Daniel Theophanes <kardianos@gmail.com>
---
 service.go               | 5 +++++
 service_systemd_linux.go | 3 +++
 2 files changed, 8 insertions(+)

diff --git a/service.go b/service.go
index 94f271e4..7040a602 100644
--- a/service.go
+++ b/service.go
@@ -83,6 +83,8 @@ const (
 	optionRunWait      = "RunWait"
 	optionReloadSignal = "ReloadSignal"
 	optionPIDFile      = "PIDFile"
+	optionLimitNOFILE        = "LimitNOFILE"
+	optionLimitNOFILEDefault = -1 // -1 = don't set in configuration
 	optionRestart      = "Restart"
 
 	optionSuccessExitStatus = "SuccessExitStatus"
@@ -147,6 +149,9 @@ type Config struct {
 	//    - Restart       string (always)           - How shall service be restarted.
 	//    - SuccessExitStatus string ()             - The list of exit status that shall be considered as successful,
 	//                                                in addition to the default ones.
+	//  * Linux (systemd)
+	//    - LimitNOFILE	 int - Maximum open files (ulimit -n) (https://serverfault.com/questions/628610/increasing-nproc-for-processes-launched-by-systemd-on-centos-7)
+
 	Option KeyValue
 }
 
diff --git a/service_systemd_linux.go b/service_systemd_linux.go
index 88cbf9f0..3ce78bf5 100644
--- a/service_systemd_linux.go
+++ b/service_systemd_linux.go
@@ -156,6 +156,7 @@ func (s *systemd) Install() error {
 		HasOutputFileSupport bool
 		ReloadSignal         string
 		PIDFile              string
+		LimitNOFILE          int
 		Restart              string
 		SuccessExitStatus    string
 		LogOutput            bool
@@ -165,6 +166,7 @@ func (s *systemd) Install() error {
 		s.hasOutputFileSupport(),
 		s.Option.string(optionReloadSignal, ""),
 		s.Option.string(optionPIDFile, ""),
+		s.Option.int(optionLimitNOFILE, optionLimitNOFILEDefault),
 		s.Option.string(optionRestart, "always"),
 		s.Option.string(optionSuccessExitStatus, ""),
 		s.Option.bool(optionLogOutput, optionLogOutputDefault),
@@ -288,6 +290,7 @@ ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
 StandardOutput=file:/var/log/{{.Name}}.out
 StandardError=file:/var/log/{{.Name}}.err
 {{- end}}
+{{if gt .LimitNOFILE -1 }}LimitNOFILE={{.LimitNOFILE}}{{end}}
 {{if .Restart}}Restart={{.Restart}}{{end}}
 {{if .SuccessExitStatus}}SuccessExitStatus={{.SuccessExitStatus}}{{end}}
 RestartSec=120