#!/usr/bin/env python3
#
# @package      hubzero-submit-monitors
# @file         monitorJobInitialize.py
# @copyright    Copyright (c) 2012-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2012-2020 The Regents of the University of California.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of The Regents of the University of California.
#
# ----------------------------------------------------------------------
#  monitorJobInitialize.py
#
#  script which initializes job monitoring statistics files
#
import sys
import os
import sqlite3
import traceback

MONITORROOT  = os.path.join(os.sep,'opt','submit')
DBFILENAME   = "monitorJob.db"
DBFILEPATH   = os.path.join(MONITORROOT,'DB',DBFILENAME)
 
if __name__ == '__main__':

   dbConnection = None
   try:
      dbConnection = sqlite3.connect(DBFILEPATH,isolation_level=None)
      cursor = dbConnection.cursor()
      cursor.executescript("""
                              PRAGMA user_version = 3;
                              CREATE TABLE activeJobs (
                                 aggregator     VARCHAR(32) DEFAULT '?',
                                 localJobId     INT         NOT NULL,
                                 instanceId     INT         NOT NULL,
                                 distributorPid INT         NOT NULL,
                                 hubUserId      INT         DEFAULT NULL,
                                 siteName       VARCHAR(32) DEFAULT '?',
                                 nCores         INT         DEFAULT 1,
                                 runName        VARCHAR(32) NOT NULL,
                                 siteDesignator VARCHAR(32) NOT NULL,
                                 remoteJobId    VARCHAR(32) NOT NULL,
                                 jobStatus      VARCHAR(32) DEFAULT '?',
                                 jobStage       VARCHAR(32) DEFAULT '?',
                                 jobQueue       VARCHAR(32) DEFAULT '?',
                                 destination    VARCHAR(32) DEFAULT '?',
                                 executionHost  VARCHAR(64) DEFAULT '?',
                                 timeRecorded   DOUBLE      DEFAULT '0.'
                              );
                              CREATE UNIQUE INDEX activeJobs_globalJobId       ON activeJobs (siteDesignator,remoteJobId);
                              CREATE        INDEX activeJobs_localJobId        ON activeJobs (localJobId,instanceId);
                              CREATE        INDEX activeJobs_siteDesignator    ON activeJobs (siteDesignator);
                              CREATE        INDEX activeJobs_siteQueue         ON activeJobs (siteDesignator,jobQueue);
                              CREATE        INDEX activeJobs_siteStatus        ON activeJobs (siteDesignator,jobStatus);
                              CREATE        INDEX activeJobs_instanceStatus    ON activeJobs (instanceId,jobStatus);
                              CREATE        INDEX activeJobs_hubUserId         ON activeJobs (hubUserId);
                              CREATE        INDEX activeJobs_userStatus        ON activeJobs (hubUserId,jobStatus);
                              CREATE        INDEX activeJobs_userLocalIdStatus ON activeJobs (hubUserId,localJobId,jobStatus);
                              CREATE        INDEX activeJobs_statusTime        ON activeJobs (jobStatus,timeRecorded);

                              CREATE TABLE activeJobIdentities (
                                 localJobId   INT         NOT NULL,
                                 instanceId   INT         NOT NULL,
                                 hubUserId    INT         NOT NULL,
                                 identityName VARCHAR(32) NOT NULL
                              );
                              CREATE INDEX activeJobIdentities_localJobId   ON activeJobIdentities (localJobId,instanceId);
                              CREATE INDEX activeJobIdentities_identityName ON activeJobIdentities (identityName);
                              CREATE INDEX activeJobIdentities_identityUser ON activeJobIdentities (identityName,hubUserId);

                              CREATE TABLE activeJobSites (
                                 jobSite     VARCHAR(32) UNIQUE PRIMARY KEY,
                                 pid         INT         NOT NULL,
                                 timeUpdated DOUBLE      DEFAULT '0.'
                              );

                              CREATE TABLE userActivityScores (
                                 aggregator    VARCHAR(32) DEFAULT '?',
                                 siteName      VARCHAR(32) DEFAULT '?',
                                 hubUserId     INT         NOT NULL,
                                 activityScore DOUBLE      DEFAULT '0.5',
                                 timeUpdated   DOUBLE      DEFAULT '-1.'
                              );
                              CREATE INDEX userActivityScores_hubUserId  ON userActivityScores (hubUserId);
                              CREATE INDEX userActivityScores_aggregator ON userActivityScores (aggregator,hubUserId);
                              CREATE INDEX userActivityScores_siteUser   ON userActivityScores (siteName,hubUserId);

                              CREATE TABLE fileTailings (
                                 siteDesignator VARCHAR(32)  NOT NULL,
                                 remoteJobId    VARCHAR(32)  NOT NULL,
                                 fileName       VARCHAR(256) NOT NULL,
                                 nLines         INT          DEFAULT 10,
                                 timeUpdated    DOUBLE       DEFAULT '0.',
                                 tailText       BLOB
                              );
                              CREATE UNIQUE INDEX fileTailings_globalTailId ON fileTailings (siteDesignator,remoteJobId,fileName);
                              CREATE        INDEX fileTailings_globalRunId  ON fileTailings (siteDesignator,remoteJobId);

                              CREATE TABLE registeredJobs (
                                 aggregator     VARCHAR(32) DEFAULT '?',
                                 state          INT         NOT NULL,
                                 runName        VARCHAR(32) NOT NULL,
                                 localJobId     INT         NOT NULL,
                                 instanceId     INT         NOT NULL,
                                 distributorPid INT         NOT NULL,
                                 hubUserId      INT         DEFAULT NULL,
                                 siteName       VARCHAR(32) DEFAULT '?',
                                 timeRegistered DOUBLE      DEFAULT '0.'
                              );
                              CREATE INDEX registeredJobs_aggregatorState ON registeredJobs (aggregator,state);
                              CREATE INDEX registeredJobs_siteName        ON registeredJobs (siteName);
                              CREATE INDEX registeredJobs_hubUserId       ON registeredJobs (hubUserId);
                              CREATE INDEX registeredJobs_userSiteName    ON registeredJobs (hubUserId,siteName);
                              CREATE INDEX registeredJobs_localJobId      ON registeredJobs (localJobId,instanceId);

                              CREATE TABLE userSubmitterClasses (
                                 hubUserId      INT UNIQUE PRIMARY KEY,
                                 submitterClass INT NOT NULL
                              );
                           """)
      dbConnection.commit()
   except sqlite3.OperationalError as e:
      if dbConnection:
         dbConnection.rollback()
      if e.args[0] != "table activeJobs already exists":
         print(traceback.format_exc())
   except sqlite3.Error as e:
      if dbConnection:
         dbConnection.rollback()
      print(traceback.format_exc())
   finally:
      if dbConnection:
         dbConnection.close()

