Skip to content

Commit

Permalink
Merge pull request #549 from moloch--/Remove_snapshots
Browse files Browse the repository at this point in the history
Remove snapshots #531
  • Loading branch information
eljeffeg authored Mar 12, 2023
2 parents 0291fe1 + 6a8a9a5 commit 052889a
Show file tree
Hide file tree
Showing 30 changed files with 583 additions and 737 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@v2
with:
config-file: ./.github/codeql/codeql-config.yml
# Override language selection by uncommenting this and choosing your languages
Expand All @@ -34,7 +34,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
uses: github/codeql-action/autobuild@v2

# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
Expand All @@ -48,4 +48,4 @@ jobs:
# make release

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@v2
57 changes: 57 additions & 0 deletions alembic/versions/fe5e615ae090_add_game_history_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""add game history table
Revision ID: fe5e615ae090
Revises: de5d615ae090
Create Date: 2023-02-28 19:33:02.808038
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.sql.expression import func

conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

# revision identifiers, used by Alembic.
revision = "fe5e615ae090"
down_revision = "de5d615ae090"
branch_labels = None
depends_on = None


def _table_has_column(table, column):
has_column = False
for col in inspector.get_columns(table):
if column not in col["name"]:
continue
has_column = True
return has_column


def _has_table(table_name):
tables = inspector.get_table_names()
return table_name in tables


def upgrade():
if not _has_table("game_history"):
op.create_table(
"game_history",
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("created", sa.DateTime, nullable=True),
sa.Column(
"team_id",
sa.Integer,
sa.ForeignKey("team.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("_type", sa.VARCHAR(length=20), nullable=False),
sa.Column("_value", sa.Integer, default=0, nullable=False),
)


def downgrade():
if _has_table("game_history"):
op.drop_table("game_history")
119 changes: 119 additions & 0 deletions alembic/versions/ffe623ae412_delete_snapshot_tables.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""delete snapshot table
Revision ID: ffe623ae412
Revises: fe5e615ae090
Create Date: 2023-03-11 19:33:02.808038
"""
import sqlalchemy as sa
from datetime import datetime
from alembic import op
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.sql.expression import func

conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

# revision identifiers, used by Alembic.
revision = "ffe623ae412"
down_revision = "fe5e615ae090"
branch_labels = None
depends_on = None

history = {}
flag_count = {}

def _table_has_column(table, column):
has_column = False
for col in inspector.get_columns(table):
if column not in col["name"]:
continue
has_column = True
return has_column


def _has_table(table_name):
tables = inspector.get_table_names()
return table_name in tables

def add_history(created, team_id, reason, value):
conn = op.get_bind()
conn.execute(f"INSERT INTO game_history (created, team_id, _type, _value) VALUES ('{created}', {team_id}, '{reason}', {value});")

def check_flag(item):
team_id = item[0]
created = datetime.now()
if str(team_id) in flag_count:
flag_count[str(team_id)] += 1
else:
add_history(created, team_id, "flag_count", 0)
flag_count[str(team_id)] = 1
add_history(created, team_id, "flag_count", flag_count[str(team_id)])

def check_history(item):
created = item[1]
team_id = item[2]
money = item[3]
bots = item[4]
if str(team_id) in history:
team = history[str(team_id)]
if bots != team["bots"]:
history[str(team_id)]["bots"] = bots
add_history(created, team_id, "bot_count", bots)
elif money != team["money"]:
history[str(team_id)]["money"] = money
add_history(created, team_id, "score", money)
return
else:
add_history(created, team_id, "bot_count", 0)
add_history(created, team_id, "start", 0)
if bots > 0:
add_history(created, team_id, "bot_count", 0)
if money > 0:
add_history(created, team_id, "score", money)
history[str(team_id)] = {"money": money, "bots": bots}

def upgrade():
try:
conn = op.get_bind()
res = conn.execute("SELECT * FROM snapshot_team;")
results = res.fetchall()
i = 0
for item in results:
check_history(item)
i += 1
if i > 0:
conn.execute("COMMIT;")

except Exception as e:
print("Failed to import prior snapshot data into game history: %s" % str(e))
print("Continuing...")
try:
res = conn.execute("SELECT * FROM team_to_flag;")
results = res.fetchall()
i = 0
for item in results:
check_flag(item)
i += 1
if i > 0:
conn.execute("COMMIT;")
except Exception as e:
print("Failed to import prior flag count into game history: %s" % str(e))
print("Continuing...")

if _has_table("snapshot_to_snapshot_team"):
op.drop_table("snapshot_to_snapshot_team")
if _has_table("snapshot_team_to_game_level"):
op.drop_table("snapshot_team_to_game_level")
if _has_table("snapshot_team_to_flag"):
op.drop_table("snapshot_team_to_flag")
if _has_table("snapshot_team"):
op.drop_table("snapshot_team")
if _has_table("snapshot"):
op.drop_table("snapshot")


def downgrade():
print("No downgrade for this")
pass
40 changes: 6 additions & 34 deletions handlers/AdminHandlers/AdminGameHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@
from models.Team import Team
from models.Theme import Theme
from models.Penalty import Penalty
from models.Snapshot import Snapshot
from models.SnapshotTeam import SnapshotTeam
from models.SourceCode import SourceCode
from models.Corporation import Corporation
from models.Category import Category
Expand All @@ -52,9 +50,8 @@
from libs.StringCoding import encode, decode
from libs.ValidationError import ValidationError
from libs.ConfigHelpers import save_config
from libs.GameHistory import GameHistory
from libs.ConsoleColors import *
from libs.Scoreboard import score_bots
from libs.Scoreboard import score_bots, Scoreboard
from handlers.BaseHandlers import BaseHandler
from string import printable
from setup.xmlsetup import import_xml
Expand Down Expand Up @@ -644,14 +641,6 @@ def refresh_app_config(self):
logging.info("Starting botnet callback function")
self.application.settings["score_bots_callback"].start()

logging.info("Restarting history callback function")
game_history = GameHistory.instance()
self.application.settings["history_callback"].stop()
self.application.history_callback = PeriodicCallback(
game_history.take_snapshot, options.history_snapshot_interval
)
self.application.settings["history_callback"].start()


class AdminResetHandler(BaseHandler):
@restrict_ip_address
Expand All @@ -676,10 +665,11 @@ def post(self, *args, **kwargs):
user.money = 0
teams = Team.all()
for team in teams:
team.game_history = []
if options.banking:
team.money = options.starting_team_money
team.set_score("start", options.starting_team_money)
else:
team.money = 0
team.set_score("start", 0)
team.flags = []
team.hints = []
team.boxes = []
Expand All @@ -706,16 +696,6 @@ def post(self, *args, **kwargs):
for swat in swats:
self.dbsession.delete(swat)
self.dbsession.commit()
snapshot = Snapshot.all()
for snap in snapshot:
self.dbsession.delete(snap)
self.dbsession.commit()
snapshot_team = SnapshotTeam.all()
for snap in snapshot_team:
self.dbsession.delete(snap)
self.dbsession.commit()
game_history = GameHistory.instance()
game_history.take_snapshot() # Take starting snapshot
flags = Flag.all()
for flag in flags:
# flag.value = flag.value allows a fallback to when original_value was used
Expand All @@ -725,6 +705,7 @@ def post(self, *args, **kwargs):
self.dbsession.add(flag)
self.dbsession.commit()
self.dbsession.flush()
Scoreboard.update_gamestate(self)
self.event_manager.push_score_update()
self.flush_memcached()
success = "Successfully Reset Game"
Expand Down Expand Up @@ -769,22 +750,12 @@ def post(self, *args, **kwargs):
for swat in swats:
self.dbsession.delete(swat)
self.dbsession.commit()
snapshot = Snapshot.all()
for snap in snapshot:
self.dbsession.delete(snap)
self.dbsession.commit()
snapshot_team = SnapshotTeam.all()
for snap in snapshot_team:
self.dbsession.delete(snap)
self.dbsession.commit()
for user in users:
self.dbsession.delete(user)
self.dbsession.commit()
for team in teams:
self.dbsession.delete(team)
self.dbsession.commit()
game_history = GameHistory.instance()
game_history.take_snapshot() # Take starting snapshot
flags = Flag.all()
for flag in flags:
# flag.value = flag.value allows a fallback to when original_value was used
Expand All @@ -794,6 +765,7 @@ def post(self, *args, **kwargs):
self.dbsession.add(flag)
self.dbsession.commit()
self.dbsession.flush()
Scoreboard.update_gamestate(self)
self.event_manager.push_score_update()
self.flush_memcached()
if options.teams:
Expand Down
12 changes: 7 additions & 5 deletions handlers/AdminHandlers/AdminGameObjectHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ def create_team(self):
team.name = self.get_argument("team_name", "")
team.motto = self.get_argument("motto", "")
if not self.config.banking:
team.money = 0
team.set_score("start", 0)
else:
team.set_score("start", options.starting_team_money)
level_0 = GameLevel.by_number(0)
if not level_0:
level_0 = GameLevel.all()[0]
Expand Down Expand Up @@ -429,7 +431,7 @@ def post(self, *args, **kwargs):
if penalty:
value = penalty.cost()
if value > 0:
team.money += value
team.set_score("penalty", value + team.money)
if user:
user.money += value
self.dbsession.add(user)
Expand All @@ -451,15 +453,15 @@ def post(self, *args, **kwargs):
for item in Flag.team_captures(flag.id):
tm = Team.by_id(item[0])
deduction = flag.dynamic_value(tm) - flag_value
tm.money = int(tm.money - deduction)
tm.set_score("decay", int(tm.money - deduction))
self.dbsession.add(tm)
self.event_manager.flag_decayed(tm, flag)
team.money += flag_value
team.set_score("flag", flag_value + team.money)
if user:
user.money += flag_value
user.flags.append(flag)
self.dbsession.add(user)
team.flags.append(flag)
team.add_flag(flag)
self.dbsession.add(team)
self.dbsession.commit()
BoxHandler.success_capture(self, user, flag, flag_value)
Expand Down
10 changes: 5 additions & 5 deletions handlers/AdminHandlers/AdminUserHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ def post(self, *args, **kwargs):
if group == "all":
teams = Team.all()
for team in teams:
team.money += value
team.set_score("admin", value + team.money)
self.dbsession.add(team)
else:
team = Team.by_uuid(group)
team.money += value
team.set_score("admin", value + team.money)
self.dbsession.add(team)
self.dbsession.commit()
self.event_manager.admin_score_update(team, message, value)
Expand Down Expand Up @@ -96,7 +96,7 @@ def edit_team(self):
raise ValidationError("Team does not exist")
team.name = self.get_argument("name", team.name)
team.motto = self.get_argument("motto", team.motto)
team.money = self.get_argument("money", team.money)
team.set_score("admin", self.get_argument("money", team.money))
team.notes = self.get_argument("notes", "")
if hasattr(self.request, "files") and "avatarfile" in self.request.files:
team.avatar = self.request.files["avatarfile"][0]["body"]
Expand Down Expand Up @@ -217,9 +217,9 @@ def create_team(self, user):
team.motto = ""
team._avatar = identicon(team.name, 6)
if self.config.banking:
team.money = self.config.starting_team_money
team.set_score("start", self.config.starting_team_money)
else:
team.money = 0
team.set_score("start", 0)
level_0 = GameLevel.by_number(0)
if not level_0:
level_0 = GameLevel.all()[0]
Expand Down
3 changes: 0 additions & 3 deletions handlers/BaseHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,6 @@ def start_game(self):
if not self.application.settings["game_started"]:
logging.info("The game is about to begin, good hunting!")
self.application.settings["game_started"] = True
self.application.settings["history_callback"].start()
if self.config.use_bots:
self.application.settings["score_bots_callback"].start()
# Fire game start webhook
Expand All @@ -266,8 +265,6 @@ def stop_game(self):
if self.application.settings["game_started"]:
logging.info("The game is stopping ...")
self.application.settings["game_started"] = False
if self.application.settings["history_callback"]._running:
self.application.settings["history_callback"].stop()
if self.application.settings["score_bots_callback"]._running:
self.application.settings["score_bots_callback"].stop()
# Fire game stop webhook
Expand Down
Loading

0 comments on commit 052889a

Please sign in to comment.