Module: AcpcTableManager

Defined in:
lib/acpc_table_manager.rb,
lib/acpc_table_manager/match.rb,
lib/acpc_table_manager/utils.rb,
lib/acpc_table_manager/config.rb,
lib/acpc_table_manager/version.rb,
lib/acpc_table_manager/acpc_proxy.rb,
lib/acpc_table_manager/proxy_utils.rb,
lib/acpc_table_manager/monkey_patches.rb,
lib/acpc_table_manager/simple_logging.rb

Defined Under Namespace

Modules: MonkeyPatches, ProxyUtils, SimpleLogging, TimeRefinement Classes: AcpcProxy, CommunicatorComponent, Config, ExhibitionConfig, Match, MatchAlreadyEnqueued, NilDefaultConfig, NoBotRunner, NoPortForDealerAvailable, ProxyCommunicator, ProxyReceiver, Receiver, RequiresTooManySpecialPorts, Sender, SubscribeTimeout, TableManagerReceiver, UninitializedError

Constant Summary collapse

VERSION =
'4.0.2'.freeze
@@config =
nil
@@exhibition_config =
nil
@@is_initialized =
false
@@redis_config_file =
nil
@@config_file =
nil
@@notifier =
nil

Class Method Summary collapse

Class Method Details

.allocate_ports(players, game, ports_in_use) ⇒ Object



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
# File 'lib/acpc_table_manager.rb', line 532

def self.allocate_ports(players, game, ports_in_use)
  num_special_ports_for_this_match = 0
  max_num_special_ports = if exhibition_config.special_ports_to_dealer.nil?
    0
  else
    exhibition_config.special_ports_to_dealer.length
  end
  players.map do |player|
    bot_info = exhibition_config.games[game]['opponents'][player]
    if bot_info && bot_info['requires_special_port']
      num_special_ports_for_this_match += 1
      if num_special_ports_for_this_match > max_num_special_ports
        raise(
          RequiresTooManySpecialPorts,
          %Q{At least #{num_special_ports_for_this_match} special ports are required but only #{max_num_special_ports} ports were declared.}
        )
      end
      special_port = next_special_port(ports_in_use)
      ports_in_use << special_port
      special_port
    else
      0
    end
  end
end

.available_special_ports(ports_in_use) ⇒ Object



440
441
442
443
444
445
446
# File 'lib/acpc_table_manager.rb', line 440

def self.available_special_ports(ports_in_use)
  if exhibition_config.special_ports_to_dealer
    exhibition_config.special_ports_to_dealer - ports_in_use
  else
    []
  end
end

.configObject



118
119
120
121
122
123
124
# File 'lib/acpc_table_manager.rb', line 118

def self.config
  if @@config
    @@config
  else
    raise_uninitialized
  end
end

.config_fileObject



141
# File 'lib/acpc_table_manager.rb', line 141

def self.config_file() @@config_file end

.data_directory(game = nil) ⇒ Object



254
255
256
257
258
259
260
261
# File 'lib/acpc_table_manager.rb', line 254

def self.data_directory(game = nil)
  raise_if_uninitialized
  if game
    File.join(@@config.data_directory, shell_sanitize(game))
  else
    @@config.data_directory
  end
end

.dealer_arguments(game, name, players, random_seed) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/acpc_table_manager.rb', line 305

def self.dealer_arguments(game, name, players, random_seed)
  {
    match_name: shell_sanitize(name),
    game_def_file_name: Shellwords.escape(
      exhibition_config.games[game]['file']
    ),
    hands: Shellwords.escape(
      exhibition_config.games[game]['num_hands_per_match']
    ),
    random_seed: Shellwords.escape(random_seed.to_s),
    player_names: sanitized_player_names(players).join(' '),
    options: exhibition_config.dealer_options.join(' ')
  }
end

.each_key_value_pair(collection) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/acpc_table_manager/utils.rb', line 4

def self.each_key_value_pair(collection)
  # @todo I can't believe this is necessary...
  if collection.is_a?(Array)
    collection.each_with_index { |v, k| yield k, v }
  else
    collection.each { |k, v| yield k, v }
  end
  collection
end

.enqueue_match(game, players, seed) ⇒ Object



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/acpc_table_manager.rb', line 410

def self.enqueue_match(game, players, seed)
  sanitized_name = match_name(
    game_def_key: game,
    players: players,
    time: true
  )
  enqueued_matches_ = enqueued_matches game
  if enqueued_matches_.any? { |e| e[:name] == sanitized_name }
    raise(
      MatchAlreadyEnqueued,
      %Q{Match "#{sanitized_name}" already enqueued.}
    )
  end
  enqueued_matches_ << (
    {
      name: sanitized_name,
      game_def_key: game,
      players: sanitized_player_names(players),
      random_seed: seed
    }
  )
  update_enqueued_matches game, enqueued_matches_
end

.enqueued_matches(game) ⇒ Object



271
272
273
# File 'lib/acpc_table_manager.rb', line 271

def self.enqueued_matches(game)
  YAML.load_file(enqueued_matches_file(game)) || []
end

.enqueued_matches_file(game) ⇒ Object



263
264
265
# File 'lib/acpc_table_manager.rb', line 263

def self.enqueued_matches_file(game)
  File.join(data_directory(game), 'enqueued_matches.yml')
end

.exhibition_configObject



127
128
129
130
131
132
133
# File 'lib/acpc_table_manager.rb', line 127

def self.exhibition_config
  if @@exhibition_config
    @@exhibition_config
  else
    raise_uninitialized
  end
end

.initialized?Boolean

Returns:

  • (Boolean)


231
232
233
# File 'lib/acpc_table_manager.rb', line 231

def self.initialized?
  @@is_initialized
end

.interpolate_all_strings(value, interpolation_hash) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/acpc_table_manager/utils.rb', line 23

def self.interpolate_all_strings(value, interpolation_hash)
  if value.is_a?(String)
    # $VERBOSE and $DEBUG change '%''s behaviour
    _v = $VERBOSE
    $VERBOSE = false
    r = begin
      value % interpolation_hash
    rescue ArgumentError
      value
    end
    $VERBOSE = _v
    r
  elsif value.respond_to?(:each)
    each_key_value_pair(value) do |k, v|
      value[k] = interpolate_all_strings(v, interpolation_hash)
    end
  else
    value
  end
end

.load!(config_file_path) ⇒ Object



222
223
224
225
# File 'lib/acpc_table_manager.rb', line 222

def self.load!(config_file_path)
  @@config_file = config_file_path
  load_config! YAML.load_file(config_file_path), File.dirname(config_file_path)
end

.load_config!(config_data, yaml_directory = File.pwd) ⇒ Object



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
# File 'lib/acpc_table_manager.rb', line 146

def self.load_config!(config_data, yaml_directory = File.pwd)
  interpolation_hash = {
    pwd: yaml_directory,
    home: Dir.home,
    :~ => Dir.home,
    dealer_directory: AcpcDealer::DEALER_DIRECTORY
  }
  config = interpolate_all_strings(config_data, interpolation_hash)
  interpolation_hash[:pwd] = File.dirname(config['table_manager_constants'])

  @@config = Config.new(
    config['table_manager_constants'],
    config['log_directory'],
    config['match_log_directory'],
    config['data_directory'],
    interpolation_hash
  )

  interpolation_hash[:pwd] = File.dirname(config['exhibition_constants'])
  @@exhibition_config = ExhibitionConfig.new(
    config['exhibition_constants'],
    interpolation_hash,
    Logger.from_file_name(File.join(@@config.my_log_directory, 'exhibition_config.log'))
  )

  if config['error_report']
    Rusen.settings.sender_address = config['error_report']['sender']
    Rusen.settings.exception_recipients = config['error_report']['recipients']

    Rusen.settings.outputs = config['error_report']['outputs'] || [:pony]
    Rusen.settings.sections = config['error_report']['sections'] || [:backtrace]
    Rusen.settings.email_prefix = config['error_report']['email_prefix'] || '[ERROR] '
    Rusen.settings.smtp_settings = config['error_report']['smtp']

    @@notifier = Rusen
  else
    @@config.log(
      __method__,
      {
        warning: "Email reporting disabled. Please set email configuration to enable this feature."
      },
      Logger::Severity::WARN
    )
  end
  @@redis_config_file = config['redis_config_file'] || 'default'

  FileUtils.mkdir(opponents_log_dir) unless File.directory?(opponents_log_dir)

  @@is_initialized = true

  @@exhibition_config.games.keys.each do |game|
    d = data_directory(game)
    FileUtils.mkdir_p d  unless File.directory?(d)
    q = enqueued_matches_file(game)
    FileUtils.touch q unless File.exist?(q)
    r = running_matches_file(game)
    FileUtils.touch r unless File.exist?(r)
  end
end

.match_name(players: nil, game_def_key: nil, time: true) ⇒ Object



295
296
297
298
299
300
301
302
303
# File 'lib/acpc_table_manager.rb', line 295

def self.match_name(players: nil, game_def_key: nil, time: true)
  name = "match"
  name += ".#{sanitized_player_names(players).join('.')}" if players
  if game_def_key
    name += ".#{game_def_key}.#{exhibition_config.games[game_def_key]['num_hands_per_match']}h"
  end
  name += ".#{Time.now_as_string}" if time
  shell_sanitize name
end

.new_log(log_file_name, log_directory_ = nil) ⇒ Object



239
240
241
242
243
244
# File 'lib/acpc_table_manager.rb', line 239

def self.new_log(log_file_name, log_directory_ = nil)
  raise_if_uninitialized
  log_directory_ ||= @@config.my_log_directory
  FileUtils.mkdir_p(log_directory_) unless File.directory?(log_directory_)
  Logger.from_file_name(File.join(log_directory_, log_file_name)).with_metadata!
end

.new_redis_connection(options = {}) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/acpc_table_manager.rb', line 206

def self.new_redis_connection(options = {})
  if @@redis_config_file && @@redis_config_file != 'default'
    redis_config = YAML.load_file(@@redis_config_file).symbolize_keys
    options.merge!(redis_config[:default].symbolize_keys)
    Redis.new(
      if config['redis_environment_mode'] && redis_config[config['redis_environment_mode'].to_sym]
        options.merge(redis_config[config['redis_environment_mode'].to_sym].symbolize_keys)
      else
        options
      end
    )
  else
    Redis.new options
  end
end

.next_special_port(ports_in_use) ⇒ Object



448
449
450
451
452
453
454
455
456
457
458
# File 'lib/acpc_table_manager.rb', line 448

def self.next_special_port(ports_in_use)
  available_ports_ = available_special_ports(ports_in_use)
  port_ = available_ports_.pop
  until port_.nil? || AcpcDealer.port_available?(port_)
    port_ = available_ports_.pop
  end
  unless port_
    raise NoPortForDealerAvailable, "None of the available special ports (#{available_special_ports(ports_in_use)}) are open."
  end
  port_
end

.notifierObject



144
# File 'lib/acpc_table_manager.rb', line 144

def self.notifier() @@notifier end

.notify(exception) ⇒ Object



227
228
229
# File 'lib/acpc_table_manager.rb', line 227

def self.notify(exception)
  @@notifier.notify(exception) if @@notifier
end

.opponents_log_dirObject



250
251
252
# File 'lib/acpc_table_manager.rb', line 250

def self.opponents_log_dir
  File.join(AcpcTableManager.config.log_directory, 'opponents')
end

.player_id(game, player_name, seat) ⇒ Object



434
435
436
437
438
# File 'lib/acpc_table_manager.rb', line 434

def self.player_id(game, player_name, seat)
  shell_sanitize(
    "#{match_name(game_def_key: game, players: [player_name], time: false)}.#{seat}"
  )
end

.proxy_player?(player_name, game_def_key) ⇒ Boolean

Returns:

  • (Boolean)


320
321
322
# File 'lib/acpc_table_manager.rb', line 320

def self.proxy_player?(player_name, game_def_key)
  exhibition_config.games[game_def_key]['opponents'][player_name].nil?
end

.raise_if_uninitializedObject



235
236
237
# File 'lib/acpc_table_manager.rb', line 235

def self.raise_if_uninitialized
  raise_uninitialized unless initialized?
end

.raise_uninitializedObject

Raises:



110
111
112
113
114
# File 'lib/acpc_table_manager.rb', line 110

def self.raise_uninitialized
  raise UninitializedError.new(
    "Unable to complete with AcpcTableManager uninitialized. Please initialize AcpcTableManager with configuration settings by calling AcpcTableManager.load! with a (YAML) configuration file name."
  )
end

.redis_config_fileObject



138
# File 'lib/acpc_table_manager.rb', line 138

def self.redis_config_file() @@redis_config_file end

.resolve_path(path, root = __FILE__) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/acpc_table_manager/utils.rb', line 14

def self.resolve_path(path, root = __FILE__)
  path = Pathname.new(path)
  if path.exist?
    path.realpath.to_s
  else
    File.expand_path(path, root)
  end
end

.running_matches(game) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/acpc_table_manager.rb', line 275

def self.running_matches(game)
  saved_matches = YAML.load_file(running_matches_file(game))
  return [] unless saved_matches

  checked_matches = []
  saved_matches.each do |match|
    if AcpcDealer::process_exists?(match[:dealer][:pid])
      checked_matches << match
    end
  end
  if checked_matches.length != saved_matches.length
    update_running_matches game, checked_matches
  end
  checked_matches
end

.running_matches_file(game) ⇒ Object



267
268
269
# File 'lib/acpc_table_manager.rb', line 267

def self.running_matches_file(game)
  File.join(data_directory(game), 'running_matches.yml')
end

.sanitized_player_names(names) ⇒ Object



291
292
293
# File 'lib/acpc_table_manager.rb', line 291

def self.sanitized_player_names(names)
  names.map { |name| Shellwords.escape(name.gsub(/\s+/, '_')) }
end

.shell_sanitize(string) ⇒ Object



106
107
108
# File 'lib/acpc_table_manager.rb', line 106

def self.shell_sanitize(string)
  Zaru.sanitize!(Shellwords.escape(string.gsub(/\s+/, '_')))
end

.start_bot(id, bot_info, port) ⇒ Integer

Returns PID of the bot started.

Returns:

  • (Integer)

    PID of the bot started



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/acpc_table_manager.rb', line 390

def self.start_bot(id, bot_info, port)
  runner = bot_info['runner'].to_s
  if runner.nil? || runner.strip.empty?
    raise NoBotRunner, %Q{Bot "#{id}" with info #{bot_info} has no runner.}
  end
  args = [runner, config.dealer_host.to_s, port.to_s]
  log_file = File.join(opponents_log_dir, "#{id}.log")
  command_to_run = args.join(' ')

  config.log(
    __method__,
    {
      starting_bot: id,
      args: args,
      log_file: log_file
    }
  )
  start_process command_to_run, log_file
end

.start_dealer(game, name, players, random_seed, port_numbers) ⇒ Object



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/acpc_table_manager.rb', line 324

def self.start_dealer(game, name, players, random_seed, port_numbers)
  config.log __method__, name: name
  args = dealer_arguments game, name, players, random_seed

  config.log __method__, {
    dealer_arguments: args,
    log_directory: ::AcpcTableManager.config.match_log_directory,
    port_numbers: port_numbers,
    command: AcpcDealer::DealerRunner.command(
      args,
      port_numbers
    )
  }

  Timeout::timeout(3) do
    AcpcDealer::DealerRunner.start(
      args,
      config.match_log_directory,
      port_numbers
    )
  end
end

.start_match(game, name, players, seed, port_numbers) ⇒ Object



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
# File 'lib/acpc_table_manager.rb', line 489

def self.start_match(
  game,
  name,
  players,
  seed,
  port_numbers
)
  dealer_info = start_dealer(
    game,
    name,
    players,
    seed,
    port_numbers
  )
  port_numbers = dealer_info[:port_numbers]

  player_info = []
  players.each_with_index do |player_name, i|
    player_info << (
      {
        name: player_name,
        pid: (
          if exhibition_config.games[game]['opponents'][player_name]
            start_bot(
              player_id(game, player_name, i),
              exhibition_config.games[game]['opponents'][player_name],
              port_numbers[i]
            )
          else
            start_proxy(
              game,
              player_id(game, player_name, i),
              port_numbers[i],
              i
            )
          end
        )
      }
    )
  end
  return dealer_info, player_info
end

.start_matches_if_allowed(game = nil) ⇒ Object



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/acpc_table_manager.rb', line 460

def self.start_matches_if_allowed(game = nil)
  if game
    running_matches_ = running_matches(game)
    skipped_matches = []
    enqueued_matches_ = enqueued_matches(game)
    start_matches_in_game_if_allowed(
      game,
      running_matches_,
      skipped_matches,
      enqueued_matches_
    )
    unless enqueued_matches_.empty? && skipped_matches.empty?
      update_enqueued_matches game, skipped_matches + enqueued_matches_
    end
  else
    exhibition_config.games.keys.each do |game|
      start_matches_if_allowed game
    end
  end
end

.start_proxy(game, proxy_id, port, seat) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/acpc_table_manager.rb', line 347

def self.start_proxy(game, proxy_id, port, seat)
  config.log __method__, msg: "Starting proxy"

  args = [
    "-t #{config_file}",
    "-i #{proxy_id}",
    "-p #{port}",
    "-s #{seat}",
    "-g #{game}"
  ]
  command = "#{File.expand_path('../../exe/acpc_proxy', __FILE__)} #{args.join(' ')}"
  start_process command
end

.unload!Object



246
247
248
# File 'lib/acpc_table_manager.rb', line 246

def self.unload!
  @@is_initialized = false
end

.update_enqueued_matches(game, enqueued_matches_) ⇒ Object



481
482
483
# File 'lib/acpc_table_manager.rb', line 481

def self.update_enqueued_matches(game, enqueued_matches_)
  write_yml enqueued_matches_file(game), enqueued_matches_
end

.update_running_matches(game, running_matches_) ⇒ Object



485
486
487
# File 'lib/acpc_table_manager.rb', line 485

def self.update_running_matches(game, running_matches_)
  write_yml running_matches_file(game), running_matches_
end