Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.1 kB
1
Indexable
Never
def purge_logs():
    vms = get_VMList()

    for vm in vms:
        syslog_file = get_syslog_file_location(vm)
        retention_period = get_retention_period(vm)

    vm_details = get_vm_details()
    for vms in vm_details:
        vm_id = vms['vm_id']
        vm_ip = vms['vm_ip']
        bookmark_index = get_bookmark_index(vm_ip)
        print(bookmark_index)

        print("VM:", vm)
        print("Syslog File Location:", syslog_file)
        print("Retention Period:", retention_period)
        print("Bookmark Index:", bookmark_index)
        print("Purging Logs...")

        with open(syslog_file, "r") as file:
            # Find the line at the bookmark index
            bookmark_line = None
            try:
                bookmark_line = next(itertools.islice(file, bookmark_index-1, bookmark_index))
            except StopIteration:
                print("Bookmark line not found.")
                continue

            bookmark_timestamp = get_timestamp_from_line(bookmark_line)

        # Calculate the purging date (7 days before the bookmark timestamp)
        bookmark_date = datetime.datetime.strptime(bookmark_timestamp, "%Y-%m-%dT%H:%M:%S+00:00")
        purging_date = bookmark_date - datetime.timedelta(days=7)

        # Perform the log purging
        lines_to_keep = []
        with open(syslog_file, "r") as file:
            # Append lines newer than the purging date to the list of lines to keep
            for line in file:
                timestamp = get_timestamp_from_line(line)
                line_date = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S+00:00")
                if line_date >= purging_date:
                    lines_to_keep.append(line)

        # Write the lines to keep back to the syslog file
        with open(syslog_file, "w") as file:
            file.writelines(lines_to_keep)

        print("Purging Completed")
        print("Printing First Two Lines:")

        with open(syslog_file) as file:
            print(file.readline())
            print(file.readline())

        print()

purge_logs()