forked from tessera-metrics/tessera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.py
277 lines (242 loc) · 8.02 KB
/
tasks.py
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import glob
import logging
import os
import sys
from urlparse import urljoin
import requests
from requests.exceptions import ConnectionError
from invoke import ctask as task, Collection
from invocations.testing import test
from tessera import app, db, config
from tessera_client.api.model import Section
from tessera.importer.graphite import GraphiteDashboardImporter
from tessera.importer.json import JsonImporter, JsonExporter
from werkzeug.serving import run_simple
import flask
from flask.ext import migrate
warn = logging.WARN
log = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)-8s [%(name)s] %(message)s'
)
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(warn)
logging.getLogger('sqlalchemy.engine').setLevel(warn)
DEFAULT_TESSERA_URL = 'http://{0}:{1}'.format(config['SERVER_ADDRESS'], config['SERVER_PORT'])
DEFAULT_GRAPHITE_URL = config['GRAPHITE_URL']
DEFAULT_MIGRATION_DIR = config['MIGRATION_DIR']
@task
def run(c):
"""Launch the server."""
run_simple(config['SERVER_ADDRESS'], config['SERVER_PORT'], app, use_reloader=True)
# =============================================================================
# db collection
# inv db.init
# inv db.init_migrations
# inv db.current
# inv db.revisions
# inv db.migrate
# inv db.upgrade
# inv db.downgrade
# inv db.stamp
# inv db.history
# =============================================================================
@task
def initdb(c):
"""
Deprecated, use db.init instead.
"""
db.create_all()
@task(name='init')
def db_init(c):
"""
Set up a new, empty database.
"""
db.create_all()
@task(name='init_migrations')
def db_init_migrations(c, dir=None):
"""
Update the project to support migrations.
"""
with app.app_context():
migrate.init(dir)
@task(name='current')
def db_current(c, dir=DEFAULT_MIGRATION_DIR):
"""
Show current migration revision.
"""
with app.app_context():
migrate.current(directory=dir)
@task(name='revision')
def db_revision(c, dir=DEFAULT_MIGRATION_DIR):
"""
Generate new empty revision script.
"""
with app.app_context():
migrate.revision(directory=dir)
@task(name='migrate')
def db_migrate(c, dir=DEFAULT_MIGRATION_DIR):
"""
Generate new autofilled migration.
"""
with app.app_context():
migrate.migrate(directory=dir)
@task(name='upgrade')
def db_upgrade(c, dir=DEFAULT_MIGRATION_DIR):
"""
Run any migrations needed make database current.
"""
with app.app_context():
migrate.upgrade(directory=dir)
@task(name='downgrade')
def db_downgrade(c, dir=DEFAULT_MIGRATION_DIR):
"""
Downgrade database to a specific revision.
"""
with app.app_context():
migrate.downgrade(directory=dir)
@task(name='stamp')
def db_stamp(c, dir=DEFAULT_MIGRATION_DIR):
"""
Set database revision to a specific value.
"""
with app.app_context(directory=dir):
pass
@task(name='history')
def db_history(c, dir=DEFAULT_MIGRATION_DIR):
"""
List migration history.
"""
with app.app_context():
migrate.history(directory=dir)
# =============================================================================
# graphite tasks
# inv graphite.import
# inv graphite.export
# =============================================================================
@task(name='import')
def import_graphite_dashboards(
c, query='', layout=Section.Layout.FLUID, columns=4, overwrite=False,
graphite=DEFAULT_GRAPHITE_URL, tessera=DEFAULT_TESSERA_URL
):
"""
Import dashboards from a Graphite vanilla dashboard.
"""
log.info('Importing dashboards from graphite')
importer = GraphiteDashboardImporter(graphite, tessera, config['GRAPHITE_AUTH'])
importer.import_dashboards(
query, overwrite=overwrite, layout=layout, columns=int(columns)
)
@task(name='dump')
def dump_graphite_dashboards(c, query='', graphite=DEFAULT_GRAPHITE_URL, tessera=DEFAULT_TESSERA_URL):
"""
Dump Graphite dashboards to stdout in Tessera JSON format.
"""
log.info('Importing dashboards from graphite')
importer = GraphiteDashboardImporter(graphite, tessera)
importer.dump_dashboards(query)
# =============================================================================
# json tasks
# inv json.import
# inv json.export
# =============================================================================
@task(name='export')
def export_json(c, dir, tag=None, graphite=DEFAULT_GRAPHITE_URL, tessera=DEFAULT_TESSERA_URL):
"""
Export dashboards as JSON to a local directory.
"""
msg = 'Exporting dashboards (tagged: {0}) as JSON to directory {1}'
log.info(msg.format(tag, dir))
exporter = JsonExporter(graphite, tessera)
exporter.export(dir, tag)
@task(name='import')
def import_json(c, pattern, graphite=DEFAULT_GRAPHITE_URL, tessera=DEFAULT_TESSERA_URL):
"""
Import dashboards from a directory previously used for exporting.
"""
log.info('Import dashboards from {0})'.format(pattern))
files = glob.glob(pattern)
log.info('Found {0} files to import'.format(len(files)))
importer = JsonImporter(graphite, tessera)
importer.import_files(files)
# =============================================================================
# test tasks
# inv test.unit
# inv test.integration
# =============================================================================
@task
def integration(c):
"""
Run high level integration test suite.
"""
return test(c, opts="--tests=integration")
tests = Collection('test')
tests.add_task(test, name='unit', default=True)
tests.add_task(integration)
@task
def copy(c, source_id, source_uri=None, destination_uri=None):
"""
Copy a dashboard (via API) between two running Tessera instances.
:param str source_id:
Source dashboard ID, e.g. if copying a dashboard that lives at
``http://mytessera.com/dashboards/123``, this would simply be ``123``.
:param str source_uri:
Source base URI, e.g. ``http://mytessera.com`` or
``https://tessera.example.com:8080``. Will pull default value from the
``TESSERA_SOURCE_URI`` environment variable if not given.
:param str destination_uri:
Destination base URI, similar to ``source_uri``. Will pull default
value from ``TESSERA_DESTINATION_URI`` if not given.
"""
# Arg handling junk
missing = []
if source_uri is None:
try:
source_uri = os.environ['TESSERA_SOURCE_URI']
except KeyError:
missing.append("source")
if destination_uri is None:
try:
destination_uri = os.environ['TESSERA_DESTINATION_URI']
except KeyError:
missing.append("destination")
if missing:
sys.exit("Missing the following URI parameters: {0}".format(
', '.join("{0}_uri".format(x) for x in missing)))
# Actual copy
endpoint = '/api/dashboard/'
source = reduce(urljoin, (source_uri, endpoint, source_id))
try:
original = requests.get(source, params={'definition': 'true'})
except ConnectionError as e:
sys.exit("Unable to connect to {0}: {1}".format(source, e))
dest = urljoin(destination_uri, endpoint)
try:
response = requests.post(dest, data=original.content,
headers={'Content-Type': 'application/json'})
except ConnectionError as e:
sys.exit("Unable to connect to {0}: {1}".format(dest, e))
new_uri = urljoin(dest, response.json()['view_href'])
print("{0} -> {1}".format(source, new_uri))
ns = Collection(
run,
copy,
initdb,
tests,
Collection('db',
db_init,
db_init_migrations,
db_current,
db_revision,
db_migrate,
db_upgrade,
db_downgrade,
db_stamp,
db_history
),
Collection('json', import_json, export_json),
Collection('graphite',
import_graphite_dashboards,
dump_graphite_dashboards,
),
)