Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions modules/weko-logging/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@
include_package_data=True,
platforms="any",
entry_points={
"flask.commands": [
"logging = weko_logging.cli:logging",
],
"invenio_base.apps": [
"weko_logging_fs = weko_logging.fs:WekoLoggingFS",
"weko_logging_user_activity = weko_logging.audit:WekoLoggingUserActivity",
Expand Down
51 changes: 51 additions & 0 deletions modules/weko-logging/weko_logging/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

import click
from datetime import datetime
from flask.cli import with_appcontext
from invenio_db import db

@click.group()
def logging():
"""Logging CLI group."""
pass

@logging.group()
def partition():
"""Partition management commands."""
pass

@partition.command('create')
@click.argument('year', nargs=1,type=int)
@click.argument('month', default=0,type=int)
@with_appcontext
def _partition_create(year, month):
"""Create partition table for user activity logs.

YEAR: Year of the partition table.
MONTH: Month of the partition table. If 0, create for all months in the year.
"""
from weko_logging.models import make_user_activity_logs_partition_table,\
get_user_activity_logs_partition_tables

(sm, em) = (1, 12) if month==0 else (month, month)

try:
d = datetime(year, sm, 1)
except Exception as e:
click.secho(e, fg='red')
return

try:
tables = get_user_activity_logs_partition_tables()

for m in range(sm, em+1):
tablename = make_user_activity_logs_partition_table(year, m)
if tablename in tables:
click.secho('Table {} is already exist.'.format(tablename), fg='yellow')
else:
click.secho('Creating partitioning table {}.'.format(tablename), fg='green')
db.metadata.tables[tablename].create(bind=db.engine, checkfirst=True)
db.session.commit()
except Exception as e:
db.session.rollback()
click.secho(str(e), fg='red')
100 changes: 80 additions & 20 deletions modules/weko-logging/weko_logging/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@

from datetime import datetime, timezone

from sqlalchemy import Sequence
from dateutil.relativedelta import relativedelta
from sqlalchemy import Sequence, event
from sqlalchemy.dialects import mysql, postgresql
from sqlalchemy_utils.types import JSONType
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.sql.ddl import DDL

from invenio_accounts.models import User
from invenio_communities.models import Community
from invenio_db import db

group_id_seq = Sequence('user_activity_log_group_id_seq', metadata=db.metadata)

class UserActivityLog(db.Model):
class _UserActivityLogBase(db.Model):
"""User activity log model."""

__tablename__ = 'user_activity_logs'
Expand All @@ -35,29 +38,34 @@ class UserActivityLog(db.Model):
db.DateTime().with_variant(mysql.DATETIME(fsp=6), 'mysql'),
nullable=False,
default=lambda: datetime.now(timezone.utc),
primary_key=True
)
"""Date and time of the log entry."""

user_id = db.Column(
db.Integer(),
db.ForeignKey(
User.id,
name='fk_user_activity_active_user_id',
ondelete='SET NULL'
),
nullable=True
)
@declared_attr
def user_id(cls):
return db.Column(
db.Integer(),
db.ForeignKey(
User.id,
name='fk_user_activity_active_user_id',
ondelete='SET NULL'
),
nullable=True
)
"""User ID of the user who performed the action."""

community_id = db.Column(
db.String(100),
db.ForeignKey(
Community.id,
name='fk_user_activity_community_id',
ondelete='SET NULL'
),
nullable=True
)
@declared_attr
def community_id(cls):
return db.Column(
db.String(100),
db.ForeignKey(
Community.id,
name='fk_user_activity_community_id',
ondelete='SET NULL'
),
nullable=True
)
"""Community ID of the community where the action was performed."""

log_group_id = db.Column(
Expand Down Expand Up @@ -117,3 +125,55 @@ def get_log_group_sequence(cls, session):
session = db.session
next_id = session.execute(group_id_seq)
return next_id

class UserActivityLog(db.Model,_UserActivityLogBase):
"""User activity log model."""

__tablename__ = 'user_activity_logs'
__table_args__ = (
db.UniqueConstraint('date', name='uq_date'),
{ "postgresql_partition_by": 'RANGE (date)' }
)

def get_user_activity_logs_partition_tables():
"""Get the partition table for the user_activity_logs table

Returns:
list: List of partition table names.
"""

query = "select tablename from pg_tables where tablename like 'user_activity_logs_partition_%'"
tables = db.session.execute(query).fetchall()

return [a[0] for a in tables]

def make_user_activity_logs_partition_table(year, month):
"""Create a new partition table for user_activity_logs for a specific year and month.

Args:
year (int): The year for the partition.
month (int): The month for the partition.
Returns:
str: The name of the created partition table.
"""
start_date = datetime(year, month, 1, 0, 0, 0)
end_date = start_date + relativedelta(months=1)
suffix = '_' + start_date.strftime('%Y%m')
tablename = UserActivityLog.__tablename__ + suffix

NewPartitionTable = type('UserActivityLogPartition' + suffix,
(db.Model,_UserActivityLogBase),
{"__tablename__": tablename})
NewPartitionTable.__table__.add_is_dependent_on(UserActivityLog.__table__)

alter_table = \
"ALTER TABLE " + UserActivityLog.__tablename__ + " ATTACH PARTITION " + \
tablename + \
" FOR VALUES FROM ('{}') TO ('{}');".format(start_date.strftime('%Y-%m-%d'),
end_date.strftime('%Y-%m-%d'))

event.listen(NewPartitionTable.__table__,
"after_create",
DDL(alter_table))

return tablename
Loading
Loading