Skip to content
This repository was archived by the owner on May 23, 2023. It is now read-only.

Commit d4ec131

Browse files
Merge pull request #8 from madeiramadeirabr/equiparacao_lambda_sqs
Equiparacao lambda sqs com lambda api
2 parents a49ffe0 + de669e0 commit d4ec131

File tree

53 files changed

+1272
-174
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+1272
-174
lines changed

examples/lambda_api/app.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,6 @@
4343
@app.route('/')
4444
def index():
4545
body = {"app": '%s:%s' % (APP_NAME, APP_VERSION)}
46-
# logger.info('Env: {} App Info: {}'.format(config.APP_ENV, body))
47-
# Temporário para debug
48-
# logger.info('Env Vars: {}'.format(config.to_dict()))
4946
return http_helper.create_response(body=body, status_code=200)
5047

5148

examples/lambda_api/lambda_app/aws/secrets.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88

99
class Secrets:
10-
def __init__(self, logger=None):
10+
def __init__(self, logger=None, profile=None, session=None):
1111
"""
1212
# This cant import get_config
1313
:param logger:
@@ -16,24 +16,34 @@ def __init__(self, logger=None):
1616
self.logger = logger if logger is not None else get_logger()
1717
# last_exception
1818
self.exception = None
19+
# profile
20+
self.profile = profile if profile is not None else \
21+
os.environ['AWS_PROFILE'] if 'AWS_PROFILE' in os.environ else None
22+
# session
23+
self.session = session if session is not None else \
24+
boto3.session.Session(profile_name=self.profile)
1925

2026
def connect(self):
2127
connection = None
2228
try:
23-
profile = os.environ['AWS_PROFILE'] if 'AWS_PROFILE' in os.environ else None
2429
region_name = os.environ['AWS_REGION'] if 'AWS_REGION' in os.environ else None
30+
2531
# region validation
2632
if region_name is None:
2733
region_name = os.environ['REGION_NAME'] if 'REGION_NAME' in os.environ else 'us-east-2'
2834

29-
self.logger.info('profile: {}'.format(profile))
30-
if profile:
31-
session = boto3.session.Session(profile_name=profile)
35+
self.logger.info('Secrets - profile: {}'.format(self.profile))
36+
self.logger.info('Secrets - self.config.REGION_NAME: {}'.format(region_name))
37+
38+
if self.profile:
39+
session = self.session
40+
# todo avaliar troca para session.resource
3241
connection = session.client(
3342
service_name='secretsmanager',
3443
region_name=region_name
3544
)
3645
else:
46+
# todo avaliar troca para boto3.resource
3747
connection = boto3.client(
3848
service_name='secretsmanager',
3949
region_name=region_name

examples/lambda_api/lambda_app/events/aws/sqs.py renamed to examples/lambda_api/lambda_app/aws/sqs.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,18 @@ def connect(self, retry=False):
3131
connection = None
3232
try:
3333
endpoint_url = self.config.SQS_ENDPOINT
34+
region_name = self.config.REGION_NAME
35+
36+
# region validation
37+
if region_name is None:
38+
region_name = os.environ['REGION_NAME'] if 'REGION_NAME' in os.environ else 'us-east-2'
3439

3540
queue_name = os.path.basename(os.environ['APP_QUEUE']) if 'APP_QUEUE' in os.environ else None
41+
3642
self.logger.info('SQSEvents - profile: {}'.format(self.profile))
3743
self.logger.info('SQSEvents - endpoint_url: {}'.format(endpoint_url))
3844
self.logger.info('SQSEvents - queue_name: {}'.format(queue_name))
39-
self.logger.info('SQSEvents - self.config.REGION_NAME: {}'.format(self.config.REGION_NAME))
45+
self.logger.info('SQSEvents - self.config.REGION_NAME: {}'.format(region_name))
4046

4147
if self.profile:
4248
session = self.session

examples/lambda_api/lambda_app/database/dynamodb.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import boto3
55

6-
from chalicelib.logging import get_logger
6+
from lambda_app.logging import get_logger
77

88
logger = get_logger()
99

@@ -17,6 +17,7 @@ def reset():
1717
_CONNECTION = False
1818

1919

20+
# TODO aplicar class aos moldes da pasta aws
2021
def get_connection(connect=True, retry=False):
2122
global _CONNECTION, _RETRY_COUNT, _MAX_RETRY_ATTEMPTS
2223
if not _CONNECTION:

examples/lambda_api/lambda_app/database/mysql.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ def reset():
1616
_CONNECTION = False
1717

1818

19+
# TODO aplicar class aos moldes da pasta aws
1920
def get_connection(config=None, connect=True, retry=False):
2021
global _CONNECTION, _RETRY_COUNT, _MAX_RETRY_ATTEMPTS
2122
if not _CONNECTION:

examples/lambda_api/lambda_app/database/redis.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ def reset():
1717
_CONNECTION = False
1818

1919

20+
# TODO aplicar class aos moldes da pasta aws
2021
def get_connection(config=None, retry=False):
2122
global _CONNECTION, _RETRY_COUNT, _MAX_RETRY_ATTEMPTS
2223
if not _CONNECTION:

examples/lambda_api/lambda_app/services/event_manager.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from lambda_app.exceptions import ApiException
77
from lambda_app.helper import generate_hash
88
from lambda_app.logging import get_logger
9+
from lambda_app.services.v1.ocoren_event_service import OcorenEventService
910
from lambda_app.vos.events import EventVO
1011

1112

@@ -28,7 +29,7 @@ def __init__(self, event_service=None, logger=None, config=None, redis_connectio
2829
self.config = config if config is not None else get_config()
2930
# database connection
3031
self.redis_connection = redis_connection if redis_connection is not None else get_connection()
31-
self.event_service = event_service if event_service is not None else None
32+
self.event_service = event_service if event_service is not None else OcorenEventService(self.logger)
3233
self.event_tracker = event_tracker if event_tracker is not None else EventTracker(self.logger)
3334
self.exception = None
3435

examples/lambda_api/lambda_app/services/v1/healthcheck/resources.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from lambda_app.services.v1.healthcheck import AbstractHealthCheck, HealthCheckResult
66
from lambda_app.database.mysql import get_connection
77
from lambda_app.database.redis import get_connection as redis_get_connection
8-
from lambda_app.events.aws.sqs import SQSEvents
8+
from lambda_app.aws.sqs import SQSEvents
99

1010

1111
class SelfConnectionHealthCheck(AbstractHealthCheck):

examples/lambda_api/lambda_app/services/v1/ocoren_event_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from lambda_app.config import get_config
2-
from lambda_app.events.aws.sqs import SQSEvents
2+
from lambda_app.aws.sqs import SQSEvents
33
from lambda_app.logging import get_logger
44
from lambda_app.vos.events import EventVO
55

Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
import sys
2+
import re
3+
import os
4+
import logging
5+
6+
os.environ["LOG_LEVEL"] = logging.getLevelName(logging.INFO)
7+
8+
if __package__:
9+
current_path = os.path.abspath(os.path.dirname(__file__)).replace('/' + str(__package__), '', 1)
10+
else:
11+
current_path = os.path.abspath(os.path.dirname(__file__))
12+
13+
if not current_path[-1] == '/':
14+
current_path += '/'
15+
16+
ROOT_DIR = current_path.replace('scripts/migrations/mysql/', '')
17+
18+
_REGISTERED_PATHS = False
19+
20+
21+
def register_paths():
22+
global _REGISTERED_PATHS
23+
if not _REGISTERED_PATHS:
24+
# path fixes, define the priority of the modules search
25+
sys.path.insert(0, ROOT_DIR)
26+
sys.path.insert(0, ROOT_DIR + 'venv/')
27+
sys.path.insert(1, ROOT_DIR + 'chalicelib/')
28+
sys.path.insert(1, ROOT_DIR + 'flask_app/')
29+
sys.path.insert(1, ROOT_DIR + 'lambda_app/')
30+
sys.path.insert(2, ROOT_DIR + 'vendor/')
31+
_REGISTERED_PATHS = True
32+
pass
33+
34+
35+
# register the paths
36+
register_paths()
37+
38+
from lambda_app.logging import get_logger
39+
from lambda_app.boot import reset, load_dot_env, load_env
40+
from lambda_app.config import reset as reset_config, get_config
41+
from lambda_app.database.mysql import get_connection
42+
43+
logger = get_logger()
44+
logger.info("ROOT_DIR " + ROOT_DIR)
45+
46+
47+
if __package__:
48+
current_path = os.path.abspath(os.path.dirname(__file__)).replace('/' + str(__package__), '', 1)
49+
else:
50+
current_path = os.path.abspath(os.path.dirname(__file__))
51+
52+
if not current_path[-1] == '/':
53+
current_path += '/'
54+
55+
56+
class ConnectionHelper:
57+
@staticmethod
58+
def get_mysql_local_connection():
59+
return get_connection()
60+
61+
62+
class MySQLHelper:
63+
64+
@staticmethod
65+
def get_connection():
66+
"""
67+
:return:
68+
"""
69+
return ConnectionHelper.get_mysql_local_connection()
70+
71+
@staticmethod
72+
def drop_table(connection, table_name):
73+
result = True
74+
try:
75+
# connection = MySQLHelper.get_connection()
76+
connection.connect()
77+
78+
content = "DROP TABLE IF EXISTS " + table_name
79+
print(f"Deleting {table_name}...")
80+
with connection.cursor() as cursor:
81+
cursor.execute(content)
82+
print(f"{table_name} deleted")
83+
84+
except Exception as err:
85+
print(f"{table_name} not exists")
86+
try:
87+
connection.close()
88+
except Exception as err:
89+
pass
90+
return result
91+
92+
@staticmethod
93+
def sow_table(connection, table_name, file_name):
94+
result = False
95+
cnt = 0
96+
seeder_file = None
97+
try:
98+
connection.connect()
99+
seeder_file = open(file_name, 'r')
100+
line = seeder_file.readline().strip().replace(';', '')
101+
cnt = 0
102+
try:
103+
while line:
104+
cnt += 1
105+
with connection.cursor() as cursor:
106+
if line != '':
107+
cursor.execute(line,)
108+
line = seeder_file.readline().strip().replace(';', '')
109+
110+
connection.commit()
111+
result = True
112+
except Exception as ex:
113+
result = False
114+
connection.rollback()
115+
print(ex)
116+
except Exception as ex:
117+
result = False
118+
print(ex)
119+
finally:
120+
if seeder_file is not None:
121+
seeder_file.close()
122+
123+
print("Total of rows affected: %d" % cnt)
124+
try:
125+
connection.close()
126+
except Exception as err:
127+
pass
128+
return result
129+
130+
@staticmethod
131+
def create_table(connection, table_name, file_name):
132+
result = False
133+
134+
connection.connect()
135+
try:
136+
sql = 'SELECT table_name FROM information_schema.tables WHERE table_schema = %s'
137+
with connection.cursor() as cursor:
138+
cursor.execute(sql, (table_name,))
139+
table_exists = cursor.fetchone()
140+
except Exception as err:
141+
table_exists = False
142+
143+
if not table_exists:
144+
sql_file = open(file_name, 'r')
145+
create_table = sql_file.read()
146+
sql_file.close()
147+
148+
try:
149+
with connection.cursor() as cursor:
150+
result = cursor.execute(create_table)
151+
print(f"Creating {table_name}...")
152+
except Exception as err:
153+
result = False
154+
print(f"Not created {table_name}...")
155+
else:
156+
print(f'Table {table_name} already exists')
157+
try:
158+
connection.close()
159+
except Exception as err:
160+
pass
161+
return result
162+
163+
164+
command = None
165+
sql_file = None
166+
try:
167+
sql_file = sys.argv[1]
168+
except IndexError as err:
169+
logger.error(err)
170+
exit('Filename required')
171+
172+
try:
173+
logger.info("Load configuration")
174+
# reset config and env
175+
reset()
176+
reset_config()
177+
# load integration
178+
APP_TYPE = os.environ['APP_TYPE']
179+
if APP_TYPE == 'Flask':
180+
load_dot_env()
181+
else:
182+
load_env()
183+
config = get_config()
184+
except IndexError as err:
185+
logger.error(err)
186+
exit('Filename required')
187+
188+
189+
class Command:
190+
CREATE_TABLE = 'CREATE_TABLE'
191+
INSERT_INTO = 'INSERT_INTO'
192+
193+
194+
def get_commnad(line):
195+
command = None
196+
if "CREATE TABLE" in line:
197+
command = Command.CREATE_TABLE
198+
if "INSERT INTO" in line:
199+
command = Command.INSERT_INTO
200+
return command
201+
202+
203+
def get_table_name(content, only_table=False):
204+
table_name = None
205+
rx = re.search("CREATE TABLE (IF NOT EXISTS )?([\w.]+)", content)
206+
if not rx:
207+
rx = re.search("INSERT INTO ([\w.]+)", content)
208+
if rx:
209+
groups = rx.groups()
210+
if len(groups) > 0:
211+
table_name = groups[len(groups)-1]
212+
213+
if table_name and only_table:
214+
table_name_parts = table_name.split('.')
215+
table_name = table_name_parts[len(table_name_parts)-1]
216+
return table_name
217+
218+
219+
try:
220+
connection = MySQLHelper.get_connection()
221+
with open(ROOT_DIR + sql_file, 'r') as f:
222+
content = f.read()
223+
f.close()
224+
225+
command = get_commnad(content)
226+
file_name = ROOT_DIR + sql_file
227+
if command == Command.CREATE_TABLE:
228+
table_name = get_table_name(content)
229+
created = MySQLHelper.create_table(connection, table_name, file_name)
230+
if created is not False:
231+
logger.info("Table created")
232+
if command == Command.INSERT_INTO:
233+
table_name = get_table_name(content)
234+
sow = MySQLHelper.sow_table(connection, table_name, file_name)
235+
if sow is not False:
236+
logger.info("Table sow")
237+
238+
239+
except Exception as err:
240+
logger.error(err)
241+
exit('File not found')

0 commit comments

Comments
 (0)