<commit_before>import json
import httplib
import time

from flask import Request

from .utils import network_utils
from .config import config
from .logger import log
from .exceptions import CreationException
from .sessions import RequestHelper
from .utils.graphite import graphite, send_metrics


class DesiredCapabilities(object):
    def __init__(self, name, platform, takeScreenshot, runScript):
        self.name = name
        self.platform = platform
        self.takeScreenshot = bool(takeScreenshot)
        self.runScript = dict(runScript)


def start_session(request, session):
    notdot_platform = "".join(session.platform.split("."))
    _start = time.time()

    status = graphite("%s.%s" % (notdot_platform, "ping_vm"))(ping_vm)(session)
    if session.closed:
        raise CreationException("Session closed by user")

    if not status:
        log.info("ping failed: TIMEOUT. Session: %s".format(session.id))
        raise CreationException("failed to ping virtual machine")

    # check status
    if not graphite("%s.%s" % (notdot_platform, "selenium_status"))(selenium_status)(request, session, config.SELENIUM_PORT):
        if session.timeouted:
            raise CreationException("failed to get status of selenium-server-standalone")

    if session.desired_capabilities.runScript:
        startup_script(session)

    response = graphite("%s.%s" % (notdot_platform, "start_selenium_session"))(start_selenium_session)(request, session, config.SELENIUM_PORT)
    status, headers, body = response
    send_metrics("%s.%s" % (notdot_platform, "creation_total"), time.time() - _start)

    if status == httplib.OK:
        selenium_session = json.loads(body)["sessionId"]
        session.selenium_session = selenium_session
        body = set_body_session_id(body, session.id)
        headers["Content-Length"] = len(body)

    return status, headers, body


def startup_script(session):
    r = RequestHelper(method="POST", body=json.dumps(session.desired_capabilities.runScript))
    status, headers, body = run_script(r, session)
    if status != httplib.OK:
        raise Exception("failed to run script: %s" % body)
    script_result = json.loads(body)
    if script_result.get("status") != 0:
        raise Exception("failed to run script with code %s:\n%s" % (
            script_result.get("status"), script_result.get("output")))


def ping_vm(session):
    # ping ip:port
    ip = session.virtual_machine.ip
    port = config.SELENIUM_PORT
    timeout = config.PING_TIMEOUT
    start = time.time()
    log.info("starting ping: {ip}:{port}".format(ip=ip, port=port))
    while time.time() - start < timeout and not session.closed:<commit_msg>fix session deletion if could not start selenium session<commit_after>import json
import httplib
import time

from flask import Request

from .utils import network_utils
from .config import config
from .logger import log
from .exceptions import CreationException
from .sessions import RequestHelper
from .utils.graphite import graphite, send_metrics


class DesiredCapabilities(object):
    def __init__(self, name, platform, takeScreenshot, runScript):
        self.name = name
        self.platform = platform
        self.takeScreenshot = bool(takeScreenshot)
        self.runScript = dict(runScript)


def start_session(request, session):
    notdot_platform = "".join(session.platform.split("."))
    _start = time.time()

    status = graphite("%s.%s" % (notdot_platform, "ping_vm"))(ping_vm)(session)
    if session.closed:
        raise CreationException("Session closed by user")

    if not status:
        log.info("ping failed: TIMEOUT. Session: %s".format(session.id))
        raise CreationException("failed to ping virtual machine")

    # check status
    if not graphite("%s.%s" % (notdot_platform, "selenium_status"))(selenium_status)(request, session, config.SELENIUM_PORT):
        if session.timeouted:
            raise CreationException("Failed to get status of selenium-server-standalone")

    if session.desired_capabilities.runScript:
        startup_script(session)

    response = graphite("%s.%s" % (notdot_platform, "start_selenium_session"))(start_selenium_session)(request, session, config.SELENIUM_PORT)
    status, headers, body = response
    send_metrics("%s.%s" % (notdot_platform, "creation_total"), time.time() - _start)

    if status == httplib.OK:
        selenium_session = json.loads(body)["sessionId"]
        session.selenium_session = selenium_session
        body = set_body_session_id(body, session.id)
        headers["Content-Length"] = len(body)
    else:
        raise CreationException("Failed to start selenium session: %s" % body)

    return status, headers, body


def startup_script(session):
    r = RequestHelper(method="POST", body=json.dumps(session.desired_capabilities.runScript))
    status, headers, body = run_script(r, session)
    if status != httplib.OK:
        raise Exception("failed to run script: %s" % body)
    script_result = json.loads(body)
    if script_result.get("status") != 0:
        raise Exception("failed to run script with code %s:\n%s" % (
            script_result.get("status"), script_result.get("output")))


def ping_vm(session):
    # ping ip:port
    ip = session.virtual_machine.ip
    port = config.SELENIUM_PORT
    timeout = config.PING_TIMEOUT
    start = time.time()
    log.info("starting ping: {ip}:{port}".format(ip=ip, port=port))
    while time.time() - start < timeout and not session.closed:
{'fraction_non_alphanumeric': 0.11431701972242513, 'fraction_numerical': 0.0003652300949598247, 'mean_word_length': 3.8426171529619806, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2852627', 'n_tokens_mistral': 1681, 'n_tokens_neox': 1592, 'n_words': 402}