Class: Yast::NtpClientClass

Inherits:
Module
  • Object
show all
Defined in:
../../src/modules/NtpClient.rb

Instance Method Summary (collapse)

Instance Method Details

- (Object) Abort

Abort function

Returns:

  • blah blah lahjk



146
147
148
149
# File '../../src/modules/NtpClient.rb', line 146

def Abort
  return @AbortFunction.call == true if @AbortFunction != nil
  false
end

- (Object) ActivateRandomPoolServersFunction

Add servers needed for random_pool_servers function into the current configuration.



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File '../../src/modules/NtpClient.rb', line 666

def ActivateRandomPoolServersFunction
  # leave the current configuration if any
  store_current_options = {}
  Builtins.foreach(@ntp_records) do |one_record|
    if Ops.get_string(one_record, "type", "") == "server" &&
        Ops.get_string(one_record, "address", "") != ""
      one_address = Ops.get_string(one_record, "address", "")
      Ops.set(store_current_options, one_address, {})
      Ops.set(
        store_current_options,
        [one_address, "options"],
        Ops.get_string(one_record, "options", "")
      )
    end
  end

  # remove all old ones
  DeActivateRandomPoolServersFunction()

  @ntp_records = Builtins.filter(@ntp_records) do |one_record|
    Ops.get_string(
      # filter out all servers
      one_record,
      "type",
      ""
    ) != "server"
  end

  Builtins.foreach(@random_pool_servers) do |one_server|
    one_options = ""
    if Builtins.haskey(store_current_options, one_server)
      one_options = Ops.get_string(
        store_current_options,
        [one_server, "options"],
        ""
      )
      Builtins.y2milestone(
        "Leaving current configuration for server '%1', options '%2'",
        one_server,
        one_options
      )
    end
    @ntp_records = Builtins.add(
      @ntp_records,
      {
        "address" => one_server,
        "comment" => "\n# Random pool server, see http://www.pool.ntp.org/ for more information\n",
        "options" => one_options,
        "type"    => "server"
      }
    )
  end

  nil
end

- (Hash) AutoPackages

Return required packages for auto-installation

Returns:

  • (Hash)

    of packages to be installed and to be removed



1228
1229
1230
# File '../../src/modules/NtpClient.rb', line 1228

def AutoPackages
  { "install" => @required_packages, "remove" => [] }
end

- (Object) DeActivateRandomPoolServersFunction

Removes all servers contained in the random_pool_servers list from the current configuration.



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# File '../../src/modules/NtpClient.rb', line 647

def DeActivateRandomPoolServersFunction
  Builtins.foreach(@random_pool_servers) do |random_pool_server|
    @ntp_records = Builtins.filter(@ntp_records) do |one_record|
      Ops.get_string(
        # do not filter out not-servers
        one_record,
        "type",
        ""
      ) != "server" ||
        # do not filter out serces that are not random_pool_servers
        Ops.get_string(one_record, "address", "") != random_pool_server
    end
  end

  nil
end

- (Boolean) deleteSyncRecord(index)

Delete specified synchronization record

Parameters:

  • index (Fixnum)

    integer index of record to delete

Returns:

  • (Boolean)

    true on success



1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
# File '../../src/modules/NtpClient.rb', line 1202

def deleteSyncRecord(index)
  if Ops.greater_or_equal(index, Builtins.size(@ntp_records)) ||
      Ops.less_or_equal(index, -1)
    Builtins.y2error("Record with index %1 doesn't exist", index)
    return false
  end
  Ops.set(@ntp_records, index, nil)
  @ntp_records = Builtins.filter(@ntp_records) { |r| r != nil }
  @modified = true
  true
end

- (Object) DetectNtpServers(method)

Detect NTP servers present in the local network

Parameters:

  • method (Symbol)

    symbol method of the detection (only `slp suported ATM)

Returns:

  • a list of found NTP servers



1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File '../../src/modules/NtpClient.rb', line 1090

def DetectNtpServers(method)
  if method == :slp
    required_package = "yast2-slp"

    # if package is not installed (in the inst-sys, it is: bnc#399659)
    if !Stage.initial && !PackageSystem.Installed(required_package)
      if !PackageSystem.CheckAndInstallPackages([required_package])
        Report.Error(
          Builtins.sformat(
            _(
              "Cannot search for NTP server in local network\nwithout package %1 installed.\n"
            ),
            required_package
          )
        )
        Builtins.y2warning("Not searching for local NTP servers via SLP")
        return []
      else
        SCR.RegisterAgent(path(".slp"), term(:ag_slp, term(:SlpAgent)))
      end
    end

    servers = SLPAPI.FindSrvs("service:ntp", "")
    server_names = Builtins.maplist(servers) do |m|
      Ops.get_string(m, "pcHost", "")
    end
    server_names = Builtins.filter(server_names) { |s| s != "" }
    return deep_copy(server_names)
  end
  Builtins.y2error("Unknown detection method: %1", method)
  []
end

- (Object) enableOptionInSyncRecord(option)

Ensure that selected_record contains the option. (A set operation in a string)



1216
1217
1218
1219
1220
1221
1222
1223
1224
# File '../../src/modules/NtpClient.rb', line 1216

def enableOptionInSyncRecord(option)
  # careful, "burst" != "iburst"
  old = Ops.get_string(@selected_record, "options", "")
  old_l = Builtins.splitstring(old, " \t")
  old_l = Builtins.add(old_l, option) if !Builtins.contains(old_l, option)
  Ops.set(@selected_record, "options", Builtins.mergestring(old_l, " "))

  nil
end

- (Hash) Export

Dump the ntp-client settings to a single map (For use by autoinstallation.)

Returns:

  • (Hash)

    Dumped settings (later acceptable by Import ())



944
945
946
947
948
949
950
951
952
953
# File '../../src/modules/NtpClient.rb', line 944

def Export
  {
    "synchronize_time" => @synchronize_time,
    "sync_interval"    => @sync_interval,
    "start_at_boot"    => @run_service,
    "start_in_chroot"  => @run_chroot,
    "ntp_policy"       => @ntp_policy,
    "peers"            => @ntp_records
  }
end

- (Fixnum) findSyncRecord(type, address)

Find index of synchronization record

Parameters:

  • type (String)

    string record type

  • address (String)

    string address

Returns:

  • (Fixnum)

    index of the record if found, -1 otherwise



1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File '../../src/modules/NtpClient.rb', line 1174

def findSyncRecord(type, address)
  index = -1
  ret = -1
  Builtins.foreach(@ntp_records) do |m|
    index = Ops.add(index, 1)
    if type == Ops.get_string(m, "type", "") &&
        address == Ops.get_string(m, "address", "")
      ret = index
    end
  end
  ret
end

- (Hash{String => String}) GetAllKnownCountries

Reads and returns all known countries with their country codes

Structure:

Returns:

  • (Hash{String => String})

    of known contries



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
# File '../../src/modules/NtpClient.rb', line 161

def GetAllKnownCountries
  #first point of dependence on yast2-country-data
  if !@countries_already_read
    @known_countries = Convert.convert(
      Builtins.eval(
        SCR.Read(
          path(".target.ycp"),
          Ops.add(Directory.datadir, "/country.ycp")
        )
      ),
      :from => "any",
      :to   => "map <string, string>"
    )
    @countries_already_read = true
    @known_countries = {} if @known_countries == nil
  end

  #workaround bug #241054: servers in United Kingdom are in domain .uk
  # domain .gb does not exist - add UK to the list of known countries
  if Builtins.haskey(@known_countries, "GB")
    Ops.set(@known_countries, "UK", Ops.get(@known_countries, "GB", ""))
    @known_countries = Builtins.remove(@known_countries, "GB")
  end

  deep_copy(@known_countries)
end

- (Object) GetCountryNames

Get the mapping between country codea and names (“CZ” -> “Czech Republic”)

Returns:

  • a map the country codes and names mapping



241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File '../../src/modules/NtpClient.rb', line 241

def GetCountryNames
  if @country_names == nil
    @country_names = Convert.convert(
      Builtins.eval(SCR.Read(path(".target.yast2"), "country.ycp")),
      :from => "any",
      :to   => "map <string, string>"
    )
  end
  if @country_names == nil
    Builtins.y2error("Failed to read country names")
    @country_names = {}
  end
  deep_copy(@country_names)
end

- (Object) GetCurrentLanguageCode

Read current language (RC_LANG from sysconfig)

Returns:

  • two-letter language code (cs_CZ.UTF-8 -> CZ)



190
191
192
193
194
195
# File '../../src/modules/NtpClient.rb', line 190

def GetCurrentLanguageCode
  lang = Convert.to_string(SCR.Read(path(".sysconfig.language.RC_LANG")))

  #second point of dependence on yast2-country-data
  Language.GetGivenLanguageCountry(lang)
end

- (Object) GetNtpServers

Get the list of known NTP servers

Returns:

  • a list of known NTP servers



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
# File '../../src/modules/NtpClient.rb', line 210

def GetNtpServers
  if @ntp_servers == nil
    @ntp_servers = {}
    #FIXME This is wrong approach, because datadir should be array of all Y2DIR/DATA
    # so we need to skip it in tests, even if we set Y2DIR properly
    return {} if Mode.test
    servers = YAML.load_file(Directory.datadir + "/ntp_servers.yml") rescue nil
    if servers == nil 
      Builtins.y2error("Failed to read the list of NTP servers")
    else
      Builtins.y2milestone(
        "%1 known NTP servers read",
        Builtins.size(servers)
      )
      @ntp_servers = Builtins.listmap(servers) do |s|
        server = Ops.get(s, "address", "")
        { server => s }
      end
    end
    Builtins.foreach(GetAllKnownCountries()) do |short_country, country_name|
      # just refactored existing code
      p = MakePoolRecord(short_country, country_name)
      Ops.set(@ntp_servers, Ops.get(p, "address", ""), p)
    end
  end

  deep_copy(@ntp_servers)
end

- (Array) GetNtpServersByCountry(country, terse_output)

Get list of public NTP servers for a country

Parameters:

  • country (String)

    two-letter country code

  • terse_output (Boolean)

    display additional data (location etc.)

Returns:

  • (Array)

    of servers (usable as combo-box items)



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
# File '../../src/modules/NtpClient.rb', line 260

def GetNtpServersByCountry(country, terse_output)
  country_names = {}
  servers = GetNtpServers()
  if country != ""
    servers = Builtins.filter(servers) do |s, o|
      Ops.get(o, "country", "") == country
    end
    # bnc#458917 add country, in case data/country.ycp does not have it
    p = MakePoolRecord(country, "")
    Ops.set(servers, Ops.get(p, "address", ""), p)
  else
    country_names = GetCountryNames()
  end

  items = Builtins.maplist(servers) do |s, o|
    label = Ops.get(o, "location", "")
    l_country = Ops.get(o, "country", "")
    if country != ""
      l_country = ""
    else
      l_country = Ops.get(country_names, l_country, l_country)
    end
    if label != "" && l_country != ""
      label = Builtins.sformat("%1 (%2, %3)", s, label, l_country)
    elsif label == "" && l_country == ""
      label = s
    else
      label = Builtins.sformat("%1 (%2%3)", s, label, l_country)
    end
    if terse_output
      next Item(Id(s), s)
    else
      next Item(Id(s), label)
    end
  end

  deep_copy(items)
end

- (Object) getSyncRecords

Get the list of synchronization-related records

Returns:

  • a list of maps with keys type (eg. “server”), address and index.



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
# File '../../src/modules/NtpClient.rb', line 1125

def getSyncRecords
  index = -1
  ret = Builtins.maplist(@ntp_records) do |m|
    index = Ops.add(index, 1)
    type = Ops.get_string(m, "type", "")
    if !Builtins.contains(
        ["server", "peer", "broadcast", "broadcastclient", "__clock"],
        type
      )
      next nil
    end
    {
      "type"    => type,
      "index"   => index,
      "address" => Ops.get_string(m, "address", ""),
      "device"  => Ops.get_string(m, "device", "")
    }
  end
  ret = Builtins.filter(ret) { |m| m != nil }
  deep_copy(ret)
end

- (Array<String>) GetUsedNtpServers

Function returns list of NTP servers used in the configuration.

Returns:

  • (Array<String>)

    of servers



606
607
608
609
610
611
612
613
614
615
616
617
618
# File '../../src/modules/NtpClient.rb', line 606

def GetUsedNtpServers
  used_servers = []
  Builtins.foreach(@ntp_records) do |record|
    if Ops.get_string(record, "type", "") == "server"
      used_servers = Builtins.add(
        used_servers,
        Ops.get_string(record, "address", "")
      )
    end
  end

  deep_copy(used_servers)
end

- (Boolean) Import(settings)

Get all ntp-client settings from the first parameter (For use by autoinstallation.)

Parameters:

  • settings (Hash)

    The YCP structure to be imported.

Returns:

  • (Boolean)

    True on success



911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# File '../../src/modules/NtpClient.rb', line 911

def Import(settings)
  settings = deep_copy(settings)
  @synchronize_time = Ops.get_boolean(settings, "synchronize_time", false)
  @sync_interval = Ops.get_integer(settings, "sync_interval", 5)
  @run_service = Ops.get_boolean(settings, "start_at_boot", false)
  @run_chroot = Ops.get_boolean(settings, "start_in_chroot", true)
  # compatibility: configure_dhcp:true translates to ntp_policy:auto
  config_dhcp = Ops.get_boolean(settings, "configure_dhcp", false)
  @ntp_policy = Ops.get_string(
    settings,
    "ntp_policy",
    config_dhcp ? "auto" : ""
  )
  @ntp_records = Ops.get_list(settings, "peers", [])
  @ntp_records = Builtins.maplist(@ntp_records) do |p|
    if Builtins.haskey(p, "key") && Builtins.haskey(p, "value")
      Ops.set(p, "type", Ops.get_string(p, "key", ""))
      Ops.set(p, "address", Ops.get_string(p, "value", ""))
      if Builtins.haskey(p, "param")
        Ops.set(p, "options", Ops.get_string(p, "param", ""))
      end
      next deep_copy(p)
    else
      next deep_copy(p)
    end
  end
  @modified = true
  true
end

- (Boolean) IsRandomServersServiceEnabled

Checks whether all servers listed in the random_pool_servers list are used in the configuration.

Returns:

  • (Boolean)

    true if enabled



624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# File '../../src/modules/NtpClient.rb', line 624

def IsRandomServersServiceEnabled
  # all servers needed by pool.ntp.org service, before checking false == not used
  needed_servers = {}
  Builtins.foreach(@random_pool_servers) do |server_name|
    Ops.set(needed_servers, server_name, false)
  end

  Builtins.foreach(GetUsedNtpServers()) do |used_server|
    # if server is needed by pool.ntp.org and matches
    if Ops.get(needed_servers, used_server) != nil
      Ops.set(needed_servers, used_server, true)
    end
  end

  ret = true
  Builtins.foreach(needed_servers) do |nserver_name, ns_value|
    ret = false if ns_value != true
  end
  ret
end

- (Object) main



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
# File '../../src/modules/NtpClient.rb', line 17

def main
  Yast.import "UI"
  textdomain "ntp-client"

  Yast.import "Directory"
  Yast.import "FileUtils"
  Yast.import "Language"
  Yast.import "Message"
  Yast.import "Mode"
  Yast.import "NetworkInterfaces"
  Yast.import "PackageSystem"
  Yast.import "Popup"
  Yast.import "Progress"
  Yast.import "Report"
  Yast.import "Service"
  Yast.import "SLPAPI"
  Yast.import "Stage"
  Yast.import "String"
  Yast.import "Summary"
  Yast.import "SuSEFirewall"
  Yast.import "FileChanges"


  # Abort function
  # return boolean return true if abort
  @AbortFunction = nil

  # Data was modified?
  @modified = false

  # Write only, used during autoinstallation.
  # Don't run services and SuSEconfig, it's all done at one place.
  @write_only = false

  # Read all ntp-client settings
  # @return true on success
  @ntp_records = []

  @restrict_map = {}

  # Should the daemon be started when system boots?
  @run_service = true

  # Should the time synchronized periodicaly?
  @synchronize_time = false

  # The interval of synchronization in minutes.
  @sync_interval = 5

  # The cron file name for the synchronization.
  @cron_file = "/etc/cron.d/novell.ntp-synchronize"

  # Service name of the NTP daemon
  @service_name = "ntp"

  # Should the daemon be started in chroot environment?
  @run_chroot = false


  # Netconfig policy: for merging and prioritizing static and DHCP config.
  # FIXME get a public URL
  # https://svn.suse.de/svn/sysconfig/branches/mt/dhcp6-netconfig/netconfig/doc/README
  @ntp_policy = "auto"


  # Index of the currently sellected item
  @selected_index = -1

  # The currently sellected item
  @selected_record = {}

  # Active Directory controller
  @ad_controller = ""

  # Should the firewall settings be changed?
  @change_firewall = false

  # Required packages
  @required_packages = ["ntp"]

  # ports in firewall to open
  @firewall_services = ["service:ntp"]


  # List of known NTP servers
  # server address -> information
  #  address: the key repeated
  #  country: CC (uppercase)
  #  location: for displaying
  #  ...: (others are unused)
  @ntp_servers = nil

  # Mapping between country codes and country names ("CZ" -> "Czech Republic")
  @country_names = nil

  @simple_dialog = false

  @config_has_been_read = false

  @ntp_selected = false

  # for lazy loading
  @countries_already_read = false
  @known_countries = {}

  # List of servers defined by the pool.ntp.org to get random ntp servers
  #
  # @see #http://www.pool.ntp.org/
  @random_pool_servers = [
    "0.pool.ntp.org",
    "1.pool.ntp.org",
    "2.pool.ntp.org"
  ]
end

- (Object) MakePoolRecord(_CC, location)



197
198
199
200
201
202
203
204
205
206
# File '../../src/modules/NtpClient.rb', line 197

def MakePoolRecord(_CC, location)
  mycc = Builtins.tolower(_CC)
  #There is no gb.pool.ntp.org only uk.pool.ntp.org
  mycc = "uk" if mycc == "gb"
  {
    "address"  => Ops.add(mycc, ".pool.ntp.org"),
    "country"  => _CC,
    "location" => location
  }
end

- (Object) PolicyIsAuto



132
133
134
# File '../../src/modules/NtpClient.rb', line 132

def PolicyIsAuto
  @ntp_policy == "auto" || @ntp_policy == "STATIC *"
end

- (Object) PolicyIsNomodify



136
137
138
# File '../../src/modules/NtpClient.rb', line 136

def PolicyIsNomodify
  @ntp_policy == ""
end

- (Object) PolicyIsNonstatic



140
141
142
# File '../../src/modules/NtpClient.rb', line 140

def PolicyIsNonstatic
  @ntp_policy != "" && @ntp_policy != "STATIC"
end

- (Object) ProcessNtpConf

Read and parse /etc.ntp.conf

Returns:

  • true on success



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
# File '../../src/modules/NtpClient.rb', line 301

def ProcessNtpConf
  if @config_has_been_read
    Builtins.y2milestone("Configuration has been read already, skipping.")
    return false
  end

  conf = nil
  if FileUtils.Exists("/etc/ntp.conf")
    conf = Convert.to_map(SCR.Read(path(".etc.ntp_conf.all")))
  end

  if conf == nil
    Builtins.y2error(
      "Failed to read /etc/ntp.conf, either it doesn't exist or contains no data"
    )
    return false
  end
  Builtins.y2milestone("Raw ntp conf %1", conf)
  @config_has_been_read = true
  value = Ops.get_list(conf, "value", [])
  index = -1
  @ntp_records = Builtins.maplist(value) do |m|
    index = Ops.add(index, 1)
    type = Ops.get_string(m, "name", "")
    address = Ops.get_string(m, "value", "")
    options = ""
    if Builtins.contains(
        [
          "server",
          "peer",
          "broadcast",
          "broadcastclient",
          "manycast",
          "manycastclient",
          "fudge",
          "restrict"
        ],
        type
      )
      l = Builtins.splitstring(address, " \t")
      l = Builtins.filter(l) { |s| s != "" }
      address = Ops.get(l, 0, "")
      Ops.set(l, 0, "")
      options = Builtins.mergestring(l, " ")
    end
    entry = {
      "type"    => type,
      "address" => address,
      "options" => options,
      "comment" => Ops.get_string(m, "comment", "")
    }
    deep_copy(entry)
  end
  fudge_records = Builtins.filter(@ntp_records) do |m|
    Ops.get_string(m, "type", "") == "fudge"
  end
  fudge_map = Convert.convert(
    Builtins.listmap(fudge_records) do |m|
      key = Ops.get_string(m, "address", "")
      { key => m }
    end,
    :from => "map <string, map>",
    :to   => "map <string, map <string, any>>"
  )

  restrict_records = Builtins.filter(@ntp_records) do |m|
    Ops.get_string(m, "type", "") == "restrict"
  end

  @restrict_map = Convert.convert(
    Builtins.listmap(restrict_records) do |m|
      key = Ops.get_string(m, "address", "")
      value2 = {}
      opts = Builtins.splitstring(
        String.CutBlanks(Ops.get_string(m, "options", "")),
        " \t"
      )
      if Ops.get(opts, 0, "") == "mask"
        Ops.set(value2, "mask", Ops.get(opts, 1, ""))
        Ops.set(opts, 0, "")
        Ops.set(opts, 1, "")
      else
        Ops.set(value2, "mask", "")
      end
      Ops.set(
        value2,
        "options",
        String.CutBlanks(Builtins.mergestring(opts, " "))
      )
      Ops.set(value2, "comment", Ops.get_string(m, "comment", ""))
      { key => value2 }
    end,
    :from => "map <string, map>",
    :to   => "map <string, map <string, any>>"
  )

  @ntp_records = Builtins.filter(@ntp_records) do |m|
    Ops.get_string(m, "type", "") != "fudge"
  end

  @ntp_records = Builtins.filter(@ntp_records) do |m|
    Ops.get_string(m, "type", "") != "restrict"
  end

  @ntp_records = Convert.convert(
    Builtins.maplist(@ntp_records) do |m|
      if Builtins.haskey(fudge_map, Ops.get_string(m, "address", ""))
        Ops.set(
          m,
          "fudge_options",
          Ops.get_string(
            fudge_map,
            [Ops.get_string(m, "address", ""), "options"],
            ""
          )
        )
        Ops.set(
          m,
          "fudge_comment",
          Ops.get_string(
            fudge_map,
            [Ops.get_string(m, "address", ""), "comment"],
            ""
          )
        )
      end
      deep_copy(m)
    end,
    :from => "list <map>",
    :to   => "list <map <string, any>>"
  )

  # mark local clock to be local clock and not real servers
  @ntp_records = Builtins.maplist(@ntp_records) do |p|
    if Ops.get_string(p, "type", "") == "server" &&
        Builtins.regexpmatch(
          Ops.get_string(p, "address", ""),
          "^127.127.[0-9]+.[0-9]+$"
        )
      Ops.set(p, "type", "__clock")
    end
    deep_copy(p)
  end

  true
end

- (Object) Read

Read all ntp-client settings

Returns:

  • true on success



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
# File '../../src/modules/NtpClient.rb', line 473

def Read
  return true if @config_has_been_read

  # NtpClient read dialog caption
  caption = _("Initializing NTP Client Configuration")

  steps = 2
  sl = 500

  have_progress = Mode.normal

  # We do not set help text here, because it was set outside
  if have_progress
    Progress.New(
      caption,
      " ",
      steps,
      [
        # progress stage
        _("Read network configuration"),
        # progress stage
        _("Read NTP settings")
      ],
      [
        # progress step
        _("Reading network configuration..."),
        # progress step
        _("Reading NTP settings..."),
        # progress step
        _("Finished")
      ],
      ""
    )
  end

  # read network configuration
  return false if Abort()
  Progress.NextStage if have_progress

  progress_orig = Progress.set(false)
  NetworkInterfaces.Read
  Progress.set(progress_orig)

  #SCR::Read may return nil (no such value in sysconfig, file not there etc. )
  policy = Convert.to_string(
    SCR.Read(path(".sysconfig.network.config.NETCONFIG_NTP_POLICY"))
  )
  #set if not nil, otherwise use 'auto' as safe fallback (#449362)
  @ntp_policy = policy if policy != nil

  GetNtpServers()
  GetCountryNames()
  # read current settings
  return false if Abort()
  Progress.NextStage if have_progress

  failed = false

  if !Mode.testsuite && !Mode.installation &&
      !PackageSystem.CheckAndInstallPackagesInteractive(["ntp"])
    Builtins.y2milestone(
      "PackageSystem::CheckAndInstallPackagesInteractive failed"
    )
    return false
  end

  @run_service = Service.Enabled(@service_name)

  #Poke to /var/lib/YaST if there is Active Directory controller address dumped in .ycp file
  ad_ntp_file = Ops.add(Directory.vardir, "/ad_ntp_data.ycp")
  if FileUtils.Exists(ad_ntp_file)
    Builtins.y2milestone("Reading %1", ad_ntp_file)
    ad_ntp_data = Convert.convert(
      SCR.Read(path(".target.ycp"), ad_ntp_file),
      :from => "any",
      :to   => "map <string, string>"
    )
    @ad_controller = Ops.get(ad_ntp_data, "ads", "")
    if @ad_controller != ""
      Builtins.y2milestone(
        "Got %1 for ntp sync, deleting %2, since it is no longer needed",
        @ad_controller,
        ad_ntp_file
      )
      SCR.Execute(path(".target.remove"), ad_ntp_file)
    end
  end

  # Stay away if the user may have made changes which we cannot parse.
  # But bnc#456553, no pop-ups for CLI.
  if !Mode.commandline && !FileChanges.CheckFiles(["/etc/ntp.conf"])
    failed = true
  end
  ProcessNtpConf()

  ReadSynchronization()

  run_chroot_s = Convert.to_string(
    SCR.Read(path(".sysconfig.ntp.NTPD_RUN_CHROOTED"))
  )
  @run_chroot = run_chroot_s == "yes"

  if run_chroot_s == nil
    failed = true
    Builtins.y2error("Failed reading .sysconfig.ntp.NTPD_RUN_CHROOTED")
  end

  if failed
    # error report
    Report.Error(Message.CannotReadCurrentSettings)
  end

  if !Mode.testsuite
    progress_orig2 = Progress.set(false)
    SuSEFirewall.Read
    Progress.set(progress_orig2)
  end

  return false if Abort()
  if have_progress
    Progress.NextStage
    Progress.Title(_("Finished"))
  end
  Builtins.sleep(sl)

  return false if Abort()
  @modified = false
  true
end

- (Object) ReadSynchronization

Read the synchronization status, fill synchronize_time and sync_interval variables Return updated value of synchronize_time



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File '../../src/modules/NtpClient.rb', line 451

def ReadSynchronization
  crontab = Convert.to_list(SCR.Read(path(".cron"), @cron_file, ""))
  Builtins.y2milestone("CRONTAB %1", crontab)
  tmp = Ops.get_string(crontab, [0, "events", 0, "active"], "0")
  @synchronize_time = tmp == "1"
  tmp = Ops.get_string(crontab, [0, "events", 0, "minute"], "*/5")
  Builtins.y2milestone("MINUTE %1", tmp)
  pos = Builtins.regexppos(tmp, "[0-9]+")
  tmp2 = Builtins.substring(
    tmp,
    Ops.get_integer(pos, 0, 0),
    Ops.get_integer(pos, 1, 0)
  )
  @sync_interval = Builtins.tointeger(tmp2)
  Builtins.y2milestone("SYNC_INTERVAL %1", @sync_interval)

  @synchronize_time
end

- (Boolean) selectSyncRecord(index)

Select synchronization record

Parameters:

  • index (Fixnum)

    integer, -1 for creating a new record

Returns:

  • (Boolean)

    true on success



1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File '../../src/modules/NtpClient.rb', line 1150

def selectSyncRecord(index)
  ret = true
  if Ops.greater_or_equal(index, Builtins.size(@ntp_records)) ||
      Ops.less_than(index, -1)
    Builtins.y2error(
      "Record with index %1 doesn't exist, creating new",
      index
    )
    index = -1
    ret = false
  end
  if index == -1
    @selected_record = {}
  else
    @selected_record = Ops.get(@ntp_records, index, {})
  end
  @selected_index = index
  ret
end

- (Boolean) storeSyncRecord

Store currently sellected synchronization record

Returns:

  • (Boolean)

    true on success



1189
1190
1191
1192
1193
1194
1195
1196
1197
# File '../../src/modules/NtpClient.rb', line 1189

def storeSyncRecord
  if @selected_index == -1
    @ntp_records = Builtins.add(@ntp_records, @selected_record)
  else
    Ops.set(@ntp_records, @selected_index, @selected_record)
  end
  @modified = true
  true
end

- (String) Summary

Create a textual summary and a list of unconfigured cards

Returns:

  • (String)

    summary of the current configuration



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
# File '../../src/modules/NtpClient.rb', line 957

def Summary
  summary = ""
  if @run_service
    # summary string
    summary = Summary.AddLine(
      summary,
      _("The NTP daemon starts when starting the system.")
    )
  else
    # summary string
    summary = Summary.AddLine(
      summary,
      _("The NTP daemon does not start automatically.")
    )
  end

  types = {
    # summary string, %1 is list of addresses
    "server"          => _(
      "Servers: %1"
    ),
    # summary string, %1 is list of addresses
    "__clock"         => _(
      "Radio Clocks: %1"
    ),
    # summary string, %1 is list of addresses
    "peer"            => _(
      "Peers: %1"
    ),
    # summary string, %1 is list of addresses
    "broadcast"       => _(
      "Broadcast time information to: %1"
    ),
    # summary string, %1 is list of addresses
    "broadcastclient" => _(
      "Accept broadcasted time information from: %1"
    )
  }
  #   if (config_dhcp)
  #   {
  #   summary = Summary::AddLine (summary,
  #   // summary string
  #   _("Configure NTP daemon via DHCP."));
  #   return summary;
  #   }
  # netconfig policy
  if PolicyIsAuto()
    # summary string, FIXME
    summary = Summary.AddLine(
      summary,
      _("Combine static and DHCP configuration.")
    )
  elsif PolicyIsNomodify()
    # summary string, FIXME
    summary = Summary.AddLine(summary, _("Static configuration only."))
  else
    # summary string, FIXME
    summary = Summary.AddLine(summary, _("Custom configuration policy.")) # FIXME too generic!
  end

  Builtins.foreach(
    ["server", "__clock", "peer", "broadcast", "broadcastclient"]
  ) do |t|
    l = Builtins.filter(@ntp_records) do |p|
      Ops.get_string(p, "type", "") == t
    end
    names = Builtins.maplist(l) { |i| Ops.get_string(i, "address", "") }
    names = Builtins.filter(names) { |n| n != "" }
    if Ops.greater_than(Builtins.size(names), 0)
      summary = Summary.AddLine(
        summary,
        Builtins.sformat(
          Ops.get_string(types, t, ""),
          Builtins.mergestring(names, ", ")
        )
      )
    end
  end
  summary
end

- (Boolean) TestNtpServer(server, verbosity)

Test if specified NTP server answers

Parameters:

  • server (String)

    string host name or IP address of the NTP server

  • verbosity (Symbol)

    no_ui: ...,transient_popup: pop up while scanning, `result_popup: also final pop up about the result

Returns:

  • (Boolean)

    true if NTP server answers properly



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
# File '../../src/modules/NtpClient.rb', line 1043

def TestNtpServer(server, verbosity)
  if verbosity != :no_ui
    UI.OpenDialog(
      # An informative popup label diring the NTP server testings
      Left(Label(_("Testing the NTP server...")))
    )
  end

  Builtins.y2milestone("Testing reachability of server %1", server)

  # testing the server using IPv4 and then using IPv6 protocol
  # bug #74076, Firewall could have been blocked IPv6
  ret_IPv4 = Convert.to_integer(
    SCR.Execute(
      path(".target.bash"),
      Builtins.sformat("/usr/sbin/sntp -4 -t 5 %1", server)
    )
  )
  ret_IPv6 = 0
  if ret_IPv4 != 0
    ret_IPv6 = Convert.to_integer(
      SCR.Execute(
        path(".target.bash"),
        Builtins.sformat("/usr/sbin/sntp -6 -t 5 %1", server)
      )
    )
  end

  UI.CloseDialog if verbosity != :no_ui

  ok = ret_IPv4 == 0 || ret_IPv6 == 0
  if verbosity == :result_popup
    if ok
      # message report - result of test of connection to NTP server
      Popup.Notify(_("Server is reachable and responds properly."))
    else
      # error message  - result of test of connection to NTP server
      # report error instead of simple message (#306018)
      Report.Error(_("Server is unreachable or does not respond properly."))
    end
  end
  ok
end

- (Object) Write

Write all ntp-client settings

Returns:

  • true on success



724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
# File '../../src/modules/NtpClient.rb', line 724

def Write
  #boolean update_dhcp = original_config_dhcp != config_dhcp;

  # NtpClient read dialog caption
  caption = _("Saving NTP Client Configuration")

  steps = 2

  sl = 0
  Builtins.sleep(sl)

  have_progress = Mode.normal

  # We do not set help text here, because it was set outside
  if have_progress
    Progress.New(
      caption,
      " ",
      steps,
      [
        # progress stage
        _("Write NTP settings"),
        # progress stage
        _("Restart NTP daemon")
      ],
      [
        # progress step
        _("Writing the settings..."),
        # progress step
        _("Restarting NTP daemon..."),
        # progress step
        _("Finished")
      ],
      ""
    )
  end

  # write settings
  return false if Abort()
  Progress.NextStage if have_progress

  if true
    Builtins.foreach(@restrict_map) do |key, m|
      ret = {
        "address" => key,
        "comment" => Ops.get_string(m, "comment", ""),
        "type"    => "restrict",
        "options" => Ops.add(
          Ops.add(
            Ops.get_string(m, "mask", "") != "" ?
              Ops.add(" mask ", Ops.get_string(m, "mask", "")) :
              "",
            " "
          ),
          Ops.get_string(m, "options", "")
        )
      }
      @ntp_records = Builtins.add(@ntp_records, ret)
    end

    Builtins.y2milestone("Writing settings %1", @ntp_records)

    save2 = Builtins.flatten(Builtins.maplist(@ntp_records) do |r|
      s1 = {
        "comment" => Ops.get_string(r, "comment", ""),
        "kind"    => "value",
        "name"    => Ops.get_string(r, "type", ""),
        "type"    => 0,
        "value"   => Ops.add(
          Ops.add(Ops.get_string(r, "address", ""), " "),
          Ops.get_string(r, "options", "")
        )
      }
      s2 = nil
      if Ops.get_string(r, "type", "") == "__clock"
        s2 = {
          "comment" => Ops.get_string(r, "fudge_comment", ""),
          "kind"    => "value",
          "name"    => "fudge",
          "type"    => 0,
          "value"   => Ops.add(
            Ops.add(Ops.get_string(r, "address", ""), " "),
            Ops.get_string(r, "fudge_options", "")
          )
        }
        Ops.set(s1, "name", "server")
      end
      [s1, s2]
    end)
    save2 = Builtins.filter(save2) { |m| m != nil }

    failed = false
    conf = Convert.to_map(SCR.Read(path(".etc.ntp_conf.all")))
    if conf == nil
      failed = true
    else
      Ops.set(conf, "value", save2)
      failed = true if !SCR.Write(path(".etc.ntp_conf.all"), conf)
      failed = true if !SCR.Write(path(".etc.ntp_conf"), nil)
    end

    FileChanges.StoreFileCheckSum("/etc/ntp.conf")

    Report.Error(Message.CannotWriteSettingsTo("/etc/ntp.conf")) if failed
  end
  # write policy and run netconfig command
  SCR.Write(
    path(".sysconfig.network.config.NETCONFIG_NTP_POLICY"),
    @ntp_policy
  )
  SCR.Write(path(".sysconfig.network.config"), nil)

  if SCR.Execute(path(".target.bash"), "/sbin/netconfig update -m ntp") != 0
    # error message
    Report.Error(_("Cannot update the dynamic configuration policy."))
  end

  SCR.Write(
    path(".sysconfig.ntp.NTPD_RUN_CHROOTED"),
    @run_chroot ? "yes" : "no"
  )
  SCR.Write(path(".sysconfig.ntp"), nil)

  Builtins.sleep(sl)

  # restart daemon
  return false if Abort()
  Progress.NextStage if have_progress

  # SuSEFirewall::Write checks on its own whether there are pending
  # changes, so call it always. bnc#476951
  if true
    progress_orig = Progress.set(false)
    SuSEFirewall.Write
    Progress.set(progress_orig)
  end

  if !Service.Adjust(@service_name, @run_service ? "enable" : "disable")
    # error report
    Report.Error(Message.CannotAdjustService("NTP"))
  end

  if @run_service && !@write_only &&
      0 != Service.RunInitScript(@service_name, "restart")
    # error report
    Report.Error(_("Cannot restart the NTP daemon."))
  end
  Service.RunInitScript(@service_name, "stop") if !@run_service
  if @synchronize_time
    SCR.Write(
      path(".target.string"),
      @cron_file,
      Ops.add(
        Ops.add("-*/", @sync_interval),
        " * * * * root /etc/init.d/ntp ntptimeset &>/dev/null\n"
      )
    )
  else
    SCR.Execute(
      path(".target.bash"),
      Ops.add(
        Ops.add(
          Ops.add(Ops.add("test -e ", @cron_file), "  && rm "),
          @cron_file
        ),
        ";"
      )
    )
  end

  Builtins.sleep(sl)

  return false if Abort()
  if have_progress
    Progress.NextStage
    Progress.Title(_("Finished"))
  end
  Builtins.sleep(sl)

  return false if Abort()
  true
end