This repository was archived by the owner on Apr 16, 2021. It is now read-only.
forked from CCExtractor/sample-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·199 lines (153 loc) · 5.91 KB
/
Copy pathrun.py
File metadata and controls
executable file
·199 lines (153 loc) · 5.91 KB
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
from __future__ import print_function
import os
import sys
import traceback
from flask import Flask, g
from werkzeug.contrib.fixers import ProxyFix
from werkzeug.routing import BaseConverter
from config_parser import parse_config
from database import create_session
from decorators import template_renderer
from log_configuration import LogConfiguration
from mailer import Mailer
from mod_auth.controllers import mod_auth
from mod_ci.controllers import mod_ci
from mod_deploy.controllers import mod_deploy
from mod_home.controllers import mod_home
from mod_regression.controllers import mod_regression
from mod_sample.controllers import mod_sample
from mod_test.controllers import mod_test
from mod_upload.controllers import mod_upload
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
# Load config
config = parse_config('config')
app.config.from_mapping(config)
try:
app.config['DEBUG'] = os.environ['DEBUG']
except KeyError:
app.config['DEBUG'] = False
# Init logger
log_configuration = LogConfiguration(app.root_path, 'platform', app.config['DEBUG'])
log = log_configuration.create_logger("Platform")
def install_secret_keys(application, secret_session='secret_key', secret_csrf='secret_csrf'):
"""
Configure the SECRET_KEY from a file in the instance directory.
If the file does not exist, print instructions to create it from a shell with a random key, then exit.
"""
do_exit = False
session_file = os.path.join(application.root_path, secret_session)
csrf_file = os.path.join(application.root_path, secret_csrf)
try:
application.config['SECRET_KEY'] = open(session_file, 'rb').read()
except IOError:
traceback.print_exc()
print('Error: No secret key. Create it with:')
if not os.path.isdir(os.path.dirname(session_file)):
print('mkdir -p', os.path.dirname(session_file))
print('head -c 24 /dev/urandom >', session_file)
do_exit = True
try:
application.config['CSRF_SESSION_KEY'] = open(csrf_file, 'rb').read()
except IOError:
print('Error: No secret CSRF key. Create it with:')
if not os.path.isdir(os.path.dirname(csrf_file)):
print('mkdir -p', os.path.dirname(csrf_file))
print('head -c 24 /dev/urandom >', csrf_file)
do_exit = True
if do_exit:
sys.exit(1)
install_secret_keys(app)
# Expose submenu method for jinja templates
def sub_menu_open(menu_entries, active_route):
for menu_entry in menu_entries:
if 'route' in menu_entry and menu_entry['route'] == active_route:
return True
return False
app.jinja_env.globals.update(sub_menu_open=sub_menu_open)
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
# Add datetime format filter
def date_time_format(value, fmt='%Y-%m-%d %H:%M:%S'):
return value.strftime(fmt)
app.jinja_env.filters['date'] = date_time_format
def get_github_issue_link(issue_id):
return 'https://www.github.com/{org}/{repo}/issues/{id}'.format(
org=config.get('GITHUB_OWNER', ''),
repo=config.get('GITHUB_REPOSITORY', ''),
id=issue_id
)
app.jinja_env.filters['issue_link'] = get_github_issue_link
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
# Allow regexes in routes
app.url_map.converters['regex'] = RegexConverter
@app.errorhandler(404)
@template_renderer('404.html', 404)
def not_found(error):
return
@app.errorhandler(500)
@template_renderer('500.html', 500)
def internal_error(error):
log.debug('500 error: {err}'.format(err=error))
log.debug('Stacktrace:')
log.debug(traceback.format_exc())
return
@app.errorhandler(403)
@template_renderer('403.html', 403)
def forbidden(error):
user_name = 'Guest' if g.user is None else g.user.name
user_role = 'Guest' if g.user is None else g.user.role.value
log.debug('{u} (role: {r}) tried to access {page}'.format(u=user_name, r=user_role, page=error.description))
return {
'user_role': user_role,
'endpoint': error.description
}
@app.before_request
def before_request():
g.menu_entries = {}
g.db = create_session(app.config['DATABASE_URI'])
g.mailer = Mailer(
app.config.get('EMAIL_DOMAIN', ''), app.config.get('EMAIL_API_KEY', ''), 'CCExtractor.org CI Platform'
)
g.version = "0.1"
g.log = log
g.github = {
'deploy_key': app.config.get('GITHUB_DEPLOY_KEY', ''),
'ci_key': app.config.get('GITHUB_CI_KEY', ''),
'bot_token': app.config.get('GITHUB_TOKEN', ''),
'repository_owner': app.config.get('GITHUB_OWNER', ''),
'repository': app.config.get('GITHUB_REPOSITORY', '')
}
@app.teardown_appcontext
def teardown(exception):
db = g.get('db', None)
if db is not None:
db.remove()
# Register blueprints
app.register_blueprint(mod_auth, url_prefix='/account') # Needs to be first
app.register_blueprint(mod_upload, url_prefix='/upload')
app.register_blueprint(mod_regression, url_prefix='/regression')
app.register_blueprint(mod_sample, url_prefix='/sample')
app.register_blueprint(mod_home)
app.register_blueprint(mod_deploy)
app.register_blueprint(mod_test, url_prefix="/test")
app.register_blueprint(mod_ci)
if __name__ == '__main__':
# Run in development mode; Werkzeug server
# Load variables for running (if defined)
ssl_context = host = None
proto = 'https'
key = app.config.get('SSL_KEY', 'cert/key.key')
cert = app.config.get('SSL_CERT', 'cert/cert.cert')
if len(key) == 0 or len(cert) == 0:
ssl_context = 'adhoc'
else:
ssl_context = (cert, key)
server_name = app.config.get('0.0.0.0')
port = app.config.get('SERVER_PORT', 443)
print('Server should be running soon on {0}://{1}:{2}'.format(proto, server_name, port))
if server_name != '127.0.0.1':
host = '0.0.0.0'
app.run(host, port, app.config['DEBUG'], ssl_context=ssl_context)