Module: TungstenScript

Defined in:
lib/tungsten/script.rb,
lib/continuent-tools-core.rb

Constant Summary collapse

NAGIOS_OK =
0
NAGIOS_WARNING =
1
NAGIOS_CRITICAL =
2

Instance Method Summary collapse

Instance Method Details

#add_command(command_key, definition) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/tungsten/script.rb', line 173

def add_command(command_key, definition)
  begin
    command_key = command_key.to_sym()
    if @command_definitions.has_key?(command_key)
      raise "The #{command_key} command has already been defined"
    end

    if definition[:default] == true
      if @command != nil
        raise "Multiple commands have been specified as the default"
      end
      @command = command_key.to_s()
    end

    @command_definitions[command_key] = definition
  rescue => e
    TU.exception(e)
  end
end

#add_option(option_key, definition, &parse) ⇒ Object



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
# File 'lib/tungsten/script.rb', line 193

def add_option(option_key, definition, &parse)
  begin
    option_key = option_key.to_sym()
    if @option_definitions.has_key?(option_key)
      raise "The #{option_key} option has already been defined"
    end

    unless definition[:on].is_a?(Array)
      definition[:on] = [definition[:on]]
    end
    
    # Check if the arguments for this option overlap with any other options
    definition[:on].each{
      |arg|
      
      arg = arg.split(" ").shift()
      if @option_definition_arguments.has_key?(arg)
        raise "The #{arg} argument is already defined for this script"
      end
      @option_definition_arguments[arg] = true
    }

    if parse != nil
      definition[:parse] = parse
    end

    @option_definitions[option_key] = definition
  rescue => e
    TU.exception(e)
  end
end

#allow_unparsed_arguments?(v = nil) ⇒ Boolean

Returns:

  • (Boolean)


523
524
525
526
527
528
529
# File 'lib/tungsten/script.rb', line 523

def allow_unparsed_arguments?(v = nil)
  if (v != nil)
    @allow_unparsed_arguments = v
  end
  
  @allow_unparsed_arguments
end

#cleanup(code = 0) ⇒ Object



551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/tungsten/script.rb', line 551

def cleanup(code = 0)
  if code != 0
    log_path = TU.log().path()
    if log_path.to_s() != "" && File.exist?(log_path)
      TU.notice("See #{script_log_path()} for more information")
    end
  end
  
  TU.debug("Finish #{$0} #{ARGV.join(' ')}")
  TU.debug("RC: #{code}")
  
  TU.exit(code)
end

#commandObject



120
121
122
# File 'lib/tungsten/script.rb', line 120

def command
  @command
end

#configureObject



124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/tungsten/script.rb', line 124

def configure
  add_option(:validate, {
    :on => "--validate",
    :default => false,
    :help => "Only run the script validation"
  })
  
  add_option(:autocomplete, {
    :on => "--autocomplete",
    :default => false,
    :hidden => true
  })
end

#description(v = nil) ⇒ Object



535
536
537
538
539
540
541
# File 'lib/tungsten/script.rb', line 535

def description(v = nil)
  if v != nil
    @description = v
  end
  
  @description || nil
end

#display_autocompleteObject



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
# File 'lib/tungsten/script.rb', line 483

def display_autocomplete
  values = TU.get_autocomplete_arguments()
  if @command_definitions.size() > 0
    @command_definitions.each{
      |command_key,definition|
      values << command_key.to_s()
    }
  end
  
  @option_definitions.each{
    |option_key,definition|
    
    if definition[:hidden] == true
      next
    end
    
    values = values + definition[:on]
  }
  
  values.map!{
    |v|
    parts = v.split(" ")
    if parts.size() == 2
      "#{parts[0]}="
    else
      v
    end
  }
  
  puts values.join(" ")
end

#display_helpObject



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
# File 'lib/tungsten/script.rb', line 428

def display_help
  if script_name().to_s() != ""
    TU.output("Usage: #{script_name()} [global-options] [script-options]")
    TU.output("")
  end

  unless description() == nil
    description().split("<br>").each{
      |section|
      TU.output(TU.wrapped_lines(section))
    }
    TU.output("")
  end
  
  TU.display_help()
  
  if @command_definitions.size() > 0
    TU.write_header("Script Commands", nil)
    
    commands = @command_definitions.keys().sort { |a, b| a.to_s <=> b.to_s }
    commands.each{
      |command_key|
      definition = @command_definitions[command_key]
      if definition[:default] == true
        default = "default"
      else
        default = ""
      end
      
      TU.output_usage_line(command_key.to_s(), definition[:help], default)
    }
  end
  
  TU.write_header("Script Options", nil)
  
  @option_definitions.each{
    |option_key,definition|
    
    if definition[:hidden] == true
      next
    end
    
    if definition[:help].is_a?(Array)
      help = definition[:help].shift()
      additional_help = definition[:help]
    else
      help = definition[:help]
      additional_help = []
    end
    
    TU.output_usage_line(definition[:on].join(","),
      help, definition[:default], nil, additional_help.join("\n"))
  }
end

#initializeObject



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
# File 'lib/tungsten/script.rb', line 23

def initialize
  # A tracking variable that will be set to true when the object is fully
  # initizlied
  @initialized = false
  
  # Does this script required to run against an installed Tungsten directory
  @require_installed_directory = true
  
  # Should unparsed arguments cause an error
  @allow_unparsed_arguments = false
  
  # Definition of each command that this script will support
  @command_definitions = {}
  
  # The command, if any, the script should run
  @command = nil
  
  # Definition of each option that this script is expecting as input
  @option_definitions = {}
  
  # The command-line arguments of all options that have been defined
  # This is used to identify duplicate arguments
  @option_definition_arguments = {}
  
  # The collected option values from the script input
  @options = {}
  
  # Parameters loaded from INI files to be parsed
  @ini_parameters = []
  
  TU.debug("Begin #{$0} #{ARGV.join(' ')}")
  
  begin
    prepare_environment()
    configure()
    @option_definitions.each{
      |option_key,definition|
      if definition.has_key?(:default)
        opt(option_key, definition[:default])
      end
    }
  
    if TU.display_help?()
      display_help()
      cleanup(0)
    end
    
    # Load parameters from the available INI files
    load_ini_files()
    # Parse parameters loaded from the INI files and on command line
    parse_options()
    
    if @options[:autocomplete] == true
      display_autocomplete()
      cleanup(0)
    end
    
    unless TU.is_valid?()
      cleanup(1)
    end
    
    begin
      if script_log_path() != nil
        TU.set_log_path(script_log_path())
      end
    rescue => e
      TU.debug("Unable to set script log path")
      TU.debug(e)
    end
  
    TU.debug("Command: #{@command}")
    TU.debug("Options:")
    @options.each{
      |k,v|
      TU.debug("    #{k} => #{v}")
    }
  
    validate()
  
    unless TU.is_valid?()
      cleanup(1)
    end
    
    if @options[:validate] == true
      cleanup(0)
    end
  rescue => e
    TU.exception(e)
    cleanup(1)
  end
  
  @initialized = true
end

#initialized?Boolean

Returns:

  • (Boolean)


547
548
549
# File 'lib/tungsten/script.rb', line 547

def initialized?
  @initialized
end

#load_ini_filesObject



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
# File 'lib/tungsten/script.rb', line 233

def load_ini_files
  # If there is no script name then we cannot load INI files
  if script_name().to_s() == ""
    return
  end
  
  # Calculate the INI section name to use
  section_names = [script_name()]
  matches = script_name().to_s().match("tungsten_(.*)")
  if matches && matches.size() > 0
    script_ini_file = "#{matches[1]}.ini"
    section_names << matches[1]
  else
    script_ini_file = File.basename(script_name(), File.extname(script_name())) + ".ini"
    section_names << File.basename(script_name(), File.extname(script_name()))
  end
  
  load_ini_parameters("/etc/tungsten/scripts.ini", 
    section_names)
  
  if script_ini_file != nil
    load_ini_parameters("/etc/tungsten/#{script_ini_file}", 
      ["__anonymous__"] + section_names)
  end
  
  # Add these arguments to the beginging of the TungstenUtil stack
  # When the script processes command line options it will read these 
  # and then be overwritten by and command line options.
  TU.remaining_arguments = @ini_parameters + TU.remaining_arguments
end

#load_ini_parameters(file, section_name) ⇒ Object

Convert the parsed INI contents into the command line argument style



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
# File 'lib/tungsten/script.rb', line 265

def load_ini_parameters(file, section_name)
  unless File.exists?(file)
    return
  end
  
  unless section_name.is_a?(Array)
    section_name = [section_name]
  end
  section_name.delete_if{|n| n.to_s() == ""}
  
  if section_name.size() == 0
    return
  end
  
  parameters = TU.parse_ini_file(file, false)
  section_name.each{
    |section|
    if section.to_s() == ""
      next
    end
    
    unless parameters.has_key?(section)
      next
    end
    
    parameters[section].each{
      |line|
      # Single character parameters get a single dash
      if line.length() == 1
        @ini_parameters << "-#{line}"
      else
        @ini_parameters << "--#{line}"
      end
    }
  }
end

#nagios_critical(msg) ⇒ Object



575
576
577
578
# File 'lib/tungsten/script.rb', line 575

def nagios_critical(msg)
  puts "CRITICAL: #{msg}"
  cleanup(NAGIOS_CRITICAL)
end

#nagios_ok(msg) ⇒ Object



565
566
567
568
# File 'lib/tungsten/script.rb', line 565

def nagios_ok(msg)
  puts "OK: #{msg}"
  cleanup(NAGIOS_OK)
end

#nagios_warning(msg) ⇒ Object



570
571
572
573
# File 'lib/tungsten/script.rb', line 570

def nagios_warning(msg)
  puts "WARNING: #{msg}"
  cleanup(NAGIOS_WARNING)
end

#opt(option_key, value = nil) ⇒ Object



156
157
158
159
160
161
162
# File 'lib/tungsten/script.rb', line 156

def opt(option_key, value = nil)
  if value != nil
    @options[option_key] = value
  end
  
  return @options[option_key]
end

#opt_default(option_key, default_value) ⇒ Object

Set the value for option_key if it has not been set



165
166
167
168
169
170
171
# File 'lib/tungsten/script.rb', line 165

def opt_default(option_key, default_value)
  if opt(option_key) == nil
    opt(option_key, default_value)
  end
  
  opt(option_key)
end

#orig_validateObject



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 'lib/continuent-tools-core.rb', line 268

def validate
  if require_installed_directory?()
    if TI == nil
      raise "Unable to run #{$0} without the '--directory' argument pointing to an active Tungsten installation"
    else
      TI.inherit_path()
    end
  end
  
  unless allow_unparsed_arguments?()
    unless TU.remaining_arguments.size == 0
      TU.error("Unable to parse the following arguments: #{TU.remaining_arguments.join(' ')}")
    end
  end
  
  if require_command?() && @command_definitions.size() > 0 && @command == nil
    TU.error("A command was not given for this script. Valid commands are #{@command_definitions.keys().join(', ')} and must be the first argument.")
  end
  
  @option_definitions.each{
    |option_key,definition|
    
    if definition[:required] == true
      if opt(option_key).to_s() == ""
        arg = definition[:on][0].split(" ")[0]
        TU.error("Missing value for the #{arg} option")
      end
    end
  }
end

#parse_boolean_option(val) ⇒ Object



359
360
361
362
363
364
365
366
367
# File 'lib/tungsten/script.rb', line 359

def parse_boolean_option(val)
  if val == "true"
    true
  elsif val == "false"
    false
  else
    raise MessageError.new("Unable to parse value '#{val}' as a boolean")
  end
end

#parse_boolean_option_blank_is_false(val) ⇒ Object



381
382
383
384
385
386
387
388
389
390
391
# File 'lib/tungsten/script.rb', line 381

def parse_boolean_option_blank_is_false(val)
  if val == "true"
    true
  elsif val == "false"
    false
  elsif val.to_s() == ""
    false
  else
    raise MessageError.new("Unable to parse value '#{val}' as a boolean")
  end
end

#parse_boolean_option_blank_is_true(val) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
# File 'lib/tungsten/script.rb', line 369

def parse_boolean_option_blank_is_true(val)
  if val == "true"
    true
  elsif val == "false"
    false
  elsif val.to_s() == ""
    true
  else
    raise MessageError.new("Unable to parse value '#{val}' as a boolean")
  end
end

#parse_float_option(val) ⇒ Object



355
356
357
# File 'lib/tungsten/script.rb', line 355

def parse_float_option(val)
  val.to_f()
end

#parse_integer_option(val) ⇒ Object



346
347
348
349
350
351
352
353
# File 'lib/tungsten/script.rb', line 346

def parse_integer_option(val)
  v = val.to_i()
  unless v.to_s() == val
    raise MessageError.new("Unable to parse '#{val}' as an integer")
  end
  
  return v
end

#parse_optionsObject



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
# File 'lib/tungsten/script.rb', line 302

def parse_options
  opts = OptionParser.new()
  
  @option_definitions.each{
    |option_key,definition|
    
    args = definition[:on]
    if definition[:aliases] != nil && definition[:aliases].is_a?(Array)
      definition[:aliases].each{
        |arg_alias|
        args << arg_alias
      }
    end
    
    opts.on(*args) {
      |val|
              
      if definition[:parse] != nil
        begin
          val = definition[:parse].call(val)
          
          unless val == nil
            opt(option_key, val)
          end
        rescue MessageError => me
          TU.error(me.message())
        end
      else  
        opt(option_key, val)
      end
    }
  }
  
  TU.run_option_parser(opts)
  
  if @command_definitions.size() > 0 && TU.remaining_arguments.size() > 0
    if TU.remaining_arguments[0] != nil
      if @command_definitions.has_key?(TU.remaining_arguments[0].to_sym())
        @command = TU.remaining_arguments.shift()
      end
    end
  end
end

#prepareObject



117
118
# File 'lib/tungsten/script.rb', line 117

def prepare
end

#prepare_environmentObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/tungsten/script.rb', line 138

def prepare_environment
  target_umask = nil
  if TI != nil
    install_umask = TI.setting(TI.setting_key(HOSTS, "file_protection_umask"))
    if install_umask.to_s() != ""
      target_umask = install_umask.to_i(8)
    end
  else
    library_mode = sprintf("%o", File.stat(File.dirname(__FILE__)).mode)
    library_umask = 777 - library_mode[-3,3].to_i()
    target_umask = sprintf("%04d", library_umask).to_i(8)
  end
  
  if target_umask != nil
    File.umask(target_umask)
  end
end

#require_command?Boolean

Returns:

  • (Boolean)


531
532
533
# File 'lib/tungsten/script.rb', line 531

def require_command?
  true
end

#require_installed_directory?(v = nil) ⇒ Boolean

Returns:

  • (Boolean)


515
516
517
518
519
520
521
# File 'lib/tungsten/script.rb', line 515

def require_installed_directory?(v = nil)
  if (v != nil)
    @require_installed_directory = v
  end
  
  @require_installed_directory
end

#runObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/tungsten/script.rb', line 6

def run
  begin
    prepare()
    main()
  rescue CommandError => e
    TU.debug(e)
  rescue => e
    TU.exception(e)
  end
  
  if TU.is_valid?()
    cleanup(0)
  else
    cleanup(1)
  end
end

#script_log_pathObject



543
544
545
# File 'lib/tungsten/script.rb', line 543

def script_log_path
  nil
end

#script_nameObject



424
425
426
# File 'lib/tungsten/script.rb', line 424

def script_name
  nil
end

#set_option_default(option_key, default = nil) ⇒ Object



225
226
227
228
229
230
231
# File 'lib/tungsten/script.rb', line 225

def set_option_default(option_key, default = nil)
  unless @option_definitions.has_key?(option_key)
    raise "Unable to set option default for #{:option_key.to_s()} because the option is not defined."
  end
  
  @option_definitions[option_key][:default] = default
end

#sudo_prefixObject



580
581
582
# File 'lib/tungsten/script.rb', line 580

def sudo_prefix
  TI.sudo_prefix()
end

#validateObject



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
# File 'lib/tungsten/script.rb', line 393

def validate
  if require_installed_directory?()
    if TI == nil
      raise "Unable to run #{$0} without the '--directory' argument pointing to an active Tungsten installation"
    else
      TI.inherit_path()
    end
  end
  
  unless allow_unparsed_arguments?()
    unless TU.remaining_arguments.size == 0
      TU.error("Unable to parse the following arguments: #{TU.remaining_arguments.join(' ')}")
    end
  end
  
  if require_command?() && @command_definitions.size() > 0 && @command == nil
    TU.error("A command was not given for this script. Valid commands are #{@command_definitions.keys().join(', ')} and must be the first argument.")
  end
  
  @option_definitions.each{
    |option_key,definition|
    
    if definition[:required] == true
      if opt(option_key).to_s() == ""
        arg = definition[:on][0].split(" ")[0]
        TU.error("Missing value for the #{arg} option")
      end
    end
  }
end