Class: Homebrew::Service

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
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:



310
311
312
313
# File 'service.rb', line 310

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)


223
224
225
226
227
228
229
230
231
232
# File 'service.rb', line 223

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:



235
236
237
238
239
240
241
242
243
# File 'service.rb', line 235

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

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

Parameters:

Returns:



281
282
283
284
285
286
287
288
# File 'service.rb', line 281

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:



99
100
101
102
103
104
105
106
107
108
# File 'service.rb', line 99

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

#fFormula

Returns:



32
33
34
# File 'service.rb', line 32

def f
  @formula
end

#input_path(path = nil) ⇒ String?

Parameters:

Returns:



75
76
77
78
79
80
81
82
83
84
# File 'service.rb', line 75

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)


211
212
213
214
215
216
217
218
219
220
# File 'service.rb', line 211

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)


114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'service.rb', line 114

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)


151
152
153
154
# File 'service.rb', line 151

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)


157
158
159
160
161
162
163
164
165
166
# File 'service.rb', line 157

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:



87
88
89
90
91
92
93
94
95
96
# File 'service.rb', line 87

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)


291
292
293
294
295
296
297
298
299
300
# File 'service.rb', line 291

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:



318
319
320
321
322
323
324
325
# File 'service.rb', line 318

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:



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
274
275
276
277
278
# File 'service.rb', line 246

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:



181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'service.rb', line 181

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)


169
170
171
172
173
174
175
176
177
178
# File 'service.rb', line 169

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:



63
64
65
66
67
68
69
70
71
72
# File 'service.rb', line 63

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)


37
38
39
40
41
42
43
44
45
46
47
48
# File 'service.rb', line 37

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:



197
198
199
200
201
202
203
204
205
206
207
208
# File 'service.rb', line 197

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:



133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'service.rb', line 133

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:



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

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)


330
331
332
333
# File 'service.rb', line 330

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

#to_plistString

Returns a String plist.

Returns:



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
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'service.rb', line 338

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

  # Adding all session types has as the primary effect that if you initialise it through e.g. a Background session
  # and you later "physically" sign in to the owning account (Aqua session), things shouldn't flip out.
  # Also, we're not checking @process_type here because that is used to indicate process priority and not
  # necessarily if it should run in a specific session type. Like database services could run with ProcessType
  # Interactive so they have no resource limitations enforced upon them, but they aren't really interactive in the
  # general sense.
  base[:LimitLoadToSessionType] = %w[Aqua Background LoginWindow StandardIO System]

  base.to_plist
end

#to_systemd_timerString

Returns a String systemd unit timer.

Returns:



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'service.rb', line 431

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:



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'service.rb', line 398

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:



51
52
53
54
55
56
57
58
59
60
# File 'service.rb', line 51

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