Skip to content

Commit 2ae1563

Browse files
authored
Merge pull request #197 from Code4GovTech/dev
Migrations to Prod
2 parents f9b04d0 + 5c666a8 commit 2ae1563

16 files changed

+405
-88
lines changed

.dockerignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
.env
1+
.env
2+
!.git

.gitmodules

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[submodule "shared_migrations"]
2+
path = shared_migrations
3+
url = https://github.com/Code4GovTech/shared-models-migrations.git

Dockerfile

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,16 @@ FROM python:3.9-slim-buster
33
WORKDIR /app
44
COPY ./requirements.txt /app
55
RUN pip install -r requirements.txt
6+
7+
RUN apt-get update && \
8+
apt-get install -y --no-install-recommends git openssh-client && \
9+
rm -rf /var/lib/apt/lists/*
10+
11+
612
COPY . .
13+
RUN git init
14+
RUN --mount=type=ssh git submodule update --init --recursive
15+
716
ARG REPOSITORY_MONITOR_APP_PK_PEM
817

918
RUN echo $REPOSITORY_MONITOR_APP_PK_PEM > /app/utils/repository_monitor_app_pk.pem

app.py

Lines changed: 59 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
from io import BytesIO
44
import aiohttp, asyncio
55
import dotenv, os, json, urllib, sys, dateutil, datetime, sys
6+
7+
from githubdatapipeline.issues.processor import get_url
68
from utils.github_adapter import GithubAdapter
79
from utils.dispatcher import dispatch_event
10+
from utils.link_pr_issue import AddIssueId
811
from utils.webhook_auth import verify_github_webhook
9-
from utils.db import SupabaseInterface,PostgresORM
12+
from shared_migrations.db.server import ServerQueries
1013
from events.ticketEventHandler import TicketEventHandler
1114
from events.ticketFeedbackHandler import TicketFeedbackHandler
1215
from githubdatapipeline.pull_request.scraper import getNewPRs
@@ -22,6 +25,7 @@
2225
from datetime import datetime
2326
from quart_cors import cors
2427
from utils.migrate_tickets import MigrateTickets
28+
from utils.migrate_users import MigrateContributors
2529

2630
scheduler = AsyncIOScheduler()
2731

@@ -43,7 +47,7 @@ async def get_github_data(code, discord_id):
4347
async with aiohttp.ClientSession() as session:
4448
github_response = await GithubAdapter.get_github_data(code)
4549
auth_token = (github_response)["access_token"]
46-
50+
4751
headers = {
4852
"Accept": "application/json",
4953
"Authorization": f"Bearer {auth_token}"
@@ -67,15 +71,16 @@ async def get_github_data(code, discord_id):
6771
"discord_id": int(discord_id),
6872
"github_id": github_id,
6973
"github_url": f"https://github.com/{github_username}",
70-
"email": ','.join(private_emails)
74+
"email": ','.join(private_emails),
75+
"joined_at": datetime.now()
7176
}
7277

7378
return user_data
74-
79+
7580
async def comment_cleaner():
7681
while True:
7782
await asyncio.sleep(5)
78-
comments = await PostgresORM().readAll("app_comments")
83+
comments = await ServerQueries().readAll("app_comments")
7984
for comment in comments:
8085
utc_now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
8186
update_time = dateutil.parser.parse(comment["updated_at"])
@@ -87,7 +92,7 @@ async def comment_cleaner():
8792
issue_id = comment["issue_id"]
8893
comment = await TicketFeedbackHandler().deleteComment(owner, repo, comment_id)
8994
print(f"Print Delete Task,{comment}", file=sys.stderr)
90-
print(await PostgresORM().deleteComment(issue_id,"app_comments"))
95+
print(await ServerQueries().deleteComment(issue_id,"app_comments"))
9196

9297
async def fetch_github_issues_from_repo(owner, repo):
9398
try:
@@ -96,11 +101,11 @@ async def fetch_github_issues_from_repo(owner, repo):
96101
return response
97102
else:
98103
print(f"Failed to get issues: {response}")
99-
104+
100105
except Exception as e:
101106
logger.info(e)
102107
raise Exception
103-
108+
104109
repositories_list = [
105110
"KDwevedi/c4gt-docs",
106111
"KDwevedi/testing_for_github_app"
@@ -159,23 +164,23 @@ async def verify(githubUsername):
159164

160165
@app.route("/misc_actions")
161166
async def addIssues():
162-
tickets = await PostgresORM().readAll("ccbp_tickets")
167+
tickets = await ServerQueries().readAll("ccbp_tickets")
163168
count =1
164169
for ticket in tickets:
165170
print(f'{count}/{len(tickets)}')
166171
count+=1
167172
if ticket["status"] == "closed":
168173
# if ticket["api_endpoint_url"] in ["https://api.github.com/repos/glific/glific/issues/2824"]:
169174
await TicketEventHandler().onTicketClose({"issue":await get_url(ticket["api_endpoint_url"])})
170-
171175

172-
return ''
176+
177+
return ''
173178

174179

175180
@app.route("/update_profile", methods=["POST"])
176181
async def updateGithubStats():
177182
webhook_data = await request.json
178-
data = await PostgresORM().read("github_profile_data", filters={"dpg_points": ("gt", 0)})
183+
data = await ServerQueries().read("github_profile_data", filters={"dpg_points": ("gt", 0)})
179184
GithubProfileDisplay().update(data)
180185
return 'Done'
181186

@@ -186,7 +191,7 @@ async def do_update():
186191
while True:
187192
print("Starting Update")
188193
await asyncio.sleep(21600)
189-
data = await PostgresORM().read("github_profile_data", filters={"dpg_points": ("gt", 0)})
194+
data = await ServerQueries().read("github_profile_data", filters={"dpg_points": ("gt", 0)})
190195
GithubProfileDisplay().update(data)
191196

192197

@@ -216,7 +221,7 @@ async def test():
216221
@app.route("/register/<discord_userdata>")
217222
async def register(discord_userdata):
218223
print("🛠️SUCCESSFULLY REDIECTED FROM GITHUB TO SERVER", locals(), file=sys.stderr)
219-
postgres_client = PostgresORM()
224+
postgres_client = ServerQueries()
220225

221226
discord_id = discord_userdata
222227
print("🛠️SUCCESFULLY DEFINED FUNCTION TO POST TO SUPABASE", locals(), file=sys.stderr)
@@ -233,7 +238,7 @@ async def register(discord_userdata):
233238
print("🛠️PUSHED USER DETAILS TO SUPABASE")
234239
except Exception as e:
235240
print("🛠️ENCOUNTERED EXCEPTION PUSHING TO SUPABASE",e, file=sys.stderr)
236-
241+
237242
print("🛠️FLOW COMPLETED SUCCESSFULLY, REDIRECTING TO DISCORD", file=sys.stderr)
238243
return await render_template('success.html'), {"Refresh": f'1; url=https://discord.com/channels/{os.getenv("DISCORD_SERVER_ID")}'}
239244

@@ -243,14 +248,14 @@ async def event_handler():
243248
try:
244249
data = await request.json
245250
print('data is ', data)
246-
secret_key = os.getenv("WEBHOOK_SECRET")
251+
secret_key = os.getenv("WEBHOOK_SECRET")
247252

248253
verification_result, error_message = await verify_github_webhook(request,secret_key)
249-
250-
postgres_client = PostgresORM.get_instance()
254+
255+
postgres_client = ServerQueries()
251256
event_type = request.headers.get("X-GitHub-Event")
252257
await dispatch_event(event_type, data, postgres_client)
253-
258+
254259
return data
255260
except Exception as e:
256261
logger.info(e)
@@ -268,11 +273,11 @@ async def discord_metrics():
268273
data = {
269274
"product_name" : product_name,
270275
"mentor_messages" : value['mentor_messages'],
271-
"contributor_messages": value['contributor_messages']
276+
"contributor_messages": value['contributor_messages']
272277
}
273278
discord_data.append(data)
274279

275-
data = await PostgresORM().add_discord_metrics(discord_data)
280+
data = await ServerQueries().add_discord_metrics(discord_data)
276281
return data
277282

278283
@app.route("/metrics/github", methods = ['POST'])
@@ -287,16 +292,16 @@ async def github_metrics():
287292
"closed_prs": value['closed_prs'],
288293
"open_issues": value['open_issues'],
289294
"closed_issues": value['closed_issues'],
290-
"number_of_commits": value['number_of_commits'],
295+
"number_of_commits": value['number_of_commits'],
291296
}
292297
github_data.append(data)
293298

294-
data = await PostgresORM().add_github_metrics(github_data)
299+
data = await ServerQueries().add_github_metrics(github_data)
295300
return data
296301

297302
@app.route("/role-master")
298303
async def get_role_master():
299-
role_masters = await PostgresORM().readAll("role_master")
304+
role_masters = await ServerQueries().readAll("role_master")
300305
print('role master ', role_masters)
301306
return role_masters.data
302307

@@ -308,7 +313,7 @@ async def get_program_tickets_user():
308313
filter = ''
309314
if request_data:
310315
filter = json.loads(request_data.decode('utf-8'))
311-
postgres_client = PostgresORM.get_instance()
316+
postgres_client = ServerQueries()
312317
all_issues = await postgres_client.fetch_filtered_issues(filter)
313318
print('length of all issue ', len(all_issues))
314319

@@ -334,10 +339,10 @@ async def get_program_tickets_user():
334339

335340
contributors_data = issue["contributors_registration"]
336341
if contributors_data:
337-
contributors_name = contributors_data["name"]
342+
contributors_name = contributors_data["name"]
338343
if contributors_name:
339344
pass
340-
else:
345+
else:
341346
contributors_url = contributors_data["github_url"].split('/')
342347
contributors_name = contributors_url[-1] if contributors_url else None
343348

@@ -377,5 +382,32 @@ async def migrate_tickets():
377382
print('exception occured ', e)
378383
return 'failed'
379384

385+
386+
@app.route('/migrate-contributors')
387+
async def migrate_contributors():
388+
try:
389+
migrator = MigrateContributors() # Create an instance
390+
391+
asyncio.create_task(migrator.migration())
392+
return 'migration started'
393+
except Exception as e:
394+
print('exception occured ', e)
395+
return 'failed'
396+
397+
398+
@app.route('/add-issue-id-pr')
399+
async def add_issue_id_pr():
400+
try:
401+
migrator = AddIssueId() # Create an instance
402+
403+
asyncio.create_task(migrator.process_prs())
404+
405+
# return await migrator.process_prs()
406+
return 'migration started'
407+
except Exception as e:
408+
print('exception occured ', e)
409+
return 'failed'
410+
411+
380412
if __name__ == '__main__':
381413
app.run()

events/ticketEventHandler.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import aiohttp
55
import os, sys, datetime, json
6-
from utils.db import PostgresORM
6+
from shared_migrations.db.server import ServerQueries
77
from utils.markdown_handler import MarkdownHeaders
88
from utils.github_api import GithubAPI
99
from utils.jwt_generator import GenerateJWT
@@ -80,8 +80,8 @@ def matchProduct(enteredProductName):
8080

8181

8282
async def send_message(ticket_data):
83-
discord_channels = await PostgresORM().readAll("discord_channels")
84-
products = await PostgresORM().readAll("product")
83+
discord_channels = await ServerQueries().readAll("discord_channels")
84+
products = await ServerQueries().readAll("product")
8585

8686
url = None
8787
# for product in products:
@@ -139,7 +139,7 @@ async def get_pull_request(owner, repo, number):
139139

140140
class TicketEventHandler:
141141
def __init__(self):
142-
self.postgres_client = PostgresORM()
142+
self.postgres_client = ServerQueries()
143143
self.ticket_points = {
144144
"hard":30,
145145
"easy":10,
@@ -255,11 +255,11 @@ async def onTicketCreate(self, eventData):
255255
repo = url_components[-3]
256256
owner = url_components[-4]
257257
try:
258-
await PostgresORM().add_data({"issue_id":issue["id"],"updated_at": datetime.utcnow().isoformat()},"app_comments")
258+
await self.postgres_client.add_data({"issue_id":issue["id"],"updated_at": datetime.utcnow().isoformat()},"app_comments")
259259
comment = await TicketFeedbackHandler().createComment(owner, repo, issue_number, markdown_contents)
260260
if comment:
261261

262-
await PostgresORM().update_data({
262+
await self.postgres_client.update_data({
263263
"api_url":comment["url"],
264264
"comment_id":comment["id"],
265265
"issue_id":issue["id"],
@@ -343,25 +343,25 @@ async def onTicketEdit(self, eventData):
343343
if added_contributor:
344344
print('contributors data added')
345345

346-
if await PostgresORM().check_record_exists("app_comments","issue_id",issue["id"]) and ticketType=="ccbp":
346+
if await self.postgres_client.check_record_exists("app_comments","issue_id",issue["id"]) and ticketType=="ccbp":
347347
url_components = issue["url"].split('/')
348348
repo = url_components[-3]
349349
owner = url_components[-4]
350-
comments = await PostgresORM().get_data("issue_id","app_comments",issue["id"],None)
350+
comments = await self.postgres_client.get_data("issue_id","app_comments",issue["id"],None)
351351
comment_id = comments[0]["comment_id"]
352352
if TicketFeedbackHandler().evaluateDict(markdown_contents):
353353
comment = await TicketFeedbackHandler().updateComment(owner, repo, comment_id, markdown_contents)
354354
if comment:
355355

356-
await PostgresORM.get_instance().update_data({
356+
await self.postgres_client.update_data({
357357
"updated_at": datetime.utcnow().isoformat(),
358358
"issue_id": issue["id"]
359359
},"issue_id","app_comments")
360360
else:
361361
try:
362362
comment = await TicketFeedbackHandler().deleteComment(owner, repo, comment_id)
363363
print(f"Print Delete Task,{comment}", file=sys.stderr)
364-
print(await PostgresORM.get_instance().deleteComment(issue["id"],"app_comments"))
364+
print(await self.postgres_client.deleteComment(issue["id"],"app_comments"))
365365
except:
366366
print("Error in deletion")
367367
elif ticketType=="ccbp":
@@ -373,14 +373,14 @@ async def onTicketEdit(self, eventData):
373373
try:
374374

375375

376-
await PostgresORM().add_data({
376+
await self.postgres_client.add_data({
377377
"issue_id":issue["id"],
378378
"updated_at": datetime.utcnow().isoformat()
379379
},"app_comments")
380380
comment = await TicketFeedbackHandler().createComment(owner, repo, issue_number, markdown_contents)
381381
if comment:
382382

383-
await PostgresORM().update_data({
383+
await self.postgres_client.update_data({
384384
"api_url":comment["url"],
385385
"comment_id":comment["id"],
386386
"issue_id":issue["id"],

githubdatapipeline/issues/destination.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from utils.db import SupabaseInterface, PostgresORM
1+
from shared_migrations.db.server import ServerQueries
22
import sys
33
def hasCommunityLabel(labels):
44
if any([label["name"].lower() == "c4gt community" for label in labels]):
@@ -7,7 +7,7 @@ def hasCommunityLabel(labels):
77

88
async def recordIssue(issue):
99
# currentTickets = SupabaseInterface.get_instance().readAll(table="community_program_tickets")
10-
currentTickets = await PostgresORM().readAll(table="community_program_tickets")
10+
currentTickets = await ServerQueries().readAll(table="community_program_tickets")
1111
iss = {
1212
"url": issue["url"] if issue.get("url") else None,
1313
"repository_url": issue["repository_url"] if issue.get("repository_url") else None,
@@ -32,11 +32,11 @@ async def recordIssue(issue):
3232

3333
if iss["id"] in [ticket["id"] for ticket in currentTickets]:
3434
# SupabaseInterface.get_instance().update(table="community_program_tickets", update=iss, query_key="id", query_value=iss["id"])
35-
await PostgresORM().update_data(data=iss, col_name="id", table="community_program_tickets")
35+
await ServerQueries().update_data(data=iss, col_name="id", table="community_program_tickets")
3636
print("updated", file = sys.stderr)
3737
else:
3838
# SupabaseInterface.get_instance().insert(table="community_program_tickets", data=iss)
39-
await PostgresORM().add_data(data=iss, table="community_program_tickets")
39+
await ServerQueries().add_data(data=iss, table="community_program_tickets")
4040
print("created", file = sys.stderr)
4141

4242

githubdatapipeline/pull_request/scraper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import aiohttp, os, sys
2-
from utils.db import PostgresORM
2+
from shared_migrations.db.server import ServerQueries
33
from aiographql.client import GraphQLClient, GraphQLRequest
44
import asyncio
55

@@ -413,7 +413,7 @@ async def get_pull_request(owner, repo, number):
413413

414414

415415
async def get_closed_tickets():
416-
tickets = await PostgresORM().readAll("ccbp_tickets")
416+
tickets = await ServerQueries().readAll("ccbp_tickets")
417417
if tickets is None:
418418
print("No tickets found.")
419419
return []

0 commit comments

Comments
 (0)