-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
158 lines (143 loc) · 5.7 KB
/
app.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
import os, sys, redis
from minio import Minio
import boto3
import botocore.exceptions
from minio.error import S3Error
from flask import Flask, redirect, send_file, Response
from flask_cors import CORS
import mysql.connector
import logging
import requests
from werkzeug.wsgi import FileWrapper
import json
app = Flask(__name__)
CORS(app)
cache = redis.Redis(host='redis', port=6379)
minioAccessKey = os.environ.get('MINIO_ACCESS_KEY')
minioSecretKey = os.environ.get('MINIO_SECRET_KEY')
s3Bucket = os.environ.get('BUCKET_NAME')
minioUrl = os.environ.get('MINIO_URL')
apiSecret = os.environ.get("API_SECRET")
ga4Id = os.environ.get("GA4_ID")
url = "https://www.google-analytics.com/mp/collect?measurement_id=" + ga4Id + "&api_secret=" + apiSecret
minioClient = Minio(minioUrl, access_key=minioAccessKey, secret_key=minioSecretKey, secure=False)
s3_client = boto3.client(
's3',
'us-east-1',
aws_access_key_id=minioAccessKey,
aws_secret_access_key=minioSecretKey
)
logger = logging.getLogger("atlas-file-service")
logging.basicConfig(level=logging.ERROR)
class MYSQLConnection:
def __init__(self):
logger.info(
"Start: MYSQLConnection().__init__(), trying to load environment variables in docker"
)
self.host = None
self.port = 3306
self.user = None
self.password = None
self.database_name = "knowledge_environment"
try:
self.host = os.environ.get("MYSQL_HOST")
self.user = os.environ.get("MYSQL_USER")
self.password = os.environ.get("MYSQL_PASSWORD")
except Exception as connectError:
logger.warning(
"Can't load environment variables from docker... trying local .env file instead...", connectError
)
def get_db_cursor(self, connect_try=0):
try:
if (self.database.is_connected() == False):
self.get_db_connection();
self.cursor = self.database.cursor(buffered=False, dictionary=True)
return self.cursor
except Exception as error:
if connect_try < 5:
logger.info("Can't get cursor. Trying to reconnect to the database.")
connect_try = connect_try + 1
self.get_db_connection()
return self.get_db_cursor(connect_try)
else:
logger.error("Tried too many times to get mysql cursor. Exiting.", error)
os.sys.exit()
def get_db_connection(self):
try:
self.database = mysql.connector.connect(
host=self.host,
user=self.user,
port=self.port,
password=self.password,
database=self.database_name,
pool_name="atlas-file-service"
)
self.database.get_warnings = True
return self.database
except Exception as error:
logger.error("Can't connect to MySQL", error)
os.sys.exit()
def get_data(self, sql, query_data=None):
try:
self.get_db_cursor()
data = []
self.cursor.execute(sql, query_data)
for row in self.cursor:
data.append(row)
return data
except Exception as error:
logger.error("Can't get knowledge_environment data.", error)
finally:
self.cursor.close()
db = MYSQLConnection()
db.get_db_connection()
def get_file_info_by_file_name(file_name):
return db.get_data(
"SELECT * FROM repo_file_v WHERE file_name = %s",
(file_name,),
)
@app.route('/v1/file/download/<packageId>/<objectName>', methods=['POST', 'GET'])
def downloadFile(packageId, objectName):
result = get_file_info_by_file_name(objectName)
if result[0]["access"] == "open":
try:
objectNameFull = packageId + '/' + objectName
object = minioClient.get_object(s3Bucket, objectNameFull, request_headers=None)
payload = {
"client_id": "XXXXXXXXXX.YYYYYYYYYY",
"events": [
{
"name": "AtlasRepositoryDownload",
"params": {
"event_category": "Repository",
"event_action": "Download",
"label": objectName
}
}]
}
requests.post(url, json=payload, headers={"Content-Type": "application/json"})
file_wrapper = FileWrapper(object)
headers = {
'Content-Disposition': 'attachment; filename="{}"'.format(objectName)
}
response = Response(file_wrapper,
mimetype='application/octet-stream',
direct_passthrough=True,
headers=headers)
return response
except S3Error as err:
logger.error(err)
return err
else:
return "File not found", 404
@app.route('/v1/derived/download/<packageId>/<objectName>', methods=['GET'])
def downloadDerivedFileS3PS(packageId, objectName):
try:
objectNameFull = packageId + '/derived/' + objectName
return s3_client.generate_presigned_url('get_object',
Params={'Bucket': s3Bucket, 'Key': objectNameFull},
ExpiresIn=3600)
except botocore.exceptions.ClientError as error:
logger.error(error)
except botocore.exceptions.ParamValidationError as error:
logger.error(error)