Exemple #1
0
def init():
    # Config.show_keep_alive_after_idle = 1
    Config = Factory.get('Config')
    Lang = Factory.get('Translation')
    try:
        Config.printSettings()
        Db.init()

        if not ServerControl.is_server_running():
            out(Lang.get('server_not_running'))
            ServerControl.start_server()

        custom_import(Config.events_config,'events') #Load events

        Rcon.init(Config.rcon_host, Config.rcon_port, Config.query_port, Config.rcon_password, Config.rcon_socket_timeout)

        InputHandler.init() #Activate listening for terminal input

        #custom_import(Config.events_config,'input') #Load terminal input configuration
        custom_import(Config.tasks_config,'tasks') #Load tasks

        # Prevent threads from dying due to early main completed execution.
        while True:
            if Storage.terminate_application is True:
                exit()
            time.sleep(1)  # Important part of not being a CPU hog.

    except KeyboardInterrupt:
        Storage.terminate_application = True
Exemple #2
0
def init():
    # Config.show_keep_alive_after_idle = 1
    Config = Factory.get('Config')
    Lang = Factory.get('Translation')
    try:
        Config.printSettings()
        Db.init()

        if not ServerControl.is_server_running():
            out(Lang.get('server_not_running'))
            ServerControl.start_server()

        custom_import(Config.events_config, 'events')  #Load events

        Rcon.init(Config.rcon_host, Config.rcon_port, Config.query_port,
                  Config.rcon_password, Config.rcon_socket_timeout)

        InputHandler.init()  #Activate listening for terminal input

        #custom_import(Config.events_config,'input') #Load terminal input configuration
        custom_import(Config.tasks_config, 'tasks')  #Load tasks

        # Prevent threads from dying due to early main completed execution.
        while True:
            if Storage.terminate_application is True:
                exit()
            time.sleep(1)  # Important part of not being a CPU hog.

    except KeyboardInterrupt:
        Storage.terminate_application = True
Exemple #3
0
    def get_version(cls):
        data = Rcon.query_server()
        if data:
            if Factory.has('GUI_CONTROL'):
                Factory.get('GUI_CONTROL').set_server_version(data['game_version'])

            out('Server is running game version: ', data['game_version'])
        else:
            out('Unable to retrieve server game version')
Exemple #4
0
def exceptionHandler(exception_type, exception, traceback, debug_hook=sys.excepthook):
    #sys.tracebacklimit = 0
    Config = Factory.get('Config')
    if Config.traceback_hide_output:
        debug_hook(exception_type, exception, traceback)
    else:
        print("{}: {}".format(exception_type.__name__, exception))
Exemple #5
0
 def get_active_threads(cls):
     GUI = Factory.get('GUI')
     max_threads = len(ThreadHandler.activethreads)
     active_threads = 0
     for key,timestamp in ThreadHandler.activethreads.items():
         if timestamp > (time.time()-30):
             active_threads += 1
     GUI.active_threads['text'] = "{} / {}".format(active_threads,max_threads)
Exemple #6
0
def out(*args,**kwargs):
    if Config.display_output is False:
        return
    Storage.last_output_unix_time = time.time()
    
    text = "{} [{}] # ".format(time_str(), len(Storage.players_online_steam_name))

    if Factory.has('GUI'):
        GUI = Factory.get('GUI')
        if GUI:
            print(text,*args,**kwargs,file=GUI)
    else:
        print(text,*args,**kwargs)

    if log_defined():
        log = get_log_file_handle()
        if log:
            print(text,*args,**kwargs,file=log, flush=True)
            
        debug_log = get_log_file_handle(True)
        if log:
            print(text,*args,**kwargs,file=debug_log, flush=True)
Exemple #7
0
 def server_last_response(cls):
     if Factory.has('GUI_CONTROL'):
         Factory.get('GUI_CONTROL').set_last_serverresponse()
Exemple #8
0
 def update_gui_listplayers(cls,player_list):
     if Factory.has('GUI_CONTROL'):
         Factory.get('GUI_CONTROL').update_playerlist()
Exemple #9
0
from ark.storage import Storage
from ark.cli import *
from ark.rcon import Rcon
from ark.server_control import ServerControl
from factory import Factory
from pathlib import Path
import os

Config = Factory.get('Config')
Db = Factory.get('Database')

class EventOther(object):
    @classmethod
    def server_last_response(cls):
        if Factory.has('GUI_CONTROL'):
            Factory.get('GUI_CONTROL').set_last_serverresponse()

    @classmethod
    def keep_alive(cls):
        if Factory.has('GUI_CONTROL'):
            Factory.get('GUI_CONTROL').set_last_keepalive()

    """ Ark Server savegame integrity filesize check

    Occasionally the savegame is corrupted and a new save is started.
    This is easily detected as the backup savegames are much larger in size.
    Compare size and terminate application if the check fails.
    """
    @classmethod
    def check_savegame_integrity(cls):
        path = os.path.join(Config.path_to_server,'ShooterGame','Saved','SavedArks')
Exemple #10
0
from ark.storage import Storage
from ark.cli import *
from ark.database import Db
from ark.rcon import Rcon
from ark.server_control import ServerControl
from factory import Factory
from pathlib import Path
import os

Config = Factory.get('Config')


class EventOther(object):
    """ Ark Server savegame integrity filesize check

    Occasionally the savegame is corrupted and a new save is started.
    This is easily detected as the backup savegames are much larger in size.
    Compare size and terminate application if the check fails.
    """
    @classmethod
    def check_savegame_integrity(cls):
        path = os.path.join(Config.path_to_server, 'ShooterGame', 'Saved',
                            'SavedArks')

        p = Path(path)
        if not p.is_dir():
            out(
                'EVENT ERROR - Save Game Integrity Check: Unable to locate path: ',
                path)
            return
Exemple #11
0
import re
import subprocess
from urllib import request

import ark.rcon
from .cli import *
from ark.steam.source_server_query import ArkSourceQuery
from factory import Factory
Config = Factory.get('Config')

# noinspection PyUnusedLocal
class ServerControl(object):
    """Control for Ark (Steam) Server
    
    Ideally do UDP query to server, get version and compare it with version from Steam web api.
    For now that seems impossible.
    
    So check local buildId in file, update, and check the file again :/
    
    Make sure you run update_server() and new_version() in a thread to avoid blocking script.
    """
    
    app_id = "376030" #String. To avoid type casting. Never have use for it as int.
    _update_available = False

    @classmethod
    def get_config(cls,clearPasswords=True):
        result = {}

        path = "{}Game.ini".format(Config.path_to_config)
        f = open(path,'rb')
Exemple #12
0
import time

from ark.rcon import Rcon
from ark.scheduler import Scheduler
from ark.server_control import ServerControl
from ark.storage import Storage
from factory import Factory

Lang = Factory.get("Translation")


class Task_DailyRestart(Scheduler):
    """Broadcasts warnings start 10 minutes prior to update and restart.
    """

    @staticmethod
    def run():
        Rcon.delayed_restart(60, Lang.get("event_restart"))


class Task_DailyRestartRepopulate(Scheduler):
    """Broadcasts warnings start 10 minutes prior to update and restart.
    """

    @staticmethod
    def run():
        Storage.repopulate_dinos_on_next_restart = True
        Rcon.delayed_restart(60, Lang.get("event_restart_repopulate"))
Exemple #13
0
 def update_playerlist(cls):
     GUI = Factory.get('GUI')
     GUI.last_player_activity['text'] = time_str()
     GUI.player_list.delete(0,END)
     for steam_id, name in Storage.players_online_steam_name.items():
         GUI.player_list.insert(END,"{} [{}]".format(name,steam_id))
Exemple #14
0
import re

from ark.scheduler import Scheduler

from factory import Factory
Db = Factory.get('Database')

class Task_SQL_keep_alive(Scheduler):
    @staticmethod
    def run():
        Db.keep_alive()
Exemple #15
0
libmgr.load()
# print(ppDict(libmgr.libraries))

Factory.create(cas)
cas.parse(argv)

if cas.command in sesmgr.handles:
    sesmgr.process(cas.command, cas.cmdargs)
elif cas.command in libmgr.handles:
    libmgr.process(cas.command, cas.cmdargs)
else:
    if sesmgr.loadSession():
        sesmgr.getLibraryData(libmgr.libraries)

        handler = Factory.get(cas.command)
        parametersThatNeedToBeReadFromConfig, parametersThatWereUpdatedFromCLI \
            = handler.handleCLIArguments(cas.cmdargs)

        if not cas.standalone:
            sesmgr.updateParamsFromCLI(parametersThatWereUpdatedFromCLI)
            sesmgr.getLibraryData(libmgr.libraries)
            # sesmgr.display()
            response = {
                r: sesmgr.getParam(r)
                for r in parametersThatNeedToBeReadFromConfig
            }
            # SessionManager._display(response, 0, '>>')
            handler.updateParamsFromSession(response)
        else:
            print(
Exemple #16
0
 def set_last_keepalive(cls):
     GUI = Factory.get('GUI')
     GUI.last_keepalive['text'] = time_str()
Exemple #17
0
from constants import *
from dataset_reader import DataReader
from factory import Factory
import numpy as np
import time
from shutil import rmtree

if __name__ == '__main__':
    try:
        rmtree(OUTPUT_PATH)
    except:
        pass
    dataset = DataReader(DATASET_PATH)
    dataset_extract = dataset.read()
    samples, labels = np.array(dataset_extract[0]), np.array(
        dataset_extract[1])
    factory = Factory()
    times = [time.time()]
    for classifier_name in CLASSIFIERS:
        classifier = factory.get(classifier_name, samples, labels)
        print(f'start training {classifier_name}')
        classifier.train()
        cur = time.time()
        print((cur - times[-1]))
        times.append(cur)
    print(f'total time = {(times[-1]-times[0])}')
Exemple #18
0
import time

from ark.rcon import Rcon
from ark.scheduler import Scheduler
from ark.server_control import ServerControl
from ark.storage import Storage
from factory import Factory
Lang = Factory.get('Translation')


class Task_DailyRestart(Scheduler):
    """Broadcasts warnings start 10 minutes prior to update and restart.
    """
    @staticmethod
    def run():
        Rcon.delayed_restart(60, Lang.get('event_restart'))


class Task_DailyRestartRepopulate(Scheduler):
    """Broadcasts warnings start 10 minutes prior to update and restart.
    """
    @staticmethod
    def run():
        Storage.repopulate_dinos_on_next_restart = True
        Rcon.delayed_restart(60, Lang.get('event_restart_repopulate'))
Exemple #19
0
 def set_config(cls,file):
     GUI = Factory.get('GUI')
     GUI.config['text'] = file
Exemple #20
0
 def process_input(cls,event):
     GUI = Factory.get('GUI')
     from ark.input_handler import InputHandler
     if InputHandler.handle_input(GUI.command.get()):
         GUI.command.delete(0,END)
Exemple #21
0
 def keep_alive(cls):
     if Factory.has('GUI_CONTROL'):
         Factory.get('GUI_CONTROL').set_last_keepalive()
Exemple #22
0
from ark.storage import Storage
from factory import Factory
from ark.rcon import Rcon
from ark.cli import *
import time
import re

Db = Factory.get('Database')
Config = Factory.get('Config')
Lang = Factory.get('Translation')

class CmdsOther(object):
    @staticmethod
    def list_online(steam_name,player_name,text):
        players = {}
        for steam_id, p_steam_name in Storage.players_online_steam_name.items():
            if steam_id in Storage.players_online_player_name and Storage.players_online_player_name[steam_id]:
                players[steam_id] = Storage.players_online_player_name[steam_id]
            else:
                players[steam_id] = p_steam_name


        player_list = ", ".join(players.values())
        response = Lang.get('chat_players_online').format(len(Storage.players_online_steam_name), player_list)
        Rcon.message_steam_name(steam_name,response)

    @staticmethod
    def last_seen(steam_name,player_name,text):
        cmdlen = len("!lastseen ")
        name = text[cmdlen:]
        player = Db.find_player_wildcard(name)
Exemple #23
0
 def set_last_serverresponse(cls):
     GUI = Factory.get('GUI')
     GUI.last_serverresponse['text'] = time_str()
Exemple #24
0
For easy reading of code all transmittable RCON commands are in class RconCommands
The RCON class is simply just a collection of helper functions and a wrapper for core code.
"""

from ark.rcon_commands import RconCommands
from ark.steam.source_server_query import ArkSourceQuery
from .cli import *
from .thread_handler import ThreadHandler
from ark.storage import Storage
from ark.event_handler import EventHandler
from ark.database import Db
import time
from ark.server_control import ServerControl

from factory import Factory
Config = Factory.get('Config')
Lang = Factory.get('Translation')

class Rcon(RconCommands):

    @classmethod
    def delayed_restart(cls,minutes, message=""):
        """Delayed restart of the server

        Will restart the server after 5,10,30,60 minutes.
        Notifies the server with broadcast on all these intervals and on 60 seconds

        Args:
            minutes: 5,10,30,60 minutes.

        Returns:
Exemple #25
0
import datetime

from .cli import *
from .database import Db
from .input_handler import InputHandler, InputResponses
from .rcon import Rcon
from .server_control import ServerControl
import re
from factory import Factory

Lang = Factory.get('Translation')

# noinspection PyUnusedLocal,PyUnusedLocal
class DefaultInputCommands(object):
    @classmethod
    def init(cls):
        InputHandler.register_command('stats',cls._cmd_stats)
        InputHandler.register_command('exit',cls._cmd_exit)
        InputHandler.register_command('check_version',cls._cmd_check_version)
        InputHandler.register_command('version',cls._cmd_version)
        InputHandler.register_command('saveworld',cls._cmd_saveworld)
        InputHandler.register_command('shutdown',cls._cmd_shutdown)
        InputHandler.register_command('exit',cls._cmd_exit)
        InputHandler.register_command('raw',cls._cmd_raw)
        InputHandler.register_command('online',cls._cmd_online)
        InputHandler.register_command('restart',cls._cmd_restart)
        InputHandler.register_command('repopulate',cls._cmd_repopulate_on_next_restart)
        InputHandler.register_command('server up',cls._cmd_server_running)
        InputHandler.register_command('next restart',cls._cmd_time_until_restart)
        InputHandler.register_command('update',cls._cmd_update)
Exemple #26
0
 def set_server_version(cls,version):
     GUI = Factory.get('GUI')
     GUI.server_version['text'] = version
Exemple #27
0
import time

from sqlalchemy import create_engine, exc, text, func
from sqlalchemy.orm import sessionmaker

from ark.cli import Config
from ark.database.orm_models import Base, WebsiteData, Player, Chat, ChatFilter, Survey, Option, Vote
from ark.database.core import DbCore
from factory import Factory
from ark.cli import *

DbCore = Factory.get("DatabaseCore")


class Db(object):
    """Helper functions for database

    No reason to hate sqlalchemy or spend 30 years learning.
    Write your often-used functions here :)
    """

    @staticmethod
    def keep_alive():
        try:
            resp = DbCore.engine.execute("select 1")
        except exc.SQLAlchemyError as e:
            out("SQL Failure: with keep alive:", e)

    @staticmethod
    def update_last_seen(steam_ids):
        """Update last_seen column on a player
Exemple #28
0
For easy reading of code all transmittable RCON commands are in class RconCommands
The RCON class is simply just a collection of helper functions and a wrapper for core code.
"""

from ark.rcon_commands import RconCommands
from ark.steam.source_server_query import ArkSourceQuery
from .cli import *
from .thread_handler import ThreadHandler
from ark.storage import Storage
from ark.event_handler import EventHandler
from ark.database import Db
import time
from ark.server_control import ServerControl

from factory import Factory
Config = Factory.get('Config')
Lang = Factory.get('Translation')


class Rcon(RconCommands):
    @classmethod
    def delayed_restart(cls, minutes, message=""):
        """Delayed restart of the server

        Will restart the server after 5,10,30,60 minutes.
        Notifies the server with broadcast on all these intervals and on 60 seconds

        Args:
            minutes: 5,10,30,60 minutes.

        Returns: