repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
totosimo/parentFriend
|
config/routes.rb
|
Rails.application.routes.draw do
devise_for :users, :controllers => { :registrations => :registrations }
root to: 'pages#home'
get '/main', to: 'pages#main'
get '/meet', to: 'pages#meet'
post '/meet', to: 'pages#update_location'
resources :users, only: [:index, :show]
resources :chatrooms, only: [:index, :show, :create] do
resources :messages, only: [:create]
end
resources :events do
resources :bookings, only: [:create]
end
resources :bookings, only: [:index, :destroy]
end
|
totosimo/parentFriend
|
app/controllers/messages_controller.rb
|
class MessagesController < ApplicationController
def create
@chatroom = Chatroom.find(params[:chatroom_id])
@message = Message.new(message_params)
@message.chatroom = @chatroom
@message.user = current_user
authorize @message
if @message.save
ChatroomChannel.broadcast_to(
@chatroom,
{
html: render_to_string(partial: "message", locals: { message: @message }),
message_user_id: @message.user.id,
message_id: @message.id,
message_user_name: @message.user.first_name
}
)
# redirect_to chatroom_path(@chatroom, anchor: "message-#{@message.id}")
else
render "chatrooms/show"
# comment
end
end
private
def message_params
params.require(:message).permit(:content)
end
end
|
totosimo/parentFriend
|
app/controllers/events_controller.rb
|
class EventsController < ApplicationController
def index
@events = policy_scope(Event)
@markers = @events.geocoded.map do |event|
{
lat: event.latitude,
lng: event.longitude,
infoWindow: render_to_string(partial: "info_window", locals: { event: event }),
image_url: helpers.asset_url('event.webp')
}
end
end
def show
@event = Event.find(params[:id])
@bkgs = @event.bookings
authorize @event
@found = false
@bkgs.each do |booking|
@found = true if booking.user == current_user
end
end
def new
@event = Event.new
authorize @event
end
def create
@event = Event.new(event_params)
@booking = Booking.new
@event.user = current_user
authorize @event
authorize @booking
@booking.event = @event
@booking.user = current_user
if @event.save && @booking.save
redirect_to event_path(@event)
else
render :new
end
end
def edit
@event = Event.find(params[:id])
authorize @event
end
def destroy
@event = Event.find(params[:id])
@event.destroy
redirect_to events_path
authorize @event
end
def update
@event = Event.find(params[:id])
authorize @event
if @event.update(event_params)
redirect_to event_path(@event)
else
render :edit
end
end
private
def event_params
params.require(:event).permit(:name, :description, :date_time_start, :date_time_end, :address, :event_type, :photo)
end
end
|
totosimo/parentFriend
|
app/controllers/bookings_controller.rb
|
<gh_stars>0
class BookingsController < ApplicationController
before_action :set_booking, only: [:destroy]
def index
@bookings = policy_scope(Booking).order(created_at: :desc)
end
def destroy
authorize @booking
@booking.destroy
redirect_to bookings_path
end
def create
@event = Event.find(params[:event_id])
@booking = Booking.new
authorize @booking
if !event_booked?(@event)
@booking.user = current_user
@booking.event = @event
if @booking.save!
redirect_to event_path(@event), notice: "Your booking has been successfully created"
else
redirect_to event_path(@event), notice: "Booking aborted, the event has been cancelled by the host"
end
else
redirect_to event_path(@event), notice: "You are already attending this event!"
end
end
private
def set_booking
@booking = Booking.where(user: current_user).find(params[:id])
end
def event_booked?(ev)
found = false
ev.bookings.each do |booking|
found = true if booking.user == current_user
end
return found
end
end
|
totosimo/parentFriend
|
app/controllers/chatrooms_controller.rb
|
class ChatroomsController < ApplicationController
def index
@chatrooms = policy_scope(Chatroom)
my_chatrooms = current_user.chatrooms
other_users = my_chatrooms.map { |chat| chat.users.reject { |user| user.eql?(current_user) } }
@my_chat_users = []
my_chatrooms.each_with_index do |chat, i|
@my_chat_users << { chat: chat, other_u: other_users[i][0] }
end
@my_chat_users
end
def show
@chatroom = Chatroom.find(params[:id])
@message = Message.new
authorize @chatroom
chat_user_ids = @chatroom.user_chatrooms.map { |record| record.user_id }
@user = User.find(chat_user_ids.reject { |id| id.eql?(current_user.id) })[0]
# raise
end
def create
cu = current_user
u = User.find(params[:user_id])
s_one = "#{u.id}-#{cu.id}"
s_two = "#{cu.id}-#{u.id}"
@chatroom = Chatroom.where("name like ? OR name like ?", s_one, s_two).first
if @chatroom.present?
#check for existing chatroom and redirect to it
authorize @chatroom
redirect_to chatroom_path(@chatroom)
else
#else create chatroom
@chatroom = Chatroom.new(name: "#{cu.id}-#{u.id}")
authorize @chatroom
@user_chatroom = UserChatroom.new(user: cu, chatroom: @chatroom)
@user_chatroom_two = UserChatroom.new(user: u, chatroom: @chatroom)
if @chatroom.save && @user_chatroom.save && @user_chatroom_two.save
redirect_to chatroom_path(@chatroom)
else
render 'users/show'
end
end
end
end
|
totosimo/parentFriend
|
app/models/user_chatroom.rb
|
<reponame>totosimo/parentFriend
class UserChatroom < ApplicationRecord
belongs_to :user
belongs_to :chatroom
end
|
totosimo/parentFriend
|
app/models/chatroom.rb
|
<filename>app/models/chatroom.rb
class Chatroom < ApplicationRecord
has_many :messages
has_many :user_chatrooms
has_many :users, through: :user_chatrooms
end
|
totosimo/parentFriend
|
db/migrate/20210303152902_create_user_chatrooms.rb
|
class CreateUserChatrooms < ActiveRecord::Migration[6.0]
def change
create_table :user_chatrooms do |t|
t.references :user, null: false, foreign_key: true
t.references :chatroom, null: false, foreign_key: true
t.timestamps
end
end
end
|
agelwarg/PDFKit
|
spec/source_spec.rb
|
<reponame>agelwarg/PDFKit
require 'spec_helper'
describe PDFKit::Source do
describe "#url?" do
it "should return true if passed a url like string" do
source = PDFKit::Source.new('http://google.com')
source.should be_url
end
it "should return false if passed a file" do
source = PDFKit::Source.new(File.new(__FILE__))
source.should_not be_url
end
it "should return false if passed HTML" do
source = PDFKit::Source.new('<blink>Oh Hai!</blink>')
source.should_not be_url
end
it "should return false if passed HTML with embedded urls at the beginning of a line" do
source = PDFKit::Source.new("<blink>Oh Hai!</blink>\nhttp://www.google.com")
source.should_not be_url
end
end
describe "#file?" do
it "should return true if passed a file" do
source = PDFKit::Source.new(File.new(__FILE__))
source.should be_file
end
it "should return false if passed a url like string" do
source = PDFKit::Source.new('http://google.com')
source.should_not be_file
end
it "should return false if passed HTML" do
source = PDFKit::Source.new('<blink>Oh Hai!</blink>')
source.should_not be_file
end
end
describe "#html?" do
it "should return true if passed HTML" do
source = PDFKit::Source.new('<blink>Oh Hai!</blink>')
source.should be_html
end
it "should return false if passed a file" do
source = PDFKit::Source.new(File.new(__FILE__))
source.should_not be_html
end
it "should return false if passed a url like string" do
source = PDFKit::Source.new('http://google.com')
source.should_not be_html
end
end
describe "#to_s" do
it "should return the HTML if passed HTML" do
source = PDFKit::Source.new('<blink>Oh Hai!</blink>')
source.to_s.should == '<blink>Oh Hai!</blink>'
end
it "should return a path if passed a file" do
source = PDFKit::Source.new(File.new(__FILE__))
source.to_s.should == __FILE__
end
it "should return the url if passed a url like string" do
source = PDFKit::Source.new('http://google.com')
source.to_s.should == 'http://google.com'
end
end
end
|
hho2002/kinoko
|
plugins/glib/src/gcore/process.rb
|
<reponame>hho2002/kinoko
#!/usr/bin/ruby
require 'fileutils'
$path = if ARGV.size > 0 then ARGV[0] else Dir.pwd end
files = []
headers = nil
if File.file?($path)
headers = [$path]
$path = $path.gsub /\/[^\/]+$/, ''
else
headers = Dir["#{$path}/**/*.h"]
end
class HMethod
attr_accessor :name,
:params,
:labels,
:all_labels
def initialize name
@name = name
end
end
class HProperty
attr_accessor :name,
:getter,
:setter,
:labels,
:all_labels
def initialize name
@name = name
end
end
class HClass
attr_accessor :name,
:namespace,
:real_namespace,
:template,
:header,
:labels,
:all_labels,
:active,
:methods,
:properties,
:has_onload,
:onload_pre_offset,
:onload_begin,
:onload_end,
:onload_new_line,
:onload_super
def initialize name
@name = name
@active = true
@methods = {}
@properties = {}
@has_onload = false
@onload_new_line = false
end
end
$tmp_classes = {}
$include_classes = {}
$classes_index = {}
$untouched_classes = {}
$current_header = ''
$current_namespace = nil
$current_class = nil
$class_stack = []
$labels_stack = {}
$current_labels = nil
def p_labels labels
str = 'map<string, Variant>{'
labels.each do |key, value|
str << "{#{key}, #{value}},"
end
str << '}'
end
def push_class cls
fullname = "#{cls.namespace}::#{cls.name}"
unless $include_classes.has_key?(fullname)
cls.header = $current_header
$include_classes[fullname] = cls
$classes_index[cls.name] = fullname
end
end
def check_namespace(args)
if args[:line][/^[\s\t]*namespace[\s\t]*(\w+)/]
yield $1
end
end
def check_class_begin(args)
if args[:line][/CLASS_BEGIN(\w*)\(([^\)]+)/]
type = $1
res = []
res_cls = nil
$2.gsub /[\w:]+/ do |w|
res << w
end
if res.size > 0 and res[0] != 'NAME'
is_tem = false
if args[:index] > 0
l = args[:lines][args[:index] - 1]
is_tem = true if l[/^[\s\t]*template/]
end
cls_ns = nil
cls_ns = $current_namespace if type[/N/]
real_ns = $current_namespace
if is_tem
tp_cls = $tmp_classes[res[0]]
unless tp_cls
tp_cls = HClass.new res[0]
tp_cls.namespace = cls_ns
str = ''
$class_stack.each{|clz| str << "::#{clz.name}"}
tp_cls.real_namespace = "#{real_ns}#{str}"
$tmp_classes[res[0]] = tp_cls
end
if $untouched_classes.has_key?(res[0])
tp_cls.template = $untouched_classes[res[0]]
$untouched_classes.delete res[0]
push_class tp_cls
end
res_cls = tp_cls
else
cls = HClass.new res[0]
cls.namespace = cls_ns
str = ''
$class_stack.each{|clz| str << "::#{clz.name}"}
cls.real_namespace = "#{real_ns}#{str}"
push_class cls
res_cls = cls
end
if type[/T/]
tmp = res[3..-1]
if $tmp_classes.has_key? res[1]
cls = $tmp_classes[res[1]]
cls.template = tmp
#push_class cls
else
$untouched_classes[res[1]] = tmp
end
res_cls.onload_super = "#{res[1]}<#{tmp}>"
elsif type[/0/]
res_cls.onload_super = 'gc::Base'
else
res_cls.onload_super = res[1]
end
yield res[0], res_cls
end
end
end
def check_class_end args
return unless $current_class
if args[:line][/CLASS_END/]
yield args[:line].index /CLASS_END/
end
end
def check_label args
if args[:line][/LABEL\(([^\)]+)/]
arr = $1.split ','
if arr.size == 2
yield arr
end
end
end
def check_labels args
line = args[:line].strip
if line[/LABELS\(([^$]+)/]
str = $1[0...-1]
yield str
end
end
def check_method args
return unless $current_class
if args[:line][/ METHOD /] and str = args[:line][/(\w+)\(([^\)]*)/]
yield $1, $2
end
end
def check_property args
return unless $current_class
if args[:line][/[\t ^]PROPERTY\(([^\)]+)/]
arr = $1.split ','
yield arr[0].strip, arr[1].strip, arr[2].strip
end
end
def check_on_load_begin args
return unless $current_class
if args[:line][/ON_LOADED_BEGIN\(([^\)]+)/]
arr = $1.split ','
yield args[:line].index(/ON_LOADED_BEGIN\(([^\)]+)/), arr
end
end
def check_on_load_end args
return unless $current_class
if args[:line][/ON_LOADED_END/]
yield args[:line].index(/ON_LOADED_END/) + 'ON_LOADED_END'.size
end
end
CLASS_LABELS_TEMPLATE = 'cls->setLabels({{labels}})'
ADD_METHOD_TEMPLATE = %q[ADD_METHOD(cls, {{class}}, {{method}}{{labels}})]
ADD_PROPERTY_TEMPLATE = %q[ADD_PROPERTY(cls, "{{name}}", {{getter}}, {{setter}}{{labels}})]
ON_LOAD_BEGIN = 'ON_LOADED_BEGIN(cls, {{super}})'
ON_LOAD_END = 'ON_LOADED_END'
def check c, a, b
if c
a
else
b
end
end
def process_labels str, object, dot = true
if object.all_labels
str.gsub! '{{labels}}', "#{check dot, ', ', ''}#{object.all_labels}"
elsif object.labels.size > 0
str.gsub! '{{labels}}', "#{check dot, ', ', ''}#{p_labels object.labels}"
else
str.gsub! '{{labels}}', ''
end
end
def process_header header, content, classes
changed = false
classes.sort{|a,b| classes.index(b) <=> classes.index(a)}.each do |cls|
if cls.methods.size > 0
changed = true
added_methods = []
properties_strs = []
cls.properties.each do |key, value|
getter = cls.methods[value.getter]
setter = cls.methods[value.setter]
getter_str = ''
setter_str = ''
if getter
getter_str = ADD_METHOD_TEMPLATE
.gsub('{{class}}', cls.name)
.gsub('{{method}}', getter.name)
process_labels getter_str, getter
else
getter_str = 'NULL'
#raise "Method not found: #{value.getter}"
end
if setter
setter_str = ADD_METHOD_TEMPLATE
.gsub('{{class}}', cls.name)
.gsub('{{method}}', setter.name)
process_labels setter_str, setter
else
setter_str = 'NULL'
#raise "Method not found: #{value.setter}" unless setter
end
added_methods << getter.name if getter
added_methods << setter.name if setter
pro_str = ADD_PROPERTY_TEMPLATE
.gsub('{{name}}', value.name)
.gsub('{{getter}}', getter_str)
.gsub('{{setter}}', setter_str)
process_labels pro_str, value
properties_strs << pro_str
end
method_strs = []
cls.methods.each do |key, value|
unless added_methods.index key
method = value
method_str = ADD_METHOD_TEMPLATE
.gsub('{{class}}', cls.name)
.gsub('{{method}}', method.name)
process_labels method_str, method
method_strs << method_str
end
end
space = ' ' * cls.onload_pre_offset
str = ''
unless cls.has_onload
space << ' ' * 4
str << "protected:\n#{space}"
end
str << ON_LOAD_BEGIN.gsub('{{super}}', cls.onload_super)
str << "\n"
if cls.labels.size > 0 or cls.all_labels
str << space
str << ' ' * 4
lbs = CLASS_LABELS_TEMPLATE.clone
process_labels(lbs, cls, false)
str << lbs
str << ";\n"
end
properties_strs.each do |s|
str << space
str << ' ' * 4
str << s
str << ";\n"
end
method_strs.each do |s|
str << space
str << ' ' * 4
str << s
str << ";\n"
end
str << space
str << ON_LOAD_END
str << "\n" if cls.onload_new_line
unless cls.has_onload
str << ' ' * cls.onload_pre_offset
str << content[cls.onload_end]
end
content[cls.onload_begin..cls.onload_end] = str
end
end
if changed
target_path = header.gsub "#{$path}/", "#{$path}/tmp/"
tmp_path = target_path.gsub /[^$\/]+$/, ''
FileUtils.mkpath tmp_path
p $path
p "Move: #{header} to #{target_path}"
FileUtils.move header, target_path, force: true
p "Write new: #{header}"
File.open header, 'w' do |f|
f.write content
end
end
end
headers.each do |header|
$current_header = header.gsub "#{$path}/", ''
content = ''
current_classes = []
next if header["#{$path}/tmp/"]
p "Start process #{header}:"
File.open header, 'r' do |f|
$current_namespace = nil
$current_class = nil
$labels_stack = {}
$current_labels = nil
$class_stack = []
content = f.read
length = content.size
index = 0
lines = []
line = ''
line_start = 0
length.times do |offset|
ch = content[offset]
if ch == "\n"
lines << line
params = {line: line, lines: lines, index: index}
check_namespace params do |res|
p "--> Enter namespace: #{res}"
$current_namespace = res
end
check_class_begin params do |res, cls|
p "--> Class begin: #{res}"
$class_stack << cls
$current_class = cls
if cls.active
cls.all_labels = $current_labels
cls.labels = $labels_stack
end
$labels_stack = {}
$current_labels = nil
end
check_class_end params do |off|
p "--> Class end: #{off}"
if $current_class
$class_stack.pop if $class_stack.size >= 1
if $current_class.active
current_classes << $current_class
end
$current_class.active = false
unless $current_class.has_onload
$current_class.onload_begin = $current_class.onload_end = line_start + off
$current_class.onload_pre_offset = off
$current_class.onload_new_line = true
end
if $class_stack.size > 0
$current_class = $class_stack.last
end
end
end
check_label params do |res|
p "--> A label: #{res[0].strip} => #{res[1].strip}"
$labels_stack[res[0].strip] = res[1].strip
end
check_labels params do |res|
p "--> Labels: #{res}"
$current_labels = res
end
check_method params do |name, ps|
p "--> A method: #{name}"
if $current_class && $current_class.active
method = HMethod.new name
method.params = ps
method.all_labels = $current_labels
method.labels = $labels_stack
$labels_stack = {}
$current_labels = nil
if $current_class.active
$current_class.methods[name] = method
end
end
end
check_property params do |name, getter, setter|
p "--> A property: #{name}"
property = HProperty.new name
property.setter = setter
property.getter = getter
property.all_labels = $current_labels
property.labels = $labels_stack
$labels_stack = {}
$current_labels = nil
if $current_class.active
$current_class.properties[name] = property
end
end
check_on_load_begin params do |off, ps|
p "--> On load method: #{off}"
if $current_class.active
$current_class.onload_begin = line_start + off
$current_class.onload_pre_offset = off
end
end
check_on_load_end params do |off|
if $current_class.active
$current_class.onload_end = line_start + off - 1
end
$current_class.has_onload = true
end
line_start = offset + 1
index += 1
line = ''
else
line << ch
end
end
end
process_header header, content, current_classes
end
LOAD_CLASSES_TEMPLATE = %q[
{{header}}
using namespace gc;
void ClassDB::loadClasses() {
//class_loaders[h("gc::Base")] = (void*)&gc::Base::getClass;
{{loaders}}
}
]
def process_load_classes
headers = []
loaders = []
$include_classes.each do |key, cls|
headers << "#include \"#{cls.header}\""
loader = " "
loader << "class_loaders[h(\"#{if cls.namespace then "#{cls.namespace}::" else '' end}#{cls.name}\")]"
loader << " = (void*)&#{if cls.real_namespace then "#{cls.real_namespace}::" else '' end}#{cls.name}"
if cls.template and cls.template.size > 0
loader << '<'
narr = cls.template.map do |t|
if $classes_index[t]
$classes_index[t]
else
t
end
end
loader << narr * ','
loader << '>'
end
loader << '::getClass;'
loaders << loader
end
target_path = "#{$path}/Classes.cpp"
File.delete target_path if File.exist? target_path
File.open target_path, 'w' do |f|
content = LOAD_CLASSES_TEMPLATE.gsub '{{header}}', headers.uniq * "\n"
content = content.gsub '{{loaders}}', loaders * "\n"
f.write content
end
end
if headers.size > 1
process_load_classes
end
|
hho2002/kinoko
|
plugins/glib/env/ruby/gs/data.rb
|
require 'object'
module GS
class Data < GS::Object
native "gc::Data"
end
class FileData < GS::Object
native "gc::FileData"
end
end
|
hho2002/kinoko
|
plugins/glib/env/ruby/gs/callback.rb
|
require 'object'
module GS
class Callback < GS::Object
native "gc::Callback"
def initialize &block
super
@block = block
end
def _invoke args
@block.call *args if @block
end
def inv *argv
invoke argv
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/ecs.rb
|
require "thor"
require "colorize"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Ecs < Thor
desc "list_clusters", "list clustes"
def list_clusters()
clusters = AwsPocketknife::Ecs.list_clusters
headers = ["name", "status", "services", "containers_count","running_tasks_count", "pending_tasks_count",]
data = []
if clusters.nil?
puts "No clusters found. Check your region"
else
#AwsPocketknife::Ecs.nice_print(object: clusters)
clusters.each do |cluster|
info = cluster[:info]
data << [cluster[:name], info.status, info.active_services_count,
info.registered_container_instances_count, info.running_tasks_count, info.pending_tasks_count
]
end
AwsPocketknife::Ecs.pretty_table(headers: headers, data: data)
end
end
desc "list_services CLUSTER_NAME", "list services for a given cluster"
def list_services(cluster)
services = AwsPocketknife::Ecs.list_services cluster: cluster
headers = ["name", "status", "desired_count","running_count",
"pending_count", "task_definition", "maximum_percent", "minimum_healthy_percent", "cpu (units)", "mem (MiB)", "mem_reservation (MiB)"]
data = []
if services.nil?
puts "No service found"
else
mem_total = 0
mem_res_total = 0
cpu_total = 0
services.each do |service|
info = service[:info]
task_def = service[:task_definition]
data << [service[:name], info.status, info.desired_count,
info.running_count, info.pending_count, info.task_definition.split('/')[1],
info.deployment_configuration.maximum_percent, info.deployment_configuration.minimum_healthy_percent,
task_def.cpu, task_def.memory, task_def.memory_reservation
]
cpu_total = cpu_total + task_def.cpu unless task_def.cpu.nil?
mem_total = mem_total + task_def.memory unless task_def.memory.nil?
mem_res_total = (mem_res_total + task_def.memory_reservation) unless task_def.memory_reservation.nil?
end
puts ""
puts "Memory is the hard limit (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed."
puts "Memory reservation is the soft limit (in MiB) of memory to reserve for the container. When system memory is under contention, Docker attempts to keep the container memory to this soft limit"
puts ""
AwsPocketknife::Ecs.pretty_table(headers: headers, data: data)
puts ""
puts "CPU TOTAL: #{cpu_total} Units"
puts "MEM TOTAL: #{mem_total} MiB"
puts "MEM RES TOTAL: #{mem_res_total} MiB"
puts ""
end
end
desc "desc_service CLUSTER_NAME, SERVICE_NAME", "describe service for a given cluster"
def desc_service(cluster, service_name)
service = AwsPocketknife::Ecs.describe_services cluster: cluster, name: service_name
if service.nil?
puts "service #{service_name} not found"
else
AwsPocketknife::Ecs.nice_print(object: service.to_h)
end
end
desc "clone_service CLUSTER_NAME, SERVICE_NAME", "creates a copy of an existing service"
def clone_service(cluster, service_name)
resp = AwsPocketknife::Ecs.clone_service cluster: cluster, name: service_name
puts ""
puts "Response: "
puts ""
AwsPocketknife::Ecs.nice_print(object: resp.to_h)
end
# container instance
desc "drain_instances CLUSTER_NAME, CONTAINERS", "drains containers associated to the ecs cluster. CONTAINERS can a be a string delimited list"
def drain_instances(cluster, names)
resp = AwsPocketknife::Ecs.drain_instances cluster: cluster, names: names
puts ""
puts "Response: "
puts ""
AwsPocketknife::Ecs.nice_print(object: resp.to_a)
end
# container instance
desc "list_instance_tasks CLUSTER_NAME, CONTAINER_NAME", "list tasks running in container (instance)"
def list_instance_tasks(cluster, name)
resp = AwsPocketknife::Ecs.list_container_tasks cluster: cluster, container_name: name
headers = ["name", "started_at", "stopped_at", "last_status", "task"]
data = []
if resp.nil?
puts "No tasks found"
else
resp.tasks.each do |task|
data << [task.task_definition_arn.split('/')[1], task.started_at, task.stopped_at, task.last_status, task.task_arn.split('/')[1]]
end
AwsPocketknife::Ecs.pretty_table(headers: headers, data: data)
end
end
desc "list_instances CLUSTER_NAME", "list instances for a given cluster"
def list_instances(cluster)
instances = AwsPocketknife::Ecs.list_container_instances cluster: cluster
headers = ["name", "ec2_instance_id", "agent_connected",
"pending_tasks_count","running_tasks_count", "status",
"cpu (units)", "mem (MiB)"
]
headers_2 = ["active", "draining",
"tasks pending", "tasks running",
"cpu_reserved / cpu_total", "mem_reserved / mem_total"
]
data = []
data_2 = []
if instances.nil?
puts "No instances found"
else
count_active = 0
count_draining = 0
mem_cluster_total = 0.0
mem_cluster_res_total = 0.0
mem_percentage = 0.0
cpu_cluster_total = 0.0
cpu_cluster_res_total = 0.0
cpu_percentage = 0.0
pending_tasks_count_total = 0
running_tasks_count_total = 0
instances.each do |instance|
info = instance[:info]
cpu_total = info.registered_resources[0].integer_value
mem_total = info.registered_resources[1].integer_value
cpu_available = info.remaining_resources[0].integer_value
mem_available = info.remaining_resources[1].integer_value
connected = info.agent_connected
data << [instance[:name], info.ec2_instance_id, connected,
info.pending_tasks_count, info.running_tasks_count, info.status,
"#{cpu_available} / #{cpu_total}", "#{mem_available} / #{mem_total}"
]
pending_tasks_count_total = pending_tasks_count_total + info.pending_tasks_count
running_tasks_count_total = running_tasks_count_total + info.running_tasks_count
mem_cluster_total = mem_cluster_total + mem_total if info.status == "ACTIVE"
mem_cluster_res_total = mem_cluster_res_total + mem_available if info.status == "ACTIVE"
mem_percentage = (((mem_cluster_total - mem_cluster_res_total)/mem_cluster_total) * 100).round(2)
cpu_cluster_total = cpu_cluster_total + cpu_total if info.status == "ACTIVE"
cpu_cluster_res_total = cpu_cluster_res_total + cpu_available if info.status == "ACTIVE"
cpu_percentage = (((cpu_cluster_total - cpu_cluster_res_total)/cpu_cluster_total) * 100).round(2)
count_active = count_active + 1 if info.status == "ACTIVE"
count_draining = count_draining + 1 if info.status == "DRAINING"
end
data_2 << [count_active, count_draining,
pending_tasks_count_total, running_tasks_count_total,
"#{(cpu_cluster_total - cpu_cluster_res_total).round(0)} / #{cpu_cluster_total.round(0)} (#{cpu_percentage} %)", "#{(mem_cluster_total - mem_cluster_res_total).round(0)} / #{mem_cluster_total.round(0)} (#{mem_percentage} %)"
]
AwsPocketknife::Ecs.pretty_table(headers: headers, data: data)
puts ""
puts ""
AwsPocketknife::Ecs.pretty_table(headers: headers_2, data: data_2)
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/asg.rb
|
require 'aws_pocketknife'
require 'base64'
require 'openssl'
module AwsPocketknife
module Asg
class << self
include AwsPocketknife::Common::Utils
def describe_asg_by_name(name: "")
asg_list = name.split(";")
asg_client.describe_auto_scaling_groups({auto_scaling_group_names: asg_list, })
end
def list(max_records: 100)
asgs = []
resp = asg_client.describe_auto_scaling_groups({
max_records: max_records,
})
asgs << resp.auto_scaling_groups
next_token = resp.next_token
while true
break if next_token.nil? or next_token.empty?
resp = get_asgs(next_token: next_token, max_records: max_records)
asgs << resp.auto_scaling_groups
next_token = resp.next_token
end
asgs.flatten!
end
private
def get_asgs(next_token: "", max_records: 100)
asg_client.describe_auto_scaling_groups({
max_records: max_records,
next_token: next_token,
})
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/ami.rb
|
<filename>lib/aws_pocketknife/cli/ami.rb
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Ami < Thor
desc "clean AMI_NAME_PATTERN DAYS --dry_run", "Given a name or filter (i.e, test-*), this command will delete all matched AMIs (and associated snapshots) with creation time lower than DAYS."
option :dry_run, :type => :boolean, :default => true, :desc => 'just show images that would be deleted'
def clean(ami_name_pattern, days)
dry_run = options.fetch("dry_run", true)
AwsPocketknife::Ec2.clean_ami ami_name_pattern: ami_name_pattern,
days: days,
dry_run: dry_run
end
desc "delete_by_id AMI_ID ", "Deletes the ami id."
def delete_by_id(id)
AwsPocketknife::Ec2.delete_ami_by_id id: id
end
desc "share IMAGE_ID ACCOUNT_ID", "share the IMAGE_ID with the specified ACCOUNT_ID"
def share(image_id, account_id)
AwsPocketknife::Ec2.share_ami(image_id: image_id, user_id: account_id)
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/route53_spec.rb
|
<gh_stars>1-10
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Route53 do
let(:route53_client) {instance_double(Aws::Route53::Client)}
before (:each) do
allow(AwsPocketknife::Route53).to receive(:route53_client).and_return(route53_client)
end
describe '#get_hosted_zone_id' do
it 'should get hosted zone id' do
hosted_zone = "/hostedzone/ABC"
expect(subject.get_hosted_zone_id(hosted_zone: hosted_zone)).to eq("ABC")
end
end
describe '#list_hosted_zones' do
it 'should list hosted zones' do
allow(route53_client).to receive(:list_hosted_zones)
expect(route53_client).to receive(:list_hosted_zones)
subject.list_hosted_zones
end
end
describe '#get_record' do
it 'should return find record and return its object' do
hosted_zone_name = "test"
hosted_zone_id = "ABC"
record_name = "example2.com"
record_type = "A"
aws_hosted_zone_response = get_aws_response({id: hosted_zone_id})
aws_records_response = get_aws_response({resource_record_sets: [
{name: "example1.com", type: "A"},
{name: "example2.com", type: "A"},
]})
allow(subject).to receive(:describe_hosted_zone).and_return(aws_hosted_zone_response)
allow(subject).to receive(:get_hosted_zone_id)
.with(hosted_zone: hosted_zone_id).and_return(hosted_zone_id)
allow(route53_client).to receive(:list_resource_record_sets)
.with({hosted_zone_id: hosted_zone_id,
start_record_name: record_name,
start_record_type: record_type,
max_items: 1,
})
.and_return(aws_records_response)
record = subject.get_record(hosted_zone_name: hosted_zone_name, record_name: record_name, record_type: record_type)
expect(record.length).to eq(1)
expect(record[0].name).to eq(record_name)
end
it 'should return empty array when record is not found' do
hosted_zone_name = "test"
hosted_zone_id = "ABC"
record_name = "example3.com"
record_type = "A"
aws_hosted_zone_response = get_aws_response({id: hosted_zone_id})
aws_records_response = get_aws_response({resource_record_sets: [
{name: "example1.com", type: "A"},
{name: "example2.com", type: "A"},
]})
allow(subject).to receive(:describe_hosted_zone).and_return(aws_hosted_zone_response)
allow(subject).to receive(:get_hosted_zone_id)
.with(hosted_zone: hosted_zone_id).and_return(hosted_zone_id)
allow(route53_client).to receive(:list_resource_record_sets)
.with({hosted_zone_id: hosted_zone_id,
start_record_name: record_name,
start_record_type: record_type,
max_items: 1,
})
.and_return(aws_records_response)
record = subject.get_record(hosted_zone_name: hosted_zone_name, record_name: record_name, record_type: record_type)
expect(record.length).to eq(0)
expect(record).to eq([])
end
end
describe '#list_records_for_zone_name' do
it 'should return an empty []' do
allow(subject).to receive(:describe_hosted_zone).and_return(nil)
expect(subject.list_records_for_zone_name(hosted_zone_name: "test")).to eq([])
end
it 'should list_records_for_zone_name for record type in ["A", "CNAME", "AAAA"]' do
hosted_zone_name = "test"
hosted_zone_id = "ABC"
aws_hosted_zone_response = get_aws_response({id: hosted_zone_id})
aws_records_response = get_aws_response({resource_record_sets: [
{name: "example1.com", type: "A"},
{name: "example2.com", type: "CNAME"},
{name: "example3.com", type: "AAAA"}
]})
allow(subject).to receive(:describe_hosted_zone).and_return(aws_hosted_zone_response)
allow(subject).to receive(:get_hosted_zone_id)
.with(hosted_zone: hosted_zone_id).and_return(hosted_zone_id)
allow(route53_client).to receive(:list_resource_record_sets)
.with({hosted_zone_id: hosted_zone_id})
.and_return(aws_records_response)
records = subject.list_records_for_zone_name(hosted_zone_name: hosted_zone_name)
expect(records.length).to eq(3)
i = 0
records.each do |record|
expect(record.name).to eq(aws_records_response.resource_record_sets[i].name)
i = i + 1
end
end
it 'should return empty array for record type not in ["A", "CNAME", "AAAA"]' do
hosted_zone_name = "test"
hosted_zone_id = "ABC"
aws_hosted_zone_response = RecursiveOpenStruct.new({id: hosted_zone_id}, recurse_over_arrays: true)
aws_records_response = RecursiveOpenStruct.new({resource_record_sets: [
{name: "example1.com", type: "SOA"},
{name: "example2.com", type: "NS"},
{name: "example3.com", type: "TXT"}
]}, recurse_over_arrays: true)
allow(subject).to receive(:describe_hosted_zone).and_return(aws_hosted_zone_response)
allow(subject).to receive(:get_hosted_zone_id)
.with(hosted_zone: hosted_zone_id).and_return(hosted_zone_id)
allow(route53_client).to receive(:list_resource_record_sets)
.with({hosted_zone_id: hosted_zone_id})
.and_return(aws_records_response)
records = subject.list_records_for_zone_name(hosted_zone_name: hosted_zone_name)
expect(records.length).to eq(0)
end
end
describe '#update_record' do
it 'should update alias record from existing dns record' do
origin_hosted_zone = "ABC"
origin_dns_name = "example.com"
record_type = "A"
destiny_dns_name ="example2.com"
destiny_hosted_zone = "ABCD"
comment = ""
hosted_zone_id = "id"
destiny_hosted_zone_id = "id"
change = {
action: "UPSERT",
resource_record_set: {
name: origin_dns_name,
type: record_type,
alias_target: {
hosted_zone_id: destiny_hosted_zone_id, # required
dns_name: "dualstack." + destiny_dns_name, # required
evaluate_target_health: false, # required
}
}
}
payload = {
hosted_zone_id: hosted_zone_id,
change_batch: {
comment: comment,
changes: [change]
}
}
aws_response_1 = get_aws_response({id: hosted_zone_id})
aws_response_2 = get_aws_response({
alias_target:
{
hosted_zone_id: "id", dns_name: origin_dns_name},
resource_records: [{value: origin_dns_name}]
})
aws_response_3 = get_aws_response({alias_target: {hosted_zone_id: "id", dns_name: destiny_dns_name}})
expect(subject).to receive(:describe_hosted_zone)
.with(hosted_zone: origin_hosted_zone)
.and_return(aws_response_1)
expect(subject).to receive(:get_record)
.with(hosted_zone_name: origin_hosted_zone,
record_name: origin_dns_name,
record_type: record_type)
.and_return([aws_response_2])
expect(subject).to receive(:get_record)
.with(hosted_zone_name: destiny_hosted_zone,
record_name: destiny_dns_name,
record_type: record_type)
.and_return([aws_response_3])
allow(route53_client).to receive(:change_resource_record_sets).with(payload)
subject.update_record(origin_hosted_zone: origin_hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name: destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone
)
end
it 'should not update alias record when both dns are the same' do
origin_hosted_zone = "ABC"
origin_dns_name = "example.com"
record_type = "A"
destiny_dns_name ="example.com"
destiny_hosted_zone = "ABCD"
comment = ""
hosted_zone_id = "id"
destiny_hosted_zone_id = "id"
change = {
action: "UPSERT",
resource_record_set: {
name: origin_dns_name,
type: record_type,
alias_target: {
hosted_zone_id: destiny_hosted_zone_id, # required
dns_name: destiny_dns_name, # required
evaluate_target_health: false, # required
}
}
}
payload = {
hosted_zone_id: hosted_zone_id,
change_batch: {
comment: comment,
changes: [change]
}
}
aws_response_1 = get_aws_response({id: hosted_zone_id})
aws_response_2 = get_aws_response({
alias_target:
{
hosted_zone_id: "id", dns_name: origin_dns_name},
resource_records: [{value: origin_dns_name}]
})
aws_response_3 = get_aws_response({alias_target: {hosted_zone_id: "id", dns_name: destiny_dns_name}})
expect(subject).to receive(:describe_hosted_zone)
.with(hosted_zone: origin_hosted_zone)
.and_return(aws_response_1)
expect(subject).to receive(:get_record)
.with(hosted_zone_name: origin_hosted_zone,
record_name: origin_dns_name,
record_type: record_type)
.and_return([aws_response_2])
expect(subject).to receive(:get_record)
.with(hosted_zone_name: destiny_hosted_zone,
record_name: destiny_dns_name,
record_type: record_type)
.and_return([aws_response_3])
expect(route53_client).not_to receive(:change_resource_record_sets).with(payload)
subject.update_record(origin_hosted_zone: origin_hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name: destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone
)
end
it 'should update CNAME record given a dns name' do
origin_hosted_zone = "ABC"
origin_dns_name = "example.com"
record_type = "CNAME"
destiny_dns_name ="example2.com"
destiny_hosted_zone = ""
comment = ""
hosted_zone_id = "id"
change = {
action: "UPSERT",
resource_record_set: {
name: origin_dns_name,
type: record_type,
ttl: 300,
resource_records: [{value: destiny_dns_name}]
}
}
payload = {
hosted_zone_id: hosted_zone_id,
change_batch: {
comment: comment,
changes: [change]
}
}
aws_response_1 = get_aws_response({id: hosted_zone_id})
aws_response_2 = get_aws_response({alias_target:
{
hosted_zone_id: "id", dns_name: origin_dns_name},
resource_records: [{value: origin_dns_name}]
})
expect(subject).to receive(:describe_hosted_zone)
.with(hosted_zone: origin_hosted_zone)
.and_return(aws_response_1)
expect(subject).to receive(:get_record)
.with(hosted_zone_name: origin_hosted_zone,
record_name: origin_dns_name,
record_type: record_type)
.and_return([aws_response_2])
allow(route53_client).to receive(:change_resource_record_sets).with(payload)
expect(route53_client).to receive(:change_resource_record_sets).with(payload)
subject.update_record(origin_hosted_zone: origin_hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name: destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone
)
end
it 'should not update CNAME if origin and destiny dns are the same' do
origin_hosted_zone = "ABC"
origin_dns_name = "example.com"
record_type = "CNAME"
destiny_dns_name ="example.com"
destiny_hosted_zone = ""
comment = ""
hosted_zone_id = "id"
change = {
action: "UPSERT",
resource_record_set: {
name: origin_dns_name,
type: record_type,
ttl: 300,
resource_records: [{value: destiny_dns_name}]
}
}
payload = {
hosted_zone_id: hosted_zone_id,
change_batch: {
comment: comment,
changes: [change]
}
}
aws_response_1 = get_aws_response({id: hosted_zone_id})
aws_response_2 = get_aws_response({
alias_target:
{
hosted_zone_id: "id", dns_name: origin_dns_name},
resource_records: [{value: origin_dns_name}]
})
expect(subject).to receive(:describe_hosted_zone)
.with(hosted_zone: origin_hosted_zone)
.and_return(aws_response_1)
expect(subject).to receive(:get_record)
.with(hosted_zone_name: origin_hosted_zone,
record_name: origin_dns_name,
record_type: record_type)
.and_return([aws_response_2])
expect(route53_client).not_to receive(:change_resource_record_sets).with(payload)
result = subject.update_record(origin_hosted_zone: origin_hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name: destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone
)
expect(result).to eq(false)
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/tasks/route53.rake
|
require_relative "../route53"
require_relative '../cli/route53'
route53_cli = AwsPocketknife::Cli::Route53.new
namespace :route53 do
desc "Describe hosted zone"
task :describe_hosted_zone, [:hosted_zone] do |t, args|
route53_cli.describe_hosted_zone(args)
end
desc "Listed hosted zones"
task :list_hosted_zones do
route53_cli.list
end
desc "List records for hosted zone"
task :list_records, [:hosted_zone] do |t, args|
route53_cli.list_records(args[:hosted_zone])
end
desc "Get record for hosted zone. Record type accepts SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA"
task :get_record, [:hosted_zone, :record_name, :record_type] do |t, args|
record_type = args[:record_type] || 'A'
record_name = args[:record_name]
records = AwsPocketknife::Route53.get_record(hosted_zone_name: args[:hosted_zone],
record_name:record_name,
record_type: record_type)
headers = ["Name", "Type", "DNS Name"]
data = []
if records.length > 0
records.each do |record|
if record.type == 'CNAME'
data << [record.name, record.type, record.resource_records[0].value]
else
data << [record.name, record.type, record.alias_target.dns_name]
end
end
AwsPocketknife::Route53.pretty_table(headers: headers, data: data)
else
puts "Record #{record_name} not found in hosted zone #{args[:hosted_zone]}"
end
end
desc "Update dns record from existing dns entry."
task :update_record, [:hosted_zone, :record_name, :destiny_record_name, :destiny_hosted_zone, :record_type] do |t, args|
record_type = args[:record_type] || 'A'
origin_dns_name = args[:record_name]
destiny_record_name = args[:destiny_record_name]
hosted_zone = args[:hosted_zone]
destiny_hosted_zone = args[:destiny_hosted_zone]
AwsPocketknife::Route53.update_record(origin_hosted_zone: hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name: destiny_record_name,
destiny_hosted_zone: destiny_hosted_zone
)
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/tasks/iam.rake
|
require_relative "../iam"
require_relative '../cli/iam'
iam_cli = AwsPocketknife::Cli::Iam.new
namespace :iam do
desc 'List ssl certificates'
task :list_ssl_certificates do
iam_cli.list_ssl_certs
end
desc 'Create IAM User'
task :create_user, [:username] do |_t, args|
iam_cli.create_user args[:username]
end
desc 'Create IAM Group'
task :create_group, [:group_name] do |_t, args|
iam_cli.create_group args[:group_name]
end
desc 'Create IAM Policy from file. You pass list of s3 buckets like so: s1bucket;s2bucket'
task :create_policy, [:policy_name,:policy_file,:s3_buckets] do |_t, args|
AwsPocketknife::Iam.create_policy_from_policy_file(policy_name: args[:policy_name], policy_file: args[:policy_file], s3_buckets: args[:s3_buckets])
end
desc 'Attach IAM Policy to Group'
task :attach_policy_to_group, [:policy_name,:group_name] do |_t, args|
AwsPocketknife::Iam.attach_policy_to_group(args[:policy_name],args[:group_name])
end
desc 'Add user to Group'
task :attach_user_to_group, [:username,:group_name] do |_t, args|
iam_cli.add_user_to_group args[:username], args[:group_name]
end
desc 'Create Role'
task :create_role, [:role_name,:trust_relationship_file] do |_t, args|
AwsPocketknife::Iam.create_role(args[:role_name],args[:trust_relationship_file])
end
desc 'Attach policy to role'
task :attach_policy_to_role, [:role_name,:policy_name] do |_t, args|
AwsPocketknife::Iam.attach_policy_to_role(args[:role_name],args[:policy_name])
end
desc 'Create Instance Profile'
task :create_instance_profile, [:instance_profile_name] do |_t, args|
AwsPocketknife::Iam.create_instance_profile(args[:instance_profile_name])
end
desc 'Add Role to Instance Profile'
task :add_role_to_instance_profile, [:instance_profile_name,:role_name] do |_t, args|
AwsPocketknife::Iam.add_role_to_instance_profile(args[:role_name],args[:instance_profile_name])
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/common/logging.rb
|
<filename>lib/aws_pocketknife/common/logging.rb
require 'log4r'
module AwsPocketknife
module Common
module Logging
include Log4r
Logger = Log4r::Logger
Log4r::Logger.root.level = Log4r::INFO
class << self
def logger
@log ||= initialize_log
end
def initialize_log(name: "aws_pocketknife", pattern: "[%l] %d %m")
log = Logger.new(name)
log_format = Log4r::PatternFormatter.new(:pattern => pattern)
log_output = Log4r::StdoutOutputter.new 'console'
log_output.formatter = log_format
log.add(log_output)
return log
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/main.rb
|
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Main < Thor
map %w[--version -v] => :__print_version
desc "ec2 SUBCOMMAND ...ARGS", "ec2 command lines"
subcommand "ec2", AwsPocketknife::Cli::Ec2
desc "ami SUBCOMMAND ...ARGS", "ami command lines"
subcommand "ami", AwsPocketknife::Cli::Ami
desc "eb SUBCOMMAND ...ARGS", "elastic beanstalk command lines"
subcommand "eb", AwsPocketknife::Cli::Eb
desc "route53 SUBCOMMAND ...ARGS", "route53 command lines"
subcommand "route53", AwsPocketknife::Cli::Route53
desc "iam SUBCOMMAND ...ARGS", "iam command lines"
subcommand "iam", AwsPocketknife::Cli::Iam
desc "rds SUBCOMMAND ...ARGS", "rds command lines"
subcommand "rds", AwsPocketknife::Cli::Rds
desc "asg SUBCOMMAND ...ARGS", "asg command lines"
subcommand "asg", AwsPocketknife::Cli::Asg
desc "elb SUBCOMMAND ...ARGS", "elb command lines"
subcommand "elb", AwsPocketknife::Cli::Elb
desc "ecs SUBCOMMAND ...ARGS", "ecs command lines"
subcommand "ecs", AwsPocketknife::Cli::Ecs
desc "--version, -v", "print the version"
def __print_version
puts AwsPocketknife::VERSION
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/cli/ec2_spec.rb
|
<reponame>gustavosoares/aws_pocketknife<gh_stars>1-10
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Cli::Ec2 do
let(:instance_name) {'test-*'}
let(:instance_id) {'i-1234'}
describe '#find_by_name' do
it 'should call find_by_name with the right arguments' do
allow(AwsPocketknife::Ec2).to receive(:find_by_name).with(name: instance_name).and_return([])
allow(AwsPocketknife::Ec2).to receive(:pretty_table)
expect(AwsPocketknife::Ec2).to receive(:find_by_name).with(name: instance_name)
subject.find_by_name instance_name
end
end
describe '#find_by_id' do
it 'should call find_by_id with the right arguments' do
aws_response = get_instance_response instance_id: instance_id
allow(AwsPocketknife::Ec2).to receive(:find_by_id)
.with(instance_id: instance_id).and_return(aws_response)
allow(AwsPocketknife::Ec2).to receive(:nice_print)
expect(AwsPocketknife::Ec2).to receive(:find_by_id).with(instance_id: instance_id)
expect(AwsPocketknife::Ec2).to receive(:nice_print)
subject.find_by_id instance_id
end
it 'should call find_by_id with the right arguments and get back a nil response' do
allow(AwsPocketknife::Ec2).to receive(:find_by_id)
.with(instance_id: instance_id).and_return(nil)
allow(AwsPocketknife::Ec2).to receive(:nice_print)
expect(AwsPocketknife::Ec2).to receive(:find_by_id).with(instance_id: instance_id)
expect(AwsPocketknife::Ec2).not_to receive(:nice_print)
subject.find_by_id instance_id
end
end
describe '#get_windows_password' do
it 'should call get_windows_password with the right arguments' do
aws_response = get_instance_response instance_id: instance_id
allow(AwsPocketknife::Ec2).to receive(:get_windows_password)
.with(instance_id: instance_id).and_return(aws_response)
allow(AwsPocketknife::Ec2).to receive(:pretty_table)
expect(AwsPocketknife::Ec2).to receive(:get_windows_password).with(instance_id: instance_id)
expect(AwsPocketknife::Ec2).to receive(:pretty_table)
subject.get_windows_password instance_id
end
end
describe '#stop' do
it 'should call stop with the right arguments' do
allow(AwsPocketknife::Ec2).to receive(:stop_instance_by_id)
.with(instance_id)
expect(AwsPocketknife::Ec2).to receive(:stop_instance_by_id).with(instance_id)
subject.stop instance_id
end
end
describe '#start' do
it 'should call stop with the right arguments' do
allow(AwsPocketknife::Ec2).to receive(:start_instance_by_id)
.with(instance_id)
expect(AwsPocketknife::Ec2).to receive(:start_instance_by_id).with(instance_id)
subject.start instance_id
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/rds_spec.rb
|
<reponame>gustavosoares/aws_pocketknife<gh_stars>1-10
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Rds do
let(:rds_client) {instance_double(Aws::RDS::Client)}
let(:db_name) { 'my_db' }
let(:snapshot_name) { 'db_snapshot_1' }
before (:each) do
allow(subject).to receive(:rds_client).and_return(rds_client)
end
describe '#describe_snapshots' do
it 'should get snapshots' do
aws_reponse = describe_snapshot_response db_snapshot_identifier: snapshot_name, date: '2040-12-16 11:57:42 +1100'
allow(rds_client).to receive(:describe_db_snapshots).with({db_instance_identifier: db_name}).and_return(aws_reponse)
expect(rds_client).to receive(:describe_db_snapshots).with({db_instance_identifier: db_name})
subject.describe_snapshots db_name: db_name
end
end
describe '#clean_snapshots' do
it 'should clean snapsthos when dry_run is false' do
aws_reponse = describe_snapshot_response db_snapshot_identifier: snapshot_name, date: '2040-12-16 11:57:42 +1100'
allow(rds_client).to receive(:describe_db_snapshots)
.with({db_instance_identifier: db_name})
.and_return(aws_reponse)
allow(rds_client).to receive(:delete_db_snapshot)
.with({db_snapshot_identifier: snapshot_name})
expect(rds_client).to receive(:describe_db_snapshots).with({db_instance_identifier: db_name})
expect(rds_client).to receive(:delete_db_snapshot).with({db_snapshot_identifier: snapshot_name})
subject.clean_snapshots db_name: db_name, days: 15, dry_run: false
end
it 'should not clean snapsthos when dry_run is true' do
aws_reponse = describe_snapshot_response db_snapshot_identifier: snapshot_name, date: '2040-12-16 11:57:42 +1100'
allow(rds_client).to receive(:describe_db_snapshots)
.with({db_instance_identifier: db_name})
.and_return(aws_reponse)
allow(rds_client).to receive(:delete_db_snapshot)
.with({db_snapshot_identifier: snapshot_name})
expect(rds_client).to receive(:describe_db_snapshots).with({db_instance_identifier: db_name})
expect(rds_client).not_to receive(:delete_db_snapshot).with({db_snapshot_identifier: snapshot_name})
subject.clean_snapshots db_name: db_name, days: 15, dry_run: true
end
end
describe '#create_snapshot' do
it 'should create snapshot and poll until status ready' do
aws_reponse_1 = describe_snapshot_response db_snapshot_identifier: snapshot_name,
date: '2040-12-16 11:57:42 +1100',
status: AwsPocketknife::Rds::CREATING
aws_reponse_2 = describe_snapshot_response db_snapshot_identifier: snapshot_name, date: '2040-12-16 11:57:42 +1100'
allow(Kernel).to receive(:sleep)
allow(subject).to receive(:get_snapshot_name).with(db_name).and_return(snapshot_name)
allow(rds_client).to receive(:create_db_snapshot)
allow(rds_client).to receive(:describe_db_snapshots)
.with({db_instance_identifier: db_name})
.and_return(aws_reponse_1)
allow(rds_client).to receive(:describe_db_snapshots)
.with({db_snapshot_identifier: snapshot_name})
.and_return(aws_reponse_1, aws_reponse_1, aws_reponse_2)
expect(rds_client).to receive(:create_db_snapshot)
expect(rds_client).to receive(:describe_db_snapshots)
.with({db_snapshot_identifier: snapshot_name}).exactly(3).times()
subject.create_snapshot db_name: db_name
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/asg_spec.rb
|
<gh_stars>1-10
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Asg do
let(:asg_client) {instance_double(Aws::AutoScaling::Client)}
before (:each) do
allow(subject).to receive(:asg_client).and_return(asg_client)
end
describe '#describe_asg_by_name' do
it 'should return list with the searched asg' do
asg_name = "asg"
asg_list = [asg_name]
aws_response = get_aws_response({auto_scaling_groups: [
{auto_scaling_group_name: asg_name}
]})
allow(asg_client).to receive(:describe_auto_scaling_groups)
.with({
auto_scaling_group_names: asg_list,
}).and_return(aws_response)
asg = subject.describe_asg_by_name(name: asg_name)
expect(asg.auto_scaling_groups.first.auto_scaling_group_name).to eq(asg_name)
end
it 'should return empty list with searched asg is not found' do
asg_name = "asg"
asg_list = [asg_name]
aws_response = RecursiveOpenStruct.new({auto_scaling_groups: []}, recurse_over_arrays: true)
allow(asg_client).to receive(:describe_auto_scaling_groups)
.with({
auto_scaling_group_names: asg_list,
}).and_return(aws_response)
asg = subject.describe_asg_by_name(name: asg_name)
expect(asg.auto_scaling_groups.empty?).to eq(true)
end
end
describe '#list' do
it 'should list asgs with default max records when there is no next token' do
asg_name = "asg"
aws_response = get_aws_response({auto_scaling_groups: [
{auto_scaling_group_name: asg_name}
]})
allow(asg_client).to receive(:describe_auto_scaling_groups)
.with({
max_records: 100,
}).and_return(aws_response)
asgs = subject.list
expect(asgs.length).to eq(1)
end
it 'should list asgs with default max records and use next token attribute from response' do
asg_name = "asg"
next_token = "<PASSWORD>"
max_records = 100
asg_list = [asg_name]
aws_response_1 = get_aws_response({auto_scaling_groups: [
{auto_scaling_group_name: asg_name},
], next_token: next_token})
aws_response_2 = get_aws_response({auto_scaling_groups: [
{auto_scaling_group_name: asg_name}
]})
allow(asg_client).to receive(:describe_auto_scaling_groups)
.with({
max_records: max_records,
}).and_return(aws_response_1)
expect(subject).to receive(:get_asgs)
.with(next_token: next_token, max_records: max_records)
.and_return(aws_response_2)
asgs = subject.list
expect(asgs.length).to eq(2)
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/rds.rb
|
<reponame>gustavosoares/aws_pocketknife
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Rds < Thor
desc "snapshot SUBCOMMAND ...ARGS", "snapshot command lines"
subcommand "snapshot", AwsPocketknife::Cli::RdsSnapshot
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/asg.rb
|
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Asg < Thor
desc "list", "list all autoscaling groups"
def list
asgs = AwsPocketknife::Asg.list
print_asg(asgs: asgs)
end
desc "desc ASG_NAME", "describe autoscaling group name"
def desc(asg_name)
asg = AwsPocketknife::Asg.describe_asg_by_name(name: asg_name)
if asg.auto_scaling_groups.empty?
puts "ASG #{asg_name} not found"
else
AwsPocketknife::Asg.nice_print(object: asg.to_h)
end
end
private
def print_asg(asgs: [])
headers = ["name", "min size", "max size", "desired capacity", "instances", "elb"]
data = []
if asgs.length > 0
asgs.each do |asg|
instances = []
asg.instances.map { |instance| instances << instance.instance_id }
data << [asg.auto_scaling_group_name, asg.min_size, asg.max_size,
asg.desired_capacity, instances.join(", "), asg.load_balancer_names.join(", ")]
end
AwsPocketknife::Asg.pretty_table(headers: headers, data: data)
else
puts "No asg(s) found for name #{args[:name]}"
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/aws_pocketknife_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
require 'aws_pocketknife'
describe AwsPocketknife do
it 'has a version number' do
expect(AwsPocketknife::VERSION).not_to be nil
end
it 'should use default region when env var is unset' do
ENV['AWS_REGION'] = ""
expect(AwsPocketknife::AWS_REGION).to eq("us-west-2")
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/elb.rb
|
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Elb < Thor
desc "desc ELB_NAME", "describe classic elastic load balancer"
def desc(elb_name)
elb = AwsPocketknife::Elb.describe_elb_by_name(name: elb_name)
if elb.nil?
puts "ELB #{elb_name} not found"
else
AwsPocketknife::Ec2.nice_print(object: elb.to_h)
end
end
desc "list", "list elastic load balancer"
def list()
elbs = AwsPocketknife::Elb.list
print_elbs(elbs: elbs)
end
desc "list_v2", "list load balancers using v2 api (application and network loadbalancers)"
def list_v2()
elbs = AwsPocketknife::Elb.list_v2
print_elbs_v2(elbs: elbs)
end
private
def print_elbs(elbs: [])
headers = ["name", "vpc_id", "security_groups", "scheme"]
data = []
if elbs.length > 0
elbs.each do |elb|
data << [elb.load_balancer_name, elb.vpc_id, elb.security_groups.join(", "), elb.scheme]
end
AwsPocketknife::Elb.pretty_table(headers: headers, data: data)
else
puts "No elb(s) found for name #{args[:name]}"
end
end
def print_elbs_v2(elbs: [])
headers = ["name", "vpc_id", "security_groups", "scheme", "type"]
data = []
if elbs.length > 0
elbs.each do |elb|
data << [elb.load_balancer_name, elb.vpc_id, elb.security_groups.join(", "), elb.scheme, elb.type]
end
AwsPocketknife::Elb.pretty_table(headers: headers, data: data)
else
puts "No elb(s) found for name #{args[:name]}"
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/elb.rb
|
require 'aws_pocketknife'
module AwsPocketknife
module Elb
class << self
include AwsPocketknife::Common::Utils
def describe_elb_by_name(name: '')
resp = elb_client.describe_load_balancers({
load_balancer_names: [name],
page_size: 1,
})
if resp.nil? or resp.load_balancer_descriptions.empty?
return nil
else
return resp.load_balancer_descriptions.first
end
end
def list(max_records: 100)
elbs = []
resp = elb_client.describe_load_balancers({
page_size: max_records,
})
elbs << resp.load_balancer_descriptions
next_marker = resp.next_marker
while true
break if next_marker.nil? or next_marker.empty?
resp = get_elbs(next_marker: next_marker, max_records: max_records)
elbs << resp.load_balancer_descriptions
next_marker = resp.next_marker
end
elbs.flatten!
end
def list_v2(max_records: 100)
elbs = []
resp = elb_clientV2.describe_load_balancers({
page_size: max_records,
})
elbs << resp.load_balancers
next_marker = resp.next_marker
while true
break if next_marker.nil? or next_marker.empty?
resp = get_elbs(next_marker: next_marker, max_records: max_records)
elbs << resp.load_balancers
next_marker = resp.next_marker
end
elbs.flatten!
end
private
def get_elbs(next_marker: "", max_records: 100)
elb_client.describe_load_balancers({
page_size: max_records,
marker: next_marker,
})
end
def get_elbs_v2(next_marker: "", max_records: 100)
elb_clientV2.describe_load_balancers({
page_size: max_records,
marker: next_marker,
})
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/common/utils.rb
|
require "pretty_table"
require "awesome_print"
require_relative "logging"
module AwsPocketknife
module Common
module Utils
#include AwsPocketknife::Common::Logging
def ec2_client
@ec2_client ||= AwsPocketknife.ec2_client
end
def ecs_client
@ecs_client ||= AwsPocketknife.ecs_client
end
def iam_client
@iam_client ||= AwsPocketknife.iam_client
end
def route53_client
@route53_client ||= AwsPocketknife.route53_client
end
def rds_client
@rds_client ||= AwsPocketknife.rds_client
end
def elb_client
@elb_client ||= AwsPocketknife.elb_client
end
def elb_clientV2
@elb_clientV2 ||= AwsPocketknife.elb_clientV2
end
def asg_client
@asg_client ||= AwsPocketknife.asg_client
end
def cloudwatch_logs_client
@cloudwatch_logs_client ||= AwsPocketknife.cloudwatch_logs_client
end
def elastic_beanstalk_client
@elastic_beanstalk_client ||= AwsPocketknife.elastic_beanstalk_client
end
def pretty_table(headers: [], data: [])
puts PrettyTable.new(data, headers).to_s
end
# https://github.com/michaeldv/awesome_print
def nice_print(object: nil)
ap object
end
def get_tag_value(tags: [], tag_key: "")
unless tags.empty? or tag_key.length == 0
tag = tags.select { |tag| tag.key == tag_key }
return tag[0].value if tag.length == 1
return "" if tag.length == 0
else
return ""
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/eb.rb
|
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Eb < Thor
desc "list", "list environments"
def list
environments = AwsPocketknife::ElasticBeanstalk.describe_environment
headers = [ 'App Name', 'Env Name', 'cname', 'Updated', 'Version', 'Health']
data = []
environments.each do |e|
data << [e.application_name, e.environment_name, e.cname, e.date_updated, e.version_label, e.health]
end
AwsPocketknife::ElasticBeanstalk.pretty_table(headers: headers, data: data)
end
desc "desc ENVIRONMENT_NAME", "describe environment name"
def desc(environment_name)
environment = AwsPocketknife::ElasticBeanstalk.describe_environment_resources(environment_name: environment_name)
unless environment.nil?
AwsPocketknife::ElasticBeanstalk.nice_print(object: environment.to_h)
else
puts "#{environment_name} not found"
end
end
desc "vars NAME", "list environment variables for the specified elastic beanstalk environment name"
def vars(environment_name)
variables = AwsPocketknife::ElasticBeanstalk.list_environment_variables(environment_name: environment_name)
headers = [ 'Name', 'Value']
data = []
variables.each do |v|
v_temp = v.split("=")
name = v_temp[0]
# remove first element (headers) from array
v_temp.shift
value = v_temp.join
data << [name, value]
end
puts "Environment: #{environment_name}"
AwsPocketknife::ElasticBeanstalk.pretty_table(headers: headers, data: data)
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/cli/route53_spec.rb
|
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Cli::Route53 do
let(:hosted_zone) {'example.com.'}
let(:record_name) {'abc.example.com'}
let(:record_type) {'AAAA'}
describe '#describe_hosted_zone' do
it 'should call describe_hosted_zone with right arguments' do
allow(AwsPocketknife::Route53).to receive(:describe_hosted_zone).with(hosted_zone: hosted_zone)
expect(AwsPocketknife::Route53).to receive(:describe_hosted_zone).with(hosted_zone: hosted_zone)
subject.describe_hosted_zone hosted_zone
end
end
describe '#list' do
it 'should call list with right arguments' do
allow(AwsPocketknife::Route53).to receive(:list_hosted_zones).and_return([])
expect(AwsPocketknife::Route53).to receive(:list_hosted_zones)
subject.list
end
end
describe '#list_records' do
it 'should call list_records with right arguments and get back an empty list of records' do
allow(AwsPocketknife::Route53).to receive(:list_records_for_zone_name).with(hosted_zone_name: hosted_zone).and_return([])
expect(AwsPocketknife::Route53).to receive(:list_records_for_zone_name).with(hosted_zone_name: hosted_zone)
subject.list_records hosted_zone
end
end
describe '#get_record' do
it 'should call get_record without record_type argument and get back an empty list' do
allow(AwsPocketknife::Route53).to receive(:get_record).with(hosted_zone_name: hosted_zone,
record_name:record_name,
record_type: 'A').and_return([])
expect(AwsPocketknife::Route53).to receive(:get_record).with(hosted_zone_name: hosted_zone,
record_name:record_name,
record_type: 'A')
subject.get_record hosted_zone, record_name
end
it 'should call get_record with record_type argument and get back an empty list' do
allow(AwsPocketknife::Route53).to receive(:get_record).with(hosted_zone_name: hosted_zone,
record_name:record_name,
record_type: record_type).and_return([])
expect(AwsPocketknife::Route53).to receive(:get_record).with(hosted_zone_name: hosted_zone,
record_name:record_name,
record_type: record_type)
subject.get_record hosted_zone, record_name, record_type
end
end
describe '#update_record' do
let (:origin_dns_name) {'origin.example.com'}
let (:destiny_dns_name) {'destiny.example.com'}
let (:destiny_hosted_zone) {'example2.com'}
it 'should call update_record with right arguments' do
allow(AwsPocketknife::Route53).to receive(:update_record).with(origin_hosted_zone: hosted_zone,
origin_dns_name: origin_dns_name,
record_type: 'A',
destiny_dns_name: destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone)
expect(AwsPocketknife::Route53).to receive(:update_record).with(origin_hosted_zone: hosted_zone,
origin_dns_name: origin_dns_name,
record_type: 'A',
destiny_dns_name: destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone)
subject.update_record hosted_zone, origin_dns_name, destiny_dns_name, destiny_hosted_zone
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/elastic_beanstalk.rb
|
require 'aws_pocketknife'
module AwsPocketknife
module ElasticBeanstalk
class << self
include AwsPocketknife::Common::Utils
def describe_environment_resources(environment_name: '')
elastic_beanstalk_client.describe_environment_resources({
environment_name: environment_name,
})
end
def list_environments()
describe_environment
end
def describe_environment(environment_name: '')
resp = nil
if environment_name.length == 0
resp = elastic_beanstalk_client.describe_environments({})
else
environment_list = environment_name.split(";")
resp = elastic_beanstalk_client.describe_environments({
environment_names: environment_list,
})
end
resp[:environments]
end
def list_environment_variables(environment_name: '')
#get application name
environment = describe_environment(environment_name: environment_name)[0]
app_name = environment.application_name
#get environment_variables
resp = elastic_beanstalk_client.describe_configuration_settings({
application_name: app_name,
environment_name: environment_name,
})
configuration_setting = resp.configuration_settings[0]
option_settings = configuration_setting.option_settings
environment_variables = []
option_settings.each do |option|
if option.option_name == "EnvironmentVariables"
environment_variables = option.value.split(",")
break
end
end
environment_variables
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cloudwatch_logs.rb
|
require 'aws_pocketknife'
require 'base64'
require 'openssl'
require 'recursive-open-struct'
module AwsPocketknife
module CloudwatchLogs
class << self
include AwsPocketknife::Common::Utils
def create_log_group(log_group_name: "")
unless log_group_name.empty?
cloudwatch_logs_client.create_log_group({
log_group_name: log_group_name, # required
})
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/spec_helper.rb
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'aws_pocketknife'
require 'webmock/rspec'
require_relative 'aws_spec_helper'
def capture_stdout(&blk)
old = $stdout
$stdout = fake = StringIO.new
blk.call
fake.string
ensure
$stdout = old
end
def capture(stream)
begin
stream = stream.to_s
eval "$#{stream} = StringIO.new"
yield
result = eval("$#{stream}").string
ensure
eval("$#{stream} = #{stream.upcase}")
end
result
end
def capture_stderr(&blk)
old = $stderr
$stderr = fake = StringIO.new
blk.call
fake.string
ensure
$stderr = old
end
RSpec.configure do |config|
config.mock_with :rspec
Aws.config.update(stub_responses: true)
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife.rb
|
<gh_stars>1-10
require 'aws_pocketknife/version'
require 'aws-sdk-core'
require 'aws_pocketknife/common/utils'
require 'aws_pocketknife/common/logging'
require 'aws_pocketknife/iam'
require 'aws_pocketknife/ec2'
require 'aws_pocketknife/ecs'
require 'aws_pocketknife/route53'
require 'aws_pocketknife/asg'
require 'aws_pocketknife/cloudwatch_logs'
require 'aws_pocketknife/elastic_beanstalk'
require 'aws_pocketknife/elb'
require 'aws_pocketknife/rds'
require 'aws_pocketknife/cli/iam'
require 'aws_pocketknife/cli/asg'
require 'aws_pocketknife/cli/elb'
require 'aws_pocketknife/cli/ec2'
require 'aws_pocketknife/cli/ecs'
require 'aws_pocketknife/cli/ami'
require 'aws_pocketknife/cli/eb'
require 'aws_pocketknife/cli/route53'
require 'aws_pocketknife/cli/rds_snapshot'
require 'aws_pocketknife/cli/rds'
require 'aws_pocketknife/cli/main'
module AwsPocketknife
extend self
AWS_REGION = ENV['AWS_REGION'] || 'us-west-2'
AWS_PROFILE = ENV['AWS_PROFILE'] || nil
class << self
def cloudwatch_logs_client
@cloudwatch_logs_client ||= Aws::CloudWatchLogs::Client.new(get_client_options)
end
def cf_client
@cloud_formation_client ||= Aws::CloudFormation::Client.new(get_client_options)
end
def s3_client
@s3_client ||= Aws::S3::Client.new(get_client_options)
end
def elb_client
@elb_client ||= Aws::ElasticLoadBalancing::Client.new(get_client_options)
end
def elb_clientV2
@elb_clientV2 ||= Aws::ElasticLoadBalancingV2::Client.new(get_client_options)
end
def asg_client
@asg_client ||= Aws::AutoScaling::Client.new(get_client_options)
end
def elastic_beanstalk_client
@elastic_beanstalk_client ||= Aws::ElasticBeanstalk::Client.new(get_client_options)
end
def iam_client
@iam_client ||= Aws::IAM::Client.new(get_client_options)
end
def rds_client
@rds_client ||= Aws::RDS::Client.new(get_client_options)
end
def ec2_client
@ec2_client ||= Aws::EC2::Client.new(get_client_options)
end
def ecs_client
@ecs_client ||= Aws::ECS::Client.new(get_client_options)
end
def route53_client
@route53_client ||= Aws::Route53::Client.new(get_client_options)
end
private
def get_client_options
if AWS_PROFILE.nil?
return { retry_limit: 5, region: AWS_REGION }
else
credentials = Aws::SharedCredentials.new(profile_name: AWS_PROFILE)
return { retry_limit: 5, region: AWS_REGION, credentials: credentials }
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/cli/rds_snapshot_spec.rb
|
<filename>spec/cli/rds_snapshot_spec.rb<gh_stars>1-10
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Cli::RdsSnapshot do
let(:db_name) {'test'}
describe '#clean' do
let(:days) { '15' }
let(:dry_run) { true }
it 'should call clean with dry_run true' do
allow(AwsPocketknife::Rds).to receive(:clean_snapshots).with(db_name: db_name,
days: days,
dry_run: dry_run)
expect(AwsPocketknife::Rds).to receive(:clean_snapshots).with(db_name: db_name,
days: days,
dry_run: dry_run)
subject.clean db_name, days
end
it 'should call clean_ami with dry_run false' do
dry_run = false
allow(AwsPocketknife::Rds).to receive(:clean_snapshots).with(db_name: db_name,
days: days,
dry_run: dry_run)
expect(AwsPocketknife::Rds).to receive(:clean_snapshots).with(db_name: db_name,
days: days,
dry_run: dry_run)
subject.options = {"dry_run" => dry_run}
subject.clean db_name, days
end
end
describe '#list' do
it 'should call describe_snapshots with right arguments' do
allow(AwsPocketknife::Rds).to receive(:describe_snapshots).with(db_name: db_name).and_return([])
expect(AwsPocketknife::Rds).to receive(:describe_snapshots).with(db_name: db_name)
subject.list db_name
end
end
describe '#create' do
it 'should call describe_snapshots with right arguments' do
allow(AwsPocketknife::Rds).to receive(:create_snapshot).with(db_name: db_name)
expect(AwsPocketknife::Rds).to receive(:create_snapshot).with(db_name: db_name)
subject.create db_name
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/ec2.rb
|
<reponame>gustavosoares/aws_pocketknife
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Ec2 < Thor
desc "find_by_name NAME", "find instances by name. (You can filter by adding *) "
def find_by_name(name)
instances = AwsPocketknife::Ec2.find_by_name(name: name)
headers = ["name", "id", "image", "state", "private ip", "public ip", "type", "key name", "launch time"]
data = []
if instances.length > 0
instances.each do |instance|
name = AwsPocketknife::Ec2.get_tag_value(tags: instance.tags, tag_key: "Name")
data << [name, instance.instance_id, instance.image_id, instance.state.name,
instance.private_ip_address, instance.public_ip_address, instance.instance_type,
instance.key_name, instance.launch_time]
end
AwsPocketknife::Ec2.pretty_table(headers: headers, data: data)
else
puts "No instance(s) found for name #{name}"
end
end
desc "find_by_id INSTANCE_ID", "find instances by id."
def find_by_id(instance_id)
instance = AwsPocketknife::Ec2.find_by_id(instance_id: instance_id)
if instance.nil?
puts "Instance #{instance_id} not found"
else
AwsPocketknife::Ec2.nice_print(object: instance.to_h)
end
end
desc "get_windows_password INSTANCE_ID", "get windows password."
def get_windows_password(instance_id)
instance = AwsPocketknife::Ec2.get_windows_password(instance_id: instance_id)
headers = ["instance id", "password", "private ip", "public ip"]
data = [[instance.instance_id,
instance.password,
instance.private_ip_address,
instance.public_ip_address]]
AwsPocketknife::Ec2.pretty_table(headers: headers, data: data)
end
desc "stop INSTANCE_ID", "stop ec2 instance"
def stop(instance_id)
AwsPocketknife::Ec2.stop_instance_by_id(instance_id)
end
desc "start INSTANCE_ID", "start ec2 instance"
def start(instance_id)
AwsPocketknife::Ec2.start_instance_by_id(instance_id)
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/aws_spec_helper.rb
|
require 'aws_pocketknife'
require 'recursive-open-struct'
def get_aws_response(object)
RecursiveOpenStruct.new(object, recurse_over_arrays: true)
end
# stub aws describe_image call
# .state #=> String, one of "pending", "available", "invalid", "deregistered", "transient", "failed", "error"
def get_image_response(image_id: '', date: '2040-12-16 11:57:42 +1100', state: AwsPocketknife::Ec2::STATE_PENDING)
if image_id.empty?
return nil
else
get_aws_response({image_id: image_id, state: state, creation_date: date,
block_device_mappings: [
{ebs: {snapshot_id: snapshot_id}}
]
})
end
end
def get_instance_response(instance_id: '')
get_aws_response({instance_id: instance_id})
end
def describe_snapshot_response(db_snapshot_identifier: 'my-snapshot',
date: '2040-12-16 11:57:42 +1100',
status: AwsPocketknife::Rds::AVAILABLE)
get_aws_response({db_snapshots: [{
db_snapshot_identifier: db_snapshot_identifier,
snapshot_create_time: date,
percent_progress: '10',
status: status,
snapshot_type: 'manual'}
]})
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/route53.rb
|
<reponame>gustavosoares/aws_pocketknife
require 'aws_pocketknife'
module AwsPocketknife
module Route53
class << self
include AwsPocketknife::Common::Utils
Logging = Common::Logging.logger
def list_hosted_zones
result = route53_client.list_hosted_zones
unless result.nil?
return result.hosted_zones
else
return []
end
end
def describe_hosted_zone(hosted_zone: "")
hosted_zones = list_hosted_zones
zone = find_hosted_zone_id(list: hosted_zones, name: hosted_zone)
end
def get_hosted_zone_id_and_origin_record(origin_dns_name, origin_hosted_zone, record_type)
hosted_zone = describe_hosted_zone(hosted_zone: origin_hosted_zone)
hosted_zone_id = get_hosted_zone_id(hosted_zone: hosted_zone.id)
# get origin record
origin_record = get_record(hosted_zone_name: origin_hosted_zone,
record_name: origin_dns_name,
record_type: record_type)
if origin_record.empty?
Logging.warn "Could not find record for #{origin_dns_name} at #{origin_hosted_zone}"
end
return hosted_zone_id, origin_record
end
def update_record(origin_hosted_zone: "",
origin_dns_name: "",
record_type: "A",
destiny_dns_name:"",
destiny_hosted_zone: ""
)
puts "Updating #{origin_dns_name} at #{origin_hosted_zone} with #{destiny_dns_name} at #{destiny_hosted_zone}"
if destiny_hosted_zone.empty?
return update_cname_record(origin_hosted_zone: origin_hosted_zone,
origin_dns_name: origin_dns_name,
destiny_dns_name:destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone
)
else
return update_record_from_existing_dns_entry(origin_hosted_zone: origin_hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name:destiny_dns_name,
destiny_hosted_zone: destiny_hosted_zone
)
end
end
def get_payload_for_record_update(change: "", hosted_zone_id: "")
{
hosted_zone_id: hosted_zone_id,
change_batch: {
comment: "",
changes: [change]
}
}
end
def get_record(hosted_zone_name: "", record_name: "", record_type: "")
record = []
records = list_records_for_zone_name(
hosted_zone_name: hosted_zone_name,
record_name:record_name,
record_type: record_type)
records.each do |r|
return [r] if r.name == record_name
end
return record
end
def list_records(hosted_zone_id: "", record_name: "")
return route53_client.list_resource_record_sets({hosted_zone_id: hosted_zone_id,
start_record_name: record_name,
})
end
def list_records_for_zone_name(hosted_zone_name: "", record_name: "", record_type: "", max_items: 100)
records = []
temp_records = []
hosted_zone = describe_hosted_zone(hosted_zone: hosted_zone_name)
return records if hosted_zone.nil?
hosted_zone_id = get_hosted_zone_id(hosted_zone: hosted_zone.id)
result = nil
is_truncated = false
if record_name.length != 0 and record_type != 0
result = route53_client.list_resource_record_sets({hosted_zone_id: hosted_zone_id,
start_record_name: record_name,
start_record_type: record_type, # accepts SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
max_items: 1,
})
temp_records << result.resource_record_sets
is_truncated = result.is_truncated
else
result = route53_client.list_resource_record_sets({hosted_zone_id: hosted_zone_id})
temp_records << result.resource_record_sets
is_truncated = result.is_truncated
end
# loop through chunk of records
while is_truncated
next_record_name = result.next_record_name
result = list_records(hosted_zone_id: hosted_zone_id, record_name: next_record_name)
temp_records << result.resource_record_sets
is_truncated = result.is_truncated
end
temp_records.flatten!
temp_records.each do |record|
if ["A", "CNAME", "AAAA"].include?record.type
records << record
end
end
return records
end
def get_hosted_zone_id(hosted_zone: "")
hosted_zone.split("/").reverse[0]
end
private
def update_cname_record(origin_hosted_zone: "",
origin_dns_name: "",
record_type: "CNAME",
destiny_dns_name:"",
destiny_hosted_zone: ""
)
hosted_zone_id, origin_record = get_hosted_zone_id_and_origin_record(origin_dns_name, origin_hosted_zone, record_type)
new_dns_name = destiny_dns_name
origin_record = origin_record[0]
if not origin_record.alias_target.nil? and new_dns_name == origin_record.alias_target.dns_name
Logging.info "Origin and destiny alias_target.dns_name are the same: #{new_dns_name} Aborting..."
return false
elsif origin_record.resource_records.length != 0 and new_dns_name == origin_record.resource_records[0].value
Loggin.info "Origin and destiny alias_target.dns_name are the same: #{new_dns_name} Aborting..."
return false
end
change = {
action: "UPSERT",
resource_record_set: {
name: origin_dns_name,
type: record_type,
ttl: 300,
resource_records: [{value: new_dns_name}]
}
}
payload = get_payload_for_record_update(change: change, hosted_zone_id: hosted_zone_id)
nice_print(object: payload)
result = route53_client.change_resource_record_sets(payload)
end
def update_record_from_existing_dns_entry(origin_hosted_zone: "",
origin_dns_name: "",
record_type: "A",
destiny_dns_name:"",
destiny_hosted_zone: ""
)
# get hosted zone
hosted_zone_id, origin_record = get_hosted_zone_id_and_origin_record(origin_dns_name, origin_hosted_zone, record_type)
# get record for new dns name
destiny_record = get_record(hosted_zone_name: destiny_hosted_zone,
record_name: destiny_dns_name,
record_type: record_type)
if destiny_record.empty?
Logging.warn "Could not find destiny record for #{destiny_dns_name} at #{destiny_hosted_zone}"
return nil
end
if destiny_record[0].alias_target.nil?
Logging.warn "DNS #{destiny_dns_name} is invalid"
return nil
end
destiny_hosted_zone_id = destiny_record[0].alias_target.hosted_zone_id
new_dns_name = destiny_record[0].alias_target.dns_name
origin_record = origin_record[0]
unless new_dns_name.start_with?("dualstack.")
Logging.info "Adding dualstack. to #{new_dns_name}"
new_dns_name = "dualstack." + new_dns_name
end
if not origin_record.alias_target.nil? and new_dns_name == origin_record.alias_target.dns_name
Logging.info "Origin dns and destiny alias_target.dns_name points to the same record: #{new_dns_name}\nAborting..."
return false
elsif origin_record.resource_records.length != 0 and new_dns_name == origin_record.resource_records[0].value
Logging.info "Origin dns and destiny alias_target.dns_name points to the same record: #{new_dns_name}\nAborting..."
return false
end
change = {
action: "UPSERT",
resource_record_set: {
name: origin_dns_name,
type: record_type,
alias_target: {
hosted_zone_id: destiny_hosted_zone_id, # required
dns_name: new_dns_name, # required
evaluate_target_health: false, # required
}
}
}
payload = get_payload_for_record_update(change: change, hosted_zone_id: hosted_zone_id)
nice_print(object: payload)
result = route53_client.change_resource_record_sets(payload)
end
# Recevies a list of hosted zones and returns the element specified in name
def find_hosted_zone_id(list: nil, name: nil)
list.each do |h|
return h if h.name == name
end
return nil
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/route53.rb
|
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Route53 < Thor
desc "describe_hosted_zone HOSTED_ZONE", "describe hosted zone"
def describe_hosted_zone(hosted_zone)
hosted_zone = AwsPocketknife::Route53.describe_hosted_zone(hosted_zone: hosted_zone)
unless hosted_zone.nil?
AwsPocketknife::Route53.nice_print(object: hosted_zone.to_h)
else
puts "#{hosted_zone} not found"
end
end
desc "list", "list hosted zones"
def list
hosted_zones = AwsPocketknife::Route53.list_hosted_zones
headers = [ 'Name', 'Zone ID', 'Comment']
data = []
hosted_zones.each do |h|
data << [h.name,
AwsPocketknife::Route53.get_hosted_zone_id(hosted_zone: h.id),
h.config.comment]
end
AwsPocketknife::Route53.pretty_table(headers: headers, data: data)
end
desc "list_records HOSTED_ZONE", "list records for hosted zone"
def list_records(hosted_zone)
records = AwsPocketknife::Route53.list_records_for_zone_name(hosted_zone_name: hosted_zone)
headers = ["Name", "Type", "DNS Name"]
data = []
if records.length > 0
records.each do |record|
if record.type == 'CNAME'
data << [record.name, record.type, record.resource_records[0].value]
else
if record.alias_target.nil?
data << [record.name, record.type, "N/A"]
else
data << [record.name, record.type, record.alias_target.dns_name]
end
end
end
AwsPocketknife::Route53.pretty_table(headers: headers, data: data)
else
puts "No records found hosted zone #{hosted_zone}"
end
end
desc "get_record HOSTED_ZONE RECORD_NAME --record_type", "Get record for hosted zone."
#option :record_type, :type => :string, :default => 'A', :desc => 'Record type accepts SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA. Default to A'
def get_record(hosted_zone, record_name, record_type='A')
#record_type = options.fetch("record_type", 'A')
records = AwsPocketknife::Route53.get_record(hosted_zone_name: hosted_zone,
record_name:record_name,
record_type: record_type)
headers = ["Name", "Type", "DNS Name"]
data = []
if records.length > 0
records.each do |record|
if record.type == 'CNAME'
data << [record.name, record.type, record.resource_records[0].value]
else
data << [record.name, record.type, record.alias_target.dns_name]
end
end
AwsPocketknife::Route53.pretty_table(headers: headers, data: data)
else
puts "Record #{record_name} not found in hosted zone #{hosted_zone}"
end
end
desc "update_record HOSTED_ZONE ORIGIN_DNS_NAME DESTINY_RECORD_NAME DESTINY_HOSTED_ZONE RECORD_TYPE (default to A)", "Update a dns record from an existing dns entry."
def update_record(hosted_zone, origin_dns_name, destiny_record_name, destiny_hosted_zone, record_type='A')
AwsPocketknife::Route53.update_record(origin_hosted_zone: hosted_zone,
origin_dns_name: origin_dns_name,
record_type: record_type,
destiny_dns_name: destiny_record_name,
destiny_hosted_zone: destiny_hosted_zone
)
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/ecs.rb
|
require 'aws_pocketknife'
require 'base64'
require 'openssl'
require 'retryable'
require 'date'
require 'recursive-open-struct'
module AwsPocketknife
module Ecs
MAX_ATTEMPTS = 15
DELAY_SECONDS = 10
STATE_PENDING = 'pending'
STATE_AVAILABLE = 'available'
STATE_DEREGISTERED = 'deregistered'
STATE_INVALID = 'invalid'
STATE_FAILED = 'failed'
STATE_ERROR = 'error'
class << self
include AwsPocketknife::Common::Utils
Logging = Common::Logging.logger
# container instance
# set a list of instances to draining. instances is a comma delimited string
def drain_instances(cluster: '', names: '')
ecs_client.update_container_instances_state({
cluster: cluster,
container_instances: names.split(';'), # required
status: "DRAINING", # required, accepts ACTIVE, DRAINING
})
end
def describe_container_instances(cluster: '', container: '')
ecs_client.describe_container_instances({cluster: cluster, container_instances: [container]}).container_instances.first
end
# list container instances
def list_container_instances(cluster: '', max_results: 50)
containers_list = []
responses = []
containers = get_containers cluster: cluster, max_results: max_results
responses << containers.container_instance_arns
next_token = containers.next_token
while true
break if next_token.nil? or next_token.empty?
resp = get_containers(cluster: cluster, next_token: next_token, max_results: max_results)
responses << resp.container_instance_arns
next_token = resp.next_token
end
responses.flatten!
responses.each do |container|
container_map = {}
task_list = []
container_map[:name] = container.split('/')[1]
info = describe_container_instances cluster: cluster, container: container
container_map[:info] = info
#container_map[:tasks] = list_container_tasks(cluster: cluster, container_name: container_map[:name])
containers_list << container_map
end
return containers_list
end
# list tasks in container instance
def list_container_tasks(cluster: '', container_name: '')
tasks_list = []
tasks = list_tasks cluster: cluster, container_instance: container_name
describe_tasks(cluster: cluster, tasks: tasks)
end
# clusters
def describe_clusters(name: '')
ecs_client.describe_clusters({clusters: [name]}).clusters.first
end
def list_clusters(max_results: 50)
clusters_list = []
responses = []
clusters = get_clusters max_results: max_results
responses << clusters.cluster_arns
next_token = clusters.next_token
while true
break if next_token.nil? or next_token.empty?
resp = get_clusters(next_token: next_token, max_results: max_results)
responses << resp.cluster_arns
next_token = resp.next_token
end
responses.flatten!
responses.each do |cluster|
cluster_map = {}
cluster_map[:name] = cluster.split('/')[1]
info = describe_clusters name: cluster
cluster_map[:info] = info
clusters_list << cluster_map
end
return clusters_list
end
# services
def describe_services(name: '', cluster: '')
ecs_client.describe_services({cluster: cluster, services: [name]}).services.first
end
def create_service(payload: {})
ecs_client.create_service(payload)
end
def clone_service(name: '', cluster: '')
d = DateTime.now
date_fmt = d.strftime("%d%m%Y_%H%M%S")
current_service = describe_services name: name, cluster: cluster
new_name = "#{name}-clone-#{date_fmt}"
payload = {
cluster: cluster,
service_name: new_name,
task_definition: current_service.task_definition,
load_balancers: current_service.load_balancers.to_a,
desired_count: current_service.desired_count,
role: current_service.role_arn,
deployment_configuration: current_service.deployment_configuration.to_h,
placement_constraints: current_service.placement_constraints.to_a,
placement_strategy: current_service.placement_strategy.to_a,
}
puts "Cloned service payload:"
AwsPocketknife::Ecs.nice_print(object: payload.to_h)
create_service payload: payload
end
def list_services(cluster: '', max_results: 50)
services_list = []
responses = []
services = get_services max_results: max_results, cluster: cluster
responses << services.service_arns
next_token = services.next_token
while true
break if next_token.nil? or next_token.empty?
resp = get_services(next_token: next_token, max_results: max_results, cluster: cluster)
responses << resp.service_arns
next_token = resp.next_token
end
responses.flatten!
responses.each do |service|
service_map = {}
service_map[:name] = service.split('/')[1]
info = describe_services name: service, cluster: cluster
service_map[:info] = info
service_map[:task_definition] = describe_task_definition task_definition: info.task_definition
services_list << service_map
end
return services_list
end
# tasks-definitions
def describe_task_definition(task_definition: '')
resp = ecs_client.describe_task_definition({task_definition: task_definition})
return resp.task_definition.container_definitions.first
end
def list_tasks cluster: '', container_instance: ''
ecs_client.list_tasks({
cluster: cluster,
container_instance: container_instance,
}).task_arns
end
def describe_tasks cluster: '', tasks: []
if tasks.empty?
return []
else
return ecs_client.describe_tasks({
cluster: cluster,
tasks: tasks,
})
end
end
# helpers
def get_services(next_token: "", max_results: 100, cluster: '')
ecs_client.list_services({
max_results: max_results,
cluster: cluster,
next_token: next_token,
})
end
def get_clusters(next_token: "", max_results: 100)
ecs_client.list_clusters({
max_results: max_results,
next_token: next_token
})
end
def get_containers(cluster: "", next_token: "", max_results: 100)
ecs_client.list_container_instances({
max_results: max_results,
cluster: cluster,
next_token: next_token
})
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/cli/ami_spec.rb
|
<reponame>gustavosoares/aws_pocketknife<gh_stars>1-10
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Cli::Ami do
describe '#clean' do
let(:ami_name_pattern) {'test-*'}
let(:days) { '15' }
let(:dry_run) { true }
it 'should call clean_ami with dry_run true' do
allow(AwsPocketknife::Ec2).to receive(:clean_ami).with(ami_name_pattern: ami_name_pattern,
days: days,
dry_run: dry_run)
expect(AwsPocketknife::Ec2).to receive(:clean_ami).with(ami_name_pattern: ami_name_pattern,
days: days,
dry_run: dry_run)
subject.clean ami_name_pattern, days
end
it 'should call clean_ami with dry_run false' do
dry_run = false
allow(AwsPocketknife::Ec2).to receive(:clean_ami).with(ami_name_pattern: ami_name_pattern,
days: days,
dry_run: dry_run)
expect(AwsPocketknife::Ec2).to receive(:clean_ami).with(ami_name_pattern: ami_name_pattern,
days: days,
dry_run: dry_run)
subject.options = {"dry_run" => dry_run}
subject.clean ami_name_pattern, days
end
end
describe '#share' do
let(:image_id) {'i-1'}
let(:account_id) {'12345678'}
it 'should call share with right arguments' do
allow(AwsPocketknife::Ec2).to receive(:share_ami).with(image_id: image_id, user_id: account_id)
expect(AwsPocketknife::Ec2).to receive(:share_ami).with(image_id: image_id, user_id: account_id)
subject.share image_id, account_id
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/iam.rb
|
<filename>lib/aws_pocketknife/iam.rb
require 'erubis'
require 'aws_pocketknife'
module AwsPocketknife
module Iam
class << self
include AwsPocketknife::Common::Utils
def list_ssl_certificates
iam_client.list_server_certificates({})
end
def create_iam_user(username)
puts "Creating iam user: #{username}"
iam_client.create_user({user_name: username})
puts "Iam user: #{username} created"
end
def create_group(group_name)
puts "Creating group: #{group_name}"
iam_client.create_group({group_name: group_name})
puts "Created group: #{group_name}"
end
def create_policy(policy_name, policy)
puts "Creating policy: #{policy_name}"
iam_client.create_policy({policy_name: policy_name,policy_document: policy})
puts "Created policy: #{policy_name}"
end
def create_policy_from_policy_file(policy_name: "", policy_file: "", s3_buckets: "")
puts "Creating policy #{policy_name} from saved policy #{policy_file}"
policy = IO.read(policy_file)
buckets = get_bucket_list(buckets_list: s3_buckets)
template = Erubis::Eruby.new(policy)
vars = {buckets: buckets}
policy = template.result(vars)
puts policy
unless (policy.nil?)
iam_client.create_policy({policy_name: policy_name, policy_document: policy})
else
puts 'Policy not found'
end
puts "Created Policy #{policy_name}"
end
def attach_policy_to_group(policy_name, group_name )
puts "Attaching policy #{policy_name} to group #{group_name}"
arn_number = get_policy_arn(policy_name)
unless arn_number.nil?
iam_client.attach_group_policy(group_name: group_name, policy_arn: arn_number)
else
puts "The policy #{policy_name} could not be found"
end
puts "Policy #{policy_name} attached to group #{group_name}"
end
def add_user_to_group(username,group_name)
puts "Attaching user: #{username} to group: #{group_name}"
iam_client.add_user_to_group(group_name: group_name, user_name: username)
puts "User: #{username} attached to group: #{group_name}"
end
def create_role(role_name, trust_relationship_file)
begin
if File.exist?(trust_relationship_file)
trust_relationship = IO.read(trust_relationship_file)
unless trust_relationship.nil?
puts "Creating role: #{role_name} with trust relationship #{trust_relationship}"
iam_client.create_role(role_name: role_name, assume_role_policy_document: trust_relationship)
puts "Created role: #{role_name} with trust relationship #{trust_relationship}"
else
raise "Trust Relationship file could not be loaded"
end
else
raise "Trust Relationship file could not be loaded"
end
rescue Exception => e
puts e
raise e
end
end
def attach_policy_to_role(role_name, policy_name)
arn_number = get_policy_arn(policy_name)
unless arn_number.nil?
puts "Attach policy: #{policy_name} to role: #{role_name}"
iam_client.attach_role_policy(role_name: role_name, policy_arn: arn_number)
puts "Attached policy: #{policy_name} to role: #{role_name}"
else
raise "The policy #{policy_name} could not be found"
end
end
def create_instance_profile(instance_profile_name)
puts "Creating instance profile: #{instance_profile_name}"
iam_client.create_instance_profile(instance_profile_name: instance_profile_name)
puts "Created instance profile: #{instance_profile_name}"
end
def add_role_to_instance_profile(role_name,instance_profile_name)
puts "Adding role #{role_name} to instance profile: #{instance_profile_name}"
iam_client.add_role_to_instance_profile(instance_profile_name: instance_profile_name, role_name: role_name)
puts "Added role #{role_name} to instance profile: #{instance_profile_name}"
end
private
def get_bucket_list(buckets_list: "")
buckets_list.strip.split(";")
end
def get_policy_arn(policy_name)
response = iam_client.list_policies({scope: 'Local'})
arn_number = nil
response.policies.each do |value|
if value.policy_name == policy_name
arn_number = value.arn
break;
end
end
arn_number
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/ec2.rb
|
require 'aws_pocketknife'
require 'base64'
require 'openssl'
require 'retryable'
require 'recursive-open-struct'
module AwsPocketknife
module Ec2
MAX_ATTEMPTS = 15
DELAY_SECONDS = 10
STATE_PENDING = 'pending'
STATE_AVAILABLE = 'available'
STATE_DEREGISTERED = 'deregistered'
STATE_INVALID = 'invalid'
STATE_FAILED = 'failed'
STATE_ERROR = 'error'
class << self
include AwsPocketknife::Common::Utils
#include AwsPocketknife::Common::Logging
Logging = Common::Logging.logger
def find_ami_by_name(name: '')
ec2_client.describe_images({dry_run: false,
filters: [
{
name: "tag:Name",
values: [name]
}
]}).images
end
def find_ami_by_id(id: '')
ec2_client.describe_images({dry_run: false,
image_ids: [id]}).images.first
end
def delete_ami_by_id(id: '')
Logging.info "deleting image #{id}"
image = find_ami_by_id(id: id)
snapshot_ids = snapshot_ids(image)
ec2_client.deregister_image(image_id: id)
Retryable.retryable(:tries => 20, :sleep => lambda { |n| 2**n }, :on => StandardError) do |retries, exception|
image = find_ami_by_id(id: id)
message = "retry #{retries} - Deleting image #{id}"
message << " State: #{image.state}" if image
Logging.info message
raise StandardError unless image.nil?
end
delete_snapshots(snapshot_ids: snapshot_ids)
end
def delete_snapshots(snapshot_ids: [])
snapshot_ids.each do |snapshot_id|
Logging.info "Deleting Snapshot: #{snapshot_id}"
ec2_client.delete_snapshot(snapshot_id: snapshot_id)
end
end
def snapshot_ids(image)
snapshot_ids = []
image.block_device_mappings.each do |device_mapping|
ebs = device_mapping.ebs
snapshot_ids << ebs.snapshot_id if ebs && !ebs.snapshot_id.to_s.empty?
end
snapshot_ids
end
def clean_ami(options)
Logging.info "options: #{options}"
dry_run = options.fetch(:dry_run, true)
Logging.info "Finding AMIs by creation time"
image_ids = find_ami_by_creation_time(options)
Logging.info "Done. Finding unusued AMIs now..."
images_to_delete = find_unused_ami(image_ids: image_ids)
Logging.info "images (#{image_ids.length}): #{image_ids}"
Logging.info "images to delete (#{images_to_delete.length}): #{images_to_delete}"
unless dry_run
images_to_delete.each do |image_id|
delete_ami_by_id(id: image_id)
end
end
end
def find_unused_ami(image_ids: [])
images_to_delete = []
image_ids.each do |image_id|
# check if there is any instance using the image id
Logging.info "Checking if #{image_id} can be deleted..."
instances = describe_instances_by_image_id(image_id_list: [image_id])
if instances.empty?
images_to_delete << image_id
else
Logging.info "#{image_id} is used by instance #{instances.map { |instance| instance.instance_id }}"
end
Kernel.sleep 2
end
return images_to_delete
end
def find_ami_by_creation_time(options)
days = options.fetch(:days, '30').to_i * 24 * 3600
creation_time = Time.now-days
Logging.info "Cleaning up images older than #{days} days, i.e, with creation_time < #{creation_time})"
image_ids = []
images = find_ami_by_name(name: options.fetch(:ami_name_pattern, ''))
images.each do |image|
image_creation_time = Time.parse(image.creation_date)
msg = "image #{image.name} (#{image.image_id}) (image_creation_time: #{image_creation_time}) < (#{creation_time}) ? "
if image_creation_time <= creation_time
image_ids << image.image_id
msg << "YES, marking to be deleted"
else
msg << "NO"
end
Logging.info msg
end
Logging.info "Done reading AMIs"
return image_ids
end
def share_ami(image_id: '', user_id: '', options: {})
begin
options = {}
options[:image_id] = image_id
options[:launch_permission] = create_launch_permission(user_id)
Logging.info "Sharing Image #{image_id} with #{user_id} with options #{options}"
response = @ec2_client.modify_image_attribute(options=options)
return response
rescue Exception => e
Logging.error "## Got an error when sharing the image... #{e.cause} -> #{e.message}"
raise
end
end
def create_image(instance_id: "", name: "", description: "Created at #{Time.now}",
timeout: 1800, publish_to_account: "",
volume_type: "gp2",
iops: 3,
encrypted: false,
volume_size: 60
)
begin
Logging.info "creating image"
instance = find_by_id(instance_id: instance_id)
instance = ec2.instances[instance_id]
image = instance.create_image(name, :description => description)
sleep 2 until image.exists?
Logging.info "image #{image.id} state: #{image.state}"
sleep 10 until image.state != :pending
if image.state == :failed
raise "Create image failed"
end
Logging.info "image created"
rescue => e
Logging.error "Creating AMI failed #{e.message}"
Logging.error e.backtrace.join("\n")
raise e
end
if publish_to_account.length != 0
Logging.info "add permissions for #{publish_to_account}"
image.permissions.add(publish_to_account.gsub(/-/, ''))
end
image.id.tap do |image_id|
Logging.info "Image #{@name}[#{image_id}] created"
return image_id
end
end
def stop_instance_by_id(instance_ids)
instance_id_list = get_instance_id_list(instance_ids: instance_ids)
Logging.info "Stoping instance id: #{instance_id_list}"
resp = ec2_client.stop_instances({ instance_ids: instance_id_list })
wait_till_instance_is_stopped(instance_id_list, max_attempts: MAX_ATTEMPTS, delay_seconds: DELAY_SECONDS)
Logging.info "Stopped ec2 instance #{instance_id_list}"
end
def start_instance_by_id(instance_ids)
instance_id_list = get_instance_id_list(instance_ids: instance_ids)
Logging.info "Start instance id: #{instance_id_list}"
ec2_client.start_instances({ instance_ids: instance_id_list })
end
# http://serverfault.com/questions/560337/search-ec2-instance-by-its-name-from-aws-command-line-tool
def find_by_name(name: "")
instances = []
resp = ec2_client.describe_instances({dry_run: false,
filters: [
{
name: "tag:Name",
values: [name]
}
]})
resp.reservations.each do |reservation|
reservation.instances.each do |instance|
instances << instance
end
end
instances
end
def describe_instances_by_image_id(image_id_list: [])
instances = []
resp = ec2_client.describe_instances({dry_run: false,
filters: [
{
name: "image-id",
values: image_id_list
}
]})
resp.reservations.each do |reservation|
reservation.instances.each do |instance|
instances << instance
end
end
instances
end
def find_by_id(instance_id: "")
resp = ec2_client.describe_instances({dry_run: false, instance_ids: [instance_id.to_s]})
if resp.nil? or resp.reservations.length == 0 or resp.reservations[0].instances.length == 0
return nil
else
return resp.reservations.first.instances.first
end
end
def get_windows_password(instance_id: "")
private_keyfile_dir = ENV["AWS_POCKETKNIFE_KEYFILE_DIR"] || ""
raise "Environment variable AWS_POCKETKNIFE_KEYFILE_DIR is not defined" if private_keyfile_dir.length == 0
instance = find_by_id(instance_id: instance_id)
key_name = instance.key_name
private_keyfile = File.join(private_keyfile_dir, "#{key_name}.pem")
raise "File #{private_keyfile} not found" unless File.exist?(private_keyfile)
resp = ec2_client.get_password_data({dry_run: false,
instance_id: instance_id})
encrypted_password = resp.password_data
decrypted_password = decrypt_windows_password(encrypted_password, private_keyfile)
RecursiveOpenStruct.new({password: <PASSWORD>,
instance_id: instance.instance_id,
private_ip_address: instance.private_ip_address,
public_ip_address: instance.public_ip_address}, recurse_over_arrays: true)
end
# def ec2
# @ec2 ||= Aws::EC2.new(:ec2_endpoint => "ec2.#{AwsPocketknife::AWS_REGION}.amazonaws.com")
# end
private
def create_launch_permission(user_id)
{
add: [
{
user_id: user_id
},
]
}
end
# Decrypts an encrypted password using a provided RSA
# private key file (PEM-format).
def decrypt_windows_password(encrypted_password, private_keyfile)
encrypted_password_bytes = Base64.decode64(encrypted_password)
private_keydata = File.open(private_keyfile, "r").read
private_key = OpenSSL::PKey::RSA.new(private_keydata)
private_key.private_decrypt(encrypted_password_bytes)
end
def get_instance_id_list(instance_ids: "")
instance_ids.strip.split(";")
end
def wait_till_instance_is_stopped(instance_ids, max_attempts: 12, delay_seconds: 10)
total_wait_seconds = max_attempts * delay_seconds;
Logging.info "Waiting up to #{total_wait_seconds} seconds with #{delay_seconds} seconds delay for ec2 instance #{instance_ids} to be stopped"
ec2_client.wait_until(:instance_stopped, { instance_ids: instance_ids }) do |w|
w.max_attempts = max_attempts
w.delay = delay_seconds
end
end
def wait_till_instance_is_terminated(instance_ids, max_attempts: 12, delay_seconds: 10)
total_wait_seconds = max_attempts * delay_seconds;
Logging.info "Waiting up to #{total_wait_seconds} seconds with #{delay_seconds} seconds delay for ec2 instance #{instance_ids} to be terminated"
ec2_client.wait_until(:instance_terminated, { instance_ids: instance_ids }) do |w|
w.max_attempts = max_attempts
w.delay = delay_seconds
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/rds.rb
|
<reponame>gustavosoares/aws_pocketknife<filename>lib/aws_pocketknife/rds.rb
require 'aws_pocketknife'
module AwsPocketknife
module Rds
AVAILABLE = 'available'.freeze
CREATING = 'creating'.freeze
DELETING = 'deleting'.freeze
class << self
include AwsPocketknife::Common::Utils
def describe_snapshots(options)
db_name = options.fetch(:db_name, '')
rds_client.describe_db_snapshots({db_instance_identifier: db_name}).db_snapshots
end
# creates snapshot for the database name
def create_snapshot(options)
db_name = options.fetch(:db_name, 'my-snapshot')
snapshot_name = get_snapshot_name(db_name)
rds_client.create_db_snapshot(db_instance_identifier: db_name, db_snapshot_identifier: snapshot_name)
Retryable.retryable(:tries => 15, :sleep => lambda { |n| 2**n }, :on => StandardError) do |retries, exception|
response = rds_client.describe_db_snapshots(db_snapshot_identifier: snapshot_name)
snapshot = response.db_snapshots.find { |s| s.db_snapshot_identifier == snapshot_name }
status = snapshot.status
percent_progress = snapshot.percent_progress
puts "RDS Snapshot #{snapshot_name} status: #{status}, progress #{percent_progress}%"
raise StandardError if status != AwsPocketknife::Rds::AVAILABLE
end
end
def get_snapshot_name(db_name)
now_str = Time.now.strftime('%Y-%m-%d-%H-%M')
"#{db_name}-#{now_str}"
end
def clean_snapshots(options)
puts "options: #{options}"
db_name = options.fetch(:db_name, '')
days = options.fetch(:days, '30').to_i * 24 * 3600
dry_run = options.fetch(:dry_run, true)
creation_time = Time.now - days
puts "Cleaning up MANUAL snapshots older than #{days} days, i.e, with creation_time < #{creation_time} for db [#{db_name}]"
snapshots_to_remove = []
snapshots = describe_snapshots options
snapshots.each do |snapshot|
snapshot.snapshot_create_time.is_a?(String) ? snapshot_creation_time = Time.parse(snapshot.snapshot_create_time) : snapshot_creation_time = snapshot.snapshot_create_time
msg = "Snapshot #{snapshot.db_snapshot_identifier} (type=#{snapshot.snapshot_type}) (snapshot_creation_time: #{snapshot_creation_time}) > (#{creation_time})? "
if creation_time <= snapshot_creation_time
if (snapshot.snapshot_type == 'manual')
snapshots_to_remove << snapshot
msg << " YES, marking to be deleted"
else
msg << " NO"
end
else
msg << "NO (is not a manual snapshot)"
end
puts msg
end
puts "snapshots_to_remove: #{snapshots_to_remove.map { |s| s.db_snapshot_identifier}}"
unless dry_run
snapshots_to_remove.each do |snapshot|
puts "Removing snapshot #{snapshot.db_snapshot_identifier} (status=#{snapshot.status})"
rds_client.delete_db_snapshot({db_snapshot_identifier:snapshot.db_snapshot_identifier})
end
end
end
end
end
end
|
gustavosoares/aws_pocketknife
|
aws_pocketknife.gemspec
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'aws_pocketknife/version'
Gem::Specification.new do |spec|
spec.name = "aws_pocketknife"
spec.version = AwsPocketknife::VERSION
spec.authors = ["<NAME>"]
spec.email = ["<EMAIL>"]
spec.summary = "Command line tools to make aws administration a little bit easier and faster than using the aws consol or aws cli."
spec.description = "Have you ever find yourself going through the aws cli documentation page over and over again just to remember the right syntax or argument(s) for that command that you wanna run? Do you feel that you are more productive from the command line? Are you tired of having to open private browser windows or even a different browser to work with multiple aws accounts? AWS Pocketknife is a command line tool to make aws administration a little bit easier and faster than using the aws console or aws cli. It also helps to script some AWS tasks such as cleaning up
old AMIs along its snapshots or cleaning up manual RDS snapshots or even creating a manual snapshot for a particular RDS.
These commands are also handy if you have multiple aws accounts to manage, since you can't have multiple tabs open for
different accounts in a web browser. The only way would be to use diffente browsers or open incognito windows."
spec.homepage = "https://github.com/gustavosoares/aws_pocketknife"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency 'aws-sdk-core', '~> 2.9'
spec.add_dependency 'retryable', '~> 2.0'
spec.add_dependency "rake", "~> 10.0"
spec.add_dependency "colorize", "= 0.8.1"
spec.add_dependency "erubis", "= 2.7.0"
spec.add_dependency "pretty_table", "= 0.1.0"
spec.add_dependency "awesome_print", "= 1.6.1"
spec.add_dependency "recursive-open-struct", "= 1.0.1"
spec.add_dependency "log4r", "= 1.1.10"
spec.add_dependency "thor", "~> 0.19"
spec.add_development_dependency "bundler", "~> 1.11"
spec.add_development_dependency "rspec", "~> 3.4"
spec.add_development_dependency "debase", "= 0.2.2.beta6"
spec.add_development_dependency "webmock", "= 1.24.2"
end
|
gustavosoares/aws_pocketknife
|
spec/ec2_spec.rb
|
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Ec2 do
let(:snapshot_id) { 'snap-12345678' }
let(:image_id) {'ami-1234567'}
let(:instance_id) {'i-1234'}
let(:user_id) { '12345678' }
let(:ec2_client) {instance_double(Aws::EC2::Client)}
before (:each) do
allow(AwsPocketknife::Ec2).to receive(:ec2_client).and_return(ec2_client)
end
describe '#share_ami' do
it 'should call modify_image_attribute with success' do
end
end
describe '#find_unused_ami' do
let(:image_ids) {['1', '2', '3']}
before (:each) do
allow(Kernel).to receive(:sleep)
end
it 'should return list with ami that can be deleted' do
first_response = [get_instance_response(instance_id: 'i-1')]
second_response = [get_instance_response(instance_id: 'i-2')]
third_response = []
allow(AwsPocketknife::Ec2).to receive(:describe_instances_by_image_id).and_return(first_response, second_response, third_response)
images_to_delete = AwsPocketknife::Ec2.find_unused_ami(image_ids: image_ids)
expect(images_to_delete).to eq(['3'])
end
it 'should return empty list when all amis are in use' do
first_response = [get_instance_response(instance_id: 'i-1')]
second_response = [get_instance_response(instance_id: 'i-2')]
allow(AwsPocketknife::Ec2).to receive(:describe_instances_by_image_id).and_return(first_response, second_response)
images_to_delete = AwsPocketknife::Ec2.find_unused_ami(image_ids: image_ids)
expect(images_to_delete).to eq([])
end
end
describe '#find_ami_by_creation_time' do
let(:days) {'15'}
let(:ami_name_pattern) {'test-*'}
let(:options) { {days: days, ami_name_pattern: ami_name_pattern} }
it 'should return list of amis with creation time greater than days' do
first_response = get_image_response image_id: '1', date: '2013-12-16 11:57:42 +1100'
second_response = get_image_response image_id: '2', date: '2040-12-16 11:57:42 +1100'
allow(subject).to receive(:find_ami_by_name).and_return([first_response, second_response])
image_ids = subject.find_ami_by_creation_time(options)
expect(image_ids).to eq(['2'])
end
it 'should return empty list when no AMIs can be found with creation time greater than days' do
first_response = get_image_response image_id: '1', date: '2013-12-15 11:57:42 +1100'
second_response = get_image_response image_id: '2', date: '2013-12-16 11:57:42 +1100'
allow(subject).to receive(:find_ami_by_name).and_return([first_response, second_response])
image_ids = subject.find_ami_by_creation_time(options)
expect(image_ids).to eq([])
end
end
describe '#delete_ami_by_id' do
it 'should delete ami with sucess' do
first_response = get_image_response image_id: '1', date: '2013-12-15 11:57:42 +1100', state: AwsPocketknife::Ec2::STATE_PENDING
second_response = get_image_response image_id: '1', date: '2013-12-15 11:57:42 +1100', state: AwsPocketknife::Ec2::STATE_PENDING
third_response = get_image_response image_id: '1', date: '2013-12-15 11:57:42 +1100', state: AwsPocketknife::Ec2::STATE_DEREGISTERED
fourth_response = get_image_response image_id: ''
allow(subject).to receive(:find_ami_by_id).and_return(first_response, second_response, third_response, fourth_response)
allow(ec2_client).to receive(:deregister_image).with(image_id: image_id)
allow(ec2_client).to receive(:deregister_image).with(image_id: image_id)
allow(Kernel).to receive(:sleep)
expect(ec2_client).to receive(:delete_snapshot).with(snapshot_id: snapshot_id)
expect(subject).to receive(:find_ami_by_id).with(id: image_id).exactly(4).times()
subject.delete_ami_by_id(id: image_id)
end
end
describe '#stop_instance_by_id' do
it 'should stop one instance' do
instance_id = "1"
allow(subject).to receive(:wait_till_instance_is_stopped).and_return("mock")
allow(ec2_client).to receive(:stop_instances).with({ instance_ids: ["1"] })
expect(ec2_client).to receive(:stop_instances).with({ instance_ids: ["1"] })
subject.stop_instance_by_id(instance_id)
end
it 'should stop list of instances' do
instance_id = "1;2;3"
allow(subject).to receive(:wait_till_instance_is_stopped).and_return("mock")
allow(ec2_client).to receive(:stop_instances).with({ instance_ids: ["1", "2", "3"] })
expect(ec2_client).to receive(:stop_instances).with({ instance_ids: ["1", "2", "3"] })
subject.stop_instance_by_id(instance_id)
end
end
describe '#start_instance_by_id' do
it 'should start one instance' do
instance_id = "1"
allow(ec2_client).to receive(:start_instances).with({ instance_ids: ["1"] })
expect(ec2_client).to receive(:start_instances).with({ instance_ids: ["1"] })
subject.start_instance_by_id(instance_id)
end
it 'should start list of instances' do
instance_id = "1;2;3"
allow(ec2_client).to receive(:start_instances).with({ instance_ids: ["1", "2", "3"] })
expect(ec2_client).to receive(:start_instances).with({ instance_ids: ["1", "2", "3"] })
subject.start_instance_by_id(instance_id)
end
end
describe '#describe_instances_by_name' do
it 'should describe instances by name' do
name = "test"
aws_response = get_aws_response({reservations: [
{instances: [{instance_id: instance_id}]}
]})
allow(ec2_client).to receive(:describe_instances)
.with({dry_run: false,
filters: [
{
name: "tag:Name",
values: [name]
}
]})
.and_return(aws_response)
instances = subject.find_by_name(name: name)
expect(instances.first.instance_id).to eq(instance_id)
end
end
describe '#describe_instance_by_id' do
it 'should return nil when instance id is not found' do
instance_id = "i-test"
aws_response = get_aws_response({reservations: [
{instances: []}
]})
allow(ec2_client).to receive(:describe_instances)
.with({dry_run: false, instance_ids: [instance_id]})
.and_return(aws_response)
instance = subject.find_by_id(instance_id: instance_id)
expect(instance).to eq(nil)
end
it 'should return instance' do
instance_id = "i-test"
aws_response = RecursiveOpenStruct.new({reservations: [
{instances: [{instance_id: instance_id}]}
]}, recurse_over_arrays: true)
allow(ec2_client).to receive(:describe_instances)
.with({dry_run: false, instance_ids: [instance_id]})
.and_return(aws_response)
instance = subject.find_by_id(instance_id: instance_id)
expect(instance).to_not eq(nil)
expect(instance.instance_id).to eq(instance_id)
end
end
describe '#get_windows_password' do
let (:instance_id) { "i-test" }
it 'should retrieve windows password with success' do
private_keyfile_dir = "dir"
key_name = "my_key"
encrypted_password = "<PASSWORD>"
private_keyfile = "test"
aws_response = get_aws_response({password_data: encrypted_password})
allow(ec2_client).to receive(:get_password_data).with({dry_run: false, instance_id: instance_id})
.and_return(aws_response)
allow(ENV).to receive(:[]).with("AWS_POCKETKNIFE_KEYFILE_DIR").and_return(private_keyfile_dir)
allow(subject).to receive(:find_by_id)
.with(instance_id: instance_id)
.and_return(RecursiveOpenStruct.new({key_name: key_name},
recurse_over_arrays: true))
allow(File).to receive(:exist?)
.with("test").and_return(true)
allow(File).to receive(:join)
.with(private_keyfile_dir, "#{key_name}.pem").and_return(private_keyfile)
allow(subject).to receive(:decrypt_windows_password)
.with(encrypted_password, private_keyfile)
.and_return("<PASSWORD>")
instance = subject.get_windows_password(instance_id: instance_id)
expect(instance.password).to eq("<PASSWORD>")
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/cloudwatch_logs_spec.rb
|
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::CloudwatchLogs do
let(:cloudwatch_logs_client) {instance_double(Aws::CloudWatchLogs::Client)}
before (:each) do
allow(subject).to receive(:cloudwatch_logs_client).and_return(cloudwatch_logs_client)
end
describe '#create_log_group' do
it 'should create log group given a log group name' do
log_group_name = "test"
allow(cloudwatch_logs_client).to receive(:create_log_group)
.with({
log_group_name: log_group_name, # required
})
expect(cloudwatch_logs_client).to receive(:create_log_group)
.with({
log_group_name: log_group_name, # required
})
subject.create_log_group(log_group_name: log_group_name)
end
it 'should not create log group when log group name is empty' do
log_group_name = ''
expect(cloudwatch_logs_client).not_to receive(:create_log_group)
subject.create_log_group(log_group_name: log_group_name)
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/rds_snapshot.rb
|
<gh_stars>1-10
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class RdsSnapshot < Thor
desc "list DB_NAME", "list snapshots for a given database name."
def list(db_name)
snapshots = AwsPocketknife::Rds.describe_snapshots(db_name: db_name)
headers = [ 'Name', 'Creation Time', 'Snapshot Type', 'Status','Port', 'Engine', 'Version', 'Storage (Gb)', 'IOPS']
data = []
snapshots.each do |h|
data << [h.db_snapshot_identifier,
h.snapshot_create_time,
h.snapshot_type,
h.status,
h.port,
h.engine,
h.engine_version,
h.allocated_storage,
h.iops
]
end
AwsPocketknife::Rds.pretty_table(headers: headers, data: data)
end
desc "clean DB_NAME DAYS --dry_run", "Remove manual snapshots with creation time lower than DAYS for database_name."
option :dry_run, :type => :boolean, :default => true, :desc => 'just show images that would be deleted'
def clean(db_name, days)
dry_run = options.fetch("dry_run", true)
AwsPocketknife::Rds.clean_snapshots db_name: db_name,
days: days,
dry_run: dry_run
end
desc "create DB_NAME", "Creates a snapshot for database name."
def create(db_name)
AwsPocketknife::Rds.create_snapshot db_name: db_name
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/cli/iam_spec.rb
|
<filename>spec/cli/iam_spec.rb
require 'rspec'
require 'spec_helper'
describe AwsPocketknife::Cli::Iam do
let(:username) {'user'}
let(:group_name) {'group'}
describe '#list_ssl_certs' do
it 'should call list_ssl_certs with the right arguments' do
allow(AwsPocketknife::Iam).to receive(:list_ssl_certificates)
expect(AwsPocketknife::Iam).to receive(:list_ssl_certificates)
subject.list_ssl_certs
end
end
describe '#create_user' do
it 'should call method with the right arguments' do
allow(AwsPocketknife::Iam).to receive(:create_iam_user).with(username)
expect(AwsPocketknife::Iam).to receive(:create_iam_user).with(username)
subject.create_user username
end
end
describe '#create_group' do
it 'should call method with the right arguments' do
allow(AwsPocketknife::Iam).to receive(:create_group).with(group_name)
expect(AwsPocketknife::Iam).to receive(:create_group).with(group_name)
subject.create_group group_name
end
end
describe '#add_user_to_group' do
it 'should call method with the right arguments' do
allow(AwsPocketknife::Iam).to receive(:add_user_to_group).with(username, group_name)
expect(AwsPocketknife::Iam).to receive(:add_user_to_group).with(username, group_name)
subject.add_user_to_group username, group_name
end
end
end
|
gustavosoares/aws_pocketknife
|
lib/aws_pocketknife/cli/iam.rb
|
<filename>lib/aws_pocketknife/cli/iam.rb
require "thor"
require "aws_pocketknife"
module AwsPocketknife
module Cli
class Iam < Thor
desc "list_ssl_certs", "list ssl certs"
def list_ssl_certs
certs = AwsPocketknife::Iam.list_ssl_certificates
AwsPocketknife::Iam.nice_print(object: certs.to_h)
end
desc "create_user USERNAME", "create user"
def create_user(username)
AwsPocketknife::Iam.create_iam_user username
end
desc "create_group GROUP_NAME", "create group"
def create_group(group_name)
AwsPocketknife::Iam.create_group group_name
end
desc "add_user_to_group USERNAME GROUP_NAME", "add user to group"
def add_user_to_group(username, group_name)
AwsPocketknife::Iam.add_user_to_group username, group_name
end
end
end
end
|
gustavosoares/aws_pocketknife
|
spec/iam_spec.rb
|
require 'rspec'
require "rspec/expectations"
require 'spec_helper'
describe AwsPocketknife::Iam do
describe "#create_user" do
it 'Create an iam user with the supplied username' do
# Setup
user = 'testUser'
# Act
# Verify
expect_any_instance_of(Aws::IAM::Client).to receive(:create_user).with({user_name:user})
AwsPocketknife::Iam.create_iam_user(user)
end
end
describe "#create_policy" do
it 'Should create a policy within aws with the supplied policy name and policy' do
policy_name = 'testUser'
policy = '{
"Version": "2012-10-17",
"Statement": [
{
"Action": "ec2:*",
"Effect": "Allow",
"Resource": "*"
}
]
}'
expect_any_instance_of(Aws::IAM::Client).to receive(:create_policy).with({policy_name:policy_name,policy_document:policy})
AwsPocketknife::Iam.create_policy(policy_name,policy)
end
it 'Should create a policy within aws from a saved policy file' do
policy_name = 'testUser'
s3_buckets = "bucket1;bucket2"
policy_file = "devops.json"
io_read = '{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
<% buckets.first(buckets.length-1).each do |bucket| %>
"<%= bucket %>",
<% end %>
"<%= buckets.reverse[0] %>"
]
},'
allow(IO).to receive(:read).with(File.join(policy_file)).and_return(io_read)
policy = '{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"bucket1",
"bucket2"
]
},'
expect_any_instance_of(Aws::IAM::Client).to receive(:create_policy).with({policy_name:policy_name, policy_document:policy})
AwsPocketknife::Iam.create_policy_from_policy_file(policy_name: policy_name, policy_file: policy_file, s3_buckets: s3_buckets)
end
end
describe "#attach_policy_to_group" do
it 'Should attach a policy defined within aws to a user'do
# Setup
group_name = 'testGroup'
policy_name = 'testPolicy'
arn_number = '123'
# Verify
allow(AwsPocketknife::Iam).to receive(:get_policy_arn).with(policy_name).and_return(arn_number)
expect_any_instance_of(Aws::IAM::Client).to receive(:attach_group_policy).with(group_name: group_name, policy_arn: arn_number)
AwsPocketknife::Iam.attach_policy_to_group(policy_name, group_name)
end
it 'Should log when the policy cannot be found' do
# Setup
# Setup
group_name = 'testGroup'
policy_name = 'testPolicy'
# Act
printed = capture_stdout do
AwsPocketknife::Iam.attach_policy_to_group(policy_name, group_name)
end
# Verify
expect(printed).to include("The policy #{policy_name} could not be found")
end
end
describe "#add_user_to_group" do
it 'Should associate the defined user and group together'do
# Setup
group_name = 'testGroup'
username = 'testuser'
# Act
expect_any_instance_of(Aws::IAM::Client).to receive(:add_user_to_group).with({group_name:group_name,user_name:username})
printed = capture_stdout do
AwsPocketknife::Iam.add_user_to_group(username,group_name)
end
# Assert
expect(printed).to include("Attaching user: #{username} to group: #{group_name}")
end
end
describe "#create_role"do
#Need to be able to load a file which dir are tests run from ?
it 'should create a row within aws using the specified role name and policy'do
# Setup
role_name = "testRole"
trust_relationship_file = "file.json"
trust_relationship = "mock"
allow(IO).to receive(:read).with(trust_relationship_file).and_return(trust_relationship)
allow(File).to receive(:exist?).with(trust_relationship_file).and_return(true)
expect_any_instance_of(Aws::IAM::Client).to receive(:create_role).with(role_name: role_name, assume_role_policy_document: trust_relationship)
# Act
printed = capture_stdout do
AwsPocketknife::Iam.create_role(role_name,trust_relationship_file)
end
# Assert
expect(printed).to include("Creating role: #{role_name} with trust relationship #{trust_relationship}")
expect(printed).to include("Created role: #{role_name} with trust relationship #{trust_relationship}")
end
it 'should not create role when trust relationship document cannot be loaded' do
# Setup
role_name = "testRole"
trust_relationship_file = 'trustrelationshipfile'
# Act
expect{AwsPocketknife::Iam.create_role(role_name,trust_relationship_file)}.to raise_error(message= "Trust Relationship file could not be loaded")
end
end
describe "#attach_policy_to_role" do
it 'Should attach the supplied policy to supplied role' do
# Setup
role = 'role'
policy = 'policy'
# Act
allow(AwsPocketknife::Iam).to receive(:get_policy_arn).and_return('123')
expect_any_instance_of(Aws::IAM::Client).to receive(:attach_role_policy).with({role_name:role,policy_arn:'123'})
# Act
printed = capture_stdout do
AwsPocketknife::Iam.attach_policy_to_role(role,policy)
end
end
it 'should throw and exception when the arn number of the policy cannot be found'do
# Setup
role = 'role'
policy = 'policy'
# Act
allow(AwsPocketknife::Iam).to receive(:get_policy_arn).and_return(nil)
expect{AwsPocketknife::Iam.attach_policy_to_role(role,policy)}.to raise_error(message="The policy #{policy} could not be found")
end
end
describe "#create_instance_profile"do
it 'should add an instance profile within aws with the supplied instance profile name'do
instance_profile_name = 'instanceProfileName'
expect_any_instance_of(Aws::IAM::Client).to receive(:create_instance_profile).with(instance_profile_name: instance_profile_name)
# Act
printed = capture_stdout do
AwsPocketknife::Iam.create_instance_profile(instance_profile_name)
end
# Assert
expect(printed).to include("Creating instance profile: #{instance_profile_name}")
expect(printed).to include("Created instance profile: #{instance_profile_name}")
end
end
describe "#add_role_to_instance_profile"do
it 'should add the supplied role to the supplied instance profile'do
instance_profile_name = 'instanceProfileName'
role_name = 'roleName'
expect_any_instance_of(Aws::IAM::Client).to receive(:add_role_to_instance_profile).with(instance_profile_name: instance_profile_name, role_name: role_name)
# Act
printed = capture_stdout do
AwsPocketknife::Iam.add_role_to_instance_profile(role_name, instance_profile_name)
end
# Assert
expect(printed).to include("Adding role #{role_name} to instance profile: #{instance_profile_name}")
expect(printed).to include("Added role #{role_name} to instance profile: #{instance_profile_name}")
end
end
end
|
mruby-plato-mgem/mruby-plato-serial-enzi
|
test/serial.rb
|
# PlatoEnzi::Serial class
module ENZI
class Serial
def initialize(baud); end
def read; -1; end
def write(v); v; end
def available; 0; end
def flush; end
def close; end
end
end
assert('Serial', 'class') do
assert_equal(PlatoEnzi::Serial.class, Class)
end
assert('Serial', 'superclass') do
assert_equal(PlatoEnzi::Serial.superclass, Object)
end
assert('Serial', 'new') do
ser1 = PlatoEnzi::Serial.new(9600)
ser2 = PlatoEnzi::Serial.new(19200, 7)
ser3 = PlatoEnzi::Serial.new(38400, 8, 1)
ser4 = PlatoEnzi::Serial.new(76800, 8, 1, 1)
ser5 = PlatoEnzi::Serial.new(115200, 8, 1, 1, :even)
assert_true(ser1 && ser2 && ser3 && ser4 && ser5)
end
assert('Serial', 'new - argument error') do
assert_raise(ArgumentError) {PlatoEnzi::Serial.new}
assert_raise(ArgumentError) {PlatoEnzi::Serial.new(19200, 8, 1, 1, :odd, 1)}
end
assert('Serial', '_read') do
ser = PlatoEnzi::Serial.new(9600)
assert_equal(ser._read, -1)
end
assert('Serial', '_write') do
assert_nothing_raised {
ser = PlatoEnzi::Serial.new(9600)
ser._write(1)
}
end
assert('Serial', 'flush') do
assert_nothing_raised {
ser = PlatoEnzi::Serial.new(9600)
ser.flush
}
end
assert('Serial', 'close') do
assert_nothing_raised {
ser = PlatoEnzi::Serial.new(9600)
ser.close
}
end
|
mruby-plato-mgem/mruby-plato-serial-enzi
|
mrbgem.rake
|
<gh_stars>0
MRuby::Gem::Specification.new('mruby-plato-serial-enzi') do |spec|
spec.license = 'MIT'
spec.authors = '<NAME>'
spec.description = 'PlatoEnzi::Serial class'
spec.add_dependency('mruby-plato-machine')
spec.add_dependency('mruby-plato-machine-enzi')
spec.add_dependency('mruby-plato-serial')
end
|
mruby-plato-mgem/mruby-plato-serial-enzi
|
mrblib/serial.rb
|
<filename>mrblib/serial.rb
#
# PlatoEnzi::Serial class
#
module PlatoEnzi
class Serial
include Plato::Serial
@@serial = nil
@@baud = nil
def initialize(baud, dbits=8, start=1, stop=1, parity=:none)
if @@serial
if @@baud != baud
@@serial.close
@@serial = @baud = nil
end
end
unless @@serial
@@serial = ENZI::Serial.new(baud)
@@baud = baud
end
end
def _read
raise "Serial not initialized." unless @@serial
v = @@serial.read
v = -1 if v == 0xffff # for enzi-1.04 or earlier
v
end
def _write(v)
raise "Serial not initialized." unless @@serial
@@serial.write(v)
end
def available
raise "Serial not initialized." unless @@serial
@@serial.available
end
def flush
raise "Serial not initialized." unless @@serial
@@serial.flush
end
def close
@@serial.close if @@serial
@@serial = nil
end
end
end
# register enzi device
Plato::Serial.register_device(PlatoEnzi::Serial)
|
akerl/ballista
|
lib/ballista/version.rb
|
##
# Set the version (needed for Mercenary -v)
module Ballista
VERSION = '0.1.0'.freeze
end
|
akerl/ballista
|
lib/ballista/frequencies/base.rb
|
<filename>lib/ballista/frequencies/base.rb<gh_stars>1-10
require 'date'
module Ballista
module Frequencies
##
# Base class for frequency subclasses
class Base
def initialize(action, start, stop)
@name = action[:name]
@start = action[:starts] ? Date.parse(action[:starts]) : start
@stop = action[:stops] ? Date.parse(action[:stops]) : stop
@amount = action[:amount].to_i
@when = action[:when]
end
def entry(date)
[date, @name, @amount]
end
end
end
end
|
akerl/ballista
|
lib/ballista/projection.rb
|
require 'date'
require 'libledger'
module Ballista
##
# Projection class for creating journals
class Projection
def initialize(params = {})
@entries = params[:entries]
end
def project(start_dt, end_dt)
entries = start_dt.upto(end_dt).map { |date| parse_day(date) }
Ledger.new(entries: entries.flatten)
end
private
##
# This method pads all months so their last day covers through 31
# This ensures all monthly events can trigger, even in shorter months
def get_days(date)
return [date.day] if date.month == date.next.month
date.day.upto(date.day + 3).to_a
end
def out_of_bounds?(entry, date)
if entry[:starts] && Date.parse(entry[:starts]) > date
true
elsif entry[:ends] && Date.parse(entry[:ends]) < date # rubocop:disable Lint/DuplicateBranch
true
else
false
end
end
def parse_day(date)
get_days(date).map do |fake_day|
calendar[fake_day].map do |entry|
next if out_of_bounds?(entry, date)
build_entry(entry, date)
end.compact
end
end
def build_entry(entry, date)
Ledger::Entry.new(
date: date,
name: entry[:name],
state: '!',
actions: build_actions(entry)
)
end
def build_actions(entry)
entry[:actions].map { |name, amount| { name: name, amount: amount } }
end
def calendar
return @calendar if @calendar
@calendar = Hash.new { |h, k| h[k] = [] }
load_entries!
@calendar
end
def load_entries!
@entries.each do |entry|
dates = entry[:when]
dates = [dates] unless dates.is_a? Array
dates.each { |date| @calendar[date] << entry }
end
end
end
end
|
akerl/ballista
|
lib/ballista/frequencies/biweekly.rb
|
module Ballista
module Frequencies
##
# Biweekly actions
class Biweekly < Weekly
def step
14
end
end
end
end
|
akerl/ballista
|
lib/ballista.rb
|
<reponame>akerl/ballista<filename>lib/ballista.rb
##
# Define the main module
module Ballista
class << self
##
# Insert a helper .new() method for creating a new Projection object
def new(*args)
self::Projection.new(*args)
end
end
end
require 'ballista/version'
require 'ballista/projection'
require 'ballista/frequencies'
|
akerl/ballista
|
lib/ballista/frequencies.rb
|
<gh_stars>1-10
require 'ballista/frequencies/base'
require 'ballista/frequencies/monthly'
require 'ballista/frequencies/weekly'
require 'ballista/frequencies/biweekly'
module Ballista
##
# Base module for Frequency of actions
module Frequencies
class << self
FREQUENCIES = {
monthly: Monthly,
weekly: Weekly,
biweekly: Biweekly
}.freeze
end
end
end
|
akerl/ballista
|
lib/ballista/frequencies/weekly.rb
|
<reponame>akerl/ballista
module Ballista
module Frequencies
##
# Weekly actions
class Weekly < Base
def log
pointer = Date.parse(@when)
get_dates([], pointer)
end
def get_dates(log, pointer)
return log if pointer > @stop
return get_dates(log, pointer + step) if pointer < @start
log << entry(pointer)
get_dates(log, pointer + step)
end
def step
7
end
end
end
end
|
akerl/ballista
|
lib/ballista/frequencies/monthly.rb
|
module Ballista
module Frequencies
##
# Monthly actions
class Monthly < Base
def initialize(*_)
super
@when = [@when] unless @when.is_a? Array
end
def log
@when.flat_map do |date|
pointer = Date.new(Date.today.year, 1, date)
get_dates([], pointer, 0)
end
end
def get_dates(log, pointer, counter)
date = pointer >> counter
return log if date > @stop
return get_dates(log, pointer, counter + 1) if date < @start
log << entry(date)
get_dates(log, pointer, counter + 1)
end
end
end
end
|
pjskennedy/http-memcached-example
|
main.rb
|
<reponame>pjskennedy/http-memcached-example
require 'sinatra'
require 'securerandom'
INSTANCE_ID = SecureRandom.uuid
get "/" do
"Running on #{INSTANCE_ID}"
end
get '/health' do
status 200
"Healthy"
end
|
smy5152/re-former
|
app/models/user.rb
|
<reponame>smy5152/re-former<gh_stars>0
class User < ApplicationRecord
validates :username, presence: true
validates :email, presence: false
validates :password, presence: false, length: { in: 6..16 }
end
|
smy5152/re-former
|
config/routes.rb
|
<filename>config/routes.rb
Rails.application.routes.draw do
root "users#index"
resources :users, only: [:new, :create, :update, :edit, :show]
end
|
blalasaadri/type-system-ruby
|
lib/greeter.rb
|
# frozen_string_literal: true
# A class for greetings
class Greeter
def greet(name)
"Hello, #{name}!"
end
end
|
blalasaadri/type-system-ruby
|
test/test_greeter_bdd.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'minitest/autorun'
require_relative '../lib/greeter'
describe Greeter do
before do
@greeter = Greeter.new
end
describe 'when asked to greet somebody' do
it 'must greet that person' do
(@greeter.greet 'person').must_equal 'Hello, person!'
end
end
end
|
blalasaadri/type-system-ruby
|
test/test_greeter.rb
|
<reponame>blalasaadri/type-system-ruby<filename>test/test_greeter.rb
# frozen_string_literal: true
require 'minitest/autorun'
require_relative '../lib/greeter'
class TestGreeter < Minitest::Test
def setup
@greeter = Greeter.new
end
def test_that_greeter_greets
assert_equal 'Hello, user!', (@greeter.greet 'user')
end
def test_that_will_be_skipped
skip 'test this later'
end
end
|
blalasaadri/type-system-ruby
|
lib/main.rb
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'greeter.rb'
@greeter = Greeter.new
puts @greeter.greet 'World'
|
badoo/THEPageControl
|
THEPageControl.podspec
|
Pod::Spec.new do |s|
s.name = "THEPageControl"
s.version = "1.2.0"
s.summary = "Simple and flexible page control"
s.description = <<-DESC
Simple to use page control written in Swift. Provides full customization per dot.
Includes automatic intermediate state resolution for smooth transitions.
DESC
s.homepage = "https://github.com/badoo/THEPageControl"
s.screenshots = "https://raw.githubusercontent.com/badoo/THEPageControl/master/readme_images/example.gif"
s.license = { :type => "MIT" }
s.authors = { "<NAME>" => "<EMAIL>" }
s.platform = :ios, "8.0"
s.source = { :path => "./" }
s.source = { :git => "https://github.com/badoo/THEPageControl.git", :tag => "#{s.version}" }
s.source_files = "THEPageControl/Source/**/*.{h,m,swift}"
s.public_header_files = "THEPageControl/Source/**/*.h"
s.requires_arc = true
end
|
hannahsan91/Jeeps
|
lib/jeeps/cli.rb
|
class Jeeps::CLI
def call
puts "Thanks for coming to check out Wrangler mileage! Remember: it's the smiles per gallon, not the miles per gallon!"
get_years
list_years
get_user_year
# get_mpg_for(year)
# list_mpg
end
def get_years
@years = Jeeps::Year.all
end
def list_years
puts "On what year are you interested in checking mileage?"
@years.each.with_index(1) do |year, index|
puts "#{index}. #{year.name}"
end
end
def get_user_year
chosen_year = gets.strip.to_i
show_mileage_for(chosen_year) if valid_input(chosen_year, @years)
end
def valid_input(input, data)
input.to_i <= data.length && input.to_i > 0
end
def show_mileage_for(chosen_year)
year = @years[chosen_year - 1]
year.get_mileage
puts "Here is the combined mileage for #{year.name}"
year.mileage.each.with_index(1) do |mileage, idx|
puts "#{idx}. #{mileage.name}"
end
end
end
|
hannahsan91/Jeeps
|
lib/jeeps/year.rb
|
<gh_stars>0
class Jeeps::Year
@@all = []
attr_accessor :name, :mileage
def initialize(name)
@name = name
@mileage = []
save
end
def self.all
Jeeps::Scraper.scrape_years if @@all.empty?
@@all
end
def get_mileage
Jeeps::Scraper.scrape_mileage(self) if @@mileage.empty?
end
def save
@@all << self
end
end
|
hannahsan91/Jeeps
|
lib/jeeps.rb
|
require_relative "./jeeps/version"
require_relative "./jeeps/cli"
require_relative "./jeeps/year"
require_relative "./jeeps/scraper"
require_relative "./jeeps/mileage"
require 'pry'
require 'nokogiri'
require 'open-uri'
module Jeeps
class Error < StandardError; end
end
|
hannahsan91/Jeeps
|
lib/jeeps/version.rb
|
<filename>lib/jeeps/version.rb<gh_stars>0
module Jeeps
VERSION = "0.1.0"
end
|
hannahsan91/Jeeps
|
lib/jeeps/mileage.rb
|
<filename>lib/jeeps/mileage.rb
class Jeeps::Mileage
@@all = []
attr_accessor :name, :year
def initialize(name, year)
@name = name
@year = year
#notify year about mileage
add_to_year
@year.mileage << self
save
end
def self.all
@@all
end
def add_to_year
@year.mileage << self unless @year.mileage.include?(self)
end
def save
@@all << self
end
end
|
hannahsan91/Jeeps
|
lib/jeeps/scraper.rb
|
<reponame>hannahsan91/Jeeps
class Jeeps::Scraper
def self.scrape_years
doc = Nokogiri::HTML(open("https://www.officialdata.org/cars/Jeep/Wrangler%20Unlimited%204WD"))
years = page.css("div#table-container")
years.each do |y|
name = y.text
Jeeps::Year.new(name)
end
end
def self.scrape_mileage(year)
doc = Nokogiri::HTML(open("https://www.officialdata.org/cars/Jeep/Wrangler%20Unlimited%204WD"))
mileage = page.css("div#table-container")
mileage.each do |m|
number = m.text
Jeeps::Mileage.new(name)
end
end
end
|
slightair/enoki
|
lib/enoki/cli/generate.rb
|
require 'pathname'
module Enoki
class CLI < Thor
NAME_PLACEHOLDER = "__name__"
EXT_TEMPLATE = ".tt"
SOURCE_CODE_EXT_LIST = %w(c m mm swift).map { |ext| ".#{ext}" }
include Thor::Actions
desc "generate TEMPLATE FUNCTION_NAME", "generate code files from template"
method_option :target, aliases: "-t", desc: "Add files to specified target"
def generate(template_name, name)
unless templates.include? template_name
say_error "Template not found"
exit 1
end
selected_template_root = Pathname.new(File.expand_path(template_name, template_dir))
project_root = Pathname.new(project_root_dir)
file_list = Dir.glob(selected_template_root.join("**/*#{EXT_TEMPLATE}")).map do |file|
Pathname.new(file).relative_path_from(selected_template_root)
end
file_list.each do |path|
resolved_path = Pathname.new(path.to_path.gsub(NAME_PLACEHOLDER, name).chomp(EXT_TEMPLATE))
source_path = path.expand_path(selected_template_root).to_path
dest_path = resolved_path.expand_path(project_root).to_path
template(source_path, dest_path, context: context_for_template(name))
add_file_reference(resolved_path, options[:target])
end
project.save
end
no_commands do
def context_for_template(name)
binding
end
def add_file_reference(path, target_name)
path_list = path.to_path.split(File::SEPARATOR)
group = project.root_object.main_group
while path_list.size > 1
dir = path_list.shift
next_group = group.children.find { |g| g.path == dir } || group.new_group(dir, dir)
group = next_group
end
file = path_list.shift
file_ref = group.files.find { |f| f.path == file } || group.new_reference(file)
if SOURCE_CODE_EXT_LIST.include?(path.extname)
target = project.targets.find { |t| t.name == target_name } || project.targets.first
if target
target.source_build_phase.add_file_reference(file_ref, true)
end
end
end
end
end
end
|
slightair/enoki
|
lib/enoki/cli/list.rb
|
module Enoki
class CLI < Thor
desc "list", "list templates"
def list
puts templates
end
end
end
|
slightair/enoki
|
enoki.gemspec
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'enoki/version'
Gem::Specification.new do |spec|
spec.name = "enoki"
spec.version = Enoki::VERSION
spec.authors = ["slightair"]
spec.email = ["<EMAIL>"]
spec.summary = %q{Code generator for Xcode project.}
spec.description = %q{Code generator for Xcode project. You can manage multiple user-defined file template set in your project.}
spec.homepage = "https://github.com/slightair/enoki"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features|examples)/})
end
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_dependency "thor", "~> 0.19"
spec.add_dependency "xcodeproj", [">= 1.5", "< 2.0"]
end
|
slightair/enoki
|
lib/enoki/cli/common.rb
|
require 'yaml'
require 'xcodeproj'
module Enoki
class CLI < Thor
no_commands do
def settings_file
"./.enoki.yml"
end
def settings
@settings ||= begin
unless File.exist?(settings_file)
say_error("Settings file not found. Please create '.enoki.yml' or run 'enoki init'")
exit 1
end
YAML.load_file(settings_file)
end
end
def template_dir
@template_dir ||= File.absolute_path(settings["template_dir"] || "./templates")
end
def project_root_dir
@project_root_dir ||= File.absolute_path(settings["project_root_dir"] || "./")
end
def project_file_path
@project_file_path ||= begin
if settings["project_file_path"].nil?
raise "Error: Required settings not found in .enoki.yml! (project_file_path)"
end
File.absolute_path(settings["project_file_path"])
end
end
def templates
Dir.glob(File.join(template_dir, "*/")).map { |f| File.basename(f) }
end
def project
@project ||= Xcodeproj::Project.open(project_file_path)
end
end
end
end
|
slightair/enoki
|
lib/enoki/cli/init.rb
|
module Enoki
class CLI < Thor
include Thor::Actions
def self.source_root
File.expand_path("../", File.dirname(__FILE__))
end
desc "init", "create settings file"
def init
if File.exist?(settings_file)
exit 0 unless yes?("Settings file already exist. Re-create settings file? (y/N)", :yellow)
end
default_template_dir = "./templates"
default_project_root_dir = "./"
default_project_file_path = "./YourProject.xcodeproj"
template_dir = ask("Your template directory?", default: default_template_dir, path: true)
project_root_dir = ask("Your project root directory?", default: default_project_root_dir, path: true)
project_file_path = ask("Your project file path?", default: default_project_file_path, path: true)
template("templates/.enoki.yml.tt", settings_file, context: binding)
end
end
end
|
slightair/enoki
|
lib/enoki/cli.rb
|
<gh_stars>1-10
require 'thor'
require 'enoki/cli/shell'
require 'enoki/cli/common'
require 'enoki/cli/init'
require 'enoki/cli/show'
require 'enoki/cli/list'
require 'enoki/cli/generate'
module Enoki
class CLI < Thor
desc "version", "print enoki version"
def version
puts Enoki::VERSION
end
map %w(-v --version) => :version
end
end
|
slightair/enoki
|
lib/enoki.rb
|
<reponame>slightair/enoki
require "enoki/version"
require "enoki/cli"
module Enoki
# Your code goes here...
end
|
slightair/enoki
|
lib/enoki/cli/show.rb
|
<gh_stars>1-10
module Enoki
class CLI < Thor
desc "show", "show settings"
def show
[:template_dir, :project_root_dir, :project_file_path].each do |e|
puts("#{e}: #{send(e)}")
end
end
end
end
|
slightair/enoki
|
lib/enoki/cli/shell.rb
|
module Enoki
class CLI < Thor
no_commands do
def say_error(message)
say(message, :red)
end
def say_warning(message)
say(message, :yellow)
end
end
end
end
|
bmaland/hello_engine
|
test/unit/helpers/hello_engine/hello_helper_test.rb
|
<filename>test/unit/helpers/hello_engine/hello_helper_test.rb
require 'test_helper'
module HelloEngine
class HelloHelperTest < ActionView::TestCase
end
end
|
bmaland/hello_engine
|
test/dummy/config/routes.rb
|
Rails.application.routes.draw do
mount HelloEngine::Engine => "/hello_engine"
end
|
bmaland/hello_engine
|
test/hello_engine_test.rb
|
require 'test_helper'
class HelloEngineTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, HelloEngine
end
end
|
bmaland/hello_engine
|
config/routes.rb
|
HelloEngine::Engine.routes.draw do
get "hello/index"
root to: 'hello#index'
end
|
bmaland/hello_engine
|
lib/hello_engine.rb
|
<reponame>bmaland/hello_engine<filename>lib/hello_engine.rb
require "hello_engine/engine"
module HelloEngine
end
|
bmaland/hello_engine
|
lib/hello_engine/engine.rb
|
module HelloEngine
class Engine < ::Rails::Engine
isolate_namespace HelloEngine
end
end
|
bmaland/hello_engine
|
app/helpers/hello_engine/hello_helper.rb
|
<filename>app/helpers/hello_engine/hello_helper.rb<gh_stars>0
module HelloEngine
module HelloHelper
end
end
|
bmaland/hello_engine
|
test/functional/hello_engine/hello_controller_test.rb
|
<gh_stars>0
require 'test_helper'
module HelloEngine
class HelloControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
end
end
|
bmaland/hello_engine
|
hello_engine.gemspec
|
<filename>hello_engine.gemspec<gh_stars>0
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "hello_engine/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "hello_engine"
s.version = HelloEngine::VERSION
s.authors = [": <NAME>"]
s.email = [": Your email"]
s.homepage = ""
s.summary = ": Summary of HelloEngine."
s.description = ": Description of HelloEngine."
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", "~> 3.2.12"
# s.add_dependency "jquery-rails"
s.add_development_dependency "sqlite3"
end
|
bmaland/hello_engine
|
app/controllers/hello_engine/hello_controller.rb
|
<reponame>bmaland/hello_engine
require_dependency "hello_engine/application_controller"
module HelloEngine
class HelloController < ApplicationController
def index
end
end
end
|
martinos/http_fp
|
lib/http_fn/rack.rb
|
require "http_fn"
require "pp"
#
# https://www.diffchecker.com/ihCGIKyG
module HttpFn::Rack
fn_reader :to_env, :server, :rack_resp_to_resp
@@server = -> rack { to_env >> rack.method(:call) >> rack_resp_to_resp }
@@to_env = -> request {
session ||= {}
session_options ||= {}
uri = request.then(&HttpFn.to_uri)
header = (request[:header] || {}).dup
body = request[:body] || ""
content_type_key, val = header.detect { |key, val| puts key; key.downcase == "content-type" }
env = {
# CGI variables specified by Rack
"REQUEST_METHOD" => request[:method].to_s.upcase,
"CONTENT_TYPE" => header.delete(content_type_key),
"CONTENT_LENGTH" => body.bytesize,
"PATH_INFO" => uri.path,
"QUERY_STRING" => uri.query || "",
"SERVER_NAME" => uri.host,
"SERVER_PORT" => uri.port,
"SCRIPT_NAME" => "",
}
env["HTTP_AUTHORIZATION"] = "Basic " + [uri.userinfo].pack("m").delete("\r\n") if uri.userinfo
# Rack-specific variables
env["rack.input"] = StringIO.new(body)
env["rack.errors"] = $stderr
env["rack.version"] = ::Rack::VERSION
env["rack.url_scheme"] = uri.scheme
env["rack.run_once"] = true
env["rack.session"] = session
env["rack.session.options"] = session_options
header.each { |k, v| env["HTTP_#{k.tr("-", "_").upcase}"] = v }
env
}
@@rack_resp_to_resp = -> resp {
{ status: resp[0],
header: resp[1],
body: @@body_from_rack_response.(resp[2]) }
}
@@body_from_rack_response = -> response {
body = ""
response.each { |line| body << line }
response.close if response.respond_to?(:close)
body
}
end
|
martinos/http_fp
|
test/http_fn_test.rb
|
require "minitest_helper"
require "http_fn"
class HttpFn::HttpFnTest < Minitest::Test
include HttpFn
def test_basic_auth
req = with_basic_auth.("martin").("secret").(empty_req)
authorization = req[:header]["Authorization"]
refute_nil authorization
assert_equal "Basic bWFydGluOnNlY3JldA==", authorization
end
end
|
martinos/http_fp
|
test/http_fn/curl_test.rb
|
require 'minitest_helper'
require 'http_fn'
require 'http_fn/rack'
require 'http_fn/curl'
class HttpFn::CurlTest < Minitest::Test
include HttpFn
def setup
@curl = verb.("GET") >>~
with_path.("/coucou") >>~
with_headers.(json_headers) >>~
with_host.("https://api.github.com") >>~
with_json.({user: "martin"}) >>~
HttpFn::Curl.req >>+ run_
end
def test_should_return_a_curl_command
res = <<EOF
curl -X 'GET' 'https://api.github.com/coucou?' \\
-H 'accept: application/json' \\
-H 'Content-Type: application/json' \\
-H 'user-agent: paw/3.0.11 (macintosh; os x/10.11.6) gcdhttprequest'
-d $'{"user":"martin"}'
EOF
assert_equal res.chomp, @curl
end
end
|
martinos/http_fp
|
test/http_fn/rack_test.rb
|
require "minitest_helper"
require "rack"
require "http_fn/rack"
# https://github.com/macournoyer/thin/blob/a7d1174f47a4491a15b505407c0501cdc8d8d12c/spec/request/parser_spec.rb
# rack sample
# https://gist.github.com/a1869ea2e5db0563d5772b2eff74ff9f
class HttpFn::RackTest < MiniTest::Test
include HttpFn
def setup
@req = HttpFn.empty_req.then(&with_host.("http://localhost:3000"))
end
def test_upcase_headers
req = @req.then(&add_headers.("X-invisible" => "tata"))
env = Rack.to_env.(req)
assert_equal "tata", env["HTTP_X_INVISIBLE"]
end
def test_basic_headers
env = empty_req.then(&(verb.("get") >> with_host.("https://localhost:3000") >> with_query.({ "name" => "martin" }) >> with_path.("/users/1") >> Rack.to_env))
# assert_equal "HTTP/1.1", env["SERVER_PROTOCOL"]
# assert_equal "HTTP/1.1", env["HTTP_VERSION"]
# assert_equal "/users/1", env["REQUEST_PATH"]
assert_equal "GET", env["REQUEST_METHOD"]
assert_equal "https", env["rack.url_scheme"]
assert_equal "/users/1", env["PATH_INFO"]
end
def test_host
env = empty_req.then(&(verb.("get") >> with_host.("https://localhost:3000") >> with_query.({ "name" => "martin" }) >> with_path.("/users/1") >> Rack.to_env))
# assert_equal "localhost:3000", env["HTTP_HOST"]
assert_equal "localhost", env["SERVER_NAME"]
assert_equal 3000, env["SERVER_PORT"]
assert_equal "name=martin", env["QUERY_STRING"]
assert_equal "", env["SCRIPT_NAME"]
end
def test_dont_prepend_HTTP_to_content_type_and_content_length
env = empty_req.then(&(verb.("get") >> with_host.("https://localhost:3000") >> with_query.({ "name" => "martin" }) >> with_path.("/users/1") >> add_headers.({ "content-type" => "application/json" }) >> Rack.to_env))
assert_equal "application/json", env["CONTENT_TYPE"]
assert_equal 0, env["CONTENT_LENGTH"]
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.