brynq-sdk-task-scheduler 1.1.3__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.0
2
2
  Name: brynq_sdk_task_scheduler
3
- Version: 1.1.3
3
+ Version: 1.2.0
4
4
  Summary: Code to execute tasks in BrynQ.com with the task scheduler
5
5
  Home-page: UNKNOWN
6
6
  Author: BrynQ
@@ -32,6 +32,9 @@ class TaskScheduler(BrynQ):
32
32
  self.es = Elastic()
33
33
  self.mysql = MySQL()
34
34
  self.email_after_errors = email_after_errors
35
+ self.customer_db = self.mysql.database
36
+ self.customer_id = self.mysql.raw_query(f'SELECT id FROM sc.customers WHERE dbname = \'{self.customer_db}\'')[0][0]
37
+ self.partner_id = os.getenv('PARTNER_ID').lower().replace(' ', '_') if os.getenv('PARTNER_ID') else 'brynq'
35
38
  self.task_id = task_id
36
39
  self.loglevel = loglevel
37
40
  self.started_at = datetime.datetime.now()
@@ -42,7 +45,6 @@ class TaskScheduler(BrynQ):
42
45
  # If the task is started locally, the parameters should be set locally
43
46
  else:
44
47
  self.started_local = True
45
- self.customer_db = 'placeholder'
46
48
  self.run_id = int(round(time.time() * 100000))
47
49
  print(self.task_id, self.run_id)
48
50
  self.error_count = 0
@@ -50,13 +52,14 @@ class TaskScheduler(BrynQ):
50
52
  # Check if the log tables exists in the customer database. If not, create them
51
53
  # Mysql throws a warning when a table already exists. We don't care so we ignore warnings. (not exceptions!)
52
54
  warnings.filterwarnings('ignore')
53
- # self.check_if_logging_tables_exists()
54
55
 
55
56
  # Check if the task is started on schedule or manual. store in a variable to use later in the script
56
57
  self.task_manual_started = self.check_if_task_manual_started()
57
58
 
58
59
  # Creates Elasticsearch index and data view if not exists
59
- self.es.initialize_customer()
60
+ self.es_index = f"task_execution_log_{self.customer_db}_{self.started_at.strftime('%Y_%m')}"
61
+ self.es.create_index(index_name=self.es_index)
62
+ self.es.create_data_view(space_name='interfaces', view_name=f'task_execution_log_{self.customer_db}', name=f'Task execution log {self.customer_db}', time_field='started_at')
60
63
 
61
64
  # Start the task and setup the data in the database
62
65
  self.start_task()
@@ -72,99 +75,13 @@ class TaskScheduler(BrynQ):
72
75
  key_count += self.__count_keys(value) # Recursively count keys in nested dictionaries
73
76
  return key_count
74
77
 
75
- def check_if_logging_tables_exists(self):
76
- """
77
- This function checks if all the needed tables for the task_scheduler exists. If they don't, this function
78
- creates the needed tables
79
- :return: nothing
80
- """
81
- # Check if the table task_scheduler exists. If not, create it
82
- new_table_query = 'CREATE TABLE IF NOT EXISTS `task_scheduler` (' \
83
- '`id` int(11) NOT NULL AUTO_INCREMENT,' \
84
- '`dashboard_reload` bool NOT NULL DEFAULT \'0\',' \
85
- '`title` varchar(50) NOT NULL,' \
86
- '`description` varchar(255) NOT NULL,' \
87
- '`dashboard_guid` varchar(255) NULL DEFAULT NULL,' \
88
- '`docker_image` varchar(255) DEFAULT NULL,' \
89
- '`runfile_path` varchar(255) DEFAULT NULL,' \
90
- '`trigger_type` enum("MANUAL", "TIME", "OTHER_TASK") NOT NULL DEFAULT \'MANUAL\',' \
91
- '`next_reload` timestamp NULL DEFAULT NULL,' \
92
- '`timezone` enum("Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", "America/Boise", "America/Cambridge_Bay", "America/Campo_Grande", "America/Cancun", "America/Caracas", "America/Cayenne", "America/Cayman", "America/Chicago", "America/Chihuahua", "America/Costa_Rica", "America/Creston", "America/Cuiaba", "America/Curacao", "America/Danmarkshavn", "America/Dawson", "America/Dawson_Creek", "America/Denver", "America/Detroit", "America/Dominica", "America/Edmonton", "America/Eirunepe", "America/El_Salvador", "America/Fort_Nelson", "America/Fortaleza", "America/Glace_Bay", "America/Godthab", "America/Goose_Bay", "America/Grand_Turk", "America/Grenada", "America/Guadeloupe", "America/Guatemala", "America/Guayaquil", "America/Guyana", "America/Halifax", "America/Havana", "America/Hermosillo", "America/Indiana/Indianapolis", "America/Indiana/Knox", "America/Indiana/Marengo", "America/Indiana/Petersburg", "America/Indiana/Tell_City", "America/Indiana/Vevay", "America/Indiana/Vincennes", "America/Indiana/Winamac", "America/Inuvik", "America/Iqaluit", "America/Jamaica", "America/Juneau", "America/Kentucky/Louisville", "America/Kentucky/Monticello", "America/Kralendijk", "America/La_Paz", "America/Lima", "America/Los_Angeles", "America/Lower_Princes", "America/Maceio", "America/Managua", "America/Manaus", "America/Marigot", "America/Martinique", "America/Matamoros", "America/Mazatlan", "America/Menominee", "America/Merida", "America/Metlakatla", "America/Mexico_City", "America/Miquelon", "America/Moncton", "America/Monterrey", "America/Montevideo", "America/Montserrat", "America/Nassau", "America/New_York", "America/Nipigon", "America/Nome", "America/Noronha", "America/North_Dakota/Beulah", "America/North_Dakota/Center", "America/North_Dakota/New_Salem", "America/Ojinaga", "America/Panama", "America/Pangnirtung", "America/Paramaribo", "America/Phoenix", "America/Port-au-Prince", "America/Port_of_Spain", "America/Porto_Velho", "America/Puerto_Rico", "America/Punta_Arenas", "America/Rainy_River", "America/Rankin_Inlet", "America/Recife", "America/Regina", "America/Resolute", "America/Rio_Branco", "America/Santarem", "America/Santiago", "America/Santo_Domingo", "America/Sao_Paulo", "America/Scoresbysund", "America/Sitka", "America/St_Barthelemy", "America/St_Johns", "America/St_Kitts", "America/St_Lucia", "America/St_Thomas", "America/St_Vincent", "America/Swift_Current", "America/Tegucigalpa", "America/Thule", "America/Thunder_Bay", "America/Tijuana", "America/Toronto", "America/Tortola", "America/Vancouver", "America/Whitehorse", "America/Winnipeg", "America/Yakutat", "America/Yellowknife", "Antarctica/Casey", "Antarctica/Davis", "Antarctica/DumontDUrville", "Antarctica/Macquarie", "Antarctica/Mawson", "Antarctica/McMurdo", "Antarctica/Palmer", "Antarctica/Rothera", "Antarctica/Syowa", "Antarctica/Troll", "Antarctica/Vostok", "Arctic/Longyearbyen", "Asia/Aden", "Asia/Almaty", "Asia/Amman", "Asia/Anadyr", "Asia/Aqtau", "Asia/Aqtobe", "Asia/Ashgabat", "Asia/Atyrau", "Asia/Baghdad", "Asia/Bahrain", "Asia/Baku", "Asia/Bangkok", "Asia/Barnaul", "Asia/Beirut", "Asia/Bishkek", "Asia/Brunei", "Asia/Chita", "Asia/Choibalsan", "Asia/Colombo", "Asia/Damascus", "Asia/Dhaka", "Asia/Dili", "Asia/Dubai", "Asia/Dushanbe", "Asia/Famagusta", "Asia/Gaza", "Asia/Hebron", "Asia/Ho_Chi_Minh", "Asia/Hong_Kong", "Asia/Hovd", "Asia/Irkutsk", "Asia/Jakarta", "Asia/Jayapura", "Asia/Jerusalem", "Asia/Kabul", "Asia/Kamchatka", "Asia/Karachi", "Asia/Kathmandu", "Asia/Khandyga", "Asia/Kolkata", "Asia/Krasnoyarsk", "Asia/Kuala_Lumpur", "Asia/Kuching", "Asia/Kuwait", "Asia/Macau", "Asia/Magadan", "Asia/Makassar", "Asia/Manila", "Asia/Muscat", "Asia/Nicosia", "Asia/Novokuznetsk", "Asia/Novosibirsk", "Asia/Omsk", "Asia/Oral", "Asia/Phnom_Penh", "Asia/Pontianak", "Asia/Pyongyang", "Asia/Qatar", "Asia/Qostanay", "Asia/Qyzylorda", "Asia/Riyadh", "Asia/Sakhalin", "Asia/Samarkand", "Asia/Seoul", "Asia/Shanghai", "Asia/Singapore", "Asia/Srednekolymsk", "Asia/Taipei", "Asia/Tashkent", "Asia/Tbilisi", "Asia/Tehran", "Asia/Thimphu", "Asia/Tokyo", "Asia/Tomsk", "Asia/Ulaanbaatar", "Asia/Urumqi", "Asia/Ust-Nera", "Asia/Vientiane", "Asia/Vladivostok", "Asia/Yakutsk", "Asia/Yangon", "Asia/Yekaterinburg", "Asia/Yerevan", "Atlantic/Azores", "Atlantic/Bermuda", "Atlantic/Canary", "Atlantic/Cape_Verde", "Atlantic/Faroe", "Atlantic/Madeira", "Atlantic/Reykjavik", "Atlantic/South_Georgia", "Atlantic/St_Helena", "Atlantic/Stanley", "Australia/Adelaide", "Australia/Brisbane", "Australia/Broken_Hill", "Australia/Currie", "Australia/Darwin", "Australia/Eucla", "Australia/Hobart", "Australia/Lindeman", "Australia/Lord_Howe", "Australia/Melbourne", "Australia/Perth", "Australia/Sydney", "Canada/Atlantic", "Canada/Central", "Canada/Eastern", "Canada/Mountain", "Canada/Newfoundland", "Canada/Pacific", "Europe/Amsterdam", "Europe/Andorra", "Europe/Astrakhan", "Europe/Athens", "Europe/Belgrade", "Europe/Berlin", "Europe/Bratislava", "Europe/Brussels", "Europe/Bucharest", "Europe/Budapest", "Europe/Busingen", "Europe/Chisinau", "Europe/Copenhagen", "Europe/Dublin", "Europe/Gibraltar", "Europe/Guernsey", "Europe/Helsinki", "Europe/Isle_of_Man", "Europe/Istanbul", "Europe/Jersey", "Europe/Kaliningrad", "Europe/Kiev", "Europe/Kirov", "Europe/Lisbon", "Europe/Ljubljana", "Europe/London", "Europe/Luxembourg", "Europe/Madrid", "Europe/Malta", "Europe/Mariehamn", "Europe/Minsk", "Europe/Monaco", "Europe/Moscow", "Europe/Oslo", "Europe/Paris", "Europe/Podgorica", "Europe/Prague", "Europe/Riga", "Europe/Rome", "Europe/Samara", "Europe/San_Marino", "Europe/Sarajevo", "Europe/Saratov", "Europe/Simferopol", "Europe/Skopje", "Europe/Sofia", "Europe/Stockholm", "Europe/Tallinn", "Europe/Tirane", "Europe/Ulyanovsk", "Europe/Uzhgorod", "Europe/Vaduz", "Europe/Vatican", "Europe/Vienna", "Europe/Vilnius", "Europe/Volgograd", "Europe/Warsaw", "Europe/Zagreb", "Europe/Zaporozhye", "Europe/Zurich", "GMT", "Indian/Antananarivo", "Indian/Chagos", "Indian/Christmas", "Indian/Cocos", "Indian/Comoro", "Indian/Kerguelen", "Indian/Mahe", "Indian/Maldives", "Indian/Mauritius", "Indian/Mayotte", "Indian/Reunion", "Pacific/Apia", "Pacific/Auckland", "Pacific/Bougainville", "Pacific/Chatham", "Pacific/Chuuk", "Pacific/Easter", "Pacific/Efate", "Pacific/Enderbury", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Funafuti", "Pacific/Galapagos", "Pacific/Gambier", "Pacific/Guadalcanal", "Pacific/Guam", "Pacific/Honolulu", "Pacific/Kiritimati", "Pacific/Kosrae", "Pacific/Kwajalein", "Pacific/Majuro", "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Wake", "Pacific/Wallis", "US/Alaska", "US/Arizona", "US/Central", "US/Eastern", "US/Hawaii", "US/Mountain", "US/Pacific", "UTC") CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT \"Europe/Amsterdam\",' \
93
- '`frequency` varchar(255) DEFAULT \'{"month":0,"day":0,"hour":0,"minute":0}\',' \
94
- '`start_after_task_id` int DEFAULT NULL,' \
95
- '`start_after_preceding_task` enum("FAILED", "SUCCESS") DEFAULT NULL,' \
96
- '`last_reload` timestamp NULL DEFAULT NULL,' \
97
- '`last_error_message` varchar(255) DEFAULT NULL,' \
98
- '`status` varchar(255) DEFAULT \'IDLE\',' \
99
- '`disabled` tinyint(4) DEFAULT \'1\',' \
100
- '`run_instant` tinyint(1) DEFAULT \'0\',' \
101
- '`sftp_mapping` varchar(255) NOT NULL DEFAULT \'[]\',' \
102
- '`step_nr` int NOT NULL DEFAULT \'0\',' \
103
- '`stopped_by_user` tinyint(1) DEFAULT \'0\',' \
104
- '`stop_is_allowed` bool NOT NULL DEFAULT \'0\',' \
105
- 'PRIMARY KEY (`id`),' \
106
- 'UNIQUE KEY `task_scheduler_id_uindex` (`id`),' \
107
- 'constraint task_scheduler_task_scheduler_id_fk foreign key (start_after_task_id) references task_scheduler (id)' \
108
- ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci'
109
- self.mysql.raw_query(new_table_query)
110
-
111
- # Check if the table task_scheduler_log exists. If not, create it
112
- new_table_query = 'CREATE TABLE IF NOT EXISTS `task_scheduler_log` (' \
113
- '`reload_id` bigint NOT NULL,' \
114
- '`task_id` int NULL,' \
115
- '`reload_status` varchar(255) NULL,' \
116
- '`started_at` datetime NULL,' \
117
- '`finished_at` datetime NULL' \
118
- ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci'
119
- self.mysql.raw_query(new_table_query)
120
-
121
- # Check if the table check_task_execution_log exists. If not, create it
122
- new_table_query = 'CREATE TABLE IF NOT EXISTS `task_execution_log`(' \
123
- '`reload_id` bigint NOT NULL,' \
124
- '`task_id` int NULL,' \
125
- '`log_level` varchar(255) NULL,' \
126
- '`created_at` datetime NULL,' \
127
- '`line_number` int NULL,' \
128
- '`message` longtext NULL)' \
129
- 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci'
130
- self.mysql.raw_query(new_table_query)
131
-
132
- # Check if the table check_task_execution_steps exists. If not, create it
133
- new_table_query = 'CREATE TABLE IF NOT EXISTS `task_execution_steps`(' \
134
- '`id` bigint NOT NULL AUTO_INCREMENT,' \
135
- '`task_id` int NULL,' \
136
- '`nr` int DEFAULT 0 NOT NULL,' \
137
- '`description` varchar(255) DEFAULT \'ZzZzZz...\' NOT NULL,' \
138
- 'PRIMARY KEY (`id`),' \
139
- 'UNIQUE KEY `task_execution_steps_id_uindex` (`id`),' \
140
- 'UNIQUE INDEX `task_execution_steps_task_id_nr_uindex` (`task_id`, `nr`))' \
141
- 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci'
142
- self.mysql.raw_query(new_table_query)
143
-
144
- new_table_query = 'CREATE TABLE IF NOT EXISTS `task_variables`(' \
145
- 'id INT NOT NULL AUTO_INCREMENT,' \
146
- 'task_id INT NOT NULL,' \
147
- 'name VARCHAR(150) NOT NULL,' \
148
- 'description VARCHAR(255) NULL,' \
149
- 'type ENUM(\'INT\', \'TINYINT\', \'BIGINT\', \'FLOAT\', \'DOUBLE\', \'DATETIME\', \'TIMESTAMP\', \'TIME\', \'VARCHAR\', \'BLOB\', \'TEXT\', \'LONGBLOB\') NOT NULL,' \
150
- 'value VARCHAR(600) NULL,' \
151
- 'temp_value VARCHAR(600) NULL,' \
152
- 'PRIMARY KEY (`id`),' \
153
- 'UNIQUE KEY `task_variables_id_uindex` (`id`),' \
154
- 'UNIQUE INDEX `task_variables_name_value_uindex` (`task_id`, `name`, `value`), ' \
155
- 'INDEX `task_variables_name_index` (`name`),' \
156
- 'CONSTRAINT task_variables_task_scheduler_id_fk ' \
157
- 'FOREIGN KEY (`task_id`) REFERENCES task_scheduler (`id`) ON DELETE CASCADE)' \
158
- 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci'
159
- self.mysql.raw_query(new_table_query)
160
-
161
- # Add the variable 'email_errors_to' as default to the new added table if it doesn't exist for the current task
162
- response = self.mysql.select('task_variables', 'temp_value',
163
- f'WHERE name = \'email_errors_to\' AND task_id = {self.task_id}')
164
- if len(response) == 0:
165
- new_variables = f"-- INSERT INTO `task_variables` (`task_id`, `name`, `type`, `value`, `temp_value`) " \
166
- f"VALUES ({self.task_id}, 'email_errors_to', 'TEXT', 'example@brynq.com, example2@brynq.com', 'example@brynq.com, example2@brynq.com')"
167
- self.mysql.raw_query(new_variables, insert=True)
78
+ def __get_caller_info(self):
79
+ stack = inspect.stack()
80
+ caller_frame = stack[2][0]
81
+ file_name = caller_frame.f_code.co_filename
82
+ line_number = caller_frame.f_lineno
83
+ function_name = stack[2][3]
84
+ return file_name, line_number, function_name
168
85
 
169
86
  def create_task_execution_steps(self, step_details: list):
170
87
  """
@@ -253,7 +170,8 @@ class TaskScheduler(BrynQ):
253
170
  if loglevel not in allowed_loglevels:
254
171
  raise Exception('You\'ve entered a not allowed loglevel. Choose one of: {}'.format(allowed_loglevels))
255
172
 
256
- # Handling different data types and preparing extra payload information based on the data type
173
+ # For Elastic, we need to have the data in JSON format. Handling different data types and preparing extra payload information based on the data type
174
+ # If the data is just a series, count rows, columns and cells
257
175
  if isinstance(data, pd.Series):
258
176
  dataframe = pd.DataFrame(data).T
259
177
  extra_payload = {
@@ -263,6 +181,7 @@ class TaskScheduler(BrynQ):
263
181
  }
264
182
  if not full_extract:
265
183
  extra_payload['payload'] = dataframe.to_json(orient='records')
184
+ # If the data is a list, count rows, columns and cells
266
185
  elif isinstance(data, dict):
267
186
  records = self.__count_keys(data)
268
187
  extra_payload = {
@@ -280,6 +199,7 @@ class TaskScheduler(BrynQ):
280
199
  }
281
200
  if not full_extract:
282
201
  extra_payload['payload'] = data.to_json(orient='records')
202
+ # If the data is a response from an URL request, also store all the information about the URL request.
283
203
  elif isinstance(data, requests.Response):
284
204
  records = 1
285
205
  if data.request.body is not None:
@@ -312,41 +232,37 @@ class TaskScheduler(BrynQ):
312
232
  elif data is not None and full_extract is False:
313
233
  extra_payload['full_load'] = False
314
234
 
315
- # Preparing the primary payload with log details
235
+ # Get the linenumber from where the logline is executed.
236
+ file_name, line_number, function_name = self.__get_caller_info()
237
+
238
+ # Put everything together in the payload for ElasticSearch and send it
316
239
  payload = {
317
- 'reload_id': self.run_id,
318
240
  'task_id': self.task_id,
319
- 'customer_id': os.getenv('BRYNQ_SUBDOMAIN').lower().replace(' ', '_'),
241
+ 'reload_id': self.run_id,
320
242
  'started_at': datetime.datetime.now().isoformat(),
321
- 'loglevel': loglevel,
243
+ 'partner_id': self.partner_id,
244
+ 'customer_id': self.customer_id,
245
+ 'customer': os.getenv('BRYNQ_CUSTOMER_NAME').lower().replace(' ', '_'),
246
+ 'file_name': file_name,
247
+ 'function_name': function_name,
248
+ 'line_number': line_number,
249
+ 'task_loglevel': self.loglevel,
250
+ 'line_loglevel': loglevel,
322
251
  'message': message
323
252
  }
324
253
  payload.update(extra_payload)
254
+ self.es.post_document(index_name=self.es_index, document=payload)
325
255
 
326
- # Sending the payload to ElasticSearch
327
- self.es.task_execution_log(payload)
328
-
329
- # Get the linenumber from where the logline is executed. Get the stacktrace of this action, jump 1 file up and pick then the linenumber (second item)
330
- linenumber = inspect.getouterframes(inspect.currentframe())[1][2]
331
- # Write the logline to the database, depends on the chosen loglevel in the task
332
- print('{} at line: {}'.format(message, linenumber))
256
+ # Write the logline to the MYSQL database, depends on the chosen loglevel in the task
257
+ print('{} at line: {}'.format(message, line_number))
333
258
  # Remove quotes from message since these break the query
334
259
  message = re.sub("[']", '', message)
335
- timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
336
- information = {
337
- 'reload_id': self.run_id,
338
- 'task_id': self.task_id,
339
- 'log_level': loglevel,
340
- 'line_number': linenumber,
341
- 'message': message,
342
- 'created_at': timestamp
343
- }
344
260
  if self.loglevel == 'DEBUG':
345
261
  # Count the errors
346
262
  if loglevel == 'ERROR' or loglevel == 'CRITICAL':
347
263
  self.error_count += 1
348
264
  return self.mysql.raw_query(
349
- "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), linenumber, message), insert=True)
265
+ "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), line_number, message), insert=True)
350
266
  return self.mysql.update(table='task_execution_log',
351
267
  columns=['reload_id', 'task_id', 'log_level', 'created_at', 'line_number', 'message'],
352
268
  values=[self.run_id, self.task_id, loglevel, datetime.datetime.now(), linenumber, message])
@@ -355,15 +271,15 @@ class TaskScheduler(BrynQ):
355
271
  if loglevel == 'ERROR' or loglevel == 'CRITICAL':
356
272
  self.error_count += 1
357
273
  return self.mysql.raw_query(
358
- "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), linenumber, message), insert=True)
274
+ "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), line_number, message), insert=True)
359
275
  elif self.loglevel == 'ERROR' and (loglevel == 'ERROR' or loglevel == 'CRITICAL'):
360
276
  self.error_count += 1
361
277
  return self.mysql.raw_query(
362
- "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), linenumber, message), insert=True)
278
+ "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), line_number, message), insert=True)
363
279
  elif self.loglevel == 'CRITICAL' and loglevel == 'CRITICAL':
364
280
  self.error_count += 1
365
281
  return self.mysql.raw_query(
366
- "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), linenumber, message), insert=True)
282
+ "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, '{}', '{}', {}, '{}')".format(self.run_id, self.task_id, loglevel, datetime.datetime.now(), line_number, message), insert=True)
367
283
 
368
284
  def update_execution_step(self, step_number: int):
369
285
  """
@@ -385,27 +301,35 @@ class TaskScheduler(BrynQ):
385
301
  :param started_at: Give the time the task is started
386
302
  :return: nothing
387
303
  """
304
+ # Format error to a somewhat readable format
305
+ exc_type, exc_obj, exc_tb = sys.exc_info()
306
+ error = str(e)[:400].replace('\'', '').replace('\"', '') + ' | Line: {}'.format(exc_tb.tb_lineno)
388
307
 
389
- # Preparing the primary payload with error details for upload to elastic
308
+ # Get the linenumber from where the logline is executed.
309
+ file_name, line_number, function_name = self.__get_caller_info()
310
+
311
+ # Preparing the primary payload with error details for upload to elastic and send it
390
312
  payload = {
391
- 'reload_id': self.run_id,
392
313
  'task_id': self.task_id,
393
- 'customer_id': os.getenv('BRYNQ_SUBDOMAIN').lower().replace(' ', '_'),
314
+ 'reload_id': self.run_id,
394
315
  'started_at': datetime.datetime.now().isoformat(),
395
- 'loglevel': 'CRITICAL',
316
+ 'partner_id': self.partner_id,
317
+ 'customer_id': self.customer_id,
318
+ 'customer': os.getenv('BRYNQ_CUSTOMER_NAME').lower().replace(' ', '_'),
319
+ 'file_name': file_name,
320
+ 'function_name': function_name,
321
+ 'line_number': line_number,
322
+ 'task_loglevel': self.loglevel,
323
+ 'line_loglevel': 'CRITICAL',
396
324
  'message': str(e),
397
325
  'traceback': traceback.format_exc()
398
326
  }
327
+ self.es.post_document(index_name=self.es_index, document=payload)
399
328
 
400
- # Sending the payload to ElasticSearch
401
- self.es.task_execution_log(payload)
402
329
 
403
- # Format error to a somewhat readable format
404
- exc_type, exc_obj, exc_tb = sys.exc_info()
405
- error = str(e)[:400].replace('\'', '').replace('\"', '') + ' | Line: {}'.format(exc_tb.tb_lineno)
406
330
  # Get scheduler task details for logging
407
331
  task_details = \
408
- self.mysql.select('task_scheduler', 'docker_image, runfile_path', 'WHERE id = {}'.format(self.task_id))[0]
332
+ self.mysql.select('task_scheduler, data_interfaces', 'data_interfaces.docker_image, data_interfaces.runfile_path', 'WHERE task_scheduler.data_interface_id = data_interfaces.id AND task_scheduler.id = {}'.format(self.task_id))[0]
409
333
  taskname = task_details[0]
410
334
  customer = task_details[1].split('/')[-1].split('.')[0]
411
335
 
@@ -415,15 +339,6 @@ class TaskScheduler(BrynQ):
415
339
  ['IDLE', datetime.datetime.now(), 'Failed', 0],
416
340
  'WHERE `id` = {}'.format(self.task_id))
417
341
  # Log to database
418
- timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
419
- information = {
420
- 'reload_id': self.run_id,
421
- 'task_id': self.task_id,
422
- 'log_level': 'CRITICAL',
423
- 'line_number': exc_tb.tb_lineno,
424
- 'message': error,
425
- 'created_at': timestamp
426
- }
427
342
  self.mysql.raw_query(
428
343
  "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, 'CRITICAL', '{}', {}, '{}')".format(self.run_id,
429
344
  self.task_id,
@@ -448,15 +363,6 @@ class TaskScheduler(BrynQ):
448
363
 
449
364
  raise Exception(error)
450
365
  else:
451
- timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
452
- information = {
453
- 'reload_id': self.run_id,
454
- 'task_id': self.task_id,
455
- 'log_level': 'CRITICAL',
456
- 'line_number': exc_tb.tb_lineno,
457
- 'message': error,
458
- 'created_at': timestamp
459
- }
460
366
  self.mysql.raw_query(
461
367
  "INSERT INTO `task_execution_log` (reload_id, task_id, log_level, created_at, line_number, message) VALUES ({}, {}, 'CRITICAL', '{}', {}, '{}')".format(self.run_id,
462
368
  self.task_id,
@@ -537,11 +443,9 @@ class TaskScheduler(BrynQ):
537
443
  for i in email_to:
538
444
  email_list.append({'name': 'BrynQ User', 'mail': i.strip()})
539
445
  # Set the content of the mail and all other stuff
540
- task = self.mysql.select(table='task_scheduler', selection='title', filter=f'WHERE id = {self.task_id}')[0][
541
- 0]
446
+ task = self.mysql.select(table='data_interfaces', selection='title', filter=f'WHERE id = {self.task_id}')[0][0]
542
447
  finished_at = \
543
- self.mysql.select(table='task_scheduler', selection='last_reload', filter=f'WHERE id = {self.task_id}')[0][
544
- 0]
448
+ self.mysql.select(table='task_scheduler', selection='last_reload', filter=f'WHERE data_interface_id = {self.task_id}')[0][0]
545
449
  if failed:
546
450
  subject = f'Task \'{task}\' has failed'
547
451
  content = f'Task \'{task}\' with task ID \'{self.task_id}\' failed during its last run and was stopped at {finished_at}. ' \
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.0
2
2
  Name: brynq-sdk-task-scheduler
3
- Version: 1.1.3
3
+ Version: 1.2.0
4
4
  Summary: Code to execute tasks in BrynQ.com with the task scheduler
5
5
  Home-page: UNKNOWN
6
6
  Author: BrynQ
@@ -3,7 +3,7 @@ from setuptools import setup
3
3
 
4
4
  setup(
5
5
  name='brynq_sdk_task_scheduler',
6
- version='1.1.3',
6
+ version='1.2.0',
7
7
  description='Code to execute tasks in BrynQ.com with the task scheduler',
8
8
  long_description='Code to execute tasks in the BrynQ.com platform with the task scheduler',
9
9
  author='BrynQ',