Blame SOURCES/bz1568588-3-gcp-vpc-move-vip.patch

391384
From 92da4155d881e9ac2dce3a51c6953817349d164a Mon Sep 17 00:00:00 2001
391384
From: Helen Koike <helen.koike@collabora.com>
391384
Date: Mon, 25 Jun 2018 11:03:51 -0300
391384
Subject: [PATCH 1/4] gcp-vpc-move-vip.in: manage ip alias
391384
391384
Add a resource agent to manage ip alias in the cluster.
391384
391384
start:
391384
	Check if any machine in hostlist has the alias_ip assigned and
391384
	disassociate it.
391384
	Assign alias_ip to the current machine.
391384
391384
stop:
391384
	Disassociate the alias_ip from the current machine.
391384
391384
status/monitor:
391384
	Check if alias_ip is assigned with the current machine.
391384
391384
---
391384
391384
This is a port to the following bash script to python:
391384
https://storage.googleapis.com/sapdeploy/pacemaker-gcp/alias
391384
391384
The problem with the bash script is the use of gcloud whose command line
391384
API is not stable.
391384
391384
ocf-tester.in results:
391384
391384
	> sudo ./tools/ocf-tester.in -o alias_ip='10.128.1.0/32' -o stackdriver_logging=yes -n gcp-vpc-move-vip.in heartbeat/gcp-vpc-move-vip.in
391384
	Beginning tests for heartbeat/gcp-vpc-move-vip.in...
391384
	./tools/ocf-tester.in: line 226: cd: @datadir@/resource-agents: No such file or directory
391384
	close failed in file object destructor:
391384
	sys.excepthook is missing
391384
	lost sys.stderr
391384
	* rc=1: Your agent produces meta-data which does not conform to ra-api-1.dtd
391384
	Tests failed: heartbeat/gcp-vpc-move-vip.in failed 1 tests
391384
391384
The only test faillig is the meta-data, but all the agents that I tried
391384
also fails on this. If this is a concern, could you please point me out
391384
to a test which succeeds so I can check what I am doing differently?
391384
391384
This commit can also be viewed at:
391384
	https://github.com/collabora-gce/resource-agents/tree/alias
391384
391384
Thanks
391384
---
391384
 configure.ac                  |   1 +
391384
 doc/man/Makefile.am           |   1 +
391384
 heartbeat/Makefile.am         |   1 +
391384
 heartbeat/gcp-vpc-move-vip.in | 299 ++++++++++++++++++++++++++++++++++++++++++
391384
 4 files changed, 302 insertions(+)
391384
 create mode 100755 heartbeat/gcp-vpc-move-vip.in
391384
391384
diff --git a/configure.ac b/configure.ac
391384
index bdf057d33..3d8f9ca74 100644
391384
--- a/configure.ac
391384
+++ b/configure.ac
391384
@@ -959,6 +959,7 @@ AC_CONFIG_FILES([heartbeat/dnsupdate], [chmod +x heartbeat/dnsupdate])
391384
 AC_CONFIG_FILES([heartbeat/eDir88], [chmod +x heartbeat/eDir88])
391384
 AC_CONFIG_FILES([heartbeat/fio], [chmod +x heartbeat/fio])
391384
 AC_CONFIG_FILES([heartbeat/gcp-vpc-move-ip], [chmod +x heartbeat/gcp-vpc-move-ip])
391384
+AC_CONFIG_FILES([heartbeat/gcp-vpc-move-vip], [chmod +x heartbeat/gcp-vpc-move-vip])
391384
 AC_CONFIG_FILES([heartbeat/iSCSILogicalUnit], [chmod +x heartbeat/iSCSILogicalUnit])
391384
 AC_CONFIG_FILES([heartbeat/iSCSITarget], [chmod +x heartbeat/iSCSITarget])
391384
 AC_CONFIG_FILES([heartbeat/jira], [chmod +x heartbeat/jira])
391384
diff --git a/doc/man/Makefile.am b/doc/man/Makefile.am
391384
index c59126d13..e9eaf369f 100644
391384
--- a/doc/man/Makefile.am
391384
+++ b/doc/man/Makefile.am
391384
@@ -114,6 +114,7 @@ man_MANS	       = ocf_heartbeat_AoEtarget.7 \
391384
                           ocf_heartbeat_galera.7 \
391384
                           ocf_heartbeat_garbd.7 \
391384
                           ocf_heartbeat_gcp-vpc-move-ip.7 \
391384
+                          ocf_heartbeat_gcp-vpc-move-vip.7 \
391384
                           ocf_heartbeat_iSCSILogicalUnit.7 \
391384
                           ocf_heartbeat_iSCSITarget.7 \
391384
                           ocf_heartbeat_iface-bridge.7 \
391384
diff --git a/heartbeat/Makefile.am b/heartbeat/Makefile.am
391384
index 4f5059e27..36b271956 100644
391384
--- a/heartbeat/Makefile.am
391384
+++ b/heartbeat/Makefile.am
391384
@@ -111,6 +111,7 @@ ocf_SCRIPTS	     =  AoEtarget		\
391384
 			galera			\
391384
 			garbd			\
391384
 			gcp-vpc-move-ip		\
391384
+			gcp-vpc-move-vip	\
391384
 			iSCSILogicalUnit	\
391384
 			iSCSITarget		\
391384
 			ids			\
391384
diff --git a/heartbeat/gcp-vpc-move-vip.in b/heartbeat/gcp-vpc-move-vip.in
391384
new file mode 100755
391384
index 000000000..4954e11df
391384
--- /dev/null
391384
+++ b/heartbeat/gcp-vpc-move-vip.in
391384
@@ -0,0 +1,299 @@
391384
+#!/usr/bin/env python
391384
+# ---------------------------------------------------------------------
391384
+# Copyright 2016 Google Inc.
391384
+#
391384
+# Licensed under the Apache License, Version 2.0 (the "License");
391384
+# you may not use this file except in compliance with the License.
391384
+# You may obtain a copy of the License at
391384
+#
391384
+# http://www.apache.org/licenses/LICENSE-2.0
391384
+# Unless required by applicable law or agreed to in writing, software
391384
+# distributed under the License is distributed on an "AS IS" BASIS,
391384
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
391384
+# See the License for the specific language governing permissions and
391384
+# limitations under the License.
391384
+# ---------------------------------------------------------------------
391384
+# Description:	Google Cloud Platform - Floating IP Address (Alias)
391384
+# ---------------------------------------------------------------------
391384
+
391384
+import json
391384
+import logging
391384
+import os
391384
+import sys
391384
+import time
391384
+
391384
+import googleapiclient.discovery
391384
+
391384
+if sys.version_info >= (3, 0):
391384
+  # Python 3 imports.
391384
+  import urllib.parse as urlparse
391384
+  import urllib.request as urlrequest
391384
+else:
391384
+  # Python 2 imports.
391384
+  import urllib as urlparse
391384
+  import urllib2 as urlrequest
391384
+
391384
+
391384
+CONN = None
391384
+THIS_VM = None
391384
+OCF_SUCCESS = 0
391384
+OCF_ERR_GENERIC = 1
391384
+OCF_ERR_CONFIGURED = 6
391384
+OCF_NOT_RUNNING = 7
391384
+METADATA_SERVER = 'http://metadata.google.internal/computeMetadata/v1/'
391384
+METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
391384
+METADATA = \
391384
+'''
391384
+
391384
+<resource-agent name="gcp-vpc-move-vip">
391384
+  <version>1.0</version>
391384
+  <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>
391384
+  <shortdesc lang="en">Floating IP Address on Google Cloud Platform</shortdesc>
391384
+  <parameters>
391384
+    <parameter name="hostlist" unique="1" required="1">
391384
+      <longdesc lang="en">List of hosts in the cluster</longdesc>
391384
+      <shortdesc lang="en">Host list</shortdesc>
391384
+      <content type="string" default="" />
391384
+    </parameter>
391384
+    <parameter name="stackdriver-logging" unique="0" required="0">
391384
+      <longdesc lang="en">If enabled (set to true), IP failover logs will be posted to stackdriver logging</longdesc>
391384
+      <shortdesc lang="en">Stackdriver-logging support</shortdesc>
391384
+      <content type="boolean" default="" />
391384
+    </parameter>
391384
+    <parameter name="alias_ip" unique="1" required="1">
391384
+      <longdesc lang="en">IP Address to be added including CIDR. E.g 192.168.0.1/32</longdesc>
391384
+      <shortdesc lang="en">IP Address to be added including CIDR. E.g 192.168.0.1/32</shortdesc>
391384
+      <content type="string" default="" />
391384
+    </parameter>
391384
+    <parameter name="alias_range_name" unique="1" required="0">
391384
+      <longdesc lang="en">Subnet name for the Alias IP2</longdesc>
391384
+      <shortdesc lang="en">Subnet name for the Alias IP</shortdesc>
391384
+      <content type="string" default="" />
391384
+    </parameter>
391384
+  </parameters>
391384
+  <actions>
391384
+    <action name="start" timeout="300" />
391384
+    <action name="stop" timeout="15" />
391384
+    <action name="monitor" timeout="15" interval="60" depth="0" />
391384
+    <action name="meta-data" timeout="15" />
391384
+  </actions>
391384
+</resource-agent>'''
391384
+
391384
+
391384
+def get_metadata(metadata_key, params=None, timeout=None):
391384
+  """Performs a GET request with the metadata headers.
391384
+
391384
+  Args:
391384
+    metadata_key: string, the metadata to perform a GET request on.
391384
+    params: dictionary, the query parameters in the GET request.
391384
+    timeout: int, timeout in seconds for metadata requests.
391384
+
391384
+  Returns:
391384
+    HTTP response from the GET request.
391384
+
391384
+  Raises:
391384
+    urlerror.HTTPError: raises when the GET request fails.
391384
+  """
391384
+  timeout = timeout or 60
391384
+  metadata_url = os.path.join(METADATA_SERVER, metadata_key)
391384
+  params = urlparse.urlencode(params or {})
391384
+  url = '%s?%s' % (metadata_url, params)
391384
+  request = urlrequest.Request(url, headers=METADATA_HEADERS)
391384
+  request_opener = urlrequest.build_opener(urlrequest.ProxyHandler({}))
391384
+  return request_opener.open(request, timeout=timeout * 1.1).read()
391384
+
391384
+
391384
+def get_instance(project, zone, instance):
391384
+  request = CONN.instances().get(
391384
+      project=project, zone=zone, instance=instance)
391384
+  return request.execute()
391384
+
391384
+
391384
+def get_network_ifaces(project, zone, instance):
391384
+  return get_instance(project, zone, instance)['networkInterfaces']
391384
+
391384
+
391384
+def wait_for_operation(project, zone, operation):
391384
+  while True:
391384
+    result = CONN.zoneOperations().get(
391384
+        project=project,
391384
+        zone=zone,
391384
+        operation=operation['name']).execute()
391384
+
391384
+    if result['status'] == 'DONE':
391384
+      if 'error' in result:
391384
+        raise Exception(result['error'])
391384
+      return
391384
+    time.sleep(1)
391384
+
391384
+
391384
+def set_alias(project, zone, instance, alias, alias_range_name=None):
391384
+  fingerprint = get_network_ifaces(project, zone, instance)[0]['fingerprint']
391384
+  body = {
391384
+      'aliasIpRanges': [],
391384
+      'fingerprint': fingerprint
391384
+  }
391384
+  if alias:
391384
+    obj = {'ipCidrRange': alias}
391384
+    if alias_range_name:
391384
+      obj['subnetworkRangeName'] = alias_range_name
391384
+    body['aliasIpRanges'].append(obj)
391384
+
391384
+  request = CONN.instances().updateNetworkInterface(
391384
+      instance=instance, networkInterface='nic0', project=project, zone=zone,
391384
+      body=body)
391384
+  operation = request.execute()
391384
+  wait_for_operation(project, zone, operation)
391384
+
391384
+
391384
+def get_alias(project, zone, instance):
391384
+  iface = get_network_ifaces(project, zone, instance)
391384
+  try:
391384
+    return iface[0]['aliasIpRanges'][0]['ipCidrRange']
391384
+  except KeyError:
391384
+    return ''
391384
+
391384
+
391384
+def get_localhost_alias():
391384
+  net_iface = get_metadata('instance/network-interfaces', {'recursive': True})
391384
+  net_iface = json.loads(net_iface.decode('utf-8'))
391384
+  try:
391384
+    return net_iface[0]['ipAliases'][0]
391384
+  except (KeyError, IndexError):
391384
+    return ''
391384
+
391384
+
391384
+def get_zone(project, instance):
391384
+  request = CONN.instances().aggregatedList(project=project)
391384
+  while request is not None:
391384
+    response = request.execute()
391384
+    zones = response.get('items', {})
391384
+    for zone in zones.values():
391384
+      for inst in zone.get('instances', []):
391384
+        if inst['name'] == instance:
391384
+          return inst['zone'].split("/")[-1]
391384
+    request = CONN.instances().aggregatedList_next(
391384
+        previous_request=request, previous_response=response)
391384
+  raise Exception("Unable to find instance %s" % (instance))
391384
+
391384
+
391384
+def gcp_alias_start(alias):
391384
+  if not alias:
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
+  my_alias = get_localhost_alias()
391384
+  my_zone = get_metadata('instance/zone').split('/')[-1]
391384
+  project = get_metadata('project/project-id')
391384
+
391384
+  # If I already have the IP, exit. If it has an alias IP that isn't the VIP,
391384
+  # then remove it
391384
+  if my_alias == alias:
391384
+    logging.info(
391384
+        '%s already has %s attached. No action required' % (THIS_VM, alias))
391384
+    sys.exit(OCF_SUCCESS)
391384
+  elif my_alias:
391384
+    logging.info('Removing %s from %s' % (my_alias, THIS_VM))
391384
+    set_alias(project, my_zone, THIS_VM, '')
391384
+
391384
+  # Loops through all hosts & remove the alias IP from the host that has it
391384
+  hostlist = os.environ.get('OCF_RESKEY_hostlist', '')
391384
+  hostlist.replace(THIS_VM, '')
391384
+  for host in hostlist.split():
391384
+    host_zone = get_zone(project, host)
391384
+    host_alias = get_alias(project, host_zone, host)
391384
+    if alias == host_alias:
391384
+      logging.info(
391384
+          '%s is attached to %s - Removing all alias IP addresses from %s' %
391384
+          (alias, host, host))
391384
+      set_alias(project, host_zone, host, '')
391384
+      break
391384
+
391384
+  # add alias IP to localhost
391384
+  set_alias(
391384
+      project, my_zone, THIS_VM, alias,
391384
+      os.environ.get('OCF_RESKEY_alias_range_name'))
391384
+
391384
+  # Check the IP has been added
391384
+  my_alias = get_localhost_alias()
391384
+  if alias == my_alias:
391384
+    logging.info('Finished adding %s to %s' % (alias, THIS_VM))
391384
+  elif my_alias:
391384
+    logging.error(
391384
+        'Failed to add IP. %s has an IP attached but it isn\'t %s' %
391384
+        (THIS_VM, alias))
391384
+    sys.exit(OCF_ERR_GENERIC)
391384
+  else:
391384
+    logging.error('Failed to add IP address %s to %s' % (alias, THIS_VM))
391384
+    sys.exit(OCF_ERR_GENERIC)
391384
+
391384
+
391384
+def gcp_alias_stop(alias):
391384
+  if not alias:
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
+  my_alias = get_localhost_alias()
391384
+  my_zone = get_metadata('instance/zone').split('/')[-1]
391384
+  project = get_metadata('project/project-id')
391384
+
391384
+  if my_alias == alias:
391384
+    logging.info('Removing %s from %s' % (my_alias, THIS_VM))
391384
+    set_alias(project, my_zone, THIS_VM, '')
391384
+
391384
+
391384
+def gcp_alias_status(alias):
391384
+  if not alias:
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
+  my_alias = get_localhost_alias()
391384
+  if alias == my_alias:
391384
+    logging.info('%s has the correct IP address attached' % THIS_VM)
391384
+  else:
391384
+    sys.exit(OCF_NOT_RUNNING)
391384
+
391384
+
391384
+def configure():
391384
+  global CONN
391384
+  global THIS_VM
391384
+
391384
+  # Populate global vars
391384
+  CONN = googleapiclient.discovery.build('compute', 'v1')
391384
+  THIS_VM = get_metadata('instance/name')
391384
+
391384
+  # Prepare logging
391384
+  logging.basicConfig(
391384
+      format='gcp:alias - %(levelname)s - %(message)s', level=logging.INFO)
391384
+  logging.getLogger('googleapiclient').setLevel(logging.WARN)
391384
+  logging_env = os.environ.get('OCF_RESKEY_stackdriver_logging')
391384
+  if logging_env:
391384
+    logging_env = logging_env.lower()
391384
+    if any(x in logging_env for x in ['yes', 'true', 'enabled']):
391384
+      try:
391384
+        import google.cloud.logging.handlers
391384
+        client = google.cloud.logging.Client()
391384
+        handler = google.cloud.logging.handlers.CloudLoggingHandler(
391384
+            client, name=THIS_VM)
391384
+        handler.setLevel(logging.INFO)
391384
+        formatter = logging.Formatter('gcp:alias "%(message)s"')
391384
+        handler.setFormatter(formatter)
391384
+        root_logger = logging.getLogger()
391384
+        root_logger.addHandler(handler)
391384
+      except ImportError:
391384
+        logging.error('Couldn\'t import google.cloud.logging, '
391384
+            'disabling Stackdriver-logging support')
391384
+
391384
+
391384
+def main():
391384
+  configure()
391384
+
391384
+  alias = os.environ.get('OCF_RESKEY_alias_ip')
391384
+  if 'start' in sys.argv[1]:
391384
+    gcp_alias_start(alias)
391384
+  elif 'stop' in sys.argv[1]:
391384
+    gcp_alias_stop(alias)
391384
+  elif 'status' in sys.argv[1] or 'monitor' in sys.argv[1]:
391384
+    gcp_alias_status(alias)
391384
+  elif 'meta-data' in sys.argv[1]:
391384
+    print(METADATA)
391384
+  else:
391384
+    logging.error('gcp:alias - no such function %s' % str(sys.argv[1]))
391384
+
391384
+
391384
+if __name__ == "__main__":
391384
+  main()
391384
391384
From 0e6ba4894a748664ac1d8ff5b9e8c271f0b04d93 Mon Sep 17 00:00:00 2001
391384
From: Helen Koike <helen.koike@collabora.com>
391384
Date: Thu, 12 Jul 2018 09:01:22 -0300
391384
Subject: [PATCH 2/4] gcp-vpc-move-vip.in: minor fixes
391384
391384
- Get hostlist from the project if the parameter is not given
391384
- Verify if alias is present out of each action function
391384
- Don't call configure if 'meta-data' action is given
391384
---
391384
 heartbeat/gcp-vpc-move-vip.in | 40 ++++++++++++++++++++++++++++------------
391384
 1 file changed, 28 insertions(+), 12 deletions(-)
391384
391384
diff --git a/heartbeat/gcp-vpc-move-vip.in b/heartbeat/gcp-vpc-move-vip.in
391384
index 4954e11df..f3d117bda 100755
391384
--- a/heartbeat/gcp-vpc-move-vip.in
391384
+++ b/heartbeat/gcp-vpc-move-vip.in
391384
@@ -50,7 +50,7 @@ METADATA = \
391384
   <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>
391384
   <shortdesc lang="en">Floating IP Address on Google Cloud Platform</shortdesc>
391384
   <parameters>
391384
-    <parameter name="hostlist" unique="1" required="1">
391384
+    <parameter name="hostlist" unique="1" required="0">
391384
       <longdesc lang="en">List of hosts in the cluster</longdesc>
391384
       <shortdesc lang="en">Host list</shortdesc>
391384
       <content type="string" default="" />
391384
@@ -177,9 +177,22 @@ def get_zone(project, instance):
391384
   raise Exception("Unable to find instance %s" % (instance))
391384
 
391384
 
391384
+def get_instances_list(project, exclude):
391384
+  hostlist = []
391384
+  request = CONN.instances().aggregatedList(project=project)
391384
+  while request is not None:
391384
+    response = request.execute()
391384
+    zones = response.get('items', {})
391384
+    for zone in zones.values():
391384
+      for inst in zone.get('instances', []):
391384
+        if inst['name'] != exclude:
391384
+          hostlist.append(inst['name'])
391384
+    request = CONN.instances().aggregatedList_next(
391384
+        previous_request=request, previous_response=response)
391384
+  return hostlist
391384
+
391384
+
391384
 def gcp_alias_start(alias):
391384
-  if not alias:
391384
-    sys.exit(OCF_ERR_CONFIGURED)
391384
   my_alias = get_localhost_alias()
391384
   my_zone = get_metadata('instance/zone').split('/')[-1]
391384
   project = get_metadata('project/project-id')
391384
@@ -196,8 +209,11 @@ def gcp_alias_start(alias):
391384
 
391384
   # Loops through all hosts & remove the alias IP from the host that has it
391384
   hostlist = os.environ.get('OCF_RESKEY_hostlist', '')
391384
-  hostlist.replace(THIS_VM, '')
391384
-  for host in hostlist.split():
391384
+  if hostlist:
391384
+    hostlist.replace(THIS_VM, '').split()
391384
+  else:
391384
+    hostlist = get_instances_list(project, THIS_VM)
391384
+  for host in hostlist:
391384
     host_zone = get_zone(project, host)
391384
     host_alias = get_alias(project, host_zone, host)
391384
     if alias == host_alias:
391384
@@ -227,8 +243,6 @@ def gcp_alias_start(alias):
391384
 
391384
 
391384
 def gcp_alias_stop(alias):
391384
-  if not alias:
391384
-    sys.exit(OCF_ERR_CONFIGURED)
391384
   my_alias = get_localhost_alias()
391384
   my_zone = get_metadata('instance/zone').split('/')[-1]
391384
   project = get_metadata('project/project-id')
391384
@@ -239,8 +253,6 @@ def gcp_alias_stop(alias):
391384
 
391384
 
391384
 def gcp_alias_status(alias):
391384
-  if not alias:
391384
-    sys.exit(OCF_ERR_CONFIGURED)
391384
   my_alias = get_localhost_alias()
391384
   if alias == my_alias:
391384
     logging.info('%s has the correct IP address attached' % THIS_VM)
391384
@@ -280,17 +292,21 @@ def configure():
391384
 
391384
 
391384
 def main():
391384
-  configure()
391384
+  if 'meta-data' in sys.argv[1]:
391384
+    print(METADATA)
391384
+    return
391384
 
391384
   alias = os.environ.get('OCF_RESKEY_alias_ip')
391384
+  if not alias:
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
+
391384
+  configure()
391384
   if 'start' in sys.argv[1]:
391384
     gcp_alias_start(alias)
391384
   elif 'stop' in sys.argv[1]:
391384
     gcp_alias_stop(alias)
391384
   elif 'status' in sys.argv[1] or 'monitor' in sys.argv[1]:
391384
     gcp_alias_status(alias)
391384
-  elif 'meta-data' in sys.argv[1]:
391384
-    print(METADATA)
391384
   else:
391384
     logging.error('gcp:alias - no such function %s' % str(sys.argv[1]))
391384
 
391384
391384
From 1f50c4bc80f23f561a8630c12076707366525899 Mon Sep 17 00:00:00 2001
391384
From: Helen Koike <helen.koike@collabora.com>
391384
Date: Thu, 12 Jul 2018 13:02:16 -0300
391384
Subject: [PATCH 3/4] gcp-vcp-move-vip.in: implement validate-all
391384
391384
Also fix some return errors
391384
---
391384
 heartbeat/gcp-vpc-move-vip.in | 47 +++++++++++++++++++++++++++++++------------
391384
 1 file changed, 34 insertions(+), 13 deletions(-)
391384
391384
diff --git a/heartbeat/gcp-vpc-move-vip.in b/heartbeat/gcp-vpc-move-vip.in
391384
index f3d117bda..a90c2de8d 100755
391384
--- a/heartbeat/gcp-vpc-move-vip.in
391384
+++ b/heartbeat/gcp-vpc-move-vip.in
391384
@@ -22,7 +22,10 @@ import os
391384
 import sys
391384
 import time
391384
 
391384
-import googleapiclient.discovery
391384
+try:
391384
+  import googleapiclient.discovery
391384
+except ImportError:
391384
+  pass
391384
 
391384
 if sys.version_info >= (3, 0):
391384
   # Python 3 imports.
391384
@@ -36,6 +39,7 @@ else:
391384
 
391384
 CONN = None
391384
 THIS_VM = None
391384
+ALIAS = None
391384
 OCF_SUCCESS = 0
391384
 OCF_ERR_GENERIC = 1
391384
 OCF_ERR_CONFIGURED = 6
391384
@@ -210,7 +214,7 @@ def gcp_alias_start(alias):
391384
   # Loops through all hosts & remove the alias IP from the host that has it
391384
   hostlist = os.environ.get('OCF_RESKEY_hostlist', '')
391384
   if hostlist:
391384
-    hostlist.replace(THIS_VM, '').split()
391384
+    hostlist = hostlist.replace(THIS_VM, '').split()
391384
   else:
391384
     hostlist = get_instances_list(project, THIS_VM)
391384
   for host in hostlist:
391384
@@ -260,14 +264,31 @@ def gcp_alias_status(alias):
391384
     sys.exit(OCF_NOT_RUNNING)
391384
 
391384
 
391384
-def configure():
391384
+def validate():
391384
+  global ALIAS
391384
   global CONN
391384
   global THIS_VM
391384
 
391384
   # Populate global vars
391384
-  CONN = googleapiclient.discovery.build('compute', 'v1')
391384
-  THIS_VM = get_metadata('instance/name')
391384
+  try:
391384
+    CONN = googleapiclient.discovery.build('compute', 'v1')
391384
+  except Exception as e:
391384
+    logging.error('Couldn\'t connect with google api: ' + str(e))
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
+
391384
+  try:
391384
+    THIS_VM = get_metadata('instance/name')
391384
+  except Exception as e:
391384
+    logging.error('Couldn\'t get instance name, is this running inside GCE?: ' + str(e))
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
 
391384
+  ALIAS = os.environ.get('OCF_RESKEY_alias_ip')
391384
+  if not ALIAS:
391384
+    logging.error('Missing alias_ip parameter')
391384
+    sys.exit(OCF_ERR_CONFIGURED)
391384
+
391384
+
391384
+def configure_logs():
391384
   # Prepare logging
391384
   logging.basicConfig(
391384
       format='gcp:alias - %(levelname)s - %(message)s', level=logging.INFO)
391384
@@ -296,19 +317,19 @@ def main():
391384
     print(METADATA)
391384
     return
391384
 
391384
-  alias = os.environ.get('OCF_RESKEY_alias_ip')
391384
-  if not alias:
391384
-    sys.exit(OCF_ERR_CONFIGURED)
391384
+  validate()
391384
+  if 'validate-all' in sys.argv[1]:
391384
+    return
391384
 
391384
-  configure()
391384
+  configure_logs()
391384
   if 'start' in sys.argv[1]:
391384
-    gcp_alias_start(alias)
391384
+    gcp_alias_start(ALIAS)
391384
   elif 'stop' in sys.argv[1]:
391384
-    gcp_alias_stop(alias)
391384
+    gcp_alias_stop(ALIAS)
391384
   elif 'status' in sys.argv[1] or 'monitor' in sys.argv[1]:
391384
-    gcp_alias_status(alias)
391384
+    gcp_alias_status(ALIAS)
391384
   else:
391384
-    logging.error('gcp:alias - no such function %s' % str(sys.argv[1]))
391384
+    logging.error('no such function %s' % str(sys.argv[1]))
391384
 
391384
 
391384
 if __name__ == "__main__":
391384
391384
From f11cb236bb348ebee74e962d0ded1cb2fc97bd5f Mon Sep 17 00:00:00 2001
391384
From: Helen Koike <helen.koike@collabora.com>
391384
Date: Fri, 13 Jul 2018 08:01:02 -0300
391384
Subject: [PATCH 4/4] gcp-vpc-move-vip.in: minor fixes
391384
391384
---
391384
 heartbeat/gcp-vpc-move-vip.in | 5 +++--
391384
 1 file changed, 3 insertions(+), 2 deletions(-)
391384
391384
diff --git a/heartbeat/gcp-vpc-move-vip.in b/heartbeat/gcp-vpc-move-vip.in
391384
index a90c2de8d..9fc87242f 100755
391384
--- a/heartbeat/gcp-vpc-move-vip.in
391384
+++ b/heartbeat/gcp-vpc-move-vip.in
391384
@@ -1,4 +1,4 @@
391384
-#!/usr/bin/env python
391384
+#!@PYTHON@ -tt
391384
 # ---------------------------------------------------------------------
391384
 # Copyright 2016 Google Inc.
391384
 #
391384
@@ -59,7 +59,7 @@ METADATA = \
391384
       <shortdesc lang="en">Host list</shortdesc>
391384
       <content type="string" default="" />
391384
     </parameter>
391384
-    <parameter name="stackdriver-logging" unique="0" required="0">
391384
+    <parameter name="stackdriver_logging" unique="0" required="0">
391384
       <longdesc lang="en">If enabled (set to true), IP failover logs will be posted to stackdriver logging</longdesc>
391384
       <shortdesc lang="en">Stackdriver-logging support</shortdesc>
391384
       <content type="boolean" default="" />
391384
@@ -80,6 +80,7 @@ METADATA = \
391384
     <action name="stop" timeout="15" />
391384
     <action name="monitor" timeout="15" interval="60" depth="0" />
391384
     <action name="meta-data" timeout="15" />
391384
+    <action name="validate-all" timeout="15" />
391384
   </actions>
391384
 </resource-agent>'''
391384