Class: Homebrew::Service

Inherits:
Object
  • Object
show all
Extended by:
Forwardable, T::Sig
Defined in:
service.rb

Overview

The Service class implements the DSL methods used in a formula’s service block and stores related instance variables. Most of these methods also return the related instance variable when no argument is provided.

Constant Summary collapse

RUN_TYPE_IMMEDIATE =
:immediate
RUN_TYPE_INTERVAL =
:interval
RUN_TYPE_CRON =
:cron
PROCESS_TYPE_BACKGROUND =
:background
PROCESS_TYPE_STANDARD =
:standard
PROCESS_TYPE_INTERACTIVE =
:interactive
PROCESS_TYPE_ADAPTIVE =
:adaptive
KEEP_ALIVE_KEYS =
[:always, :successful_exit, :crashed, :path].freeze

Instance Method Summary collapse

Constructor Details

#initialize(formula, &block) ⇒ Service

sig { params(formula: Formula).void }



24
25
26
27
28
29
# File 'service.rb', line 24

def initialize(formula, &block)
  @formula = formula
  @run_type = RUN_TYPE_IMMEDIATE
  @environment_variables = {}
  @service_block = block
end

Instance Method Details

#commandArray<String>

Returns:



305
306
307
308
# File 'service.rb', line 305

def command
  instance_eval(&@service_block)
  @run.map(&:to_s)
end

#cron(value = nil) ⇒ Hash?

Parameters:

  • value (String, nil) (defaults to: nil)

Returns:

  • (Hash, nil)


218
219
220
221
222
223
224
225
226
227
# File 'service.rb', line 218

def cron(value = nil)
  case T.unsafe(value)
  when nil
    @cron
  when String
    @cron = parse_cron(T.must(value))
  else
    raise TypeError, "Service#cron expects a String"
  end
end

#default_cron_valuesHash{Symbol => Integer, String}

Returns:



230
231
232
233
234
235
236
237
238
# File 'service.rb', line 230

def default_cron_values
  {
    Month:   "*",
    Day:     "*",
    Weekday: "*",
    Hour:    "*",
    Minute:  "*",
  }
end

#environment_variables(variables = {}) ⇒ Hash{String => String}?

Parameters:

Returns:



276
277
278
279
280
281
282
283
# File 'service.rb', line 276

def environment_variables(variables = {})
  case T.unsafe(variables)
  when Hash
    @environment_variables = variables.transform_values(&:to_s)
  else
    raise TypeError, "Service#environment_variables expects a hash"
  end
end

#error_log_path(path = nil) ⇒ String?

Parameters:

Returns:



94
95
96
97
98
99
100
101
102
103
# File 'service.rb', line 94

def error_log_path(path = nil)
  case T.unsafe(path)
  when nil
    @error_log_path
  when String, Pathname
    @error_log_path = path.to_s
  else
    raise TypeError, "Service#error_log_path expects a String"
  end
end

#input_path(path = nil) ⇒ String?

Parameters:

Returns:



70
71
72
73
74
75
76
77
78
79
# File 'service.rb', line 70

def input_path(path = nil)
  case T.unsafe(path)
  when nil
    @input_path
  when String, Pathname
    @input_path = path.to_s
  else
    raise TypeError, "Service#input_path expects a String or Pathname"
  end
end

#interval(value = nil) ⇒ Integer?

Parameters:

  • value (Integer, nil) (defaults to: nil)

Returns:

  • (Integer, nil)


206
207
208
209
210
211
212
213
214
215
# File 'service.rb', line 206

def interval(value = nil)
  case T.unsafe(value)
  when nil
    @interval
  when Integer
    @interval = value
  else
    raise TypeError, "Service#interval expects an Integer"
  end
end

#keep_alive(value = nil) ⇒ Hash{Symbol => T.untyped}?

Parameters:

  • value (Boolean, Hash{Symbol => T.untyped}, nil) (defaults to: nil)

Returns:

  • (Hash{Symbol => T.untyped}, nil)


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'service.rb', line 109

def keep_alive(value = nil)
  case T.unsafe(value)
  when nil
    @keep_alive
  when true, false
    @keep_alive = { always: value }
  when Hash
    hash = T.cast(value, Hash)
    unless (hash.keys - KEEP_ALIVE_KEYS).empty?
      raise TypeError, "Service#keep_alive allows only #{KEEP_ALIVE_KEYS}"
    end

    @keep_alive = value
  else
    raise TypeError, "Service#keep_alive expects a Boolean or Hash"
  end
end

#keep_alive?Boolean

Returns a Boolean describing if a service is set to be kept alive.

Returns:

  • (Boolean)


146
147
148
149
# File 'service.rb', line 146

def keep_alive?
  instance_eval(&@service_block)
  @keep_alive.present? && @keep_alive[:always] != false
end

#launch_only_once(value = nil) ⇒ Boolean?

Parameters:

  • value (Boolean, nil) (defaults to: nil)

Returns:

  • (Boolean, nil)


152
153
154
155
156
157
158
159
160
161
# File 'service.rb', line 152

def launch_only_once(value = nil)
  case T.unsafe(value)
  when nil
    @launch_only_once
  when true, false
    @launch_only_once = value
  else
    raise TypeError, "Service#launch_only_once expects a Boolean"
  end
end

#log_path(path = nil) ⇒ String?

Parameters:

Returns:



82
83
84
85
86
87
88
89
90
91
# File 'service.rb', line 82

def log_path(path = nil)
  case T.unsafe(path)
  when nil
    @log_path
  when String, Pathname
    @log_path = path.to_s
  else
    raise TypeError, "Service#log_path expects a String"
  end
end

#macos_legacy_timers(value = nil) ⇒ Boolean?

Parameters:

  • value (Boolean, nil) (defaults to: nil)

Returns:

  • (Boolean, nil)


286
287
288
289
290
291
292
293
294
295
# File 'service.rb', line 286

def macos_legacy_timers(value = nil)
  case T.unsafe(value)
  when nil
    @macos_legacy_timers
  when true, false
    @macos_legacy_timers = value
  else
    raise TypeError, "Service#macos_legacy_timers expects a Boolean"
  end
end

#manual_commandString

Returns the String command to run manually instead of the service.

Returns:



313
314
315
316
317
318
319
320
# File 'service.rb', line 313

def manual_command
  instance_eval(&@service_block)
  vars = @environment_variables.except(:PATH)
                               .map { |k, v| "#{k}=\"#{v}\"" }

  out = vars + command
  out.join(" ")
end

#parse_cron(cron_statement) ⇒ Hash{Symbol => Integer, String}

Parameters:

Returns:



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'service.rb', line 241

def parse_cron(cron_statement)
  parsed = default_cron_values

  case cron_statement
  when "@hourly"
    parsed[:Minute] = 0
  when "@daily"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
  when "@weekly"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
    parsed[:Weekday] = 0
  when "@monthly"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
    parsed[:Day] = 1
  when "@yearly", "@annually"
    parsed[:Minute] = 0
    parsed[:Hour] = 0
    parsed[:Day] = 1
    parsed[:Month] = 1
  else
    cron_parts = cron_statement.split
    raise TypeError, "Service#parse_cron expects a valid cron syntax" if cron_parts.length != 5

    [:Minute, :Hour, :Day, :Month, :Weekday].each_with_index do |selector, index|
      parsed[selector] = Integer(cron_parts.fetch(index)) if cron_parts.fetch(index) != "*"
    end
  end

  parsed
end

#process_type(value = nil) ⇒ Symbol?

Parameters:

  • value (Symbol, nil) (defaults to: nil)

Returns:



176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'service.rb', line 176

def process_type(value = nil)
  case T.unsafe(value)
  when nil
    @process_type
  when :background, :standard, :interactive, :adaptive
    @process_type = value
  when Symbol
    raise TypeError, "Service#process_type allows: "\
                     "'#{PROCESS_TYPE_BACKGROUND}'/'#{PROCESS_TYPE_STANDARD}'/"\
                     "'#{PROCESS_TYPE_INTERACTIVE}'/'#{PROCESS_TYPE_ADAPTIVE}'"
  else
    raise TypeError, "Service#process_type expects a Symbol"
  end
end

#restart_delay(value = nil) ⇒ Integer?

Parameters:

  • value (Integer, nil) (defaults to: nil)

Returns:

  • (Integer, nil)


164
165
166
167
168
169
170
171
172
173
# File 'service.rb', line 164

def restart_delay(value = nil)
  case T.unsafe(value)
  when nil
    @restart_delay
  when Integer
    @restart_delay = value
  else
    raise TypeError, "Service#restart_delay expects an Integer"
  end
end

#root_dir(path = nil) ⇒ String?

Parameters:

Returns:



58
59
60
61
62
63
64
65
66
67
# File 'service.rb', line 58

def root_dir(path = nil)
  case T.unsafe(path)
  when nil
    @root_dir
  when String, Pathname
    @root_dir = path.to_s
  else
    raise TypeError, "Service#root_dir expects a String or Pathname"
  end
end

#run(command = nil) ⇒ Array?

Parameters:

Returns:

  • (Array, nil)


32
33
34
35
36
37
38
39
40
41
42
43
# File 'service.rb', line 32

def run(command = nil)
  case T.unsafe(command)
  when nil
    @run
  when String, Pathname
    @run = [command]
  when Array
    @run = command
  else
    raise TypeError, "Service#run expects an Array"
  end
end

#run_type(value = nil) ⇒ Symbol?

Parameters:

  • value (Symbol, nil) (defaults to: nil)

Returns:



192
193
194
195
196
197
198
199
200
201
202
203
# File 'service.rb', line 192

def run_type(value = nil)
  case T.unsafe(value)
  when nil
    @run_type
  when :immediate, :interval, :cron
    @run_type = value
  when Symbol
    raise TypeError, "Service#run_type allows: '#{RUN_TYPE_IMMEDIATE}'/'#{RUN_TYPE_INTERVAL}'/'#{RUN_TYPE_CRON}'"
  else
    raise TypeError, "Service#run_type expects a Symbol"
  end
end

#sockets(value = nil) ⇒ Hash{Symbol => String}?

Parameters:

  • value (String, nil) (defaults to: nil)

Returns:



128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'service.rb', line 128

def sockets(value = nil)
  case T.unsafe(value)
  when nil
    @sockets
  when String
    match = T.must(value).match(%r{([a-z]+)://([a-z0-9.]+):([0-9]+)}i)
    raise TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" if match.blank?

    type, host, port = match.captures
    @sockets = { host: host, port: port, type: type }
  else
    raise TypeError, "Service#sockets expects a String"
  end
end

#std_service_path_envString

Returns:



300
301
302
# File 'service.rb', line 300

def std_service_path_env
  "#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
end

#timed?Boolean

Returns a Boolean describing if a service is timed.

Returns:

  • (Boolean)


325
326
327
328
# File 'service.rb', line 325

def timed?
  instance_eval(&@service_block)
  @run_type == RUN_TYPE_CRON || @run_type == RUN_TYPE_INTERVAL
end

#to_plistString

Returns a String plist.

Returns:



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'service.rb', line 333

def to_plist
  # command needs to be first because it initializes all other values
  base = {
    Label:            @formula.plist_name,
    ProgramArguments: command,
    RunAtLoad:        @run_type == RUN_TYPE_IMMEDIATE,
  }

  base[:LaunchOnlyOnce] = @launch_only_once if @launch_only_once == true
  base[:LegacyTimers] = @macos_legacy_timers if @macos_legacy_timers == true
  base[:TimeOut] = @restart_delay if @restart_delay.present?
  base[:ProcessType] = @process_type.to_s.capitalize if @process_type.present?
  base[:StartInterval] = @interval if @interval.present? && @run_type == RUN_TYPE_INTERVAL
  base[:WorkingDirectory] = @working_dir if @working_dir.present?
  base[:RootDirectory] = @root_dir if @root_dir.present?
  base[:StandardInPath] = @input_path if @input_path.present?
  base[:StandardOutPath] = @log_path if @log_path.present?
  base[:StandardErrorPath] = @error_log_path if @error_log_path.present?
  base[:EnvironmentVariables] = @environment_variables unless @environment_variables.empty?

  if keep_alive?
    if (always = @keep_alive[:always].presence)
      base[:KeepAlive] = always
    elsif @keep_alive.key?(:successful_exit)
      base[:KeepAlive] = { SuccessfulExit: @keep_alive[:successful_exit] }
    elsif @keep_alive.key?(:crashed)
      base[:KeepAlive] = { Crashed: @keep_alive[:crashed] }
    elsif @keep_alive.key?(:path) && @keep_alive[:path].present?
      base[:KeepAlive] = { PathState: @keep_alive[:path].to_s }
    end
  end

  if @sockets.present?
    base[:Sockets] = {}
    base[:Sockets][:Listeners] = {
      SockNodeName:    @sockets[:host],
      SockServiceName: @sockets[:port],
      SockProtocol:    @sockets[:type].upcase,
      SockFamily:      "IPv4v6",
    }
  end

  if @cron.present? && @run_type == RUN_TYPE_CRON
    base[:StartCalendarInterval] = @cron.reject { |_, value| value == "*" }
  end

  base.to_plist
end

#to_systemd_timerString

Returns a String systemd unit timer.

Returns:



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'service.rb', line 418

def to_systemd_timer
  timer = <<~EOS
    [Unit]
    Description=Homebrew generated timer for #{@formula.name}

    [Install]
    WantedBy=timers.target

    [Timer]
    Unit=#{@formula.service_name}
  EOS

  instance_eval(&@service_block)
  options = []
  options << "Persistent=true" if @run_type == RUN_TYPE_CRON
  options << "OnUnitActiveSec=#{@interval}" if @run_type == RUN_TYPE_INTERVAL

  if @run_type == RUN_TYPE_CRON
    minutes = @cron[:Minute] == "*" ? "*" : format("%02d", @cron[:Minute])
    hours   = @cron[:Hour] == "*" ? "*" : format("%02d", @cron[:Hour])
    options << "OnCalendar=#{@cron[:Weekday]}-*-#{@cron[:Month]}-#{@cron[:Day]} #{hours}:#{minutes}:00"
  end

  timer + options.join("\n")
end

#to_systemd_unitString

Returns a String systemd unit.

Returns:



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'service.rb', line 385

def to_systemd_unit
  unit = <<~EOS
    [Unit]
    Description=Homebrew generated unit for #{@formula.name}

    [Install]
    WantedBy=multi-user.target

    [Service]
  EOS

  # command needs to be first because it initializes all other values
  cmd = command.join(" ")

  options = []
  options << "Type=#{@launch_only_once == true ? "oneshot" : "simple"}"
  options << "ExecStart=#{cmd}"

  options << "Restart=always" if @keep_alive.present? && @keep_alive[:always].present?
  options << "RestartSec=#{restart_delay}" if @restart_delay.present?
  options << "WorkingDirectory=#{@working_dir}" if @working_dir.present?
  options << "RootDirectory=#{@root_dir}" if @root_dir.present?
  options << "StandardInput=file:#{@input_path}" if @input_path.present?
  options << "StandardOutput=append:#{@log_path}" if @log_path.present?
  options << "StandardError=append:#{@error_log_path}" if @error_log_path.present?
  options += @environment_variables.map { |k, v| "Environment=\"#{k}=#{v}\"" } if @environment_variables.present?

  unit + options.join("\n")
end

#working_dir(path = nil) ⇒ String?

Parameters:

Returns:



46
47
48
49
50
51
52
53
54
55
# File 'service.rb', line 46

def working_dir(path = nil)
  case T.unsafe(path)
  when nil
    @working_dir
  when String, Pathname
    @working_dir = path.to_s
  else
    raise TypeError, "Service#working_dir expects a String"
  end
end