Blame SOURCES/bz1846733-gcp-vpc-move-vip-1-support-multiple-alias-ips.patch

83967c
--- a/heartbeat/gcp-vpc-move-vip.in	2020-08-17 10:33:22.132531259 +0200
83967c
+++ b/heartbeat/gcp-vpc-move-vip.in	2020-08-17 10:34:54.050633259 +0200
83967c
@@ -22,7 +22,8 @@
83967c
 import sys
83967c
 import time
83967c
 
83967c
-OCF_FUNCTIONS_DIR="%s/lib/heartbeat" % os.environ.get("OCF_ROOT")
83967c
+OCF_FUNCTIONS_DIR = os.environ.get("OCF_FUNCTIONS_DIR", "%s/lib/heartbeat"
83967c
+                                   % os.environ.get("OCF_ROOT"))
83967c
 sys.path.append(OCF_FUNCTIONS_DIR)
83967c
 
83967c
 from ocf import *
83967c
@@ -43,6 +44,10 @@
83967c
   import urllib2 as urlrequest
83967c
 
83967c
 
83967c
+# Constants for alias add/remove modes
83967c
+ADD = 0
83967c
+REMOVE = 1
83967c
+
83967c
 CONN = None
83967c
 THIS_VM = None
83967c
 ALIAS = None
83967c
@@ -53,27 +58,27 @@
83967c
 
83967c
 <resource-agent name="gcp-vpc-move-vip">
83967c
   <version>1.0</version>
83967c
-  <longdesc lang="en">Floating IP Address on Google Cloud Platform - Using Alias IP address functionality to attach a secondary IP address to a running instance</longdesc>
83967c
-  <shortdesc lang="en">Floating IP Address on Google Cloud Platform</shortdesc>
83967c
+  <longdesc lang="en">Floating IP Address or Range on Google Cloud Platform - Using Alias IP address functionality to attach a secondary IP range to a running instance</longdesc>
83967c
+  <shortdesc lang="en">Floating IP Address or Range on Google Cloud Platform</shortdesc>
83967c
   <parameters>
83967c
     <parameter name="alias_ip" unique="1" required="1">
83967c
-      <longdesc lang="en">IP Address to be added including CIDR. E.g 192.168.0.1/32</longdesc>
83967c
-      <shortdesc lang="en">IP Address to be added including CIDR. E.g 192.168.0.1/32</shortdesc>
83967c
+      <longdesc lang="en">IP range to be added including CIDR netmask (e.g., 192.168.0.1/32)</longdesc>
83967c
+      <shortdesc lang="en">IP range to be added including CIDR netmask (e.g., 192.168.0.1/32)</shortdesc>
83967c
       <content type="string" default="" />
83967c
     </parameter>
83967c
-    <parameter name="alias_range_name" unique="1" required="0">
83967c
+    <parameter name="alias_range_name" unique="0" required="0">
83967c
       <longdesc lang="en">Subnet name for the Alias IP</longdesc>
83967c
       <shortdesc lang="en">Subnet name for the Alias IP</shortdesc>
83967c
       <content type="string" default="" />
83967c
     </parameter>
83967c
-    <parameter name="hostlist" unique="1" required="0">
83967c
-      <longdesc lang="en">List of hosts in the cluster</longdesc>
83967c
+    <parameter name="hostlist" unique="0" required="0">
83967c
+      <longdesc lang="en">List of hosts in the cluster, separated by spaces</longdesc>
83967c
       <shortdesc lang="en">Host list</shortdesc>
83967c
       <content type="string" default="" />
83967c
     </parameter>
83967c
     <parameter name="stackdriver_logging" unique="0" required="0">
83967c
-      <longdesc lang="en">If enabled (set to true), IP failover logs will be posted to stackdriver logging. Using stackdriver logging requires additional libraries (google-cloud-logging).</longdesc>
83967c
-      <shortdesc lang="en">Stackdriver-logging support. Requires additional libraries (google-cloud-logging).</shortdesc>
83967c
+      <longdesc lang="en">If enabled (set to true), IP failover logs will be posted to stackdriver logging</longdesc>
83967c
+      <shortdesc lang="en">Stackdriver-logging support</shortdesc>
83967c
       <content type="boolean" default="" />
83967c
     </parameter>
83967c
   </parameters>
83967c
@@ -107,7 +112,8 @@
83967c
   url = '%s?%s' % (metadata_url, params)
83967c
   request = urlrequest.Request(url, headers=METADATA_HEADERS)
83967c
   request_opener = urlrequest.build_opener(urlrequest.ProxyHandler({}))
83967c
-  return request_opener.open(request, timeout=timeout * 1.1).read().decode("utf-8")
83967c
+  return request_opener.open(
83967c
+      request, timeout=timeout * 1.1).read().decode("utf-8")
83967c
 
83967c
 
83967c
 def get_instance(project, zone, instance):
83967c
@@ -134,17 +140,21 @@
83967c
     time.sleep(1)
83967c
 
83967c
 
83967c
-def set_alias(project, zone, instance, alias, alias_range_name=None):
83967c
-  fingerprint = get_network_ifaces(project, zone, instance)[0]['fingerprint']
83967c
+def set_aliases(project, zone, instance, aliases, fingerprint):
83967c
+  """Sets the alias IP ranges for an instance.
83967c
+
83967c
+  Args:
83967c
+    project: string, the project in which the instance resides.
83967c
+    zone: string, the zone in which the instance resides.
83967c
+    instance: string, the name of the instance.
83967c
+    aliases: list, the list of dictionaries containing alias IP ranges
83967c
+      to be added to or removed from the instance.
83967c
+    fingerprint: string, the fingerprint of the network interface.
83967c
+  """
83967c
   body = {
83967c
-      'aliasIpRanges': [],
83967c
-      'fingerprint': fingerprint
83967c
+    'aliasIpRanges': aliases,
83967c
+    'fingerprint': fingerprint
83967c
   }
83967c
-  if alias:
83967c
-    obj = {'ipCidrRange': alias}
83967c
-    if alias_range_name:
83967c
-      obj['subnetworkRangeName'] = alias_range_name
83967c
-    body['aliasIpRanges'].append(obj)
83967c
 
83967c
   request = CONN.instances().updateNetworkInterface(
83967c
       instance=instance, networkInterface='nic0', project=project, zone=zone,
83967c
@@ -153,21 +163,75 @@
83967c
   wait_for_operation(project, zone, operation)
83967c
 
83967c
 
83967c
-def get_alias(project, zone, instance):
83967c
-  iface = get_network_ifaces(project, zone, instance)
83967c
+def add_rm_alias(mode, project, zone, instance, alias, alias_range_name=None):
83967c
+  """Adds or removes an alias IP range for a GCE instance.
83967c
+
83967c
+  Args:
83967c
+    mode: int, a constant (ADD (0) or REMOVE (1)) indicating the
83967c
+      operation type.
83967c
+    project: string, the project in which the instance resides.
83967c
+    zone: string, the zone in which the instance resides.
83967c
+    instance: string, the name of the instance.
83967c
+    alias: string, the alias IP range to be added to or removed from
83967c
+      the instance.
83967c
+    alias_range_name: string, the subnet name for the alias IP range.
83967c
+
83967c
+  Returns:
83967c
+    True if the existing list of alias IP ranges was modified, or False
83967c
+    otherwise.
83967c
+  """
83967c
+  ifaces = get_network_ifaces(project, zone, instance)
83967c
+  fingerprint = ifaces[0]['fingerprint']
83967c
+
83967c
+  try:
83967c
+    old_aliases = ifaces[0]['aliasIpRanges']
83967c
+  except KeyError:
83967c
+    old_aliases = []
83967c
+
83967c
+  new_aliases = [a for a in old_aliases if a['ipCidrRange'] != alias]
83967c
+
83967c
+  if alias:
83967c
+    if mode == ADD:
83967c
+      obj = {'ipCidrRange': alias}
83967c
+      if alias_range_name:
83967c
+        obj['subnetworkRangeName'] = alias_range_name
83967c
+      new_aliases.append(obj)
83967c
+    elif mode == REMOVE:
83967c
+      pass    # already removed during new_aliases build
83967c
+    else:
83967c
+      raise ValueError('Invalid value for mode: {}'.format(mode))
83967c
+
83967c
+  if (sorted(new_aliases) != sorted(old_aliases)):
83967c
+    set_aliases(project, zone, instance, new_aliases, fingerprint)
83967c
+    return True
83967c
+  else:
83967c
+    return False
83967c
+
83967c
+
83967c
+def add_alias(project, zone, instance, alias, alias_range_name=None):
83967c
+  return add_rm_alias(ADD, project, zone, instance, alias, alias_range_name)
83967c
+
83967c
+
83967c
+def remove_alias(project, zone, instance, alias):
83967c
+  return add_rm_alias(REMOVE, project, zone, instance, alias)
83967c
+
83967c
+
83967c
+def get_aliases(project, zone, instance):
83967c
+  ifaces = get_network_ifaces(project, zone, instance)
83967c
   try:
83967c
-    return iface[0]['aliasIpRanges'][0]['ipCidrRange']
83967c
+    aliases = ifaces[0]['aliasIpRanges']
83967c
+    return [a['ipCidrRange'] for a in aliases]
83967c
   except KeyError:
83967c
-    return ''
83967c
+    return []
83967c
 
83967c
 
83967c
-def get_localhost_alias():
83967c
+def get_localhost_aliases():
83967c
   net_iface = get_metadata('instance/network-interfaces', {'recursive': True})
83967c
   net_iface = json.loads(net_iface)
83967c
   try:
83967c
-    return net_iface[0]['ipAliases'][0]
83967c
+    return net_iface[0]['ipAliases']
83967c
   except (KeyError, IndexError):
83967c
-    return ''
83967c
+    return []
83967c
 
83967c
 
83967c
 def get_zone(project, instance):
83967c
@@ -201,21 +265,17 @@
83967c
 
83967c
 
83967c
 def gcp_alias_start(alias):
83967c
-  my_alias = get_localhost_alias()
83967c
+  my_aliases = get_localhost_aliases()
83967c
   my_zone = get_metadata('instance/zone').split('/')[-1]
83967c
   project = get_metadata('project/project-id')
83967c
 
83967c
-  # If I already have the IP, exit. If it has an alias IP that isn't the VIP,
83967c
-  # then remove it
83967c
-  if my_alias == alias:
83967c
+  if alias in my_aliases:
83967c
+    # TODO: Do we need to check alias_range_name?
83967c
     logger.info(
83967c
         '%s already has %s attached. No action required' % (THIS_VM, alias))
83967c
     sys.exit(OCF_SUCCESS)
83967c
-  elif my_alias:
83967c
-    logger.info('Removing %s from %s' % (my_alias, THIS_VM))
83967c
-    set_alias(project, my_zone, THIS_VM, '')
83967c
 
83967c
-  # Loops through all hosts & remove the alias IP from the host that has it
83967c
+  # If the alias is currently attached to another host, detach it.
83967c
   hostlist = os.environ.get('OCF_RESKEY_hostlist', '')
83967c
   if hostlist:
83967c
     hostlist = hostlist.replace(THIS_VM, '').split()
83967c
@@ -223,47 +283,53 @@
83967c
     hostlist = get_instances_list(project, THIS_VM)
83967c
   for host in hostlist:
83967c
     host_zone = get_zone(project, host)
83967c
-    host_alias = get_alias(project, host_zone, host)
83967c
-    if alias == host_alias:
83967c
+    host_aliases = get_aliases(project, host_zone, host)
83967c
+    if alias in host_aliases:
83967c
       logger.info(
83967c
-          '%s is attached to %s - Removing all alias IP addresses from %s' %
83967c
-          (alias, host, host))
83967c
-      set_alias(project, host_zone, host, '')
83967c
+          '%s is attached to %s - Removing %s from %s' %
83967c
+          (alias, host, alias, host))
83967c
+      remove_alias(project, host_zone, host, alias)
83967c
       break
83967c
 
83967c
-  # add alias IP to localhost
83967c
-  set_alias(
83967c
+  # Add alias IP range to localhost
83967c
+  add_alias(
83967c
       project, my_zone, THIS_VM, alias,
83967c
       os.environ.get('OCF_RESKEY_alias_range_name'))
83967c
 
83967c
-  # Check the IP has been added
83967c
-  my_alias = get_localhost_alias()
83967c
-  if alias == my_alias:
83967c
+  # Verify that the IP range has been added
83967c
+  my_aliases = get_localhost_aliases()
83967c
+  if alias in my_aliases:
83967c
     logger.info('Finished adding %s to %s' % (alias, THIS_VM))
83967c
-  elif my_alias:
83967c
-    logger.error(
83967c
-        'Failed to add IP. %s has an IP attached but it isn\'t %s' %
83967c
-        (THIS_VM, alias))
83967c
-    sys.exit(OCF_ERR_GENERIC)
83967c
   else:
83967c
-    logger.error('Failed to add IP address %s to %s' % (alias, THIS_VM))
83967c
+    if my_aliases:
83967c
+      logger.error(
83967c
+          'Failed to add alias IP range %s. %s has alias IP ranges attached but'
83967c
+          + ' they don\'t include %s' % (alias, THIS_VM, alias))
83967c
+    else:
83967c
+      logger.error(
83967c
+          'Failed to add IP range %s. %s has no alias IP ranges attached'
83967c
+           % (alias, THIS_VM))
83967c
     sys.exit(OCF_ERR_GENERIC)
83967c
 
83967c
 
83967c
 def gcp_alias_stop(alias):
83967c
-  my_alias = get_localhost_alias()
83967c
+  my_aliases = get_localhost_aliases()
83967c
   my_zone = get_metadata('instance/zone').split('/')[-1]
83967c
   project = get_metadata('project/project-id')
83967c
 
83967c
-  if my_alias == alias:
83967c
-    logger.info('Removing %s from %s' % (my_alias, THIS_VM))
83967c
-    set_alias(project, my_zone, THIS_VM, '')
83967c
+  if alias in my_aliases:
83967c
+    logger.info('Removing %s from %s' % (alias, THIS_VM))
83967c
+    remove_alias(project, my_zone, THIS_VM, alias)
83967c
+  else:
83967c
+    logger.info(
83967c
+        '%s is not attached to %s. No action required'
83967c
+        % (alias, THIS_VM))
83967c
 
83967c
 
83967c
 def gcp_alias_status(alias):
83967c
-  my_alias = get_localhost_alias()
83967c
-  if alias == my_alias:
83967c
-    logger.info('%s has the correct IP address attached' % THIS_VM)
83967c
+  my_aliases = get_localhost_aliases()
83967c
+  if alias in my_aliases:
83967c
+    logger.info('%s has the correct IP range attached' % THIS_VM)
83967c
   else:
83967c
     sys.exit(OCF_NOT_RUNNING)
83967c
 
83967c
@@ -275,7 +341,8 @@
83967c
 
83967c
   # Populate global vars
83967c
   try:
83967c
-    CONN = googleapiclient.discovery.build('compute', 'v1')
83967c
+    CONN = googleapiclient.discovery.build('compute', 'v1',
83967c
+                                           cache_discovery=False)
83967c
   except Exception as e:
83967c
     logger.error('Couldn\'t connect with google api: ' + str(e))
83967c
     sys.exit(OCF_ERR_CONFIGURED)
83967c
@@ -283,7 +350,8 @@
83967c
   try:
83967c
     THIS_VM = get_metadata('instance/name')
83967c
   except Exception as e:
83967c
-    logger.error('Couldn\'t get instance name, is this running inside GCE?: ' + str(e))
83967c
+    logger.error('Couldn\'t get instance name, is this running inside GCE?: '
83967c
+                 + str(e))
83967c
     sys.exit(OCF_ERR_CONFIGURED)
83967c
 
83967c
   ALIAS = os.environ.get('OCF_RESKEY_alias_ip')
83967c
@@ -309,7 +377,8 @@
83967c
         formatter = logging.Formatter('gcp:alias "%(message)s"')
83967c
         handler.setFormatter(formatter)
83967c
         log.addHandler(handler)
83967c
-        logger = logging.LoggerAdapter(log, {'OCF_RESOURCE_INSTANCE': OCF_RESOURCE_INSTANCE})
83967c
+        logger = logging.LoggerAdapter(log, {'OCF_RESOURCE_INSTANCE':
83967c
+                                             OCF_RESOURCE_INSTANCE})
83967c
       except ImportError:
83967c
         logger.error('Couldn\'t import google.cloud.logging, '
83967c
             'disabling Stackdriver-logging support')