monosasi 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9720e083ca93e2af0a7864c1a4d83128432000ea
4
+ data.tar.gz: 72de3c79fb3663ad9b3700df30c70d9bcfc2bb67
5
+ SHA512:
6
+ metadata.gz: bcdf6aadb86bb36ef142c97a737b31ef7a801061bfc82c58810813251802d1f37eaaea81b40218ed96ba492fd1ea3cc622cd40d3e7d966f94b23b4d4c8835f22
7
+ data.tar.gz: 09d283a469c5b4354603646b635c96d2f0d221d3ae543ca16454a0678f1f1a35ba5c26f7d86dc9daef59e1656115cae5166685db176c9e035e85a85c4b5060cc
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ test.rb
11
+ Rulefile
12
+ *.rule
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.4
4
+ before_install: gem install bundler -v 1.11.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in monosasi.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 winebarrel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # Monosasi
2
+
3
+ Monosasi is a tool to manage [Cloudwatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) rules.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'monosasi'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install monosasi
20
+
21
+ ## Usage
22
+
23
+ ```sh
24
+ export AWS_ACCESS_KEY_ID='...'
25
+ export AWS_SECRET_ACCESS_KEY='...'
26
+
27
+ # export rules to `Rulefile`
28
+ monosasi -e -o Rulefile
29
+
30
+ vi Rulefile
31
+
32
+ # apply `Rulefile` to Cloudwatch Events
33
+ monosasi -a --dry-run
34
+ monosasi -a
35
+ ```
36
+
37
+ ## Help
38
+
39
+ ```
40
+ Usage: monosasi [options]
41
+ -k, --access-key ACCESS_KEY
42
+ -s, --secret-key SECRET_KEY
43
+ -r, --region REGION
44
+ --profile PROFILE
45
+ --credentials-path PATH
46
+ -a, --apply
47
+ -f, --file FILE
48
+ --dry-run
49
+ -e, --export
50
+ -o, --output FILE
51
+ --split
52
+ --target REGEXP
53
+ --no-color
54
+ --debug
55
+ ```
56
+
57
+ ## Rulefile example
58
+
59
+ ```ruby
60
+ require 'other/rulefile'
61
+
62
+ rule "cron" do
63
+ state "ENABLED"
64
+ description "my cron"
65
+ schedule_expression "cron(0 17 ? * MON-FRI *)"
66
+ target "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" do
67
+ arn "arn:aws:lambda:ap-northeast-1:123456789012:function:hello-world"
68
+ input_path '$.detail'
69
+ end
70
+ target "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy" do
71
+ arn "arn:aws:lambda:ap-northeast-1:123456789012:function:my-func"
72
+ end
73
+ end
74
+
75
+ rule "ssm role" do
76
+ state "ENABLED"
77
+ event_pattern do
78
+ {"detail-type"=>
79
+ ["EC2 Command Invocation Status-change Notification",
80
+ "EC2 Command Status-change Notification"],
81
+ "source"=>["aws.ssm"]}
82
+ end
83
+ target "zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz" do
84
+ arn "arn:aws:lambda:ap-northeast-1:123456789012:function:trigger-func"
85
+ input '{"foo": "bar"}'
86
+ end
87
+ end
88
+ ```
89
+
90
+ ## Similar tools
91
+ * [Codenize.tools](http://codenize.tools/)
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "monosasi"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/exe/monosasi ADDED
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env ruby
2
+ $: << File.expand_path('../../lib', __FILE__)
3
+
4
+ require 'monosasi'
5
+ require 'optparse'
6
+
7
+ Version = Monosasi::VERSION
8
+ DEFAULT_FILENAME = 'Rulefile'
9
+
10
+ MAGIC_COMMENT = <<-EOS
11
+ # -*- mode: ruby -*-
12
+ # vi: set ft=ruby :
13
+ EOS
14
+
15
+ def parse_options(argv)
16
+ options = {
17
+ file: DEFAULT_FILENAME,
18
+ output: '-',
19
+ dry_run: false,
20
+ color: true,
21
+ aws: {ssl_verify_peer: false},
22
+ }
23
+
24
+ opt = OptionParser.new
25
+ opt.on('-k', '--access-key ACCESS_KEY') {|v| options[:aws][:access_key_id] = v }
26
+ opt.on('-s', '--secret-key SECRET_KEY') {|v| options[:aws][:secret_access_key] = v }
27
+ opt.on('-r', '--region REGION') {|v| options[:aws][:region] = v }
28
+
29
+ opt.on('', '--profile PROFILE') do |v|
30
+ options[:aws][:credentials] ||= {}
31
+ options[:aws][:credentials][:profile_name] = v
32
+ end
33
+
34
+ opt.on('', '--credentials-path PATH') do |v|
35
+ options[:aws][:credentials] ||= {}
36
+ options[:aws][:credentials][:path] = v
37
+ end
38
+
39
+ opt.on('-a', '--apply') { options[:mode] = :apply }
40
+ opt.on('-f', '--file FILE') {|v| options[:file] = v }
41
+ opt.on('' , '--dry-run') { options[:dry_run] = true }
42
+ opt.on('-e', '--export') { options[:mode] = :export }
43
+ opt.on('-o', '--output FILE') {|v| options[:output] = v }
44
+ opt.on('' , '--split') { options[:split] = :true }
45
+ opt.on('' , '--target REGEXP') {|v| options[:target] = Regexp.new(v) }
46
+ opt.on('' , '--no-color') { options[:color] = false }
47
+ opt.on('' , '--debug') { options[:debug] = true }
48
+
49
+ opt.parse!(argv)
50
+
51
+ unless options[:mode]
52
+ puts opt.help
53
+ exit 1
54
+ end
55
+
56
+ if options[:aws][:credentials]
57
+ credentials = Aws::SharedCredentials.new(options[:aws][:credentials])
58
+ options[:aws][:credentials] = credentials
59
+ end
60
+
61
+ Aws.config.update(options[:aws])
62
+ String.colorize = options[:color]
63
+
64
+ if options[:debug]
65
+ Monosasi::Logger.instance.set_debug(options[:debug])
66
+
67
+ Aws.config.update(
68
+ :http_wire_trace => true,
69
+ :logger => Monosasi::Logger.instance
70
+ )
71
+ end
72
+
73
+ options
74
+ rescue => e
75
+ $stderr.puts("[ERROR] #{e.message}")
76
+ exit 1
77
+ end
78
+
79
+ def main(argv)
80
+ options = parse_options(argv)
81
+ client = Monosasi::Client.new(options)
82
+ logger = Monosasi::Logger.instance
83
+
84
+ case options[:mode]
85
+ when :export
86
+ exported = client.export
87
+ output = options[:output]
88
+
89
+ if options[:split]
90
+ logger.info('Export Rule')
91
+
92
+ output = DEFAULT_FILENAME if output == '-'
93
+ dir = File.dirname(output)
94
+ FileUtils.mkdir_p(dir)
95
+ requires = []
96
+
97
+ exported.each do |rule_name, rule|
98
+ filename = "#{rule_name}.rule"
99
+ requires << filename
100
+ rule_file = File.join(dir, filename)
101
+
102
+ logger.info(" write `#{rule_file}`")
103
+
104
+ dsl = Monosasi::DSL.convert({rule_name => rule}, options)
105
+
106
+ open(rule_file, 'wb') do |f|
107
+ f.puts MAGIC_COMMENT
108
+ f.puts dsl
109
+ end
110
+ end
111
+
112
+ logger.info(" write `#{output}`")
113
+
114
+ open(output, 'wb') do |f|
115
+ f.puts MAGIC_COMMENT
116
+
117
+ requires.each do |rule_file|
118
+ f.puts "require '#{rule_file}'"
119
+ end
120
+ end
121
+ else
122
+ dsl = Monosasi::DSL.convert(exported, options)
123
+
124
+ if output == '-'
125
+ logger.info('# Export Rule')
126
+
127
+ puts dsl
128
+ else
129
+ logger.info("Export Rule to `#{output}`")
130
+
131
+ open(output, 'wb') do |f|
132
+ f.puts MAGIC_COMMENT
133
+ f.puts dsl
134
+ end
135
+ end
136
+ end
137
+ when :apply
138
+ file = options[:file]
139
+
140
+ unless File.exist?(file)
141
+ raise "No Rulefile found (looking for: #{file})"
142
+ end
143
+
144
+ message = "Apply `#{file}` to CloudWatch Events"
145
+ message << ' (dry-run)' if options[:dry_run]
146
+ logger.info(message)
147
+ updated = client.apply(file)
148
+ logger.info('No change'.intense_blue) unless updated
149
+ else
150
+ raise "Unknown mode: #{options[:mode]}"
151
+ end
152
+ rescue => e
153
+ if options[:debug]
154
+ raise e
155
+ else
156
+ $stderr.puts("[ERROR] #{e.message}".red)
157
+ exit 1
158
+ end
159
+ end
160
+
161
+ main(ARGV)
@@ -0,0 +1,112 @@
1
+ class Monosasi::Client
2
+ include Monosasi::Utils::TargetMatcher
3
+
4
+ def initialize(options = {})
5
+ @options = options
6
+ @client = @options[:client] || Aws::CloudWatchEvents::Client.new
7
+ @driver = Monosasi::Driver.new(@client, options)
8
+ @exporter = Monosasi::Exporter.new(@client, @options)
9
+ end
10
+
11
+ def export
12
+ @exporter.export
13
+ end
14
+
15
+ def apply(file)
16
+ walk(file)
17
+ end
18
+
19
+ private
20
+
21
+ def walk(file)
22
+ expected = load_file(file)
23
+ actual = @exporter.export
24
+
25
+ updated = walk_rules(expected, actual)
26
+
27
+ if @options[:dry_run]
28
+ false
29
+ else
30
+ updated
31
+ end
32
+ end
33
+
34
+ def walk_rules(expected, actual)
35
+ updated = false
36
+
37
+ expected.each do |rule_name, expected_rule|
38
+ next unless target?(rule_name)
39
+
40
+ actual_rule = actual.delete(rule_name)
41
+
42
+ unless actual_rule
43
+ @driver.create_rule(rule_name, expected_rule)
44
+ updated = true
45
+ actual_rule = expected_rule.merge(:targets => {})
46
+ end
47
+
48
+ updated = walk_rule(rule_name, expected_rule, actual_rule) || updated
49
+ end
50
+
51
+ actual.each do |rule_name, actual_rule|
52
+ next unless target?(rule_name)
53
+
54
+ @driver.delete_rule(rule_name, actual_rule)
55
+ updated = true
56
+ end
57
+
58
+ updated
59
+ end
60
+
61
+ def walk_rule(rule_name, expected, actual)
62
+ updated = false
63
+
64
+ expected_without_targets = expected.dup
65
+ expected_targets = expected_without_targets.delete(:targets)
66
+
67
+ actual_without_targets = actual.dup
68
+ actual_targets = actual_without_targets.delete(:targets)
69
+
70
+ if expected_without_targets != actual_without_targets
71
+ @driver.update_rule(rule_name, expected_without_targets, actual_without_targets)
72
+ updated = true
73
+ end
74
+
75
+ walk_targets(rule_name, expected_targets, actual_targets) || updated
76
+ end
77
+
78
+ def walk_targets(rule_name, expected, actual)
79
+ updated = false
80
+
81
+ expected.each do |target_id, expected_target|
82
+ actual_target = actual.delete(target_id)
83
+
84
+ if not actual_target
85
+ @driver.create_target(rule_name, target_id, expected_target)
86
+ updated = true
87
+ elsif expected_target != actual_target
88
+ @driver.update_target(rule_name, target_id, expected_target, actual_target)
89
+ updated = true
90
+ end
91
+ end
92
+
93
+ actual.each do |target_id, actual_target|
94
+ @driver.delete_target(rule_name, target_id)
95
+ updated = true
96
+ end
97
+
98
+ updated
99
+ end
100
+
101
+ def load_file(file)
102
+ if file.kind_of?(String)
103
+ open(file) do |f|
104
+ Monosasi::DSL.parse(f.read, file)
105
+ end
106
+ elsif file.respond_to?(:read)
107
+ Monosasi::DSL.parse(file.read, file.path)
108
+ else
109
+ raise TypeError, "can't convert #{file} into File"
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,110 @@
1
+ class Monosasi::Driver
2
+ include Monosasi::Logger::Helper
3
+ include Monosasi::Utils::Diff
4
+
5
+ def initialize(client, options = {})
6
+ @client = client
7
+ @options = options
8
+ end
9
+
10
+ def create_rule(rule_name, rule)
11
+ log(:info, "Create Rule `#{rule_name}`", color: :cyan)
12
+
13
+ unless @options[:dry_run]
14
+ put_rule(rule_name, rule)
15
+ end
16
+ end
17
+
18
+ def delete_rule(rule_name, rule)
19
+ log(:info, "Delete Rule `#{rule_name}`", color: :red)
20
+
21
+ unless @options[:dry_run]
22
+ targets = rule[:targets]
23
+
24
+ unless targets.empty?
25
+ @client.remove_targets(:rule => rule_name, :ids => targets.keys)
26
+ end
27
+
28
+ @client.delete_rule(:name => rule_name)
29
+ end
30
+ end
31
+
32
+ def update_rule(rule_name, rule, old_rule)
33
+ log(:info, "Update Rule `#{rule_name}`", color: :green)
34
+ log(:info, diff(old_rule, rule, color: @options[:color]), color: false)
35
+
36
+ unless @options[:dry_run]
37
+ put_rule(rule_name, rule)
38
+ end
39
+ end
40
+
41
+ def create_target(rule_name, target_id, target)
42
+ log(:info, "Create Rule `#{rule_name}` > Target `#{target_id}`", color: :cyan)
43
+
44
+ unless @options[:dry_run]
45
+ put_target(rule_name, target_id, target)
46
+ end
47
+ end
48
+
49
+ def delete_target(rule_name, target_id)
50
+ log(:info, "Delete Rule `#{rule_name}` > Target `#{target_id}`", color: :red)
51
+
52
+ unless @options[:dry_run]
53
+ @client.remove_targets(:rule => rule_name, :ids => [target_id])
54
+ end
55
+ end
56
+
57
+ def update_target(rule_name, target_id, target, old_target)
58
+ log(:info, "Update Rule `#{rule_name}` > Target `#{target_id}`", color: :green)
59
+ log(:info, diff(old_target, target, color: @options[:color]), color: false)
60
+
61
+ unless @options[:dry_run]
62
+ put_target(rule_name, target_id, target)
63
+ end
64
+ end
65
+
66
+ private
67
+
68
+ def put_rule(rule_name, rule)
69
+ params = {
70
+ :name => rule_name,
71
+ :state => rule[:state],
72
+ :role_arn => rule[:role_arn],
73
+ }
74
+
75
+ if rule[:description]
76
+ params[:description] = rule[:description]
77
+ end
78
+
79
+ if rule[:schedule_expression]
80
+ params[:schedule_expression] = rule[:schedule_expression]
81
+ end
82
+
83
+ if rule[:event_pattern]
84
+ params[:event_pattern] = JSON.dump(rule[:event_pattern])
85
+ end
86
+
87
+ @client.put_rule(params)
88
+ end
89
+
90
+ def put_target(rule_name, target_id, target)
91
+ params_target = {
92
+ :id => target_id,
93
+ :arn => target[:arn],
94
+ }
95
+
96
+ if target[:input]
97
+ params_target[:input] = target[:input]
98
+ end
99
+
100
+ if target[:input_path]
101
+ params_target[:input_path] = target[:input_path]
102
+ end
103
+ params = {
104
+ :rule => rule_name,
105
+ :targets => [params_target],
106
+ }
107
+
108
+ @client.put_targets(params)
109
+ end
110
+ end
@@ -0,0 +1,26 @@
1
+ class Monosasi::DSL::Context::Rule::Target
2
+ include Monosasi::DSL::TemplateHelper
3
+
4
+ def initialize(context, id, &block)
5
+ @id = id
6
+ @context = context.merge(target_id: id)
7
+ @result = {}
8
+ instance_eval(&block)
9
+ end
10
+
11
+ attr_reader :result
12
+
13
+ private
14
+
15
+ def arn(value)
16
+ @result[:arn] = value.to_s
17
+ end
18
+
19
+ def input_path(value)
20
+ @result[:input_path] = value.to_s
21
+ end
22
+
23
+ def input(value)
24
+ @result[:input] = value.to_s
25
+ end
26
+ end
@@ -0,0 +1,41 @@
1
+ class Monosasi::DSL::Context::Rule
2
+ include Monosasi::DSL::TemplateHelper
3
+
4
+ def initialize(context, name, &block)
5
+ @name = name
6
+ @context = context.merge(rule_name: name)
7
+ @result = {:targets => {}}
8
+ instance_eval(&block)
9
+ end
10
+
11
+ attr_reader :result
12
+
13
+ private
14
+
15
+ def state(value)
16
+ @result[:state] = value.to_s
17
+ end
18
+
19
+ def description(value)
20
+ @result[:description] = value.to_s
21
+ end
22
+
23
+ def schedule_expression(value)
24
+ @result[:schedule_expression] = value.to_s
25
+ end
26
+
27
+ def event_pattern
28
+ value = yield
29
+
30
+ unless value.is_a?(Hash)
31
+ raise TypeError, "wrong expand_path type (given #{value.inspect}:#{value.class}, expected Hash)"
32
+ end
33
+
34
+ @result[:event_pattern] = value
35
+ end
36
+
37
+ def target(id, &block)
38
+ id = id.to_s
39
+ @result[:targets][id] = Monosasi::DSL::Context::Rule::Target.new(@context, id, &block).result
40
+ end
41
+ end
@@ -0,0 +1,55 @@
1
+ class Monosasi::DSL::Context
2
+ include Monosasi::DSL::TemplateHelper
3
+
4
+ def self.eval(dsl, path, options = {})
5
+ self.new(path, options) do
6
+ eval(dsl, binding, path)
7
+ end
8
+ end
9
+
10
+ def result
11
+ @result.sort_array!
12
+ end
13
+
14
+ def initialize(path, options = {}, &block)
15
+ @path = path
16
+ @options = options
17
+ @result = {}
18
+
19
+ @context = Hashie::Mash.new(
20
+ :path => path,
21
+ :options => options,
22
+ :templates => {}
23
+ )
24
+
25
+ instance_eval(&block)
26
+ end
27
+
28
+ def template(name, &block)
29
+ @context.templates[name.to_s] = block
30
+ end
31
+
32
+ private
33
+
34
+ def require(file)
35
+ rule_file = (file =~ %r|\A/|) ? file : File.expand_path(File.join(File.dirname(@path), file))
36
+
37
+ if File.exist?(rule_file)
38
+ instance_eval(File.read(rule_file), rule_file)
39
+ elsif File.exist?(rule_file + '.rb')
40
+ instance_eval(File.read(rule_file + '.rb'), rule_file + '.rb')
41
+ else
42
+ Kernel.require(file)
43
+ end
44
+ end
45
+
46
+ def rule(name, &block)
47
+ name = name.to_s
48
+
49
+ if @result[name]
50
+ raise "Rule `#{name}` is already defined"
51
+ end
52
+
53
+ @result[name] = Monosasi::DSL::Context::Rule.new(@context, name, &block).result
54
+ end
55
+ end
@@ -0,0 +1,98 @@
1
+ class Monosasi::DSL::Converter
2
+ def self.convert(exported, options = {})
3
+ self.new(exported, options).convert
4
+ end
5
+
6
+ def initialize(exported, options = {})
7
+ @exported = exported
8
+ @options = options
9
+ end
10
+
11
+ def convert
12
+ output_rules(@exported)
13
+ end
14
+
15
+ private
16
+
17
+ def output_rules(rule_by_name)
18
+ rules = []
19
+
20
+ rule_by_name.sort_by(&:first).each do |name, rule|
21
+ rules << output_rule(name, rule)
22
+ end
23
+
24
+ rules.join("\n")
25
+ end
26
+
27
+ def output_rule(name, rule)
28
+ body = <<-EOS
29
+ state #{rule[:state].inspect}
30
+ EOS
31
+
32
+ if rule[:description]
33
+ body += <<-EOS
34
+ description #{rule[:description].inspect}
35
+ EOS
36
+ end
37
+
38
+ if rule[:schedule_expression]
39
+ body += <<-EOS
40
+ schedule_expression #{rule[:schedule_expression].inspect}
41
+ EOS
42
+ end
43
+
44
+ if rule[:event_pattern]
45
+ event_pattern = rule[:event_pattern].pretty_inspect
46
+ event_pattern.gsub!(/^/, "\s" * 4)
47
+
48
+ body += <<-EOS
49
+ event_pattern do
50
+ #{event_pattern.strip}
51
+ end
52
+ EOS
53
+ end
54
+
55
+ if rule[:targets]
56
+ body += output_targets(rule[:targets])
57
+ end
58
+
59
+ <<-EOS
60
+ rule #{name.inspect} do
61
+ #{body.strip}
62
+ end
63
+ EOS
64
+ end
65
+
66
+ def output_targets(targets)
67
+ targets.map {|id, target|
68
+ output_target(id, target).chomp
69
+ }.join("\n")
70
+ end
71
+
72
+ def output_target(id, target)
73
+ body = <<-EOS
74
+ arn #{target[:arn].inspect}
75
+ EOS
76
+
77
+ if target[:input]
78
+ input = target[:input].pretty_inspect
79
+ input.gsub!(/^/, "\s" * 6)
80
+
81
+ body += <<-EOS
82
+ input #{target[:input].inspect}
83
+ EOS
84
+ end
85
+
86
+ if target[:input_path]
87
+ body += <<-EOS
88
+ input_path #{target[:input_path].inspect}
89
+ EOS
90
+ end
91
+
92
+ <<-EOS.chomp
93
+ target #{id.inspect} do
94
+ #{body.strip}
95
+ end
96
+ EOS
97
+ end
98
+ end
@@ -0,0 +1,18 @@
1
+ module Monosasi::DSL::TemplateHelper
2
+ def include_template(template_name, context = {})
3
+ tmplt = @context.templates[template_name.to_s]
4
+
5
+ unless tmplt
6
+ raise "Template `#{template_name}` is not defined"
7
+ end
8
+
9
+ context_orig = @context
10
+ @context = @context.merge(context)
11
+ instance_eval(&tmplt)
12
+ @context = context_orig
13
+ end
14
+
15
+ def context
16
+ @context
17
+ end
18
+ end
@@ -0,0 +1,11 @@
1
+ class Monosasi::DSL
2
+ class << self
3
+ def convert(exported, options = {})
4
+ Monosasi::DSL::Converter.convert(exported, options)
5
+ end
6
+
7
+ def parse(dsl, path, options = {})
8
+ Monosasi::DSL::Context.eval(dsl, path, options).result
9
+ end
10
+ end # of class methods
11
+ end
@@ -0,0 +1,53 @@
1
+ class Monosasi::Exporter
2
+ include Monosasi::Utils::TargetMatcher
3
+
4
+ CONCURRENCY = 8
5
+
6
+ def initialize(client, options = {})
7
+ @client = client
8
+ @options = options
9
+ end
10
+
11
+ def export
12
+ export_rules.sort_array!
13
+ end
14
+
15
+ private
16
+
17
+ def export_rules
18
+ rule_by_name = {}
19
+ resp = @client.list_rules
20
+
21
+ Parallel.each(resp.rules, in_threads: CONCURRENCY) do |rule|
22
+ rule = rule.to_h
23
+ rule.delete(:arn)
24
+ rule_name = rule.delete(:name)
25
+
26
+ next unless target?(rule_name)
27
+
28
+ if rule[:event_pattern]
29
+ rule[:event_pattern] = JSON.parse(rule[:event_pattern])
30
+ end
31
+
32
+ targets = export_targets(rule_name)
33
+ rule[:targets] = targets
34
+
35
+ rule_by_name[rule_name] = rule
36
+ end
37
+
38
+ rule_by_name
39
+ end
40
+
41
+ def export_targets(rule_name)
42
+ target_by_id = {}
43
+ resp = @client.list_targets_by_rule(rule: rule_name)
44
+
45
+ resp.targets.each do |target|
46
+ target = target.to_h
47
+ id = target.delete(:id)
48
+ target_by_id[id] = target
49
+ end
50
+
51
+ target_by_id
52
+ end
53
+ end
@@ -0,0 +1,33 @@
1
+ module Monosasi::Ext
2
+ module HashExt
3
+ def sort_array!
4
+ keys.each do |key|
5
+ value = self[key]
6
+ self[key] = sort_array0(value)
7
+ end
8
+
9
+ self
10
+ end
11
+
12
+ private
13
+
14
+ def sort_array0(value)
15
+ case value
16
+ when Hash
17
+ new_value = {}
18
+
19
+ value.each do |k, v|
20
+ new_value[k] = sort_array0(v)
21
+ end
22
+
23
+ new_value
24
+ when Array
25
+ value.map {|v| sort_array0(v) }.sort_by(&:to_s)
26
+ else
27
+ value
28
+ end
29
+ end
30
+ end
31
+ end
32
+
33
+ Hash.send(:include, Monosasi::Ext::HashExt)
@@ -0,0 +1,28 @@
1
+ module Monosasi::Ext
2
+ module StringExt
3
+ module ClassMethods
4
+ def colorize=(value)
5
+ @colorize = value
6
+ end
7
+
8
+ def colorize
9
+ @colorize
10
+ end
11
+ end # ClassMethods
12
+
13
+ Term::ANSIColor::Attribute.named_attributes.each do |attribute|
14
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
15
+ def #{attribute.name}
16
+ if String.colorize
17
+ Term::ANSIColor.send(#{attribute.name.inspect}, self)
18
+ else
19
+ self
20
+ end
21
+ end
22
+ EOS
23
+ end
24
+ end
25
+ end
26
+
27
+ String.send(:include, Monosasi::Ext::StringExt)
28
+ String.extend(Monosasi::Ext::StringExt::ClassMethods)
@@ -0,0 +1,28 @@
1
+ class Monosasi::Logger < ::Logger
2
+ include Singleton
3
+
4
+ def initialize
5
+ super($stdout)
6
+
7
+ self.formatter = proc do |severity, datetime, progname, msg|
8
+ "#{msg}\n"
9
+ end
10
+
11
+ self.level = Logger::INFO
12
+ end
13
+
14
+ def set_debug(value)
15
+ self.level = value ? Logger::DEBUG : Logger::INFO
16
+ end
17
+
18
+ module Helper
19
+ def log(level, message, log_options = {})
20
+ global_option = @options || {}
21
+ message = "[#{level.to_s.upcase}] #{message}" unless level == :info
22
+ message << ' (dry-run)' if global_option[:dry_run]
23
+ message = message.send(log_options[:color]) if log_options[:color]
24
+ logger = global_option[:logger] || Monosasi::Logger.instance
25
+ logger.send(level, message)
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,14 @@
1
+ class Monosasi::Utils
2
+ module Diff
3
+ def diff(obj1, obj2, options = {})
4
+ diffy = Diffy::Diff.new(
5
+ obj1.pretty_inspect,
6
+ obj2.pretty_inspect,
7
+ :diff => '-u'
8
+ )
9
+
10
+ diffy.to_s(options[:color] ? :color : :text).gsub(/\s+\z/m, '')
11
+ end
12
+ module_function :diff
13
+ end
14
+ end
@@ -0,0 +1,11 @@
1
+ class Monosasi::Utils
2
+ module TargetMatcher
3
+ def target?(name)
4
+ if @options[:target]
5
+ @options[:target] =~ name
6
+ else
7
+ true
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,3 @@
1
+ module Monosasi
2
+ VERSION = '0.1.0'
3
+ end
data/lib/monosasi.rb ADDED
@@ -0,0 +1,28 @@
1
+ require 'aws-sdk'
2
+ require 'diffy'
3
+ require 'hashie'
4
+ require 'json'
5
+ require 'logger'
6
+ require 'parallel'
7
+ require 'pp'
8
+ require 'pp_sort_hash'
9
+ require 'singleton'
10
+ require 'term/ansicolor'
11
+
12
+ require 'monosasi/version'
13
+
14
+ require 'monosasi/ext/hash_ext'
15
+ require 'monosasi/ext/string_ext'
16
+ require 'monosasi/logger'
17
+ require 'monosasi/utils/diff'
18
+ require 'monosasi/utils/target_matcher'
19
+
20
+ require 'monosasi/client'
21
+ require 'monosasi/driver'
22
+ require 'monosasi/dsl'
23
+ require 'monosasi/dsl/template_helper'
24
+ require 'monosasi/dsl/context'
25
+ require 'monosasi/dsl/context/rule'
26
+ require 'monosasi/dsl/context/rule/target'
27
+ require 'monosasi/dsl/converter'
28
+ require 'monosasi/exporter'
data/monosasi.gemspec ADDED
@@ -0,0 +1,32 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'monosasi/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'monosasi'
8
+ spec.version = Monosasi::VERSION
9
+ spec.authors = ['winebarrel']
10
+ spec.email = ['sgwr_dts@yahoo.co.jp']
11
+
12
+ spec.summary = %q{Monosasi is a tool to manage Cloudwatch Events rules.}
13
+ spec.description = %q{Monosasi is a tool to manage Cloudwatch Events rules.}
14
+ spec.homepage = 'https://github.com/winebarrel/monosasi'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = 'exe'
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_dependency 'aws-sdk', '>= 2.5'
23
+ spec.add_dependency 'diffy'
24
+ spec.add_dependency 'hashie'
25
+ spec.add_dependency 'parallel'
26
+ spec.add_dependency 'pp_sort_hash'
27
+ spec.add_dependency 'term-ansicolor'
28
+
29
+ spec.add_development_dependency 'bundler'
30
+ spec.add_development_dependency 'rake'
31
+ spec.add_development_dependency 'rspec', '~> 3.0'
32
+ end
metadata ADDED
@@ -0,0 +1,198 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: monosasi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - winebarrel
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-10-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: aws-sdk
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.5'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.5'
27
+ - !ruby/object:Gem::Dependency
28
+ name: diffy
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: hashie
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: parallel
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pp_sort_hash
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: term-ansicolor
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: bundler
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rake
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: rspec
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '3.0'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '3.0'
139
+ description: Monosasi is a tool to manage Cloudwatch Events rules.
140
+ email:
141
+ - sgwr_dts@yahoo.co.jp
142
+ executables:
143
+ - monosasi
144
+ extensions: []
145
+ extra_rdoc_files: []
146
+ files:
147
+ - ".gitignore"
148
+ - ".rspec"
149
+ - ".travis.yml"
150
+ - Gemfile
151
+ - LICENSE.txt
152
+ - README.md
153
+ - Rakefile
154
+ - bin/console
155
+ - bin/setup
156
+ - exe/monosasi
157
+ - lib/monosasi.rb
158
+ - lib/monosasi/client.rb
159
+ - lib/monosasi/driver.rb
160
+ - lib/monosasi/dsl.rb
161
+ - lib/monosasi/dsl/context.rb
162
+ - lib/monosasi/dsl/context/rule.rb
163
+ - lib/monosasi/dsl/context/rule/target.rb
164
+ - lib/monosasi/dsl/converter.rb
165
+ - lib/monosasi/dsl/template_helper.rb
166
+ - lib/monosasi/exporter.rb
167
+ - lib/monosasi/ext/hash_ext.rb
168
+ - lib/monosasi/ext/string_ext.rb
169
+ - lib/monosasi/logger.rb
170
+ - lib/monosasi/utils/diff.rb
171
+ - lib/monosasi/utils/target_matcher.rb
172
+ - lib/monosasi/version.rb
173
+ - monosasi.gemspec
174
+ homepage: https://github.com/winebarrel/monosasi
175
+ licenses:
176
+ - MIT
177
+ metadata: {}
178
+ post_install_message:
179
+ rdoc_options: []
180
+ require_paths:
181
+ - lib
182
+ required_ruby_version: !ruby/object:Gem::Requirement
183
+ requirements:
184
+ - - ">="
185
+ - !ruby/object:Gem::Version
186
+ version: '0'
187
+ required_rubygems_version: !ruby/object:Gem::Requirement
188
+ requirements:
189
+ - - ">="
190
+ - !ruby/object:Gem::Version
191
+ version: '0'
192
+ requirements: []
193
+ rubyforge_project:
194
+ rubygems_version: 2.5.1
195
+ signing_key:
196
+ specification_version: 4
197
+ summary: Monosasi is a tool to manage Cloudwatch Events rules.
198
+ test_files: []