Skip to content

my python cronjob stopped working after last update #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Pok4 opened this issue Nov 3, 2024 · 0 comments
Closed

my python cronjob stopped working after last update #23

Pok4 opened this issue Nov 3, 2024 · 0 comments

Comments

@Pok4
Copy link

Pok4 commented Nov 3, 2024

Hello,
today i update the library on ubuntu 22 to the latest version 3.1.0. My python is 3.10 and my python cron has stopped working.
opengsq source --host 45.144.155.171 --port 27015 --function get_info - this works on command line, but my cron has totally stopped and not print proper info anymore. Servers not querying properly, all is offline.
Here is the script:

import mysql.connector
import asyncio
from opengsq.protocols import Source
from opengsq.protocols.minecraft import Minecraft
from opengsq.protocols.samp import Samp
from opengsq.protocols.fivem import FiveM
from time import time,sleep

last_update = int(time())
statistic_hour = 3600; #on every 1 hour we will add maps/players or other info in db
delete_old_stats_than = 2764800 #in seconds, after how much seconds we delete the old stats, 345600 seconds = 4 days,8days = 691200,32days = 2764800
delete_old_map_stats_than = 1296000 #delete maps stats older than 15 days
delete_offline_than = 7  #vip will be active for 7 days by default
delete_offline_than_seconds = delete_offline_than * 24 * 60 * 60 #dont touch it

# Replace these with your actual database credentials
db_config = {
    'host': 'localhost',
    'user': 'argos',
    'password': 'pass',
    'database': 'argos',
    'charset': 'utf8mb4',
    'autocommit': False,  # Set autocommit to False for explicit transaction control 
}

# Pagination parameters
start_from = 0
rows_per_page = 10
sleep_after_rows = 1
sleep_duration = 5

#MAIN SCRIPT CONTINUE
async def querygame(ip_real, port_real, game, hostname_untouch):
    try:
        if game.strip() in ("csgo", "source", "cs2", "halflife2", "cs16", "cscz", "halflife"):
            sourceg = Source(host=ip_real.strip(), port=port_real.strip())
            info1 = await sourceg.get_info()

            return {
                'hostname': info1['Name'] if info1 else hostname_untouch,
                'players': info1['Players'] if info1 else 0,
                'maxplayers': info1['MaxPlayers'] if info1 else 0,
                'server_map': info1['Map'] if info1 else 'unknown',
                'bots': info1['Bots'] if info1 else 0,
                'status': 'online' if info1 else 'offline'
            }

        if game.strip() == "minecraft":
            mc = Minecraft(host=ip_real.strip(), port=port_real.strip())
            info2 = await mc.get_status_pre17()

            return {
                'hostname': info2["motd"] if info2 else hostname_untouch,
                'players': info2['numplayers'] if info2 else 0,
                'maxplayers': info2['maxplayers'] if info2 else 0,
                'server_map': 'minecraft',
                'bots': 0,
                'status': 'online' if info2 else 'offline'
            }
        if game.strip() == "samp":
            sampg = Samp(host=ip_real.strip(), port=port_real.strip())
            info3 = await sampg.get_status()

            return {
                'hostname': info3['servername'] if info3 else hostname_untouch,
                'players': info3['numplayers'] if info3 else 0,
                'maxplayers': info3['maxplayers'] if info3 else 0,
                'server_map': info3['gametype'] if info3 else 'unknown',
                'bots': 0,
                'status': 'online' if info3 else 'offline'
            }
        if game.strip() == "fivem":
            fivemm = FiveM(host=ip_real.strip(), port=port_real)
            info4 = await fivemm.get_info()
            return {
                'hostname': info4['hostname'] if info4 else hostname_untouch,
                'players': info4['players'] if info4 else 0,
                'maxplayers': info4['maxplayers'] if info4 else 0,
                'server_map': info4['mapname'] if info4 else 'unknown',
                'bots': 0,
                'status': 'online' if info4 else 'offline'
            }
       
    except Exception as e:
        # Handle any exceptions, e.g., connection errors
        return {
            'hostname': hostname_untouch,
            'players': 0,
            'maxplayers': 0,
            'server_map': 'unknown',
            'status': 'offline',
            'bots': 0
        }

# Establish a connection to the MySQL server
def process_servers(db_config, start_from, rows_per_page, sleep_after_rows, sleep_duration):
    try:
        connection = mysql.connector.connect(**db_config)
        print("Connected to MySQL database")

        # Create a cursor object to interact with the database
        cursor = connection.cursor(buffered=True)
        cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED")

        query = "SELECT * FROM argos_gmon_servers WHERE ban=0 ORDER BY id DESC LIMIT %s, %s FOR UPDATE"
        cursor.execute(query, (start_from, rows_per_page))

        # Fetch all the rows
        rows = cursor.fetchall()

        if not rows:
            print("No results found on page. Exiting.")
            cursor.close()
            connection.close()

        # Display the results
        if rows:
            for row in rows:
                server_id, ip_real, port_real, query_port, game, hostname_untouch = row[0], row[2], row[3], row[4], row[16], row[5]

                try:
                    result = asyncio.run(querygame(ip_real, port_real, game, hostname_untouch))
                    players = result['players']
                    maxplayers = result['maxplayers']
                    hostname = result['hostname']
                    servermap = result['server_map']
                    bots = result['bots']
                    status = result['status']

                    if status == "online":
                        # Update with actual info
                        update_query = "UPDATE argos_gmon_servers SET hostname=%s, players=%s, maxplayers=%s, bots=%s, status=%s, map=%s, last_update=%s WHERE id=%s"
                        cursor.execute(update_query, (hostname, players, maxplayers, bots, status, servermap, last_update, server_id))

                        # delete from last offline
                        delete_query = "DELETE FROM argos_gmon_last_offline WHERE server_id = %s"
                        cursor.execute(delete_query, (server_id,))

                        # add hostname hrono
                        check_query = ("SELECT hostname FROM argos_gmon_hostname_hrono WHERE hostname = %s AND server_id = %s")
                        cursor.execute(check_query, (hostname, server_id))
                        check_query = cursor.fetchall()
                        if cursor.rowcount < 1:
                            insert_query3 = ("INSERT INTO argos_gmon_hostname_hrono (hostname, server_id, date) VALUES (%s, %s, %s)")
                            cursor.execute(insert_query3, (hostname, server_id, last_update))

                        # player stats
                        select_query_p = "SELECT server_id FROM argos_gmon_player_stats WHERE (date + %s > UNIX_TIMESTAMP() OR date IS NULL) AND server_id = %s"
                        cursor.execute(select_query_p, (statistic_hour, server_id))
                        check_result_p = cursor.fetchall()

                        if not check_result_p:
                            insert_query_p = "INSERT INTO argos_gmon_player_stats (players, date, server_id) VALUES (%s, %s, %s)"
                            cursor.execute(insert_query_p, (players, last_update, server_id))

                        # Add Map Stats
                        select_query = "SELECT server_id FROM argos_gmon_map_stats WHERE (date + %s > UNIX_TIMESTAMP() OR date IS NULL) AND server_id=%s"
                        cursor.execute(select_query, (statistic_hour, server_id))
                        check_result = cursor.fetchall()

                        # check if there is no result for maps and insert it
                        if not check_result:
                            insert_query = "INSERT INTO argos_gmon_map_stats (map, date, server_id) VALUES (%s,%s,%s)"
                            cursor.execute(insert_query, (servermap, last_update, server_id))

                    else:  # offline
                        check_query2 = ("SELECT id FROM argos_gmon_last_offline WHERE server_id = %s")
                        cursor.execute(check_query2, (server_id,))
                        check_query2 = cursor.fetchall()
                        if cursor.rowcount < 1:
                            insert_query2 = ("INSERT INTO argos_gmon_last_offline (server_id, last_time_offline) VALUES (%s, %s)")
                            cursor.execute(insert_query2, (server_id, last_update))

                    # delete old stats / maps and players stats
                    delete_map_stats_query = "DELETE FROM argos_gmon_map_stats WHERE date + %s < UNIX_TIMESTAMP() AND server_id = %s"
                    cursor.execute(delete_map_stats_query, (delete_old_map_stats_than, server_id))

                    delete_player_stats_query = "DELETE FROM argos_gmon_player_stats WHERE date + %s < UNIX_TIMESTAMP() AND server_id = %s"
                    cursor.execute(delete_player_stats_query, (delete_old_stats_than, server_id))

                    # clear vip/boost packages if they are expired
                    update_query_1 = "UPDATE argos_gmon_servers SET vip_status=0, vip_status_expire=0 WHERE vip_status_expire < UNIX_TIMESTAMP() AND vip_status=1"
                    cursor.execute(update_query_1)

                    update_query_2 = "UPDATE argos_gmon_servers SET vip_status=0, vip_status_expire=0 WHERE vip_status_expire < UNIX_TIMESTAMP() AND vip_status=2"
                    cursor.execute(update_query_2)

                    # Delete offline servers more than X days
                    select_query = "SELECT server_id FROM argos_gmon_last_offline WHERE server_id=%s AND last_time_offline + %s < UNIX_TIMESTAMP()"
                    cursor.execute(select_query, (server_id, delete_offline_than_seconds))

                    # Fetch all results
                    rows = cursor.fetchall()

                    # Check if rows are found
                    if rows:
                        # Get the first server_id
                        srv_id = rows[0][0]

                        # Prepare the DELETE queries
                        delete_query_servers = "DELETE FROM argos_gmon_servers WHERE id=%s"
                        delete_query_last_offline = "DELETE FROM argos_gmon_last_offline WHERE server_id=%s"

                        # Execute the DELETE queries
                        cursor.execute(delete_query_servers, (srv_id,))
                        cursor.execute(delete_query_last_offline, (srv_id,))

                    # Commit the changes
                    connection.commit()

                    print("server id:", server_id, players, maxplayers, hostname, servermap, bots, status, ip_real, port_real)

                except Exception as e:
                    print(e)
            start_from += rows_per_page

            if rows_per_page > sleep_after_rows and (server_id) % sleep_after_rows == 0:
                print(f"Sleeping for {sleep_duration} seconds...")
                sleep(sleep_duration)
                
                #call function again to make a loop
                process_servers(db_config, start_from, rows_per_page, sleep_after_rows, sleep_duration)
        else:
            print("No results found. Check your conditions.")

    except mysql.connector.Error as e:
        print(f"Error: {e}")

    finally:
        # Close the cursor and connection in the finally block
        if 'cursor' in locals() and cursor:
            cursor.close()
        if 'connection' in locals() and connection.is_connected():
            connection.close()
            print("MySQL connection closed")

process_servers(db_config, start_from, rows_per_page, sleep_after_rows, sleep_duration)

i dont know, but with the previous version i dont have problems...
Im using this python cron to update game servers on my game CMS...
If you know what is happen, please, tell me.

@Pok4 Pok4 closed this as completed Jun 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant