import logging
import os

from autotest_lib.client.common_lib import error
from autotest_lib.server import utils
from autotest_lib.server.cros import provision

try:
    from chromite.lib import metrics
except ImportError:
    metrics = utils.metrics_mock


DURATION_METRIC = 'chromeos/autotest/autoserv/cleanup_duration'


# A string of the form 'label1,label2:value,label3'.
job_labels = locals().get('job_labels') or ','.join(args)
labels_list = [l.strip() for l in job_labels.split(',') if l]


def cleanup(machine):
    try:
        hostname = utils.get_hostname_from_machine(machine)
        job.record('START', None, 'cleanup')
        host = hosts.create_host(machine, try_lab_servo=True)
        with metrics.SecondsTimer(DURATION_METRIC,
                                  fields={'dut_host_name': hostname}):
            # Try to save /var/log files. If the dut is not sshable, try to restart
            # with servo. This is a temp fix to collect log for test failed with dut
            # not returning from reboot.
            # TODO(dshi): This temp fix should be removed after crash collect work
            # is completed, crbug.com/336985
            try:
                host.ssh_ping()
            except error.AutoservSshPingHostError:
                # Try to restart dut with servo.
                host._servo_repair_power()
            local_log_dir = os.path.join(job.resultdir, hostname)
            host.collect_logs('/var/log', local_log_dir, ignore_errors=True)

            host.cleanup()
            provision.Cleanup.run_task_actions(job, host, labels_list)
    except Exception:
        logging.exception('Cleanup failed due to Exception.')
        job.record('END FAIL', None, 'cleanup')
        # See the provision control segment for the explanation of why we're
        # doing this.
        raise Exception('')
    else:
        job.record('END GOOD', None, 'cleanup',
                   '%s cleaned successfully' % hostname)


job.parallel_simple(cleanup, machines, log=False)

# vim: set syntax=python :