-
Notifications
You must be signed in to change notification settings - Fork 12
/
services_manager_service.rb
663 lines (576 loc) · 20.6 KB
/
services_manager_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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
381
382
383
384
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
414
415
416
417
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# encoding: utf-8
# Copyright (c) [2014-2018] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.
require "yast"
require "yast2/systemctl"
require "yast2/system_service"
require "services-manager/service_loader"
module Yast
import "Mode"
import "Service"
import "ServicesProposal"
import "Stage"
class ServicesManagerServiceClass < Module
include Yast::Logger
extend Yast::I18n
START_MODE = {
on_boot: N_('On Boot'),
on_demand: N_('On Demand'),
manual: N_('Manually')
}.freeze
# @!attribute [w] modified
# @note Used by AutoYaST.
# @return [Boolean] Whether the module has been modified
attr_writer :modified
# @return [Hash{String => Yast2::SystemService}]
def services
read if @services.nil?
@services
end
attr_reader :errors
attr_writer :services
alias_method :all, :services
def initialize
textdomain 'services-manager'
@modified = false
@errors = []
end
# Finds a service
#
# @param name [String] service name
# @return [Yast2::SystemService, nil]
def find(name)
return services[name] unless Stage.initial || Mode.auto
# In inst-sys we cannot check for installed services but generate entries for these
# services if they do not exist yet. The same applies to AutoYaST when a service might be
# installed as part of the software selection.
services[name] = Yast2::SystemService.build(name)
end
# Sets whether service should be running after writing the configuration
#
# @param name [String] service name
# @return [Boolean] whether the service exists
def activate(name)
exists?(name) do |service|
service.start
log.info "Service #{name} has been marked for activation"
true
end
end
# Sets whether service should be running after writing the configuration
#
# @param name [String] service name
# @return [Boolean] whether the service exists
def deactivate(name)
exists?(name) do |service|
service.stop
log.info "Service #{name} has been marked for de-activation"
true
end
end
# @param name [String] service name
# @return [Boolean] the current setting whether service should be running
def active(name)
exists?(name, &:active?)
end
alias_method :active?, :active
# @param name [String] service name
# @param key [Symbol] value that has been changed (:active and :start_mode)
# @return [Boolean] true if the key has changed
def changed_value?(name, key)
exists?(name) { |s| s.changed?(key) }
end
# Returns whether the given service has been enabled
#
# @param name [String] service name
# @return Boolean enabled
def enabled(name)
exists?(name) { |s| s.start_mode != :manual }
end
# Enables a given service (in memory only, use {#save} later)
#
# @param name [String] service name
def enable(name)
set_start_mode(name, :on_boot)
end
# Disables a given service (in memory only, use {#save} later)
#
# @param name [String] service name
def disable(name)
set_start_mode(name, :manual)
end
# Service state
#
# @param name [String] service name
# @return [String, false] false if the service does not exist
def state(name)
exists?(name, &:state)
end
# Service substate
#
# @param name [String] service name
# @return [String, false] false if the service does not exist
def substate(name)
exists?(name, &:substate)
end
# Service description
#
# @param name [String] service name
# @return [String, false] false if the service does not exist
def description(name)
exists?(name, &:description)
end
# Returns services which have been modified (in memory)
#
# @return [Array<Yast2::SystemService>] List of modified services
def modified_services
services.values.select { |s| s.found? && s.changed? }
end
# Returns services which are not available in the underlying system
#
# @return [Array<Yast2::SystemService>] List of not found services
def missing_services
services.values.reject(&:found?)
end
# Reloads the service list
#
# @return [Hash{String => Yast2::SystemService}]
# @see #read
def reload
@services = nil
read
end
# Reads all services' data
#
# @note When running AutoYaST, system services will not be read as the relevant services
# will be imported later.
#
# @return [Hash{String => Yast2::SystemService}]
def read
return @services if @services
@services = Mode.auto ? {} : Y2ServicesManager::ServiceLoader.new.read
end
# Resets the global status of the object
#
# @return [Boolean]
def reset
services.values.each(&:reset)
true
end
# Returns services to be exported to AutoYast profile
#
# FIXME: should be checked (and decided what to do if so) if service is marked to be exported as
# both, enabled or disabled
#
# @param target [Symbol] Control how much information should be exported
# (e.g., :default or :compact).
# @return [Hash{String => Array<String>}] profile data
def export(target: :default)
exportable_services = select_exportable_services(target == :compact)
on_boot_srvs = exportable_on_boot_services(exportable_services)
on_demand_srvs = exportable_on_demand_services(exportable_services)
disabled_srvs = exportable_disabled_services(exportable_services)
log.info "Exported services: on boot: #{on_boot_srvs}; on-demand: #{on_demand_srvs}; " \
"disabled: #{disabled_srvs}"
exported = {
"enable" => on_boot_srvs, "on_demand" => on_demand_srvs, "disable" => disabled_srvs
}
exported.reject { |_k, v| v.empty? }
end
# Selects which services should be exported
#
# @param changed_preset [Boolean] Consider only those services which start mode is not the preset
# @return [Hash{String => Array<String>}] profile data
def select_exportable_services(changed_preset)
exportable_services = services.keys
return exportable_services unless changed_preset
exportable_services.reject! do |name|
exists?(name, &:default_start_mode?)
end
end
# Import services from AutoYast profile
#
# Enabling or disabling them according to its declared status.
# Unknown services only will be logged as error.
#
# @see #enable_or_disable
#
# @param profile [Yast::ServiceManagerProfile] a service manager profile
#
# @return [Boolean] true when all services were known; false if any services was unknown
def import(profile)
log.info "List of services from autoyast profile: #{profile.services.map(&:name)}"
known_services, unknown_services = profile.services.partition { |service| exists?(service.name) }
result = enable_or_disable(known_services)
if unknown_services.empty? && result
true
else
log.error("Services #{unknown_services.inspect} don't exist on this system")
false
end
end
# Saves the current configuration in memory
#
# @return [Boolean]
def save
log.info "Saving systemd services..."
errors.clear
refresh_services if Stage.initial || Mode.auto
register_missing_services
save_modified_services
errors.empty?
end
# Activates the service in cache
#
# @param name [String] service name
# @return [Boolean]
def switch(name)
active(name) ? deactivate(name) : activate(name)
end
# Sets start_mode for a service (in memory only, use save())
#
# @param name [String] service name
# @param mode [Symbol] Start mode
# @see Yast2::SystemService#start_modes
def set_start_mode(name, mode)
exists?(name) { |s| s.start_mode = mode }
end
# Returns the start_mode for the given service (from memory)
#
# @param name [String] service name
# @return [Symbol] Start mode
def start_mode(name)
exists?(name, &:start_mode)
end
# Returns the list of supported start modes for the given service
#
# @param name [String] service name
# @return [Array<Symbol>] Supported start modes
def start_modes(name)
exists?(name, &:start_modes)
end
# Returns full information from systemctl command about the service status
#
# @param service [Yast2::SystemService]
#
# @return [String] full unformatted information
def status(service)
output = service.keywords.map do |keyword|
cmd = Yast2::Systemctl.execute("status #{keyword} 2>&1")
cmd["stdout"]
end
output.join("\n")
end
# Translates the start mode for a given service
#
# @param name [String] service name
# @return [String] Translated start mode
def start_mode_to_human_for(name)
start_mode_to_human(start_mode(name))
end
# List of YaST supported start modes
#
# @return [Array<String>] Supported start modes
def all_start_modes
START_MODE.keys
end
# Returns the localized start mode
#
# @param mode [Symbol] Start mode
# @return [String] Localized start mode
def start_mode_to_human(mode)
_(START_MODE[mode])
end
# Determines whether some service has been modified
#
# @return [Boolean] true if some service has been modified; false otherwise
#
# @see Yast2::SystemService#changed?
def modified
@modified || modified_services.any?
end
alias_method :modified?, :modified
# Summary of changes in the services
#
# @return [String]
def changes_summary
started_services_summary +
stopped_services_summary +
changed_to_on_boot_services_summary +
changed_to_on_demand_services_summary +
changed_to_manual_services_summary
end
private
# Registers errors for missing services
#
# @see #missing_services
def register_missing_services
missing_services.each do |service|
self.errors << not_found_error_message_for(service)
end
end
# Saves modified services
def save_modified_services
services = modified_services
if services.empty?
log.info "No service has been changed, nothing to do..."
return
end
log.info "Modified services: #{services.map(&:name)}"
services.each do |service|
if !service.save(keep_state: Stage.initial)
self.errors.concat(error_messages_for(service))
end
rescue Yast::SystemctlError
# This exception is raised when the service cannot be refreshed
next
end
end
# Helper method to avoid if-else branching
# When passed a block, this will be executed only if the service exists
# Whitout block it returns the boolean value
#
# @param name [String] service name
# @yieldreturn [Boolean]
# @return [Boolean] false if the service does not exist,
# otherwise what the block returned
def exists?(name)
service = find(name)
if service && block_given?
yield service
else
!!service
end
end
# Returns a list of error messages for the given service
#
# @param service [String] Service name
# @return [Array<String>] List of error messages
def error_messages_for(service)
service.errors.keys.map do |key|
send("#{key}_error_message_for", service)
end
end
# Returns a error message related to the activation/deactivation of services
#
# @return [String] Error message
def active_error_message_for(service)
# TRANSLATORS: target action to perform over a service
change = service.active? ? _("start") : _("stop")
# TRANSLATORS: current service status
status = service.running? ? _("running") : _("not running")
format(
# TRANSLATORS: Error message when a service cannot be activated/deactivated.
# %{change} is replaced by the target action (i.e., "start" or "stop"),
# %{service} is a service name (e.g., "cups"), and %{status} is the current
# service status (i.e., "running" or "not running").
_("Could not %{change} '%{service}' which is currently %{status}."),
change: change,
service: service.name,
status: status
)
end
# Start mode translations in error messages
START_MODE_TEXT = {
on_boot: N_('on boot'),
on_demand: N_('on demand'),
manual: N_('manually')
}.freeze
# Returns a error message related to setting services start modes
#
# @return [String] Error message
def start_mode_error_message_for(service)
format(
# TRANSLATORS: Error message when it was not possible to change the start
# mode of a service. %{service} is replaced by a service name (e.g., "cups")
# and %{change} is the target start mode (e.g., "on boot").
_("Could not set '%{service}' to be started %{change}."),
service: service.name,
change: _(START_MODE_TEXT[service.start_mode])
)
end
# Returns a error message when the underlying service is not found
#
# @return [String] Error message
def not_found_error_message_for(service)
format(
_("Service '%{service}' was not found."),
service: service.name
)
end
# Selects candidate services to be exported as enabled to AutoYast profile
#
# @param srvs [Array<String>] Exportable services names
# @return [Array<String>] Service names
def exportable_on_boot_services(srvs)
service_names = srvs.select { |s| start_mode(s) == :on_boot }
service_names | ServicesProposal.enabled_services
end
# Selects candidate services to be exported as enabled on-demand to AutoYast profile
#
# @param srvs [Array<String>] Exportable services names
# @return [Array<String>] Service names
def exportable_on_demand_services(srvs)
srvs.select { |s| start_mode(s) == :on_demand }
end
# Selects candidate services to be exported as disabled to AutoYast profile
#
# Untouched services are discarded; only services modified by the user to be disabled must be
# exported to AutoYast profile.
#
# @param srvs [Array<String>] Exportable services names
# @return [Array<String>] Service names
def exportable_disabled_services(srvs)
service_names = srvs.select { |s| !enabled(s) && changed_value?(s, :start_mode) }
service_names | ServicesProposal.disabled_services
end
# Enable or disable given services according to its status
#
# An error will be logged for unknown statuses
#
# @see #import
#
# @param services [Array<Service>] services to be enabled or disabled
def enable_or_disable(services)
result = true
services.each do |service|
set_start_mode(service.name, service.start_mode)
rescue ArgumentError
result = false
log.error("Invalid start mode '#{service.start_mode}' for service '#{service.name}'")
end
result
end
# Refresh the services information
#
# This is vitally important during 1st stage, where services information was read
# too early (from the instsys and not from the installed system).
def refresh_services
services.values.each(&:refresh)
end
# Summary of services that have been started
#
# @return [String]
def started_services_summary
return "" unless started_services.any?
format(
_("The following services(%{amount}) will be started:<br />%{services}<br /><br />"),
amount: started_services.size,
services: services_names(started_services)
)
end
# Summary of services that have been stopped
#
# @return [String]
def stopped_services_summary
return "" unless stopped_services.any?
format(
_("The following services(%{amount}) will be stopped:<br />%{services}<br /><br />"),
amount: stopped_services.size,
services: services_names(stopped_services)
)
end
# Summary of services that have been set to start on boot
#
# @return [String]
def changed_to_on_boot_services_summary
return "" unless changed_to_on_boot_services.any?
format(
_("The following services(%{amount}) will be configured to start after booting:<br />%{services}<br /><br />"),
amount: changed_to_on_boot_services.size,
services: services_names(changed_to_on_boot_services)
)
end
# Summary of services that have been set to start on demand
#
# @return [String]
def changed_to_on_demand_services_summary
return "" unless changed_to_on_demand_services.any?
format(
_("The following services(%{amount}) will be configured to start on demand:<br />%{services}<br /><br />"),
amount: changed_to_on_demand_services.size,
services: services_names(changed_to_on_demand_services)
)
end
# Summary of services that have been set to start manually
#
# @return [String]
def changed_to_manual_services_summary
return "" unless changed_to_manual_services.any?
format(
_("The following services(%{amount}) will be configured to start manually:<br />%{services}<br /><br />"),
amount: changed_to_manual_services.size,
services: services_names(changed_to_manual_services)
)
end
# Returns the name of the given services, joined by comma.
#
# @param services [Array<Yast2::SystemService>]
# @return [String]
def services_names(services)
services.map(&:name).join(", ")
end
# Services that have been marked to start
#
# @return [Array<Yast2::SystemService>]
def started_services
modified_services.select { |s| s.action == :start }
end
# Services that have been market to stop
#
# @return [Array<Yast2::SystemService>]
def stopped_services
modified_services.select { |s| s.action == :stop }
end
# Services that have been configured to start on boot
#
# @return [Array<Yast2::SystemService>]
def changed_to_on_boot_services
modified_services.select { |s| s.changed?(:start_mode) && s.start_mode == :on_boot }
end
# Services that have been configured to start on demand
#
# @return [Array<Yast2::SystemService>]
def changed_to_on_demand_services
modified_services.select { |s| s.changed?(:start_mode) && s.start_mode == :on_demand }
end
# Services that have been configured to start manually
#
# @return [Array<Yast2::SystemService>]
def changed_to_manual_services
modified_services.select { |s| s.changed?(:start_mode) && s.start_mode == :manual }
end
publish({:function => :active, :type => "boolean ()" })
publish({:function => :activate, :type => "string (boolean)" })
publish({:function => :all, :type => "map <string, map> ()" })
publish({:function => :disable, :type => "string (boolean)" })
publish({:function => :enable, :type => "string (boolean)" })
publish({:function => :enabled, :type => "boolean ()" })
publish({:function => :errors, :type => "list ()" })
publish({:function => :export, :type => "list <string> ()" })
publish({:function => :import, :type => "boolean (list <string>)" })
publish({:function => :modified, :type => "boolean ()" })
publish({:function => :modified=, :type => "boolean (boolean)" })
publish({:function => :read, :type => "map <string, map> ()" })
publish({:function => :reset, :type => "boolean ()" })
publish({:function => :save, :type => "boolean ()" })
publish({:function => :status, :type => "string (string)" })
end
ServicesManagerService = ServicesManagerServiceClass.new
end