#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Jan 23, 2014

@author: noob
"""

import socket
import sys
import settings

# Костыль, чтобы команда выполнялась только на одном сервере.
# Подразумевается, что в каждом дц по одному серверу
if not socket.gethostname().startswith('sas') and not settings.env_type == 'production':
    sys.stderr.write('broken jobs killer is cancelled')
    sys.exit(0)


import logging
from common.models import Job, ApiToken
from common.util.clients import ClickhouseClient
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from django.http import HttpRequest
import time


from api.views.jobclose import JobClose


class Command(BaseCommand):
    help = 'Close broken jobs'
    logging.error('cron_broken_jobs called')

    def handle(self, *args, **options):
        hour_ago = datetime.now() - timedelta(0, 3600, 0)
        online_jobs = Job.objects.filter(td=None, fd__lt=hour_ago)
        logging.debug('online_jobs %s', [job.n for job in online_jobs])
        for job in online_jobs:
            try:
                ch_client = ClickhouseClient()
                latest_sec = ch_client.select('''
                    select toUInt32(max(time)) 
                    from loaddb.rt_microsecond_details 
                    where job_id=%(job)s
                    and job_date=toDate(%(job_date)s) 
                    ''', query_params=job.basic_query_params)
                logging.debug('job %s LATEST SEC %s', job.n, latest_sec)                
                if latest_sec and latest_sec[0][0] < time.mktime(hour_ago.timetuple()) or not latest_sec:
                    request = HttpRequest()
                    request.method = 'get'
                    api_token = ApiToken.objects.get(user=job.user)
                    request.user = job.user
                    request.GET['api_token'] = api_token.token
                    riper = JobClose()
                    riper.get(request, job)
                logging.error('closed broken job %s', job.n)
            except:
                logging.exception('FAILED TO CLOSE JOB %s', job.n)
                

