dogscaler 2.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 35e22796993fa0606bf74ec6f426af6e3698bc66
4
+ data.tar.gz: 58beff7cd38b0f963df35cee6f420c9297cb84fa
5
+ SHA512:
6
+ metadata.gz: 06605d6b5c6051b27b834f75ad5beac0eeffdb136f5ec24cf97edfa052a0c1bb3f530bb113cfc005f154d01d1d4d18f692b056146bc5ada6b9f62547603bf422
7
+ data.tar.gz: c8e85503590261d715196f959a00c78f237ab9da24d846a743f139577f5925017aae3d91780b3e767651a8b65f900a44dae63e8fd2344e331f0c82cd0502569d
data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ *.gem
2
+ *.yaml
3
+ build_gem.sh
data/CHANGELOG ADDED
@@ -0,0 +1,5 @@
1
+ Bugfix: If we attempt to scale before MAX, we scale to max instead of
2
+ stopping
3
+ Bugfix: fix state file handling, our config was always defaulting to {}.
4
+ Bugfix: better error handling when theres no autoscale group
5
+
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source "http://rubygems.org"
2
+ gem 'slack-ruby-client', '~> 0.7'
3
+ gem 'dogapi', '~> 1.23'
4
+ gem 'virtus', '~> 1.0'
5
+ gem 'facets', '~> 3.1'
6
+ gem 'thor', '~> 0.19'
7
+ gem 'aws-sdk','~> 2.6'
8
+ gem 'json', '~> 2.0'
data/Gemfile.lock ADDED
@@ -0,0 +1,75 @@
1
+ GEM
2
+ remote: http://rubygems.org/
3
+ specs:
4
+ activesupport (5.0.1)
5
+ concurrent-ruby (~> 1.0, >= 1.0.2)
6
+ i18n (~> 0.7)
7
+ minitest (~> 5.1)
8
+ tzinfo (~> 1.1)
9
+ aws-sdk (2.6.1)
10
+ aws-sdk-resources (= 2.6.1)
11
+ aws-sdk-core (2.6.1)
12
+ jmespath (~> 1.0)
13
+ aws-sdk-resources (2.6.1)
14
+ aws-sdk-core (= 2.6.1)
15
+ axiom-types (0.1.1)
16
+ descendants_tracker (~> 0.0.4)
17
+ ice_nine (~> 0.11.0)
18
+ thread_safe (~> 0.3, >= 0.3.1)
19
+ coercible (1.0.0)
20
+ descendants_tracker (~> 0.0.1)
21
+ concurrent-ruby (1.0.4)
22
+ descendants_tracker (0.0.4)
23
+ thread_safe (~> 0.3, >= 0.3.1)
24
+ dogapi (1.23.0)
25
+ multi_json
26
+ equalizer (0.0.11)
27
+ facets (3.1.0)
28
+ faraday (0.11.0)
29
+ multipart-post (>= 1.2, < 3)
30
+ faraday_middleware (0.11.0.1)
31
+ faraday (>= 0.7.4, < 1.0)
32
+ gli (2.15.0)
33
+ hashie (3.4.6)
34
+ i18n (0.7.0)
35
+ ice_nine (0.11.2)
36
+ jmespath (1.3.1)
37
+ json (2.0.3)
38
+ minitest (5.10.1)
39
+ multi_json (1.12.1)
40
+ multipart-post (2.0.0)
41
+ slack-ruby-client (0.7.8)
42
+ activesupport
43
+ faraday (>= 0.9)
44
+ faraday_middleware
45
+ gli
46
+ hashie
47
+ json
48
+ websocket-driver
49
+ thor (0.19.1)
50
+ thread_safe (0.3.5)
51
+ tzinfo (1.2.2)
52
+ thread_safe (~> 0.1)
53
+ virtus (1.0.5)
54
+ axiom-types (~> 0.1)
55
+ coercible (~> 1.0)
56
+ descendants_tracker (~> 0.0, >= 0.0.3)
57
+ equalizer (~> 0.0, >= 0.0.9)
58
+ websocket-driver (0.6.5)
59
+ websocket-extensions (>= 0.1.0)
60
+ websocket-extensions (0.1.2)
61
+
62
+ PLATFORMS
63
+ ruby
64
+
65
+ DEPENDENCIES
66
+ aws-sdk (~> 2.6)
67
+ dogapi (~> 1.23)
68
+ facets (~> 3.1)
69
+ json (~> 2.0)
70
+ slack-ruby-client (~> 0.7)
71
+ thor (~> 0.19)
72
+ virtus (~> 1.0)
73
+
74
+ BUNDLED WITH
75
+ 1.12.5
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2016, Cvent, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
data/README.md ADDED
@@ -0,0 +1,131 @@
1
+ Dogscaler
2
+ =======================
3
+ Dogscaler was written to scale up autoscale groups based on the results of a
4
+ datadog query.
5
+
6
+ ## Installation
7
+ Installation is easy just as any other gem:
8
+
9
+ ```bash
10
+ gem install dogscaler
11
+
12
+ ```
13
+
14
+ ## Configuration
15
+ ### Datadog API
16
+
17
+ Within datadog, you need to generate an application key and also include your api key. You can find this information from
18
+ Integrations -> Api
19
+
20
+
21
+ ### Amazon Permissions
22
+
23
+ Create a set of credentials in IAM and give them access to:
24
+ Autoscale -> DescribeAutoscaleGroups and
25
+ Autoscale -> UpdateAutoscaleGroups
26
+
27
+ These permissions are used to lookup autoscale groups, check their size and updated the desired number of instances.
28
+
29
+
30
+ ### Config File
31
+ Create a dogscaler.yaml file with contents like:
32
+
33
+ ```
34
+
35
+ datadog:
36
+ api_key: <KEYHERE>
37
+ application_key: <KEYHERE>
38
+ aws:
39
+ region: 'us-west-2'
40
+ profile: 'main' # This expects a .aws/credentials file with a section matching this name
41
+ slack:
42
+ channel: '#production'
43
+ api_token: 'token_here'
44
+
45
+ instances:
46
+ 'mailer_prod':
47
+ queries:
48
+ - name: unsent_invites
49
+ query: max:mail.db.v3.unsent_invitations{*}
50
+ scale_up_threshhold: 1500
51
+ scale_down_threshhold: 20
52
+ transform: avg
53
+ - name: mailer load
54
+ query: avg:system.cpu.user{env:production,type:mailer}
55
+ scale_up_threshhold: 75
56
+ scale_down_threshhold: 20
57
+ transform: avg
58
+ asg_tag_filters:
59
+ Type: mailer
60
+ Environment: production
61
+ grow_by: 1
62
+ shrink_by: 1
63
+ cooldown_period: 240
64
+ 'web_prod':
65
+ queries:
66
+ - name: web load
67
+ query: avg:system.cpu.user{env:production,type:web}
68
+ scale_up_threshhold: 75
69
+ scale_down_threshhold: 20
70
+ transform: avg
71
+ asg_tag_filters:
72
+ Type: web
73
+ Environment: production
74
+ grow_by: 2
75
+ shrink_by: 1
76
+ cooldown_period: 240
77
+ ```
78
+
79
+ ## Usage
80
+
81
+
82
+ Below are some simple examples
83
+
84
+ Help output:
85
+
86
+ ```bash
87
+ dogscaler help
88
+ Commands:
89
+ dogscaler apply # Scale the environment based on a query
90
+ dogscaler config # Generate a default configuration
91
+ dogscaler debug # testing command, describes the query it ran and the results
92
+ dogscaler help [COMMAND] # Describe available commands or one specific command
93
+
94
+ Options:
95
+ d, [--debug=Enable debug mode], [--no-debug]
96
+ r, [--region=AWS Region]
97
+ # Default: us-west-2
98
+ v, [--verbose=Verbose Output], [--no-verbose]
99
+ t, [--terse=Terse Output], [--no-terse]
100
+ [--dryrun=Do a dry run], [--no-dryrun]
101
+ [--config=Path to configuration file]
102
+ ```
103
+
104
+ The basic example - Apply the configuration.
105
+
106
+ ```
107
+ $ dogscaler apply --config dogscaler.yaml
108
+ ```
109
+
110
+ Test the configuration without making changes, with verbose output:
111
+
112
+ ```bash
113
+ $ dogscaler apply --dryrun -v --config dogscaler.yaml
114
+ INFO -- : Value: 147.01052631578946 Threshold: 75.
115
+ INFO -- : Would scale up by 2 instances.
116
+ INFO -- : Value: 147.01052631578946 Threshold: 75.
117
+ INFO -- : Would scale up by 2 instances.
118
+ INFO -- : Updating autoscale group production
119
+ INFO -- : From current capacity: 1 to: 2
120
+ INFO -- : Not updating due to dry run mode
121
+ INFO -- : Value: 3.0 Threshold: 5.
122
+ INFO -- : Would scale down by 1 instances.
123
+ INFO -- : Would have reduced capacity of production-web but already at minimum.
124
+ INFO -- : Current desired: 3
125
+ INFO -- : Current min: 3
126
+ ```
127
+
128
+ And then in slack you'll see:
129
+
130
+ <img src="docs/images/datadog_example.jpg?raw=true" width="77%"/>
131
+
data/TODO ADDED
@@ -0,0 +1,6 @@
1
+ What happens if we have multiple queries we want to scale the same autogroup based on?
2
+ eg. number of emails in a queue (or) load on a system.
3
+
4
+ Can we look up the last scale event for a group and use that to determine a cooldown between scaling events.
5
+
6
+
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 2.0.10
data/bin/dogscaler ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'rubygems'
4
+ require 'yaml'
5
+ require 'thor'
6
+ require 'virtus'
7
+ # Fix for slack client gem
8
+ require "active_support/core_ext/module/remove_method"
9
+
10
+ require_relative '../lib/logging'
11
+ require_relative '../lib/settings'
12
+ require_relative '../lib/dogscaler/config'
13
+ require_relative '../lib/dogscaler/query'
14
+ require_relative '../lib/dogscaler/instance'
15
+ require_relative '../lib/dogscaler/state'
16
+ require_relative '../lib/dogscaler/datadog'
17
+ require_relative '../lib/dogscaler/slack'
18
+ require_relative '../lib/dogscaler/awsclient'
19
+ require_relative '../lib/dogscaler/cli'
20
+
21
+
22
+ Dogscaler::Cli.start(ARGV)
Binary file
data/dogscaler.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "dogscaler"
8
+ spec.version = Dogscaler::VERSION
9
+ spec.authors = ["David Gibbons"]
10
+ spec.email = ["dgibbons@crowdcompass.com"]
11
+ spec.summary = %q{Autoscale groups based on datadog queries}
12
+ spec.description = %q{Autoscale aws groups based on datadog queries}
13
+ spec.license = "apache"
14
+ spec.executables << 'dogscaler'
15
+ spec.files = `git ls-files -z`.split("\x0")
16
+ spec.require_paths = ["lib"]
17
+
18
+ spec.add_development_dependency "bundler", "~> 1.9"
19
+ spec.add_dependency "thor", '~> 0.19'
20
+ spec.add_dependency 'dogapi', '~> 1.23'
21
+ spec.add_dependency 'virtus', '~> 1.0'
22
+ spec.add_dependency 'facets', '~> 3.1'
23
+ spec.add_dependency 'aws-sdk', '~> 2.6'
24
+ spec.add_dependency 'json', '~> 2.0'
25
+ spec.add_dependency 'slack-ruby-client', '~> 0.7'
26
+
27
+ end
@@ -0,0 +1,30 @@
1
+ datadog:
2
+ api_key: <KEYHERE>
3
+ application_key: <KEYHERE>
4
+ aws:
5
+ region: 'us-west-2'
6
+ profile: 'main'
7
+ instances:
8
+ -
9
+ name: 'nginx wait in dev'
10
+ query: "max:nginx.net.waiting{env:dev}"
11
+ autoscale_group: "development"
12
+ scale_up_threshhold: 75
13
+ scale_down_threshhold: 20
14
+ grow_by: 2
15
+ shrink_by: 1
16
+ transform: avg
17
+ -
18
+ name: 'nginx wait in prod'
19
+ query: "max:nginx.net.waiting{env:production}"
20
+ asg_tag_filters:
21
+ Type: web
22
+ Environment: production
23
+ scale_up_threshhold: 10
24
+ scale_down_threshhold: 5
25
+ grow_by: 2
26
+ shrink_by: 1
27
+ transform: min
28
+
29
+
30
+
@@ -0,0 +1,101 @@
1
+ require 'aws-sdk'
2
+
3
+ module Dogscaler
4
+ class AwsClient
5
+ NoResultsError = Class.new(StandardError)
6
+ TooManyResultsError = Class.new(StandardError)
7
+ NoAutoscaleNameFound = Class.new(StandardError)
8
+ include Logging
9
+
10
+ def initialize
11
+ @credentials = Aws::SharedCredentials.new(profile_name: Settings.aws['profile'])
12
+ @region = Settings.aws['region']
13
+ end
14
+
15
+ def asg_client
16
+ @asg_client ||= Aws::AutoScaling::Client.new(credentials: @credentials, :region => @region)
17
+ end
18
+
19
+ def ec2_client
20
+ @ec2_client ||= Aws::EC2::Client.new(credentials: @credentials, :region => @region)
21
+ end
22
+
23
+ def get_autoscale_groups
24
+ next_token = nil
25
+ autoscalegroups = []
26
+ loop do
27
+ body = {next_token: next_token}
28
+ resp = asg_client.describe_auto_scaling_groups(body)
29
+ asgs = resp.auto_scaling_groups
30
+ asgs.each do |instance|
31
+ autoscalegroups << instance
32
+ end
33
+ next_token = resp.next_token
34
+ break if next_token.nil?
35
+ end
36
+ return autoscalegroups
37
+ end
38
+
39
+ def autoscalegroups
40
+ @@asgs ||= get_autoscale_groups
41
+ end
42
+
43
+ def get_asg(asg_name=nil, asg_tag_filters = {})
44
+ raise NoAutoscaleNameFound if asg_name.nil? and asg_tag_filters.empty?
45
+
46
+ if not asg_tag_filters.empty?
47
+ asg_name = autoscalegroups.select do |group|
48
+ validate_tags(group.tags, asg_tag_filters)
49
+ end
50
+ else
51
+ asg_name = autoscalegroups.select do |group|
52
+ group.auto_scaling_group_name == asg_name
53
+ end
54
+ end
55
+
56
+ asg_name.select! do |group|
57
+ group.desired_capacity > 0 and
58
+ group.max_size > 0
59
+ end
60
+
61
+ raise TooManyResultsError if asg_name.count > 1
62
+ if asg_name.empty?
63
+ logger.error "No results found for asg_name #{asg_name}, filters: #{asg_tag_filters}"
64
+ raise NoResultsError
65
+ end
66
+ return asg_name.first
67
+ end
68
+
69
+ def validate_tags(tags, filters)
70
+ values = []
71
+ filters.each do |key, value|
72
+ trueness = false
73
+ logger.debug "Checking: #{key} for: #{value}"
74
+ tags.each do |tag|
75
+ if tag['key'] == key && tag['value'] == value
76
+ trueness = true
77
+ break
78
+ end
79
+ end
80
+ values << trueness
81
+ end
82
+ # we're good if the results are all good
83
+ values.all?
84
+ end
85
+
86
+ def get_capacity(asg_name)
87
+ asg_client.describe_auto_scaling_groups({auto_scaling_group_names: \
88
+ [asg_name] }).auto_scaling_groups.first.desired_capacity
89
+ end
90
+
91
+ def set_capacity(instance, options)
92
+ template = {
93
+ auto_scaling_group_name: instance.autoscalegroupname,
94
+ desired_capacity: instance.change
95
+ }
96
+
97
+ logger.debug template
98
+ asg_client.update_auto_scaling_group(template)
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,82 @@
1
+ require 'logger'
2
+ # Used for the symbolize_keys method
3
+ require 'facets'
4
+
5
+ module Dogscaler
6
+ class Cli < Thor
7
+ include Logging
8
+ class_option :debug, :aliases => [ :d ],
9
+ :type => :boolean, :banner => "Enable debug mode", :default => false
10
+ class_option :region, :aliases => [ :r ],
11
+ :type => :string, :banner => "AWS Region", :default => 'us-west-2'
12
+ class_option :verbose, :aliases => [ :v ],
13
+ :type => :boolean, :banner => "Verbose Output", :default => false
14
+ class_option :terse, :aliases => [ :t],
15
+ :type => :boolean, :banner => "Terse Output", :default => false
16
+ class_option :dryrun, :alias => [ :n ],
17
+ :type => :boolean, :banner => "Do a dry run", :default => false
18
+ class_option :config,
19
+ :type => :string, :banner => "Path to configuration file"
20
+
21
+
22
+ desc "debug", "testing command, describes the query it ran and the results"
23
+ def debug
24
+ Settings.load!(File.expand_path(options[:config])) if options[:config]
25
+ Settings.instances.each do |i|
26
+ instance = Dogscaler::Instance.new
27
+ instance.attributes = i.symbolize_keys
28
+ dd_client = Dogscaler::Datadog.new(Settings.datadog)
29
+ dd_client.process(instance)
30
+ end
31
+ end
32
+
33
+ desc "config", "Generate a default configuration"
34
+ def config
35
+ Dogscaler::Config.new.generate
36
+ end
37
+
38
+ desc "apply", "Scale the environment based on a query"
39
+ def apply
40
+ Settings.load!(File.expand_path(options[:config])) if options[:config]
41
+
42
+ if options[:debug]
43
+ self.class.logger.level = Logger::DEBUG
44
+ elsif options[:terse]
45
+ self.class.logger.level = Logger::ERROR
46
+ elsif options[:verbose]
47
+ self.class.logger.level = Logger::INFO
48
+ else
49
+ self.class.logger.level = Logger::WARN
50
+ end
51
+
52
+ instances = []
53
+ Settings.instances.each do |k,v|
54
+ instance = Dogscaler::Instance.new
55
+ instance.attributes = v.symbolize_keys
56
+ instance.process_checks
57
+ instances << instance
58
+ end
59
+ state = Dogscaler::State.new
60
+ begin
61
+ slack = Dogscaler::SlackClient.new(Settings.slack['api_token'], Settings.slack['channel'])
62
+ rescue NoMethodError
63
+ # Slack not configured
64
+ slack = false
65
+ end
66
+ instances.each do |instance|
67
+ if instance.preflight_checks(state)
68
+ message = "Scaling #{instance.autoscalegroupname} from #{instance.capacity} to #{instance.change}"
69
+ logger.info(message)
70
+ if options[:dryrun]
71
+ logger.info "Not updating due to dry run mode"
72
+ else
73
+ slack.send_message(message) if slack
74
+ state.update(instance.autoscalegroupname)
75
+ instance.update_capacity(options)
76
+ end
77
+ end
78
+ end
79
+ state.save!
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,49 @@
1
+ module Dogscaler
2
+ class Config
3
+ def generate
4
+ config = <<-END
5
+ # Enter your datadog api credentials here:
6
+ datadog:
7
+ api_key: KEYHERE
8
+ application_key: KEYHERE
9
+ # This assumes you have a ~/.aws/credentials file, if you use multiple, you can specify which profile to use here.
10
+ aws:
11
+ region: us-west-2
12
+ profile: default
13
+ slack:
14
+ channel: '#slack'
15
+ api_token: TOKENHERE
16
+
17
+ # This is a list of events to check for. Each event will be checked on each run.
18
+ instances:
19
+ 'core':
20
+ queries:
21
+ - name: 'scale on cpu user'
22
+ query: avg:system.cpu.user{env:production,type:core}
23
+ scale_up_threshhold: 10 # scale up if the query surpasses this values
24
+ scale_down_threshhold: 5 # scale down if the query goes below this value
25
+ transform: avg # What transform to use on the query, eg (min,max,last,avg,count)
26
+ shrink_by: 1 # How many instances to add to the autoscale group
27
+ grow_by: 1 # how many instances to remove from the autoscale group
28
+ cooldown: 60 # Cooldown time between autoscale events should trigger.
29
+ asg_tag_filters: # key value tags of filter and find our autoscale group.
30
+ Type: core
31
+ Environment: production
32
+ 'mailer':
33
+ queries:
34
+ - name: 'scale on user invites'
35
+ query: max:mailer.db.v3.unsent_invitations{*}
36
+ scale_up_threshhold: 1
37
+ scale_down_threshhold: 0
38
+ transform: avg
39
+ grow_by: 1
40
+ shrink_by: 1
41
+ asg_tag_filters:
42
+ Type: mailer
43
+ Environment: production
44
+ END
45
+ puts config
46
+ end
47
+ end
48
+ end
49
+
@@ -0,0 +1,34 @@
1
+ require 'dogapi'
2
+ module Dogscaler
3
+ class Datadog
4
+ include Logging
5
+ def initialize(settings)
6
+ @dog ||= Dogapi::Client.new(settings['api_key'], settings['application_key'])
7
+ end
8
+
9
+ def process(query, period=5)
10
+ to = Time.now
11
+ from = to - (period.to_i*60)
12
+ res = @dog.get_points(query, from.strftime('%s'), to.strftime('%s'))
13
+ if res[0] != '200'
14
+ logger.error "Error code generated on query, please validate your api keys, and query"
15
+ logger.error "query: #{query}"
16
+ logger.error "Result: #{res}"
17
+ exit 1
18
+ end
19
+ if res[1]['series'].empty?
20
+ logger.error "No results returned from query #{instance.query}"
21
+ exit 1
22
+ end
23
+ points = unzip(res)
24
+
25
+ end
26
+
27
+ def unzip(raw)
28
+ points = []
29
+ raw[1]['series'][0]['pointlist'].each {|k,v| points << v.to_i }
30
+ points
31
+ end
32
+ end
33
+ end
34
+
@@ -0,0 +1,134 @@
1
+
2
+ module Dogscaler
3
+ class Instance
4
+ include Virtus.model
5
+ include Logging
6
+ attribute :name, String
7
+ attribute :cooldown_period, Integer
8
+ attribute :queries, Array, :default => []
9
+ attribute :parsed_queries, Array
10
+ attribute :grow_by, Integer, :default => 1
11
+ attribute :shrink_by, Integer, :default => 1
12
+ attribute :asg_tag_filters, Hash
13
+ attribute :autoscale_group, String
14
+ attribute :capacity, Integer
15
+
16
+ def initialize
17
+ @checks = []
18
+ end
19
+ def cooldown
20
+ self.cooldown_period || 60
21
+ end
22
+
23
+ def asg
24
+ @asg ||= aws.get_asg(self.autoscale_group, self.asg_tag_filters)
25
+ end
26
+
27
+ def aws
28
+ @aws ||= Dogscaler::AwsClient.new
29
+ end
30
+
31
+ def checks
32
+ @checks
33
+ end
34
+
35
+ def max_instances
36
+ asg.max_size
37
+ end
38
+
39
+ def min_instances
40
+ asg.min_size
41
+ end
42
+
43
+ def autoscalegroupname
44
+ asg.auto_scaling_group_name
45
+ end
46
+
47
+ def preflight_checks(state)
48
+ # Quick fail filters
49
+ # Don't do anything if we're already at the capactiy we think we should be
50
+ if self.change == self.capacity
51
+ logger.debug "Instance count: #{self.change} matches capacity: #{self.capacity}"
52
+ return false
53
+ end
54
+ # Don't do anything if we have scaled recently
55
+ if Time.now - state.get(self.autoscalegroupname) < self.cooldown
56
+ logger.debug "We've scaled too soon, cooling down"
57
+ return false
58
+ end
59
+ # Don't do anything if the new value is lower than the minimium
60
+ if self.change < self.min_instances
61
+ logger.debug "New size: #{self.change} smaller than min count: #{self.min_instances}"
62
+ return false
63
+ end
64
+ # Don't do anything if the new value is higher than the maximum
65
+ if self.change > self.max_instances
66
+ logger.debug "New size: #{self.change} larger than max count: #{self.max_instances}"
67
+ if self.capacity == self.max_instances
68
+ logger.debug "Already at max, doing nothing"
69
+ return false
70
+ else
71
+ logger.debug "Updating to the max: #{self.max_instances}"
72
+ self.change = self.max_instances
73
+ return true
74
+ end
75
+ end
76
+ true
77
+ end
78
+
79
+ def capacity
80
+ asg.desired_capacity
81
+ end
82
+
83
+ def process_checks
84
+ dd_client = Dogscaler::Datadog.new(Settings.datadog)
85
+ self.queries.each do |i|
86
+ check = Dogscaler::Check.new()
87
+ check.attributes = i.symbolize_keys
88
+ check.points = dd_client.process(i['query'])
89
+ check.reduce!
90
+ @checks << check
91
+ end
92
+ end
93
+
94
+ def grow?
95
+ self.checks.any? {|c| c.status > 0 }
96
+ end
97
+
98
+ def shrink?
99
+ self.checks.any? {|c| c.status < 0 }
100
+ end
101
+
102
+ def shrink
103
+ capacity + -shrink_by.to_i.abs
104
+ end
105
+
106
+ def grow
107
+ capacity + grow_by.to_i.abs
108
+ end
109
+
110
+ def update_capacity(options)
111
+ aws.set_capacity(self, options)
112
+ end
113
+
114
+ def change=(value)
115
+ @change = value
116
+ end
117
+
118
+ def process_change
119
+ if self.grow?
120
+ change = self.grow
121
+ elsif self.shrink?
122
+ change = self.shrink
123
+ else
124
+ change = capacity
125
+ end
126
+ change
127
+ end
128
+
129
+ def change
130
+ @change || process_change
131
+ end
132
+
133
+ end
134
+ end
@@ -0,0 +1,54 @@
1
+ module Dogscaler
2
+ class Check
3
+ include Virtus.model
4
+ include Logging
5
+ NoPointsSetError = Class.new(StandardError)
6
+ NoResultsSetError = Class.new(StandardError)
7
+
8
+ attribute :scale_up_threshhold, Integer
9
+ attribute :scale_down_threshhold, Integer
10
+ attribute :transform, String, :default => 'avg'
11
+ attribute :points, Array, :default => []
12
+ attribute :result, Float
13
+
14
+ def status
15
+ raise NoResultSetError, 'No results set on this object' if not result
16
+ if self.result > scale_up_threshhold
17
+ logger.debug "Value: #{result} Threshold: #{scale_up_threshhold}."
18
+ 1
19
+ elsif self.result < scale_down_threshhold
20
+ logger.debug "Value: #{result} Threshold: #{scale_down_threshhold}."
21
+ -1
22
+ else
23
+ logger.debug "Value: #{result} Max Threshold: #{scale_up_threshhold}."
24
+ logger.debug "Value: #{result} Min Threshold: #{scale_down_threshhold}."
25
+ 0
26
+ end
27
+ end
28
+
29
+ def reduce!
30
+ raise NoPointsSetError, 'No points are set on this object' if points.empty?
31
+ logger.debug "Apply transform #{transform}"
32
+ case transform
33
+ when 'avg'
34
+ result = points.inject(0.0) { |sum,el| sum + el } / points.size
35
+ when 'max'
36
+ result = points.max
37
+ when 'min'
38
+ result = points.min
39
+ when 'last'
40
+ result = points[-1]
41
+ when 'sum'
42
+ result = points.reduce(0, :+)
43
+ when 'count'
44
+ result = points.count
45
+ else
46
+ logger.error 'Invalid transform: #{transform}'
47
+ exit 1
48
+ end
49
+ logger.debug "Transformed value #{result}"
50
+ self.result = result
51
+ end
52
+
53
+ end
54
+ end
@@ -0,0 +1,5 @@
1
+ module Dogscaler
2
+ class Rules
3
+
4
+ end
5
+ end
@@ -0,0 +1,20 @@
1
+ require 'slack-ruby-client'
2
+
3
+ module Dogscaler
4
+ class SlackClient
5
+ include Logging
6
+ def initialize(api_token, channel)
7
+ Slack.configure do |config|
8
+ config.token = api_token
9
+ end
10
+ @client = Slack::Web::Client.new
11
+ @channel = channel
12
+ end
13
+
14
+ def send_message(message)
15
+ @client.chat_postMessage(:channel => @channel, :text => message, :as_user => true)
16
+ end
17
+
18
+ end
19
+ end
20
+
@@ -0,0 +1,34 @@
1
+ module Dogscaler
2
+ class State
3
+ include Logging
4
+ def initialize
5
+ @state = self.load
6
+ @config = '/tmp/dogscaler.yaml'
7
+ end
8
+
9
+ def load
10
+ begin
11
+ YAML.load_file(@config)
12
+ rescue
13
+ {}
14
+ end
15
+ end
16
+
17
+ def get(asg)
18
+ @state[asg] || Time.parse("2017-01-31 12:00:00")
19
+ end
20
+
21
+ def update(asg)
22
+ t = Time.now
23
+ logger.debug "Updating the timestamp for #{asg} to #{t}"
24
+ @state[asg] = t
25
+ end
26
+
27
+ def save!
28
+ logger.debug "Saving state to #{@config}"
29
+ File.open( @config, 'w' ) do |out|
30
+ YAML.dump( @state, out )
31
+ end
32
+ end
33
+ end
34
+ end
data/lib/logging.rb ADDED
@@ -0,0 +1,34 @@
1
+ require 'logger'
2
+
3
+ module Logging
4
+ class << self
5
+ def logger
6
+ @logger ||= Logger.new($stdout)
7
+ end
8
+
9
+ def logger=(logger)
10
+ @logger = logger
11
+ end
12
+
13
+ def level=(level)
14
+ @logger.level=level
15
+ end
16
+
17
+ def warn
18
+ @logger.level=Logger::WARN
19
+ end
20
+ end
21
+
22
+ # Addition
23
+ def self.included(base)
24
+ class << base
25
+ def logger
26
+ Logging.logger
27
+ end
28
+ end
29
+ end
30
+
31
+ def logger
32
+ Logging.logger
33
+ end
34
+ end
data/lib/settings.rb ADDED
@@ -0,0 +1,32 @@
1
+ require 'yaml'
2
+ module Settings
3
+ # again - it's a singleton, thus implemented as a self-extended module
4
+ extend self
5
+
6
+ @_settings = {}
7
+ attr_reader :_settings
8
+
9
+ # This is the main point of entry - we call Settings.load! and provide
10
+ # a name of the file to read as it's argument.
11
+ def load!(filename)
12
+ newsets = YAML::load_file(filename)
13
+ deep_merge!(@_settings, newsets)
14
+ end
15
+
16
+ # Deep merging of hashes
17
+ # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
18
+ def deep_merge!(target, data)
19
+ merger = proc{|key, v1, v2|
20
+ Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
21
+ target.merge! data, &merger
22
+ end
23
+
24
+ def method_missing(name, *args, &block)
25
+ return @_settings[name.to_s] ||
26
+ fail(NoMethodError, "Unknown configuration root #{name}", caller)
27
+ end
28
+
29
+ end
30
+ app_name = "dogscaler"
31
+ overrides = File.expand_path("~/.#{app_name}.yaml")
32
+ Settings.load!(overrides) if File.exists? overrides
data/lib/version.rb ADDED
@@ -0,0 +1,3 @@
1
+ module Dogscaler
2
+ VERSION = "2.0.10"
3
+ end
metadata ADDED
@@ -0,0 +1,183 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dogscaler
3
+ version: !ruby/object:Gem::Version
4
+ version: 2.0.10
5
+ platform: ruby
6
+ authors:
7
+ - David Gibbons
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-05-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.9'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.9'
27
+ - !ruby/object:Gem::Dependency
28
+ name: thor
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.19'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.19'
41
+ - !ruby/object:Gem::Dependency
42
+ name: dogapi
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.23'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.23'
55
+ - !ruby/object:Gem::Dependency
56
+ name: virtus
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: facets
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.1'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.1'
83
+ - !ruby/object:Gem::Dependency
84
+ name: aws-sdk
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '2.6'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '2.6'
97
+ - !ruby/object:Gem::Dependency
98
+ name: json
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '2.0'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '2.0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: slack-ruby-client
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '0.7'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '0.7'
125
+ description: Autoscale aws groups based on datadog queries
126
+ email:
127
+ - dgibbons@crowdcompass.com
128
+ executables:
129
+ - dogscaler
130
+ extensions: []
131
+ extra_rdoc_files: []
132
+ files:
133
+ - ".gitignore"
134
+ - CHANGELOG
135
+ - Gemfile
136
+ - Gemfile.lock
137
+ - LICENSE
138
+ - README.md
139
+ - TODO
140
+ - VERSION
141
+ - bin/dogscaler
142
+ - build_gem.sh
143
+ - docs/images/datadog_example.jpg
144
+ - dogscaler.gemspec
145
+ - dogscaler.yaml-example
146
+ - lib/dogscaler/awsclient.rb
147
+ - lib/dogscaler/cli.rb
148
+ - lib/dogscaler/config.rb
149
+ - lib/dogscaler/datadog.rb
150
+ - lib/dogscaler/instance.rb
151
+ - lib/dogscaler/query.rb
152
+ - lib/dogscaler/rule.rb
153
+ - lib/dogscaler/slack.rb
154
+ - lib/dogscaler/state.rb
155
+ - lib/logging.rb
156
+ - lib/settings.rb
157
+ - lib/version.rb
158
+ homepage:
159
+ licenses:
160
+ - apache
161
+ metadata: {}
162
+ post_install_message:
163
+ rdoc_options: []
164
+ require_paths:
165
+ - lib
166
+ required_ruby_version: !ruby/object:Gem::Requirement
167
+ requirements:
168
+ - - ">="
169
+ - !ruby/object:Gem::Version
170
+ version: '0'
171
+ required_rubygems_version: !ruby/object:Gem::Requirement
172
+ requirements:
173
+ - - ">="
174
+ - !ruby/object:Gem::Version
175
+ version: '0'
176
+ requirements: []
177
+ rubyforge_project:
178
+ rubygems_version: 2.4.8
179
+ signing_key:
180
+ specification_version: 4
181
+ summary: Autoscale groups based on datadog queries
182
+ test_files: []
183
+ has_rdoc: