-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
547 additions
and
7 deletions.
There are no files selected for viewing
114 changes: 114 additions & 0 deletions
114
src/aap_eda/core/migrations/0056_rulebookprocesslog_log_created_at_and_more.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
# Generated by Django 4.2.16 on 2025-01-23 05:05 | ||
|
||
import logging | ||
|
||
from django.db import migrations, models | ||
|
||
from aap_eda.core.utils.rulebook_process_logs import ( | ||
extract_datetime_and_message_from_log_entry, | ||
) | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
CHUNK_SIZE = 1000 | ||
|
||
|
||
def up_log_entries(apps, schema_editor): | ||
rulebook_process_log_model = apps.get_model("core", "RulebookProcessLog") | ||
|
||
updated_entries = [] | ||
corrupted_entries = [] | ||
total_records = 0 | ||
|
||
for entry in rulebook_process_log_model.objects.iterator( | ||
chunk_size=CHUNK_SIZE | ||
): | ||
try: | ||
dt, message = extract_datetime_and_message_from_log_entry( | ||
entry.log | ||
) | ||
entry.log_created_at = dt | ||
entry.log = message | ||
|
||
updated_entries.append(entry) | ||
except Exception as ex: | ||
corrupted_entries.append(entry) | ||
logger.warning( | ||
f"Skipping parse entry {entry.id} due to error: {ex}" | ||
) | ||
|
||
# update per CHUNK_SIZE in case of large records in DB | ||
if len(updated_entries) >= CHUNK_SIZE: | ||
rulebook_process_log_model.objects.bulk_update( | ||
updated_entries, ["log", "log_created_at"] | ||
) | ||
total_records += len(updated_entries) | ||
logger.info(f"{total_records} entries are parsed.") | ||
updated_entries = [] | ||
|
||
# update the last trunck | ||
if updated_entries: | ||
rulebook_process_log_model.objects.bulk_update( | ||
updated_entries, ["log", "log_created_at"] | ||
) | ||
total_records += len(updated_entries) | ||
|
||
logger.info(f"Totally {total_records} entries are parsed.") | ||
if len(corrupted_entries) > 0: | ||
logger.info(f"Totally {len(corrupted_entries)} entries are skipped.") | ||
|
||
|
||
def down_log_entries(apps, schema_editor): | ||
rulebook_process_log_model = apps.get_model("core", "RulebookProcessLog") | ||
|
||
updated_entries = [] | ||
total_records = 0 | ||
|
||
for entry in rulebook_process_log_model.objects.iterator( | ||
chunk_size=CHUNK_SIZE | ||
): | ||
try: | ||
if entry.log_created_at: | ||
timestamp_str = entry.log_created_at.strftime( | ||
"%Y-%m-%d %H:%M:%S,%f" | ||
).rstrip("0") | ||
message = f"{timestamp_str} {entry.log}" | ||
entry.log = message | ||
updated_entries.append(entry) | ||
except ValueError as err: | ||
logger.warning( | ||
f"Skipping reverse entry {entry.id} due to error: {err}" | ||
) | ||
|
||
# update per CHUNK_SIZE in case of large records in DB | ||
if len(updated_entries) >= CHUNK_SIZE: | ||
rulebook_process_log_model.objects.bulk_update( | ||
updated_entries, ["log"] | ||
) | ||
total_records += len(updated_entries) | ||
logger.info(f"{total_records} entries are reversed.") | ||
updated_entries = [] | ||
|
||
# update the last trunck | ||
if updated_entries: | ||
rulebook_process_log_model.objects.bulk_update( | ||
updated_entries, ["log"] | ||
) | ||
total_records += len(updated_entries) | ||
|
||
logger.info(f"Totally {total_records} entries are reversed.") | ||
|
||
|
||
class Migration(migrations.Migration): | ||
dependencies = [ | ||
("core", "0055_activation_created_by_activation_modified_by_and_more"), | ||
] | ||
|
||
operations = [ | ||
migrations.AddField( | ||
model_name="rulebookprocesslog", | ||
name="log_created_at", | ||
field=models.DateTimeField(null=True), | ||
), | ||
migrations.RunPython(up_log_entries, down_log_entries), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
# Copyright 2025 Red Hat, Inc. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import re | ||
from datetime import datetime | ||
from typing import Optional, Tuple | ||
|
||
from django.utils.timezone import make_aware | ||
|
||
|
||
def extract_datetime_and_message_from_log_entry( | ||
log_entry: str, | ||
) -> Tuple[Optional[datetime], str]: | ||
""" | ||
Extract the timestamp and message parts from a log entry. | ||
Supported timestamp patterns: | ||
- "%Y-%m-%d %H:%M:%S,%f" | ||
- "%Y-%m-%d %H:%M:%S.%f" | ||
- "%Y-%m-%d %H:%M:%S %f" | ||
- "** %Y-%m-%d %H:%M:%S.%f" | ||
Parameters: | ||
log_entry (str): The log entry string. | ||
Returns: | ||
Tuple[Optional[datetime], str]: A tuple containing the extracted | ||
timestamp as a datetime object (or None if invalid) and the | ||
message as a string. | ||
""" | ||
timestamp_patterns = [ | ||
r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:[,\. ]\d{1,6}) ", | ||
r"^\*\* \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6} ", | ||
] | ||
datetime_formats = [ | ||
"%Y-%m-%d %H:%M:%S,%f", | ||
"%Y-%m-%d %H:%M:%S.%f", | ||
"%Y-%m-%d %H:%M:%S %f", | ||
] | ||
|
||
for pattern in timestamp_patterns: | ||
match = re.match(pattern, log_entry) | ||
if match: | ||
# Extract the timestamp string | ||
timestamp_str = ( | ||
match.group(0).strip("* ").strip() | ||
) # Remove "**" if present | ||
message = log_entry[ | ||
match.end() : | ||
].strip() # Extract the remaining message | ||
if message.startswith("- "): | ||
message = message[2:] # Remove ' - ' characters | ||
|
||
# Convert the timestamp string into a datetime object | ||
for fmt in datetime_formats: | ||
try: | ||
timestamp_obj = datetime.strptime(timestamp_str, fmt) | ||
return make_aware(timestamp_obj), message | ||
except ValueError: | ||
continue | ||
|
||
return None, log_entry |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# Copyright 2025 Red Hat, Inc. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from datetime import datetime | ||
|
||
import pytest | ||
from django.utils.timezone import make_aware | ||
|
||
from aap_eda.core.utils.rulebook_process_logs import ( | ||
extract_datetime_and_message_from_log_entry, | ||
) | ||
|
||
|
||
@pytest.mark.parametrize( | ||
("log_entry", "expected_dt", "expected_msg"), | ||
[ | ||
( | ||
"2025-01-17 18:39:49,191 Starting Container", | ||
make_aware(datetime(2025, 1, 17, 18, 39, 49, 191000)), | ||
"Starting Container", | ||
), | ||
( | ||
"2025-01-17 18:39:55,215 - ansible_rulebook.action.run_job_template", # noqa: E501 | ||
make_aware(datetime(2025, 1, 17, 18, 39, 55, 215000)), | ||
"ansible_rulebook.action.run_job_template", | ||
), | ||
( | ||
"** 2025-01-17 18:39:55.222773 [debug] ****", | ||
make_aware(datetime(2025, 1, 17, 18, 39, 55, 222773)), | ||
"[debug] ****", | ||
), | ||
( | ||
"2025-01-17 18:43:38 638 [main] DEBUG org.drools.ansible", | ||
make_aware(datetime(2025, 1, 17, 18, 43, 38, 638000)), | ||
"[main] DEBUG org.drools.ansible", | ||
), | ||
( | ||
"Ruleset: Long Running Range", | ||
None, | ||
"Ruleset: Long Running Range", | ||
), | ||
], | ||
) | ||
@pytest.mark.django_db | ||
def test_extract_datetimes( | ||
log_entry: str, | ||
expected_dt: str, | ||
expected_msg: str, | ||
): | ||
dt, message = extract_datetime_and_message_from_log_entry(log_entry) | ||
|
||
assert dt == expected_dt | ||
assert message == expected_msg |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.