Rails how to validate subnet mask before ip range calculation - ruby-on-rails

I am using netaddr gem to validate network IP range. But I unable to find the way validated given subnet mask is valid?
def valid_ip_range(ip, gateway, subnet_mask)
ip_range = NetAddr::CIDR.create("#{gateway} #{subnet_mask}")
valid_ip_range = NetAddr.range(ip_range.first, ip_range.last)
valid_ip_range.include?(ip_ip)
end
For Valid subnet mask
ip_range = NetAddr::CIDR.create('192.168.1.1 255.255.255.0')
=> #<NetAddr::CIDRv4:0x0000000b334720 #address_len=32, #all_f=4294967295, #hostmask=255, #ip=3232235777, #netmask=4294967040, #network=3232235776, #tag={}, #version=4, #wildcard_mask=4294967040>
For Invalid subnet mask, getting following error
ip_range = NetAddr::CIDR.create('192.168.1.1 255.128.128.0')
ip_range = NetAddr::CIDR.create('192.168.1.1 1.1.1.1')
=> NetAddr::ValidationError: 1.1.1.1 contains '1' bits within the host portion of the netmask.
from /ruby-2.1.1#customerservice-mar/gems/netaddr-1.5.1/lib/validation_shortcuts.rb:182:in `block in validate_netmask_str'

ruby ipaddr
require 'ipaddr'
net1 = IPAddr.new("192.168.2.0/24")
net2 = IPAddr.new("192.168.2.100")
net3 = IPAddr.new("192.168.3.0")
p net1.include?(net2) #=> true
p net1.include?(net3) #=> false

Related

How to configure a dynamodb in rails?

In rails 5, I need to configure the dynamodb feature. I have referred some blogs and tried to implement it. First in localhost it was running without any issue, but when I move to other new system or a server then it is showing an error like,
/home/NICHEPRO/shruthir/.rvm/gems/ruby-2.4.0/gems/aws-sdk-core-2.10.19/lib/aws-sdk-core/plugins/regional_endpoint.rb:34:in `after_initialize': missing region; use :region option or export region name to ENV['AWS_REGION'] (Aws::Errors::MissingRegionError)
from /home/NICHEPRO/shruthir/.rvm/gems/ruby-2.4.0/gems/aws-sdk-core-2.10.19/lib/seahorse/client/base.rb:84:in `block in after_initialize'
AWS gem is,
aws-sdk (2.10.19)
aws-sdk-core (2.10.19)
aws-sdk-resources (2.10.19)
Referred From:
https://assist-software.net/snippets/how-save-data-amazon-dynamodb-using-ruby-on-rails
Also I have tried to fix this by referring other blogs but I will get below error too,
Failed to open TCP connection to localhost:8080 (Connection refused - connect(2) for "localhost" port 8080)
How to solve this issue?
Hope you are using Dynamoid gem. In app/config/initializer add a new config file and add below code.
Dynamoid.configure do |config|
config.adapter = 'aws_sdk_v2' # This adapter establishes a connection to the DynamoDB servers using Amazon's own AWS gem.
config.access_key = (ENV['AWS_ACCESS_KEY_ID'] || APP_CONFIG[:aws_access_key_id])
config.secret_key = (ENV['AWS_SECRET_ACCESS_KEY'] || APP_CONFIG[:aws_secret_access_key])
config.region = (ENV['AWS_REGION'] || 'us-east-1')
config.namespace = nil # To namespace tables created by Dynamoid from other tables you might have. Set to nil to avoid namespacing.
config.warn_on_scan = true # Output a warning to the logger when you perform a scan rather than a query on a table.
config.read_capacity = 100 # Read capacity for your tables
config.write_capacity = 200 # Write capacity for your tables
config.endpoint = (ENV['DYNAMO_ENDPOINT'] || APP_CONFIG[:dynamo_endpoint]) # [Optional]. If provided, it communicates with the DB listening at the endpoint. This is useful for testing with [Amazon Local DB] (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.DynamoDBLocal.html).
end
Make sure you update your ENV variables. Or if you connect directly to AWS instead of Dynamoid gem just follow...
def client
#client ||= Aws::DynamoDB::Client.new(
access_key_id: (ENV['AWS_ACCESS_KEY_ID'] || APP_CONFIG[:aws_access_key_id]),
secret_access_key: (ENV['AWS_SECRET_ACCESS_KEY'] || APP_CONFIG[:aws_secret_access_key]),
region: (ENV['AWS_REGION'] || 'us-east-1'),
endpoint: (ENV['DYNAMO_ENDPOINT'] || APP_CONFIG[:dynamo_endpoint])
)
end
and do a query like this
client.query(
table_name: table_name,
select: 'COUNT',
expression_attribute_values: {
':v1' => index
},
key_condition_expression: 'user_id = :v1'
).count
For more info http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/DynamoDB.html

RSpec be_equal not working

I am writing some rspec examples for a plain old ruby class in my rails project and I am facing the following problem.
I have this constructor:
class Server
def initialize(host='localhost',options={:port => 443, :password => '', :vpncmd_bin_path => '/usr/local/bin/vpncmd', :timeout => 5})
#host = host
#port = options[:port].present? ? options[:port] : 443
#password = options[:password].present? ? options[:password] : ''
#vpncmd_bin_path = options[:vpncmd_bin_path].present? ? options[:vpncmd_bin_path] : '/usr/local/bin/vpncmd'
#timeout = options[:timeout].present? ? options[:timeout] : 5
#hubs = {}
#hub_cache_dirty = true
#hub_password_cache = {}
end
...
end
This test example:
it "should have a default constructor that takes no argument" do
s = SoftEther::Server.new()
expect(s.host).to be_equal('localhost')
expect(s.port).to be_equal('443')
expect(s.timeout).to be_equal(5)
expect(s.vpncmd_bin_path).to be_equal('/usr/local/bin/vpncmd')
expect(s.password).to be_equal('')
end
And rspec gives me the following result with Rails 4.2.6, jruby-9.0.5.0 and 3.4.4:
1) SoftEtherSever should have a default constructor that takes no argument
Failure/Error: expect(s.host).to be_equal('localhost')
expected `"localhost".equal?("localhost")` to return true, got false
# ./spec/poro/softether_spec.rb:19:in `block in (root)'
What did I do wrong?
equal? checks whether two instances are the same. But it returns false when two strings contains the same value but refers to different objects:
"foo".equals?("foo")
# => false
What you should really use is eq()
expect(s.host).to eq('localhost')
Just to add an edge case to Simone's answer:
If you were to freeze the strings in question, you would get the result you expected:
irb(main):001:0> 'test'.equal? 'test'
=> false
irb(main):002:0> 'test'.freeze.equal? 'test'.freeze
=> true
In Ruby 2.3, this can be done by adding
# frozen_string_literal: true
to the top of the Ruby file.
With that said, Simone is right. You should use the eq matcher unless you truly want to test that you are using the same exact object instance. Then using equal is in order.

undefined method: connect_timeout

Browser error:
NoMethodError
undefined method `connect_timeout=' for #<Mysql2::Client:0x47f7570>
On my browser, an error comes up that connect_timeout is undefined. I'm pretty sure it has something to do with the client.rb file. I'll show you the file. I had to edit some of it to actually get Webrick up and running. When I started the server, an error always appeared on my command line unless I made the changes. I've commented on what I have edited. Sometimes edited random things and some of them worked but they produced different errors on my browser. I am using a windows 8 machine. Thank you for helping.
module Mysql2
class Client
attr_reader :query_options, :read_timeout
##default_query_options = {
:as => :hash, # the type of object you want each row back as; also supports :array (an array of values)
:async => false, # don't wait for a result after sending the query, you'll have to monitor the socket yourself then eventually call Mysql2::Client#async_result
:cast_booleans => false, # cast tinyint(1) fields as true/false in ruby
:symbolize_keys => false, # return field names as symbols instead of strings
:database_timezone => :local, # timezone Mysql2 will assume datetime objects are stored in
:application_timezone => nil, # timezone Mysql2 will convert to before handing the object back to the caller
:cache_rows => true, # tells Mysql2 to use it's internal row cache for results
#:connect_flags => REMEMBER_OPTIONS | LONG_PASSWORD | LONG_FLAG | TRANSACTIONS | PROTOCOL_41 | SECURE_CONNECTION,
#I had to delete the line above because for some reason the command prompt said that each of the constants were undefined were not used in the right place or something
:cast => true,
:default_file => nil,
:default_group => nil
}
def initialize (opts = {})
opts = Mysql2::Util.key_hash_as_symbols( opts )
#read_timeout = nil
#query_options = ##default_query_options.dup
#query_options.merge! opts
#initialize_ext
# the chrome page said that the above variable is undefined :P
# Set default connect_timeout to avoid unlimited retries from signal interruption
opts[:connect_timeout] = 120 unless opts.key?(:connect_timeout)
[:reconnect, :connect_timeout, :local_infile, :read_timeout, :write_timeout, :default_file, :default_group, :secure_auth, :init_command].each do |key|
next unless opts.key?(key)
case key
when :reconnect, :local_infile, :secure_auth
send(:"#{key}=", !!opts[key])
when :connect_timeout, :read_timeout, :write_timeout
send(:"#{key}=", opts[key].to_i)
else
send(:"#{key}=", opts[key])
end
end
# force the encoding to utf8
self.charset_name = opts[:encoding] || 'utf8'
ssl_options = opts.values_at(:sslkey, :sslcert, :sslca, :sslcapath, :sslcipher)
ssl_set(*ssl_options) if ssl_options.any?
if [:user,:pass,:hostname,:dbname,:db,:sock].any?{|k| #query_options.has_key?(k) }
warn "============= WARNING FROM mysql2 ============="
warn "The options :user, :pass, :hostname, :dbname, :db, and :sock will be deprecated at some point in the future."
warn "Instead, please use :username, :password, :host, :port, :database, :socket, :flags for the options."
warn "============= END WARNING FROM mysql2 ========="
end
user = opts[:username] || opts[:user]
pass = opts[:password] || opts[:pass]
host = opts[:host] || opts[:hostname]
port = opts[:port]
database = opts[:database] || opts[:dbname] || opts[:db]
socket = opts[:socket] || opts[:sock]
flags = opts[:flags] ? opts[:flags] | #query_options[:connect_flags] : #query_options[:connect_flags]
# Correct the data types before passing these values down to the C level
user = user.to_s unless user.nil?
pass = pass.to_s unless pass.nil?
host = host.to_s unless host.nil?
port = port.to_i unless port.nil?
database = database.to_s unless database.nil?
socket = socket.to_s unless socket.nil?
connect user, pass, host, port, database, socket, flags
end
def self.default_query_options
##default_query_options
end
def query_info
info = query_info_string
return {} unless info
info_hash = {}
info.split.each_slice(2) { |s| info_hash[s[0].downcase.delete(':').to_sym] = s[1].to_i }
info_hash
end
private
def self.local_offset
::Time.local(2010).utc_offset.to_r / 86400
end
end
end
Mysql2::Client#initialize called connect_timeout= but there isn't such attr_writer in the client.
when :connect_timeout, :read_timeout, :write_timeout
send(:"#{key}=", opts[key].to_i)
else
If this client is written by yourself, add attr_accessor :connect_timeout in Mysql2::Client's definition and make proper use of the attribute. If it is from other library, check your load path. You may have missed some files that opened Mysql2::Client and monkey patched it.

How to get the IP Address in Vagrant?

I'm trying to configure a Hadoop cluster, but to do so I needed the ip address of the namenode.
The cluster itself is being created by Vagrant, but I don't have the ip address until vagrant creates the instance in AWS.
So, I have the following Vagrantfile:
current_dir = File.dirname(__FILE__)
$master_script = <<SCRIPT
// will write a script to configure
SCRIPT
Vagrant.configure("2") do |config|
config.omnibus.chef_version = :latest
config.vm.provider :aws do |aws, override|
config.vm.box = "dummy"
aws.access_key_id = "MY_KEY"
aws.secret_access_key = "SECRET_KEY"
aws.keypair_name = "my_key"
aws.ami = "ami-7747d01e"
override.ssh.username = "ubuntu"
override.ssh.private_key_path = "#{current_dir}/my_key.pem"
end
config.vm.provider :virtualbox do |v|
config.vm.box = "precise64"
config.vm.box_url = "https://vagrantcloud.com/chef/ubuntu-13.04/version/1/provider/virtualbox.box"
v.customize ["modifyvm", :id, "--memory", "1024"]
end
config.vm.define :namenode do |namenode|
namenode.vm.box = "dummy"
namenode.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "cookbooks"
chef.roles_path = "roles"
chef.add_role "cluster"
end
namenode.vm.provision :hostmanager
namenode.vm.provision "shell", :inline => $master_script
end
config.vm.define :slave do |slave|
slave.vm.box = "dummy"
slave.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "cookbooks"
chef.roles_path = "roles"
chef.add_role "cluster"
end
slave.vm.provision :hostmanager
slave.vm.provision "shell", :inline => $master_script
end
end
I need to update the mapred-site.xml and core-site.xml files with the ip address of the namenode. How could I get the ip address of the namenode box so I can update the hadoop config files? Is there a better option in the cookbook that I can use to accomplish it?
Suppose I have 1 namenode and 5 slaves, the mapred-site.xml.erb template will look like:
<configuration>
<property>
<name>mapred.job.tracker</name>
<value>hdfs://<%= node[:ipaddress] %>:8021</value>
</property>
</configuration>
However, I needed that all the namenode and the slaves to have the ip address only of the namenode. How can I accomplish that in chef?
Either way will work for me, even though I prefer the chef solution.
You could:
1- Use the instance metadata service on the namenode instance to find out its own ip:
curl http://169.254.169.254/latest/meta-data/local-ipv4
see: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
2- Tag the namenode (ex: HADOOP_ROLE=NAMENODE) and use AWS CLI on any instance to find the local ip of the namenode:
aws ec2 describe-instances \
--region=us-east-1 \
--filter "Name=tag:HADOOP_ROLE,Values=NAMENODE" \
--query='Reservations[*].Instances[*].PrivateIpAddress' \
--output=text
see: http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html

Differentiate between ip adress and DNS address in ruby

How will i know a url adress is IP address or DNS address in ruby.
Example to clarify question:
IP Address: http://74.125.236.72/
DNS Address: http://google.co.in
Just check it manually?
string =~ /\/\/[0-9.]+\/?$/
Something like below, I am thinking to solve this problem using IPAddr:-
def dns_or_ip_addrs_check(address)
addr = address[/http(?:s)?:\/\/([a-z0-9.]+)\/?/i,1]
begin
require 'ipaddr'
IPAddr.new addr
'ip address'
rescue IPAddr::InvalidAddressError
'dns address'
end
end
dns_or_ip_addrs_check('http://74.125.236.72/') # => "ip address"
dns_or_ip_addrs_check('http://google.co.in') # => "dns address"

Resources