You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
3.0 KiB

const { Injectable } = require('flitter-di')
class ServiceConfig extends Injectable {
static get services() {
return [...super.services, 'utility']
}
_data = {
after: ['syslog.target', 'network.target'],
type: 'simple',
restart: 'always',
restart_after: '2s',
install_to: 'multi-user.target',
}
name(set) { return this._get_or_set('name', set) }
description(set) { return this._get_or_set('description', set) }
after(set) { return this._get_or_set('after', set, true) }
restart(set) { return this._get_or_set('restart', set) }
restart_after(set) { return this._get_or_set('restart_after', set) }
type(set) { return this._get_or_set('type', set) }
user(set) { return this._get_or_set('user', set) }
group(set) { return this._get_or_set('group', set) }
directory(set) { return this._get_or_set('directory', set) }
execute(set) { return this._get_or_set('execute', set) }
env(set) { return this._get_or_set('env', set) }
install_to(set) { return this._get_or_set('install_to', set) }
_export() {
return this.utility.deep_copy(this._data)
}
_build() {
this._validate()
const lines = []
lines.push('[Unit]')
if ( this.description() ) lines.push(`Description=${this.description()}`)
if ( this.after() ) {
for ( const item of this.after() ) {
lines.push(`After=${item}`)
}
}
lines.push('\n[Service]')
if ( this.restart() ) {
lines.push(`Restart=${this.restart()}`)
if ( this.restart_after() ) {
lines.push(`RestartSec=${this.restart_after()}`)
}
}
if ( this.user() ) {
lines.push(`User=${this.user()}`)
}
if ( this.group() ) {
lines.push(`Group=${this.group()}`)
}
if ( this.directory() ) {
lines.push(`WorkingDirectory=${this.directory()}`)
}
if ( this.execute() ) {
lines.push(`ExecStart=${this.execute()}`)
}
if ( this.env() ) {
lines.push(`Environment=${this.env()}`)
}
if ( this.install_to() ) {
lines.push('\n[Install]')
lines.push(`WantedBy=${this.install_to()}`)
}
return lines.join('\n')
}
_validate() {
const required_fields = ['name', 'description', 'after', 'type', 'user', 'group', 'directory', 'execute']
for ( const field of required_fields ) {
if ( !this[field]() ) throw new Error(`Missing required service config field: ${field}`)
}
}
_get_or_set(field, value, arr = false) {
if ( value ) {
if ( arr ) {
if ( !this._data[field] ) this._data[field] = []
this._data[field].push(value)
} else this._data[field] = value
return this
}
return this._data[field]
}
}
module.exports = exports = ServiceConfig