#
#    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

from oslo_config import cfg
from oslo_log import log as logging
import six

from heat.common import exception
from heat.common.i18n import _
from heat.common import template_format
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources import stack_resource

LOG = logging.getLogger(__name__)

lb_template_default = r'''
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "Built in HAProxy server using Fedora 21 x64 cloud image",
  "Parameters" : {
    "KeyName" : {
      "Type" : "String"
    },
    "LbImageId" : {
      "Type" : "String",
      "Default" : "Fedora-Cloud-Base-20141203-21.x86_64"
    },
    "LbFlavor" : {
      "Type" : "String",
      "Default" : "m1.small"
    },
    "LBTimeout" : {
      "Type" : "String",
      "Default" : "600"
    },
    "SecurityGroups" : {
      "Type" : "CommaDelimitedList",
      "Default" : []
    }
  },
  "Resources": {
    "latency_watcher": {
     "Type": "AWS::CloudWatch::Alarm",
     "Properties": {
        "MetricName": "Latency",
        "Namespace": "AWS/ELB",
        "Statistic": "Average",
        "Period": "60",
        "EvaluationPeriods": "1",
        "Threshold": "2",
        "AlarmActions": [],
        "ComparisonOperator": "GreaterThanThreshold"
      }
    },
    "CfnLBUser" : {
      "Type" : "AWS::IAM::User"
    },
    "CfnLBAccessKey" : {
      "Type" : "AWS::IAM::AccessKey",
      "Properties" : {
        "UserName" : {"Ref": "CfnLBUser"}
      }
    },
    "LB_instance": {
      "Type": "AWS::EC2::Instance",
      "Metadata": {
        "AWS::CloudFormation::Init": {
          "config": {
            "packages": {
              "yum": {
                "haproxy"        : [],
                "socat"          : []
              }
            },
            "services": {
              "systemd": {
                "crond"     : { "enabled" : "true", "ensureRunning" : "true" }
              }
            },
            "files": {
              "/etc/cfn/cfn-credentials" : {
                "content" : { "Fn::Join" : ["", [
                  "AWSAccessKeyId=", { "Ref" : "CfnLBAccessKey" }, "\n",
                  "AWSSecretKey=", {"Fn::GetAtt": ["CfnLBAccessKey",
                                    "SecretAccessKey"]}, "\n"
                ]]},
                "mode"    : "000400",
                "owner"   : "root",
                "group"   : "root"
              },
              "/etc/cfn/cfn-hup.conf" : {
                "content" : { "Fn::Join" : ["", [
                  "[main]\n",
                  "stack=", { "Ref" : "AWS::StackId" }, "\n",
                  "credential-file=/etc/cfn/cfn-credentials\n",
                  "region=", { "Ref" : "AWS::Region" }, "\n",
                  "interval=60\n"
                ]]},
                "mode"    : "000400",
                "owner"   : "root",
                "group"   : "root"
              },
              "/etc/cfn/hooks.conf" : {
                "content": { "Fn::Join" : ["", [
                  "[cfn-init]\n",
                  "triggers=post.update\n",
                  "path=Resources.LB_instance.Metadata\n",
                  "action=/opt/aws/bin/cfn-init -s ",
                  { "Ref": "AWS::StackId" },
                  "    -r LB_instance ",
                  "    --region ", { "Ref": "AWS::Region" }, "\n",
                  "runas=root\n",
                  "\n",
                  "[reload]\n",
                  "triggers=post.update\n",
                  "path=Resources.LB_instance.Metadata\n",
                  "action=systemctl reload-or-restart haproxy.service\n",
                  "runas=root\n"
                ]]},
                "mode"    : "000400",
                "owner"   : "root",
                "group"   : "root"
              },
              "/etc/haproxy/haproxy.cfg": {
                "content": "",
                "mode": "000644",
                "owner": "root",
                "group": "root"
              },
              "/root/haproxy_tmp.te": {
                "mode": "000600",
                "owner": "root",
                "group": "root",
                "content": { "Fn::Join" : [ "", [
                  "module haproxy_tmp 1.0;\n",
                  "require { type tmp_t; type haproxy_t;",
                  "class sock_file { rename write create unlink link };",
                  "class dir { write remove_name add_name };}\n",
                  "allow haproxy_t ",
                  "tmp_t:dir { write remove_name add_name };\n",
                  "allow haproxy_t ",
                  "tmp_t:sock_file { rename write create unlink link};\n"
                 ]]}
               },
              "/tmp/cfn-hup-crontab.txt" : {
                "content" : { "Fn::Join" : ["", [
                "MAIL=\"\"\n",
                "\n",
                "* * * * * /opt/aws/bin/cfn-hup -f\n",
                "* * * * * /opt/aws/bin/cfn-push-stats ",
                " --watch ", { "Ref" : "latency_watcher" }, " --haproxy\n"
                ]]},
                "mode"    : "000600",
                "owner"   : "root",
                "group"   : "root"
              }
            }
          }
        }
      },
      "Properties": {
        "ImageId": { "Ref": "LbImageId" },
        "InstanceType": { "Ref": "LbFlavor" },
        "KeyName": { "Ref": "KeyName" },
        "SecurityGroups": { "Ref": "SecurityGroups" },
        "UserData": { "Fn::Base64": { "Fn::Join": ["", [
          "#!/bin/bash -v\n",
          "# Helper function\n",
          "function error_exit\n",
          "{\n",
          "  /opt/aws/bin/cfn-signal -e 1 -r \"$1\" '",
          { "Ref" : "WaitHandle" }, "'\n",
          "  exit 1\n",
          "}\n",

          "/opt/aws/bin/cfn-init -s ",
          { "Ref": "AWS::StackId" },
          "    -r LB_instance ",
          "    --region ", { "Ref": "AWS::Region" },
          " || error_exit 'Failed to run cfn-init'\n",

          "# HAProxy+SELinux, https://www.mankier.com/8/haproxy_selinux \n",

          "# this is exported by selinux-policy >=3.12.1.196\n",
          "setsebool haproxy_connect_any 1\n",

          "# when the location of haproxy stats file is fixed\n",
          "# in heat-cfntools and AWS::ElasticLoadBalancing::LoadBalancer\n",
          "# to point to /var/lib/haproxy/stats, \n",
          "# this next block can be removed.\n",
          "# compile custom module to allow /tmp files and sockets access\n",
          "cd /root\n",
          "checkmodule -M -m -o haproxy_tmp.mod haproxy_tmp.te\n",
          "semodule_package -o haproxy_tmp.pp -m haproxy_tmp.mod\n",
          "semodule -i haproxy_tmp.pp\n",
          "touch /tmp/.haproxy-stats\n",
          "semanage fcontext -a -t haproxy_tmpfs_t /tmp/.haproxy-stats\n",
          "restorecon -R -v /tmp/.haproxy-stats\n",

          "# install cfn-hup crontab\n",
          "crontab /tmp/cfn-hup-crontab.txt\n",

          "# restart haproxy service to catch initial changes\n",
          "systemctl reload-or-restart haproxy.service\n",

          "# LB setup completed, signal success\n",
          "/opt/aws/bin/cfn-signal -e 0 -r \"LB server setup complete\" '",
          { "Ref" : "WaitHandle" }, "'\n"

        ]]}}
      }
    },
    "WaitHandle" : {
      "Type" : "AWS::CloudFormation::WaitConditionHandle"
    },

    "WaitCondition" : {
      "Type" : "AWS::CloudFormation::WaitCondition",
      "DependsOn" : "LB_instance",
      "Properties" : {
        "Handle" : {"Ref" : "WaitHandle"},
        "Timeout" : {"Ref" : "LBTimeout"}
      }
    }
  },

  "Outputs": {
    "PublicIp": {
      "Value": { "Fn::GetAtt": [ "LB_instance", "PublicIp" ] },
      "Description": "instance IP"
    }
  }
}
'''


# Allow user to provide alternative nested stack template to the above
loadbalancer_opts = [
    cfg.StrOpt('loadbalancer_template',
               help=_('Custom template for the built-in '
                      'loadbalancer nested stack.'))]
cfg.CONF.register_opts(loadbalancer_opts)


class LoadBalancer(stack_resource.StackResource):
    """Implements a HAProxy-bearing instance as a nested stack.

    The template for the nested stack can be redefined with
    ``loadbalancer_template`` option in ``heat.conf``.

    Generally the image used for the instance must have the following
    packages installed or available for installation at runtime::

        - heat-cfntools and its dependencies like python-psutil
        - cronie
        - socat
        - haproxy

    Current default builtin template uses Fedora 21 x86_64 base cloud image
    (https://getfedora.org/cloud/download/)
    and apart from installing packages goes through some hoops
    around SELinux due to pecularities of heat-cfntools.
    """

    PROPERTIES = (
        AVAILABILITY_ZONES, HEALTH_CHECK, INSTANCES, LISTENERS,
        APP_COOKIE_STICKINESS_POLICY, LBCOOKIE_STICKINESS_POLICY,
        SECURITY_GROUPS, SUBNETS,
    ) = (
        'AvailabilityZones', 'HealthCheck', 'Instances', 'Listeners',
        'AppCookieStickinessPolicy', 'LBCookieStickinessPolicy',
        'SecurityGroups', 'Subnets',
    )

    _HEALTH_CHECK_KEYS = (
        HEALTH_CHECK_HEALTHY_THRESHOLD, HEALTH_CHECK_INTERVAL,
        HEALTH_CHECK_TARGET, HEALTH_CHECK_TIMEOUT,
        HEALTH_CHECK_UNHEALTHY_THRESHOLD,
    ) = (
        'HealthyThreshold', 'Interval',
        'Target', 'Timeout',
        'UnhealthyThreshold',
    )

    _LISTENER_KEYS = (
        LISTENER_INSTANCE_PORT, LISTENER_LOAD_BALANCER_PORT, LISTENER_PROTOCOL,
        LISTENER_SSLCERTIFICATE_ID, LISTENER_POLICY_NAMES,
    ) = (
        'InstancePort', 'LoadBalancerPort', 'Protocol',
        'SSLCertificateId', 'PolicyNames',
    )

    ATTRIBUTES = (
        CANONICAL_HOSTED_ZONE_NAME, CANONICAL_HOSTED_ZONE_NAME_ID, DNS_NAME,