~jcsackett/charmworld/bac-tag-constraints

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# Copyright 2013 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

from bzrlib.branch import Branch
from bzrlib.transport import get_transport
from collections import namedtuple
import os
from os.path import dirname
import time

from charmworld.utils import (
    LAST_INGEST_JOB_FINISHED,
    SERVER_STARTED,
)


Check = namedtuple('check', 'name status remark')
PASS = 'Pass'
FAIL = 'Fail'


def _check_collection_size(request, collection_name):
    """Return a Check that a mongodb collection is not empty."""
    status = FAIL
    try:
        count = request.db[collection_name].count()
        if count > 0:
            remark = '{0} {1} found'.format(count, collection_name)
            status = PASS
        else:
            remark = 'There are no {0}. Is ingest running?'
            remark = remark.format(collection_name)
    except:
        remark = 'The mongodb {0} collection is not available.'
        remark = remark.format(collection_name)
    finally:
        check = Check('{0} collection'.format(collection_name), status, remark)
    return check


def check_charms_collection(request):
    """Return a Check of the mongodb charms collection."""
    return _check_collection_size(request, 'charms')


def check_bundles_collection(request):
    """Return a Check of the mongodb bundles collection."""
    return _check_collection_size(request, 'bundles')


def check_charm_index(request):
    """Return a Check of the elasticsearch charms index."""
    status = FAIL
    try:
        results = request.index_client.search(terms='')
        if results['result_total'] > 0:
            remark = '{0} matches found'.format(results['result_total'])
            status = PASS
        else:
            remark = 'There are no matches. Is ingest running?'
    except:
        remark = 'The elasticsearch charm index is not available.'
    finally:
        check = Check('charms index', status, remark)
    return check


def check_api2(request):
    """Return a Check of the API charms interesting end point."""
    status = FAIL
    try:
        from charmworld.views.api import API2
        api = API2(request)
        interesting = api.charms(path=['interesting'])['result']
        if (interesting['new']
                and interesting['popular']
                and interesting['featured']):
            status = PASS
            remark = 'Interesting has new, popular, and featured.'
        else:
            remark = (
                'Interesting is missing new (found {0}), popular '
                '(found {1}), or featured (found {2}).')
            remark = remark.format(
                len(interesting['new']), len(interesting['popular']),
                len(interesting['featured']))
    except:
        remark = 'The API2 is not available.'
    finally:
        check = Check('API2 interesting', status, remark)
    return check


def check_api3(request):
    """Return a Check of the API charms interesting end point."""
    status = FAIL
    try:
        from charmworld.views.api import API3
        api = API3(request)
        interesting = api.search(path=['interesting'])['result']
        if (interesting['new']
                and interesting['popular']
                and interesting['featured']):
            status = PASS
            remark = 'Interesting has new, popular, and featured.'
        else:
            remark = (
                'Interesting is missing new (found {0}), popular '
                '(found {1}), or featured (found {2}).')
            remark = remark.format(
                len(interesting['new']), len(interesting['popular']),
                len(interesting['featured']))
    except:
        remark = 'The API3 is not available.'
    finally:
        check = Check('API3 interesting', status, remark)
    return check


def check_collections(request):
    """Return a Check of the collections that should exist in the Mongo DB."""
    status = FAIL
    required = set((
        'basket-queue', 'baskets', 'bundles', 'charm-queue', 'charms'))
    try:
        existing = set(request.db.collection_names())
        missing = required.difference(existing)
        if missing:
            missing = ', '.join(sorted(missing))
            remark = 'Required collections do not (yet) exist: {0}'
            remark = remark.format(missing)
        else:
            status = PASS
            remark = 'All required collections exist.'
    except:
        remark = "Cannot query the MongoDB's collection names."
    finally:
        check = Check('MongoDB collections', status, remark)
    return check


def check_ingest_queues(request):
    """Check the size of the ingest queues."""
    status = FAIL
    try:
        charm_queue_size = request.db['charm-queue'].count()
        basket_queue_size = request.db['basket-queue'].count()
        status = PASS
        remark = 'queued charms: {0}, queued baskets: {1}.'
        remark = remark.format(charm_queue_size, basket_queue_size)
    except:
        remark = 'Cannot query the ingest queues.'
    finally:
        check = Check('Ingest queue sizes', status, remark)
    return check


def check_bzr_revision(request):
    """Return the current bzr revision."""
    status = FAIL
    try:
        branch_dir = dirname(dirname(__file__))
        transport = get_transport(branch_dir)
        branch = Branch.open_from_transport(transport)
        remark = str(branch.revno())
        status = PASS
    except:
        remark = "Can't retrieve revision number."
    finally:
        check = Check('BZR revision', status, remark)
    return check


def check_elasticsearch_status(request):
    """Check the health status of the ElasticSearch server."""
    status = FAIL
    try:
        health = request.index_client.health()
        remark = (
            'status: {status}, '
            'nodes: {number_of_nodes}, '
            'active primary shards: {active_primary_shards}, '
            'active shards: {active_shards}, '
            'initializing shards: {initializing_shards}, '
            'relocating shards: {relocating_shards}'
        )
        remark = remark.format(**health)
        if health['status'] in ('green', 'yellow'):
            status = PASS
    except Exception:
        remark = "Can't retrieve the ES server's health status."
    finally:
        check = Check('ElasticSearch server', status, remark)
    return check


def check_crontab(request):
    """Check that a crontab file for charmworld exists."""
    if 'charmworld' in os.listdir('/etc/cron.d'):
        status = PASS
        remark = 'Crontab file for charmworld exists.'
    else:
        status = FAIL
        remark = 'Crontab file for charmworld not found.'
    return Check('Crontab', status, remark)


def formatted_timestamp(timestamp):
    return time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(timestamp))


def check_server_start_time(request):
    """Return the time when the server was last started."""
    try:
        start_times = request.db.server_status.find_one(SERVER_STARTED)
        del start_times['_id']
        start_times = [
            '%s: %s' % (hostname, formatted_timestamp(timestamp))
            for hostname, timestamp in sorted(start_times.items())]
        remark = ', '.join(start_times)
        status = PASS
    except Exception:
        remark = "Can't retrieve the server's start time."
        status = FAIL
    return Check('Server started', status, remark)


def check_last_ingest_job(request):
    """Return the time when the ingest job finished."""
    try:
        timestamp = request.db.server_status.find_one(
            LAST_INGEST_JOB_FINISHED)['time']
        remark = 'finished at %s' % formatted_timestamp(timestamp)
        status = PASS
    except Exception:
        remark = "Can't retrieve the time when the last ingest job finished."
        status = FAIL
    return Check('Last ingest job', status, remark)