Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True).\
joinedload('facility', innerjoin=True)).\
join(LatestInstallations, Installations.id == LatestInstallations.c.installation_id).\
order_by(Installations.date.desc()).all()
elif args['mode'] == 'diff':
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True).\
joinedload('facility', innerjoin=True)).\
join(LatestInstallations, Installations.id == LatestInstallations.c.installation_id).\
filter(Installations.type != int(InstallationType.GLOBAL)).\
order_by(Installations.date.desc()).all()
else: # history
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True).\
joinedload('facility', innerjoin=True)).\
order_by(Installations.date.desc()).all()
retval = []
for installation in installations:
retval.append({ 'facility': installation.host.facility.name,
'host': installation.host.name,
'repository': installation.build.repository.name,
'tag': installation.build.tag, 'date': installation.date,
'author': installation.user.name })
return retval, 200 if len(retval) else 204
@marshal_with(cs_installations_fields)
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('repository', required=True, trim=True, nullable=False,
type=non_empty_string, help='{error_msg} (e.g. repository=fake)')
parser.add_argument('tag', required=True, trim=True, nullable=False,
type=non_empty_string, help='{error_msg} (e.g. tag=0.0.4)')
args = parser.parse_args(strict=True)
username = authenticate(AuthenticationType.USER, request)
destinations = {}
for repository in Repositories.query.\
filter(Repositories.name == args['repository']).\
all():
for server in repository.platform.servers:
for host in server.hosts:
try:
destinations[host.server].add(host)
except KeyError:
destinations[host.server] = {host}
return install(username, args['repository'], args['tag'],
destinations, InstallationType.GLOBAL)
facility_installations_fields = { 'host': fields.String(),
'repository': fields.String(), 'tag': fields.String(),
'date': fields.DateTime(), 'author': fields.String() }
class FacilityInstallationsHandler(Resource):
@marshal_with(facility_installations_fields)
def get(self, facilityname):
facility = Facilities.query.\
filter(Facilities.name == facilityname).\
first_or_404()
args = mode_parser.parse_args(strict=True)
LatestInstallations = db.session.query(Installations)\
.with_entities(Repositories.id, Installations.host_id,\
func.max(Installations.id).label('installation_id'))\
.select_from(Installations)\
.join(Builds).join(Repositories)\
.group_by(Repositories.id, Installations.host_id)\
.subquery()
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
if args['mode'] == 'status':
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True)).\
join('host').\
join(LatestInstallations, Installations.id == LatestInstallations.c.installation_id).\
filter(Hosts.facility == facility).\
order_by(Installations.date.desc()).all()
elif args['mode'] == 'diff':
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True)).\
join('host').\
join(LatestInstallations, Installations.id == LatestInstallations.c.installation_id).\
filter(Hosts.facility == facility,
Installations.type == int(InstallationType.HOST)).\
order_by(Installations.date.desc()).all()
else: # history
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True)).\
join('host').\
filter(Hosts.facility == facility).\
order_by(Installations.date.desc()).all()
retval = []
for installation in installations:
retval.append({ 'host': installation.host.name,
'repository': installation.build.repository.name,
'tag': installation.build.tag, 'date': installation.date,
'author': installation.user.name })
return retval, 200 if len(retval) else 204
@marshal_with(facility_installations_fields)
def post(self, facilityname):
facility = Facilities.query.filter(Facilities.name == facilityname) \
.first_or_404()
parser = reqparse.RequestParser()
parser.add_argument('repository', required=True, trim=True, nullable=False,
type=non_empty_string, help='{error_msg} (e.g. repository=fake)')
parser.add_argument('tag', required=True, trim=True, nullable=False,
type=non_empty_string, help='{error_msg} (e.g. tag=0.0.4)')
args = parser.parse_args(strict=True)
username = authenticate(AuthenticationType.USER, request)
destinations = {}
for repository in Repositories.query.\
filter(Repositories.name == args['repository']).\
all():
for server in repository.platform.servers:
for host in server.hosts:
if host.facility_id != facility.id:
continue
try:
destinations[host.server].add(host)
except KeyError:
destinations[host.server] = {host}
return install(username, args['repository'], args['tag'],
destinations, InstallationType.FACILITY)
host_installations_fields = { 'repository': fields.String(),
'tag': fields.String(), 'date': fields.DateTime(),
'author': fields.String() }
class HostInstallationsHandler(Resource):
@marshal_with(host_installations_fields)
def get(self, facilityname, hostname):
host = Hosts.query.join('facility').\
filter(Facilities.name == facilityname,
Hosts.name == hostname).\
first_or_404()
args = mode_parser.parse_args(strict=True)
LatestInstallations = db.session.query(Installations)\
.with_entities(Repositories.id, Installations.host_id,\
func.max(Installations.id).label('installation_id'))\
.select_from(Installations)\
.join(Builds).join(Repositories)\
.group_by(Repositories.id, Installations.host_id)\
.subquery()
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
if args['mode'] == 'status':
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True)).\
join(LatestInstallations, Installations.id == LatestInstallations.c.installation_id).\
filter(Installations.host == host).\
order_by(Installations.date.desc()).all()
elif args['mode'] == 'diff':
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True)).\
join(LatestInstallations, Installations.id == LatestInstallations.c.installation_id).\
filter(Installations.host == host,
Installations.type == int(InstallationType.HOST)).\
order_by(Installations.date.desc()).all()
else: # history
installations = Installations.query.options(
joinedload('user', innerjoin=True),\
joinedload('build', innerjoin=True).\
joinedload('repository', innerjoin=True),
joinedload('host', innerjoin=True)).\
filter(Installations.host == host).\
order_by(Installations.date.desc()).all()
retval = []
for installation in installations:
retval.append({ 'repository': installation.build.repository.name,
'tag': installation.build.tag, 'date': installation.date,
'author': installation.user.name })
return retval, 200 if len(retval) else 204
@marshal_with(host_installations_fields)
def post(self, facilityname, hostname):
host = Hosts.query.options(joinedload('facility', innerjoin=True)) \
.filter(Facilities.name == facilityname, Hosts.name == hostname) \
.first_or_404()
parser = reqparse.RequestParser()
parser.add_argument('repository', required=True, trim=True, nullable=False,
type=non_empty_string, help='{error_msg} (e.g. repository=fake)')
parser.add_argument('tag', required=True, trim=True, nullable=False,
type=non_empty_string, help='{error_msg} (e.g. tag=0.0.4)')
args = parser.parse_args(strict=True)
username = authenticate(AuthenticationType.USER, request)
destinations = {}
destinations[host.server] = {host}
return install(username, args['repository'], args['tag'],
destinations, InstallationType.HOST)
return {}
def retrieveAnnotatedTags(gitrepo):
atags = set()
for atag in gitrepo.tags:
if atag.tag != None:
atags.add(atag)
return atags
def updateRepo(repo):
gitrepo = None
atagsBefore = set()
repoPath = app.config['GIT_TREES_DIR'] + repo.name
if os.path.isdir(repoPath):
gitrepo = git.Repo(repoPath)
gitrepo.git.clean("-fdx")
gitrepo.git.reset('--hard')
gitrepo.git.checkout("master")
atagsBefore = retrieveAnnotatedTags(gitrepo)
gitrepo.remotes.origin.fetch()
gitrepo.submodule_update(recursive=True, init=False, force_reset=True)
else:
gitrepo = git.Repo.clone_from(repo.provider.url + repo.name, to_path=repoPath)
gitrepo.submodule_update(recursive=True, init=True, force_reset=False)
atagsAfter = set()
atagsAfter = retrieveAnnotatedTags(gitrepo)
return gitrepo, atagsAfter - atagsBefore
def build():
try:
with db.app.app_context():
Alessio Igor Bogani
committed
print("Checking makefiles repository for updates...")
updateRepo(Repositories.query.filter(Repositories.name == "makefiles").first())
for distinctRepo in Repositories.query.with_entities(Repositories.name) \
.filter(Repositories.name != "makefiles").filter(Repositories.provider_id != 11).distinct().all():
Alessio Igor Bogani
committed
print("Checking " + distinctRepo.name + " repository for updates... ")
gitrepo, newAtags = updateRepo(Repositories.query \
.filter(Repositories.name == distinctRepo.name).first())
for atag in newAtags:
for repo in Repositories.query \
.filter(Repositories.name == distinctRepo.name).all():
builder = Builders.query \
.filter(Builders.platform_id == repo.platform.id).first()
if builder is None:
raise Exception("Missing builder")
print("Checkout " + str(atag) + " of the reporitory " + repo.name + "...")
Alessio Igor Bogani
committed
print("SSH-ing to builder " + builder.name + "...")
try:
with paramiko.SSHClient() as sshClient:
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshClient.connect(hostname=builder.name, port=22, username="inau",
key_filename="/home/inau/.ssh/id_rsa.pub")
print("Start building " + str(atag) + " from " + repo.name
+ " git repo on " + builder.name + "...")
stdout, _, exitStatus = execSyncedCommand(sshClient,
"source /etc/profile; cd " + app.config['GIT_TREES_DIR'] + repo.name +
"&& make clean; (test -f *.pro && qmake && cuuimake --plain-text-output); make 2>&1")
print("Building " + str(atag) + " from " + repo.name
+ " git repo on " + builder.name + " finished with code: " + str(exitStatus))
build = Builds(repository_id=repo.id, platform_id=repo.platform_id, tag=str(atag), status=exitStatus, output=stdout)
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
if exitStatus == 0:
outcome = repo.name + " " + str(atag) + ": built successfully on " + builder.name
dir = "/not-existing-directory-which-should-produce-an-error/"
if repo.type == RepositoryType.cplusplus or repo.type == RepositoryType.python \
or repo.type == RepositoryType.shellscript:
dir = "/bin/"
else: # repo.type == RepositoryType.configuration
dir = "/etc/"
print("Looking for file(s) in " + dir + "...")
basedir = app.config['GIT_TREES_DIR'] + repo.name + dir
for r, d, f in os.walk(basedir):
dir = ""
if r != basedir:
dir = os.path.basename(r) + "/"
for file in f:
hashFile = ""
with open(basedir + dir + file,"rb") as fd:
bytes = fd.read()
hashFile = hashlib.sha256(bytes).hexdigest();
if not os.path.isfile(app.config['FILES_STORE_DIR'] + hashFile):
print("Install " + basedir + dir + file + " in the file-store as " + hashFile + "...")
shutil.copyfile(basedir + dir + file, app.config['FILES_STORE_DIR'] + hashFile, follow_symlinks=False)
artifact = Artifacts(build_id=build.id, hash=hashFile, filename=dir+file)
db.session.add(artifact)
db.session.commit()
else:
outcome = repo.name + " " + str(atag) + ": built failed on " + builder.name
print("Send email to", atag.tag.tagger.email)
sendEmail([atag.tag.tagger.email], outcome, stdout)
if str([atag.tag.tagger.email]) != str([atag.tag.object.author.email]):
print("Send email to", atag.tag.object.author.email)
sendEmail([atag.tag.object.author.email], outcome, stdout)
except Exception as e:
print("Error on " + distinctRepo.name + " repository: ", e)
sendEmailAdmins("Error on " + distinctRepo.name + " repository", e)
Alessio Igor Bogani
committed
print("Error on " + distinctRepo.name + " repository: ", e)
sendEmailAdmins("Error on " + distinctRepo.name + " repository", e)
Alessio Igor Bogani
committed
printf("Error on makefiles repository: ", e)
sendEmailAdmins("Error on makefiles repository", e)
if __name__ == '__main__':
# Configure Flask
app.config['SQLALCHEMY_DATABASE_URI'] = args.db
app.config['MAIL_SERVER'] = args.smtpserver
app.config['MAIL_DOMAIN'] = args.smtpdomain
Alessio Igor Bogani
committed
app.config['MAIL_DEFAULT_SENDER'] = args.smtpsender + "@" + args.smtpdomain
app.config['FILES_STORE_DIR'] = args.store
app.config['GIT_TREES_DIR'] = args.repo
app.config['LDAP_URL'] = args.ldap
app.config['BUNDLE_ERRORS'] = True
app.config['JOBS'] = [{'id': 'builder', 'func': build,
Alessio Igor Bogani
committed
'trigger': 'interval', 'seconds': 60}]
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
if args.port != "443":
app.debug = True
app.config['SQLALCHEMY_ECHO'] = True
# Configure SQLAclhemy
db.app = app
db.init_app(app)
# Create and configure APScheduler
# sched = APScheduler()
# sched.init_app(app)
# sched.start()
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
# Create all DB tables if necessary
db.create_all()
# Creates REST endpoints
v2.add_resource(CSHandler, '/cs', '/cs/')
v2.add_resource(UsersHandler, '/cs/users', '/cs/users/')
v2.add_resource(UserHandler, '/cs/users/<string:username>',
'/cs/users/<string:username>/')
v2.add_resource(ArchitecturesHandler, '/cs/architectures', '/cs/architectures/')
v2.add_resource(ArchitectureHandler, '/cs/architectures/<string:archname>',
'/cs/architectures/<string:archname>/')
v2.add_resource(DistributionsHandler, '/cs/distributions', '/cs/distributions/')
v2.add_resource(DistributionHandler, '/cs/distributions/<string:distroid>',
'/cs/distributions/<string:distroid>/')
v2.add_resource(PlatformsHandler, '/cs/platforms', '/cs/platforms/')
v2.add_resource(PlatformHandler, '/cs/platforms/<int:platid>',
'/cs/platforms/<int:platid>/')
v2.add_resource(BuildersHandler,'/cs/builders', '/cs/builders/')
v2.add_resource(BuilderHandler, '/cs/builders/<string:buildername>',
'/cs/builders/<string:buildername>/')
v2.add_resource(ServersHandler, '/cs/servers', '/cs/servers/')
v2.add_resource(ServerHandler, '/cs/servers/<string:servername>',
'/cs/servers/<string:servername>/')
v2.add_resource(ProvidersHandler, '/cs/providers', '/cs/providers/')
v2.add_resource(ProviderHandler, '/cs/servers/<int:providerid>',
'/cs/providers/<int:providerid>/')
v2.add_resource(RepositoriesHandler, '/cs/repositories', '/cs/repositories/')
v2.add_resource(RepositoryHandler, '/cs/repositories/<int:repositoryid>',
'/cs/repositories/<int:repositoryid>/')
v2.add_resource(FacilitiesHandler, '/cs/facilities', '/cs/facilities/')
v2.add_resource(FacilityHandler, '/cs/facilities/<string:facilityname>',
'/cs/facilities/<string:facilityname>/')
v2.add_resource(HostsHandler, '/cs/facilities/<string:facilityname>/hosts',
'/cs/facilities/<string:facilityname>/hosts/')
v2.add_resource(HostHandler,
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>',
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/')
v2.add_resource(FilesHandler,
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/files',
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/files/')
v2.add_resource(FileHandler,
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/files/<string:filename>',
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/files/<string:filename>/')
v2.add_resource(CSInstallationsHandler, '/cs/installations',
'/cs/installations/', '/cs/facilities/installations',
'/cs/facilities/installations/')
v2.add_resource(FacilityInstallationsHandler,
'/cs/facilities/<string:facilityname>/installations',
'/cs/facilities/<string:facilityname>/installations/',
'/cs/facilities/<string:facilityname>/hosts/installations',
'/cs/facilities/<string:facilityname>/hosts/installations/')
v2.add_resource(HostInstallationsHandler,
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/installations',
'/cs/facilities/<string:facilityname>/hosts/<string:hostname>/installations/')
# Start Flask (reloader is not compatible with APScheduler)
if args.port != "443":
app.run(host='0.0.0.0', port=args.port, threaded=True,
use_reloader=False, use_debugger=False)
else:
app.run(host='0.0.0.0', port=args.port, threaded=True,
ssl_context=('/etc/ssl/certs/inau_elettra_eu.crt',
'/etc/ssl/private/inau_elettra_eu.key'),
use_reloader=False, use_debugger=False)