#!/usr/bin/env python

#
# Copyright 2015 sadikovi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os
import src.utils as utils
from flask import json
from flask.ext.sqlalchemy import SignallingSession
from Queue import PriorityQueue
from threading import Timer, Lock
from subprocess import Popen, PIPE
from src.loggable import Loggable
from src.job import Job
from src.octohaven import db, workingDirectory, sparkContext, numSlots
from src.sparkmodule import DOWN

# Main scheduler object for logging
scheduler = Loggable("job-scheduler")

lock = Lock()
# Number of slots, the maximum number of jobs to run at the same time
NUM_SLOTS = numSlots
# Interval to update current running state and poll jobs in seconds
REFRESH_INTERVAL = 5.0

# Constants for folders and files created
METADATA = "_metadata"
STDOUT = "stdout"
STDERR = "stderr"

@utils.private
def action(sampler):
    if not sampler:
        scheduler.logger.error("Sampler is undefined, exiting")
        return
    session = SignallingSession(db)
    try:
        sampler.logger.info("Start refreshing application state")
        sampler.incrementNumRuns()
        lock.acquire()
        for uid, pid in sampler.pool.items():
            if updateProcessStatus(pid) >= 0:
                job = Job.get(session, uid)
                if not job:
                    sampler.logger.warn("Job '%s' does not exist in database, updated skipped", uid)