sabisu 0.1.0

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2cd133c8076adffa6df6d2f18691642d3303a05c
4
+ data.tar.gz: 2e19dc2b651091c1708d0f7f762ac8941df969ee
5
+ SHA512:
6
+ metadata.gz: 4c2f8bd36a2082638081cb41243430bf1a9e64695151a0c4aa4b46bf3291be00256d9404ce3c9e4bf55e6219f664087d74344fb60d36dcb4722decf531a47ae0
7
+ data.tar.gz: 4ed3a5d3d7bad02497bb6365c1774b1cff85af744335d7d6eb9828e4c895812e27c44d2953ccd38fb7b040183336878c2276addb2d463904222ef5f719181811
data/LICENSE ADDED
@@ -0,0 +1,191 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work (an example is provided in the Appendix below).
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License.
62
+
63
+ Subject to the terms and conditions of this License, each Contributor hereby
64
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+ irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+ publicly display, publicly perform, sublicense, and distribute the Work and such
67
+ Derivative Works in Source or Object form.
68
+
69
+ 3. Grant of Patent License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby
72
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+ irrevocable (except as stated in this section) patent license to make, have
74
+ made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+ such license applies only to those patent claims licensable by such Contributor
76
+ that are necessarily infringed by their Contribution(s) alone or by combination
77
+ of their Contribution(s) with the Work to which such Contribution(s) was
78
+ submitted. If You institute patent litigation against any entity (including a
79
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80
+ Contribution incorporated within the Work constitutes direct or contributory
81
+ patent infringement, then any patent licenses granted to You under this License
82
+ for that Work shall terminate as of the date such litigation is filed.
83
+
84
+ 4. Redistribution.
85
+
86
+ You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+ in any medium, with or without modifications, and in Source or Object form,
88
+ provided that You meet the following conditions:
89
+
90
+ You must give any other recipients of the Work or Derivative Works a copy of
91
+ this License; and
92
+ You must cause any modified files to carry prominent notices stating that You
93
+ changed the files; and
94
+ You must retain, in the Source form of any Derivative Works that You distribute,
95
+ all copyright, patent, trademark, and attribution notices from the Source form
96
+ of the Work, excluding those notices that do not pertain to any part of the
97
+ Derivative Works; and
98
+ If the Work includes a "NOTICE" text file as part of its distribution, then any
99
+ Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+ You may add Your own copyright statement to Your modifications and may provide
112
+ additional or different license terms and conditions for use, reproduction, or
113
+ distribution of Your modifications, or for any such Derivative Works as a whole,
114
+ provided Your use, reproduction, and distribution of the Work otherwise complies
115
+ with the conditions stated in this License.
116
+
117
+ 5. Submission of Contributions.
118
+
119
+ Unless You explicitly state otherwise, any Contribution intentionally submitted
120
+ for inclusion in the Work by You to the Licensor shall be under the terms and
121
+ conditions of this License, without any additional terms or conditions.
122
+ Notwithstanding the above, nothing herein shall supersede or modify the terms of
123
+ any separate license agreement you may have executed with Licensor regarding
124
+ such Contributions.
125
+
126
+ 6. Trademarks.
127
+
128
+ This License does not grant permission to use the trade names, trademarks,
129
+ service marks, or product names of the Licensor, except as required for
130
+ reasonable and customary use in describing the origin of the Work and
131
+ reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty.
134
+
135
+ Unless required by applicable law or agreed to in writing, Licensor provides the
136
+ Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138
+ including, without limitation, any warranties or conditions of TITLE,
139
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140
+ solely responsible for determining the appropriateness of using or
141
+ redistributing the Work and assume any risks associated with Your exercise of
142
+ permissions under this License.
143
+
144
+ 8. Limitation of Liability.
145
+
146
+ In no event and under no legal theory, whether in tort (including negligence),
147
+ contract, or otherwise, unless required by applicable law (such as deliberate
148
+ and grossly negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special, incidental,
150
+ or consequential damages of any character arising as a result of this License or
151
+ out of the use or inability to use the Work (including but not limited to
152
+ damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153
+ any and all other commercial damages or losses), even if such Contributor has
154
+ been advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability.
157
+
158
+ While redistributing the Work or Derivative Works thereof, You may choose to
159
+ offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160
+ other liability obligations and/or rights consistent with this License. However,
161
+ in accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if You
163
+ agree to indemnify, defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason of your
165
+ accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "[]" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included on
176
+ the same "printed page" as the copyright notice for easier identification within
177
+ third-party archives.
178
+
179
+ Copyright [yyyy] [name of copyright owner]
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,72 @@
1
+ [![Build Status](https://magnum.travis-ci.com/cloudant/sabisu.png?token=r6PdrwNFR1nUzFeEEiQ6&branch=master)](https://magnum.travis-ci.com/cloudant/sabisu)
2
+ sabisu
3
+ ======
4
+
5
+ A sensu web UI powered by [Cloudant](https://cloudant.com)
6
+
7
+ Features
8
+ ========
9
+
10
+ * Full text search (based on [Lucene](http://lucene.apache.org/))
11
+ * Complex search, filtering, and sorting
12
+ * Smart autocomplete to help you find what you're looking for
13
+ * Statistical analysis of your search/query (faceting)
14
+ * Real-time streaming updates to the event list and stats (non-polling)
15
+ * Add custom attributes to your sensu events and make them searchable, indexed, and give them statistical context
16
+ * Easy "drill down" by clicking on any client, check, status or even custom attributes to see more events like them
17
+ * Silence with expiration timeout, unsilence on resolve, or never expire
18
+ * Create views of your sensu environment and save, bookmark, and share them with your colleagues
19
+
20
+ Demo
21
+ ====
22
+
23
+ If you want to take sabisu for a test drive, jump over to the [demo](http://demo.sabisuapp.org/)
24
+
25
+ Screenshots
26
+ ===========
27
+
28
+ ![Dashboard](https://raw.githubusercontent.com/cloudant/sabisu/master/screenshots/example.png "dashboard")
29
+
30
+ Requirements
31
+ ============
32
+
33
+ [Sensu](https://github.com/sensu/sensu) >= [0.12.1](https://github.com/sensu/sensu/blob/master/CHANGELOG.md#0121---2013-11-02)
34
+
35
+ Installation
36
+ ============
37
+
38
+ For installation instruction, go [here](https://github.com/cloudant/sabisu/wiki/Installation)
39
+
40
+ Development Environment
41
+ =======================
42
+
43
+ To setup sabisu for local development:
44
+
45
+ 1. First setup/install [RVM](https://rvm.io/) (or something like it, i.e. [rbenv](http://rbenv.org/)). It is a good idea to keep your dev environment separate from your system Ruby.
46
+ 2. Clone the repo (`git clone git@github.com:cloudant/sabisu.git`).
47
+ 3. Create an `.env` file to setup your environment variables (see [Environment Variables](https://github.com/cloudant/sabisu/wiki/Installation#environment-variables)).
48
+ 4. Source the file (`source .env`).
49
+ 5. Next run `bundle install` to install all gem dependencies.
50
+
51
+ sabisu uses [CoffeeScript](http://coffeescript.org/). You'll need to have npm (node package manager) setup first.
52
+ ```bash
53
+ curl http://npmjs.org/install.sh | sh
54
+ ```
55
+
56
+ Once you have npm installed, you can install CoffeeScript with:
57
+ ```bash
58
+ sudo npm install`
59
+ ```
60
+
61
+ 6. You'll need to generate the js files needed for sabisu, to do so run
62
+
63
+ ```bash
64
+ grunt coffee
65
+ ```
66
+ **TIP** you can also run `grunt watch` to update the js files everytime a coffee file has changed.
67
+
68
+ 7. Start sabisu
69
+ ```bash
70
+ foreman start
71
+ ```
72
+ 8. In your browser, visit [localhost:8080](http://localhost:8080).
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'optparse'
4
+ require 'json'
5
+
6
+ opt_parser = OptionParser.new do |opt|
7
+ opt.banner = 'Usage: sabisu [OPTIONS]'
8
+
9
+ opt.on('-c', '--config FILE', 'config file in json format') do |c|
10
+ CONFIG_FILE = JSON.parse(File.read(c), symbolize_names: true)
11
+ end
12
+
13
+ opt.on('-p', '--port INT', 'port to run on') do |p|
14
+ PORT = p
15
+ end
16
+
17
+ opt.on('-e', '--environment ENVIRONMENT',
18
+ 'environment to run as (ie "production" or "development"') do |e|
19
+ SABISU_ENV = e
20
+ end
21
+
22
+ opt.on('-h', '--help', 'help') do
23
+ puts opt_parser
24
+ exit 0
25
+ end
26
+ end
27
+
28
+ opt_parser.parse!
29
+
30
+ CONFIG_FILE = {} unless defined?(CONFIG_FILE)
31
+
32
+ begin
33
+ # look for local copy first for dev purposes
34
+ require_relative '../lib/sabisu'
35
+ rescue LoadError
36
+ require 'sabisu'
37
+ end
38
+
39
+ Sabisu::Server.run!
@@ -0,0 +1,5 @@
1
+ require_relative 'sabisu/server'
2
+
3
+ # Sensu dashboard powered by Cloudant
4
+ module Sabisu
5
+ end
@@ -0,0 +1,116 @@
1
+ # extend String class
2
+ class String
3
+ def to_bool
4
+ self == true || self =~ (/(true|t|yes|y|1)$/i) ? true : false
5
+ end
6
+ end
7
+
8
+ # Sensu dashboard powered by Cloudant
9
+ module Sabisu
10
+ # server class
11
+ class Server
12
+ if defined?(::CONFIG_FILE)
13
+ CONFIG_FILE = ::CONFIG_FILE
14
+ else
15
+ CONFIG_FILE = {}
16
+ end
17
+
18
+ configure do
19
+ # set the environment
20
+ if defined?(SABISU_ENV)
21
+ environment = SABISU_ENV
22
+ else
23
+ environment = CONFIG_FILE[:SABISU_ENV] || ENV['SABISU_ENV'] || 'production'
24
+ end
25
+ set :environment, environment.to_sym
26
+ puts environment
27
+ end
28
+
29
+ configure :development do
30
+ puts 'DEVELOPMENT ENVIRONMENT!!!'
31
+ auth = CONFIG_FILE[:NOAUTH] || ENV['NOAUTH'] || true
32
+ NOAUTH = auth.is_a?(String) ? auth.to_bool : auth
33
+
34
+ # get SSL_ONLY, default to false
35
+ use_ssl = CONFIG_FILE[:SSL_ONLY] || ENV['SSL_ONLY'] || false
36
+ SSL_ONLY = use_ssl.is_a?(String) ? use_ssl.to_bool : use_ssl
37
+ end
38
+
39
+ configure :production do
40
+ puts 'PRODUCTION ENVIRONMENT!!!'
41
+ auth = CONFIG_FILE[:NOAUTH] || ENV['NOAUTH'] || false
42
+ NOAUTH = auth.is_a?(String) ? auth.to_bool : auth
43
+
44
+ # get SSL_ONLY, default to true
45
+ use_ssl = CONFIG_FILE[:SSL_ONLY] || ENV['SSL_ONLY'] || true
46
+ SSL_ONLY = use_ssl.is_a?(String) ? use_ssl.to_bool : use_ssl
47
+
48
+ # don't show exceptions
49
+ set :raise_errors, proc { false }
50
+ set :show_exceptions, false
51
+ end
52
+
53
+ configure do
54
+ use Rack::Session::Pool, expire_after: 2_592_000
55
+ set :views, File.join(settings.root, 'templates')
56
+ set :haml, format: :html5
57
+
58
+ # enable heroku realtime logging;
59
+ # see https://devcenter.heroku.com/articles/ruby#logging
60
+ $stdout.sync = true
61
+
62
+ PORT = CONFIG_FILE[:PORT] || ENV['PORT'] || 8080
63
+ set :port, PORT
64
+
65
+ user = CONFIG_FILE[:CLOUDANT_USER] || ENV['CLOUDANT_USER'] || nil
66
+ password = CONFIG_FILE[:CLOUDANT_PASSWORD] || ENV['CLOUDANT_PASSWORD'] || nil
67
+ url = CONFIG_FILE[:CLOUDANT_URL] || ENV['CLOUDANT_URL'] || nil
68
+ current_db = CONFIG_FILE[:CLOUDANT_CURRENTDB] || ENV['CLOUDANT_CURRENTDB'] || nil
69
+ history_db = CONFIG_FILE[:CLOUDANT_HISTORYDB] || ENV['CLOUDANT_HISTORYDB'] || nil
70
+
71
+ CURRENT_DB = CouchRest.database(
72
+ "https://#{user}:#{password}@#{url}/#{current_db}"
73
+ )
74
+ HISTORY_DB = CouchRest.database(
75
+ "https://#{user}:#{password}@#{url}/#{history_db}"
76
+ )
77
+
78
+ # fields
79
+ default_fields = [
80
+ { name: 'client', path: 'client.name', facet: true, type: 'str', index: true },
81
+ { name: 'check', path: 'check.name', facet: true, type: 'str', index: true },
82
+ { name: 'status', path: 'check.status', facet: false, type: 'int', index: true },
83
+ { name: 'state_change', path: 'check.state_change', facet: false, type: 'int',
84
+ index: true },
85
+ { name: 'occurrence', path: 'occurrences', facet: false, type: 'int', index: true },
86
+ { name: 'issued', path: 'check.issued', facet: false, type: 'int', index: true },
87
+ { name: 'output', path: 'check.output', facet: false, type: 'str', index: true }
88
+ ]
89
+
90
+ custom_fields = CONFIG_FILE[:CUSTOM_FIELDS] || ENV['CUSTOM_FIELDS'] || []
91
+ if custom_fields.is_a?(String)
92
+ custom_fields = JSON.parse(custom_fields, symbolize_names: true)
93
+ end
94
+ FIELDS = default_fields + custom_fields
95
+
96
+ API_URL = CONFIG_FILE[:API_URL] || ENV['API_URL'] || 'localhost'
97
+ use_api_ssl = CONFIG_FILE[:API_SSL] || ENV['API_SSL'] || false
98
+ API_SSL = use_api_ssl.is_a?(String) ? use_api_ssl.to_bool : use_api_ssl
99
+ API_PORT = CONFIG_FILE[:API_PORT] || ENV['API_PORT'] || 4567
100
+ API_USER = CONFIG_FILE[:API_USER] || ENV['API_USER'] || nil
101
+ API_PASSWORD = CONFIG_FILE[:API_PASSWORD] || ENV['API_PASSWORD'] || nil
102
+
103
+ UI_USERNAME = CONFIG_FILE[:UILOGIN_USER] || ENV['UILOGIN_USER'] || 'guest'
104
+ UI_PASSWORD = CONFIG_FILE[:UILOGIN_PASSWORD] || ENV['UILOGIN_PASSWORD'] || 'guest'
105
+
106
+ if SSL_ONLY == true
107
+ # force ssl connections only
108
+ require 'rack-ssl-enforcer'
109
+ use Rack::SslEnforcer
110
+ end
111
+
112
+ # create/update the design doc for sabisu to index the db
113
+ Event.update_design_doc
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,184 @@
1
+ # class of events in sensu
2
+ module Sabisu
3
+ class Server
4
+ # class for sensu events
5
+ class Event
6
+ # return all docs
7
+ def self.all(options = {})
8
+ options = { skip: 0, limit: nil, sort: [] }.merge(options)
9
+ options.delete_if { |k, v| v.nil? || v == [] }
10
+
11
+ CURRENT_DB.all_docs(options.merge(include_docs: true, start_key: '"a"'))
12
+ end
13
+
14
+ # Example: Event.search("client:cheftest* AND status:1", :bookmark => 'ABCD36',
15
+ # :limit => 10,
16
+ # :sort => [ 'status<string>', '-client<string>', '-issued<number>' ])
17
+ def self.search(query, options = {})
18
+ # define facet range params for status attribute
19
+ ranges = { status: {} }
20
+ ranges[:status][:OK] = '[0 TO 0]'
21
+ ranges[:status][:Warning] = '[1 TO 1]'
22
+ ranges[:status][:Critical] = '[2 TO 2]'
23
+ ranges[:status][:Unknown] = '[3 TO 3]'
24
+ # define facet count param
25
+ counts = FIELDS.map do |field|
26
+ field[:name] if field.key?(:facet) && field[:facet] == true
27
+ end.compact
28
+ options = {
29
+ bookmark: nil,
30
+ limit: nil,
31
+ sort: [],
32
+ include_docs: true,
33
+ ranges: ranges.to_json,
34
+ counts: counts
35
+ }.merge(options)
36
+ options.delete_if { |k, v| v.nil? || v == [] }
37
+ # because couchrest doesn't handle arrays correctly
38
+ options[:counts] = options[:counts].to_s unless options[:counts].nil?
39
+ options[:sort] = options[:sort].to_s unless options[:sort].nil?
40
+
41
+ CURRENT_DB.view('_design/sabisu/_search/all_fields', options.merge(q: query))
42
+ end
43
+
44
+ def self.update_design_doc
45
+ # create search indexes
46
+ fields = FIELDS.map do |field|
47
+ next if field.key?(:index) && field[:index] == false
48
+ field[:facet] == true ? facet = ", { 'facet': true }" : ''
49
+ "
50
+ if (typeof(doc.event.#{field[:path]}) !== 'undefined' && doc.event.#{field[:path]} !== null){
51
+ index('#{field[:name]}', doc.event.#{field[:path]}#{facet});
52
+ }"
53
+ end
54
+ search_function = "
55
+ function(doc) {
56
+ index('default', doc._id);
57
+ #{fields.join(' ')}
58
+ }"
59
+ search_indexes = { all_fields: { analyzer: 'whitespace', index: search_function } }
60
+
61
+ # save the design doc only if it has changed or doesn't exist
62
+ begin
63
+ doc = CURRENT_DB.get('_design/sabisu')
64
+ if doc[:indexes] != search_indexes
65
+ doc[:languages] = 'javascript'
66
+ doc[:indexes] = search_indexes
67
+ CURRENT_DB.save_doc(doc)
68
+ end
69
+ rescue ::RestClient::Conflict
70
+ # ignore this
71
+ puts 'doc conflict'
72
+ rescue ::RestClient::ResourceNotFound
73
+ CURRENT_DB.save_doc(
74
+ '_id' => '_design/sabisu',
75
+ :language => 'javascript',
76
+ :indexes => search_indexes
77
+ )
78
+ end
79
+ end
80
+
81
+ def self.stale(params)
82
+ # get cloudant events and put them into a hash
83
+ cloudant_events = {}
84
+ cloudant_events_tmp = all['rows']
85
+ cloudant_events_tmp.each do |event|
86
+ event = event['doc']['event']
87
+ client = event['client']['name']
88
+ check = event['check']['name']
89
+ cloudant_events[client] = {} unless cloudant_events.key?(client)
90
+ cloudant_events[client][check] = {
91
+ status: event['check']['status'],
92
+ output: event['check']['output']
93
+ }
94
+ end
95
+ ##############################################
96
+
97
+ # get sensu event and put them into a hash
98
+ sensu = Sensu.new
99
+ rawdata = sensu.request(method: 'GET', ssl: true, path: '/events')
100
+ sensu_events_tmp = JSON.parse(rawdata.body)
101
+ sensu_events = {}
102
+ sensu_events_tmp.each do |event|
103
+ client = event['client']
104
+ check = event['check']
105
+ sensu_events[client] = {} unless sensu_events.key?(client)
106
+ sensu_events[client][check] = {
107
+ status: event['status'],
108
+ output: event['output']
109
+ }
110
+ end
111
+ ##############################################
112
+
113
+ stale = cloudant_events.deep_diff(sensu_events)
114
+
115
+ # get list of cloudant docs to be deleted (marked as recovered by sensu)
116
+ # this is done by iterating over the deep_diff and finding places where
117
+ # there is no sensu alert for a client/check (ie nil)
118
+ if params.key?('clear_recovered') && params['clear_recovered'].to_s == 'true'
119
+ clear_list = cloudant_events_tmp.each.map do |event|
120
+ client = event['doc']['event']['client']['name']
121
+ check = event['doc']['event']['check']['name']
122
+ unless sensu_events.key?(client) && sensu_events[client].key?(check)
123
+ { client: client, check: check }
124
+ end
125
+ end.compact
126
+
127
+ clear_events(clear_list)
128
+ end
129
+
130
+ stale
131
+ end
132
+
133
+ def self.clear_events(events)
134
+ events.each do |event|
135
+ puts "Deleting #{event[:client]}/#{event[:check]}"
136
+ begin
137
+ doc = CURRENT_DB.get("#{event[:client]}/#{event[:check]}")
138
+ doc.destroy
139
+ rescue RestClient::Conflict
140
+ # there been a conflict, ignore
141
+ puts 'doc conflict'
142
+ rescue RestClient::ResourceNotFound
143
+ # looks like its already deleted, noop
144
+ puts 'doc not found'
145
+ end
146
+ end
147
+ end
148
+
149
+ def to_hash
150
+ hash = {}
151
+ instance_variables.each do |var|
152
+ hash[var.to_s.delete('@')] = instance_variable_get(var)
153
+ end
154
+ hash
155
+ end
156
+
157
+ def to_json
158
+ JSON.pretty_generate(to_hash)
159
+ end
160
+
161
+ # takes a hash and maps it to the fields defined in FIELDS
162
+ def initialize(fields)
163
+ fields.each { |k, v| send("#{k}=", v) } if fields
164
+ end
165
+ end
166
+ end
167
+ end
168
+
169
+ # extend hash class
170
+ class Hash
171
+ def deep_diff(b)
172
+ a = self
173
+ (a.keys | b.keys).reduce({}) do |diff, k|
174
+ if a[k] != b[k]
175
+ if a[k].respond_to?(:deep_diff) && b[k].respond_to?(:deep_diff)
176
+ diff[k] = a[k].deep_diff(b[k])
177
+ else
178
+ diff[k] = [a[k], b[k]]
179
+ end
180
+ end
181
+ diff
182
+ end
183
+ end
184
+ end