repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
earlino727/byebug
test/commands/var_test.rb
require 'test_helper' module Byebug # # Tests variable evaluation. # class VarTest < TestCase def program strip_line_numbers <<-EOC 1: module Byebug 2: # 3: # Toy class to test variable evaluation. 4: # 5: class #{example_class} 6: SOMECONST = 'foo' unless defined?(SOMECONST) 7: 8: def initialize 9: @instance_variable = '1' * 20 10: byebug 11: end 12: 13: def run(level) 14: [1, 2, 3].map do |i| 15: level * i 16: end 17: end 18: end 19: 20: v = #{example_class}.new 21: v.run(2) 22: end EOC end def test_var_args_shows_information_about_current_frame_arguments enter 'break 14', 'cont', 'var args' debug_code(program) check_output_includes 'level = 2' end def test_var_const_shows_constants_in_class_or_module enter "var const Byebug::#{example_class}" debug_code(program) check_output_includes 'SOMECONST = foo' end def test_var_const_shows_constants_in_current_scope_when_without_argument enter 'var const' debug_code(program) check_output_includes 'SOMECONST = foo' end def test_var_const_shows_error_if_given_object_is_not_a_class_or_module enter 'break 21', 'cont', 'var const v' debug_code(program) check_error_includes 'Should be Class/Module: v' end def test_var_instance_shows_instance_vars_of_an_object enter 'break 21', 'cont', 'var instance v' debug_code(program) check_output_includes '@instance_variable = "11111111111111111111"' end def test_var_global_shows_global_variables enter 'var global' debug_code(program) check_output_includes '$ERROR_INFO = nil' end def test_var_instance_shows_instance_variables_of_self_if_no_object_given enter 'var instance' debug_code(program) check_output_includes '@instance_variable = "11111111111111111111"' end def test_var_instance_cuts_long_variable_values_according_to_width_setting with_setting :width, 40 do enter 'var instance' debug_code(program) check_output_includes '@instance_variable = "111111111111111...' end end def test_var_local_shows_local_variables enter 'break 15', 'cont', 'var local' debug_code(program) check_output_includes 'i = 1', 'level = 2' end def test_var_all_shows_all_variables enter 'break 15', 'cont', 'var all' debug_code(program) check_output_includes '$ERROR_INFO = nil', '@instance_variable = "11111111111111111111"', 'level = 2' end end end
earlino727/byebug
test/post_mortem_test.rb
<gh_stars>1-10 require 'test_helper' module Byebug # # Tests post mortem functionality. # class PostMortemTest < TestCase def program strip_line_numbers <<-EOC 1: module Byebug 2: # 3: # Toy class to test post mortem functionality 4: # 5: class #{example_class} 6: def a 7: fail 'blabla' 8: end 9: end 10: 11: byebug 12: 13: c = #{example_class}.new 14: c.a 15: end EOC end def test_rises_before_exit_in_post_mortem_mode with_setting :post_mortem, true do enter 'cont' assert_raises(RuntimeError) { debug_code(program) } end end def test_post_mortem_mode_sets_post_mortem_flag_to_true with_setting :post_mortem, true do enter 'cont' begin debug_code(program) rescue RuntimeError assert_equal true, Byebug.post_mortem? end end end def test_execution_is_stopped_at_the_correct_line_after_exception skip('See issue #165') if RUBY_VERSION >= '2.2.4' with_setting :post_mortem, true do enter 'cont' begin debug_code(program) rescue assert_equal 7, Byebug.raised_exception.__bb_context.frame.line end end end def test_command_forbidden_in_post_mortem_mode with_post_mortem_processor do with_setting :post_mortem, true do enter 'help next' begin debug_code(program) rescue RuntimeError check_error_includes "Unknown command 'next'. Try 'help'" end end end end def test_command_permitted_in_post_mortem_mode with_post_mortem_processor do with_setting :post_mortem, true do enter 'help where' begin debug_code(program) rescue RuntimeError check_output_includes 'Displays the backtrace' end end end end private def with_post_mortem_processor old_processor = Context.processor Context.processor = PostMortemProcessor yield ensure Context.processor = old_processor end end end
earlino727/byebug
test/commands/restart_test.rb
<reponame>earlino727/byebug require 'test_helper' require 'rbconfig' module Byebug # # Tests restarting functionality. # class RestartTest < TestCase def test_restart_without_arguments_in_standalone_mode with_mode(:standalone) do with_command_line(example_path, '1') do assert_restarts( nil, "#{RbConfig.ruby} #{Context.bin_file} #{example_path} 1" ) end end end def test_restart_with_arguments_in_standalone_mode with_mode(:standalone) do with_command_line(example_path, '1') do assert_restarts( '2', "#{RbConfig.ruby} #{Context.bin_file} #{example_path} 2" ) end end end def test_restart_without_arguments_in_attached_mode with_mode(:attached) do with_command_line(example_path, '1') do assert_restarts(nil, "#{RbConfig.ruby} #{example_path} 1") end end end def test_restart_with_arguments_in_attached_mode with_mode(:attached) do with_command_line(example_path, '1') do assert_restarts(2, "#{RbConfig.ruby} #{example_path} 2") end end end private def assert_restarts(arg, expected_cmd_line) assert_calls(Kernel, :exec, expected_cmd_line) do enter ['restart', arg].compact.join(' ') debug_code(minimal_program) check_output_includes "Re exec'ing:" end end end end
earlino727/byebug
test/commands/list_test.rb
<gh_stars>1-10 require 'test_helper' module Byebug # # Tests for listing source files. # class ListTest < TestCase def program strip_line_numbers <<-EOC 1: module Byebug 2: # 3: # Toy class to test breakpoints 4: # 5: class #{example_class} 6: def build_percentage_string 7: '%1' 8: end 9: end 10: 11: byebug 12: 13: str = #{example_class}.new.build_percentage_string 14: 15: str 16: end EOC end def test_lists_source_code_lines with_setting :listsize, 3 do enter 'list' debug_code(program) check_output_includes "[12, 14] in #{example_path}" end end def test_listsize_is_not_set_if_parameter_is_not_an_integer with_setting :listsize, 3 do enter 'set listsize 5.0', 'list' debug_code(program) check_output_doesnt_include "[11, 15] in #{example_path}" end end def test_does_not_list_before_the_beginning_of_file with_setting :listsize, 15 do enter 'cont 7', 'list' debug_code(program) check_output_includes "[1, 15] in #{example_path}" end end def test_does_not_list_after_the_end_of_file with_setting :listsize, 13 do enter 'list' debug_code(program) check_output_includes "[4, 16] in #{example_path}" end end def test_lists_the_whole_file_if_number_of_lines_is_smaller_than_listsize with_setting :listsize, 17 do enter 'list' debug_code(program) check_output_includes "[1, 16] in #{example_path}" end end def test_lists_forwards_after_the_second_call_to_list with_setting :listsize, 3 do enter 'cont 7', 'list', 'list' debug_code(program) check_output_includes "[9, 11] in #{example_path}" end end def test_lists_surrounding_lines_after_the_first_call_to_list_minus with_setting :listsize, 3 do enter 'list-' debug_code(program) check_output_includes "[12, 14] in #{example_path}" end end def test_lists_backwards_after_the_second_call_to_list_minus with_setting :listsize, 3 do enter 'list-', 'list-' debug_code(program) check_output_includes "[9, 11] in #{example_path}" end end def test_lists_backwards_from_end_of_file with_setting :listsize, 3 do enter 'list 14-16', 'list -' debug_code(program) check_output_includes "[11, 13] in #{example_path}" end end def test_lists_surrounding_lines_when_list_equals_is_called with_setting :listsize, 3 do enter 'list =' debug_code(program) check_output_includes "[12, 14] in #{example_path}" end end def test_lists_specific_range_when_requested_in_hyphen_format enter 'list 6-8' debug_code(program) check_output_includes "[6, 8] in #{example_path}" end def test_lists_specific_range_when_requested_in_comma_format enter 'list 6,8' debug_code(program) check_output_includes "[6, 8] in #{example_path}" end def test_lists_nothing_if_unexistent_range_is_specified enter 'list 20,25' debug_code(program) check_error_includes '"List" argument "20" needs to be at most 16' check_output_doesnt_include "[20, 25] in #{example_path}" end def test_lists_nothing_if_invalid_range_is_specified enter 'list 5,4' debug_code(program) check_error_includes 'Invalid line range' check_output_doesnt_include "[5, 4] in #{example_path}" end def test_list_proper_lines_when_range_around_specific_line_with_hyphen with_setting :listsize, 3 do enter 'list 4-' debug_code(program) check_output_includes "[3, 5] in #{example_path}" end end def test_list_proper_lines_when_range_around_specific_line_with_comma with_setting :listsize, 3 do enter 'list 4,' debug_code(program) check_output_includes "[3, 5] in #{example_path}" end end def test_correctly_print_lines_containing_the_percentage_symbol enter 'list 7' debug_code(program) check_output_includes(/7:\s+'%1'/) end def test_shows_error_when_invoked_with_invalid_syntax enter 'list rdfe87' debug_code(program) check_error_includes(/needs to be a number/) end def test_gives_back_a_prompt_when_invoked_with_invalid_syntax enter 'list rdfe87' debug_code(program) { assert_equal 13, frame.line } end def replace_build_percentage_string_line_and_list_it cmd_after_replace(example_path, 7, " '%11'", 'list 7-7') end def test_lists_file_changes skip enter -> { replace_build_percentage_string_line_and_list_it } debug_code(program) check_output_includes(/7:\s+'%11'/) end end end
earlino727/byebug
script/minitest_runner.rb
#!/usr/bin/env ruby $LOAD_PATH << File.expand_path(File.join('..', 'lib'), __dir__) $LOAD_PATH << File.expand_path(File.join('..', 'test'), __dir__) require 'minitest' # # Helper class to aid running minitest # class MinitestRunner def initialize @test_suites = extract_from_argv { |cmd_arg| test_suite?(cmd_arg) } end def run test_suites.each { |f| require File.expand_path(f) } flags = ["--name=/#{filtered_methods.join('|')}/", ENV['TESTOPTS']] Minitest.run(flags + ARGV) end private def runnables Minitest::Runnable.runnables end def test_suite?(str) all_test_suites.include?(str) end def test_suites return all_test_suites if @test_suites.empty? @test_suites end def test_methods(str) if str =~ /test_.*/ normalize(str) elsif str =~ /.*#test_.*/ [str] else expand(str) end end def normalize(str) runnables.each do |runnable| return "#{runnable}##{str}" if runnable.runnable_methods.include?(str) end end def expand(str) runnables.each do |runnable| return runnable.runnable_methods if "Byebug::#{runnable}" == str end end def filtered_methods @filtered_methods ||= extract_from_argv { |cmd_arg| test_methods(cmd_arg) } end def all_test_suites Dir.glob('test/**/*_test.rb') end def extract_from_argv matching, non_matching = ARGV.partition { |arg| yield(arg) } ARGV.replace(non_matching) matching end end exit(MinitestRunner.new.run) if $PROGRAM_NAME == __FILE__
earlino727/byebug
test/support/coverage.rb
# # Starts code coverage tracking. # def start_coverage_tracking require 'simplecov' SimpleCov.add_filter 'test' SimpleCov.start end start_coverage_tracking if ENV['NOCOV'].nil?
earlino727/byebug
test/support/temporary.rb
<gh_stars>1-10 module Byebug # # Some custom matches for changing stuff temporarily during tests # module TestTemporary # # Yields a block using temporary values for command line program name and # command line arguments. # # @param program_name [String] New value for the program name # @param *args [Array] New value for the program arguments # def with_command_line(program_name, *args) original_program_name = $PROGRAM_NAME original_argv = $ARGV $PROGRAM_NAME = program_name $ARGV.replace(args) yield ensure $PROGRAM_NAME = original_program_name $ARGV.replace(original_argv) end # # Yields a block using a specific mode of the debugger # def with_mode(mode) old_mode = Byebug.mode Byebug.mode = mode yield ensure Byebug.mode = old_mode end # # Yields a block using a temporary value for a setting # # @param key [Symbol] Setting key # @param value [Object] Temporary value for the setting # def with_setting(key, value) original_value = Setting[key] Setting[key] = value yield ensure Setting[key] = original_value end # # Temporary creates a new file a yields it to the passed block # def with_new_tempfile(content) file = Tempfile.new('foo') file.write(content) file.close yield(file.path) ensure file.close file.unlink end # # Changes global rc file to have specific contents, runs the block and # restores the old config afterwards. # def with_init_file(content) old_init_file = Byebug.init_file Byebug.init_file = '.byebug_test_rc' with_new_file(File.expand_path('.byebug_test_rc'), content) do yield end ensure Byebug.init_file = old_init_file end # # Creates a file, yields the block and deletes the file afterwards # # @param name [String] Name for the file # @param content [String] Content for the file # def with_new_file(name, content) File.open(name, 'w') { |f| f.write(content) } yield ensure File.delete(name) end # # Runs the block with a temporary value for an ENV variable # # @param key [String] Name for the key in the ENV hash # @param vlaue [String] Value of the key in the ENV hash # def with_env(key, value) old_value = ENV[key] ENV[key] = value yield ensure ENV[key] = old_value end end end
earlino727/byebug
test/test_helper.rb
require 'support/coverage' require 'support/test_case' Byebug::TestCase.before_suite
earlino727/byebug
test/support/utils.rb
<filename>test/support/utils.rb require 'support/matchers' require 'support/temporary' module Byebug # # Misc tools for the test suite # module TestUtils include TestMatchers include TestTemporary # # Adds commands to the input queue, so they will be later retrieved by # Processor, i.e., it emulates user's input. # # If a command is a Proc object, it will be executed before being retrieved # by Processor. May be handy when you need build a command depending on the # current context. # # @example # # enter 'b 12', 'cont' # enter 'b 12', ->{ "disable #{breakpoint.id}" }, 'cont' # def enter(*messages) interface.input.concat(messages) end # # Runs the code block passed as a string. # # The string is copied to a new file and then that file is run. This is # done, instead of using `instance_eval` or similar techniques, because # it's useful to load a real file in order to make assertions on backtraces # or file names. # # @param program String containing Ruby code to be run. This string could # be any valid Ruby code, but in order to avoid redefinition warnings in # the test suite, it should define at most one class inside the Byebug # namespace. The name of this class is defined by the +example_class+ # method. # # @param &block Optional proc which will be executed when Processor # extracts all the commands from the input queue. You can use that for # making assertions on the current test. If you specified the block and it # was never executed, the test will fail. # # @example # # enter 'next' # prog <<-EOC # byebug # puts 'hello' # EOC # # debug_code(prog) { assert_equal 3, frame.line } # def debug_code(program, &block) interface.test_block = block debug_in_temp_file(program) interface.test_block.call if interface.test_block end # # Writes a string containing Ruby code to a file and then debugs that file. # # @param program [String] Ruby code to be debugged # def debug_in_temp_file(program) example_file.write(program) example_file.close load(example_path) end # # Strips line numbers from a here doc containing ruby code. # # @param str_with_ruby_code A here doc containing lines of ruby code, each # one labeled with a line number # # @example # # strip_line_numbers <<-EOF # 1: puts 'hello' # 2: puts 'bye' # EOF # # returns # # puts 'hello' # puts 'bye' # def strip_line_numbers(str_with_ruby_code) str_with_ruby_code.gsub(/ *\d+: ? ?/, '') end # # Split a string (normally a here doc containing byebug's output) into # stripped lines # # @param output_str [String] # # @example # # split_lines <<-EOF # Sample command # # It does an amazing thing. # EOF # # returns # # ['Sample command', 'It does an amazing thing.'] # def split_lines(output_str) output_str.split("\n").map(&:strip) end # # Prepares a string to get feed to an assertion accepting arrays of # Regexp's. The string is split into lines and each of them is converted to # a regexp, properly escaping it and ignoring whitespace. # # @param output_str [String] # def prepare_for_regexp(output_str) split_lines(output_str).map do |str| Regexp.new(Regexp.escape(str), Regexp::EXTENDED) end end # # Shortcut to Byebug's interface # def interface Context.interface end # # Shortcut to Byebug's context # def context Byebug.current_context end # # Shortcut to current frame # def frame context.frame end # # Removes all (both enabled and disabled) displays # def clear_displays loop do break if Byebug.displays.empty? Byebug.displays.pop end end # # Remove +const+ from +klass+ without a warning # def force_remove_const(klass, const) klass.send(:remove_const, const) if klass.const_defined?(const) end # # Modifies a line number in a file with new content. # # @param filename File to be changed # @param lineno Line number to be changed # @param new_line New line content # def change_line(file, lineno, new_line) lines = File.readlines(file).tap { |c| c[lineno - 1] = "#{new_line}\n" } File.open(file, 'w') { |f| f.write(lines.join) } end # # Replaces line number <lineno> in file <file> with content <content> # # @param lineno Line number of line to be replaced. # @param file File containing the line to be replaced. # @param content New content for the line. # @param cmd Command to be run right after changing the line. # def cmd_after_replace(file, lineno, content, cmd) change_line(file, lineno, content) cmd end # # A minimal program that gives you a byebug's prompt # def minimal_program <<-EOM module Byebug byebug 'Hello world' end EOM end end end
earlino727/byebug
test/commands/disable_test.rb
require 'test_helper' module Byebug # # Tests disabling breakpoints. # class DisableTest < TestCase def program strip_line_numbers <<-EOC 1: module Byebug 2: # 3: # Toy class to test breakpoints 4: # 5: class #{example_class} 6: def self.a(num) 7: num + 1 8: end 9: 10: def b 11: 3 12: end 13: end 14: 15: y = 3 16: 17: byebug 18: 19: z = 5 20: 21: #{example_class}.new.b 22: #{example_class}.a(y + z) 23: end EOC end def test_disable_all_breakpoints_sets_all_enabled_flags_to_false enter 'break 21', 'break 22', 'disable breakpoints' debug_code(program) do assert_equal false, Breakpoint.first.enabled? assert_equal false, Breakpoint.last.enabled? end end def test_disable_all_breakpoints_shows_success_messages_for_all_breakpoints enter 'break 21', 'break 22', 'disable breakpoints' debug_code(program) check_output_includes(/Breakpoint #{Breakpoint.first.id} disabled/, /Breakpoint #{Breakpoint.last.id} disabled/) end def test_disable_all_breakpoints_ignores_all_breakpoints enter 'break 21', 'break 22', 'disable breakpoints', 'cont' debug_code(program) check_output_doesnt_include 'Stopped by breakpoint' end def test_disable_specific_breakpoints_sets_enabled_to_false enter 'b 21', 'b 22', -> { "disable breakpoints #{Breakpoint.first.id}" } debug_code(program) { assert_equal false, Breakpoint.first.enabled? } end def test_disable_specific_breakpoints_shows_success_message enter 'break 21', 'break 22', -> { "disable breakpoints #{Breakpoint.first.id}" } debug_code(program) check_output_includes(/Breakpoint #{Breakpoint.first.id} disabled/) end def test_disable_specific_breakpoints_properly_ignores_them enter 'break 21', 'break 22', -> { "disable breakpoints #{Breakpoint.first.id}" }, 'cont' debug_code(program) { assert_equal 22, frame.line } end def test_disable_with_an_incorrect_breakpoint_number_shows_error enter 'break 21', 'break 22', -> { "disable breakpoints #{Breakpoint.last.id + 1}" } debug_code(program) assert_equal 1, interface.error.size check_error_includes(/"disable breakpoints" argument/) end def test_disable_without_an_argument_shows_help enter 'disable' debug_code(program) check_output_includes 'Disables breakpoints or displays' end end end
Innarticles/spree_simple_weight_calculator
lib/spree_simple_weight_calculator.rb
<filename>lib/spree_simple_weight_calculator.rb require 'spree_core' require 'spree_simple_weight_calculator/engine'
Innarticles/spree_simple_weight_calculator
spec/models/spree/calculator/shipping/item_weight_spec.rb
<reponame>Innarticles/spree_simple_weight_calculator<filename>spec/models/spree/calculator/shipping/item_weight_spec.rb require 'spec_helper' module Spree module Calculator::Shipping describe ItemWeight do options = { preferred_costs_string: "0.5:5\n1:10\n50:20\n100:50.3", preferred_handling_max: 120, preferred_handling_fee: 21.5, preferred_max_item_size: 35, preferred_default_weight: 1 } let(:calculator) { Calculator::Shipping::ItemWeight.new(options) } let(:inventory_unit) { Struct.new(:line_item, :variant) } let(:variant1) { double("Variant", calculator_weight: 5, width: 1, depth: 1, height: 1, price: 4) } let(:variant2) { double("Variant", calculator_weight: 10, width: 1, depth: 1, height: 1, price: 6) } let(:variant3) { double("Variant", calculator_weight: 0.0, width: 1, depth: 1, height: 1, price: 10) } let(:package) { double(Stock::Package, order: mock_model(Order), contents: [ Stock::ContentItem.new(inventory_unit.new(1, variant1)), Stock::ContentItem.new(inventory_unit.new(1, variant1)), Stock::ContentItem.new(inventory_unit.new(1, variant1)), Stock::ContentItem.new(inventory_unit.new(1, variant1)), Stock::ContentItem.new(inventory_unit.new(2, variant2)), Stock::ContentItem.new(inventory_unit.new(2, variant2)), Stock::ContentItem.new(inventory_unit.new(2, variant2)), Stock::ContentItem.new(inventory_unit.new(2, variant2)), Stock::ContentItem.new(inventory_unit.new(2, variant2)), Stock::ContentItem.new(inventory_unit.new(2, variant2)) ]) } let(:package2) { double(Stock::Package, order: mock_model(Order), contents: [ Stock::ContentItem.new(inventory_unit.new(1, variant3)) ])} it "correctly select the default weight shipping price when no weight on the variant", :focus => true do calculator.available?(package2).should == true calculator.compute_package(package2).should == 31.5 # 10 shipping + 21.5 handling end it "correctly calculates shipping when handling fee applies" do calculator.available?(package).should == true calculator.compute_package(package).should == 221.5 # 200 cost + 21.5 handling end it "correctly calculates shipping when handling fee does not apply" do calculator.stub(preferred_handling_max: 10) calculator.available?(package).should == true calculator.compute_package(package).should == 200 end it "does not apply to overweight order" do variant1.stub(calculator_weight: 100) calculator.available?(package).should == false end it "does not apply to order with oversize items" do variant1.stub(depth: 100) calculator.available?(package).should == false end it "does not apply with invalid costs string" do calculator.stub(preferred_costs_string: "") calculator.available?(package).should == false calculator.stub(preferred_costs_string: "20:") calculator.available?(package).should == false calculator.stub(preferred_costs_string: "50=20") calculator.available?(package).should == false calculator.stub(preferred_costs_string: "abc:dfg\nerge:67") calculator.available?(package).should == false end it "correctly calculates shipping when costs string has useless spaces and newlines" do calculator.stub(:preferred_costs_string => %q{50:20 100:50.3 }) calculator.available?(package).should == true calculator.compute_package(package).should == 221.5 end end end end
Innarticles/spree_simple_weight_calculator
app/models/spree/variant_decorator.rb
module Spree Variant.class_eval do # you can add custom weight logic here def calculator_weight weight end end end
Innarticles/spree_simple_weight_calculator
app/models/spree/calculator/shipping/simple_weight.rb
module Spree module Calculator::Shipping class SimpleWeight < ShippingCalculator preference :costs_string, :text, default: "1:5\n2:7\n5:10\n10:15\n100:50" preference :default_weight, :decimal, default: 1 preference :max_item_size, :decimal, default: 0 preference :handling_fee, :decimal, default: 0 preference :handling_max, :decimal, default: 0 def self.description Spree.t(:simple_weight) end def self.register super end def available?(package) return false if !costs_string_valid? || order_overweight?(package.contents) if preferred_max_item_size > 0 package.contents.each do |item| return false if item_oversized?(item) end end true end def compute_package(package) content_items = package.contents line_items_total = total(content_items) handling_fee = preferred_handling_max > line_items_total ? preferred_handling_fee : 0 total_weight = total_weight(content_items) costs = costs_string_to_hash(clean_costs_string) weight_class = costs.keys.select { |w| total_weight <= w }.min shipping_costs = costs[weight_class] shipping_costs ? shipping_costs + handling_fee : 0 end private def clean_costs_string preferred_costs_string.strip end def costs_string_valid? !clean_costs_string.empty? && clean_costs_string.count(':') > 0 && clean_costs_string.split(/\:|\n/).size.even? && clean_costs_string.split(/\:|\n/).all? { |s | s.strip.match(/^\d|\.+$/) } end def item_oversized?(item) return false if preferred_max_item_size == 0 variant = item.variant sizes = [ variant.width || 0, variant.depth || 0, variant.height || 0 ] sizes.max > preferred_max_item_size end def order_overweight?(content_items) total_weight = total_weight(content_items) hash = costs_string_to_hash(clean_costs_string) total_weight > hash.keys.max end def costs_string_to_hash(costs_string) costs = {} costs_string.split.each do |cost_string| values = cost_string.strip.split(':') costs[values[0].strip.to_f] = values[1].strip.to_f end costs end def total_weight(contents) weight = 0 contents.each do |item| item_weight = item.variant.calculator_weight > 0.0 ? item.variant.calculator_weight : preferred_default_weight weight += item.quantity * item_weight end weight end end end end
Innarticles/spree_simple_weight_calculator
app/models/spree/calculator/shipping/item_weight.rb
<reponame>Innarticles/spree_simple_weight_calculator module Spree module Calculator::Shipping class ItemWeight < SimpleWeight preference :costs_string, :text, default: "25:7\n50:15\n100:25\n9999:45" def self.description Spree.t(:item_weight) end def compute_package(package) content_items = package.contents line_items_total = total(content_items) handling_fee = preferred_handling_max > line_items_total ? preferred_handling_fee : 0.0 costs = costs_string_to_hash(clean_costs_string) shipping_costs = 0.0 content_items.each do |item| item_weight = item.variant.calculator_weight > 0.0 ? item.variant.calculator_weight : preferred_default_weight weight_class = costs.keys.select { |w| item_weight <= w }.min shipping_costs += costs[weight_class] * item.quantity end shipping_costs + handling_fee end end end end
clampz/edurange
app/models/subnet.rb
class Subnet < ActiveRecord::Base include Provider include Aws include Cidr belongs_to :cloud has_many :instances, dependent: :destroy has_one :user, through: :cloud validates :name, presence: true, uniqueness: { scope: :cloud, message: "name already taken" } validates_presence_of :cidr_block, :cloud validate :cidr_validate, :internet_validate, :validate_stopped after_destroy :update_scenario_modified before_destroy :validate_stopped, prepend: true def validate_stopped if not self.stopped? errors.add(:running, "can not modify while subnet is booted") return false end if self.scenario.modifiable? self.scenario.update_attribute(:modified, true) end true end def independent_destroy if self.instances.size > 0 errors.add(:dependents, "must not have any instances") return false end self.destroy true end def update_scenario_modified if self.scenario.modifiable? self.scenario.update_attribute(:modified, true) end true end def internet_validate if not self.internet_accessible self.instances.each do |instance| if instance.internet_accessible errors.add(:internet_accessible, "If subnet is not internet accessible then #{instance.name} should be the same") end end end end def cidr_validate return unless self.cidr_block # Check for valid CIDR if IPAddress.valid_ipv4?(self.cidr_block.split('/')[0]) mask = self.cidr_block.split('/')[1] if not mask errors.add(:cidr_block, "Need a subnet mask") return elsif not /^\d*\d$/.match(mask) errors.add(:cidr_block, "Subnet mask is invalid!") return elsif not (mask.to_i >= MAX_CLOUD_CIDR_BLOCK and mask.to_i <= MIN_CLOUD_CIDR_BLOCK) errors.add(:cidr_block, "Subnet mask must be between #{MAX_CLOUD_CIDR_BLOCK} - #{MIN_CLOUD_CIDR_BLOCK}") return end else # Not an IP at all? Generic error! Whoo! errors.add(:cidr_block, "IP section is invalid!") return end # Check that CIDR is a subset of its cloud CIDR ord = NetAddr::CIDR.create(self.cidr_block) <=> self.cloud.cidr_block if ord == -1 self.errors.add(:cidr_block, "Subnets CIDR block is not with its clouds CIDR block") return end # Check that CIDR contains all subnet self.cloud.subnets.select{ |s| s != self }.each do |subnet| if NetAddr::CIDR.create(self.cidr_block).cmp(subnet.cidr_block) != nil self.errors.add(:cidr_block, "CIDR block must not overlap with subnet #{subnet.name} #{subnet.cidr_block}") return end end # Check that all instances are within subnet self.instances.each do |instance| if NetAddr::CIDR.create(self.cidr_block).cmp(instance.ip_address) != 1 self.errors.add(:cidr_block, "CIDR does not contain instance #{instance.name} #{instance.ip_address}") end end true end def bootable? return (self.stopped? and self.cloud.booted?) end def unbootable? return (self.booted? or self.boot_failed? or self.unboot_failed?) end def add_progress(val) # debug "Adding progress to subnet" # PrivatePub.publish_to "/scenarios/#{self.cloud.scenario.id}", subnet_progress: val end def owner?(id) return self.cloud.scenario.user_id == id end def debug(message) log = self.log ? self.log : '' message = '' if !message self.update_attribute(:log, log + message + "\n") end def scenario return self.cloud.scenario end def instances_booting? return self.instances.select{ |i| (i.booting? or i.queued_boot?) }.any? end def instances_unbooting? return self.instances.select{ |i| (i.unbooting? or i.queued_unboot?) }.any? end def instances_boot_failed? return self.instances.select{ |i| i.boot_failed? }.any? end def instances_unboot_failed? return self.instances.select{ |i| i.unboot_failed? }.any? end def instances_booted? return self.instances.select{ |i| i.booted? }.any? end def instances_active? return self.instances.select{ |i| i.driver_id != nil }.any? end def instances_stopped? self.instances.select{ |i| not i.stopped? }.size == 0 end end
clampz/edurange
app/controllers/instructor_controller.rb
<reponame>clampz/edurange class InstructorController < ApplicationController before_action :authenticate_instructor before_action :set_student_group, only: [:student_group_destroy] def index @players = Player.where(user_id: current_user.id) end def student_group_create @user = User.find(current_user.id) @student_group = @user.student_groups.new(name: params[:name]) @student_group.save respond_to do |format| format.js { render 'instructor/student_group_create.js.erb', :layout => false } end end def student_group_destroy @student_group.destroy respond_to do |format| format.js { render 'instructor/student_group_delete.js.erb', :layout => false } end end def student_group_user_add user = User.find(params[:user_id]) @student_group_user = nil if @student_group = @user.student_groups.find_by_name(params[:student_group_name]) @student_group_user = @student_group.user_add(user) end respond_to do |format| format.js { render 'instructor/student_group_user_add.js.erb', :layout => false } end end def student_group_user_remove @student_group_user = StudentGroupUser.find(params[:student_group_user_id]) if @student_group_user.student_group.user == User.find(current_user.id) @student_group_user.destroy end respond_to do |format| format.js { render 'instructor/student_group_user_remove.js.erb', :layout => false } end end private def set_student_group @student_group = StudentGroup.find(params[:student_group_id]) if not User.find(current_user.id).owns? @student_group head :ok, content_type: "text/html" return end end end
clampz/edurange
app/models/recipe.rb
<reponame>clampz/edurange class Recipe < ActiveRecord::Base belongs_to :scenario has_many :role_recipes, dependent: :destroy has_one :user, through: :scenario validates :name, presence: true, uniqueness: { scope: :scenario, message: "Name taken" } after_create :set_custom after_save :update_scenario_modified after_destroy :update_scenario_modified def update_scenario_modified if self.scenario.modifiable? self.scenario.update(modified: true) end end def instances_stopped? self.scenario.instances.each do |instance| if not instance.stopped? instance.roles.each do |role| if role.recipes.select{ |recipe| recipe == self }.size > 0 return false end end end end true end def path if self.custom? return "#{self.scenario.path_recipes}/#{self.name.filename_safe}.rb" end "#{Settings.app_path}/scenarios/recipes/#{self.name.downcase}.rb.erb" end def set_custom if File.exists? "#{Settings.app_path}/scenarios/recipes/#{self.name.downcase}.rb.erb" self.custom = false else self.custom = true if not File.exists? self.path FileUtils.touch self.path end end self.save end def text File.read(self.path) end def text_update(text) if self.custom f = File.open(self.path, "w") f.write(text) f.close end end end
clampz/edurange
app/controllers/admin_controller.rb
<filename>app/controllers/admin_controller.rb class AdminController < ApplicationController before_action :authenticate_admin before_action :set_student_group, only: [:student_group_destroy] def index @instructors = User.where role: 3 @students = User.where role: 4 end def instructor_create name = params[:name] == '' ? nil : params[:name] @user = User.new(email: params[:email], name: name, organization: params[:organization]) password = <PASSWORD>[0..15] @user.password = password @user.save if not @user.errors.any? @user.set_instructor_role @user.email_credentials(password) end respond_to do |format| format.js { render 'admin/js/instructor_create.js.erb', :layout => false } end end def reset_password @user = User.find(params[:id]) password = <PASSWORD>] @user.password = password @user.save if not @user.errors.any? @user.email_credentials(password) end respond_to do |format| format.js { render 'admin/js/reset_password.js.erb', :layout => false } end end def user_delete if @user = User.find(params[:id]) if @user != User.find(current_user.id) @user.destroy end end respond_to do |format| format.js { render 'admin/js/user_delete.js.erb', :layout => false } end end def student_to_instructor if @user = User.find(params[:id]) if not @user.is_student? @user.errors.add(:email, "User is not a student") else @user.student_to_instructor end end respond_to do |format| format.js { render 'admin/js/student_to_instructor.js.erb', :layout => false } end end def student_add_to_all if @user = User.find(params[:id]) if not @user.is_student? @user.errors.add(:email, "User is not a student") else @student_group, @student_group_user = User.find(current_user.id).student_add_to_all(@user) end end respond_to do |format| format.js { render 'admin/js/student_add_to_all.js.erb', :layout => false } end end def instructor_to_student if @user = User.find(params[:id]) if not @user.is_instructor? @user.errors.add(:email, "User is not a student") else @student_group, @student_group_user = @user.instructor_to_student(User.find(current_user.id)) end end respond_to do |format| format.js { render 'admin/js/instructor_to_student.js.erb', :layout => false } end end def student_group_create @user = User.find(current_user.id) @student_group = @user.student_groups.new(name: params[:name]) @student_group.save respond_to do |format| format.js { render 'admin/js/student_group_create.js.erb', :layout => false } end end def student_group_destroy @student_group.destroy respond_to do |format| format.js { render 'admin/js/student_group_delete.js.erb', :layout => false } end end def student_group_user_add user = User.find(params[:user_id]) @student_group_user = nil if @student_group = @user.student_groups.find_by_name(params[:student_group_name]) @student_group_user = @student_group.user_add(user) end respond_to do |format| format.js { render 'admin/js/student_group_user_add.js.erb', :layout => false } end end def student_group_user_remove @student_group_user = StudentGroupUser.find(params[:student_group_user_id]) if @student_group_user.student_group.user == User.find(current_user.id) @student_group_user.destroy end respond_to do |format| format.js { render 'admin/js/student_group_user_remove.js.erb', :layout => false } end end private def set_student_group @student_group = StudentGroup.find(params[:student_group_id]) if not User.find(current_user.id).owns? @student_group head :ok, content_type: "text/html" return end end end
clampz/edurange
db/schema.rb
<filename>db/schema.rb # encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20151115234353) do create_table "answers", force: :cascade do |t| t.boolean "correct" t.integer "question_id" t.datetime "created_at" t.datetime "updated_at" t.string "text" t.text "text_essay" t.text "comment" t.integer "value_index" t.string "essay_points_earned" t.integer "user_id" end add_index "answers", ["question_id"], name: "index_answers_on_question_id" create_table "clouds", force: :cascade do |t| t.string "name" t.string "cidr_block" t.string "driver_id" t.integer "scenario_id" t.datetime "created_at" t.datetime "updated_at" t.integer "status", default: 0 t.string "log", default: "" end add_index "clouds", ["scenario_id"], name: "index_clouds_on_scenario_id" create_table "delayed_jobs", force: :cascade do |t| t.integer "priority", default: 0, null: false t.integer "attempts", default: 0, null: false t.text "handler", null: false t.text "last_error" t.datetime "run_at" t.datetime "locked_at" t.datetime "failed_at" t.string "locked_by" t.string "queue" t.datetime "created_at" t.datetime "updated_at" end add_index "delayed_jobs", ["priority", "run_at"], name: "delayed_jobs_priority" create_table "groups", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" t.integer "scenario_id" t.text "instructions", default: "" end create_table "instance_groups", force: :cascade do |t| t.integer "group_id" t.integer "instance_id" t.boolean "administrator" t.datetime "created_at" t.datetime "updated_at" end add_index "instance_groups", ["group_id"], name: "index_instance_groups_on_group_id" add_index "instance_groups", ["instance_id"], name: "index_instance_groups_on_instance_id" create_table "instance_roles", force: :cascade do |t| t.integer "instance_id" t.integer "role_id" t.datetime "created_at" t.datetime "updated_at" end add_index "instance_roles", ["instance_id"], name: "index_instance_roles_on_instance_id" add_index "instance_roles", ["role_id"], name: "index_instance_roles_on_role_id" create_table "instances", force: :cascade do |t| t.string "name" t.string "ip_address" t.string "driver_id" t.string "cookbook_url" t.string "os" t.boolean "internet_accessible" t.integer "subnet_id" t.datetime "created_at" t.datetime "updated_at" t.integer "status", default: 0 t.string "scoring_url" t.string "scoring_page" t.string "uuid" t.string "com_page" t.string "log", default: "" t.string "bash_history_page", default: "" t.string "exit_status_page", default: "" t.string "script_log_page", default: "" end add_index "instances", ["subnet_id"], name: "index_instances_on_subnet_id" create_table "players", force: :cascade do |t| t.string "login" t.string "password" t.integer "group_id" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" t.integer "student_group_id" end add_index "players", ["group_id"], name: "index_players_on_group_id" create_table "questions", force: :cascade do |t| t.integer "scenario_id" t.datetime "created_at" t.datetime "updated_at" t.integer "order" t.string "text" t.string "type_of" t.string "options", default: "--- []\n" t.string "values" t.integer "points" t.integer "points_penalty" end add_index "questions", ["scenario_id"], name: "index_questions_on_scenario_id" create_table "recipes", force: :cascade do |t| t.integer "scenario_id" t.string "name" t.boolean "custom" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "role_recipes", force: :cascade do |t| t.integer "role_id" t.integer "recipe_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "role_recipes", ["recipe_id"], name: "index_role_recipes_on_recipe_id" add_index "role_recipes", ["role_id"], name: "index_role_recipes_on_role_id" create_table "roles", force: :cascade do |t| t.string "name" t.string "packages" t.datetime "created_at" t.datetime "updated_at" t.integer "scenario_id" end create_table "scenarios", force: :cascade do |t| t.string "name" t.string "description" t.datetime "created_at" t.datetime "updated_at" t.integer "status", default: 0 t.text "log", default: "" t.string "answers", default: "" t.string "uuid" t.string "scoring_pages" t.string "answers_url" t.text "scoring_pages_content", default: "" t.integer "user_id" t.string "com_page" t.boolean "modified", default: false t.text "instructions", default: "" t.text "instructions_student", default: "" t.integer "location", default: 0 t.boolean "modifiable", default: false end create_table "statistics", force: :cascade do |t| t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "bash_histories", default: "" t.text "bash_analytics", default: "--- []\n" t.string "scenario_name" t.datetime "scenario_created_at" t.string "script_log", default: "" t.string "exit_status", default: "" end create_table "student_group_users", force: :cascade do |t| t.integer "student_group_id" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "student_groups", force: :cascade do |t| t.integer "user_id", null: false t.string "name", default: "", null: false t.datetime "created_at" t.datetime "updated_at" end create_table "subnets", force: :cascade do |t| t.string "name" t.string "cidr_block" t.string "driver_id" t.boolean "internet_accessible", default: false t.integer "cloud_id" t.datetime "created_at" t.datetime "updated_at" t.integer "status", default: 0 t.string "log", default: "" end add_index "subnets", ["cloud_id"], name: "index_subnets_on_cloud_id" create_table "tutorials", force: :cascade do |t| t.string "title" t.text "text" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" t.string "name", null: false t.integer "role" t.string "organization" t.string "registration_code" end add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end
clampz/edurange
app/models/scenario.rb
<reponame>clampz/edurange class Scenario < ActiveRecord::Base include Aws include Provider attr_accessor :template # For picking a template when creating a new scenario belongs_to :user has_many :clouds, dependent: :destroy has_many :questions, dependent: :destroy has_many :roles, dependent: :destroy has_many :recipes, dependent: :destroy has_many :groups, dependent: :destroy has_many :subnets, through: :clouds has_many :instances, through: :subnets validate :validate_name, :validate_paths, :validate_user, :validate_stopped before_destroy :validate_stopped, prepend: true # upon the destruction of a scenario, create an # entry in the statistic table. before_destroy :create_statistic, prepend: true # after creating statistic, destory the s3 buckets where the bash histories were cached before_destroy :destroy_s3_bash_histories after_create :load enum location: [:development, :production, :local, :custom, :test] # Validations def validate_name self.name = self.name.strip if self.name == "" errors.add(:name, "Can not be blank") return false elsif /\W/.match(self.name) errors.add(:name, "Name can only contain alphanumeric and underscore") return false elsif /^_*_$/.match(self.name) errors.add(:name, "Name not allowed") return false end true end def validate_paths if not self.path errors.add(:path, 'scenario with that name and location does not exist.') return false end if not self.path_yml errors.add(:path, 'could not find scenario yml file.') return false end if not self.path_recipes errors.add(:path, 'could not find scenario recipes folder.') return false end end def validate_stopped if not self.stopped? errors.add(:running, "can only modify scenario if it is stopped") return false end true end def validate_user if not self.user errors.add(:user, 'must have a user') return false end if not user = User.find_by_id(self.user) errors.add(:user, 'must have a user') return false end if not (user.is_admin? or user.is_instructor?) errors.add(:user, 'must be admin or instructor.') return end end # Loading and file structure def destroy_dependents self.clouds.each do |cloud| cloud.destroy end self.groups.each do |group| group.destroy end self.roles.each do |role| role.destroy end self.recipes.each do |recipe| recipe.destroy end self.questions.each do |question| question.destroy end end def load name_lookup_hash = Hash.new # Because in the YML we establish relationships by name we need to keep track of # what unique id corresponds to the current loading of the scenario. Whenever we # create an object, we store it within the above hash so that we can look it up # later in this function when we are creating objects referencing things in the database. begin file = YAML.load_file(self.path_yml) #file = YAML.load_file(Settings.app_path + self.path_yml) clouds = file["Clouds"] subnets = file["Subnets"] instances = file["Instances"] roles = file["Roles"] groups = file["Groups"] scoring = file["Scoring"] self.name = file["Name"] self.description = file["Description"] self.instructions = file["Instructions"] self.uuid = `uuidgen`.chomp self.answers = '' roles_name_lookup_hash = {} if roles roles.each do |yaml_role| role = self.roles.new(name: yaml_role["Name"]) if yaml_role["Recipes"] yaml_role["Recipes"].each do |recipe_name| recipe = self.recipes.find_by_name(recipe_name) if not recipe recipe = self.recipes.new(name: recipe_name) end if not recipe.save self.destroy_dependents errors.add(:load, "error creating recipe. #{recipe.errors.messages}") return false end role_recipe = role.role_recipes.new(recipe_id: recipe.id) if not role_recipe.save self.destroy_dependents errors.add(:load, "error creating role recipe. #{role_recipe.errors.messages}") return false end end end if yaml_role["Packages"] yaml_role["Packages"].each { |package| role.packages << package } end if not role.save self.destroy_dependents errors.add(:load, "error creating role. #{role.errors.messages}") return false end roles_name_lookup_hash[role.name] = role end end if clouds clouds.each do |yaml_cloud| cloud = self.clouds.new(name: yaml_cloud["Name"], cidr_block: yaml_cloud["CIDR_Block"]) if not cloud.save self.destroy_dependents errors.add(:load, "error creating cloud. #{cloud.errors.messages}") return false end yaml_cloud["Subnets"].each do |yaml_subnet| subnet = cloud.subnets.new( name: yaml_subnet["Name"], cidr_block: yaml_subnet["CIDR_Block"], internet_accessible: yaml_subnet["Internet_Accessible"] ? true : false ) if not subnet.save self.destroy_dependents errors.add(:load, "error creating subnet. #{subnet.errors.messages}") return false end instance_ips = {} yaml_subnet["Instances"].each do |yaml_instance| ip_address, instance_ips = YmlRecord.parse_ip(yaml_instance["IP_Address"], instance_ips) if not ip_address errors.add(:load, "could not parse ip address for Instance #{yaml_instance['IP_Address']}") return false end instance = subnet.instances.new( name: yaml_instance["Name"], ip_address: ip_address, internet_accessible: yaml_instance["Internet_Accessible"] ? true : false, os: yaml_instance["OS"], uuid: `uuidgen`.chomp ) if not instance.save self.destroy_dependents errors.add(:load, "error creating instance. #{instance.errors.messages}") return false end yaml_instance["Roles"].each do |role_name| if not role = roles_name_lookup_hash[role_name] errors.add(:load, 'role not found #{role_name}') return false end instance.roles << role end name_lookup_hash[instance.name] = instance end end end end if groups groups.each do |yaml_group| users = yaml_group["Users"] access = yaml_group["Access"] admin = access["Administrator"] user = access["User"] group = self.groups.new(name: yaml_group["Name"], instructions: yaml_group["Instructions"]) if not group.save self.destroy_dependents errors.add(:load, "error creating group. #{group.errors.messages}") return false end if users users.each do |yaml_user| user_id = nil if user = User.find_by_id(yaml_user["Id"]) user_id = user.is_student? ? user.id : nil end player = group.players.new( login: yaml_user["Login"], password: <PASSWORD>["Password"], user_id: user_id ) if not player.save self.destroy_dependents errors.add(:load, "error creating player. #{player.errors.messages}") return false end end end # Give group admin on machines they own if admin admin.each do |admin_instance| instance = name_lookup_hash[admin_instance] instance.add_administrator(group) if not instance.save self.destroy_dependents errors.add(:load, "error adding group access admin to instance #{instance.name}") return false end end end if access["User"] access["User"].each do |user_instance| instance = name_lookup_hash[user_instance] instance.add_user(group) if not instance.save self.destroy_dependents errors.add(:load, "error adding group access user to instance #{instance.name}") return false end end end end end # Do scoring if scoring scoring.each do |yaml_question| question = self.questions.new( type_of: yaml_question['Type'], text: yaml_question['Text'], points: yaml_question["Points"], order: yaml_question["Order"], options: yaml_question["Options"] ? yaml_question['Options'] : [], values: yaml_question["Values"] ? yaml_question['Values'].map { |val| ({ value: val["Value"], points: val["Points"] }) } : [] ) if not question.save self.destroy_dependents errors.add(:load, "error adding question. #{question.errors.messages}") return false end end end rescue => e self.destroy_dependents errors.add(:load, e.class.to_s + ' - ' + e.message.to_s + "\n" + e.backtrace.join("\n")) return false end if self.test? or self.development? or self.custom? self.update_attribute(:modifiable, true) end self.reload self.update_attribute(:modified, false) end def path if self.custom? path = "#{Settings.app_path}scenarios/custom/#{self.user.id}/#{self.name.downcase}" else path = "#{Settings.app_path}scenarios/#{self.location}/#{self.name.downcase}" end return path if File.exists? path false end def path_yml path = "#{self.path}/#{self.name.downcase}.yml" return path if File.exists? path false end def path_recipes path = "#{self.path}/recipes" if not File.exists? path FileUtils.mkdir path end return path end def update_modified if self.modifiable? self.update_attribute(:modified, true) end end def bootable? return (self.stopped? or self.partially_booted?) end def unbootable? return (self.partially_booted? or self.booted? or self.boot_failed? or self.unboot_failed? or self.paused?) end def change_name(name) if not self.stopped? errors.add(:running, "can not modify while scenario is not stopped"); return false end name = name.strip if name == "" errors.add(:name, "Can not be blank") elsif /\W/.match(name) errors.add(:name, "Name can only contain alphanumeric and underscore") elsif /^_*_$/.match(name) errors.add(:name, "Name not allowed") elsif not self.modifiable? errors.add(:custom, "Scenario must be modifiable to change name") elsif not self.stopped? errors.add(:running, "Scenario must be stopped before name can be changed") elsif File.exists? "#{Settings.app_path}scenarios/local/#{name.downcase}/#{name.downcase}.yml" errors.add(:name, "Name taken") elsif File.exists? "#{Settings.app_path}scenarios/user/#{self.user.id}/#{name.downcase}/#{name.downcase}.yml" errors.add(:name, "Name taken") else oldpath = "#{Settings.app_path}scenarios/user/#{self.user.id}/#{self.name.downcase}" newpath = "#{Settings.app_path}scenarios/user/#{self.user.id}/#{name.downcase}" FileUtils.cp_r oldpath, newpath FileUtils.mv "#{newpath}/#{self.name.downcase}.yml", "#{newpath}/#{name.downcase}.yml" FileUtils.rm_r oldpath self.name = name self.save self.update_yml true end false end def owner?(id) return self.user_id == id end def debug(message) log = self.log ? self.log : '' message = '' if !message self.update_attribute(:log, log + message + "\n") end def scenario return self end def players players = [] self.clouds.each do |cloud| cloud.subnets.each do |subnet| subnet.instances.each do |instance| instance.instance_groups.each do |instance_group| instance_group.group.players.each do |player| found = false players.each do |inplayer| if inplayer.login == player.login found = true end end if !found players.push(player) end end end end end end return players end def students students = [] self.groups.each do |group| group.players.each do |player| students << player.user if not students.include? player.user and player.user end end students end def questions_answered(user) return nil if not self.has_student? user answered = 0 self.questions.each do |question| answered += 1 if question.answers.where("user_id = ?", user.id).size > 0 end answered end def questions_correct(user) return nil if not self.has_student? user correct = 0 self.questions.each do |question| # correct += 1 if question.answers.where("user_id = ? AND correct = 1", user.id).size > 0 question.answers.where("user_id = ?", user.id).each do |answer| correct += 1 if answer.correct end end correct end def public_instances_reachable? reachable return self.instances.select{ |i| not i.port_open?(22) }.any? end def instances_initialized? return self.instances.select{ |i| not i.initialized? }.any? end def clouds_booting? return self.clouds.select{ |c| (c.booting? or c.queued_boot?) }.any? end def clouds_unbooting? return self.clouds.select{ |c| c.unbooting? or c.queued_unboot? }.any? end def subnets_booting? return self.subnets.select{ |s| (s.booting? or s.queued_boot?) }.any? end def subnets_unbooting? return self.subnets.select{ |s| s.unbooting? or s.queued_unboot? }.any? end def clouds_boot_failed? return self.clouds.select{ |c| c.boot_failed? }.any? end def clouds_unboot_failed? return self.clouds.select{ |c| c.unboot_failed? }.any? end def clouds_booted? return self.clouds.select{ |c| c.booted? }.any? end def check_status cnt = 0 stopped = 0 queued_boot = 0 queued_unboot = 0 booted = 0 booting = 0 unbooting = 0 boot_failed = 0 unboot_failed = 0 paused = 0 pausing = 0 starting = 0 self.clouds.each do |cloud| cloud.reload cnt += 1 stopped += 1 if cloud.stopped? queued_boot += 1 if cloud.queued_boot? queued_unboot += 1 if cloud.queued_unboot? booted += 1 if cloud.booted? booting += 1 if cloud.booting? unbooting += 1 if cloud.unbooting? boot_failed += 1 if cloud.boot_failed? unboot_failed += 1 if cloud.unboot_failed? cloud.subnets.each do |subnet| subnet.reload cnt += 1 stopped += 1 if subnet.stopped? queued_boot += 1 if subnet.queued_boot? queued_unboot += 1 if subnet.queued_unboot? booted += 1 if subnet.booted? booting += 1 if subnet.booting? unbooting += 1 if subnet.unbooting? boot_failed += 1 if subnet.boot_failed? unboot_failed += 1 if subnet.unboot_failed? subnet.instances.each do |instance| instance.reload cnt += 1 stopped += 1 if instance.stopped? queued_boot += 1 if instance.queued_boot? queued_unboot += 1 if instance.queued_unboot? booted += 1 if instance.booted? paused += 1 if instance.paused? pausing += 1 if instance.pausing? starting += 1 if instance.starting? booting += 1 if instance.booting? unbooting += 1 if instance.unbooting? boot_failed += 1 if instance.boot_failed? unboot_failed += 1 if instance.unboot_failed? end end end if boot_failed > 0 self.set_boot_failed elsif unboot_failed > 0 self.set_unboot_failed elsif booting > 0 self.set_booting elsif unbooting > 0 self.set_unbooting elsif queued_boot > 0 self.set_queued_boot elsif queued_unboot > 0 self.set_queued_unboot elsif paused > 0 self.set_paused elsif pausing > 0 self.set_pausing elsif starting > 0 self.set_starting elsif booted > 0 if booted == cnt self.set_booted else self.set_partially_booted end else self.set_stopped end end def get_global_recipes_and_descriptions recipes = { } Dir.foreach("#{Settings.app_path}/scenarios/recipes") do |file| next if file == '.' or file == '..' recipe = file.gsub(".rb.erb", "") description = '' description_file = "#{Settings.app_path}/scenarios/recipes/descriptions/#{recipe}" if File.exists? description_file description += File.open(description_file).read end recipes[recipe] = description end recipes end def clone(name) ScenarioManagement.new.clone_from_name(self.name, self.location, name, self.user) end def obliterate if not self.custom? self.errors.add(:obliterate, "can not obliterate non cusom scenario") return false end name, path_graveyard_scenario = ScenarioManagement.new.obliterate_custom(self.name, self.user) self.destroy return path_graveyard_scenario end def make_custom self.name = self.name.strip if self.name == "" errors.add(:name, "Can not be blank") return false elsif /\W/.match(self.name) errors.add(:name, "Name can only contain alphanumeric and underscore") return false elsif /^_*_$/.match(self.name) errors.add(:name, "Name not allowed") return false end if File.exists? "#{Settings.app_path}/scenarios/local/#{self.name.downcase}" errors.add(:name, "A global scenario with that name already exists") return false end if File.exists? "#{Settings.app_path}/scenarios/user/#{self.user.id}/#{self.name.downcase}" errors.add(:name, "A custom scenario with that name already exists") return false end FileUtils.mkdir self.path FileUtils.mkdir "#{self.path}/recipes" self.update_attribute(:modified, true) self.update_yml return true end def update_yml if not self.modifiable? self.errors.add(:customizable, "Scenario is not modifiable.") return false end if not self.modified? self.errors.add(:modified, "Scenario is not modified.") return false end yml = { "Name" => self.name, "Description" => self.description, "Instructions" => self.instructions, "InstructionsStudent" => self.instructions_student, "Groups" => nil, "Clouds" => nil, "Subnets" => nil, "Instances" => nil } yml["Roles"] = self.roles.empty? ? nil : self.roles.map { |r| { "Name"=>r.name, "Packages" => r.packages.empty? ? nil : r.packages, "Recipes"=>r.recipes.empty? ? nil : r.recipes.map { |rec| rec.name } } } yml["Groups"] = self.groups.empty? ? nil : self.groups.map { |group| { "Name" => group.name, "Instructions" => group.instructions, "Access" => { "Administrator" => group.instance_groups.select{ |ig| ig.administrator }.map{ |ig| ig.instance.name }, "User" => group.instance_groups.select{ |ig| not ig.administrator }.map{ |ig| ig.instance.name } }, "Users" => group.players.empty? ? nil : group.players.map { |p| { "Login" => p.login, "Password" => <PASSWORD>, "Id" => self.has_student?(p.user) ? p.user_id : nil, "UserId" => p.user_id, "StudentGroupId" => p.student_group_id } } } } yml["Clouds"] = self.clouds.empty? ? nil : self.clouds.map { |cloud| { "Name" => cloud.name, "CIDR_Block" => cloud.cidr_block, "Subnets" => cloud.subnets.empty? ? nil : cloud.subnets.map { |subnet| { "Name" => subnet.name, "CIDR_Block" => subnet.cidr_block, "Internet_Accessible" => subnet.internet_accessible, "Instances" => subnet.instances.empty? ? nil : subnet.instances.map { |instance| { "Name" => instance.name, "OS" => instance.os, "IP_Address" => instance.ip_address, "Internet_Accessible" => instance.internet_accessible, "Roles" => instance.roles.map { |r| r.name } } }} }} } yml["Scoring"] = self.questions.empty? ? nil : self.questions.map { |question| { "Text" => question.text, "Type" => question.type_of, "Options" => question.options, "Values" => question.values == nil ? nil : question.values.map { |vals| { "Value" => vals[:value], "Points" => vals[:points] } }, "Order" => question.order, "Points" => question.points } } f = File.open("#{self.path}/#{self.name.downcase}.yml", "w") f.write(yml.to_yaml) f.close() self.update_attribute(:modified, false) end def has_student?(user) return false if not user self.groups.each do |group| return true if group.players.select { |p| p.user == user }.size > 0 end false end def has_question?(question) self.questions.find_by_id(question.id) != nil end def answer_cnt(user) return nil if not has_student?(user) cnt = 0 self.questions.each do |question| cnt += question.answers.where("user_id = ?", user.id).size end cnt end def answers_list(user) return nil if not has_student?(user) answers = [] self.questions.each do |question| answers += question.answers.map { |a| a.id } end answers end def find_student(user_id) self.groups.each do |group| group.players.each do |player| if player.user return player.user if player.user.id == user_id end end end nil end def students_groups(user) groups = [] self.groups.each do |group| group.players.each do |player| if player.user groups << group if player.user == user end end end groups end def update_instructions(instructions) self.update_attribute(:instructions, instructions) self.update_modified end def update_instructions_student(instructions) self.update_attribute(:instructions_student, instructions) self.update_modified end private # methods for creating statistics on scenarios # utility method def is_numeric?(s) # input -> s: a string # output -> true if the string is a number value, false otherwise begin if Float(s) return true end rescue return false end end # utility method end def create_statistic # private method to initialize a statistic entry # during Scenario destriction time. These are the first # steps of the analytics pipeline. statistic = Statistic.new # populate statistic with bash histories self.instances.all.each do |instance| # concatenate all bash histories into one big string statistic.bash_histories += instance.get_bash_history puts instance.get_bash_history # for debugging # Concatenate all script logs # Will look messy statistic.script_log += instance.get_script_log puts instance.get_script_log # for debugging # Concatenate all exit status logs statistic.exit_status += instance.get_exit_status puts instance.get_exit_status # for debugging end # partition the big bash history string into a nested hash structure # mapping usernames to the commands they entered. statistic.bash_analytics = partition_bash(statistic.bash_histories.split("\n")) puts statistic.bash_analytics # and with scenario metadata statistic.user_id = self.user_id statistic.scenario_name = self.name statistic.scenario_created_at = self.created_at # we'll also want to grab a list of users from the scenario, # otherwise this data can be got, from the keys of # the bash analytics field statistic.save # stuff into db # create statistic file for download bash_analytics = "" statistic.bash_analytics.each do |analytic| bash_analytics = bash_analytics + "#{analytic}" + "\n" end file_text = "Scenario #{statistic.scenario_name} created at #{statistic.scenario_created_at}\nStatistic #{statistic.id} created at #{statistic.created_at}\n\nBash Histories: \n \n#{statistic.bash_histories} \nBash Analytics: \n#{bash_analytics}" File.write("#{Rails.root}/data/statistics/#{statistic.id}_Statistic_#{statistic.scenario_name}.txt",file_text) #Create Script Log File #Referencing script log by statistic.script_log script_out = "Scenario #{statistic.scenario_name} created at #{statistic.scenario_created_at}\nStatistic #{statistic.id} created at #{statistic.created_at}\n\nScript Log: \n \n#{statistic.script_log} \n" File.write("#{Rails.root}/data/statistics/#{statistic.id}_Script_Log_#{statistic.scenario_name}.txt",script_out) #Create Exit Status file #Referencing exit status log by statistic.exit_status exit_stat_out = "Scenario #{statistic.scenario_name} created at #{statistic.scenario_created_at}\nStatistic #{statistic.id} created at #{statistic.created_at}\n\nExit Status Log: \n \n#{statistic.exit_status} \n" File.write("#{Rails.root}/data/statistics/#{statistic.id}_Exit_Status_#{statistic.scenario_name}.txt",exit_stat_out) end def partition_bash(data) # input -> data: a list of strings of bash commands split by newline # output -> d: a hash {user->{timestamp->command}} # method to populate the bash_analytics field of # a Statistic model with a nested hash # that maps users to timestamps to commands d = Hash.new(0) # {user -> { timestamp -> command }} i = 4 # our index, begin @ index four to skip unneeded lines # make two passes over the data # first, creating the users list # & then, grabbing commands associated # with each of those users # outer hash while i < data.length if data[i][0..1] == "##" e = data[i].length # endpoint u = data[i][3..e-1] # username if !d.include?(u) # don't overwrite unless already included d[u] = Hash.new(0) end end i += 1 end i = 0 # reset index users = d.keys # users u_i = 0 # user index # inner hash while i < data.length if is_numeric?(data[i][1..data[i].length]) e = data[i].length t = data[i][2..e-1] # timestamp if data[i + 1] != "" c = data[i + 1] # command d[users[u_i]][t] = c i += 1 # inc twice end elsif data[i][0..1] == "##" e = data[i].length u = data[i][3..e-1] # to find index in users u_i = users.find_index(u) # & change user u end i += 1 end return d # {users => { timestamps => commands }} end def destroy_s3_bash_histories # bash histories are persistent between boot cycles # only once scenario is destroyed are they deleted from s3 bucket self.instances.each do |instance| instance.aws_instance_delete_bash_history_page instance.aws_instance_delete_exit_status_page instance.aws_instance_delete_script_log_page end end end
clampz/edurange
test/integration/admin_ui_test.rb
<gh_stars>0 require 'test_helper' class AdminUITest < ActionDispatch::IntegrationTest test 'sign in' do visit('/') sign_in_form = page.all('form')[0] assert /users\/sign_in/.match(sign_in_form['action']) != nil end end
clampz/edurange
app/models/student_group.rb
<reponame>clampz/edurange class StudentGroup < ActiveRecord::Base belongs_to :user has_many :student_group_users, dependent: :destroy has_many :users, through: :student_group_users validates :name, presence: true, uniqueness: { scope: :user, message: "Name taken" } # before_destroy :check_if_all # def check_if_all # if self.name == "All" # errors.add(:name, "can not delete Student Group All") # return false # end # true # end def user_add(user) student_group_all = self.user.student_groups.find_by_name("All") if not student_group_all.users.find(user.id) errors.add(:user, "user not found") return false end sgu = self.student_group_users.new(user_id: user.id) sgu.save return sgu end end
clampz/edurange
app/services/create_admin_service.rb
class CreateAdminService def call user = nil if not user = User.find_by_email(Rails.application.secrets.admin_email) user = User.new(email: Rails.application.secrets.admin_email, name: Rails.application.secrets.admin_name) end user.password = <PASSWORD> user.password_confirmation = <PASSWORD> user.set_admin_role user end end
clampz/edurange
app/models/instance_group.rb
<reponame>clampz/edurange class InstanceGroup < ActiveRecord::Base belongs_to :group belongs_to :instance has_one :user, through: :instance has_one :scenario, through: :group after_save :update_scenario_modified after_destroy :update_scenario_modified def update_scenario_modified if self.scenario.modifiable? return self.instance.scenario.update_attribute(:modified, true) end false end def validate if not self.instance.stopped? errors.add(:name, "instance must be stopped first") return false end if InstanceGroup.where("group_id = ? AND instance_id = ? AND administrator = ?", self.group_id, self.instance_id, self.administrator).size > 0 errors.add(:name, "Already exists") return false end true end end
clampz/edurange
app/models/concerns/aws.rb
# This file contains the implementation of the AWS API calls. They are implemented # as hooks, called dynamically by the {Provider} concern when {Scenario}, {Cloud}, {Subnet}, and {Instance} are booted. # @see Provider#boot require 'active_support' module Aws extend ActiveSupport::Concern # ############################################################# # # Boot and Unboot def aws_boot_scenario(options = {}) # Do nothing if already booted if self.booted? return true end # Do initial scoring setup begin self.aws_scenario_initialize_scoring rescue => e self.boot_error(e) return false end # Boot each Cloud if options[:dependents] self.clouds.each do |cloud| begin if not cloud.boot(options) return false end rescue => e self.boot_error(e) return false end end # Wait for clouds to finish booting begin cnt = 0 until not self.clouds_booting? debug "waiting - for clouds to finish booting" if cnt > 600 raise "ERROR - scenario timed out waiting for clouds to finish" end cnt += 1 sleep 2 self.reload end rescue => e self.boot_error(e) return false end # Check if any clouds have failed to boot begin if self.clouds_boot_failed? raise "ERROR - one or more clouds have failed to boot" end rescue => e self.boot_error(e) return false end # Wait for subnets to finish booting begin cnt = 0 until not self.subnets_booting? debug "waiting - for subnets to finish booting" if cnt > 600 raise "ERROR - scenario timed out waiting for subnets to finish" end cnt += 1 sleep 2 self.reload end rescue => e self.boot_error(e) return false end # Wait for all instances to finish booting begin debug "waiting - for instances to finish booting" cnt = 0 until self.instances.select{ |i| i.booted? }.size == self.instances.size sleep 2 cnt += 1 if cnt > 600 raise "ERROR - scenario timed out waiting for instances to finish booting" end self.reload end rescue => e self.boot_error(e) return false end end self.set_booted self.debug_booting_finished true end def aws_unboot_scenario(options = {}) if options[:dependents] self.clouds.each do |cloud| begin if not cloud.unboot(options) return false end rescue => e self.unboot_error(e) return false end end # Wait for clouds to unboot begin debug "wating - for clouds to unboot" cnt = 0 until not self.clouds_unbooting? sleep 2 cnt += 1 if cnt > 600 raise "ERROR - unboot timed out waiting for clouds to finish unbooting" end self.reload end rescue => e self.boot_error(e) return false end # Check clouds for unboot errors begin if self.clouds_unboot_failed? raise "ERROR - one or more clouds have failed to unboot" end rescue => e self.unboot_error(e) return false end end # Delete scoring pages begin aws_scenario_scoring_purge rescue => e self.unboot_error(e) return false end self.set_stopped self.debug_unbooting_finished true end def aws_pause_scenario self.instances.each do |instance| instance.pause end self.set_paused end def aws_start_scenario self.instances.each do |instance| instance.start end self.set_booted end # Boots {Cloud}, and all of its {Subnet Subnets}. # Creates a AWS::EC2::VPC object with Subnet's cidr_block # @return [nil] def aws_boot_cloud(options = {}) # Initialize scoring if it is not already done begin self.scenario.aws_scenario_initialize_scoring rescue => e self.boot_error(e) return false end # Boot if not booted if self.driver_id == nil # Create VPC, assign driver_id, and create Internet Gateway begin debug "creating - VPC" ec2vpc = AWS::EC2.new.vpcs.create(self.cidr_block) rescue => e self.boot_error(e) return false end # Assign driver_id debug "assigning - VPC driver_id" begin self.update_attribute(:driver_id, ec2vpc.id) rescue => e self.boot_error(e) return false end # Create Internet Gateway debug "creating - Internet Gateway" begin ec2vpc.internet_gateway = AWS::EC2.new.internet_gateways.create rescue => e self.boot_error(e) return false end # Wait for VPC to become available begin cnt = 0 debug "waiting - for VPC #{self.driver_id} to become available" until ec2vpc.state == :available sleep 2 cnt += 1 if cnt == 30 raise "timeout - waiting for VPC to become available" return false end end rescue => e self.boot_error(e) return false end # Create routing rules begin debug "creating - routing rules" # Hardcoded firewall rules - TODO ec2vpc.security_groups.first.authorize_ingress(:tcp, 20..8080) #enable all traffic inbound from port 20 - 8080 (most we care about) ec2vpc.security_groups.first.revoke_egress('0.0.0.0/0') # Disable all outbound ec2vpc.security_groups.first.authorize_egress('0.0.0.0/0', protocol: :tcp, ports: 80) # Enable port 80 outbound ec2vpc.security_groups.first.authorize_egress('0.0.0.0/0', protocol: :tcp, ports: 443) # Enable port 443 outbound # TODO -- SECURITY -- delayed job in 20 min disable firewall. ec2vpc.security_groups.first.authorize_egress('10.0.0.0/16') # enable all traffic outbound to subnets rescue => e self.boot_error(e) return false end tries = 0 begin debug "creating - tags" AWS::EC2.new.tags.create(ec2vpc, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2vpc, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2vpc, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2vpc, "scenario", value: self.scenario.id) AWS::EC2.new.tags.create(ec2vpc.internet_gateway, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2vpc.internet_gateway, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2vpc.internet_gateway, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2vpc.internet_gateway, "scenario", value: self.scenario.id) AWS::EC2.new.tags.create(ec2vpc.security_groups.first, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2vpc.security_groups.first, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2vpc.security_groups.first, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2vpc.security_groups.first, "scenario", value: self.scenario.id) AWS::EC2.new.tags.create(ec2vpc.network_acls.first, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2vpc.network_acls.first, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2vpc.network_acls.first, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2vpc.network_acls.first, "scenario", value: self.scenario.id) AWS::EC2.new.tags.create(ec2vpc.route_tables.first, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2vpc.route_tables.first, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2vpc.route_tables.first, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2vpc.route_tables.first, "scenario", value: self.scenario.id) rescue AWS::EC2::Errors::InvalidVpcID::NotFound => e debug "vpc id not found trying again" tries += 1 if tries < 20 sleep 1 retry else self.boot_error(e) end rescue => e self.boot_error(e) return false end self.set_booted self.debug_booting_finished else self.set_stopped return false end # boot dependent Subnets if options[:dependents] self.subnets.each do |subnet| begin if not subnet.boot(options) return false end rescue => e self.boot_error(e) return false end end end true end def aws_unboot_cloud(options = {}) # Unboot dependents if options[:dependents] self.subnets.each do |subnet| begin if not subnet.unboot(options) return false end rescue => e self.unboot_error(e) return false end end # Wait for subnets to unboot begin debug "wating - for subnets to unboot" cnt = 0 until not self.subnets_unbooting? sleep 2 cnt += 1 if cnt > 600 raise "ERROR - unboot timed out waiting for subnets to finish unbooting" end self.reload end rescue => e self.unboot_error(e) return false end # Check subnets for unboot errors begin if self.subnets_unboot_failed? raise "subnets unboot failed" end rescue => e self.unboot_error(e) return false end end # Get VPC object begin debug "getting - EC2 Cloud #{self.driver_id}" vpc = AWS::EC2.new.vpcs[self.driver_id] rescue => e self.unboot_error(e) return false end # Detach and delete any InternetGateways if vpc.internet_gateway and vpc.internet_gateway.exists? igw = vpc.internet_gateway debug "detaching - InternetGateway #{vpc.internet_gateway.internet_gateway_id}" begin vpc.internet_gateway.detach(vpc) rescue => e self.unboot_error(e) return false end debug "deleting - EC2 InternetGateway #{igw.internet_gateway_id}" begin igw.delete rescue => e self.unboot_error(e) return false end end # Delete ACL's vpc.network_acls.select{ |acl| !acl.default}.each do |acl| aws_unboot_acl_new(acl, self) end # Delete Security Groups vpc.security_groups.select{ |sg| !sg.name == "default"}.each do |security_group| aws_unboot_security_group_new(security_group, self) end # Delete Routing Tables vpc.route_tables.select{ |rt| !rt.main?}.each do |route_table| aws_unboot_route_table_new(route_table, self) end # Delete the VPC tries = 0 begin debug "unbooting - VPC #{self.driver_id}" vpc.delete rescue AWS::EC2::Errors::InvalidVpcID::NotFound => e if tries < 120 sleep 2 tries += 1 else self.unboot_error(e) return false end rescue AWS::EC2::Errors::DependencyViolation => e if tries < 120 if aws_instances_stopping?(self.scenario.instances) sleep 2 tries += 1 retry else self.unboot_error(e) return false end else self.unboot_error(e) return false end rescue => e self.unboot_error(e) return false end self.update_attribute(:driver_id, nil) self.set_stopped self.debug_unbooting_finished true end # Boots {Subnet}, and all of its {Instance Instances}. # Creates a AWS::EC2::Subnet object, taking Subnet's `cidr_block` and the `VPC ID` of the {Cloud} the {Subnet} resides in. # @return [nil] def aws_boot_subnet(options = {}) if self.driver_id == nil # create Subnet debug "creating - EC2 Subnet" begin ec2subnet = AWS::EC2::SubnetCollection.new.create(self.cidr_block, vpc_id: self.cloud.driver_id) rescue => e self.boot_error(e) return false end # set driver_id debug "assigning - Subnet #{self.id} driver_id" begin self.update_attribute(:driver_id, ec2subnet.id) rescue => e self.boot_error(e) return false end # wait till Subnet is available begin cnt = 0 until ec2subnet.state == :available debug "waiting for - EC2 Subnet #{self.driver_id} to become available" sleep 2**cnt cnt += 1 if cnt == 9 raise "Timedout waiting for VPC to become available" self.boot_error($!) return false end end rescue AWS::EC2::Errors::InvalidSubnetID::NotFound debug "invalid subnet id - trying again" retry rescue => e self.boot_error(e) return false end # do routing debug "creating - EC2 RouteTable for #{self.driver_id}" begin ec2route_table = AWS::EC2::RouteTableCollection.new.create(vpc_id: self.cloud.driver_id) rescue => e self.boot_error(e) return false end debug "assigning - EC2 Route Table #{ec2route_table.id} to EC2 Subnet #{self.driver_id}" begin ec2subnet.route_table = ec2route_table rescue => e self.boot_error(e) return false end debug "getting - EC2 Cloud #{self.cloud.driver_id}" begin ec2cloud = AWS::EC2.new.vpcs[self.cloud.driver_id] rescue => e self.boot_error(e) return false end if self.internet_accessible debug "creating - Internet Accessible RouteTable for EC2 Subnet #{self.driver_id}" begin ec2route_table.create_route("0.0.0.0/0", { internet_gateway: ec2cloud.internet_gateway} ) rescue => e self.boot_error(e) return false end end debug "creating tags" begin AWS::EC2.new.tags.create(ec2subnet, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2subnet, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2subnet, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2subnet, "scenario", value: self.scenario.id) AWS::EC2.new.tags.create(ec2route_table, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2route_table, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2route_table, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2route_table, "scenario", value: self.scenario.id) rescue => e self.boot_error(e) return false end debug "booted - Subnet #{self.name}" self.set_booted self.debug_booting_finished end if options[:dependents] self.instances.select{ |i| !i.driver_id}.each do |instance| begin if not instance.boot(options) return false end rescue => e self.boot_error(e) return false end end end true end def aws_unboot_subnet(options = {}) debug "unbooting - Subnet #{self.id}" if options[:dependents] self.instances.each do |instance| if instance.driver_id if options[:run_asynchronously] # instance.set_unbooting instance.delay(queue: 'instance').unboot else if not instance.unboot return false end end else instance.set_stopped end end debug "wating - for instances to unboot" # need to do a timeout for this until not self.instances_unbooting? sleep 2 self.reload end begin if self.instances_unboot_failed? raise "subnets instances failed to boot" end rescue => e self.unboot_error(e) return false end else # if not unbooting dependents make sure no instances are booted if self.instances_booted? begin raise "Instances not unbooted" rescue => e self.unboot_error(e) return false end end end debug "disassociating - subnets route table" begin AWS::EC2.new.subnets[self.driver_id].route_table_association.delete # debug "here" # assoc.delete unless assoc.main? # debug "after" rescue => e self.unboot_error(e) return false end # debug "deleting - subnets route table" # begin # AWS::EC2.new.subnets[self.driver_id].route_table.delete # rescue => e # self.unboot_error(e) # return false # end debug "unbooting - EC2 Subnet #{self.driver_id}" begin ec2subnet = AWS::EC2.new.subnets[self.driver_id].delete rescue AWS::EC2::Errors::DependencyViolation => e if aws_instances_stopping?(self.instances) # if aws_instances_stopping?(self.instances) sleep 2 retry else self.unboot_error(e) return false end rescue => e self.unboot_error(e) return false end self.update_attribute(:driver_id, nil) self.debug_unbooting_finished self.set_stopped true end # # Boots {Instance}, generating required cookbooks and startup scripts. # # This method largely defers to {InstanceTemplate} in order to generate shell scripts and # # chef scripts to configure each instance. # # Additionally, it uploads and stores the cookbook_url, which is generated by calling {#aws_instance_upload_cookbook} # # @return [nil] def aws_boot_instance(options = {}) # scoring if self.roles.select { |r| r.recipes.find_by_name('scoring') }.size > 0 begin self.aws_instance_initialize_scoring self.reload self.scenario.update_attribute(:scoring_pages_content, self.scenario.read_attribute(:scoring_pages_content) + self.scoring_page + "\n") self.scenario.aws_scenario_write_to_scoring_pages rescue => e self.boot_error(e) return false end end # create intitiation scripts debug "creating - Instance init" begin debug "generating - instance cookbook" self.aws_instance_create_com_page self.aws_instance_create_bash_history_page self.aws_instance_create_exit_status_page self.aws_instance_create_script_log_page debug "uploading - instance cookbook" self.aws_instance_upload_cookbook(self.generate_cookbook) debug "generating - instance chef script" cloud_init = self.generate_init rescue => e self.boot_error(e) return false end # get ami based on OS if self.os == 'nat' aws_instance_ami = Settings.ami_nat elsif self.os == 'ubuntu' aws_instance_ami = Settings.ami_ubuntu end # create EC2 Instance debug "creating - EC2 Instance" instance_type_num = 0 tries = 0 # instance_types = ["t1.micro", "m3.micro", "t1.small", "m3.small"] # instance_types = ["t1.micro"] instance_types = ["t2.micro"] begin debug "tyring Instance Type #{instance_types[instance_type_num]}" ec2instance = AWS::EC2::InstanceCollection.new.create( image_id: aws_instance_ami, # ami_id string of os image private_ip_address: self.ip_address, # ip string key_name: Settings.ec2_key, # keypair string user_data: cloud_init, # startup data instance_type: instance_types[instance_type_num], subnet: self.subnet.driver_id ) debug "updating instance attribute" self.update_attribute(:driver_id, ec2instance.id) debug "updated instance attribute - #{self.driver_id}" rescue NoMethodError => e debug "- NoMethodError" self.boot_error(e) return false rescue AWS::EC2::Errors::InvalidParameterCombination => e debug "- InvalidParameterCombination" # wrong instance type self.boot_error(e) return false rescue AWS::EC2::Errors::InvalidSubnetID::NotFound => e debug "- InvalidSubnet" tries += 1 if tries > 3 self.boot_error(e) return false end sleep 2 retry rescue AWS::EC2::Errors::InsufficientInstanceCapacity => e debug "- InsufficientInstanceCapacity" if instance_type_num <= instance_types.size instance_type_num += 1 retry else self.boot_error(e) return false end rescue AWS::EC2::Errors::Unsupported => e debug "- Unsupported" tries += 1 if tries > 3 self.boot_error(e) return false end sleep 10 retry rescue => e debug "- Other Error" self.boot_error(e) return false end # wait for Instance to become available debug "waiting for - EC2 Instance #{self.driver_id} to become available" tries = 0 begin cnt = 0 until ec2instance.status == :running sleep 2**cnt cnt += 1 if cnt == 20 raise "Timeout Waiting for VPC to become available" self.boot_error($!) return false end end rescue AWS::EC2::Errors::InvalidInstanceID::NotFound => e if tries > 5 self.boot_error(e) return false end tries += 1 sleep 3 retry rescue => e self.boot_error(e) return false end # for Internet Accessible instances if self.internet_accessible # create Elastip IP debug "creating - EC2 Elastic IP" begin ec2eip = AWS::EC2::ElasticIpCollection.new.create(vpc: true) rescue => e self.boot_error(e) return false end # wait for EIP to become available cnt = 0 until ec2eip.exists? debug "waiting for - EC2 Elastic IP #{self.driver_id} to become available" sleep 2**cnt cnt += 1 if cnt == 20 raise "Timeout Waiting for VPC to become available" self.boot_error($!) return false end end # associate instance with EIP debug "associating - EC2 Elastip IP with EC2 Instance #{ec2instance.id}" begin ec2instance.associate_elastic_ip(ec2eip) rescue => e self.boot_error(e) return false end # accept packets coming in debug "accepting - EC2 Instance NIC packets, disabe source dest checks" begin ec2instance.associate_elastic_ip(ec2eip) ec2instance.network_interfaces.first.source_dest_check = false rescue => e self.boot_error(e) return false end end # create route table to the nat if instances subnet is not internet accessible if not self.subnet.internet_accessible debug "creating - Route for EC2 Subnet #{self.driver_id} to NAT" begin nat = self.subnet.cloud.scenario.instances.select{|i| i.internet_accessible}.first if nat debug "waiting - for nat to boot to make route" until nat.booted? sleep 1 nat.reload end AWS::EC2.new.subnets[self.subnet.driver_id].route_table.create_route("0.0.0.0/0", { instance: nat.driver_id } ) end rescue => e self.boot_error(e) return false end end # create tags debug "creating tag" begin AWS::EC2.new.tags.create(ec2instance, "Name", value: Settings.host + "-" + self.scenario.user.name + '-' + self.scenario.name + '-' + self.scenario.id.to_s) AWS::EC2.new.tags.create(ec2instance, "host", value: Settings.host) AWS::EC2.new.tags.create(ec2instance, "instructor", value: self.scenario.user.name) AWS::EC2.new.tags.create(ec2instance, "scenario", value: self.scenario.id) rescue => e self.boot_error(e) return false end self.set_booted self.debug_booting_finished debug "[x] booted - Instance #{self.name}" true end def aws_unboot_instance(options = {}) # check if instance exists debug "getting - EC2 Instance #{self.driver_id}" begin ec2instance = AWS::EC2.new.instances[self.driver_id] rescue => e self.unboot_error(e) return false end debug "setting - EC2 Instance #{self.driver_id} volumes deleteOnTermination" begin ec2instance.block_devices.each do |device| AWS::EC2.new.client.modify_instance_attribute( instance_id: ec2instance.id, attribute: "blockDeviceMapping", block_device_mappings: [device_name: "#{device[:device_name]}", ebs:{ delete_on_termination: true}] ) end rescue => e self.unboot_error(e) return false end debug "deleting any - EC2 Instance EIP's" begin if ec2eip = ec2instance.elastic_ip ec2instance.disassociate_elastic_ip ec2eip.delete end rescue => e self.unboot_error(e) return false end debug "deleting - EC2 Instance #{self.driver_id}" begin ec2instance.delete rescue => e self.unboot_error(e) return false end debug "stopping - EC2 Instance #{self.driver_id}" # wait for instance to terminate begin cnt = 0 until ec2instance.status_code == 48 debug "waiting #{(2**cnt).to_s} seconds for - EC2 Instance #{self.driver_id} to terminate" sleep 2**cnt cnt += 1 if cnt > 9 raise "EC2 Instance Terminate Wait Timeout" self.unboot_error($!) return false end end rescue => e self.unboot_error(e) return false end # remove s3 files debug "removing s3 files" begin self.aws_instance_delete_cookbook self.aws_instance_delete_com_page self.aws_instance_delete_scoring_page rescue => e self.unboot_error(e) return false end self.update_attribute(:driver_id, nil) self.set_stopped self.debug_unbooting_finished true end def aws_pause_instance if (not self.driver_id) or (not self.booted?) return false end self.set_pausing begin i = AWS::EC2.new.instances[self.driver_id] return if not i.exists? i.stop cnt = 0 until i.status == :stopped sleep 2**cnt cnt += 1 if cnt == 20 raise "Timeout Waiting for VPC to stop" self.boot_error($!) return end end rescue => e self.boot_error(e) return false end self.set_paused true end def aws_start_instance if (not self.driver_id) or (not self.paused?) return false end self.set_starting begin i = AWS::EC2.new.instances[self.driver_id] return if not i.exists? i.start cnt = 0 until i.status == :running sleep 2**cnt cnt += 1 if cnt == 20 raise "Timeout Waiting for VPC to start" self.boot_error($!) return false end end rescue => e self.boot_error(e) return false end self.set_booted true end ## Unboot Helpers def aws_unboot_internet_gateway_new(internet_gateway, cloud) #debug " deleting InternetGateway #{internet_gateway.internet_gateway_id}" begin internet_gateway.delete # rescue AWS::EC2::Errors::DependencyViolation => e # raise # return rescue raise return end #debug " deleted InternetGateway" end def aws_unboot_route_table_new(route_table, cloud) #debug " deleting - RouteTable #{route_table.route_table_id}" begin route_table.delete # rescue AWS::EC2::Errors::DependencyViolation => e # aws_unboot_error(cloud.scenario, e) # return rescue raise return end #debug " [x] deleted - RouteTable" end def aws_unboot_security_group_new(security_group, cloud) #debug " deleting SecurityGroup #{security_group.security_group_id}" begin security_group.delete # rescue AWS::EC2::Errors::DependencyViolation => e # aws_unboot_error(cloud.scenario, e) rescue raise return end #debug " deleted SecurityGroup" end def aws_unboot_acl_new(acl, cloud) #debug " deleting ACL #{acl.id}" begin acl.delete # rescue AWS::EC2::Errors::DependencyViolation => e # aws_unboot_error(cloud.scenario, e) # return rescue raise return end #debug " deleted ACL" end ############################################################# # Helpers def aws_instances_stopping?(instances) return instances.select { |i| i.status == "stopped" or i.status == "stopping"}.any? end # AWS::Cloud methods def aws_cloud_igw self.aws_cloud_driver_object.internet_gateway end # Fetches the {Cloud}'s AWS Virtual Private Cloud object # @return [AWS::EC2::VPCCollection] def aws_cloud_driver_object AWS::EC2::VPCCollection.new[self.driver_id] end # Fetches the {Cloud}'s AWS Virtual Private Cloud object's state # to see if it is booted. # @return [Boolean] if {Cloud} is booted # def aws_cloud_check_status # if self.aws_cloud_driver_object.state == :available # self.update(status: "booted") # end # end # @return [Boolean] Whether or not the {Subnet} is internet_accessible def aws_subnet_nat? @internet_accessible end # @return [Boolean] Whether or not the {Subnet} is booted # def aws_subnet_check_status # if self.aws_subnet_driver_object.state == :available # self.update(status: "booted") # end # end # Calls #aws_instance_allow_traffic on all of {Subnet}'s {Instance Instances} # @param cidr The cidr block to allow traffic to # @param options The options to pass. Currently undefined # @return [nil] def aws_subnet_allow_traffic(cidr, options) instances.each do |instance| instance.aws_instance_allow_traffic(cidr, options) end end # Calls {Provider#boot} on the first {#aws_instance_nat?} {Instance} # @return [String] The AWS Instance ID corresponding to the NAT Instance def aws_subnet_closest_nat_instance # Finds the NAT instance closest to us. TODO. Currently just assumes there's one self.instances.each do |instance| if instance.internet_accessible # Found our NAT if instance.booted? return instance.driver_id else instance.provider_boot return instance.driver_id end end end end # Fetches {Subnet}'s AWS Subnet Object # @return [AWS::EC2::Subnet] def aws_subnet_driver_object AWS::EC2::SubnetCollection.new[self.driver_id] end # @return [Boolean] Whether or not the {Instance} is internet_accessible def aws_instance_nat? @internet_accessible end # Currently does nothing, as we have hardcoded rules defined. # @see #aws_scenario_final_setup # @return [nil] def aws_instance_allow_traffic end # Uses memoization to cache this lookup for faster page renders # @return [String] The public IP address belonging to {Instance}'s AWS Instance Object def aws_instance_public_ip return false unless self.driver_id return false unless self.internet_accessible cnt = 0 begin return @public_ip ||= self.aws_instance_driver_object.public_ip_address rescue AWS::EC2::Errors::InvalidInstanceID::NotFound => e if cnt < 60 sleep 2 cnt += 1 retry else return false end end end # Fetches the {Instance}'s AWS Instance Object # @return [AWS::EC2::InstanceCollection] def aws_instance_driver_object AWS::EC2::InstanceCollection.new[self.driver_id] end # @return [Boolean} Whether or not {Instance}'s AWS Instance Object's status is booted. def aws_instance_check_status self.update(status: "booted") if self.aws_instance_driver_object.status == :running end # @return [String] the string corresponding to an AMI image ID for the OS of the {Instance} def aws_instance_ami_id if self.os == 'ubuntu' 'ami-31727d58' # Private ubuntu image with chef and deps, updates etc. elsif self.os == 'nat' 'ami-51727d38' # Private NAT image with chef and deps, updates etc. end end ############################################################## # S3 page (SCORING, COOKBOOKS, COM) # This uploads our chef cookbook into S3, and gets us a url. This is given to the shell script # which sets a cron job to download and run the chef recipe. # @param cookbook_text The text to upload to S3 # @return [String] A URL generated from S3 pointing to our text def aws_S3_create_page(name, permissions, content) begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? bucket.objects[name].write(content) if content return bucket.objects[name].url_for(permissions, expires: 10.days, :content_type => 'text/plain').to_s rescue raise return end end def aws_S3_delete_page(name) begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] bucket.objects[name].delete rescue raise return end end def aws_S3_name_prefix return "#{Settings.host}_#{self.scenario.user.name}_#{self.scenario.name}_#{self.scenario.id.to_s}" end # Cookbooks def aws_instance_cookbook_name return "#{aws_S3_name_prefix}_cookbook_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_instance_upload_cookbook(cookbook_text) debug "creating s3 cookbook" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? bucket.objects[self.aws_instance_cookbook_name].write(cookbook_text) self.update_attribute(:cookbook_url, bucket.objects[self.aws_instance_cookbook_name].url_for(:read, expires: 10.days).to_s) rescue raise return end end def aws_instance_delete_cookbook debug "deleting s3 cookbook" begin aws_S3_delete_page(self.aws_instance_cookbook_name) self.update_attribute(:cookbook_url, nil) rescue raise return end end # Communication def aws_instance_com_page_name return "#{aws_S3_name_prefix}_compage_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_instance_create_com_page debug "creating s3 com page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? bucket.objects[aws_instance_com_page_name].write("waiting") self.update_attribute(:com_page, bucket.objects[aws_instance_com_page_name].url_for(:write, expires: 10.days, :content_type => 'text/plain', endpoint: Settings.endpoint)).to_s rescue raise return end end def aws_instance_delete_com_page debug "deleting s3 com page" begin aws_S3_delete_page(self.aws_instance_com_page_name) self.update_attribute(:com_page, nil) rescue raise return end end # Bash History def aws_instance_bash_history_page_name return "#{aws_S3_name_prefix}_bash_history_page_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_instance_create_bash_history_page debug "creating s3 bash history page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? self.update_attribute(:bash_history_page, bucket.objects[aws_instance_bash_history_page_name].url_for(:write, expires: 10.days, :content_type => 'text/plain').to_s) rescue raise return end end def aws_instance_exit_status_page_name return "#{aws_S3_name_prefix}_exit_status_page_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_instance_create_exit_status_page debug "creating s3 exit status page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? self.update_attribute(:exit_status_page, bucket.objects[aws_instance_exit_status_page_name].url_for(:write, expires: 10.days, :content_type => 'text/plain').to_s) rescue raise return end end def aws_instance_script_log_page_name return "#{aws_S3_name_prefix}_script_log_page_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_instance_create_script_log_page debug "creating s3 script log page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? self.update_attribute(:script_log_page, bucket.objects[aws_instance_script_log_page_name].url_for(:write, expires: 10.days, :content_type => 'text/plain').to_s) rescue raise return end end def aws_instance_delete_bash_history_page debug "deleting s3 bash history page" begin aws_S3_delete_page(self.aws_instance_bash_history_page_name) # self.update_attribute(:bash_history_page, nil) rescue raise return end end def aws_instance_delete_exit_status_page debug "deleting s3 exit status page" begin aws_S3_delete_page(self.aws_instance_exit_status_page_name) # self.update_attribute(:exit_status_page, nil) rescue raise return end end def aws_instance_delete_script_log_page debug "deleting s3 script log page" begin aws_S3_delete_page(self.aws_instance_script_log_page_name) # self.update_attribute(:script_log_page, nil) rescue raise return end end ####################################################################### # Scoring # Scenario Scoring def aws_scenario_initialize_scoring begin if not self.scoring_pages debug "creating scoring pages s3 file" self.aws_scenario_create_scoring_pages end if not self.answers_url debug "creating answers url s3 file" self.aws_scenario_create_answers_url end rescue raise return end end def aws_scenario_scoring_pages_name return "#{aws_S3_name_prefix}_scenario_scoring_pages_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_scenario_create_scoring_pages debug "creating s3 scoring page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? self.update_attribute(:scoring_pages, bucket.objects[aws_scenario_scoring_pages_name].url_for(:read, expires: 10.days).to_s) rescue raise return end end def aws_scenario_write_to_scoring_pages begin AWS::S3.new.buckets[Settings.bucket_name].objects[aws_scenario_scoring_pages_name].write(self[:scoring_pages_content]) rescue raise return end end def aws_scenario_delete_scoring_pages debug "deleting s3 scoring pages" begin AWS::S3.new.buckets[Settings.bucket_name].objects[aws_scenario_scoring_pages_name].delete self.update_attribute(:scoring_pages, nil) rescue AWS::S3::Errors::PermanentRedirect return true rescue AWS::S3::Errors::NoSuchBucket return true rescue raise return end end def aws_scenario_answers_url_name return "#{aws_S3_name_prefix}_scenario_answers_url_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_scenario_create_answers_url debug "creating s3 answers page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? object = bucket.objects[aws_scenario_answers_url_name] object.write(self.answers) self.update_attribute(:answers_url, object.url_for(:read, expires: 10.days).to_s) rescue raise return end end def aws_scenario_delete_answers_url debug "deleting s3 delete answers page" begin AWS::S3.new.buckets[Settings.bucket_name].objects[aws_scenario_answers_url_name].delete self.update_attribute(:answers_url, nil) rescue AWS::S3::Errors::PermanentRedirect return true rescue AWS::S3::Errors::NoSuchBucket return true rescue raise return end end def aws_scenario_scoring_purge begin self.aws_scenario_delete_scoring_pages self.aws_scenario_delete_answers_url rescue raise return end end # Instance Scoring def aws_instance_initialize_scoring begin if not self.scoring_page self.aws_instance_create_scoring_page end if not self.scoring_url self.aws_instance_create_scoring_url end rescue raise return end end def aws_instance_scoring_page_name return "#{aws_S3_name_prefix}_instance_scoring_#{self.name}_#{self.id.to_s}_#{self.uuid}" end def aws_instance_create_scoring_url begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? bucket.objects[aws_instance_scoring_page_name].write("# put your answers here") self.update_attribute(:scoring_url, bucket.objects[aws_instance_scoring_page_name].url_for(:write, expires: 10.days, :content_type => 'text/plain').to_s) rescue raise return end end def aws_instance_create_scoring_page debug "creating s3 scoring page" begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] s3.buckets.create(Settings.bucket_name) unless bucket.exists? self.update_attribute(:scoring_page, bucket.objects[aws_instance_scoring_page_name].url_for(:read, expires: 10.days).to_s) rescue raise return end end def aws_instance_delete_scoring_page debug "deleting s3 scoring page" begin AWS::S3.new.buckets[Settings.bucket_name].objects[aws_instance_scoring_page_name].delete self.update_attribute(:scoring_page, nil) rescue raise return end end end
clampz/edurange
test/models/scoring_test.rb
require 'test_helper' class ScoringTest < ActiveSupport::TestCase test 'text presence' do s = scenarios(:two) q = Question.new(order: 1, type_of: 'String', values: [{value: "foo", points: 1}], scenario_id: s.id) q.save assert_not q.valid? assert_equal [:text], q.errors.keys end test 'type presence' do s = scenarios(:two) q = Question.new(text: "foo", order: 1, values: [{value: "foo", points: 1}], scenario_id: s.id) q.save assert_not q.valid? assert_equal [:type_of], q.errors.keys end test 'value presence' do s = scenarios(:two) # values must be present q = Question.new(text: "foo", order: 1, type_of: "String", scenario_id: s.id) q.save assert_not q.valid? assert_equal [:values], q.errors.keys # values should not be blank q.values = [] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # values should be a list of hashses q.values = ["foo"] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # hashes should not be empty q.values = [{}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # hashes shoudl contain the fields 'value' and 'points' q.values = [{value: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # hashses should not contain any extra fields q.values = [{value: "foo", points: 1, extra: 2}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # hashses should not be empty q.values = [{value: "foo", points: 1}, {}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # must all be hashes q.values = [{value: "foo", points: 1}, {value: "bar", points: 1}, "foo"] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # no duplicated values in hashes q.values = [{value: " foo", points: 1}, {value: "foo ", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # this is correct q.values = [{value: "foo", points: 1}] q.save assert q.valid? assert_equal [], q.errors.keys # this one is also correct q.values = [{value: "foo", points: 1}, {value: "bar", points: 1}] q.save assert q.valid? assert_equal [], q.errors.keys # no equal values q.type_of = "Number" q.options = ["accept-integer", "accept-decimal"] q.values = [{value: "1", points: 1}, {value: "1.0", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.options = ["accept-integer", "accept-decimal", "accept-hex"] q.values = [{value: "0x01", points: 1}, {value: "1.0", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.options = ["accept-integer", "accept-decimal", "accept-hex"] q.values = [{value: "0x01", points: 1}, {value: "1", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys end test 'options' do s = scenarios(:two) # options default to empty list q = Question.new(text: "foo", order: 1, type_of: "String", values: [{value: "1", points: 1}], scenario_id: s.id) q.save assert q.valid? assert_equal q.options, [] # possible types "String", "Number", "Essay", "Event" q.type_of = "None" q.save assert_not q.valid? assert_equal [:type_of], q.errors.keys q.type_of = "String" q.save assert q.valid? # not a valid option for string q.options = ["accept-integer"] q.save assert_not q.valid? assert_equal [:options], q.errors.keys q.options = ["ignore-case"] q.save assert q.valid? # number type must contain at least one option, values will also fail because there is no option for type accepted q.type_of = "Number" q.options = [] q.save assert_not q.valid? assert_equal [:options, :values], q.errors.keys q.options = ["none"] q.save assert_not q.valid? assert_equal [:options, :values], q.errors.keys q.options = ["accept-integer", "foo"] q.save assert_not q.valid? assert_equal [:options], q.errors.keys q.options = ["accept-integer"] q.save assert q.valid? # values must be integer because that is what is accepted q.values = [{value: "foo", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: "10.0", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: "10.0a", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: "0xff", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: " 10 ", points: 1}] q.save assert q.valid? q.values = [{value: " -10", points: 1}] q.save assert q.valid? q.values = [{value: "+10 ", points: 1}] q.save assert q.valid? # try accept decimal q.options = ["accept-decimal"] q.values = [{value: "+10.9999 ", points: 1}] q.save assert q.valid? q.values = [{value: "+10.4 ", points: 1}] q.save assert q.valid? q.values = [{value: " +10.0 ", points: 1}] q.save assert q.valid? q.values = [{value: "-.0 ", points: 1}] q.save assert q.valid? q.values = [{value: "+111.0 ", points: 1}] q.save assert q.valid? q.values = [{value: "+a111.0 ", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: " 0xff ", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # try accept hex q.options = ["accept-hex"] q.values = [{value: " 0x0 ", points: 1}] q.save assert q.valid? q.values = [{value: " 0xcca1112bef ", points: 1}] q.save assert q.valid? q.values = [{value: " 00x0", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: " -10.0", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: " 10 ", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys q.values = [{value: " asf ", points: 1}] q.save assert_not q.valid? assert_equal [:values], q.errors.keys # do essay q.type_of = "Essay" q.options = [] q.save assert q.valid? q.options = ["wrong"] q.save assert_not q.valid? assert_equal [:options], q.errors.keys q.options = ["larger-text-field"] q.save assert q.valid? end test 'text uniqueness' do s = scenarios(:two) q = Question.new(text: "foo", order: 1, type_of: "String", values: [{value: "1", points: 1}], scenario_id: s.id) q2 = Question.new(text: "foo", order: 1, type_of: "String", values: [{value: "1", points: 1}], scenario_id: s.id) q.save q2.save assert_not q2.valid? q2.text = "bar" q2.save assert q2.valid? end test 'order' do s = scenarios(:two) q1 = Question.new(text: "foo", type_of: "String", values: [{value: "1", points: 1}], scenario_id: s.id) q2 = Question.new(text: "bar", type_of: "String", values: [{value: "1", points: 1}], scenario_id: s.id) q3 = Question.new(text: "baz", type_of: "String", values: [{value: "1", points: 1}], scenario_id: s.id) q1.save q2.save q3.save assert q1.valid? assert q2.valid? assert q3.valid? assert q1.order == 1 assert q2.order == 2 assert q3.order == 3 q1 = q1.move_down assert q1.order == 1 assert q2.order == 2 assert q3.order == 3 # set q2 here or reload because move_up has side effects on the database q2 = q1.move_up assert q1.order == 2 assert q2.order == 1 assert q3.order == 3 q3 = q1.move_up assert q1.order == 3 assert q2.order == 1 assert q3.order == 2 q1 = q1.move_up assert q1.order == 3 assert q2.order == 1 assert q3.order == 2 q3 = q1.move_down assert q1.order == 2 assert q2.order == 1 assert q3.order == 3 q2 = q1.move_down assert q1.order == 1 assert q2.order == 2 assert q3.order == 3 end test 'answer string' do s = scenarios(:two) st = users(:student1) q1 = Question.new(text: "foo", type_of: "String", values: [{value: "foo", points: 1}], scenario_id: s.id) q1.save assert q1.valid? a = q1.answer_string("", st.id) assert_equal [:text], a.errors.keys a = q1.answer_string("", st.id) assert_equal [:text], a.errors.keys a = q1.answer_string(" ", st.id) assert_equal [:text], a.errors.keys a = q1.answer_string("foo", st.id) assert_equal [], a.errors.keys b = q1.answer_string("foo", st.id) assert_equal [:duplicate], b.errors.keys b = q1.answer_string(" foo ", st.id) assert_equal [:duplicate], b.errors.keys b = q1.answer_string(" Foo ", st.id) assert_equal [], b.errors.keys q1.reload q1.options = ["ignore-case"] q1.save assert_equal [], q1.errors.keys, "#{q1.errors.messages}" b = q1.answer_string(" Foo ", st.id) assert_equal [:duplicate], b.errors.keys c = q1.answer_string(" FooBar ", st.id) assert_equal [], c.errors.keys end test 'answer number' do s = scenarios(:two) st = users(:student1) q1 = Question.new(text: "foo", type_of: "Number", options: ["accept-integer"], values: [{value: "1", points: 1}], scenario_id: s.id) q1.save assert q1.valid? assert_equal [], q1.errors.keys # fail if not number type q1.type_of = "String" q1.save a = q1.answer_number("1", st.id) assert_equal [:type_of], a.errors.keys # fail because answer is decimal not integer q1.type_of = "Number" q1.save a = q1.answer_number("1.0", st.id) assert_equal [:options], a.errors.keys # fail because answer is hex not integer a = q1.answer_number("0xff", st.id) assert_equal [:options], a.errors.keys # fail because answer is not anything a = q1.answer_number("1000000z0000", st.id) assert_equal [:options], a.errors.keys # yes integer but not correct a = q1.answer_number("100", st.id) assert_equal [], a.errors.keys assert_not a.correct # yes integer but not correct a = q1.answer_number("-1", st.id) assert_equal [], a.errors.keys assert_not a.correct # correct a = q1.answer_number(" 1 ", st.id) assert_equal [], a.errors.keys assert a.correct # correct a = q1.answer_number(" +1 ", st.id) assert_equal [:duplicate], a.errors.keys q1.answers.destroy_all q1.options = ["accept-decimal"] q1.values = [{value: "2.0", points: 1}] q1.save assert q1.valid? # dont accept integer a = q1.answer_number(" +2 ", st.id) assert_equal [:options], a.errors.keys # dont accept hex a = q1.answer_number(" 0x02 ", st.id) assert_equal [:options], a.errors.keys # correct a = q1.answer_number(" +2.0 ", st.id) assert_equal [], a.errors.keys assert a.correct # no duplicates a = q1.answer_number(" 2.000 ", st.id) assert_equal [:duplicate], a.errors.keys q1.reload assert q1.answers.size == 1 end test 'answer essay' do s = scenarios(:two) st = users(:student1) q1 = Question.new(text: "foo", type_of: "Number", options: ["accept-integer"], values: [{value: "1", points: 1}], scenario_id: s.id) q1.save assert q1.valid? assert_equal [], q1.errors.keys # question is not Essay type a = q1.answer_essay("foo", st.id) assert_equal [:type_of], a.errors.keys q1.type_of = "Essay" q1.options = [] q1.save assert q1.valid? # no blank answers a = q1.answer_essay("", st.id) assert_equal [:text_essay], a.errors.keys a = q1.answer_essay(" ", st.id) assert_equal [:text_essay], a.errors.keys # valid answer should save without errors a = q1.answer_essay("foo", st.id) assert_equal [], a.errors.keys assert a.valid? end end
clampz/edurange
app/models/user.rb
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable enum role: [:user, :vip, :admin, :instructor, :student] has_many :scenarios has_many :student_groups, dependent: :destroy has_many :student_group_users, dependent: :destroy after_initialize :set_defaults, :if => :new_record? validates :email, uniqueness: true validates :name, presence: true validate :validate_name, :validate_running def validate_name return if not self.name self.name = self.name.strip if self.name == "" errors.add(:name, "can not be blank") return false elsif /\W/.match(self.name) errors.add(:name, "can only contain alphanumeric and underscore") return false elsif /^_*_$/.match(self.name) errors.add(:name, "not allowed") return false end true end def validate_running if self.scenarios.select{ |s| not s.stopped? }.size > 0 errors.add(:running, "can not modify while a scenario is running") return false end true end def owns?(obj) return true if self.is_admin? cl = obj.class arr = [Cloud, Group, Instance, Scenario, StudentGroup, Subnet, InstanceRole, InstanceGroup, Role, RoleRecipe, Recipe, Answer] if arr.include? cl return obj.user == self elsif cl == Player return obj.group.user == self elsif cl == StudentGroupUser return obj.student_group.user == self end end def set_defaults self.role ||= :student end def is_admin? return self.role == 'admin' end def is_instructor? return self.role == 'instructor' end def is_student? return self.role == 'student' end def set_instructor_role if not self.registration_code self.update(registration_code: SecureRandom.hex[0..7]) end if not File.exists? "#{Settings.app_path}scenarios/custom/#{self.id}" FileUtils.mkdir "#{Settings.app_path}scenarios/custom/#{self.id}" end if not self.student_groups.find_by_name("All") sg = self.student_groups.new(name: "All") sg.save end self.update(role: :instructor) end def set_student_role if not self.validate_running return end self.student_groups.destroy_all self.update_attribute :role, :student end def set_admin_role if not self.registration_code self.update(registration_code: SecureRandom.hex[0..7]) end if not File.exists? "#{Settings.app_path}scenarios/custom/#{self.id}" FileUtils.mkdir "#{Settings.app_path}scenarios/custom/#{self.id}" end if not self.student_groups.find_by_name("All") sg = self.student_groups.new(name: "All") sg.save end self.update(role: :admin) end def email_credentials(password) UserMailer.email_credentials(self, password).deliver_now end def student_to_instructor puts self.student_group_users.destroy_all self.student_group_users.destroy self.set_instructor_role end def student_add_to_all(student) if sg = self.student_groups.find_by_name("All") sgu = sg.student_group_users.new(user_id: student.id) sgu.save end return sg, sgu end def instructor_to_student(user) if user and (user.is_admin? or user.is_instructor?) if sg = user.student_groups.find_by_name("All") sgu = sg.student_group_users.new(user_id: self.id) sgu.save end end self.set_student_role return sg, sgu end end
clampz/edurange
test/models/scenario_test.rb
<reponame>clampz/edurange require 'test_helper' class ScenarioTest < ActiveSupport::TestCase test 'should only allow instructor and admin to create scenario' do student = users(:student1) instructor = users(:instructor1) admin = users(:admin1) scenario = student.scenarios.new(location: :test, name: 'test1') scenario.save assert_not scenario.valid? assert_equal [:user], scenario.errors.keys scenario = instructor.scenarios.new(location: :test, name: 'test1') scenario.save assert scenario.valid? assert_equal [], scenario.errors.keys end test 'should rescue when yml is corrupted' do instructor = users(:instructor1) scenario = instructor.scenarios.new(location: :test, name: 'badyml') scenario.save assert_equal [:load], scenario.errors.keys scenario = instructor.scenarios.new(location: :test, name: 'badyml2') scenario.save assert_equal [:load], scenario.errors.keys end test 'production scenarios should load' do instructor = users(:instructor1) Dir.foreach('scenarios/production') do |filename| next if ['.','..'].include? filename scenario = instructor.scenarios.new(location: :production, name: filename) scenario.save assert_equal [], scenario.errors.keys, "production scenario #{filename} does not load. #{scenario.errors.messages}" end end test 'clone' do instructor = users(:instructor999999999) scenario = instructor.scenarios.new(location: :test, name: 'test1') scenario.save assert_equal [], scenario.errors.keys clone = scenario.clone('test1clone') clone.save assert_equal [], scenario.errors.keys path = clone.path path_yml = clone.path_yml path_recipes = clone.path_recipes assert path assert path_yml assert path_recipes path_graveyard_scenario = clone.obliterate assert_not File.exists? path assert_not File.exists? path_yml assert_not File.exists? path_recipes path_graveyard = "#{Settings.app_path}/scenarios/custom/graveyard" path_graveyard_user = "#{path_graveyard}/#{instructor.id}" path_graveyard_scenario_yml = "#{path_graveyard_scenario}/#{clone.name.downcase}.yml" assert File.exists? path_graveyard assert File.exists? path_graveyard_user assert File.exists? path_graveyard_scenario assert File.exists? path_graveyard_scenario_yml FileUtils.rm_r "#{Settings.app_path}/scenarios/custom/#{instructor.id}" FileUtils.rm_r path_graveyard_user end test 'scenario should not fail if recipe folders are missing' do instructor = users(:instructor999999999) scenario = instructor.scenarios.new(location: :test, name: 'missingrecipefolder') assert File.exists? "#{scenario.path}/recipes" FileUtils.rmdir "#{scenario.path}/recipes" assert_not File.exists? "#{scenario.path}/recipes" scenario.save assert_not scenario.errors.any? assert File.exists? "#{scenario.path}/recipes" end test 'answers_url should not be nil' do instructor = users(:instructor999999999) scenario = instructor.scenarios.new(location: :test, name: 'test1') scenario.save assert scenario.answers != nil assert scenario.answers.class == String end end
clampz/edurange
config/initializers/rails_config.rb
<reponame>clampz/edurange Config.setup do |config| config.const_name = "Settings" Config.load_files( Rails.root.join("config", "settings.yml").to_s, Rails.root.join("config", "settings.local.yml").to_s ) end
clampz/edurange
app/models/concerns/provider.rb
# This file is included in {Scenario}, {Cloud}, {Subnet} and {Instance}. Essentialy it has glue code for # both defining methods dynamically (within concerns such as Aws that handle provider specific API calls) as well as # routing those methods (within {#method_missing}) # Apart from defining these methods, the only other role this file has is to declare the "status" column, an integer corresponding to # three states stored in the local database. They can be :stopped, :booting, or :booted. All files which include {Provider} receive this, # and helper methods to retrieve the database state. Check out enum in Rails. # When reading through this file (and other Concerns), think of the file including them as their "self". When a {Cloud} includes this file, # any of these methods "self" will refer to that {Cloud cloud}. module Provider extend ActiveSupport::Concern included do enum status: [:stopped, :paused, :pausing, :starting, :queued_boot, :queued_unboot, :booting, :booted, :failure, :boot_failed, :unboot_failed, :unbooting, :stopping, :partially_booted, :partially_booted_with_failure, :partially_unbooted, :partially_unbooted_with_failure] end def debug_booting debug "------------------ booting ------------------" end def debug_booting_finished debug "-------------- finished booting -------------" end def debug_unbooting debug "----------------- unbooting -----------------" end def debug_unbooting_finished debug "------------ finished unbooting ------------" end def clear_log self.update_attribute(:log, '') end ############################################################# # Booting def boot_error(error) self.set_boot_failed debug(error.class.to_s + ' - ' + error.message.to_s + error.backtrace.join("\n")); self.save self.reload self.scenario.set_boot_failed # time = Time.new # File.open("#{Rails.root}/log/boot.#{scenario.id}-#{scenario.name}.log", 'a') do |f| # f.puts "\n" # f.puts error.class.to_s + ' - ' + error.message.to_s + error.backtrace.join("\n") # f.puts "\n" # end end def boot(options = {}) classname = self.class if classname == Scenario if not (self.stopped? or self.partially_booted?) errors.add(:boot, "#{self.class} must be stopped or partially booted to boot") return false end elsif not self.stopped? errors.add(:boot, "#{self.class} must be stopped to boot") return false end if classname == Subnet if not self.cloud.booted? errors.add(:boot, "Subnets cloud must be booted") return false end elsif classname == Instance if not self.subnet.booted? errors.add(:boot, "Instances subnet must be booted") return false end end if classname == Scenario or classname = Cloud if AWS::EC2.new.vpcs.count >= Settings.vpc_limit errors.add(:boot, "VPC limit of #{Settings.vpc_limit} reached, find AWS edurange admin for help.") return false end end self.clear_log self.debug_booting if options[:debug] self.bootme(options) elsif options[:asynchronous] or options[:solo] or classname == Scenario debug "queuing - #{self.class.to_s} #{self.name} for boot" self.set_queued_boot self.delay(queue: self.class.to_s.downcase).bootme(options) else if not self.bootme(options) return false end end true end def bootme(options = {}) self.set_booting if not self.send("provider_boot_#{self.class.to_s.downcase}", options) return false end true end def unboot(options = {}) classname = self.class if classname == Scenario if not (self.booted? or self.partially_booted? or self.boot_failed? or self.unboot_failed? or self.paused?) errors.add(:boot, "#{self.class} must be booted or partially booted or have a error to uboot") return false end else if self.driver_id == nil self.set_stopped return true end # elsif not (self.booted? or self.boot_failed? or self.unboot_failed? or self.paused?) # errors.add(:boot, "#{self.class} must be booted, have an error, or be paused to unboot") # return false end if not options[:dependents] if classname == Cloud if not self.subnets_stopped? errors.add(:boot, "#{self.class}s subnets must be stopped") return false end elsif classname == Subnet if not self.instances_stopped? errors.add(:boot, "#{self.class}s instances must be stopped") return false end end end self.debug_unbooting if options[:debug] self.bootme(options) elsif options[:asynchronous] or options[:solo] or classname == Scenario debug "queuing - #{self.class.to_s} #{self.name} for unboot" self.set_queued_unboot self.delay(queue: self.class.to_s.downcase).unbootme(options) else if not self.unbootme(options) return false end end true end def unbootme(options = {}) self.set_unbooting if not self.send("provider_unboot_#{self.class.to_s.downcase}", options) return false end true end def unboot_error(error) self.set_unboot_failed debug(error.class.to_s + ' - ' + error.message.to_s + error.backtrace.join("\n")); self.scenario.set_unboot_failed end def pause if not (self.class == Instance or self.class == Scenario) return end if not self.booted? errors.add(:boot, "must be booted to pause") return end if self.class == Scenario self.set_pausing self.delay(queue: self.class.to_s.downcase).send("provider_pause_#{self.class.to_s.downcase}") else self.send("provider_pause_#{self.class.to_s.downcase}") end end def start if not (self.class == Instance or self.class == Scenario) return end if not self.paused? errors.add(:boot, "must be paused to start") return end if self.class == Scenario self.set_starting self.delay(queue: self.class.to_s.downcase).send("provider_start_#{self.class.to_s.downcase}") else self.send("provider_start_#{self.class.to_s.downcase}") end end ############################################################# # Status set and get def set_stopped self.update_attribute(:status, :stopped) if self.class != Scenario self.scenario.check_status end end def set_paused self.update_attribute(:status, :paused) if self.class != Scenario self.scenario.check_status end end def set_pausing self.update_attribute(:status, :pausing) if self.class != Scenario self.scenario.check_status end end def set_starting self.update_attribute(:status, :starting) if self.class != Scenario self.scenario.check_status end end def set_queued_boot self.update_attribute(:status, :queued_boot) if self.class != Scenario self.scenario.check_status end end def set_queued_unboot self.update_attribute(:status, :queued_unboot) if self.class != Scenario self.scenario.check_status end end def set_booting self.update_attribute(:status, :booting) if self.class != Scenario self.scenario.check_status end end def set_unbooting self.update_attribute(:status, :unbooting) if self.class != Scenario self.scenario.check_status end end def set_boot_failed self.update_attribute(:status, :boot_failed) if self.class != Scenario self.scenario.check_status end end def set_unboot_failed self.update_attribute(:status, :unboot_failed) if self.class != Scenario self.scenario.check_status end end def set_booted self.update_attribute(:status, :booted) if self.class != Scenario self.scenario.check_status end end def set_partially_booted self.update_attribute(:status, :partially_booted) if self.class != Scenario self.scenario.check_status end end def set_partially_unbooted self.update_attribute(:status, :partially_unbooted) if self.class != Scenario self.scenario.check_status end end def set_failure self.update_attribute(:status, :failure) if self.class != Scenario self.scenario.check_status end end def set_partially_booted_with_failure self.update_attribute(:status, :partially_booted_with_failure) if self.class != Scenario self.scenario.check_status end end def set_partially_unbooted_with_failure self.update_attribute(:status, :partially_unbooted_with_failure) if self.class != Scenario self.scenario.check_status end end def is_failed? return self.status == "unboot_failed" || self.status == "boot_failed" end def queued? return (self.queued_boot? or self.queued_unboot?) end # Polls the state in database, waiting to yield to given block until self is booted? # If self is not booted?, calls provider_check_status for self. # @param block The block to execute when self.booted? def run_when_booted until self.booted? self.reload sleep 1 classname = self.class.to_s.downcase self.run_provider_method("#{classname}_check_status") end yield end def wait_until_booted until ['booted', 'boot_failed'].include? self.status sleep 1 end if self.status == "boot_failed" return "error" end return nil end def wait_until_stopped until ['stopped', 'unboot_failed'].include? self.status sleep 1 end if self.status == "unboot_failed" return "error" end return nil end # Dynamically calls the method provided, routing it through the provider concern specified at runtime by # Settings.driver. # @param meth The method to call # @param args The arguments to pass # @param block Any block arguments to pass # @see #run_provider_method # @return [nil] def method_missing(meth, *args, &block) if meth.to_s =~ /^provider_(.+)$/ run_provider_method($1, *args, &block) else super end end # Calls the method provided in the EDURange config, defined in the concerns for each Driver at runtime. # Currently does not pass arguments. # @return [nil] def run_provider_method(provider_method, *args, &block) self.send("#{Settings.driver}_#{provider_method}".to_sym, *args) end end
clampz/edurange
app/controllers/statistics_controller.rb
class StatisticsController < ApplicationController before_action :authenticate_admin_or_instructor require 'rubygems' require 'zip' require 'tempfile' require 'json' def index # view for all statistics @statistics = [] if @user.is_admin? @statistics = Statistic.all else @statistics = Statistic.where(user_id: current_user.id) end end # GET /statistic/<id> def show # find the statistic by id @statistic = Statistic.find(params[:id]) # grab the analytics data @bash_analytics = @statistic.bash_analytics # grab usernames & make available in UI @users = @bash_analytics.keys @statistic_id = @statistic.id end # GET /statistic/<id>/destroyme def destroyme statistic = Statistic.find(params[:id]) statistic.destroy if statistic.destroy respond_to do |format| format.js { render js: "window.location.pathname='/statistics'" } end end end # GET /statistic/1/download_all def download_all @statistics = [] if @user.is_admin? @statistics = Statistic.all else @statistics = Statistic.where(user_id: current_user.id) end folder = "#{Rails.root}/data/statistics/" input_filepaths = [] input_filenames = [] @statistics.each do |statistic| # add bash histories file_path = "#{Rails.root}/data/statistics/#{statistic.id}_Statistic_#{statistic.scenario_name}.txt" file_name = "#{statistic.id}_Statistic_#{statistic.scenario_name}.txt" if File.exist?(file_path) input_filepaths.push(file_path) input_filenames.push(file_name) end # add exit statuses exit_status_path = "#{Rails.root}/data/statistics/#{statistic.id}_Exit_Status_#{statistic.scenario_name}.txt" exit_status_name = "#{statistic.id}_Exit_Status_#{statistic.scenario_name}.txt" if File.exist?(exit_status_path) input_filepaths.push(exit_status_path) input_filenames.push(exit_status_name) end # add script logs script_log_path = "#{Rails.root}/data/statistics/#{statistic.id}_Script_Log_#{statistic.scenario_name}.txt" script_log_name = "#{statistic.id}_Script_Log_#{statistic.scenario_name}.txt" if File.exist?(script_log_path) input_filepaths.push(script_log_path) input_filenames.push(script_log_name) end end #create a temporary zip file temp_file = Tempfile.new("statistics.zip") begin #Initialize the temp file as a zip file Zip::OutputStream.open(temp_file) { |zos| } Zip::File.open(temp_file.path, Zip::File::CREATE) do |zipfile| input_filenames.each do |filename| zipfile.add(filename, folder + filename) end end #Read the binary data from the file zip_data = File.read(temp_file.path) send_data(zip_data, :type => 'application/zip', :filename => "statistic_data.zip") ensure #close and delete the temp file temp_file.close temp_file.unlink end end # GET /statistic/<id>/download # download statistic data def download_bash_history # save statistic bash history statistic = Statistic.find(params[:id]) # Download bash histories and analytics in a file bash_analytics = "" statistic.bash_analytics.each do |analytic| bash_analytics = bash_analytics + "#{analytic}" + "\n" end file_text = "Scenario #{statistic.scenario_name} created at #{statistic.scenario_created_at}\nStatistic #{statistic.id} created at #{statistic.created_at}\n\nBash Histories: \n \n#{statistic.bash_histories} \nBash Analytics: \n#{bash_analytics}" file_path = "#{Rails.root}/data/statistics/#{statistic.id}_Statistic_#{statistic.scenario_name}.txt" file_name = "#{statistic.id}_Statistic_#{statistic.scenario_name}.txt" if File.exist?(file_path) send_file(file_path, filename: file_name, type: "application/txt") else send_data(file_text, filename: file_name, type: "application/txt") end end def download_exit_status # Download exit statuses statistic = Statistic.find(params[:id]) exit_status_text = "Scenario #{statistic.scenario_name} created at #{statistic.scenario_created_at}\nStatistic #{statistic.id} created at #{statistic.created_at}\n\nExit Status Data: \n \n#{statistic.exit_status} \n" exit_status_path = "#{Rails.root}/data/statistics/#{statistic.id}_Exit_Status_#{statistic.scenario_name}.txt" exit_status_name = "#{statistic.id}_Exit_Status_#{statistic.scenario_name}.txt" if File.exist?(exit_status_path) send_file(exit_status_path, filename: exit_status_name, type: "application/txt") else send_data(exit_status_text, filename: exit_status_name, type: "application/txt") end end def download_script_log # Download script logs statistic = Statistic.find(params[:id]) script_log_text = "Scenario #{statistic.scenario_name} created at #{statistic.scenario_created_at}\nStatistic #{statistic.id} created at #{statistic.created_at}\n\nScript Log Data: \n \n#{statistic.script_log} \n" script_log_path = "#{Rails.root}/data/statistics/#{statistic.id}_Script_Log_#{statistic.scenario_name}.txt" script_log_name = "#{statistic.id}_Script_Log_#{statistic.scenario_name}.txt" if File.exist?(script_log_path) send_file(script_log_path, filename: script_log_name, type: "application/txt") else send_data(script_log_text, filename: script_log_name, type: "application/txt") end end # method called via AJAX request, sends javascript response after performing analytics def generate_analytics # parameters passed in via query string, see comment above statistic = Statistic.find(params[:id]) # yank statistic entry user = params[:user] # array of usernames # start_time = params[:start_time] # start of time window (as string) # end_time = params[:end_time] # end of time window (also as string) # find relevant commands based on query params above if statistic.bash_analytics.keys.include?(user) && statistic.bash_analytics[user] != {} times = statistic.bash_analytics[user].keys.sort start = times[0] end_ = times[-1] commands = statistic.grab_relevant_commands(user, start, end_) # perform analytics on the comands & put into serializable form @analytics = statistic.perform_analytics(commands).to_json respond_to do |format| format.js{ render js: "new Chartkick.ColumnChart('chart', #{@analytics});" } end else respond_to do |format| format.js{ render js: "alert('User not in scenario.');"} end end end end
clampz/edurange
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # before_filter :authenticate_user! AWS.config({ :access_key_id => Settings.access_key_id, :secret_access_key => Settings.secret_access_key, }) include Pundit # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized helper_method :nat_instance private def nat_instance(nat_instance = nil) @nat_instance ||= nat_instance end def user_not_authorized flash[:alert] = "Access denied." redirect_to (request.referrer || root_path) end def authenticate_admin if user_signed_in? @user = User.find(current_user.id) if @user.is_admin? return end end redirect_to '/' end def authenticate_instructor if user_signed_in? @user = User.find(current_user.id) if @user.is_instructor? return end end redirect_to '/' end def authenticate_admin_or_instructor if user_signed_in? @user = User.find(current_user.id) if @user.is_admin? || @user.is_instructor? return end end redirect_to '/' end def authenticate_student if user_signed_in? @user = User.find(current_user.id) if @user.is_student? return end end redirect_to '/' end end
clampz/edurange
app/models/instance.rb
class Instance < ActiveRecord::Base include Provider include Aws validates_presence_of :name, :os, :subnet belongs_to :subnet has_many :instance_groups, dependent: :destroy has_many :instance_roles, dependent: :destroy has_many :groups, through: :instance_groups, dependent: :destroy has_many :roles, through: :instance_roles, dependent: :destroy has_one :user, through: :subnet has_one :scenario, through: :subnet before_create :ensure_has_ip validates :name, presence: true, uniqueness: { scope: :subnet, message: "Name taken" } validates :ip_address, presence: true validate :ip_address_validate, :internet_accessible_validate, :validate_stopped after_destroy :update_scenario_modified before_destroy :validate_stopped def validate_stopped if not self.stopped? errors.add(:running, "can not modify while scenario is booted") return false end if self.scenario.modifiable? self.scenario.update_attribute(:modified, true) end true end def update_scenario_modified if self.scenario.modifiable? self.scenario.update_attribute(:modified, true) end true end def role_add(role_name) if not self.stopped? errors.add(:running, 'instance must be stopped to add role') return false end self.roles.each do |r| if r.name == role_name self.errors.add(:role_name, "Instance already has #{role_name}") return false end end if not role = self.scenario.roles.find_by_name(role_name) self.errors.add(:role_name, "Role does not exist") return false end ir = self.instance_roles.new(role_id: role.id) ir.save update_scenario_modified return ir end def ip_address_validate ip = IPAddress.valid_ipv4?(self.ip_address) if not ip errors.add(:ip_address, "IP Address is not valid") return end if not NetAddr::CIDR.create(self.subnet.cidr_block).cmp(self.ip_address) errors.add(:ip_address, "IP Address is not within instances subnet #{self.subnet.name} #{self.subnet.cidr_block}") return end self.subnet.instances.each do |instance| next if self == instance if self.ip_address == instance.ip_address errors.add(:ip_address, "IP Address is taken") end end end def internet_accessible_validate if self.internet_accessible and not self.subnet.internet_accessible errors.add(:internet_accessible, "Instances subnet must also be internet accessible") end end def bootable? return (self.stopped? and self.subnet.booted?) end def unbootable? return (self.booted? or self.boot_failed? or self.unboot_failed?) end def generate_cookbooker # template = File.read(Settings.app_path + "lib/templates/cookbook_template_new.rb.erb") # template = Erubis::Eruby.new(template) cookbook = "# Instance cookbook\n" self.roles.each do |role| role.recipes.each do |recipe| fname = Settings.app_path + "scenarios/recipes/" + recipe + ".rb.erb" if File.file?(fname) cookbook += Erubis::Eruby.new(File.read(fname)).result + "\n" end end end cookbook end def scenario return self.subnet.cloud.scenario end def owner?(id) return self.subnet.cloud.scenario.user_id == id end def status_check puts "\nstatus check\n" if self.driver_id if AWS::EC2.new.instances[self.driver_id].exists? # check if it is running else self.driver_id = nil self.set_stopped self.save end end end def get_bash_history return "" if (!self.bash_history_page or (self.bash_history_page == "")) begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] if bucket.objects[self.aws_instance_bash_history_page_name].exists? bash_history = bucket.objects[self.aws_instance_bash_history_page_name].read() return bash_history == nil ? "" : bash_history end rescue return "error getting bash history" end return "" end def get_exit_status return "" if (!self.exit_status_page or (self.exit_status_page == "")) begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] if bucket.objects[self.aws_instance_exit_status_page_name].exists? exit_status = bucket.objects[self.aws_instance_exit_status_page_name].read() return exit_status == nil ? "" : exit_status end rescue return "error getting exit status" end return "" end def get_script_log return "" if (!self.script_log_page or (self.script_log_page == "")) begin s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] if bucket.objects[self.aws_instance_script_log_page_name].exists? script_log = bucket.objects[self.aws_instance_script_log_page_name].read() return script_log == nil ? "" : script_log end rescue return "error getting script log" end return "" end def get_chef_error return "" if !self.bash_history_page s3 = AWS::S3.new bucket = s3.buckets[Settings.bucket_name] if bucket.objects[self.aws_instance_com_page_name].exists? chef_err = bucket.objects[self.aws_instance_com_page_name].read() return chef_err == nil ? "" : chef_err end return "" end def initialized? return "-" if !self.com_page begin com_page = AWS::S3.new.buckets[Settings.bucket_name].objects[self.aws_instance_com_page_name] if com_page.exists? text = com_page.read() status = text.split("\n")[0] if status == "error" return "chef script error" elsif status == "finished" return "true" end end rescue AWS::S3::Errors::NoSuchKey return false end "initializing" end def port_open?(ip, port) begin Timeout::timeout(1) do begin s = TCPSocket.open(ip, port) s.close return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH return false end end rescue Timeout::Error end return false end def ssh_ready? if ip = self.aws_instance_public_ip if (self.port_open?(ip, 22)) return true end end return false end def ensure_has_ip if self.ip_address.blank? return false # TODO set this to a valid IP in subnet cidr end true end def s3_name_prefix scenario = self.subnet.cloud.scenario return scenario.user.name + scenario.name + scenario.id.to_s + scenario.uuid end def add_progress(val) # debug "Adding progress to instance!" # PrivatePub.publish_to "/scenarios/#{self.subnet.cloud.scenario.id}", instance_progress: val end def debug(message) log = self.log ? self.log : '' message = '' if !message self.update_attribute(:log, log + message + "\n") end def generate_init begin # Returns the bash code to initialize an instance with chef-solo init = "" os_bootstrap_path = "#{Settings.app_path}scenarios/bootstrap/os_#{self.os.filename_safe}.sh.erb" if File.exists? os_bootstrap_path init += Erubis::Eruby.new(File.read(os_bootstrap_path)).result(instance: self) + "\n" end init += Erubis::Eruby.new(File.read(Settings.app_path + "scenarios/bootstrap/chef.sh.erb")).result(instance: self) + "\n" init += Erubis::Eruby.new(File.read(Settings.app_path + "scenarios/bootstrap/sshd_password_login.sh.erb")).result(instance: self) + "\n" # Erubis::Eruby.new(File.read(Settings.app_path + "scenarios/recipes/templates/bootstrap.sh.erb")).result(instance: self) + "\n" init rescue raise return end end def generate_cookbook begin # Find out if this is a global or custom recipe scenario_path = "#{Settings.app_path}scenarios/user/#{self.scenario.user.name.filename_safe}/#{self.scenario.name.filename_safe}" scenario_path = "#{Settings.app_path}scenarios/local/#{self.scenario.name.filename_safe}" if not File.exists? scenario_path # This recipe sets up packages and users and is run for every instance cookbook = Erubis::Eruby.new(File.read("#{Settings.app_path}scenarios/recipes/templates/packages_and_users.rb.erb")).result(instance: self) + "\n" self.roles.each do |role| role.recipes.each do |recipe| if recipe.custom cookbook += recipe.text + "\n" else cookbook += Erubis::Eruby.new(recipe.text).result(instance: self) + "\n" end end end # This recipe signals the com page and also gets the bash histories cookbook += Erubis::Eruby.new(File.read("#{Settings.app_path}scenarios/recipes/templates/com_page_and_bash_histories.rb.erb")).result(instance: self) + "\n" # This recipe changes /etc/bash.bashrc so that the bash history is written to file with every command cookbook += Erubis::Eruby.new(File.read("#{Settings.app_path}scenarios/recipes/templates/write_bash_histories.rb.erb")).result(instance: self) + "\n" cookbook rescue raise return end end # Handy user methods def administrators groups = self.instance_groups.select {|instance_group| instance_group.administrator }.map {|instance_group| instance_group.group} users = groups.inject([]) {|users, group| users.concat(group.players) } end def users groups = self.instance_groups.select {|instance_group| !instance_group.administrator }.map {|instance_group| instance_group.group} users = groups.inject([]) {|users, group| users.concat(group.players) } end def add_administrator(group) InstanceGroup.create(group: group, instance: self, administrator: true) end def add_user(group) InstanceGroup.create(group: group, instance: self, administrator: false) end end
clampz/edurange
app/models/role.rb
<reponame>clampz/edurange<gh_stars>0 class Role < ActiveRecord::Base belongs_to :scenario has_many :role_recipes, dependent: :destroy has_many :recipes, through: :role_recipes has_many :instance_roles, dependent: :destroy has_one :user, through: :scenario serialize :packages, Array validates :name, presence: true, uniqueness: { scope: :scenario, message: "Name taken" } validate :instances_stopped before_destroy :instances_stopped, prepend: :true after_destroy :update_scenario_modified def instances_stopped self.instance_roles.each do |instance_role| if not instance_role.instance.stopped? errors.add(:running, "instances using this role must be stopped before deletion") return false end end if self.scenario.modifiable? self.scenario.update(modified: true) end true end def update_scenario_modified if self.scenario.modifiable? self.scenario.update_attribute(:modified, true) end true end def instances_stopped? self.instance_roles.each do |instance_role| return false if not instance_role.instance.stopped? end true end end
clampz/edurange
lib/yml_record.rb
<filename>lib/yml_record.rb<gh_stars>0 module YmlRecord # Returns an array of [filename, scenario name, description] def self.yml_headers_old output = [] Dir.foreach(Settings.app_path + "scenarios-yml/") do |filename| next if filename == '.' or filename == '..' or filename == 'ddos.yml' scenario = YAML.load_file(Settings.app_path + "scenarios-yml/#{filename}")["Scenarios"][0] name = scenario["Name"] description = scenario["Description"] output.push [filename, name, description] end return output end def self.yml_headers(location, user) output = [] if location == 'custom' path = Settings.app_path + "scenarios/custom/#{user.id}" else path = Settings.app_path + "scenarios/#{location}" end Dir.foreach(path) do |filename| next if filename == '.' or filename == '..' filepath = "#{path}/#{filename}/#{filename}.yml" if File.exists? filepath file = YAML.load_file(filepath) output.push( { filename: filename, name: file["Name"], description: file["Description"], location: location } ) end end return output end def self.yml_headers_user(user) output = [] Dir.foreach(Settings.app_path + "scenarios/user/#{user.id}") do |filename| next if filename == '.' or filename == '..' file = YAML.load_file(Settings.app_path + "scenarios/user/#{user.id}/#{filename}/#{filename}.yml") output.push( { filename: filename, name: file["Name"], description: file["Description"] } ) end return output end def self.get_scoring_info(yaml_file) file = YAML.load_file(yaml_file) return [file["Scenarios"][0]["Name"], file["Answers"]] end # Returns a new Scenario with subobjects def self.load_yml(name, user) name_lookup_hash = Hash.new # Because in the YML we establish relationships by name we need to keep track of # what unique id corresponds to the current loading of the scenario. Whenever we # create an object, we store it within the above hash so that we can look it up # later in this function when we are creating objects referencing things in the database. pathname = "scenarios/local/#{name.downcase}/#{name.downcase}.yml" if File.exists? pathname cusotm = false else custom = true pathname = "scenarios/user/#{user.id}/#{name.downcase}/#{name.downcase}.yml" end file = YAML.load_file(Settings.app_path + pathname) # file = YAML.load_file(Settings.app_path + "scenarios/local/#{name.filename_safe}/#{name.filename_safe}.yml") scenarios = file["Scenarios"] clouds = file["Clouds"] subnets = file["Subnets"] instances = file["Instances"] roles = file["Roles"] groups = file["Groups"] scoring = file["Scoring"] scenario = Scenario.new scenario.custom = custom scenario.name = file["Name"] scenario.description = file["Description"] scenario.instructions = file["Instructions"] ? file["Instructions"] : "" scenario.instructions_student = file["InstructionsStudent"] ? file["InstructionsStudent"] : "" answers ||= [] scenario.answers = answers.join("\n") scenario.uuid = `uuidgen`.chomp scenario.user = user scenario.save! name_lookup_hash[scenario.name] = scenario.id if roles roles.each do |yaml_role| role = scenario.roles.new role.name = yaml_role["Name"] if yaml_role["Recipes"] yaml_role["Recipes"].each do |recipe_name| recipe = scenario.recipes.find_by_name(recipe_name) if not recipe recipe = scenario.recipes.new(name: recipe_name) end recipe.save role_recipe = role.role_recipes.new(recipe_id: recipe.id) scenario.save end end if yaml_role["Packages"] yaml_role["Packages"].each { |package| role.packages << package } end role.save! name_lookup_hash[role.name] = role.id end end cloud = nil if clouds clouds.each do |yaml_cloud| # scenario = Scenario.find(name_lookup_hash[yaml_cloud["Scenario"]]) cloud = scenario.clouds.new cloud.name = yaml_cloud["Name"] cloud.cidr_block = yaml_cloud["CIDR_Block"] cloud.save! name_lookup_hash[cloud.name] = cloud.id end end if subnets subnets.each do |yaml_subnet| cloud = Cloud.find(name_lookup_hash[yaml_subnet["Cloud"]]) subnet = cloud.subnets.new subnet.name = yaml_subnet["Name"] subnet.cidr_block = yaml_subnet["CIDR_Block"] if yaml_subnet["Internet_Accessible"] subnet.internet_accessible = true end subnet.save! name_lookup_hash[subnet.name] = subnet.id end end instance = nil instance_ips = {} if instances instances.each do |yaml_instance| instance = Instance.new instance_roles = yaml_instance["Roles"] instance.subnet = Subnet.find(name_lookup_hash[yaml_instance["Subnet"]]) instance.name = yaml_instance["Name"] ipaddress, instance_ips = self.parse_ip(yaml_instance["IP_Address"], instance_ips) if ipaddress == nil scenario.destroy raise "ERROR - could not assign IP adress to Instance" end instance.ip_address = ipaddress if yaml_instance["Internet_Accessible"] instance.internet_accessible = true end instance.os = yaml_instance["OS"] instance_roles.each do |instance_role| role = Role.find(name_lookup_hash[instance_role]) instance.roles << role end instance.uuid = `uuidgen`.chomp instance.save! name_lookup_hash[instance.name] = instance.id end end if groups groups.each do |yaml_group| users = yaml_group["Users"] access = yaml_group["Access"] admin = access["Administrator"] user = access["User"] group = Group.new group.name = yaml_group["Name"] group.instructions = yaml_group["Instructions"] ? yaml_group["Instructions"] : "" group.scenario_id = scenario.id group.save! if users users.each do |user| login = user["Login"] password = user["Password"] player = group.players.new player.login = login player.password = password player.group = group player.user_id = user["UserId"] player.student_group_id = user["StudentGroupId"] if user_id = user["Id"] if User.find_by_id(user_id) player.save! end else player.save! end end end # Give group admin on machines they own if admin admin.each do |admin_instance| instance = Instance.find(name_lookup_hash[admin_instance]) instance.add_administrator(group) instance.save! end end if user user.each do |user_instance| instance = Instance.find(name_lookup_hash[user_instance]) instance.add_user(group) instance.save! end end end end # Do scoring if scoring scoring.each do |yml_question| question = scenario.questions.new(type_of: yml_question['Type'], text: yml_question['Text']) if yml_question["Options"] yml_question['Options'].each do |opt| question.options << opt end end if yml_question["Values"] question.values = [] yml_question['Values'].each do |val| question.values << { value: val["Value"], points: val["Points"] } end end question.points = yml_question["Points"] question.order = yml_question["Order"] question.save! end end scenario.update(modified: false) scenario.save return scenario # Return the scenario we created end def self.write_yml(yaml_file, scenario) File.open(yaml_file, 'w') do |f| f.puts scenario.to_yaml end end def self.parse_ip(ip, ips) ipnew = "" block = ips ran = nil ip_split = ip.split(".") ip_split.each_with_index do |num, i| # get block or create new one if not i == ip_split.size - 1 if block[num] block = block[num] else # insert hash unless last block then insert array if i== (ip_split.size - 2) block[num] = [] else block[num] = {} end block = block[num] end end # If range num = num.split("-") if num.size > 1 # get low and high ranges low = num[0].to_i high = num[1].to_i # if last block check for room, if no room return false if i == ip_split.size-1 if high-low+1 <= block.size return nil, nil end end # get random number, reroll if already taken ran = Random.new.rand(num[0].to_i..num[1].to_i).to_s until not block.include?(ran) ran = Random.new.rand(num[0].to_i..num[1].to_i).to_s end ipnew += ran + "." else ipnew += num[0] + "." end end block.push(ran) return ipnew.chop, ips end end
clampz/edurange
app/controllers/student_controller.rb
class StudentController < ApplicationController # layout 'student' before_action :authenticate_student before_action :set_user before_action :set_scenario, only: [:show, :answer_string, :answer_number, :answer_essay] before_action :set_question, only: [:answer_string, :answer_number, :answer_essay] before_action :set_answer, only: [:answer_essay_delete, :answer_essay_show] def index @scenarios = [] Player.where(user_id: current_user.id).each do |p| @scenarios << p.scenario if not @scenarios.include? p.scenario end end def show end def answer_string @answer = @question.answer_string(params[:text], @user.id) respond_to do |format| format.js { render "student/js/answer_string.js.erb", layout: false } end end def answer_number @answer = @question.answer_number(params[:text], @user.id) respond_to do |format| format.js { render "student/js/answer_number.js.erb", layout: false } end end def answer_essay @answer = @question.answer_essay(params[:text], @user.id) respond_to do |format| format.js { render "student/js/answer_essay.js.erb", layout: false } end end def answer_essay_delete @answer.destroy respond_to do |format| format.js { render "student/js/answer_essay_delete.js.erb", layout: false } end end def answer_essay_show respond_to do |format| format.js { render "student/js/answer_essay_show.js.erb", layout: false } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(current_user.id) end def set_scenario if @scenario = Scenario.find_by_id(params[:id]) if not @scenario.has_student? @user redirect_to '/student' end else redirect_to '/student' end end def set_question @question = Question.find(params[:question_id]) if not @scenario.questions.find_by_id(@question.id) head :ok, content_type: "text/html" return end end def set_answer @answer = Answer.find(params[:answer_id]) if not @user.owns? @answer head :ok, content_type: "text/html" return end end end
clampz/edurange
app/models/group.rb
class Group < ActiveRecord::Base belongs_to :scenario has_many :instance_groups, dependent: :destroy has_many :instances, through: :instance_groups has_many :players, dependent: :destroy has_one :user, through: :scenario validates :name, presence: true, uniqueness: { scope: :scenario, message: "Name taken" } validate :instances_stopped after_save :update_scenario_modified before_destroy :instances_stopped after_destroy :update_scenario_modified def update_scenario_modified if self.scenario.modifiable? return self.scenario.update_attribute(:modified, true) end end def administrative_access_to instances = self.instance_groups.select {|instance_group| instance_group.administrator }.map {|instance_group| instance_group.instance} end def instances_stopped self.instance_groups.each do |instance_group| if not instance_group.instance.stopped? errors.add(:running, "instances with access must be stopped before modificaton of group") return false end end true end def instances_stopped? self.instance_groups.each do |instance_group| if not instance_group.instance.stopped? errors.add(:running, 'instances with access must be stopped to modify group') return false end end true end def user_access_to instances = self.instance_groups.select {|instance_group| !instance_group.administrator }.map {|instance_group| instance_group.instance} end def student_group_add(student_group_name) if not self.instances_stopped? return [] end players = [] user = User.find(self.scenario.user.id) if not student_group = user.student_groups.find_by_name(student_group_name) errors.add(:name, "student group not found") return end student_group.student_group_users.each do |student_group_user| if not self.players.where("user_id = #{student_group_user.user_id} AND student_group_id = #{student_group.id}").first cnt = 1 login = "#{student_group_user.user.name.filename_safe}" while self.players.find_by_login(login) cnt += 1 login = login += cnt.to_s end player = self.players.new( login: login, password: <PASSWORD>64[0..8], user_id: student_group_user.user.id, student_group_id: student_group_user.student_group.id ) player.save players.push(player) end end self.update_scenario_modified players end def student_group_remove(student_group_name) if not self.instances_stopped? return [] end players = [] user = User.find(self.scenario.user.id) if not student_group = user.student_groups.find_by_name(student_group_name) errors.add(:name, "student group not found") return end student_group.student_group_users.each do |student_group_user| if player = self.players.find_by_user_id(student_group_user.user.id) players.push(player) player.delete end end self.update_scenario_modified players end def find_player_by_student_id(student_id) self.players.each do |player| if player.user return player if player.user.id == student_id end end nil end def update_instructions(instructions) self.update_attribute(:instructions, instructions) self.update_scenario_modified end end
aznalo/Qhapaq-back
controllers/genre.rb
# ジャンル一覧 get '/genres' do Genre.all.to_json end # ジャンルの詳細 get '/genre/:id' do Genre.find_by(id: params[:id]).to_json end # ジャンルの作成 post '/genre' do genre_params = JSON.parse(request.body.read) (status 403) unless User.authentication(genre_params['userToken']) genre = Genre.new({ name: genre_params['name'] }) if genre.save status 201 else status 500 end end # 該当IDのジャンル削除 delete '/genre/:id' do (status 403) unless User.authentication(genre_params['userToken']) genre = Genre.find_by(id: params[:id]) if genre genre.destroy else status 404 end end # 該当IDのジャンル編集 post '/genre/:id' do genre_params = JSON.parse(request.body.read) # (status 403) unless User.authentication(genre_params['userToken']) genre = Genre.find_by(id: params[:id]) if genre genre.update({name: genre_params['name']}) genre.to_json else status 404 end end
aznalo/Qhapaq-back
db/seeds.rb
genres = ['主食', '副菜', '汁物', '甘味'] genres.each do |t| Genre.create(name: t) end [ {name: '鯖の味噌煮', genre: '主食', category: '和食'}, {name: '回鍋肉', genre: '主食', category: '中華'}, {name: '白身魚のナージュ', genre: '主食', category: 'フレンチ'}, {name: 'なめこの味噌汁', genre: '汁物', category: '和食'}, {name: 'プリン', genre: '甘味', category: 'その他'}, ].each do |t| unless category = Category.find_by(name: t[:category]) category = Category.create(name: t[:category]) end Menu.create( name: t[:name], genre: Genre.find_by(name: t[:genre]), category: category ) end User.new( name: 'Administrator', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ).save
aznalo/Qhapaq-back
app.rb
require 'bundler/setup' Bundler.require require 'sinatra/reloader' if development? require 'pry' if development? require './models' set :server, 'thin' set :sockets, [] before do Time.zone = 'Tokyo' content_type :json headers 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => %w[GET POST PUT DELETE] end not_found do { error: 404 }.to_json end
aznalo/Qhapaq-back
controllers/user.rb
<reponame>aznalo/Qhapaq-back # ユーザのログイン用 post '/user/sign_in' do user_params = JSON.parse(request.body.read) user = User.find_by(name: user_params['name']) if user && user.authenticate(user_params['password']) token = UserToken.create( user_id: user.id, uuid: SecureRandom.uuid, expiration_time: Time.zone.now.since(1.hours) ) { user: { name: user.name }, token: token.uuid, expiration_time: token.expiration_time }.to_json else status 400 end end # ユーザーの作成用 post '/user/sign_up/:token' do #TODO #ユーザーのアカウント作成はAdminアカウントからのユーザー作成用URLを発行し、 #そのURLから一定時間以内はアカウントを作れるようにする end get '/authentication/:token' do if User.authentication(params[:token]) body ({status: 'successful'}.to_json) status 201 else body ({status: 'failure'}.to_json) status 403 end end
aznalo/Qhapaq-back
db/migrate/20190210021320_create_menus.rb
class CreateMenus < ActiveRecord::Migration[5.2] def change create_table :menus do |t| t.integer :category_id, null: false t.integer :genre_id , null: false t.string :name, null: false t.string :description t.timestamps null: false end end end
aznalo/Qhapaq-back
controllers/menu.rb
# index get '/menus' do Menu.all.to_json end # genre filter menus get '/menus/:id' do Genre.find_by(id: params[:id]).menus.to_json end #show get '/menu/:id' do menu = Menu.find_by(id: params[:id]) menu.attributes.merge({ ingredients: menu.ingredients, steps: menu.steps }).to_json end # create post '/menu' do menu_params = JSON.parse(request.body.read) (status 403) unless User.authentication(menu_params['userToken']) menu = Menu.new(parseMenu(menu_params)) status 500 unless menu.save menu_params['ingredients'].each { |v| updateIngredients(menu, v) } menu_params['steps'].each { |v| updateSteps(menu, v) } menu.to_json end # update post '/menu/:id' do menu_params = JSON.parse(request.body.read) (status 403) unless User.authentication(menu_params['userToken']) menu = Menu.find_by(id: params[:id]) status 404 unless menu status 500 unless menu.update(parseMenu(menu_params)) menu_params['ingredients'].each { |v| updateIngredients(menu, v) } menu_params['steps'].each { |v| updateSteps(menu, v) } menu_params['removeIngredientItemList'].each { |v| Ingredient.find_by(id: v['id']).destroy } menu_params['removeStepItemList'].each { |v| Step.find_by(id: v['id']).destroy } menu.to_json end private def parseMenu(params) { genre: Genre.find_by(id: params['genre_id']), category_id: 1, name: params['name'] } end def updateIngredients(menu, params) ingredient = Ingredient.find_or_initialize_by( name: params['name'], menu: menu ) ingredient.update_attributes( menu: menu, name: params['name'], amount: params['amount'], unit: params['unit'], cost: params['cost'], description: params['description'] ) end def updateSteps(menu, params) step = Step.find_or_initialize_by( description: params['description'], menu: menu ) step.update_attributes( menu: menu, description: params['description'] ) end
aznalo/Qhapaq-back
db/migrate/20190210044513_create_user_tokens.rb
<gh_stars>1-10 class CreateUserTokens < ActiveRecord::Migration[5.2] def change create_table :user_tokens do |t| t.integer :user_id, null: false t.string :uuid t.datetime :expiration_time, null: false t.timestamps null: false end end end
aznalo/Qhapaq-back
db/migrate/20190210021356_create_ingredients.rb
<filename>db/migrate/20190210021356_create_ingredients.rb<gh_stars>1-10 class CreateIngredients < ActiveRecord::Migration[5.2] def change create_table :ingredients do |t| t.integer :menu_id, null: false t.string :name, null: false t.integer :amount, null: false, default: 0 t.string :unit, null: false, default: '個' t.integer :cost, null: false, default: 0 t.string :description t.timestamps null: false end end end
aznalo/Qhapaq-back
controllers/category.rb
<filename>controllers/category.rb<gh_stars>1-10 get '/categories' do Category.all end
aznalo/Qhapaq-back
models.rb
<filename>models.rb require 'bundler/setup' Bundler.require require './controllers/user' require './controllers/genre' require './controllers/category' require './controllers/menu' config = YAML.load_file('./database.yml') ActiveRecord::Base.configurations = config if development? ActiveRecord::Base.establish_connection(config['development']) else ActiveRecord::Base.establish_connection(config['production']) end Time.zone = 'Tokyo' ActiveRecord::Base.default_timezone = :local after do ActiveRecord::Base.connection.close end class User < ActiveRecord::Base has_secure_password has_many :user_tokens, dependent: :destroy def self.authentication(token) token = UserToken.find_by(uuid: token) return token && token.user && Time.zone.now < token.expiration_time end end class UserToken < ActiveRecord::Base belongs_to :user end class Genre < ActiveRecord::Base has_many :menus, dependent: :destroy end class Menu < ActiveRecord::Base belongs_to :genre belongs_to :category has_many :ingredients, dependent: :destroy has_many :steps, dependent: :destroy end class Ingredient < ActiveRecord::Base belongs_to :menu end class Category < ActiveRecord::Base has_many :menus, dependent: :destroy end class Step < ActiveRecord::Base belongs_to :menu end
hi-artem/homebrew-boringssl
bssl.rb
class Bssl < Formula desc "BoringSSL is a fork of OpenSSL that is designed to meet Google's needs" homepage "https://boringssl.googlesource.com/boringssl/" url "https://boringssl.googlesource.com/boringssl/+archive/1607f54fed72c6589d560254626909a64124f091.tar.gz" version "1607f54fed72c6589d560254626909a64124f091" sha256 "ee6e653f86018ec3731527c89ef36f474c0ba812d52fbd53443001e10404d35f" depends_on "cmake" depends_on "go" depends_on "ninja" def install mkdir "build" do system "cmake", "-GNinja", ".." system "ninja" bin.install "tool/bssl" end end test do assert_match "0", shell_output("#{bin}/bssl isfips 2>&1") end end
TheClimateCorporation/coherence-2-x-swift-4
Coherence.podspec
<filename>Coherence.podspec # # Be sure to run `pod lib lint Coherence.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "Coherence" s.version = "2.1.0" s.summary = "Coherence" s.description = <<-DESC Coherence is a collection of base frameworks that help set the groundwork for module development. DESC s.homepage = "https://github.com/tonystone/coherence" s.license = 'Apache License, Version 2.0' s.author = "<NAME>" s.source = { :git => "https://github.com/TheClimateCorporation/coherence-2-x-swift-4.git", :tag => s.version.to_s } s.platform = :ios, '9.0' s.requires_arc = true s.module_name = 'Coherence' s.default_subspecs = ['Configuration', 'Stack'] s.subspec 'ConfigurationCore' do |sp| sp.requires_arc = false sp.source_files = 'Sources/ConfigurationCore/**/*' end s.subspec 'Configuration' do |sp| sp.dependency 'Coherence/ConfigurationCore' sp.source_files = 'Sources/Configuration/*' end s.subspec 'Stack' do |sp| sp.source_files = 'Sources/Stack/*' end s.dependency 'TraceLog', ">= 2.0", "< 5.0" s.dependency 'TraceLog/ObjC', ">= 2.0", "< 5.0" end
voxpupuli/puppet-lint-classes_and_types_beginning_with_digits-check
spec/puppet-lint/plugins/classes_and_types_beginning_with_digits/classes_and_types_beginning_with_digits_spec.rb
<gh_stars>0 require 'spec_helper' describe 'classes_and_types_beginning_with_digits' do let (:msg) { 'class or defined type found beginning with a digit' } context 'with fix disabled' do context 'no classes or defined types that begin with digits' do let (:code) { <<-EOS class apache {} define virtualhost {} class rule_10 {} define rule_34 {} EOS } it 'should not detect any problems' do expect(problems).to have(0).problems end end context 'unquoted numbers with leading zero' do let (:code) { <<-EOS class 0apache {} define 3virtualhost {} class 01234apache {} define 3456virtualhost {} EOS } it 'should detect a single problem' do expect(problems).to have(4).problems end it 'should create a warning' do expect(problems).to contain_warning(msg).on_line(1).in_column(9) end end end context 'with fix enabled' do before do PuppetLint.configuration.fix = true end after do PuppetLint.configuration.fix = false end context 'no unquoted numbers with leading zero' do let (:code) { <<-EOS class apache {} define virtualhost {} class rule_10 {} define rule_34 {} EOS } it 'should not detect any problems' do expect(problems).to have(0).problems end it 'should not modify the manifest' do expect(manifest).to eq(code) end end context 'unquoted numbers with leading zero' do let (:code) { <<-EOS class 0apache {} define 3virtualhost {} class 01234my_apache {} define 3456my_virtualhost {} EOS } it 'should detect a single problem' do expect(problems).to have(4).problems end it 'should fix the problem' do expect(problems).to contain_fixed(msg).on_line(1).in_column(9) end it 'should should use undef' do expect(manifest).to eq( <<-EOS class apache {} define virtualhost {} class my_apache {} define my_virtualhost {} EOS ) end end end end
voxpupuli/puppet-lint-classes_and_types_beginning_with_digits-check
lib/puppet-lint/plugins/classes_and_types_beginning_with_digits.rb
PuppetLint.new_check(:classes_and_types_beginning_with_digits) do def check tokens.each do |token| if (token.type == :CLASS) or (token.type == :DEFINE) if token.next_code_token.value =~ /^\d+/ notify :warning, { :message => 'class or defined type found beginning with a digit', :line => token.line, :column => token.column, :token => token, } end end end end def fix(problem) problem[:token].next_code_token.value.gsub!(/^\d+/,'') end end
naruhito/Checkout-Ruby-SDK
lib/core/version.rb
<gh_stars>1-10 module PayPal VERSION = "1.0.3" end
naruhito/Checkout-Ruby-SDK
samples/authorize_intent_examples/capture_order.rb
<reponame>naruhito/Checkout-Ruby-SDK require_relative '../paypal_client' include PayPalCheckoutSdk::Payments module Samples module AuthorizeIntentExamples class CaptureOrder # This function can be used to perform capture on an authorization. # An valid authorization id dhould be passed as an argument. def capture_order (authorization_id, debug=false) request = AuthorizationsCaptureRequest::new(authorization_id) request.prefer("return=representation") #Below request bodyn can be updated with fields as per business need. Please refer API docs for more info. request.request_body({}) begin response = PayPalClient::client::execute(request) if debug puts "Status Code: #{response.status_code}" puts "Status: #{response.result.status}" puts "Order ID: #{response.result.id}" puts "Intent: #{response.result.intent}" puts "Links:" for link in response.result.links # this could also be called as link.rel or link.href but as method is a reserved keyword for ruby avoid calling link.method puts "\t#{link["rel"]}: #{link["href"]}\tCall Type: #{link["method"]}" end puts PayPalClient::openstruct_to_hash(response.result).to_json end return response rescue BraintreeHttp::HttpError => ioe # Exception occured while processing the refund. puts " Status Code: #{ioe.status_code}" puts " Debug Id: #{ioe.result.debug_id}" puts " Response: #{ioe.result}" end end end end end # This is the driver function which invokes the capture_order function with valid authorization id # Authorization Id should be replaced with an valid authorization id. if __FILE__ == $0 Samples::AuthorizeIntentExamples::CaptureOrder::new::capture_order('4KH16819Y83216409',true) end
naruhito/Checkout-Ruby-SDK
spec/orders/orders_validate_spec.rb
require_relative '../test_harness' require_relative '../../lib/lib' require 'json' include PayPalCheckoutSdk::Orders describe OrdersValidateRequest do it 'successfully makes a request' , :skip => 'This test is an example, in production, orders require payer approval' do request = OrdersValidateRequest.new("ORDER-ID") resp = TestHarness::client.execute(request) expect(resp.status_code).to eq(200) expect(resp.result).not_to be_nil end end
naruhito/Checkout-Ruby-SDK
spec/payments/authorizations_reauthorize_spec.rb
<filename>spec/payments/authorizations_reauthorize_spec.rb require_relative '../test_harness' require_relative '../../lib/lib' require 'json' include PayPalCheckoutSdk::Payments describe AuthorizationsReauthorizeRequest do it 'successfully makes a request', :skip => 'This test is an example, in production, orders require payer approval' do request = AuthorizationsReauthorizeRequest.new("xtIHGdKgdA25uQzr") resp = TestHarness::client.execute(request) expect(resp.status_code).to eq(201) expect(resp.result).not_to be_nil end end
naruhito/Checkout-Ruby-SDK
samples/patch_order.rb
require_relative './paypal_client' require_relative './capture_intent_examples/create_order' require_relative './get_order' include PayPalCheckoutSdk::Orders module Samples class PatchOrder # Below function can be used to patch and order. # Patch is supported on only specific set of fields. # Please refer API docs for more info. def patch_order(order_id) body = [{ op:'replace', path:"/purchase_units/@reference_id=='PUHF'/description", value:'Sporting goods description' }, { op: 'replace', path: "/purchase_units/@reference_id=='PUHF'/custom_id", value: 'CUST-ID-HighFashions' } ] request = OrdersPatchRequest::new(order_id) request.request_body(body) response = PayPalClient::client::execute(request) return response end end end # Driver function which does below steps. # 1. Create an Order # 2. Patch fields in the newly created order. # 3. Print the updated fields by calling the get order. if __FILE__ == $0 begin order= Samples::CaptureIntentExamples::CreateOrder::new::create_order.result patch_response = Samples::PatchOrder::new::patch_order(order.id) puts "patch_response status code ::: #{patch_response.status_code}" if patch_response.status_code == 204 order = Samples::GetOrder::new::get_order(order.id) puts "Updated Description: #{order.result.purchase_units[0].description}" puts "Updated Custom Id: #{order.result.purchase_units[0].custom_id}" puts PayPalClient::openstruct_to_hash(order.result).to_json end rescue BraintreeHttp::HttpError => ioe # Exception occured while processing the refund. puts " Status Code: #{ioe.status_code}" puts " Debug Id: #{ioe.result.debug_id}" puts " Response: #{ioe.result}" end end
naruhito/Checkout-Ruby-SDK
samples/get_order.rb
<filename>samples/get_order.rb require_relative './paypal_client' require_relative './authorize_intent_examples/create_order' require 'json' require 'ostruct' include PayPalCheckoutSdk::Orders module Samples class GetOrder # This function can be used to retrieve an order by passing order id as argument def get_order(order_id) request = OrdersGetRequest::new(order_id) begin response = PayPalClient::client::execute(request) puts "Status Code: #{response.status_code}" puts "Status: #{response.result.status}" puts "Order ID: #{response.result.id}" puts "Intent: #{response.result.intent}" puts "Links:" for link in response.result.links # this could also be called as link.rel or link.href but as method is a reserved keyword for ruby avoid calling link.method puts "\t#{link["rel"]}: #{link["href"]}\tCall Type: #{link["method"]}" end puts "Gross Amount: #{response.result.purchase_units[0].amount.currency_code} #{response.result.purchase_units[0].amount.value}" puts PayPalClient::openstruct_to_hash(response.result).to_json return response rescue BraintreeHttp::HttpError => ioe # Exception occured while processing the refund. puts " Status Code: #{ioe.status_code}" puts " Debug Id: #{ioe.result.debug_id}" puts " Response: #{ioe.result}" end end end end # This is the driver function which invokes the get_order function with order id to retrieve # an sample order. For the order id, we invoke the create order to create an new order and then we are using # the newly created order id for retrieving the order if __FILE__ == $0 id = Samples::AuthorizeIntentExamples::CreateOrder::new::create_order.result.id; Samples::GetOrder::new::get_order(id) end
naruhito/Checkout-Ruby-SDK
lib/core/access_token.rb
<reponame>naruhito/Checkout-Ruby-SDK module PayPal class AccessToken attr_accessor :access_token, :token_type, :expires_in, :date_created def initialize(options) @access_token = options.access_token @token_type = options.token_type @expires_in = options.expires_in * 1000 @date_created = Time.now end def isExpired return Time.now > @date_created + @expires_in end def authorizationString return "#{@token_type} #{@access_token}" end end end
naruhito/Checkout-Ruby-SDK
spec/orders/orders_patch_spec.rb
require_relative '../test_harness' require_relative './orders_helper' require 'json' include PayPalCheckoutSdk::Orders describe OrdersPatchRequest do def build_request_body return [ { "op": "add", "path": "/purchase_units/@reference_id=='test_ref_id1'/description", "value": "added_description" }, { "op": "replace", "path": "/purchase_units/@reference_id=='test_ref_id1'/amount", "value": { "currency_code": "USD", "value": "200.00" } } ] end it 'successfully makes a request' do create_resp = OrdersHelper::create_order request = OrdersPatchRequest.new(create_resp.result.id) request.request_body(build_request_body) resp = TestHarness::client.execute(request) expect(resp.status_code).to eq(204) resp = OrdersHelper::get_order create_resp.result.id expect(resp.status_code).to eq(200) expect(resp.result).not_to be_nil expect(resp.result.intent).to eq('CAPTURE') expect(resp.result.purchase_units.count).to eq(1) expect(resp.result.purchase_units[0].reference_id).to eq('test_ref_id1') expect(resp.result.purchase_units[0].amount.currency_code).to eq('USD') expect(resp.result.purchase_units[0].amount.value).to eq('200.00') expect(resp.result.purchase_units[0].description).to eq('added_description') expect(resp.result.create_time).not_to be_nil expect(resp.result.links).not_to be_nil found_approve = false for link in resp.result.links if "approve" === link.rel expect(link["href"]).not_to be_nil expect(link["method"]).to eq("GET") found_approve = true end end expect(found_approve).to be_truthy expect(resp.result.status).to eq('CREATED') end end
naruhito/Checkout-Ruby-SDK
lib/paypal-checkout-sdk.rb
<reponame>naruhito/Checkout-Ruby-SDK<filename>lib/paypal-checkout-sdk.rb require_relative './lib'
lee-dohm/lush
lib/lush/version.rb
<reponame>lee-dohm/lush # # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # # Contains all code pertaining to the `lush` shell. module Lush # Version of the shell. VERSION = '0.0.1' end
lee-dohm/lush
spec/commands/change_directory_spec.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # require 'tmpdir' describe ChangeDirectory do let!(:original) { Dir.pwd } before do $stdout = StringIO.new $stderr = StringIO.new end after do Dir.chdir(original) $stdout = STDOUT $stderr = STDERR end subject { ChangeDirectory.new(path) } context 'when given a valid path' do let(:path) { File.realdirpath(Dir.tmpdir) } its(:directory) { should eq(path) } context 'and executed' do before { subject.execute } specify { expect(Dir.pwd).to eq(path) } end end context 'when given an invalid path' do let(:path) { '/invalid-path' } its(:directory) { should eq(path) } context 'and executed' do before { subject.execute } specify { expect(Dir.pwd).to eq(original) } specify { expect($stderr.string).to match(/No such directory/) } end end end
lee-dohm/lush
spec/commands/export_variable_spec.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # describe ExportVariable do let(:env) { {} } before { redirect_standard_streams } after { reset_standard_streams } context 'when given a key and value' do subject(:command) { ExportVariable.new('KEY', 'value') } before do command.env = env command.execute end specify { expect(env['KEY']).to eq('value') } end context 'when given a key and no value' do subject(:command) { ExportVariable.new('KEY', '') } before do command.env = env command.execute end specify { expect(env['KEY']).to be_nil } end context 'when given the -p parameter' do subject(:command) { ExportVariable.new('-p') } before do command.env = { 'foo' => 'one', 'bar' => 'two', 'baz' => 'three' } command.execute end specify do expect($stdout.string).to eq("export bar=two\nexport baz=three\nexport foo=one\n") end end context 'when given no arguments' do subject(:command) { ExportVariable.new } before do command.env = { 'foo' => 'one', 'bar' => 'two', 'baz' => 'three' } command.execute end specify do expect($stdout.string).to eq("bar=two\nbaz=three\nfoo=one\n") end end end
lee-dohm/lush
spec/spec_helper.rb
<filename>spec/spec_helper.rb # # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # require 'lush' include Lush::Commands # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. root = File.expand_path('../..', __FILE__) Dir[File.join(root, 'spec/support/**/*.rb')].each { |f| require f }
lee-dohm/lush
lib/lush/streams.rb
<reponame>lee-dohm/lush # # Copyright (c) 2014 by <NAME>. All Rights Reserved. # module Lush # Encapsulates all the stream shuffling code for dealing with creating and managing pipelines. class Streams # Stream to use for `STDIN`. attr_reader :in # Stream to use for `STDOUT`. attr_reader :out # Initializes a new instance of the `Streams` class. def initialize @in = $stdin @out = $stdout @pipe = [] end # Closes any finished streams. def close @out.close unless @out == $stdout @in.close unless @in == $stdin @in = @pipe.first end # Updates the stream values to the next stage in the pipeline. # # The `pipe` parameter should be true if there is another command in the pipeline and a set of # streams needs to be created to manage the pipeline. If the `pipe` parameter is false, then # `STDOUT` is set to be used as the outbound stream. # # @param [Boolean] pipe Flag indicating if there is another pipeline segment. def next(pipe: false) if pipe @pipe = IO.pipe @out = @pipe.last else @out = $stdout end end # Updates the standard streams, if necessary. def reopen reopen_out reopen_in end private # Updates `STDIN` to point to `in`, if necessary. def reopen_in unless @in == $stdin $stdin.reopen(@in) @in.close end end # Updates `STDOUT` to point to `out`, if necessary. def reopen_out unless @out == $stdout $stdout.reopen(@out) @out.close end end end end
lee-dohm/lush
spec/support/stream_redirection.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # # Redirects standard streams into `StringIO` objects to capture the output of code. def redirect_standard_streams $stdout = StringIO.new $stderr = StringIO.new end # Resets standard streams to normal. def reset_standard_streams $stdout = STDOUT $stderr = STDERR end
lee-dohm/lush
lib/lush/commands/command.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # module Lush module Commands # Base class for all built-in commands. class Command # Initializes the command with the supplied arguments. # # @param [Array<String>] args Arguments passed to the command. def initialize(*args) @args = args end # Executes the command according to the arguments. # # @raise [NotImplementedError] Cannot execute this base class. def execute raise NotImplementedError, 'Cannot execute a base Command' end end end end
lee-dohm/lush
lib/lush/commands/exit_shell.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # module Lush module Commands # Represents the `exit` built-in command. # # @see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_21 # POSIX shell exit command class ExitShell < Command # Status to return to the operating system upon exit. attr_reader :status # @param [Boolean, Fixnum] status Status to return to the operating system upon exit. def initialize(status = true) @status = status end # Executes the `exit` command. # # @raise [SystemExit] Signal to exit the shell. # @return [nil] def execute exit(@status) end end end end
lee-dohm/lush
spec/commands/exit_shell_spec.rb
<reponame>lee-dohm/lush<filename>spec/commands/exit_shell_spec.rb # # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # describe ExitShell do def exit_status(command) begin command.execute rescue SystemExit => e return e.status end raise 'Expected to raise SystemExit but did not raise an error.' end def success?(command) begin command.execute rescue SystemExit => e return e.success? end raise 'Expected to raise SystemExit but did not raise an error.' end context 'when given no value' do subject(:command) { ExitShell.new } specify { expect { command.execute }.to raise_error(SystemExit) } specify { expect(exit_status(command)).to eq(0) } specify { expect(success?(command)).to be_true } end context 'when given true' do subject(:command) { ExitShell.new(true) } its(:status) { should be_true } specify { expect { command.execute }.to raise_error(SystemExit) } specify { expect(exit_status(command)).to eq(0) } specify { expect(success?(command)).to be_true } end context 'when given false' do subject(:command) { ExitShell.new(false) } its(:status) { should be_false } specify { expect { command.execute }.to raise_error(SystemExit) } specify { expect(exit_status(command)).to eq(1) } specify { expect(success?(command)).to be_false } end context 'when given a non-zero numeric value' do subject(:command) { ExitShell.new(5) } its(:status) { should eq(5) } specify { expect { command.execute }.to raise_error(SystemExit) } specify { expect(exit_status(command)).to eq(5) } specify { expect(success?(command)).to be_false } end context 'when given zero as the status' do subject(:command) { ExitShell.new(0) } its(:status) { should be_true } specify { expect { command.execute }.to raise_error(SystemExit) } specify { expect(exit_status(command)).to eq(0) } specify { expect(success?(command)).to be_true } end end
lee-dohm/lush
lib/lush/commands/change_directory.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # module Lush module Commands # Represents the `cd` command. # # @see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cd.html#top POSIX shell cd # command class ChangeDirectory < Command # Directory to which to change upon executing. attr_reader :directory # @param [Array<String>] args Arguments passed to the command. def initialize(*args) super(*args) @directory = @args.first end # Executes the `cd` command. # # @return [nil] def execute begin Dir.chdir(@directory) rescue Errno::ENOENT $stderr.puts "ChangeDirectory: No such directory: #{@directory}" end nil end end end end
lee-dohm/lush
lib/lush/commands/export_variable.rb
<filename>lib/lush/commands/export_variable.rb # # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # module Lush module Commands # Represents the `export` built-in command. # # @see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_22 # POSIX shell export command class ExportVariable < Command # Environment to modify. Defaults to `ENV`. attr_writer :env # Initializes a new instance of the `ExportVariable` class. # # @param [Array<String>] args Arguments passed to the command. def initialize(*args) super(*args) @env = ENV end # Executes the command. # # @return [nil] def execute case when @args.empty? dump_environment when @args.first == '-p' dump_environment(export_prefix: true) else set_variable end nil end private # Dumps the environment to standard out. # # @param [Boolean] export_prefix Flag indicating whether to print the `export` prefix before # the environment variable on each line. def dump_environment(export_prefix: false) prefix = 'export ' if export_prefix @env.keys.sort.each { |k| $stdout.puts "#{prefix}#{k}=#{@env[k]}" } end # Sets the variable. def set_variable key = @args.first value = @args[1].empty? ? nil : @args[1] @env[key] = value end end end end
lee-dohm/lush
lib/lush/cli.rb
<reponame>lee-dohm/lush # # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # require 'shellwords' module Lush # Handles the command-line interface of the shell. class CLI # List of built in commands and Command class. BUILTINS = { 'cd' => Lush::Commands::ChangeDirectory, 'exit' => Lush::Commands::ExitShell, 'export' => Lush::Commands::ExportVariable } # Creates a new instance of the `CLI` class. def initialize init_prompt end # Executes the REPL. def run loop do print_prompt line = read_command_line commands = split_on_pipes(line) execute_commands(commands) end end private # Determines if `program` is a built-in command. # # @param [String] program Name of the program to execute. # @return [Boolean] Flag indicating whether `program` is a built-in command. def builtin?(program) BUILTINS.key?(program) end # Executes a built-in command. # # @param [String] program Name of the program to execute. # @param [Array<String>] arguments Arguments for the program. def call_builtin(program, *arguments) command = BUILTINS[program].new(*arguments) command.execute end # rubocop:disable MethodLength # Executes the list of commands. # # @param commands List of commands obtained from the command line. def execute_commands(commands) streams = Streams.new commands.each_with_index do |command, index| program, *arguments = Shellwords.shellsplit(command) if builtin?(program) call_builtin(program, *arguments) else streams.next(pipe: index + 1 < commands.size) spawn_program(program, *arguments, streams) streams.close end end Process.waitall end # rubocop:enable MethodLength # Gets the command line from the user. # # @return [String] Command-line text to execute. def read_command_line $stdin.gets.strip end # Initializes the command-line prompt string. def init_prompt ENV['PROMPT'] = '-> ' end # Displays the prompt. def print_prompt $stdout.print(ENV['PROMPT']) end # Executes the given program in a sub-process. # # @param [String] program Name of the program to execute. # @param [Array<String>] arguments Arguments to supply to the program. # @param [Streams] streams Set of streams to use for input and output. def spawn_program(program, *arguments, streams) fork do # Must be done within the context of the fork to only reassign the standard streams in the # subprocess. streams.reopen exec program, *arguments end end # Splits a command line on pipe delimiters. # # @param [String] line Command line text. # @return [Array<String>] List of pipeline components. def split_on_pipes(line) line.scan(/([^"'|]+)|["']([^"']+)["']/).flatten.compact end end end
lee-dohm/lush
lib/lush.rb
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # require 'lush/commands' require 'lush/cli' require 'lush/streams' require 'lush/version'
lee-dohm/lush
lib/lush/commands.rb
<reponame>lee-dohm/lush # # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # require 'lush/commands/command' require 'lush/commands/change_directory' require 'lush/commands/exit_shell' require 'lush/commands/export_variable' module Lush # Contains all built-in command definitions. module Commands nil end end
etagwerker/astor
spec/astor/browser_spec.rb
require "spec_helper" RSpec.describe Astor::Browser do describe "browse" do context "simple assignments" do let(:result) { "y = 1" } it "displays a simple AST" do node = RubyVM::AbstractSyntaxTree.parse("y = 1") displayed = Astor::Browser.browse(node) expect(displayed).to eq(result) end end context "simple assignment with formula" do let(:result) { "y = x + 1" } it "displays a simple AST" do node = RubyVM::AbstractSyntaxTree.parse("y = x + 1") displayed = Astor::Browser.browse(node) expect(displayed).to eq(result) end end end describe "visit" do context "when assignment is simple" do it "displays all types" do node = RubyVM::AbstractSyntaxTree.parse("y = 1") visited = Astor::Browser.visit(node) expect(visited).to eq("SCOPEyLASGNyLIT1") end end context "when assignment is complex" do it "displays all types" do node = RubyVM::AbstractSyntaxTree.parse("y = x + 1") visited = Astor::Browser.visit(node) expect(visited).to eq("SCOPEyLASGNyOPCALLVCALLx+LISTLIT1") end end end end
etagwerker/astor
spec/astor_spec.rb
RSpec.describe Astor do it "has a version number" do expect(Astor::VERSION).not_to be nil end end
etagwerker/astor
lib/astor/browser.rb
<reponame>etagwerker/astor module Astor class Browser class << self def visit(node, level = 0) prepend = ("\t" * level * 2) if (node.respond_to?(:type)) result = prepend + "#{node.type}\n" if node.children.any? result += "<CHILDREN>\t" node.children.compact.each do |child| result += visit(child, level + 1) end result += "</CHILDREN>" end elsif node.is_a?(Array) result = prepend + node.join(", ") else result = prepend + "#{node}\n" end result end def browse(node) if node.type == :SCOPE display_scope(node) else display_children(node) end end def display_node(node) if node.respond_to?(:type) send("display_#{node.type.to_s.downcase}", node) elsif node.is_a?(Array) node[0].to_s else node.to_s end end def display_children(node) node.children.map { |x| display_node(x) }.compact.join(" ") end def display_array(node) "[#{display_children(node).strip}]" end def display_args(node) "(#{display_children(node)})" end def display_begin(node) "\n" end def display_block(node) "" end def display_call(node) "." end def display_list(node) node.children.compact.each do |child| browse(child) end end def display_class(node) "class #{display_children(node)}\nend" end def display_colon2(node) "" end def display_defn(node) "def #{display_children(node)}\nend" end def display_dstr(node) "" end def display_str(node) "" end def display_dvar(node) "DVAR" end def display_opcall(node) "= #{display_children(node)}" end def display_else(node) "else \n" end def display_evstr(node) "\#{" end def display_fcall(node) "..." end def display_if(node) "if " end def display_iter(node) "ITER" end def display_lasgn(node) # byebug # "#{display_node(node.children[0])} = #{display_node(node.children[1])}" display_children(node) end def display_lvar(node) "????" end def display_lit(node) display_children(node) end def display_module(node) "module " end def display_scope(node) children = node.children.select {|x| x.respond_to?(:children) } children.map {|x| display_node(x) }.join(" ") end def display_sclass(node) "class <<\n\nend" end def display_self(node) "self" end def display_vcall(node) display_children(node) end end end end
etagwerker/astor
lib/astor.rb
<reponame>etagwerker/astor require "astor/version" require "astor/browser" module Astor end
baldowl/cucumber-rails
lib/cucumber/rails/version.rb
module Cucumber module Rails VERSION = '0.4.0' DEPS = { 'aruba' => '>= 0.3.4', 'cucumber' => '>= 0.10.1', 'bundler' => '>= 1.0.10', 'rack-test' => '>= 0.5.7', 'nokogiri' => '>= 1.4.4', 'rails' => '>= 3.0.3', 'capybara' => '>= 0.4.1', 'webrat' => '>= 0.7.3', 'rspec-rails' => '>= 2.2.0', 'database_cleaner' => '>= 0.6.0', 'sqlite3-ruby' => '>= 1.3.3', 'mongoid' => '>= 2.0.0.rc.7', 'akephalos' => '>= 0.2.5' } end end
baldowl/cucumber-rails
lib/cucumber/rails/capybara/select_dates_and_times.rb
<filename>lib/cucumber/rails/capybara/select_dates_and_times.rb module Cucumber module Rails module Capybara module SelectDatesAndTimes def select_date(field, options = {}) date = Date.parse(options[:with]) base_dom_id = get_base_dom_id_from_label_tag(field) find(:xpath, "//select[@id='#{base_dom_id}_1i']").select(date.year.to_s) find(:xpath, "//select[@id='#{base_dom_id}_2i']").select(date.strftime('%B')) find(:xpath, "//select[@id='#{base_dom_id}_3i']").select(date.day.to_s) end def select_time(field, options = {}) time = Time.zone.parse(options[:with]) base_dom_id = get_base_dom_id_from_label_tag(field) find(:xpath, "//select[@id='#{base_dom_id}_4i']").select(time.hour.to_s.rjust(2, '0')) find(:xpath, "//select[@id='#{base_dom_id}_5i']").select(time.min.to_s.rjust(2, '0')) end def select_datetime(field, options = {}) select_date(field, options) select_time(field, options) end private # @example "event_starts_at_" def get_base_dom_id_from_label_tag(field) find(:xpath, "//label[contains(., '#{field}')]")['for'].gsub(/(1i)$/, '') end end end end end World(::Cucumber::Rails::Capybara::SelectDatesAndTimes) When /^(?:|I )select "([^"]+)" as the "([^"]+)" time$/ do |time, selector| select_time(selector, :with => time) end When /^(?:|I )select "([^"]+)" as the "([^"]+)" date$/ do |date, selector| select_date(selector, :with => date) end When /^(?:|I )select "([^"]+)" as the "([^"]+)" date and time$/ do |datetime, selector| select_datetime(selector, :with => datetime) end
baldowl/cucumber-rails
cucumber-rails.gemspec
# -*- encoding: utf-8 -*- $LOAD_PATH.unshift File.expand_path("../lib", __FILE__) require 'cucumber/rails/version' Gem::Specification.new do |s| s.name = 'cucumber-rails' s.version = Cucumber::Rails::VERSION s.authors = ["<NAME>", "<NAME>", "<NAME>"] s.description = "Cucumber Generators and Runtime for Rails" s.summary = "cucumber-rails-#{s.version}" s.email = '<EMAIL>' s.homepage = "http://cukes.info" s.add_dependency('cucumber', Cucumber::Rails::DEPS['cucumber']) s.add_dependency('rack-test', Cucumber::Rails::DEPS['rack-test']) s.add_dependency('nokogiri', Cucumber::Rails::DEPS['nokogiri']) s.add_development_dependency('bundler', Cucumber::Rails::DEPS['bundler']) s.add_development_dependency('aruba', Cucumber::Rails::DEPS['aruba']) s.add_development_dependency('rails', Cucumber::Rails::DEPS['rails']) s.add_development_dependency('sqlite3-ruby', Cucumber::Rails::DEPS['sqlite3-ruby']) s.add_development_dependency('rspec-rails', Cucumber::Rails::DEPS['rspec-rails']) s.add_development_dependency('capybara', Cucumber::Rails::DEPS['capybara']) s.add_development_dependency('webrat', Cucumber::Rails::DEPS['webrat']) s.add_development_dependency('database_cleaner', Cucumber::Rails::DEPS['database_cleaner']) s.add_development_dependency('mongoid', Cucumber::Rails::DEPS['mongoid']) s.add_development_dependency('akephalos', Cucumber::Rails::DEPS['akephalos']) s.rubygems_version = ">= 1.6.1" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.extra_rdoc_files = ["LICENSE", "README.rdoc", "History.txt"] s.rdoc_options = ["--charset=UTF-8"] s.require_path = "lib" end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/constant.rb
# frozen_string_literal: false ## # A constant class RDoc::Constant < RDoc::CodeObject MARSHAL_VERSION = 0 # :nodoc: ## # Sets the module or class this is constant is an alias for. attr_writer :is_alias_for ## # The constant's name attr_accessor :name ## # The constant's value attr_accessor :value ## # The constant's visibility attr_accessor :visibility ## # Creates a new constant with +name+, +value+ and +comment+ def initialize(name, value, comment) super() @name = name @value = value @is_alias_for = nil @visibility = nil self.comment = comment end ## # Constants are ordered by name def <=> other return unless self.class === other [parent_name, name] <=> [other.parent_name, other.name] end ## # Constants are equal when their #parent and #name is the same def == other self.class == other.class and @parent == other.parent and @name == other.name end ## # A constant is documented if it has a comment, or is an alias # for a documented class or module. def documented? return true if super return false unless @is_alias_for case @is_alias_for when String then found = @store.find_class_or_module @is_alias_for return false unless found @is_alias_for = found end @is_alias_for.documented? end ## # Full constant name including namespace def full_name @full_name ||= "#{parent_name}::#{@name}" end ## # The module or class this constant is an alias for def is_alias_for case @is_alias_for when String then found = @store.find_class_or_module @is_alias_for @is_alias_for = found if found @is_alias_for else @is_alias_for end end def inspect # :nodoc: "#<%s:0x%x %s::%s>" % [ self.class, object_id, parent_name, @name, ] end ## # Dumps this Constant for use by ri. See also #marshal_load def marshal_dump alias_name = case found = is_alias_for when RDoc::CodeObject then found.full_name else found end [ MARSHAL_VERSION, @name, full_name, @visibility, alias_name, parse(@comment), @file.relative_name, parent.name, parent.class, section.title, ] end ## # Loads this Constant from +array+. For a loaded Constant the following # methods will return cached values: # # * #full_name # * #parent_name def marshal_load array initialize array[1], nil, array[5] @full_name = array[2] @visibility = array[3] @is_alias_for = array[4] # 5 handled above # 6 handled below @parent_name = array[7] @parent_class = array[8] @section_title = array[9] @file = RDoc::TopLevel.new array[6] end ## # Path to this constant for use with HTML generator output. def path "#{@parent.path}##{@name}" end def pretty_print q # :nodoc: q.group 2, "[#{self.class.name} #{full_name}", "]" do unless comment.empty? then q.breakable q.text "comment:" q.breakable q.pp @comment end end end ## # Sets the store for this class or module and its contained code objects. def store= store super @file = @store.add_file @file.full_name if @file end def to_s # :nodoc: parent_name = parent ? parent.full_name : '(unknown)' if is_alias_for "constant #{parent_name}::#@name -> #{is_alias_for}" else "constant #{parent_name}::#@name" end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/pathname/lib/pathname.rb
<gh_stars>0 # # = pathname.rb # # Object-Oriented Pathname Class # # Author:: <NAME> <<EMAIL>> # Documentation:: Author and <NAME> # # For documentation, see class Pathname. # # <tt>pathname.rb</tt> is distributed with Ruby since 1.8.0. # require 'pathname.so' class Pathname # :stopdoc: if RUBY_VERSION < "1.9" TO_PATH = :to_str else # to_path is implemented so Pathname objects are usable with File.open, etc. TO_PATH = :to_path end SAME_PATHS = if File::FNM_SYSCASE.nonzero? proc {|a, b| a.casecmp(b).zero?} else proc {|a, b| a == b} end # :startdoc: if File::ALT_SEPARATOR SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}" SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/ else SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}" SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/ end # chop_basename(path) -> [pre-basename, basename] or nil def chop_basename(path) base = File.basename(path) if /\A#{SEPARATOR_PAT}?\z/o =~ base return nil else return path[0, path.rindex(base)], base end end private :chop_basename # split_names(path) -> prefix, [name, ...] def split_names(path) names = [] while r = chop_basename(path) path, basename = r names.unshift basename end return path, names end private :split_names def prepend_prefix(prefix, relpath) if relpath.empty? File.dirname(prefix) elsif /#{SEPARATOR_PAT}/o =~ prefix prefix = File.dirname(prefix) prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a' prefix + relpath else prefix + relpath end end private :prepend_prefix # Returns clean pathname of +self+ with consecutive slashes and useless dots # removed. The filesystem is not accessed. # # If +consider_symlink+ is +true+, then a more conservative algorithm is used # to avoid breaking symbolic linkages. This may retain more <tt>..</tt> # entries than absolutely necessary, but without accessing the filesystem, # this can't be avoided. See #realpath. # def cleanpath(consider_symlink=false) if consider_symlink cleanpath_conservative else cleanpath_aggressive end end # # Clean the path simply by resolving and removing excess "." and ".." entries. # Nothing more, nothing less. # def cleanpath_aggressive path = @path names = [] pre = path while r = chop_basename(pre) pre, base = r case base when '.' when '..' names.unshift base else if names[0] == '..' names.shift else names.unshift base end end end if /#{SEPARATOR_PAT}/o =~ File.basename(pre) names.shift while names[0] == '..' end self.class.new(prepend_prefix(pre, File.join(*names))) end private :cleanpath_aggressive # has_trailing_separator?(path) -> bool def has_trailing_separator?(path) if r = chop_basename(path) pre, basename = r pre.length + basename.length < path.length else false end end private :has_trailing_separator? # add_trailing_separator(path) -> path def add_trailing_separator(path) if File.basename(path + 'a') == 'a' path else File.join(path, "") # xxx: Is File.join is appropriate to add separator? end end private :add_trailing_separator def del_trailing_separator(path) if r = chop_basename(path) pre, basename = r pre + basename elsif /#{SEPARATOR_PAT}+\z/o =~ path $` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o] else path end end private :del_trailing_separator def cleanpath_conservative path = @path names = [] pre = path while r = chop_basename(pre) pre, base = r names.unshift base if base != '.' end if /#{SEPARATOR_PAT}/o =~ File.basename(pre) names.shift while names[0] == '..' end if names.empty? self.class.new(File.dirname(pre)) else if names.last != '..' && File.basename(path) == '.' names << '.' end result = prepend_prefix(pre, File.join(*names)) if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path) self.class.new(add_trailing_separator(result)) else self.class.new(result) end end end private :cleanpath_conservative # #parent returns the parent directory. # # This is same as <tt>self + '..'</tt>. def parent self + '..' end # #mountpoint? returns +true+ if <tt>self</tt> points to a mountpoint. def mountpoint? begin stat1 = self.lstat stat2 = self.parent.lstat stat1.dev == stat2.dev && stat1.ino == stat2.ino || stat1.dev != stat2.dev rescue Errno::ENOENT false end end # # #root? is a predicate for root directories. I.e. it returns +true+ if the # pathname consists of consecutive slashes. # # It doesn't access actual filesystem. So it may return +false+ for some # pathnames which points to roots such as <tt>/usr/..</tt>. # def root? !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path) end # Predicate method for testing whether a path is absolute. # It returns +true+ if the pathname begins with a slash. def absolute? !relative? end # The opposite of #absolute? def relative? path = @path while r = chop_basename(path) path, = r end path == '' end # # Iterates over each component of the path. # # Pathname.new("/usr/bin/ruby").each_filename {|filename| ... } # # yields "usr", "bin", and "ruby". # def each_filename # :yield: filename return to_enum(__method__) unless block_given? _, names = split_names(@path) names.each {|filename| yield filename } nil end # Iterates over and yields a new Pathname object # for each element in the given path in descending order. # # Pathname.new('/path/to/some/file.rb').descend {|v| p v} # #<Pathname:/> # #<Pathname:/path> # #<Pathname:/path/to> # #<Pathname:/path/to/some> # #<Pathname:/path/to/some/file.rb> # # Pathname.new('path/to/some/file.rb').descend {|v| p v} # #<Pathname:path> # #<Pathname:path/to> # #<Pathname:path/to/some> # #<Pathname:path/to/some/file.rb> # # It doesn't access actual filesystem. # # This method is available since 1.8.5. # def descend vs = [] ascend {|v| vs << v } vs.reverse_each {|v| yield v } nil end # Iterates over and yields a new Pathname object # for each element in the given path in ascending order. # # Pathname.new('/path/to/some/file.rb').ascend {|v| p v} # #<Pathname:/path/to/some/file.rb> # #<Pathname:/path/to/some> # #<Pathname:/path/to> # #<Pathname:/path> # #<Pathname:/> # # Pathname.new('path/to/some/file.rb').ascend {|v| p v} # #<Pathname:path/to/some/file.rb> # #<Pathname:path/to/some> # #<Pathname:path/to> # #<Pathname:path> # # It doesn't access actual filesystem. # # This method is available since 1.8.5. # def ascend path = @path yield self while r = chop_basename(path) path, = r break if path.empty? yield self.class.new(del_trailing_separator(path)) end end # # Pathname#+ appends a pathname fragment to this one to produce a new Pathname # object. # # p1 = Pathname.new("/usr") # Pathname:/usr # p2 = p1 + "bin/ruby" # Pathname:/usr/bin/ruby # p3 = p1 + "/etc/passwd" # Pathname:/etc/passwd # # This method doesn't access the file system; it is pure string manipulation. # def +(other) other = Pathname.new(other) unless Pathname === other Pathname.new(plus(@path, other.to_s)) end def plus(path1, path2) # -> path prefix2 = path2 index_list2 = [] basename_list2 = [] while r2 = chop_basename(prefix2) prefix2, basename2 = r2 index_list2.unshift prefix2.length basename_list2.unshift basename2 end return path2 if prefix2 != '' prefix1 = path1 while true while !basename_list2.empty? && basename_list2.first == '.' index_list2.shift basename_list2.shift end break unless r1 = chop_basename(prefix1) prefix1, basename1 = r1 next if basename1 == '.' if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..' prefix1 = prefix1 + basename1 break end index_list2.shift basename_list2.shift end r1 = chop_basename(prefix1) if !r1 && /#{SEPARATOR_PAT}/o =~ File.basename(prefix1) while !basename_list2.empty? && basename_list2.first == '..' index_list2.shift basename_list2.shift end end if !basename_list2.empty? suffix2 = path2[index_list2.first..-1] r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2 else r1 ? prefix1 : File.dirname(prefix1) end end private :plus # # Pathname#join joins pathnames. # # <tt>path0.join(path1, ..., pathN)</tt> is the same as # <tt>path0 + path1 + ... + pathN</tt>. # def join(*args) args.unshift self result = args.pop result = Pathname.new(result) unless Pathname === result return result if result.absolute? args.reverse_each {|arg| arg = Pathname.new(arg) unless Pathname === arg result = arg + result return result if result.absolute? } result end # # Returns the children of the directory (files and subdirectories, not # recursive) as an array of Pathname objects. By default, the returned # pathnames will have enough information to access the files. If you set # +with_directory+ to +false+, then the returned pathnames will contain the # filename only. # # For example: # pn = Pathname("/usr/lib/ruby/1.8") # pn.children # # -> [ Pathname:/usr/lib/ruby/1.8/English.rb, # Pathname:/usr/lib/ruby/1.8/Env.rb, # Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ] # pn.children(false) # # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ] # # Note that the results never contain the entries <tt>.</tt> and <tt>..</tt> in # the directory because they are not children. # # This method has existed since 1.8.1. # def children(with_directory=true) with_directory = false if @path == '.' result = [] Dir.foreach(@path) {|e| next if e == '.' || e == '..' if with_directory result << self.class.new(File.join(@path, e)) else result << self.class.new(e) end } result end # Iterates over the children of the directory # (files and subdirectories, not recursive). # It yields Pathname object for each child. # By default, the yielded pathnames will have enough information to access the files. # If you set +with_directory+ to +false+, then the returned pathnames will contain the filename only. # # Pathname("/usr/local").each_child {|f| p f } # #=> #<Pathname:/usr/local/share> # # #<Pathname:/usr/local/bin> # # #<Pathname:/usr/local/games> # # #<Pathname:/usr/local/lib> # # #<Pathname:/usr/local/include> # # #<Pathname:/usr/local/sbin> # # #<Pathname:/usr/local/src> # # #<Pathname:/usr/local/man> # # Pathname("/usr/local").each_child(false) {|f| p f } # #=> #<Pathname:share> # # #<Pathname:bin> # # #<Pathname:games> # # #<Pathname:lib> # # #<Pathname:include> # # #<Pathname:sbin> # # #<Pathname:src> # # #<Pathname:man> # def each_child(with_directory=true, &b) children(with_directory).each(&b) end # # #relative_path_from returns a relative path from the argument to the # receiver. If +self+ is absolute, the argument must be absolute too. If # +self+ is relative, the argument must be relative too. # # #relative_path_from doesn't access the filesystem. It assumes no symlinks. # # ArgumentError is raised when it cannot find a relative path. # # This method has existed since 1.8.1. # def relative_path_from(base_directory) dest_directory = self.cleanpath.to_s base_directory = base_directory.cleanpath.to_s dest_prefix = dest_directory dest_names = [] while r = chop_basename(dest_prefix) dest_prefix, basename = r dest_names.unshift basename if basename != '.' end base_prefix = base_directory base_names = [] while r = chop_basename(base_prefix) base_prefix, basename = r base_names.unshift basename if basename != '.' end unless SAME_PATHS[dest_prefix, base_prefix] raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}" end while !dest_names.empty? && !base_names.empty? && SAME_PATHS[dest_names.first, base_names.first] dest_names.shift base_names.shift end if base_names.include? '..' raise ArgumentError, "base_directory has ..: #{base_directory.inspect}" end base_names.fill('..') relpath_names = base_names + dest_names if relpath_names.empty? Pathname.new('.') else Pathname.new(File.join(*relpath_names)) end end end class Pathname # * Find * # # Pathname#find is an iterator to traverse a directory tree in a depth first # manner. It yields a Pathname for each file under "this" directory. # # Since it is implemented by <tt>find.rb</tt>, <tt>Find.prune</tt> can be used # to control the traversal. # # If +self+ is <tt>.</tt>, yielded pathnames begin with a filename in the # current directory, not <tt>./</tt>. # def find(&block) # :yield: pathname require 'find' if @path == '.' Find.find(@path) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) } else Find.find(@path) {|f| yield self.class.new(f) } end end end class Pathname # * FileUtils * # See <tt>FileUtils.mkpath</tt>. Creates a full path, including any # intermediate directories that don't yet exist. def mkpath require 'fileutils' FileUtils.mkpath(@path) nil end # See <tt>FileUtils.rm_r</tt>. Deletes a directory and all beneath it. def rmtree # The name "rmtree" is borrowed from File::Path of Perl. # File::Path provides "mkpath" and "rmtree". require 'fileutils' FileUtils.rm_r(@path) nil end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/spec/dummy_winrm_service.rb
<reponame>arnab0073/idea module Dummy class WinRMTransport attr_reader :httpcli def initialize @httpcli = HTTPClient.new end end class WinRMService attr_reader :xfer def initialize @xfer = WinRMTransport.new end def set_timeout(timeout); end def open_shell; end def run_command; end def get_command_output; end def cleanup_command; end def close_shell; end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/baremetal/chassis_collection.rb
<filename>.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/models/baremetal/chassis_collection.rb require 'fog/core/collection' require 'fog/openstack/models/baremetal/chassis' module Fog module Baremetal class OpenStack class ChassisCollection < Fog::Collection model Fog::Baremetal::OpenStack::Chassis def all load(service.list_chassis.body['chassis']) end def details(parameters=nil) load(service.list_chassis_detailed(parameters).body['chassis']) end def find_by_uuid(uuid) new(service.get_chassis(uuid).body) end alias_method :get, :find_by_uuid def destroy(uuid) chassis = self.find_by_id(uuid) chassis.destroy end def method_missing(method_sym, *arguments, &block) if method_sym.to_s =~ /^find_by_(.*)$/ load(service.list_chassis_detailed({$1 => arguments.first}).body['chassis']) else super end end end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/openstack/requests/orchestration/stack_tests.rb
Shindo.tests('Fog::Orchestration[:openstack] | stack requests', ['openstack']) do @stack_format = { 'links' => Array, 'id' => String, 'stack_name' => String, 'description' => Fog::Nullable::String, 'stack_status' => String, 'stack_status_reason' => String, 'creation_time' => Time, 'updated_time' => Time } @create_format = { 'id' => String, 'links' => Array, } tests('success') do tests('#create_stack("teststack")').formats(@create_format) do Fog::Orchestration[:openstack].create_stack("teststack").body end tests('#list_stack_data').formats({'stacks' => [@stack_format]}) do Fog::Orchestration[:openstack].list_stack_data.body end tests('#update_stack("teststack")').formats({}) do Fog::Orchestration[:openstack].update_stack("teststack").body end tests('#delete_stack("teststack", "id")').formats({}) do Fog::Orchestration[:openstack].delete_stack("teststack", "id").body end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/tool/file2lastrev.rb
<gh_stars>0 #!/usr/bin/env ruby ENV.delete('PWD') require 'optparse' unless File.respond_to? :realpath require 'pathname' def File.realpath(arg) Pathname(arg).realpath.to_s end end Program = $0 class VCS class NotFoundError < RuntimeError; end @@dirs = [] def self.register(dir) @@dirs << [dir, self] end def self.detect(path) @@dirs.sort.reverse_each do |dir, klass| return klass.new(path) if File.directory?("#{path}/#{dir}") end raise VCS::NotFoundError, "does not seem to be under a vcs: #{path}" end def initialize(path) @srcdir = path super() end # return a pair of strings, the last revision and the last revision in which # +path+ was modified. def get_revisions(path) path = relative_to(path) last, changed, *rest = Dir.chdir(@srcdir) {self.class.get_revisions(path)} last or raise "last revision not found" changed or raise "changed revision not found" return last, changed, *rest end def relative_to(path) if path srcdir = File.realpath(@srcdir) path = File.realpath(path) list1 = srcdir.split(%r{/}) list2 = path.split(%r{/}) while !list1.empty? && !list2.empty? && list1.first == list2.first list1.shift list2.shift end if list1.empty? && list2.empty? "." else ([".."] * list1.length + list2).join("/") end else '.' end end class SVN < self register(".svn") def self.get_revisions(path) begin nulldevice = %w[/dev/null NUL NIL: NL:].find {|dev| File.exist?(dev)} if nulldevice save_stderr = STDERR.dup STDERR.reopen nulldevice, 'w' end info_xml = `svn info --xml "#{path}"` ensure if save_stderr STDERR.reopen save_stderr save_stderr.close end end _, last, _, changed, _ = info_xml.split(/revision="(\d+)"/) [last, changed] end end class GIT < self register(".git") def self.get_revisions(path) logcmd = %Q[git log -n1 --grep="^ *git-svn-id: .*@[0-9][0-9]* "] idpat = /git-svn-id: .*?@(\d+) \S+\Z/ last = `#{logcmd}`[idpat, 1] changed = path ? `#{logcmd} "#{path}"`[idpat, 1] : last [last, changed] end end end @output = nil def self.output=(output) if @output and @output != output raise "you can specify only one of --changed, --revision.h and --doxygen" end @output = output end @suppress_not_found = false srcdir = nil parser = OptionParser.new {|opts| opts.on("--srcdir=PATH", "use PATH as source directory") do |path| srcdir = path end opts.on("--changed", "changed rev") do self.output = :changed end opts.on("--revision.h", "RUBY_REVISION macro") do self.output = :revision_h end opts.on("--doxygen", "Doxygen format") do self.output = :doxygen end opts.on("-q", "--suppress_not_found") do @suppress_not_found = true end } parser.parse! rescue abort "#{File.basename(Program)}: #{$!}\n#{parser}" srcdir = srcdir ? srcdir : File.dirname(File.dirname(Program)) begin vcs = VCS.detect(srcdir) rescue VCS::NotFoundError => e abort "#{File.basename(Program)}: #{e.message}" unless @suppress_not_found else begin last, changed = vcs.get_revisions(ARGV.shift) rescue => e abort "#{File.basename(Program)}: #{e.message}" unless @suppress_not_found exit false end end case @output when :changed, nil puts changed when :revision_h puts "#define RUBY_REVISION #{changed.to_i}" when :doxygen puts "r#{changed}/r#{last}" else raise "unknown output format `#{@output}'" end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/test_mapped_diagnostic_context.rb
<filename>.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/test_mapped_diagnostic_context.rb require File.expand_path('../setup', __FILE__) module TestLogging class TestMappedDiagnosticContext < Test::Unit::TestCase include LoggingTestCase def test_key_value_access assert_nil Logging.mdc['foo'] Logging.mdc['foo'] = 'bar' assert_equal 'bar', Logging.mdc[:foo] assert_same Logging.mdc['foo'], Logging.mdc[:foo] Logging.mdc.delete(:foo) assert_nil Logging.mdc['foo'] end def test_clear Logging.mdc['foo'] = 'bar' Logging.mdc['baz'] = 'buz' assert_equal 'bar', Logging.mdc[:foo] assert_equal 'buz', Logging.mdc[:baz] Logging.mdc.clear assert_nil Logging.mdc['foo'] assert_nil Logging.mdc['baz'] end def test_context_update Logging.mdc.update(:foo => 'bar', :baz => 'buz') assert_equal 'bar', Logging.mdc[:foo] assert_equal 'buz', Logging.mdc[:baz] Logging.mdc.update('foo' => 1, 'baz' => 2) assert_equal 1, Logging.mdc[:foo] assert_equal 2, Logging.mdc[:baz] assert_equal 1, Logging.mdc.stack.length end def test_context_pushing assert Logging.mdc.context.empty? assert_equal 1, Logging.mdc.stack.length Logging.mdc.push(:foo => 'bar', :baz => 'buz') assert_equal 'bar', Logging.mdc[:foo] assert_equal 'buz', Logging.mdc[:baz] assert_equal 2, Logging.mdc.stack.length Logging.mdc.push(:foo => 1, :baz => 2, :foobar => 3) assert_equal 1, Logging.mdc[:foo] assert_equal 2, Logging.mdc[:baz] assert_equal 3, Logging.mdc[:foobar] assert_equal 3, Logging.mdc.stack.length Logging.mdc.pop assert_equal 'bar', Logging.mdc[:foo] assert_equal 'buz', Logging.mdc[:baz] assert_nil Logging.mdc[:foobar] assert_equal 2, Logging.mdc.stack.length Logging.mdc.pop assert Logging.mdc.context.empty? assert_equal 1, Logging.mdc.stack.length Logging.mdc.pop assert Logging.mdc.context.empty? assert_equal 1, Logging.mdc.stack.length end def test_thread_uniqueness Logging.mdc['foo'] = 'bar' Logging.mdc['baz'] = 'buz' t = Thread.new { sleep Logging.mdc.clear assert_nil Logging.mdc['foo'] assert_nil Logging.mdc['baz'] Logging.mdc['foo'] = 42 assert_equal 42, Logging.mdc['foo'] } Thread.pass until t.status == 'sleep' t.run t.join assert_equal 'bar', Logging.mdc['foo'] assert_equal 'buz', Logging.mdc['baz'] end def test_thread_inheritance Logging.mdc['foo'] = 'bar' Logging.mdc['baz'] = 'buz' Logging.mdc.push(:foo => 1, 'foobar' => 'something else') t = Thread.new(Logging.mdc.context) { |context| sleep assert_not_equal context.object_id, Logging.mdc.context.object_id assert_equal 1, Logging.mdc['foo'] assert_equal 'buz', Logging.mdc['baz'] assert_equal 'something else', Logging.mdc['foobar'] assert_nil Logging.mdc['unique'] assert_equal 1, Logging.mdc.stack.length } Thread.pass until t.status == 'sleep' Logging.mdc.pop Logging.mdc['unique'] = 'value' t.run t.join end end # class TestMappedDiagnosticContext end # module TestLogging
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/bigdecimal/sample/pi.rb
<reponame>arnab0073/idea<gh_stars>10-100 #!/usr/local/bin/ruby # # pi.rb # # Calculates 3.1415.... (the number of times that a circle's diameter # will fit around the circle) using J. Machin's formula. # require "bigdecimal" require "bigdecimal/math.rb" include BigMath if ARGV.size == 1 print "PI("+ARGV[0]+"):\n" p PI(ARGV[0].to_i) else print "TRY: ruby pi.rb 1000 \n" end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi.rb
require 'net/ssh/multi/session' module Net; module SSH # Net::SSH::Multi is a library for controlling multiple Net::SSH # connections via a single interface. It exposes an API similar to that of # Net::SSH::Connection::Session and Net::SSH::Connection::Channel, making it # simpler to adapt programs designed for single connections to be used with # multiple connections. # # This library is particularly useful for automating repetitive tasks that # must be performed on multiple machines. It executes the commands in # parallel, and allows commands to be executed on subsets of servers # (defined by groups). # # require 'net/ssh/multi' # # Net::SSH::Multi.start do |session| # # access servers via a gateway # session.via 'gateway', 'gateway-user' # # # define the servers we want to use # session.use 'user1@host1' # session.use 'user2@host2' # # # define servers in groups for more granular access # session.group :app do # session.use 'user@app1' # session.use 'user@app2' # end # # # execute commands on all servers # session.exec "uptime" # # # execute commands on a subset of servers # session.with(:app).exec "hostname" # # # run the aggregated event loop # session.loop # end # # See Net::SSH::Multi::Session for more documentation. module Multi # This is a convenience method for instantiating a new # Net::SSH::Multi::Session. If a block is given, the session will be # yielded to the block automatically closed (see Net::SSH::Multi::Session#close) # when the block finishes. Otherwise, the new session will be returned. # # Net::SSH::Multi.start do |session| # # ... # end # # session = Net::SSH::Multi.start # # ... # session.close # # Any options are passed directly to Net::SSH::Multi::Session.new (q.v.). def self.start(options={}) session = Session.new(options) if block_given? begin yield session session.loop session.close end else return session end end end end; end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/rackspace.rb
# # Author:: <NAME> (<<EMAIL>>) # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. provides "rackspace" require_plugin "kernel" require_plugin "network" # Checks for matching rackspace kernel name # # === Return # true:: If kernel name matches # false:: Otherwise def has_rackspace_kernel? kernel[:release].split('-').last.eql?("rscloud") end # Checks for rackspace provider attribute # # === Return # true:: If rackspace provider attribute found # false:: Otherwise def has_rackspace_metadata? status, stdout, stderr = run_command(:no_status_check => true, :command => "xenstore-read vm-data/provider_data/provider") if status == 0 stdout.strip.downcase == 'rackspace' end rescue Ohai::Exceptions::Exec false end # Identifies the rackspace cloud # # === Return # true:: If the rackspace cloud can be identified # false:: Otherwise def looks_like_rackspace? hint?('rackspace') || has_rackspace_metadata? || has_rackspace_kernel? end # Names rackspace ip address # # === Parameters # name<Symbol>:: Use :public_ip or :private_ip # eth<Symbol>:: Interface name of public or private ip def get_ip_address(name, eth) network[:interfaces][eth][:addresses].each do |key, info| if info['family'] == 'inet' rackspace[name] = key break # break when we found an address end end end # Names rackspace ipv6 address for interface # # === Parameters # name<Symbol>:: Use :public_ip or :private_ip # eth<Symbol>:: Interface name of public or private ip def get_global_ipv6_address(name, eth) network[:interfaces][eth][:addresses].each do |key, info| # check if we got an ipv6 address and if its in global scope if info['family'] == 'inet6' && info['scope'] == 'Global' rackspace[name] = key break # break when we found an address end end end # Get the rackspace region # def get_region() status, stdout, stderr = run_command(:no_status_check => true, :command => "xenstore-ls vm-data/provider_data") if status == 0 stdout.split("\n").each do |line| rackspace[:region] = line.split[2].delete('\"') if line =~ /^region/ end end rescue Ohai::Exceptions::Exec Ohai::Log.debug("Unable to find xenstore-ls, cannot capture region information for Rackspace cloud") end # Adds rackspace Mash if looks_like_rackspace? rackspace Mash.new get_ip_address(:public_ip, :eth0) get_ip_address(:private_ip, :eth1) get_region() # public_ip + private_ip are deprecated in favor of public_ipv4 and local_ipv4 to standardize. rackspace[:public_ipv4] = rackspace[:public_ip] get_global_ipv6_address(:public_ipv6, :eth0) rackspace[:public_hostname] = "#{rackspace[:public_ip].gsub('.','-')}.static.cloud-ips.com" rackspace[:local_ipv4] = rackspace[:private_ip] get_global_ipv6_address(:local_ipv6, :eth1) rackspace[:local_hostname] = hostname end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/canvasprintdialog.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/canvasprintdialog.rb #!/usr/bin/env ruby require 'tk' require 'tkextlib/iwidgets' Tk::Iwidgets::Canvasprintdialog.new.activate Tk.mainloop
arnab0073/idea
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/benchmark/memory_usage.rb
<filename>.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/benchmark/memory_usage.rb # -*- frozen-string-literal: true -*- require 'memory_profiler' require 'did_you_mean' # public def foo; end # error = (self.fooo rescue $!) # executable = -> { error.to_s } class DidYouMean::WordCollection include DidYouMean::SpellCheckable def initialize(words) @words = words end def similar_to(input, filter = '') @corrections, @input = nil, input corrections end def candidates { @input => @words } end end if !defined?(DidYouMean::WordCollection) METHODS = ''.methods INPUT = 'start_with?' collection = DidYouMean::WordCollection.new(METHODS) executable = proc { collection.similar_to(INPUT) } GC.disable MemoryProfiler.report { 100.times(&executable) }.pretty_print
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/sigar/cpu.rb
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/sigar/cpu.rb # # Author:: <NAME> <<EMAIL>> # Copyright:: Copyright (c) 2010 VMware, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "sigar" sigar = Sigar.new provides "cpu" cpuinfo = Mash.new ix = 0 sigar.cpu_info_list.each do |info| current_cpu = ix.to_s ix += 1 cpuinfo[current_cpu] = Mash.new cpuinfo[current_cpu]["vendor_id"] = info.vendor cpuinfo[current_cpu]["model"] = info.model cpuinfo[current_cpu]["mhz"] = info.mhz.to_s cpuinfo[current_cpu]["cache_size"] = info.cache_size.to_s cpuinfo[:total] = info.total_cores cpuinfo[:real] = info.total_sockets end cpu cpuinfo
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/tk/lib/tk/after.rb
<gh_stars>0 # frozen_string_literal: false # # tk/after.rb : methods for Tcl/Tk after command # # $Id: after.rb 53143 2015-12-16 05:31:54Z naruse $ # require 'tk/timer'
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/target_info.rb
module Net module NTLM # Represents a list of AV_PAIR structures # @see https://msdn.microsoft.com/en-us/library/cc236646.aspx class TargetInfo # Allowed AvId values for an AV_PAIR MSV_AV_EOL = "\x00\x00".freeze MSV_AV_NB_COMPUTER_NAME = "\x01\x00".freeze MSV_AV_NB_DOMAIN_NAME = "\x02\x00".freeze MSV_AV_DNS_COMPUTER_NAME = "\x03\x00".freeze MSV_AV_DNS_DOMAIN_NAME = "\x04\x00".freeze MSV_AV_DNS_TREE_NAME = "\x05\x00".freeze MSV_AV_FLAGS = "\x06\x00".freeze MSV_AV_TIMESTAMP = "\x07\x00".freeze MSV_AV_SINGLE_HOST = "\x08\x00".freeze MSV_AV_TARGET_NAME = "\x09\x00".freeze MSV_AV_CHANNEL_BINDINGS = "\x0A\x00".freeze # @param av_pair_sequence [String] AV_PAIR list from challenge message def initialize(av_pair_sequence) @av_pairs = read_pairs(av_pair_sequence) end attr_reader :av_pairs def to_s result = '' av_pairs.each do |k,v| result << k result << [v.length].pack('S') result << v end result << Net::NTLM::TargetInfo::MSV_AV_EOL result << [0].pack('S') result.force_encoding(Encoding::ASCII_8BIT) end private VALID_PAIR_ID = [ MSV_AV_EOL, MSV_AV_NB_COMPUTER_NAME, MSV_AV_NB_DOMAIN_NAME, MSV_AV_DNS_COMPUTER_NAME, MSV_AV_DNS_DOMAIN_NAME, MSV_AV_DNS_TREE_NAME, MSV_AV_FLAGS, MSV_AV_TIMESTAMP, MSV_AV_SINGLE_HOST, MSV_AV_TARGET_NAME, MSV_AV_CHANNEL_BINDINGS ].freeze def read_pairs(av_pair_sequence) offset = 0 result = {} return result if av_pair_sequence.nil? until offset >= av_pair_sequence.length id = av_pair_sequence[offset..offset+1] unless VALID_PAIR_ID.include?(id) raise Net::NTLM::InvalidTargetDataError.new( "Invalid AvId #{to_hex(id)} in AV_PAIR structure", av_pair_sequence ) end length = av_pair_sequence[offset+2..offset+3].unpack('S')[0].to_i if length > 0 value = av_pair_sequence[offset+4..offset+4+length-1] result[id] = value end offset += 4 + length end result end def to_hex(str) return nil if str.nil? str.bytes.map {|b| '0x' + b.to_s(16).rjust(2,'0').upcase}.join('-') end end end end
arnab0073/idea
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/shell/utility.rb
<reponame>arnab0073/idea<gh_stars>1-10 module RVM module Shell module Utility public # Takes an array / number of arguments and converts # them to a string useable for passing into a shell call. def escape_arguments(*args) return '' if args.nil? args.flatten.map { |a| escape_argument(a.to_s) }.join(" ") end # Given a string, converts to the escaped format. This ensures # that things such as variables aren't evaluated into strings # and everything else is setup as expected. def escape_argument(s) return "''" if s.empty? s.scan(/('+|[^']+)/).map do |section| section = section.first if section[0] == ?' "\\'" * section.length else "'#{section}'" end end.join end # From a command, will build up a runnable command. If args isn't provided, # it will escape arguments. def build_cli_call(command, args = nil) "#{command} #{escape_arguments(args)}".strip end end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/panedwindow.rb
#!/usr/bin/env ruby require 'tk' require 'tkextlib/iwidgets' pw = Tk::Iwidgets::Panedwindow.new(:width=>300, :height=>300) pw.add('top') pw.add('middle', :margin=>10) pw.add('bottom', :margin=>10, :minimum=>10) pw.pack(:fill=>:both, :expand=>true) pw.child_site_list.each{|pane| TkButton.new(pane, :text=>pane.path, :relief=>:raised, :borderwidth=>2).pack(:fill=>:both, :expand=>true) } pw.fraction(50,30,20) pw.paneconfigure(0, :minimum=>20) pw.paneconfigure('bottom', :margin=>15) Tk.mainloop
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tclx/tclx.rb
<reponame>arnab0073/idea # # tclx/tclx.rb # by <NAME> (<EMAIL>) # require 'tk' # call setup script for general 'tkextlib' libraries require 'tkextlib/setup.rb' # call setup script require 'tkextlib/tclx/setup.rb' # TkPackage.require('Tclx', '8.0') TkPackage.require('Tclx') module Tk module TclX PACKAGE_NAME = 'Tclx'.freeze def self.package_name PACKAGE_NAME end def self.package_version begin TkPackage.require('Tclx') rescue '' end end def self.infox(*args) Tk.tk_call('infox', *args) end def self.signal(*args) warn("Warning: Don't recommend to use TclX's 'signal' command. Please use Ruby's 'Signal.trap' method") Tk.tk_call('signal', *args) end def self.signal_restart(*args) warn("Warning: Don't recommend to use TclX's 'signal' command. Please use Ruby's 'Signal.trap' method") Tk.tk_call('signal', '-restart', *args) end ############################## class XPG3_MsgCat class << self alias open new end def initialize(catname, fail_mode=false) if fail_mode @msgcat_id = Tk.tk_call('catopen', '-fail', catname) else @msgcat_id = Tk.tk_call('catopen', '-nofail', catname) end end def close(fail_mode=false) if fail_mode Tk.tk_call('catclose', '-fail', @msgcat_id) else Tk.tk_call('catclose', '-nofail', @msgcat_id) end self end def get(setnum, msgnum, defaultstr) Tk.tk_call('catgets', @msgcat_id, setnum, msgnum, defaultstr) end end end end