from airflow import DAG
from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator

from datetime import datetime, timedelta

DAG_STARTDATE = datetime(2021, 4, 6, 00)
default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': DAG_STARTDATE,
    'email': ['gordon.inggs@capetown.gov.za'],
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 2,
    'retry_delay': timedelta(minutes=5),
}

dag_interval = "@hourly"
dag_name = 'vulnerability-viewer-infra'
dag = DAG(dag_name,
          catchup=False,
          default_args=default_args,
          schedule_interval=dag_interval,
          concurrency=1)

# arguments for the k8s operator
k8s_run_args = {
    "image": "bitnami/kubectl",
    "namespace": 'airflow-workers',
    "is_delete_operator_pod": True,
    "get_logs": True,
    "in_cluster": True,
    "startup_timeout_seconds": 60 * 30,
    "service_account_name": "vv-nginx-ldap-proxy-restart"
}


def vv_task(task_name, kwargs, run_cmds):
    """Factory for k8sPodOperator"""
    name = f"{dag_name}-{task_name}"
    run_args = {**k8s_run_args.copy(), **kwargs}

    operator = KubernetesPodOperator(
        cmds=run_cmds,
        name=name,
        task_id=name,
        dag=dag,
        execution_timeout=timedelta(minutes=5),
        **run_args
    )

    return operator


# Defining tasks
LDAP_REDPLOY_TASK = 'ldap-redploy'
compress_data_operator = vv_task(LDAP_REDPLOY_TASK, {}, ['kubectl', 'rollout', 'restart',
                                                         'deployment/vv-nginx-ldap-proxy',
                                                         '--namespace', 'vulnerability-viewer'])
