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



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/tungsten/script.rb', line 154

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



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/tungsten/script.rb', line 174

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)


504
505
506
507
508
509
510
# File 'lib/tungsten/script.rb', line 504

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

#cleanup(code = 0) ⇒ Object



532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/tungsten/script.rb', line 532

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



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

def command
  @command
end

#configureObject



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

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



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

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

#display_autocompleteObject



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

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



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

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
# 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
    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)


528
529
530
# File 'lib/tungsten/script.rb', line 528

def initialized?
  @initialized
end

#load_ini_filesObject



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

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



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

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



556
557
558
559
# File 'lib/tungsten/script.rb', line 556

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

#nagios_ok(msg) ⇒ Object



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

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

#nagios_warning(msg) ⇒ Object



551
552
553
554
# File 'lib/tungsten/script.rb', line 551

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

#opt(option_key, value = nil) ⇒ Object



137
138
139
140
141
142
143
# File 'lib/tungsten/script.rb', line 137

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



146
147
148
149
150
151
152
# File 'lib/tungsten/script.rb', line 146

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



340
341
342
343
344
345
346
347
348
# File 'lib/tungsten/script.rb', line 340

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



362
363
364
365
366
367
368
369
370
371
372
# File 'lib/tungsten/script.rb', line 362

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



350
351
352
353
354
355
356
357
358
359
360
# File 'lib/tungsten/script.rb', line 350

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



336
337
338
# File 'lib/tungsten/script.rb', line 336

def parse_float_option(val)
  val.to_f()
end

#parse_integer_option(val) ⇒ Object



327
328
329
330
331
332
333
334
# File 'lib/tungsten/script.rb', line 327

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



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

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



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

def prepare
end

#require_command?Boolean

Returns:

  • (Boolean)


512
513
514
# File 'lib/tungsten/script.rb', line 512

def require_command?
  true
end

#require_installed_directory?(v = nil) ⇒ Boolean

Returns:

  • (Boolean)


496
497
498
499
500
501
502
# File 'lib/tungsten/script.rb', line 496

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



524
525
526
# File 'lib/tungsten/script.rb', line 524

def script_log_path
  nil
end

#script_nameObject



405
406
407
# File 'lib/tungsten/script.rb', line 405

def script_name
  nil
end

#set_option_default(option_key, default = nil) ⇒ Object



206
207
208
209
210
211
212
# File 'lib/tungsten/script.rb', line 206

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



561
562
563
# File 'lib/tungsten/script.rb', line 561

def sudo_prefix
  TI.sudo_prefix()
end

#validateObject



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

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