repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
Yaroslav-F/nexmo-ruby
|
test/nexmo/client_test.rb
|
require_relative './test'
class NexmoClientTest < Nexmo::Test
def test_api_key_method
assert_equal client.api_key, api_key
end
def test_api_key_method_raises_authentication_error
client = Nexmo::Client.new
exception = assert_raises(Nexmo::AuthenticationError) { client.api_key }
assert_includes exception.message, 'No API key provided.'
end
def test_api_secret_method
assert_equal client.api_secret, api_secret
end
def test_api_secret_method_raises_authentication_error
client = Nexmo::Client.new
exception = assert_raises(Nexmo::AuthenticationError) { client.api_secret }
assert_includes exception.message, 'No API secret provided.'
end
def test_signature_secret_method
assert_equal client.signature_secret, signature_secret
end
def test_signature_secret_method_raises_authentication_error
client = Nexmo::Client.new
exception = assert_raises(Nexmo::AuthenticationError) { client.signature_secret }
assert_includes exception.message, 'No signature_secret provided.'
end
def test_application_id_method
assert_equal client.application_id, application_id
end
def test_application_id_method_raises_authentication_error
client = Nexmo::Client.new
exception = assert_raises(Nexmo::AuthenticationError) { client.application_id }
assert_includes exception.message, 'No application_id provided.'
end
def test_private_key_method
assert_equal client.private_key, private_key
end
def test_private_key_method_raises_authentication_error
client = Nexmo::Client.new
exception = assert_raises(Nexmo::AuthenticationError) { client.private_key }
assert_includes exception.message, 'No private_key provided.'
end
def test_signature_method
assert_kind_of Nexmo::Signature, client.signature
end
def test_account_method
assert_kind_of Nexmo::Account, client.account
end
def test_alerts_method
assert_kind_of Nexmo::Alerts, client.alerts
end
def test_applications_method
assert_kind_of Nexmo::Applications, client.applications
end
def test_calls_method
assert_kind_of Nexmo::Calls, client.calls
end
def test_conversions_method
assert_kind_of Nexmo::Conversions, client.conversions
end
def test_files_method
assert_kind_of Nexmo::Files, client.files
end
def test_messages_method
assert_kind_of Nexmo::Messages, client.messages
end
def test_number_insight_method
assert_kind_of Nexmo::NumberInsight, client.number_insight
end
def test_numbers_method
assert_kind_of Nexmo::Numbers, client.numbers
end
def test_pricing_method
assert_kind_of Nexmo::PricingTypes, client.pricing
end
def test_sms_method
assert_kind_of Nexmo::SMS, client.sms
end
def test_verify_method
assert_kind_of Nexmo::Verify, client.verify
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/signature.rb
|
require 'digest/md5'
require 'jwt'
module Nexmo
class Signature
def self.check(params, secret)
params = params.dup
signature = params.delete('sig')
secure_compare(signature, digest(params, secret))
end
def initialize(client)
@client = client
end
def check(params)
self.class.check(params, @client.signature_secret)
end
private
if defined?(::JWT::SecurityUtils) # ruby-jwt v2
def self.secure_compare(left, right)
::JWT::SecurityUtils.secure_compare(left, right)
end
else
def self.secure_compare(left, right)
::JWT.secure_compare(left, right)
end
end
def self.digest(params, secret)
md5 = Digest::MD5.new
params.sort.each do |k, v|
md5.update("&#{k}=#{v}")
end
md5.update(secret)
md5.hexdigest
end
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/calls.rb
|
# frozen_string_literal: true
module Nexmo
class Calls < Namespace
def create(params)
request('/v1/calls', params: params, type: Post)
end
def list(params = nil)
request('/v1/calls', params: params)
end
def get(id)
request('/v1/calls/' + id)
end
def update(id, params)
request('/v1/calls/' + id, params: params, type: Put)
end
def hangup(id)
update(id, action: 'hangup')
end
def mute(id)
update(id, action: 'mute')
end
def unmute(id)
update(id, action: 'unmute')
end
def earmuff(id)
update(id, action: 'earmuff')
end
def unearmuff(id)
update(id, action: 'unearmuff')
end
def transfer(id, destination: nil)
# Ruby 2.0.0 does not support the syntax for required keyword arguments
# that was introduced in Ruby 2.1. The following line and the nil default
# can be removed when dropping support for Ruby 2.0.0.
raise ArgumentError, 'missing keyword: destination' if destination.nil?
update(id, action: 'transfer', destination: destination)
end
def stream
@stream ||= CallStream.new(@client)
end
def talk
@talk ||= CallTalk.new(@client)
end
def dtmf
@dtmf ||= CallDTMF.new(@client)
end
private
def authorization_header?
true
end
def json_body?
true
end
end
end
|
Yaroslav-F/nexmo-ruby
|
test/nexmo/key_value_logger_test.rb
|
require_relative './test'
require 'logger'
class NexmoKeyValueLoggerTest < Nexmo::Test
attr_accessor :io
def setup
self.io = StringIO.new
end
def test_null_logging
logger = Nexmo::KeyValueLogger.new(nil)
logger.info('Nexmo API response')
assert_empty io.string
end
def test_includes_key_value_data
logger = Nexmo::KeyValueLogger.new(Logger.new(io))
logger.info('Nexmo API response', status: 200, host: 'api.nexmo.com')
assert_includes io.string, 'status=200'
assert_includes io.string, 'host=api.nexmo.com'
end
def test_ignores_nil_values
logger = Nexmo::KeyValueLogger.new(Logger.new(io))
logger.info('Nexmo API response', length: nil, trace_id: nil)
refute_includes io.string, 'length='
refute_includes io.string, 'trace_id='
end
end
|
Yaroslav-F/nexmo-ruby
|
test/nexmo/test.rb
|
<gh_stars>0
require 'minitest/autorun'
require 'webmock/minitest'
require 'nexmo'
module Nexmo
class Test < Minitest::Test
def api_key
'nexmo-api-key'
end
def api_secret
'nexmo-api-secret'
end
def api_key_and_secret
{api_key: api_key, api_secret: api_secret}
end
def signature_secret
'nexmo-signature-secret'
end
def application_id
'nexmo-application-id'
end
def private_key
File.read(File.expand_path(File.join(File.dirname(__FILE__), '..', 'private_key.txt')))
end
def client
@client ||= Nexmo::Client.new({
api_key: api_key,
api_secret: api_secret,
signature_secret: signature_secret,
application_id: application_id,
private_key: private_key
})
end
def headers
{'Content-Type' => 'application/x-www-form-urlencoded'}
end
def bearer_token
/\ABearer (.+)\.(.+)\.(.+)\z/
end
def response
{body: '{"key":"value"}', headers: response_headers}
end
def response_headers
{'Content-Type' => 'application/json;charset=utf-8'}
end
def response_object
Nexmo::Entity.new(key: 'value')
end
def msisdn
'447700900000'
end
def stub_sms_request(recipient: '447700900000', status: '0', uri: 'https://rest.nexmo.com/sms/json')
params = { from: 'Ruby', text: 'Hello from Ruby!', to: recipient }
stub_request(:post, uri)
.with(headers: headers, body: params.merge(api_key_and_secret))
.to_return({ body: { messages: [{ status: status }] }.to_json, headers: response_headers})
end
end
end
|
Yaroslav-F/nexmo-ruby
|
test/nexmo/sms_test.rb
|
require_relative './test'
class NexmoSMSTest < Nexmo::Test
def sms
Nexmo::SMS.new(client)
end
def uri
'https://rest.nexmo.com/sms/json'
end
def test_send_method
params = {from: 'Ruby', to: msisdn, text: 'Hello from Ruby!'}
request = stub_request(:post, uri).with(headers: headers, body: params.merge(api_key_and_secret)).to_return(response)
assert_equal response_object, sms.send(params)
assert_requested request
end
def test_bulk_send_method_success
recipients = ['1234567', '7891012']
recipients.each{ |recipient| stub_sms_request(recipient: recipient) }
params = { from: 'Ruby', text: 'Hello from Ruby!' }
assert_equal [], sms.bulk_send(recipients, params) # No failed Deliveries
end
# Slow (12 sec) Test! Run at your own risk
# [12.06.2018] - passes
# def test_bulk_send_method_throttled
# recipients = ['1234567', '7891012']
# recipients.each{ |recipient| stub_sms_request(recipient: recipient, status: '1') }
# params = { from: 'Ruby', text: 'Hello from Ruby!' }
# assert_equal [[Nexmo::Entity.new(status: '1')]] * 2, sms.bulk_send(recipients, params)
# end
def test_bulk_send_method_fail
recipients = ['1234567', '7891012']
recipients.each{ |recipient| stub_sms_request(recipient: recipient, status: '2') }
params = { from: 'Ruby', text: 'Hello from Ruby!' }
assert_equal [[Nexmo::Entity.new(status: '2')]] * 2, sms.bulk_send(recipients, params)
end
def test_mapping_underscored_keys_to_hyphenated_string_keys
params = {'status-report-req' => '1'}
request = stub_request(:post, uri).with(headers: headers, body: params.merge(api_key_and_secret)).to_return(response)
assert_equal response_object, sms.send(status_report_req: 1)
assert_requested request
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/account.rb
|
<filename>lib/nexmo/account.rb<gh_stars>0
# frozen_string_literal: true
module Nexmo
class Account < Namespace
def balance
request('/account/get-balance')
end
def update(params)
request('/account/settings', params: params, type: Post)
end
def topup(params)
request('/account/top-up', params: params, type: Post)
end
private
def host
'rest.nexmo.com'
end
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/call_talk.rb
|
<reponame>Yaroslav-F/nexmo-ruby<filename>lib/nexmo/call_talk.rb
# frozen_string_literal: true
module Nexmo
class CallTalk < Namespace
def start(id, params)
request('/v1/calls/' + id + '/talk', params: params, type: Put)
end
def stop(id)
request('/v1/calls/' + id + '/talk', type: Delete)
end
private
def authorization_header?
true
end
def json_body?
true
end
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo.rb
|
<reponame>Yaroslav-F/nexmo-ruby<gh_stars>0
require 'nexmo/version'
require 'nexmo/params'
require 'nexmo/jwt'
require 'nexmo/signature'
require 'nexmo/user_agent'
require 'nexmo/entity'
require 'nexmo/keys'
require 'nexmo/errors/error'
require 'nexmo/errors/client_error'
require 'nexmo/errors/server_error'
require 'nexmo/errors/authentication_error'
require 'nexmo/key_value_logger'
require 'nexmo/namespace'
require 'nexmo/client'
require 'nexmo/account'
require 'nexmo/alerts'
require 'nexmo/applications'
require 'nexmo/call_dtmf'
require 'nexmo/call_stream'
require 'nexmo/call_talk'
require 'nexmo/calls'
require 'nexmo/conversions'
require 'nexmo/files'
require 'nexmo/messages'
require 'nexmo/number_insight'
require 'nexmo/numbers'
require 'nexmo/pricing_types'
require 'nexmo/pricing'
require 'nexmo/sms'
require 'nexmo/verify'
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/alerts.rb
|
<filename>lib/nexmo/alerts.rb
# frozen_string_literal: true
module Nexmo
class Alerts < Namespace
def list
request('/sc/us/alert/opt-in/query/json')
end
def remove(params)
request('/sc/us/alert/opt-in/manage/json', params: params, type: Post)
end
alias_method :resubscribe, :remove
def send(params)
request('/sc/us/alert/json', params: params, type: Post)
end
private
def host
'rest.nexmo.com'
end
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/params.rb
|
<filename>lib/nexmo/params.rb
require 'cgi'
module Nexmo
module Params
def self.encode(params)
params.flat_map { |k, vs| Array(vs).map { |v| "#{escape(k)}=#{escape(v)}" } }.join('&')
end
private
def self.escape(component)
CGI.escape(component.to_s)
end
end
end
|
Yaroslav-F/nexmo-ruby
|
lib/nexmo/key_value_logger.rb
|
# frozen_string_literal: true
module Nexmo
class KeyValueLogger
def initialize(logger)
@logger = logger
end
def debug(message, data = nil)
@logger.debug(format(message, data)) if @logger
end
def info(message, data = nil)
@logger.info(format(message, data)) if @logger
end
def warning(message, data = nil)
@logger.warning(format(message, data)) if @logger
end
def error(message, data = nil)
@logger.error(format(message, data)) if @logger
end
private
def format(message, hash)
return message if hash.nil?
fields = hash.map { |key, value| "#{key}=#{value}" if value }.compact
fields.unshift(message)
fields.join(' ')
end
end
end
|
bendyworks/payment.bendyworks.com
|
app/controllers/charges_controller.rb
|
<reponame>bendyworks/payment.bendyworks.com<filename>app/controllers/charges_controller.rb
class ChargesController < ApplicationController
def new
end
def error
end
def create
charge = Stripe::Charge.create(
:amount => (params[:amount].to_f * 100).abs.to_i,
:currency => "usd",
:card => params[:stripeToken],
:description => params[:email]
)
@amount = params[:amount]
@payment_id = charge.id
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to error_path
end
end
|
bendyworks/payment.bendyworks.com
|
config/routes.rb
|
<gh_stars>10-100
Lucre::Application.routes.draw do
match '/' => 'charges#new', via: :get
match '/thanks' => 'charges#create', via: :post
match '/error' => 'charges#error', via: :get
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister/vpc/network_manager.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::Inventory::Persister::VPC::NetworkManager < ManageIQ::Providers::IbmCloud::Inventory::Persister::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/cloud_manager/auth_key_pair.rb
|
class ManageIQ::Providers::IbmCloud::VPC::CloudManager::AuthKeyPair < ManageIQ::Providers::CloudManager::AuthKeyPair
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/vpc/cloud_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC::CloudManager < ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/storage_manager/cloud_volume_type.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::StorageManager::CloudVolumeType < ::CloudVolumeType
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/vpc.rb
|
<gh_stars>0
class ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC < ManageIQ::Providers::IbmCloud::Inventory::Collector
require_nested :CloudManager
require_nested :NetworkManager
require_nested :StorageManager
def connection
@connection ||= manager.connect
end
def vms
connection.instances.all
end
def vm_key_pairs(vm_id)
connection.instances.instance(vm_id)&.initialization || {}
end
def flavors
connection.instance_profiles.all
end
def images
connection.images.all
end
def image(image_id)
connection.images.instance(image_id)&.details
end
def keys
connection.keys.all
end
def availability_zones
connection.regions.instance(manager.provider_region).zones.all
end
def security_groups
connection.security_groups.all
end
def cloud_networks
connection.vpcs.all
end
def cloud_subnets
connection.subnets.all
end
def floating_ips
connection.floating_ips.all
end
def volumes
connection.volumes.all
end
def volume(volume_id)
connection.volumes.instance(volume_id)&.details
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister/power_virtual_servers/cloud_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Persister::PowerVirtualServers::CloudManager < ManageIQ::Providers::IbmCloud::Inventory::Persister::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/network_manager/network_port.rb
|
<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::NetworkManager::NetworkPort < ::NetworkPort
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/power_virtual_servers/network_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers::NetworkManager < ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/provision.rb
|
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::Provision < ::MiqProvisionCloud
include_concern 'Cloning'
include_concern 'StateMachine'
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/power_virtual_servers/cloud_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers::CloudManager < ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
spec/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/vm_spec.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud
describe ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::Vm do
let(:ems) do
FactoryBot.create(:ems_ibm_cloud_power_virtual_servers_cloud, :provider_region => "us-south")
end
let(:vm) { FactoryBot.create(:vm_ibm_cloud_power_virtual_servers, :ext_management_system => ems) }
context "is_available?" do
let(:power_state_on) { "ACTIVE" }
let(:power_state_suspended) { "SHUTOFF" }
context "with :start" do
let(:state) { :start }
include_examples "Vm operation is available when not powered on"
end
context "with :stop" do
let(:state) { :stop }
include_examples "Vm operation is available when powered on"
end
context "with :shutdown_guest" do
let(:state) { :shutdown_guest }
include_examples "Vm operation is not available"
end
context "with :standby_guest" do
let(:state) { :standby_guest }
include_examples "Vm operation is not available"
end
context "with :reboot" do
let(:state) { :reboot }
include_examples "Vm operation is available when powered on"
end
context "with :reset" do
let(:state) { :reset }
include_examples "Vm operation is available when powered on"
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister/power_virtual_servers/network_manager.rb
|
<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::Inventory::Persister::PowerVirtualServers::NetworkManager < ManageIQ::Providers::IbmCloud::Inventory::Persister::PowerVirtualServers
def storage_manager
manager.parent_manager.storage_manager
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/parser/power_virtual_servers/network_manager.rb
|
<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::Inventory::Parser::PowerVirtualServers::NetworkManager < ManageIQ::Providers::IbmCloud::Inventory::Parser::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister/power_virtual_servers/storage_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Persister::PowerVirtualServers::StorageManager < ManageIQ::Providers::IbmCloud::Inventory::Persister::PowerVirtualServers
def network_manager
manager.parent_manager.network_manager
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/storage_manager/cloud_volume.rb
|
class ManageIQ::Providers::IbmCloud::VPC::StorageManager::CloudVolume < ::CloudVolume
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/network_manager/security_group.rb
|
class ManageIQ::Providers::IbmCloud::VPC::NetworkManager::SecurityGroup < ::SecurityGroup
def self.display_name(number = 1)
n_('Security Group (IBM)', 'Security Groups (IBM)', number)
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/network_manager/cloud_network.rb
|
class ManageIQ::Providers::IbmCloud::VPC::NetworkManager::CloudNetwork < ::CloudNetwork
end
|
jrafanie/manageiq-providers-ibm_cloud
|
lib/tasks_private/spec.rake
|
namespace :spec do
desc "Setup environment specs"
task :setup => ["app:test:vmdb:setup"]
end
desc "Run all specs"
RSpec::Core::RakeTask.new(:spec => ['app:test:spec_deps', 'app:test:providers_common']) do |t|
EvmTestHelper.init_rspec_task(t)
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister.rb
|
<filename>app/models/manageiq/providers/ibm_cloud/inventory/persister.rb
class ManageIQ::Providers::IbmCloud::Inventory::Persister < ManageIQ::Providers::Inventory::Persister
require_nested :PowerVirtualServers
require_nested :VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/parser/vpc/network_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Parser::VPC::NetworkManager < ManageIQ::Providers::IbmCloud::Inventory::Parser::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/power_virtual_servers/storage_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers::StorageManager < ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/event_catcher.rb
|
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::EventCatcher < ManageIQ::Providers::BaseManager::EventCatcher
require_nested :Runner
def self.settings_name
:event_catcher_ibm_cloud_power_virtual_servers
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
config/initializers/gettext.rb
|
Vmdb::Gettext::Domains.add_domain(
'ManageIQ::Providers::IbmCloud',
ManageIQ::Providers::IbmCloud::Engine.root.join('locale').to_s,
:po
)
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister/vpc/cloud_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Persister::VPC::CloudManager < ManageIQ::Providers::IbmCloud::Inventory::Persister::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/storage_manager/cloud_volume.rb
|
<filename>app/models/manageiq/providers/ibm_cloud/power_virtual_servers/storage_manager/cloud_volume.rb
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::StorageManager::CloudVolume < ::CloudVolume
supports :create
supports_not :snapshot_create
supports_not :update
def available_vms
availability_zone.vms.select { |vm| vm.format == volume_type }
end
def self.validate_create_volume(ext_management_system)
validate_volume(ext_management_system)
end
def self.raw_create_volume(ext_management_system, options)
volume_params = {
'name' => options[:name],
'size' => options[:size],
'diskType' => options[:volume_type]
}
volume = nil
ext_management_system.with_provider_connection(:service => 'PowerIaas') do |power_iaas|
volume = power_iaas.create_volume(volume_params)
end
{:ems_ref => volume['volumeID'], :status => volume['state'], :name => volume['name']}
rescue => e
_log.error("volume=[#{volume_params}], error: #{e}")
raise MiqException::MiqVolumeCreateError, e.to_s, e.backtrace
end
def validate_delete_volume
msg = validate_volume
return {:available => msg[:available], :message => msg[:message]} unless msg[:available]
if status == "in-use"
return validation_failed("Delete Volume", "Can't delete volume that is in use.")
end
{:available => true, :message => nil}
end
def raw_delete_volume
ext_management_system.with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.delete_volume(ems_ref)
end
rescue => e
_log.error("volume=[#{name}], error: #{e}")
end
def validate_attach_volume
msg = validate_volume_available
return {:available => msg[:available], :message => msg[:message]} unless msg[:available]
if status == "in-use" && !multi_attachment
return validation_failed("Attach Volume", "Can't attach non-shareable volume that is in use.")
end
{:available => true, :message => nil}
end
def raw_attach_volume(vm_ems_ref, _device = nil)
ext_management_system.with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.attach_volume(vm_ems_ref, ems_ref)
end
rescue => e
_log.error("volume=[#{name}], error: #{e}")
raise MiqException::MiqVolumeAttachError, "Unable to attach volume: #{e.message}"
end
def validate_detach_volume
validate_volume_in_use
end
def raw_detach_volume(vm_ems_ref)
ext_management_system.with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.detach_volume(vm_ems_ref, ems_ref)
end
rescue => e
_log.error("volume=[#{name}], error: #{e}")
raise MiqException::MiqVolumeDetachError, "Unable to attach volume: #{e.message}"
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/storage_manager/refresher.rb
|
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::StorageManager::Refresher < ManageIQ::Providers::BaseManager::Refresher
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/vpc/network_manager.rb
|
<filename>app/models/manageiq/providers/ibm_cloud/inventory/collector/vpc/network_manager.rb
class ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC::NetworkManager < ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/parser/power_virtual_servers/cloud_manager.rb
|
<filename>app/models/manageiq/providers/ibm_cloud/inventory/parser/power_virtual_servers/cloud_manager.rb
class ManageIQ::Providers::IbmCloud::Inventory::Parser::PowerVirtualServers::CloudManager < ManageIQ::Providers::IbmCloud::Inventory::Parser::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/manager_mixin.rb
|
module ManageIQ::Providers::IbmCloud::VPC::ManagerMixin
extend ActiveSupport::Concern
def required_credential_fields(_type)
[:auth_key]
end
def supported_auth_attributes
%w[auth_key]
end
def connect(options = {})
key = authentication_key(options[:auth_type])
region = options[:provider_region] || provider_region
sdk = self.class.raw_connect(key)
sdk.vpc(region)
end
def verify_credentials(_auth_type = nil, options = {})
!!connect(options)&.token&.authorization_header
end
module ClassMethods
def params_for_create
@params_for_create ||= {
:fields => [
{
:component => "select",
:id => "provider_region",
:name => "provider_region",
:label => _("Region"),
:isRequired => true,
:validate => [{:type => "required"}],
:options => provider_region_options
},
{
:component => 'sub-form',
:name => 'endpoints-subform',
:title => _("Endpoint"),
:fields => [
{
:component => 'validate-provider-credentials',
:name => 'authentications.default.valid',
:skipSubmit => true,
:isRequired => true,
:validationDependencies => %w[type zone_id provider_region],
:fields => [
{
:component => "password-field",
:name => "authentications.default.auth_key",
:label => _("IBM Cloud API Key"),
:type => "password",
:isRequired => true,
:validate => [{:type => "required"}]
},
],
},
],
},
],
}.freeze
end
# Verify Credentials
# args:
# {
# "uid_ems" => "",
# "authentications" => {
# "default" => {
# "auth_key" => "",
# }
# }
# }
def verify_credentials(args)
auth_key = args.dig('authentications', 'default', 'auth_key')
auth_key = ManageIQ::Password.try_decrypt(auth_key)
auth_key ||= find(args['id']).authentication_token('default')
!!raw_connect(auth_key)&.token&.authorization_header
end
def raw_connect(api_key)
if api_key.blank?
raise MiqException::MiqInvalidCredentialsError, _('Missing credentials')
end
require 'ibm-cloud-sdk'
IBM::CloudSDK.new(api_key)
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/refresher.rb
|
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::Refresher < ManageIQ::Providers::BaseManager::Refresher
def post_process_refresh_classes
[]
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/persister/vpc/storage_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Persister::VPC::StorageManager < ManageIQ::Providers::IbmCloud::Inventory::Persister::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/network_manager/cloud_subnet.rb
|
class ManageIQ::Providers::IbmCloud::VPC::NetworkManager::CloudSubnet < ::CloudSubnet
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/refresh_worker.rb
|
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::RefreshWorker < MiqEmsRefreshWorker
require_nested :Runner
def self.settings_name
:ems_refresh_worker_ibm_cloud_power_virtual_servers
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/provision/cloning.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud
module ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::Provision::Cloning
def log_clone_options(clone_options)
_log.info('IBM SERVER PROVISIONING OPTIONS: ' + clone_options.to_s)
end
def prepare_for_clone_task
specs = {
'serverName' => get_option(:vm_target_name),
'imageID' => get_option_last(:src_vm_id),
'processors' => get_option_last(:entitled_processors).to_f,
'procType' => get_option_last(:instance_type),
'memory' => get_option_last(:vm_memory).to_i,
'sysType' => get_option_last(:sys_type),
'pinPolicy' => get_option_last(:pin_policy),
'migratable' => get_option_last(:migratable) == 1,
'networks' => [{"networkID" => get_option(:vlan)}], # TODO: support multiple values
'replicants' => 1, # TODO: we have to use this field instead of what 'MIQ' does
'storageType' => get_option_last(:storage_type)
}
# TODO: support multiple values
ip_addr = get_option_last(:ip_addr)
specs['networks'][0]['ipAddress'] = ip_addr unless !ip_addr || ip_addr.strip.blank?
chosen_key_pair = get_option_last(:guest_access_key_pair)
specs['keyPairName'] = chosen_key_pair unless chosen_key_pair == 'None'
user_script_text = options[:user_script_text]
user_script_text64 = Base64.encode64(user_script_text) unless user_script_text.nil?
specs['userData'] = user_script_text64 unless user_script_text64.nil?
attached_volumes = options[:cloud_volumes] || []
attached_volumes.concat(phase_context[:new_volumes]).compact!
specs['volumeIDs'] = attached_volumes unless attached_volumes.empty?
specs
end
def start_clone(clone_options)
begin
source.with_provider_object(:service => "PowerIaas") do |power_iaas|
power_iaas.create_pvm_instance(clone_options)[0]['pvmInstanceID']
end
rescue RestClient::ExceptionWithResponse => e
raise MiqException::MiqProvisionError, e.response.to_s
end
rescue RestClient::ExceptionWithResponse => e
raise MiqException::MiqProvisionError, e.response.to_s
end
def do_clone_task_check(clone_task_ref)
source.with_provider_object(:service => "PowerIaas") do |power_iaas|
instance = power_iaas.get_pvm_instance(clone_task_ref)
instance_state = instance['status']
stop = false
case instance_state
when 'BUILD'
status = 'The server is being provisioned.'
when 'ACTIVE'
stop = (instance['processors'].to_f > 0) && (instance['memory'].to_f > 0)
status = 'The server has been provisioned.; ' + (stop ? 'Server description available.' : 'Waiting for server description.')
when 'ERROR'
raise MiqException::MiqProvisionError, "An error occurred while provisioning the instance."
else
status = "Unknown server state received from the cloud API: '#{instance_state}'"
_log.warn(status)
end
return stop, status
end
end
def customize_destination
signal :post_create_destination
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/parser.rb
|
<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::Inventory::Parser < ManageIQ::Providers::Inventory::Parser
require_nested :PowerVirtualServers
require_nested :VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/network_manager/floating_ip.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud<filename>app/models/manageiq/providers/ibm_cloud/vpc/network_manager/floating_ip.rb
class ManageIQ::Providers::IbmCloud::VPC::NetworkManager::FloatingIp < ::FloatingIp
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/power_virtual_servers.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Collector::PowerVirtualServers < ManageIQ::Providers::IbmCloud::Inventory::Collector
require_nested :CloudManager
require_nested :NetworkManager
require_nested :StorageManager
def connection
@power_iaas ||= manager.connect(:service => "PowerIaas")
end
def vms
connection.get_pvm_instances
end
def image(img_id)
connection.get_image(img_id)
end
def images
connection.get_images
end
def volumes
connection.get_volumes
end
def volume(volume_id)
connection.get_volume(volume_id)
end
def networks
connection.get_networks
end
def ports(network_id)
connection.get_network_ports(network_id)
end
def sshkeys
connection.get_ssh_keys
end
def system_pool
connection.get_system_pool.values
end
def storage_types
# TODO: The Power Cloud API does not yet have a call to retrieve
# available storage types.
::Settings.ems_refresh.ibm_cloud_power_virtual_servers.storage_types
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
spec/spec_helper.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud<filename>spec/spec_helper.rb
if ENV['CI']
require 'simplecov'
SimpleCov.start
end
Dir[Rails.root.join("spec/shared/**/*.rb")].each { |f| require f }
Dir[File.join(__dir__, "support/**/*.rb")].each { |f| require f }
require "manageiq-providers-ibm_cloud"
VCR.configure do |config|
config.ignore_hosts 'codeclimate.com' if ENV['CI']
config.cassette_library_dir = File.join(ManageIQ::Providers::IbmCloud::Engine.root, 'spec/vcr_cassettes')
config.before_record do |i|
# The ibm-cloud-sdk gem attempts to auto-renew the Bearer token if it
# detects that it is expired. This causes unhandled http interactions
# after the expiration time. We can replace the expiration time with
# one way in the future to prevent this.
if i.request.uri == "https://iam.cloud.ibm.com/identity/token"
body = JSON.parse(i.response.body)
body["expiration"] = Date.new(2100, 1, 1).to_time.to_i
i.response.body = body.to_json
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
spec/factories/ext_management_system.rb
|
FactoryBot.define do
factory :ems_ibm_cloud_power_virtual_servers_cloud,
:aliases => ["manageiq/providers/ibm_cloud_power_virtual_servers/cloud_manager"],
:class => "ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager",
:parent => :ems_cloud
end
FactoryBot.define do
factory :ems_ibm_cloud_power_virtual_servers_storage,
:aliases => ["manageiq/providers/ibm_cloud_power_virtual_servers/storage_manager"],
:class => "ManageIQ::Providers::IbmCloud::PowerVirtualServers::StorageManager",
:parent => :ems_cloud
end
FactoryBot.define do
factory :ems_ibm_cloud_vpc,
:class => "ManageIQ::Providers::IbmCloud::VPC::CloudManager",
:parent => :ems_cloud
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/cloud_manager/template.rb
|
class ManageIQ::Providers::IbmCloud::VPC::CloudManager::Template < ManageIQ::Providers::CloudManager::Template
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/system_type.rb
|
<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::SystemType < ::Flavor
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/vpc/cloud_manager/refresh_worker.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::VPC::CloudManager::RefreshWorker < MiqEmsRefreshWorker
require_nested :Runner
def self.settings_name
:ems_refresh_worker_ibm_cloud_vpc
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/collector/vpc/storage_manager.rb
|
<gh_stars>1-10
class ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC::StorageManager < ManageIQ::Providers::IbmCloud::Inventory::Collector::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
spec/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager_spec.rb
|
describe ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager do
it ".ems_type" do
expect(described_class.ems_type).to eq('ibm_cloud_power_virtual_servers')
end
it ".description" do
expect(described_class.description).to eq('IBM Power Systems Virtual Servers')
end
it "does not create orphaned network_manager" do
ems = FactoryBot.create(:ems_ibm_cloud_power_virtual_servers_cloud)
same_ems = ExtManagementSystem.find(ems.id)
ems.destroy
expect(ExtManagementSystem.count).to eq(0)
same_ems.save!
expect(ExtManagementSystem.count).to eq(0)
end
it "moves the network_manager to the same zone as the cloud_manager" do
zone1 = FactoryBot.create(:zone)
zone2 = FactoryBot.create(:zone)
ems = FactoryBot.create(:ems_ibm_cloud_power_virtual_servers_cloud, :zone => zone1)
expect(ems.network_manager.zone).to eq zone1
expect(ems.network_manager.zone_id).to eq zone1.id
ems.zone = zone2
ems.save!
ems.reload
expect(ems.network_manager.zone).to eq zone2
expect(ems.network_manager.zone_id).to eq zone2.id
end
describe "#catalog_types" do
let(:ems) { FactoryBot.create(:ems_ibm_cloud_power_virtual_servers_cloud) }
it "catalog_types" do
expect(ems.catalog_types).to be_empty
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
spec/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/auth_key_pair_spec.rb
|
describe ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::AuthKeyPair do
let(:ems) do
FactoryBot.create(:ems_ibm_cloud_power_virtual_servers_cloud, :provider_region => "us-south")
end
describe 'key pair create and delete' do
it 'creates new key pair' do
service = double
allow(ExtManagementSystem).to receive(:find).with(ems.id).and_return(ems)
allow(ems).to receive(:connect).with(:service => 'PowerIaas').and_return(service)
expect(service).to receive(:create_key_pair).with("new-name", "public-key").and_return({"name" => "new-name"})
described_class.create_key_pair(ems.id, :name => "new-name", :public_key => "public-key")
end
it 'deletes existing key pair' do
service = double
subject.name = 'key1'
subject.resource = ems
allow(ems).to receive(:connect).with(:service => 'PowerIaas').and_return(service)
expect(service).to receive(:delete_key_pair).with('key1')
subject.delete_key_pair
end
end
describe 'validations' do
it 'fails create with invalid parameters' do
expect(subject.class.validate_create_key_pair(nil)).to eq(:available => false, :message => 'The Keypair is not connected to an active Provider')
end
it 'pass create with valid parameters' do
expect(subject.class.validate_create_key_pair(ems)).to eq(:available => true, :message => nil)
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/refresh_worker/runner.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::RefreshWorker::Runner < ManageIQ::Providers::BaseManager::RefreshWorker::Runner
def do_before_work_loop
@emss.select { |ems| ems.kind_of?(EmsCloud) }.each do |ems|
log_prefix = "EMS [#{ems.hostname}] as [#{ems.authentication_userid}]"
_log.info("#{log_prefix} Queueing initial refresh for EMS #{ems.id}.")
EmsRefresh.queue_refresh(ems)
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
lib/manageiq-providers-ibm_cloud.rb
|
require "manageiq/providers/ibm_cloud/engine"
require "manageiq/providers/ibm_cloud/version"
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/parser/power_virtual_servers/storage_manager.rb
|
<filename>app/models/manageiq/providers/ibm_cloud/inventory/parser/power_virtual_servers/storage_manager.rb
class ManageIQ::Providers::IbmCloud::Inventory::Parser::PowerVirtualServers::StorageManager < ManageIQ::Providers::IbmCloud::Inventory::Parser::PowerVirtualServers
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/vm.rb
|
class ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::Vm < ManageIQ::Providers::CloudManager::Vm
supports :terminate
supports :reboot_guest do
unsupported_reason_add(:reboot_guest, _("The VM is not powered on")) unless current_state == "on"
end
supports :reset do
unsupported_reason_add(:reset, _("The VM is not powered on")) unless current_state == "on"
end
supports_not :suspend
def raw_start
with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.start_pvm_instance(ems_ref)
end
update!(:raw_power_state => "ACTIVE")
end
def raw_stop
with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.stop_pvm_instance(ems_ref)
end
update!(:raw_power_state => "SHUTOFF")
end
def raw_reboot_guest
with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.soft_reboot_pvm_instance(ems_ref)
end
end
def raw_reset
with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.hard_reboot_pvm_instance(ems_ref)
end
end
def raw_destroy
with_provider_connection(:service => 'PowerIaas') do |power_iaas|
power_iaas.delete_pvm_instance(ems_ref)
end
end
def validate_reboot
validate_vm_control_powered_on
end
def self.calculate_power_state(raw_power_state)
case raw_power_state
when "ACTIVE"
"on"
else
"off"
end
end
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/inventory/parser/vpc/cloud_manager.rb
|
class ManageIQ::Providers::IbmCloud::Inventory::Parser::VPC::CloudManager < ManageIQ::Providers::IbmCloud::Inventory::Parser::VPC
end
|
jrafanie/manageiq-providers-ibm_cloud
|
app/models/manageiq/providers/ibm_cloud/power_virtual_servers/cloud_manager/provision/state_machine.rb
|
<reponame>jrafanie/manageiq-providers-ibm_cloud
module ManageIQ::Providers::IbmCloud::PowerVirtualServers::CloudManager::Provision::StateMachine
def create_destination
signal :prepare_volumes
end
def prepare_volumes
new_volumes = options[:new_volumes]
phase_context[:new_volumes] = []
if new_volumes.any?
source.with_provider_object(:service => "PowerIaas") do |power_iaas|
new_volumes.each do |new_volume|
phase_context[:new_volumes] << power_iaas.create_volume(new_volume)['volumeID']
end
end
end
signal :prepare_provision
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_vm/images_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_vm, :current] do
let(:image_service) { Azure::VirtualMachineImageManagementService }
let(:image) do
VirtualMachineImage.new do |image|
image.os_type = 'Windows'
image.name = 'SQL-Server-2014CTP2-CU1-12.0.1736.0-ENU-WS2012R2-CY13SU12'
image.category = ' Microsoft SQL Server'
image.locations = 'West US'
end
end
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
management_endpoint: 'management.core.windows.net',
azure_subscription_id: 'Subscription-id',
location: 'west us'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
end
describe 'option validation' do
before :each do
$stdout.stubs(:write)
image_service.any_instance.stubs(
:list_virtual_machine_images
).returns([image])
end
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.images(@options) }.to_not raise_error
end
it 'should print images details' do
images = subject.images(@options)
expect(images).to match(
/#{image.os_type.fix} #{image.category[0..19]} #{image.name}/
)
end
end
describe 'optional parameter validation' do
describe '(location)' do
it 'location should be optional' do
@options.delete(:location)
expect { subject.images(@options) }.to_not raise_error
end
end
end
it_behaves_like 'validate authentication credential', :images
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_storage.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'puppet/storage_account'
Puppet::Face.define(:azure_storage, '1.0.0') do
summary 'View and manage Window Azure storage account.'
description <<-'EOT'
This subcommand provides a command line interface to work with Microsoft Azure
storage account. The goal of these actions are to easily manage storage account.
EOT
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_affinitygroup/delete.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_affinitygroup, '1.0.0' do
action :delete do
summary 'Delete affinity group.'
description <<-'EOT'
The delete action delete a affinity group.
EOT
Puppet::AffinityGroup.add_delete_options(self)
when_invoked do |options|
Puppet::AffinityGroup.initialize_env_variable(options)
affinity_group_service = Azure::BaseManagementService.new
begin
affinity_group_service.delete_affinity_group(
options[:affinity_group_name]
)
rescue => e
puts e.message
end
end
examples <<-'EOT'
$ puppet azure_affinitygroup delete --affinity-group-name ag-name \
--management-certificate path-to-azure-certificate \
--azure-subscription-id YOUR-SUBSCRIPTION-ID
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_cloudservice.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'puppet/cloud_service'
Puppet::Face.define(:azure_cloudservice, '1.0.0') do
summary 'View and manage Window Azure cloud service.'
description <<-'EOT'
This subcommand provides a command line interface to work with Microsoft Azure
cloud services. The goal of these actions are to easily manage cloud service.
EOT
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/storage_account.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'puppet/core/utility'
require 'puppet/application_config'
include Puppet::ApplicationConfig
module Puppet::StorageAccount
class << self
def views(name)
File.join(File.dirname(__FILE__), 'face/azure_storage/views', name)
end
def add_create_options(action)
add_default_options(action)
add_affinity_group_name_option(action, true)
add_location_option(action, true)
add_storage_account_name_option(action)
add_description_option(action)
add_label_option(action)
add_extended_properties_option(action)
end
def add_delete_options(action)
add_default_options(action)
add_storage_account_name_option(action)
end
def add_description_option(action)
action.option '--description=' do
summary 'Description of storage account'
description 'Description of storage account'
end
end
def add_label_option(action)
action.option '--label=' do
summary 'Label of storage account'
description 'Label of storage account'
end
end
def add_storage_account_name_option(action)
action.option '--storage-account-name=' do
summary 'The name of the storae account.'
description 'The name of the storage account.'
required
before_action do |act, args, options|
if act.name == :create && options[:location].nil? && options[:affinity_group_name].nil?
fail ArgumentError, 'affinity group name or location is required.'
end
if options[:storage_account_name].empty?
fail ArgumentError, 'Storage Account name is required.'
end
end
end
end
def add_extended_properties_option(action)
action.option '--extended-properties=' do
summary 'Extended properties of storage account'
description 'Extended properties of storage account'
properties = {}
before_action do |act, args, options|
options[:extended_properties].split(',').each do |prop|
values = prop.split(':')
properties[values[0].to_sym] = values[1] if values.size == 2
end
options[:extended_properties] = properties
end
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_affinitygroup/list_spec.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_affinitygroup, :current] do
let(:base_service) { Azure::BaseManagementService }
let(:affinity_group) do
Azure::BaseManagement::AffinityGroup.new do |ag|
ag.name = 'AG1'
ag.label = 'Label'
ag.description = 'Description'
ag.capability = %w(PersistentVMRole HighMemory)
end
end
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
management_endpoint: 'management.core.windows.net',
azure_subscription_id: 'Subscription-id'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
end
describe 'option validation' do
before :each do
base_service.any_instance.stubs(
:list_affinity_groups
).returns([affinity_group])
end
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.list(@options) }.to_not raise_error
end
it 'should print affinity groups details' do
affinity_groups = subject.list(@options)
name = "#{'Name'.fix(20)}: #{affinity_group.name}"
expect(affinity_groups).to match(/#{name}/)
label = "#{'Label'.fix(20)}: #{affinity_group.label}"
expect(affinity_groups).to match(/#{label}/)
capability = "#{'Capability'.fix(20)}: #{affinity_group.capability}"
expect(affinity_groups).to match(/#{capability}/)
end
end
it_behaves_like 'validate authentication credential', :list
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/cloud_service.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'puppet/core/utility'
require 'puppet/application_config'
include Puppet::ApplicationConfig
module Puppet::CloudService
class << self
def views(name)
File.join(File.dirname(__FILE__), 'face/azure_cloudservice/views', name)
end
def add_create_options(action)
add_default_options(action)
add_affinity_group_name_option(action, true)
add_location_option(action, true)
add_cloud_service_name_option(action)
add_description_option(action)
add_label_option(action)
end
def add_delete_options(action)
add_default_options(action)
add_cloud_service_name_option(action)
end
def add_certificate_options(action)
add_default_options(action)
add_cloud_service_name_option(action)
add_certificate_file_option(action)
add_private_key_file_option(action)
end
def add_delete_deployment_options(action)
add_default_options(action)
add_cloud_service_name_option(action)
end
def add_description_option(action)
action.option '--description=' do
summary 'Description of cloud service'
description 'Description of cloud service.'
end
end
def add_label_option(action)
action.option '--label=' do
summary 'Label of cloud service'
description 'Label of cloud service.'
end
end
def add_cloud_service_name_option(action)
action.option '--cloud-service-name=' do
summary 'The name of the cloud service.'
description 'The name of the cloud service.'
required
before_action do |act, args, options|
if act.name == :create && options[:location].nil? && options[:affinity_group_name].nil?
fail ArgumentError, 'affinity group name or location is required.'
end
if options[:cloud_service_name].empty?
fail ArgumentError, 'Cloud service name is required.'
end
end
end
end
def add_certificate_file_option(action)
action.option '--certificate-file=' do
summary 'Specify certificate file.'
description 'Path of certificate file.'
required
before_action do |act, args, options|
file_path = options[:certificate_file]
unless test 'f', file_path
fail ArgumentError, "Could not find file '#{file_path}'"
end
unless test 'r', file_path
fail ArgumentError, "Could not read from file '#{file_path}'"
end
end
end
end
def add_private_key_file_option(action)
action.option '--private-key-file=' do
summary 'Specify private key file.'
description 'Path of private key file.'
required
before_action do |act, args, options|
file_path = options[:private_key_file]
unless test 'f', file_path
fail ArgumentError, "Could not find file '#{file_path}'"
end
unless test 'r', file_path
fail ArgumentError, "Could not read from file '#{file_path}'"
end
end
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_sqldb/list_spec.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_sqldb, :current] do
let(:sql_service) { Azure::SqlDatabaseManagementService }
let(:sql_server) do
Azure::SqlDatabaseManagement::SqlDatabase.new do |db|
db.name = 'db-1'
db.administrator_login = 'login-name'
db.location = 'West US'
end
end
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
management_endpoint: 'management.core.windows.net',
azure_subscription_id: 'Subscription-id'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
end
describe 'option validation' do
before :each do
sql_service.any_instance.stubs(
:list_servers
).returns([sql_server])
end
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.list(@options) }.to_not raise_error
end
it 'should print affinity groups details' do
db_servers = subject.list(@options)
expect(db_servers).to match(/Server Name : #{sql_server.name}/)
login = "Administrator login : #{sql_server.administrator_login}"
expect(db_servers).to match(/#{login}/)
location = "#{'Location'.fix(20)}: #{sql_server.location}"
expect(db_servers).to match(/#{location}/)
end
end
it_behaves_like 'validate authentication credential', :list
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_servicebus/create_queue.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_servicebus, '1.0.0' do
action :create_queue do
summary 'Creates queue with service bus object.'
description <<-'EOT'
Creates queue with service bus object.
EOT
Puppet::ServiceBus.add_servicebus_queue_options(self)
when_invoked do |options|
Puppet::ServiceBus.initialize_env_variable(options)
azure_service_bus = Azure::ServiceBusService.new
azure_service_bus.create_queue(options[:queue_name]).inspect
end
returns 'NONE'
examples <<-'EOT'
$ puppet azure_servicebus create_queue --sb-namespace busname \
--queue-name queuename --sb-access-key <KEY>
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_vm/add_disk_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_vm, :current] do
let(:vms) { Azure::VirtualMachineManagementService }
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
azure_subscription_id: 'Subscription-id',
vm_name: 'test-vm',
cloud_service_name: 'cloud-name',
import: 'false',
disk_size: '100',
disk_label: 'Disk_label',
disk_name: 'Disk Name'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
vms.any_instance.stubs(:add_data_disk).with(
anything,
anything,
anything
)
end
describe 'option validation' do
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.add_disk(@options) }.to_not raise_error
end
end
describe '(vm_name)' do
it 'should require a vm name' do
@options.delete(:vm_name)
expect { subject.add_disk(@options) }.to raise_error(
ArgumentError,
/required: vm_name/
)
end
end
describe '(cloud_service_name)' do
it 'should require a cloud service name' do
@options.delete(:cloud_service_name)
expect { subject.add_disk(@options) }.to raise_error(
ArgumentError,
/required: cloud_service_name/
)
end
end
describe '(disk_size)' do
it 'should validate the disk_size' do
@options.delete(:disk_size)
expect { subject.add_disk(@options) }.to_not raise_error
end
end
describe '(disk_label)' do
it 'should validate disk_label' do
@options.delete(:disk_label)
expect { subject.add_disk(@options) }.to_not raise_error
end
end
describe '(disk_name)' do
it 'should require disk_name when import is true' do
@options[:import] = 'true'
expect { subject.add_disk(@options) }.to_not raise_error
end
it 'should raise error when import is true and disk_name is empty' do
@options[:import] = 'true'
@options.delete(:disk_name)
expect { subject.add_disk(@options) }.to raise_error(
ArgumentError,
/Disk name is required when import is true/
)
end
end
describe '(import)' do
it 'import should be true, false or empty' do
@options[:import] = 'wrong_value'
expect { subject.add_disk(@options) }.to raise_error(
ArgumentError,
/Disk import option is not valid/
)
end
it 'should validate disk_name when import is false' do
@options.delete(:import)
expect { subject.add_disk(@options) }.to_not raise_error
end
end
it_behaves_like 'validate authentication credential', :add_disk
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_vnet/set_virtual_network.rb
|
<filename>lib/puppet/face/azure_vnet/set_virtual_network.rb
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_vnet, '1.0.0' do
action :set do
summary 'Set Network configures the virtual network'
description <<-'EOT'
The Set Network Configuration operation asynchronously configures the virtual network.
EOT
Puppet::VirtualNetwork.add_set_virtual_network_options(self)
when_invoked do |options|
Puppet::VirtualNetwork.initialize_env_variable(options)
virtual_network_service = Azure::VirtualNetworkManagementService.new
address_space = options[:address_space].split(',')
optional = {}
if options[:subnets]
subnets = []
options[:subnets].split(',').each do |subnet|
values = subnet.split(':')
fail 'Missing argument subnet name or ip_address or cidr in subnet' if values.size != 3
subnets << { name: values[0], ip_address: values[1], cidr: values[2] }
end
optional[:subnet] = subnets
end
if options[:dns_servers]
dns = []
options[:dns_servers].split(',').each do |ds|
values = ds.split(':')
fail 'Missing argument dns name or ip_address in dns' if values.size != 2
dns << { name: values[0], ip_address: values[1] }
end
optional[:dns] = dns
end
virtual_network_service.set_network_configuration(
options[:virtual_network_name],
options[:location],
address_space,
optional
)
nil
end
returns 'None '
examples <<-'EOT'
$ puppet azure_vnet set --management-certificate path-to-certificate \
--azure-subscription-id=YOUR-SUBSCRIPTION-ID \
--dns-servers 'google-1:8.8.8.8,google-2:8.8.4.4' \
--subnets 'subnet-1:172.16.0.0:12,subnet-2:192.168.0.0:29' \
--virtual-network-name v-net --location 'West US' \
--address-space '172.16.0.0/12,192.168.0.0/16'
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/azurepack/installer.rb
|
<filename>lib/puppet/azurepack/installer.rb<gh_stars>1-10
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'erb'
module Puppet
module AzurePack
module Installer
class << self
def build_installer_template(name, options = {})
# binding is a kernel method
ERB.new(File.read(find_template(name))).result(binding)
end
def lib_script_dir
File.join(File.dirname(__FILE__), 'scripts')
end
def find_template(name)
user_script = File.expand_path("../#{name}.erb", __FILE__)
puts user_script
return user_script if File.exists?(user_script)
lib_script = File.join(lib_script_dir, "#{name}.erb")
if File.exists?(lib_script)
lib_script
else
fail "Could not find installation template for #{name}"
end
end
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_sqldb/delete.rb
|
<filename>lib/puppet/face/azure_sqldb/delete.rb
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_sqldb, '1.0.0' do
action :delete do
summary 'Delete Microsoft Azure sql database server'
description <<-'EOT'
The delete action delete windows azure sql server.
EOT
Puppet::SqlDatabase.add_delete_options(self)
when_invoked do |options|
Puppet::SqlDatabase.initialize_env_variable(options)
db = Azure::SqlDatabaseManagementService.new
db.delete_server(options[:server_name])
nil
end
returns 'NONE'
examples <<-'EOT'
$ puppet azure_sqldb delete --server-name=ezprthvj9w \
--management-certificate path-to-azure-certificate \
--azure-subscription-id OUR-SUBSCRIPTION-ID \
--management-endpoint=https://management.database.windows.net:8443/
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_vnet/set_virtual_network_spec.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_vnet, :current] do
let(:vnet_service) { Azure::VirtualNetworkManagementService }
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
azure_subscription_id: 'Subscription-id',
management_endpoint: 'management.core.windows.net',
virtual_network_name: 'login-name',
location: 'West US',
address_space: '172.16.0.0/12,10.0.0.0/8,192.168.0.0/24',
dns_servers: 'dns-1:8.8.8.8,dns-2:8.8.4.4',
subnets: 'subnet-1:172.16.0.0:12'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
vnet_service.any_instance.stubs(:set_network_configuration).with(
any_parameters
)
end
describe 'option validation' do
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.set(@options) }.to_not raise_error
end
end
describe '(virtual_network_name)' do
it 'should validate the virtual network name' do
@options.delete(:virtual_network_name)
expect { subject.set(@options) }.to raise_error(
ArgumentError,
/required: virtual_network_name/
)
end
end
describe '(location)' do
it 'should validate the location' do
@options.delete(:location)
expect { subject.set(@options) }.to raise_error(
ArgumentError,
/required: location/
)
end
end
describe '(address_space)' do
it 'should validate address space' do
@options.delete(:address_space)
expect { subject.set(@options) }.to raise_error(
ArgumentError,
/required: address_space/
)
end
end
it_behaves_like 'validate authentication credential', :set
end
describe 'optional parameter validation' do
describe '(subnets)' do
it 'subnets should be optional' do
@options.delete(:subnets)
expect { subject.set(@options) }.to_not raise_error
end
it 'should accept multiple value of subnet using comma seperated' do
@options[:subnets] = 'subnet-1:172.16.0.0:12,subnet-2:192.168.0.0:29'
expect { subject.set(@options) }.to_not raise_error
end
describe 'invalid subnets' do
it 'should raise error when cidr and ip_address is missing' do
@options[:subnets] = 'Subnet-name'
expect { subject.set(@options) }.to raise_error(
RuntimeError,
/Missing argument subnet name or ip_address or cidr in subnet/
)
end
it 'should raise error when cidr is missing' do
@options[:subnets] = 'Subnet-name:192.168.1.1'
expect { subject.set(@options) }.to raise_error(
RuntimeError,
/Missing argument subnet name or ip_address or cidr in subnet/
)
end
end
end
describe '(dns_servers)' do
it 'dns_servers should be optional' do
@options.delete(:dns_servers)
expect { subject.set(@options) }.to_not raise_error
end
it 'dns_servers and subnets should be optional' do
@options.delete(:dns_servers)
@options.delete(:subnets)
expect { subject.set(@options) }.to_not raise_error
end
describe 'invalid dns servers' do
it 'should raise error when dns name or ipaddress is missing' do
@options[:dns_servers] = 'Dns-name'
expect { subject.set(@options) }.to raise_error(
RuntimeError,
/Missing argument dns name or ip_address in dns/
)
end
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/azurepack/bootstrap.rb
|
<gh_stars>1-10
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'puppet/core/remote_connection'
require 'puppet/core/utility'
require 'puppet/azurepack/installer'
require 'tempfile'
include Puppet::Core::RemoteConnection
include Puppet::Core::Utility
module Puppet
module AzurePack
module BootStrap
class << self
def start(params)
puts "Installing puppet on node #{params[:node_ipaddress]}\n"
puts
params[:agent_environment] ||= 'production'
if params[:winrm_user]
bootstrap_windows_node(params)
elsif params[:ssh_user]
results = bootstrap_linux_node(params)
if results[:exit_code] != 0 then
puts 'The installation script exited with a non-zero exit status, indicating a failure.'
end
else
fail 'Missing option ssh_user or winrm_user'
end
end
def bootstrap_windows_node(params)
node_ip = params[:node_ipaddress]
master_ip = params[:puppet_master_ip]
login = params[:winrm_user]
password = <PASSWORD>]
env = params[:agent_environment]
if params[:winrm_transport] == 'https'
winrm_port = params[:winrm_port] || 5986
endpoint_protocol = 'https'
else
winrm_port = params[:winrm_port] || 5985
endpoint_protocol = 'http'
end
test_winrm_connecton(node_ip, winrm_port)
cmds = []
cmds << 'mkdir C:\\puppet'
wget_script.each_line do |line|
ln = line.gsub("\n", ' ')
cmds << "echo #{ln} >> C:\\puppet\\wget.vbs"
end
cmds << 'cscript /nologo C:\\puppet\\wget.vbs https://downloads.puppetlabs.com/windows/puppet-3.3.2.msi %TEMP%\\puppet.msi'
cmds << 'copy %TEMP%\\puppet.msi C:\\puppet\\puppet.msi'
cmds << "msiexec /qn /i c:\\puppet\\puppet.msi PUPPET_MASTER_SERVER=#{master_ip} PUPPET_AGENT_ENVIRONMENT=#{env}"
cmds << 'sc config puppet start= demand'
cmds << 'rmdir C:\\puppet /s /q'
winrm_remote_execute(node_ip, login, password, cmds, endpoint_protocol, winrm_port)
end
def bootstrap_linux_node(params)
login = params[:ssh_user]
ssh_opts = {}
if params[:password]
ssh_opts[:password] = params[:password]
else
ssh_opts[:keys] = [params[:private_key_file]]
end
ssh_opts[:paranoid] = false
ssh_opts[:port] = params[:ssh_port] || 22
ipaddress = params[:node_ipaddress]
wait_for_connection(ipaddress, ssh_opts[:port])
options = { agent_environment: params[:agent_environment], puppet_master_ip: params[:puppet_master_ip] }
tmp_dir = File.join('/', 'tmp', random_string('puppet-tmp-location-', 10))
create_tmpdir_cmd = "bash -c 'umask 077; mkdir #{tmp_dir}'"
ssh_remote_execute(ipaddress, login, ssh_opts, create_tmpdir_cmd)
tmp_script_file = compile_template('puppet-agent-bootstrap', options)
remote_script_path = File.join(tmp_dir, 'puppet_installation_script.sh')
scp_remote_upload(ipaddress, login, ssh_opts, tmp_script_file.path, remote_script_path)
cmd_prefix = login == 'root' ? '' : 'sudo '
install_command = "#{cmd_prefix}bash -c 'chmod u+x #{remote_script_path}; sed -i 's/\r//' #{remote_script_path}; #{remote_script_path}'"
ssh_remote_execute(ipaddress, login, ssh_opts, install_command)
end
def compile_template(template_name, options)
puts 'Installing Puppet ...'
install_script = Installer.build_installer_template(template_name, options)
puts('Compiled installation script:')
begin
f = Tempfile.open('install_script')
f.write(install_script)
f
rescue Exception => e
puts e
ensure
f.close
end
end
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_storage/delete.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_storage, '1.0.0' do
action :delete do
summary 'Delete storage account.'
description 'The delete action delete a storage account.'
Puppet::StorageAccount.add_delete_options(self)
when_invoked do |options|
Puppet::StorageAccount.initialize_env_variable(options)
storage_service = Azure::StorageManagementService.new
begin
storage_service.delete_storage_account(options[:storage_account_name])
rescue
end
nil
end
examples <<-'EOT'
$ puppet azure_storage delete --storage-account-name storagename \
--azure-subscription-id YOUR-SUBSCRIPTION-ID \
--management-certificate path-to-azure-certificate
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_sqldb/reset_password.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_sqldb, '1.0.0' do
action :reset_password do
summary 'Reset password of sql database server.'
description <<-'EOT'
The reset_passowrd action reset password of sql database server.
EOT
Puppet::SqlDatabase.add_reset_password_options(self)
when_invoked do |options|
Puppet::SqlDatabase.initialize_env_variable(options)
db = Azure::SqlDatabaseManagementService.new
db.reset_password(options[:server_name], options[:password])
nil
end
examples <<-'EOT'
$ puppet azure_sqldb reset_password --password <PASSWORD>$# \
--management-certificate path-to-azure-certificate \
--azure-subscription-id=YOUR-SUBSCRIPTION-ID --server-name hc786mm0l8 \
--management-endpoint=https://management.database.windows.net:8443/\
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_vm/images.rb
|
<filename>lib/puppet/face/azure_vm/images.rb<gh_stars>1-10
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_vm, '1.0.0' do
action :images do
summary 'List Microsoft Azure images'
description <<-'EOT'
The images action obtains a list of images from the cloud provider and
displays them on the console output.
EOT
Puppet::VirtualMachine.add_list_images_options(self)
when_invoked do |options|
Puppet::VirtualMachine.initialize_env_variable(options)
image_service = Azure::VirtualMachineImageManagementService.new
images = image_service.list_virtual_machine_images
location = options[:location]
images = images.select { |x| x.locations =~ /#{location}/i } if location
template = Tilt.new(Puppet::VirtualMachine.views('images.erb'))
template.render(nil, images: images)
end
returns 'List containing information about each Azure images.'
examples <<-'EOT'
$ puppet azure_vm images --azure-subscription-id YOUR-SUBSCRIPTION-ID \
--management-certificate path-to-azure-certificate
Listing Virtual Machine Images
OS Type Category Name
Linux RightScale with Linu RightImage-CentOS-6.2-x64-v5.8.8.1
Linux RightScale with Linu RightImage-CentOS-6.3-x64-v5.8.8
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_cloudservice/delete.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_cloudservice, '1.0.0' do
action :delete do
summary 'Delete cloud service.'
description 'The delete action delete a cloud service.'
Puppet::CloudService.add_delete_options(self)
when_invoked do |options|
Puppet::CloudService.initialize_env_variable(options)
cloud_service = Azure::CloudServiceManagementService.new
begin
cloud_service.delete_cloud_service(options[:cloud_service_name])
rescue
end
nil
end
examples <<-'EOT'
$ puppet azure_cloudservice delete --cloud-service-name cloudservice1 \
--azure-subscription-id YOUR-SUBSCRIPTION-ID \
--management-certificate path-to-azure-certificate
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_sqldb/list_firewall_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_sqldb, :current] do
let(:sql_service) { Azure::SqlDatabaseManagementService }
let(:firewalls) do
[
{
rule: 'Rule 1',
start_ip_address: '192.168.1.1',
end_ip_address: '192.168.1.255'
}
]
end
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
management_endpoint: 'management.core.windows.net',
azure_subscription_id: 'Subscription-id',
server_name: 'db-server'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
end
describe 'option validation' do
before :each do
sql_service.any_instance.stubs(
:list_sql_server_firewall_rules
).returns(firewalls)
end
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.list_firewall(@options) }.to_not raise_error
end
it 'should print affinity groups details' do
server_firewalls = subject.list_firewall(@options)
firewall = firewalls.first
start_ip = firewall[:start_ip_address]
end_ip = firewall[:end_ip_address]
rule = "#{'Rule Name'.fix(20)}: #{firewall[:rule]}"
expect(server_firewalls).to match(/#{rule}/)
start_ip_text = "#{'Start IP Address'.fix(20)}: #{start_ip}"
expect(server_firewalls).to match(/#{start_ip_text}/)
end_ip_text = "#{'End IP Address'.fix(20)}: #{end_ip}"
expect(server_firewalls).to match(/#{end_ip_text}/)
end
end
it_behaves_like 'validate authentication credential', :list_firewall
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_vm.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'puppet/virtual_machine'
Puppet::Face.define(:azure_vm, '1.0.0') do
summary 'View and manage Window Azure nodes.'
description <<-'EOT'
This subcommand provides a command line interface to work with Microsoft Azure
machine instances. The goal of these actions are to easily create new
machines, install Puppet onto them, and tear them down when they're no longer
required.
EOT
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_vm/restart.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_vm, '1.0.0' do
action :restart do
summary 'Restarts Microsoft Azure node instance'
description <<-'EOT'
The restart action restarts windows azure node instance.
EOT
Puppet::VirtualMachine.add_shutdown_options(self)
when_invoked do |options|
Puppet::VirtualMachine.initialize_env_variable(options)
virtual_machine_service = Azure::VirtualMachineManagementService.new
virtual_machine_service.restart_virtual_machine(
options[:vm_name],
options[:cloud_service_name]
)
nil
end
returns 'NONE'
examples <<-'EOT'
$ puppet azure_vm restart --cloud-service-name service_name \
--management-certificate path-to-azure-certificate \
--azure-subscription-id YOUR-SUBSCRIPTION-ID --vm-name name
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_queue/create_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'spec_helper'
describe Puppet::Face[:azure_queue, :current] do
let(:queue_service) { Azure::QueueService }
before :each do
@options = {
storage_account_name: 'storage-account',
storage_access_key: '<KEY>
queue_name: 'queue'
}
Azure.configure do |config|
config.storage_account_name = @options[:storage_account_name]
config.storage_access_key = @options[:storage_access_key]
end
queue_service.any_instance.stubs(:create_queue).with(any_parameters)
end
describe 'option validation' do
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.create(@options) }.to_not raise_error
end
end
describe '(queue_name)' do
it 'should validate queue name' do
@options.delete(:queue_name)
expect { subject.create(@options) }.to raise_error(
ArgumentError,
/required: queue_name/
)
end
end
describe '(storage_access_key)' do
it 'should validate service bus access key' do
@options.delete(:storage_access_key)
expect { subject.create(@options) }.to raise_error(
ArgumentError,
/required: storage_access_key/
)
end
end
describe '(storage_account_name)' do
it 'should validate storage account name' do
@options.delete(:storage_account_name)
expect { subject.create(@options) }.to raise_error(
ArgumentError,
/required: storage_account_name/
)
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_vm/locations_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_vm, :current] do
let(:base_service) { Azure::BaseManagementService }
let(:location_name) { 'West US' }
let(:loc_services) { 'Compute, Storage, PersistentVMRole, HighMemory' }
let(:location) do
Location.new do |loc|
loc.name = location_name
loc.available_services = loc_services
end
end
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
management_endpoint: 'management.core.windows.net',
azure_subscription_id: 'Subscription-id'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
end
describe 'option validation' do
before :each do
base_service.any_instance.stubs(:list_locations).returns([location])
end
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.locations(@options) }.to_not raise_error
end
it 'should print locations details' do
locations = subject.locations(@options)
expect(locations).to match(/#{location_name.fix} #{loc_services}/)
end
end
it_behaves_like 'validate authentication credential', :locations
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_vm/add_role.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_vm, '1.0.0' do
action :add_role do
summary 'Create multiple roles under the same cloud service'
description <<-'EOT'
The add_role action create multiple roles under the same cloud service.
Atleast a single deployment should be created under a hosted service.
EOT
Puppet::VirtualMachine.add_create_options(self, true)
when_invoked do |options|
options = ask_for_password(options, @os_type)
virtual_machine_service = Azure::VirtualMachineManagementService.new
params = {
vm_name: options[:vm_name],
vm_user: options[:vm_user],
image: options[:image],
password: options[:password],
cloud_service_name: options[:cloud_service_name],
}
others = {
storage_account_name: options[:storage_account_name],
tcp_endpoints: options[:tcp_endpoints],
private_key_file: options[:private_key_file] ,
certificate_file: options[:certificate_file],
ssh_port: options[:ssh_port],
vm_size: options[:vm_size],
virtual_network_name: options[:virtual_network_name],
subnet_name: options[:virtual_network_subnet],
affinity_group_name: options[:affinity_group_name],
availability_set_name: options[:availability_set_name],
winrm_http_port: options[:winrm_http_port],
winrm_https_port: options[:winrm_https_port],
}
winrm_tp = options[:winrm_transport]
others.merge!(winrm_transport: winrm_tp) unless winrm_tp.nil?
server = virtual_machine_service.add_role(params, others)
unless server.class == String
if options[:puppet_master_ip] && server
if server.os_type == 'Linux'
options[:node_ipaddress] = server.ipaddress
options[:ssh_user] = params[:vm_user]
Puppet::AzurePack::BootStrap.start(options)
else
puts
msg = <<-'EOT'
To Bootstrap windows node log into the VM and run these commands:
winrm set winrm/config/service @{AllowUnencrypted="true"}
winrm set winrm/config/service/auth @{Basic="true"}
And then run puppet bootstrap command on master.
EOT
puts msg
end
end
end
end
examples <<-'EOT'
$ puppet azure_vm add_role --vm-name vmname --location "Southeast Asia" \
--management-certificate path-to-azure-certificate --vm-user ranjan \
--password <PASSWORD> --storage-account-name storageaccount1'\
--image b446e5424aa335e__SUSE-Linux-Enterprise-Server-11-SP2-Agent13 \
--cloud-service-name cloudname --subscription-id YOUR-SUBSCRIPTION-ID \
--tcp-endpoints "80,3889:3889"
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_cloudservice/delete_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_cloudservice, :current] do
let(:cloud_service) { Azure::CloudServiceManagementService }
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
azure_subscription_id: 'Subscription-id',
cloud_service_name: 'cloud-name'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
cloud_service.any_instance.stubs(:delete_cloud_service).with(anything)
end
describe 'option validation' do
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.delete(@options) }.to_not raise_error
end
end
describe '(cloud_service_name)' do
it 'should validate cloud service name' do
@options.delete(:cloud_service_name)
expect { subject.delete(@options) }.to raise_error(
ArgumentError,
/required: cloud_service_name/
)
end
end
it_behaves_like 'validate authentication credential', :delete
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/core/remote_connection.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet<filename>lib/puppet/core/remote_connection.rb
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'net/ssh'
require 'net/scp'
require 'winrm'
module Puppet
module Core
module RemoteConnection
def scp_remote_upload(server, login, ssh_opts, local_path, remote_path)
begin
Net::SCP.start(server, login, ssh_opts) do |scp|
scp.upload! local_path, remote_path
end
rescue Net::SSH::HostKeyMismatch => e
puts "remembering new key: #{e.fingerprint}"
e.remember_host!
retry
rescue Net::SSH::AuthenticationFailed => user
fail "Authentication failure for user #{user}."
rescue => e
fail e.message
end
end
def ssh_remote_execute(server, login, ssh_opts, command)
puts 'Executing remote command ...'
puts "Command: #{command}"
buffer = ''
stdout = ''
exit_code = nil
begin
ssh_opts[:timeout] = 10
Net::SSH.start(server, login, ssh_opts) do |session|
session.open_channel do |channel|
channel.request_pty do |c, success|
fail 'could not request pty' unless success
channel.on_data do |ch, data|
if data =~ /\[sudo\]/ || data =~ /Password/i
channel.send_data "#{ssh_opts[:password]}\n"
end
buffer << data
stdout << data
if buffer =~ /\n/
lines = buffer.split("\n")
buffer = lines.length > 1 ? lines.pop : String.new
lines.each do |line|
puts line
end
end
end
channel.on_eof do |ch|
# Display anything remaining in the buffer
puts buffer unless buffer.empty?
end
channel.on_request('exit-status') do |ch, data|
exit_code = data.read_long
puts "SSH Command Exit Code: #{exit_code}"
end
# Finally execute the command
channel.exec(command)
end
end
session.loop
end
rescue Timeout::Error
raise 'Connection Timed out'
rescue Errno::EHOSTUNREACH
fail 'Host unreachable'
rescue Errno::ECONNREFUSED
fail 'Connection refused'
rescue Net::SSH::HostKeyMismatch => e
puts "remembering new key: #{e.fingerprint}"
e.remember_host!
retry
rescue Net::SSH::AuthenticationFailed => user
fail "Authentication failure for user #{user}."
rescue => e
puts e.message
end
puts 'Executing remote command ... Done'
{ exit_code: exit_code, stdout: stdout }
end
def winrm_remote_execute(node_ip, login, password, cmds, endpoint_protocol, port)
endpoint = "#{endpoint_protocol}://#{node_ip}:#{port}/wsman"
winrm = WinRM::WinRMWebService.new(
endpoint,
:plaintext,
user: login,
pass: password,
basic_auth_only: true
)
cmds.each do |cmd|
puts "Executing command #{cmd}"
winrm.cmd(cmd) do |stdout, stderr|
STDOUT.print stdout
STDERR.print stderr
end
end
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_vm/add_role_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_vm, :current] do
let(:image_name) { 'azure-linux-image' }
let(:os_type) { 'Windows' }
let(:image_service) { Azure::VirtualMachineImageManagementService }
let(:vm_service) { Azure::VirtualMachineManagementService }
let(:vm) { Azure::VirtualMachineManagement::VirtualMachine }
let(:virtual_machine_obj) do
vm.new do |virtual_machine|
virtual_machine.vm_name = 'windows-instance'
virtual_machine.ipaddress = '192.168.1.1'
virtual_machine.os_type = os_type
end
end
let(:image) do
VirtualMachineImage.new do |image|
image.os_type = os_type
image.name = image_name
end
end
before :each do
$stdout.stubs(:write)
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
azure_subscription_id: 'Subscription-id',
vm_name: 'test-vm',
vm_user: 'vm_user',
image: image_name,
password: '<PASSWORD>',
ssh_port: 22,
affinity_group_name: 'ag',
certificate_file: File.expand_path('spec/fixtures/certificate.pem'),
private_key_file: File.expand_path('spec/fixtures/private_key.key'),
cloud_service_name: 'cloud-name',
management_endpoint: 'management.core.windows.net',
puppet_master_ip: '127.0.0.1',
storage_account_name: 'storage_account',
tcp_endpoints: '80:80',
virtual_network_name: 'vnet',
virtual_network_subnet: 'Subnet-1',
winrm_transport: 'http',
vm_size: 'Small',
availability_set_name: 'availabiity-set-name',
winrm_http_port: '5985',
winrm_https_port: '5986'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
vm_service.any_instance.stubs(:add_role).with(
anything,
anything
).returns(virtual_machine_obj)
image_service.any_instance.expects(
:list_virtual_machine_images
).returns([image]).at_least(0)
end
describe 'option validation' do
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(image)' do
it 'should require a image' do
@options.delete(:image)
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/required: image/
)
end
it 'should validate the image' do
@options[:image] = 'WrongImageName'
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/Source image name is invalid/
)
end
end
describe '(vm_name)' do
it 'should validate the vm name' do
@options.delete(:vm_name)
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/required: vm_name/
)
end
end
it_behaves_like 'validate authentication credential', :add_role
describe '(vm_user)' do
it 'should require a vm user' do
@options.delete(:vm_user)
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/required: vm_user/
)
end
end
end
describe 'optional parameter validation' do
describe '(vm_size)' do
it 'vm_size should be optional' do
@options.delete(:vm_size)
expect { subject.add_role(@options) }.to_not raise_error
end
it 'should validate the vm_size' do
@options[:vm_size] = 'InvalidSize'
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/The vm-size is not valid/
)
end
end
describe '(availability_set)' do
it 'availability_set should be optional' do
@options.delete(:availability_set_name)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(winrm_transport)' do
it 'winrm_transport should be optional' do
@options.delete(:winrm_transport)
expect { subject.add_role(@options) }.to_not raise_error
end
it 'should validate the winrm_transport' do
@options[:winrm_transport] = 'ftp'
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/The winrm transport is not valid/
)
end
it 'should validate the winrm_transport' do
@options[:winrm_transport] = 'http'
expect { subject.add_role(@options) }.to_not raise_error
end
it 'should validate the winrm_transport' do
@options[:winrm_transport] = 'https,http'
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(virtual_network_subnet)' do
it 'virtual_network_subnet should be optional' do
@options.delete(:virtual_network_subnet)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(virtual_network_name)' do
it 'virtual_network_name should be optional' do
@options.delete(:virtual_network_name)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(tcp_endpoints)' do
it 'tcp_endpoints should be optional' do
@options.delete(:tcp_endpoints)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(ssh_port)' do
it 'ssh_port should be optional' do
@options.delete(:ssh_port)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(affinity_group_name)' do
it 'affinity_group_name should be optional' do
@options.delete(:affinity_group_name)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(certificate_file)' do
it 'certificate_file should be optional' do
@options.delete(:certificate_file)
expect { subject.add_role(@options) }.to_not raise_error
end
it 'certificate_file should exist' do
@options[:certificate_file] = 'FileNotExist'
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/Could not find file 'FileNotExist'/
)
end
end
describe '(private_key_file)' do
it 'private_key_file should be optional' do
@options.delete(:private_key_file)
expect { subject.add_role(@options) }.to_not raise_error
end
it 'private_key_file should exist' do
@options[:private_key_file] = 'FileNotExist'
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/Could not find file 'FileNotExist'/
)
end
end
describe '(cloud_service_name)' do
it 'cloud_service_name should be optional' do
@options.delete(:cloud_service_name)
expect { subject.add_role(@options) }.to raise_error(
ArgumentError,
/required: cloud_service_name/
)
end
end
describe '(deployment_name)' do
it 'deployment_name should be optional' do
@options.delete(:deployment_name)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(puppet_master_ip)' do
it 'puppet_master_ip should be optional' do
@options.delete(:puppet_master_ip)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(storage_account_name)' do
it 'storage_account_name should be optional' do
@options.delete(:storage_account_name)
expect { subject.add_role(@options) }.to_not raise_error
end
end
end
describe '(Password)' do
describe '(password prompt for windows)' do
before :each do
image.os_type = 'Windows'
image_service.any_instance.expects(
:list_virtual_machine_images).returns([image]).at_least(0)
@count = 0
@prompt_msg = nil
HighLine.any_instance.stubs(:ask).with(anything) do |msg|
@prompt_msg = msg
@count += 1
end
end
it 'should ask for password if password options is empty' do
@options.delete(:password)
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(1)
expect(@prompt_msg).to match(/PASSWORD?/)
end
it 'should prompt for password if password is weak.' do
@options[:password] = '<PASSWORD>'
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(1)
expect(@prompt_msg).to match(/PASSWORD?/)
end
it 'should not prompt for password if password is complex.' do
@options[:password] = '<PASSWORD>'
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(0)
end
end
describe 'password prompt for linux' do
before :each do
image.os_type = 'Linux'
image_service.any_instance.expects(
:list_virtual_machine_images).returns([image]).at_least(0)
@options.delete(:puppet_master_ip)
@count = 0
@prompt_msg = nil
HighLine.any_instance.stubs(:ask).with(anything) do |msg|
@prompt_msg = msg
@count += 1
# TODO: Fix How to input into IOStream
@count == 1 ? 'y' : 'ComplexPassword123'
end
end
it 'should prompt enable password message if options password is empty \
and ssh certificate is provided.' do
@options.delete(:password)
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(1)
expect(@prompt_msg).to match(
/Do you want to enable password authentication/
)
end
it 'should ask for password if password and ssh certificate options is empty' do
@options.delete(:password)
@options.delete(:certificate_file)
@options.delete(:private_key_file)
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(1)
expect(@prompt_msg).to match(/PASSWORD?/)
end
it 'should prompt for password if password is weak and ssh certificate is given.' do
@options.delete(:certificate_file)
@options.delete(:private_key_file)
@options[:password] = '<PASSWORD>'
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(1)
expect(@prompt_msg).to match(/PASSWORD?/)
end
it 'should not prompt for password if password is complex.' do
@options[:password] = '<PASSWORD>'
@options.delete(:certificate_file)
@options.delete(:private_key_file)
expect { subject.add_role(@options) }.to_not raise_error
expect(@count).to eq(0)
end
end
end
describe '(winrm_http_port)' do
it 'winrm_http_port should be optional' do
@options.delete(:winrm_http_port)
expect { subject.add_role(@options) }.to_not raise_error
end
end
describe '(winrm_https_port)' do
it 'winrm_https_port should be optional' do
@options.delete(:winrm_https_port)
expect { subject.add_role(@options) }.to_not raise_error
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_vm/delete_endpoint.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_vm, '1.0.0' do
action :delete_endpoint do
summary 'Delete endpoint of virtual machine.'
description <<-'EOT'
Delete endpoint of windows azure node instances.
EOT
Puppet::VirtualMachine.delete_endpoint_options(self)
when_invoked do |options|
Puppet::VirtualMachine.initialize_env_variable(options)
virtual_machine_service = Azure::VirtualMachineManagementService.new
virtual_machine_service.delete_endpoint(
options[:vm_name],
options[:cloud_service_name],
options[:endpoint_name]
)
nil
end
returns 'NONE'
examples <<-'EOT'
$ puppet azure_vm delete_endpoint --endpoint-name endpointname \
--management-certificate path-to-azure-certificate --vm-name vmname \
--cloud-service-name cloudname
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_affinitygroup/update.rb
|
<reponame>Bhaskers-Blu-Org2/azure-puppet
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_affinitygroup, '1.0.0' do
action :update do
summary 'Update affinity group.'
description <<-'EOT'
The update action updates a affinity group.
EOT
Puppet::AffinityGroup.add_update_options(self)
when_invoked do |options|
Puppet::AffinityGroup.initialize_env_variable(options)
affinity_group_service = Azure::BaseManagementService.new
others = { description: options[:description] }
begin
affinity_group_service.update_affinity_group(
options[:affinity_group_name],
options[:label],
others
)
rescue => e
puts e.message
end
end
examples <<-'EOT'
$ puppet azure_affinitygroup update --description 'Some Description'
--management-certificate path-to-azure-certificate \
--azure-subscription-id YOUR-SUBSCRIPTION-ID --label aglabel \
--affinity-group-name agname
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_affinitygroup/update_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'spec_helper'
describe Puppet::Face[:azure_affinitygroup, :current] do
let(:base_service) { Azure::BaseManagementService }
before :each do
mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem')
@options = {
management_certificate: mgmtcertfile,
management_endpoint: 'management.core.windows.net',
azure_subscription_id: 'Subscription-id',
affinity_group_name: 'ag-name',
label: 'Label',
description: 'Affinity group Description'
}
Azure.configure do |config|
config.management_certificate = @options[:management_certificate]
config.subscription_id = @options[:azure_subscription_id]
end
end
describe 'option validation' do
describe 'valid options' do
before :each do
base_service.any_instance.stubs(:update_affinity_group).with(
any_parameters
)
end
it 'should not raise any exception' do
expect { subject.update(@options) }.to_not raise_error
end
it_behaves_like 'validate authentication credential', :update
end
describe '(affinity_group_name)' do
it 'should validate the affinity group name' do
@options.delete(:affinity_group_name)
expect { subject.update(@options) }.to raise_error(
ArgumentError,
/required: affinity_group_name/
)
end
end
describe '(label)' do
it 'should validate the label' do
@options.delete(:label)
expect { subject.update(@options) }.to raise_error(
ArgumentError,
/required: label/
)
end
end
end
describe 'optional parameter validation' do
before :each do
base_service.any_instance.stubs(:update_affinity_group).with(
any_parameters
)
end
describe '(description)' do
it 'description should be optional' do
@options.delete(:description)
expect { subject.update(@options) }.to_not raise_error
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/core/utility.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
require 'highline/import'
module Puppet
module Core
module Loggerx
class << self
def info(msg)
puts msg.bold.white
end
def error_with_exit(msg)
puts msg.bold.red
fail msg.bold.red
end
def warn(msg)
fail msg.yellow
end
def error(msg)
fail msg.bold.red
end
def exception_message(msg)
print msg.bold.red
fail msg.bold.red
end
def success(msg)
msg_with_new_line = msg + "\n"
print msg_with_new_line.green
end
end
end
module Utility
def random_string(str = 'azure', no_of_char = 5)
str + (0...no_of_char).map { ('a'..'z').to_a[rand(26)] }.join
end
def validate_file(filepath, filename, extensions)
fail ArgumentError, "#{filename} file is required" if filepath.empty?
unless test 'f', filepath
fail ArgumentError, "Could not find file '#{filepath}'"
end
unless test 'r', filepath
fail ArgumentError, "Could not read from file '#{filepath}'"
end
ext_msg = extensions.map { |ele| '.' + ele }.join(' or ')
if filepath !~ /(#{extensions.join('|')})$/
fail "#{filename} expects a #{ext_msg} file."
end
end
def ask_for_password(options, os_type)
regex = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}/
password = options[:password]
return options if !password.nil? && !password.match(regex).nil?
password_required = 'y'
if options[:private_key_file] && options[:certificate_file] && os_type == 'Linux'
password_required = ask("\nDo you want to enable password authentication (y/n)? ") do
|pass| pass.validate = /^y{1}$|^n{1}$/
end
end
if password_required == 'y' || os_type == 'Windows'
puts 'The supplied password must be 6-72 characters long and meet password complexity requirements.'
puts 'Require atleast 1 captial letter and digit.'
options[:password] = ask("\nPASSWORD? ") { |pass| pass.echo = '*'; pass.validate = regex }
end
options
end
def wait_for_connection(ipaddress, port)
Loggerx.info "Waiting for sshd on #{ipaddress}:#{port}"
print('# ') until test_ssh_connecton(ipaddress, port) do
sleep 10
end
end
def test_ssh_connecton(fqdn, sshport)
tcp_socket = TCPSocket.new(fqdn, sshport)
readable = IO.select([tcp_socket], nil, nil, 5)
if readable
Loggerx.info("Node #{fqdn} is accepting ssh connections.")
yield
true
else
false
end
rescue SocketError
sleep 2
false
rescue Errno::ETIMEDOUT
false
rescue Errno::EPERM
false
rescue Errno::ECONNREFUSED
sleep 2
false
rescue Errno::EHOSTUNREACH
sleep 2
false
ensure
tcp_socket && tcp_socket.close
end
def test_winrm_connecton(fqdn, port)
Loggerx.info "Waiting for winrm on #{fqdn}:#{port}"
tcp_socket = TCPSocket.new(fqdn, port)
Loggerx.success 'done'
return true
rescue SocketError
raise 'Socket Error'
rescue Errno::ETIMEDOUT
fail 'Connection timeout'
rescue Errno::EPERM
fail 'Operation not permitted'
rescue Errno::ECONNREFUSED
fail 'Connection Refused'
rescue Errno::EHOSTUNREACH
fail 'Not Reachable'
rescue Errno::ENETUNREACH
fail 'Not Reachable'
ensure
tcp_socket && tcp_socket.close
end
def wget_script
wget_content = <<-WGET
URL = WScript.Arguments(0)
saveTo = WScript.Arguments(1)
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.open "GET", URL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(saveTo) Then objFSO.DeleteFile saveTo
Set objFSO = Nothing
objADOStream.SaveToFile saveTo
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
WScript.Quit
WGET
wget_content
end
end
end
end
class String
def fix(size = 18, padstr = ' ')
self[0...size].ljust(size, padstr)
end
{ reset: 0,
bold: 1,
dark: 2,
underline: 4,
blink: 5,
orange: 6,
negative: 7,
black: 30,
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35,
cyan: 36,
white: 37,
}.each do |key, value|
define_method key do
"\e[#{value}m" + self + "\e[0m"
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/face/azure_storage/update.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
# encoding: UTF-8
Puppet::Face.define :azure_storage, '1.0.0' do
action :update do
summary 'Update storage service.'
description 'The update action updates a storage account.'
Puppet::StorageAccount.add_create_options(self)
when_invoked do |options|
Puppet::StorageAccount.initialize_env_variable(options)
storage_account = Azure::StorageManagementService.new
others = {
description: options[:description],
label: options[:label],
affinity_group_name: options[:affinity_group_name],
location: options[:location],
extended_properties: options[:extended_properties]
}
storage_account.update_storage_account(
options[:storage_account_name],
others
)
nil
end
examples <<-'EOT'
$ puppet azure_storage update --label aglabel \
--azure-subscription-id YOUR-SUBSCRIPTION-ID --location 'West Us' \
--affinity-group-name agname --description 'Some Description' \
--management-certificate path-to-azure-certificate
EOT
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
spec/unit/puppet/face/azure_servicebus/delete_topic_spec.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
require 'spec_helper'
describe Puppet::Face[:azure_servicebus, :current] do
let(:service_bus) { Azure::ServiceBusService }
before :each do
@options = {
sb_namespace: 'busname',
sb_access_key: '<KEY>
topic_name: 'topic'
}
Azure.configure do |config|
config.sb_namespace = @options[:sb_namespace]
config.sb_access_key = @options[:sb_access_key]
end
service_bus.any_instance.stubs(:delete_topic).with(any_parameters)
end
describe 'option validation' do
describe 'valid options' do
it 'should not raise any exception' do
expect { subject.delete_topic(@options) }.to_not raise_error
end
end
describe '(topic_name)' do
it 'should validate topic name' do
@options.delete(:topic_name)
expect { subject.delete_topic(@options) }.to raise_error(
ArgumentError,
/required: topic_name/
)
end
end
describe '(sb_access_key)' do
it 'should validate service bus access key' do
@options.delete(:sb_access_key)
expect { subject.delete_topic(@options) }.to raise_error(
ArgumentError,
/required: sb_access_key/
)
end
end
describe '(sb_namespace)' do
it 'should validate service bus namespace' do
@options.delete(:sb_namespace)
expect { subject.delete_topic(@options) }.to raise_error(
ArgumentError,
/required: sb_namespace/
)
end
end
end
end
|
Bhaskers-Blu-Org2/azure-puppet
|
lib/puppet/service_bus.rb
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies, Inc.
# All Rights Reserved. Licensed under the Apache 2.0 License.
#--------------------------------------------------------------------------
module Puppet::ServiceBus
class << self
def initialize_env_variable(options)
ENV['AZURE_SERVICEBUS_NAMESPACE'] = options[:sb_namespace]
ENV['AZURE_SERVICEBUS_ACCESS_KEY'] = options[:sb_access_key]
ENV["AZURE_STORAGE_ACCOUNT"] = options[:storage_account_name]
ENV["AZURE_STORAGE_ACCESS_KEY"] = options[:storage_access_key]
gem "azure", '=0.6.4'
require 'azure'
end
def views(name)
File.join(File.dirname(__FILE__), 'face/azure_servicebus/views', name)
end
def add_default_options(action)
add_sb_namespace_option(action)
add_sb_access_key_option(action)
end
def add_queue_default_options(action)
add_storage_account_name_option(action)
add_storage_access_key_option(action)
end
def add_servicebus_queue_options(action)
add_default_options(action)
add_queue_name_option(action)
end
def add_servicebus_topic_options(action)
add_default_options(action)
add_topic_name_option(action)
end
def add_create_queue_options(action)
add_queue_default_options(action)
add_queue_name_option(action)
end
def add_create_message_options(action)
add_queue_default_options(action)
add_queue_name_option(action)
add_queue_message_option(action)
end
def add_sb_namespace_option(action)
action.option '--sb-namespace=' do
summary 'The azure service bus namespace.'
description 'azure service bus namespace.'
required
end
end
def add_sb_access_key_option(action)
action.option '--sb-access-key=' do
summary 'The azure service bus access key.'
description 'The azure service bus access key.'
required
end
end
def add_queue_name_option(action)
action.option '--queue-name=' do
summary 'Name of azure queue.'
description 'Name of azure queue.'
required
end
end
def add_topic_name_option(action)
action.option '--topic-name=' do
summary 'Name of azure topic.'
description 'Name of azure topic.'
required
end
end
def add_queue_message_option(action)
action.option '--queue-message=' do
summary 'Queue message'
required
end
end
def add_storage_account_name_option(action)
action.option '--storage-account-name=' do
summary 'The storage account name of Windows Azure portal.'
description 'The storage account name of Windows Azure portal.'
required
end
end
def add_storage_access_key_option(action)
action.option '--storage-access-key=' do
summary 'The access key of storage account.'
description 'The access key of storage account.'
required
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.