Blame SOURCES/bz1633251-gcp-pd-move-1.patch

919373
From dedf420b8aa7e7e64fa56eeda2d7aeb5b2a5fcd9 Mon Sep 17 00:00:00 2001
919373
From: Gustavo Serra Scalet <gustavo.scalet@collabora.com>
919373
Date: Mon, 17 Sep 2018 12:29:51 -0300
919373
Subject: [PATCH] Add gcp-pd-move python script
919373
919373
---
919373
 configure.ac             |   1 +
919373
 doc/man/Makefile.am      |   1 +
919373
 heartbeat/Makefile.am    |   1 +
919373
 heartbeat/gcp-pd-move.in | 370 +++++++++++++++++++++++++++++++++++++++
919373
 4 files changed, 373 insertions(+)
919373
 create mode 100755 heartbeat/gcp-pd-move.in
919373
919373
diff --git a/configure.ac b/configure.ac
919373
index 10f5314da..b7ffb99f3 100644
919373
--- a/configure.ac
919373
+++ b/configure.ac
919373
@@ -958,6 +958,7 @@ AC_CONFIG_FILES([heartbeat/conntrackd], [chmod +x heartbeat/conntrackd])
919373
 AC_CONFIG_FILES([heartbeat/dnsupdate], [chmod +x heartbeat/dnsupdate])
919373
 AC_CONFIG_FILES([heartbeat/eDir88], [chmod +x heartbeat/eDir88])
919373
 AC_CONFIG_FILES([heartbeat/fio], [chmod +x heartbeat/fio])
919373
+AC_CONFIG_FILES([heartbeat/gcp-pd-move], [chmod +x heartbeat/gcp-pd-move])
919373
 AC_CONFIG_FILES([heartbeat/gcp-vpc-move-ip], [chmod +x heartbeat/gcp-vpc-move-ip])
919373
 AC_CONFIG_FILES([heartbeat/gcp-vpc-move-vip], [chmod +x heartbeat/gcp-vpc-move-vip])
919373
 AC_CONFIG_FILES([heartbeat/gcp-vpc-move-route], [chmod +x heartbeat/gcp-vpc-move-route])
919373
diff --git a/doc/man/Makefile.am b/doc/man/Makefile.am
919373
index 0bef88740..0235c9af6 100644
919373
--- a/doc/man/Makefile.am
919373
+++ b/doc/man/Makefile.am
919373
@@ -115,6 +115,7 @@ man_MANS	       = ocf_heartbeat_AoEtarget.7 \
919373
                           ocf_heartbeat_fio.7 \
919373
                           ocf_heartbeat_galera.7 \
919373
                           ocf_heartbeat_garbd.7 \
919373
+                          ocf_heartbeat_gcp-pd-move.7 \
919373
                           ocf_heartbeat_gcp-vpc-move-ip.7 \
919373
                           ocf_heartbeat_gcp-vpc-move-vip.7 \
919373
                           ocf_heartbeat_gcp-vpc-move-route.7 \
919373
diff --git a/heartbeat/Makefile.am b/heartbeat/Makefile.am
919373
index 993bff042..843186c98 100644
919373
--- a/heartbeat/Makefile.am
919373
+++ b/heartbeat/Makefile.am
919373
@@ -111,6 +111,7 @@ ocf_SCRIPTS	     =  AoEtarget		\
919373
 			fio			\
919373
 			galera			\
919373
 			garbd			\
919373
+			gcp-pd-move		\
919373
 			gcp-vpc-move-ip		\
919373
 			gcp-vpc-move-vip	\
919373
 			gcp-vpc-move-route	\
919373
diff --git a/heartbeat/gcp-pd-move.in b/heartbeat/gcp-pd-move.in
919373
new file mode 100755
919373
index 000000000..f9f6c3163
919373
--- /dev/null
919373
+++ b/heartbeat/gcp-pd-move.in
919373
@@ -0,0 +1,370 @@
919373
+#!@PYTHON@ -tt
919373
+# - *- coding: utf- 8 - *-
919373
+#
919373
+# ---------------------------------------------------------------------
919373
+# Copyright 2018 Google Inc.
919373
+#
919373
+# Licensed under the Apache License, Version 2.0 (the "License");
919373
+# you may not use this file except in compliance with the License.
919373
+# You may obtain a copy of the License at
919373
+#
919373
+# http://www.apache.org/licenses/LICENSE-2.0
919373
+# Unless required by applicable law or agreed to in writing, software
919373
+# distributed under the License is distributed on an "AS IS" BASIS,
919373
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
919373
+# See the License for the specific language governing permissions and
919373
+# limitations under the License.
919373
+# ---------------------------------------------------------------------
919373
+# Description:	Google Cloud Platform - Disk attach
919373
+# ---------------------------------------------------------------------
919373
+
919373
+import json
919373
+import logging
919373
+import os
919373
+import re
919373
+import sys
919373
+import time
919373
+
919373
+OCF_FUNCTIONS_DIR = "%s/lib/heartbeat" % os.environ.get("OCF_ROOT")
919373
+sys.path.append(OCF_FUNCTIONS_DIR)
919373
+
919373
+import ocf
919373
+
919373
+try:
919373
+  import googleapiclient.discovery
919373
+except ImportError:
919373
+  pass
919373
+
919373
+if sys.version_info >= (3, 0):
919373
+  # Python 3 imports.
919373
+  import urllib.parse as urlparse
919373
+  import urllib.request as urlrequest
919373
+else:
919373
+  # Python 2 imports.
919373
+  import urllib as urlparse
919373
+  import urllib2 as urlrequest
919373
+
919373
+
919373
+CONN = None
919373
+PROJECT = None
919373
+ZONE = None
919373
+REGION = None
919373
+LIST_DISK_ATTACHED_INSTANCES = None
919373
+INSTANCE_NAME = None
919373
+
919373
+PARAMETERS = {
919373
+  'disk_name': None,
919373
+  'disk_scope': None,
919373
+  'disk_csek_file': None,
919373
+  'mode': None,
919373
+  'device_name': None,
919373
+}
919373
+
919373
+MANDATORY_PARAMETERS = ['disk_name', 'disk_scope']
919373
+
919373
+METADATA_SERVER = 'http://metadata.google.internal/computeMetadata/v1/'
919373
+METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
919373
+METADATA = '''
919373
+
919373
+<resource-agent name="gcp-pd-move">
919373
+<version>1.0</version>
919373
+<longdesc lang="en">
919373
+Resource Agent that can attach or detach a regional/zonal disk on current GCP
919373
+instance.
919373
+Requirements :
919373
+- Disk has to be properly created as regional/zonal in order to be used
919373
+correctly.
919373
+</longdesc>
919373
+<shortdesc lang="en">Attach/Detach a persistent disk on current GCP instance</shortdesc>
919373
+<parameters>
919373
+<parameter name="disk_name" unique="1" required="1">
919373
+<longdesc lang="en">The name of the GCP disk.</longdesc>
919373
+<shortdesc lang="en">Disk name</shortdesc>
919373
+<content type="string" default="" />
919373
+</parameter>
919373
+<parameter name="disk_scope" unique="1" required="1">
919373
+<longdesc lang="en">Disk scope </longdesc>
919373
+<shortdesc lang="en">Network name</shortdesc>
919373
+<content type="string" default="regional" />
919373
+</parameter>
919373
+<parameter name="disk_csek_file" unique="1" required="0">
919373
+<longdesc lang="en">Path to a Customer-Supplied Encryption Key (CSEK) key file</longdesc>
919373
+<shortdesc lang="en">Customer-Supplied Encryption Key file</shortdesc>
919373
+<content type="string" default="" />
919373
+</parameter>
919373
+<parameter name="mode" unique="1" required="0">
919373
+<longdesc lang="en">Attachment mode (rw, ro)</longdesc>
919373
+<shortdesc lang="en">Attachment mode</shortdesc>
919373
+<content type="string" default="rw" />
919373
+</parameter>
919373
+<parameter name="device_name" unique="0" required="0">
919373
+<longdesc lang="en">An optional name that indicates the disk name the guest operating system will see.</longdesc>
919373
+<shortdesc lang="en">Optional device name</shortdesc>
919373
+<content type="boolean" default="" />
919373
+</parameter>
919373
+</parameters>
919373
+<actions>
919373
+<action name="start" timeout="300s" />
919373
+<action name="stop" timeout="15s" />
919373
+<action name="monitor" timeout="15s" interval="10s" depth="0" />
919373
+<action name="meta-data" timeout="5s" />
919373
+</actions>
919373
+</resource-agent>'''
919373
+
919373
+
919373
+def get_metadata(metadata_key, params=None, timeout=None):
919373
+  """Performs a GET request with the metadata headers.
919373
+
919373
+  Args:
919373
+    metadata_key: string, the metadata to perform a GET request on.
919373
+    params: dictionary, the query parameters in the GET request.
919373
+    timeout: int, timeout in seconds for metadata requests.
919373
+
919373
+  Returns:
919373
+    HTTP response from the GET request.
919373
+
919373
+  Raises:
919373
+    urlerror.HTTPError: raises when the GET request fails.
919373
+  """
919373
+  timeout = timeout or 60
919373
+  metadata_url = os.path.join(METADATA_SERVER, metadata_key)
919373
+  params = urlparse.urlencode(params or {})
919373
+  url = '%s?%s' % (metadata_url, params)
919373
+  request = urlrequest.Request(url, headers=METADATA_HEADERS)
919373
+  request_opener = urlrequest.build_opener(urlrequest.ProxyHandler({}))
919373
+  return request_opener.open(request, timeout=timeout * 1.1).read()
919373
+
919373
+
919373
+def populate_vars():
919373
+  global CONN
919373
+  global INSTANCE_NAME
919373
+  global PROJECT
919373
+  global ZONE
919373
+  global REGION
919373
+  global LIST_DISK_ATTACHED_INSTANCES
919373
+
919373
+  global PARAMETERS
919373
+
919373
+  # Populate global vars
919373
+  try:
919373
+    CONN = googleapiclient.discovery.build('compute', 'v1')
919373
+  except Exception as e:
919373
+    logger.error('Couldn\'t connect with google api: ' + str(e))
919373
+    sys.exit(ocf.OCF_ERR_CONFIGURED)
919373
+
919373
+  for param in PARAMETERS:
919373
+    value = os.environ.get('OCF_RESKEY_%s' % param, None)
919373
+    if not value and param in MANDATORY_PARAMETERS:
919373
+      logger.error('Missing %s mandatory parameter' % param)
919373
+      sys.exit(ocf.OCF_ERR_CONFIGURED)
919373
+    PARAMETERS[param] = value
919373
+
919373
+  try:
919373
+    INSTANCE_NAME = get_metadata('instance/name')
919373
+  except Exception as e:
919373
+    logger.error(
919373
+        'Couldn\'t get instance name, is this running inside GCE?: ' + str(e))
919373
+    sys.exit(ocf.OCF_ERR_CONFIGURED)
919373
+
919373
+  PROJECT = get_metadata('project/project-id')
919373
+  ZONE = get_metadata('instance/zone').split('/')[-1]
919373
+  REGION = ZONE[:-2]
919373
+  LIST_DISK_ATTACHED_INSTANCES = get_disk_attached_instances(
919373
+      PARAMETERS['disk_name'])
919373
+
919373
+
919373
+def configure_logs():
919373
+  # Prepare logging
919373
+  global logger
919373
+  logging.getLogger('googleapiclient').setLevel(logging.WARN)
919373
+  logging_env = os.environ.get('OCF_RESKEY_stackdriver_logging')
919373
+  if logging_env:
919373
+    logging_env = logging_env.lower()
919373
+    if any(x in logging_env for x in ['yes', 'true', 'enabled']):
919373
+      try:
919373
+        import google.cloud.logging.handlers
919373
+        client = google.cloud.logging.Client()
919373
+        handler = google.cloud.logging.handlers.CloudLoggingHandler(
919373
+            client, name=INSTANCE_NAME)
919373
+        handler.setLevel(logging.INFO)
919373
+        formatter = logging.Formatter('gcp:alias "%(message)s"')
919373
+        handler.setFormatter(formatter)
919373
+        ocf.log.addHandler(handler)
919373
+        logger = logging.LoggerAdapter(
919373
+            ocf.log, {'OCF_RESOURCE_INSTANCE': ocf.OCF_RESOURCE_INSTANCE})
919373
+      except ImportError:
919373
+        logger.error('Couldn\'t import google.cloud.logging, '
919373
+            'disabling Stackdriver-logging support')
919373
+
919373
+
919373
+def wait_for_operation(operation):
919373
+  while True:
919373
+    result = CONN.zoneOperations().get(
919373
+        project=PROJECT,
919373
+        zone=ZONE,
919373
+        operation=operation['name']).execute()
919373
+
919373
+    if result['status'] == 'DONE':
919373
+      if 'error' in result:
919373
+        raise Exception(result['error'])
919373
+      return
919373
+    time.sleep(1)
919373
+
919373
+
919373
+def get_disk_attached_instances(disk):
919373
+  def get_users_list():
919373
+    fl = 'name="%s"' % disk
919373
+    request = CONN.disks().aggregatedList(project=PROJECT, filter=fl)
919373
+    while request is not None:
919373
+      response = request.execute()
919373
+      locations = response.get('items', {})
919373
+      for location in locations.values():
919373
+        for d in location.get('disks', []):
919373
+          if d['name'] == disk:
919373
+            return d.get('users', [])
919373
+      request = CONN.instances().aggregatedList_next(
919373
+          previous_request=request, previous_response=response)
919373
+    raise Exception("Unable to find disk %s" % disk)
919373
+
919373
+  def get_only_instance_name(user):
919373
+    return re.sub('.*/instances/', '', user)
919373
+
919373
+  return map(get_only_instance_name, get_users_list())
919373
+
919373
+
919373
+def is_disk_attached(instance):
919373
+  return instance in LIST_DISK_ATTACHED_INSTANCES
919373
+
919373
+
919373
+def detach_disk(instance, disk_name):
919373
+  # Python API misses disk-scope argument.
919373
+
919373
+  # Detaching a disk is only possible by using deviceName, which is retrieved
919373
+  # as a disk parameter when listing the instance information
919373
+  request = CONN.instances().get(
919373
+      project=PROJECT, zone=ZONE, instance=instance)
919373
+  response = request.execute()
919373
+
919373
+  device_name = None
919373
+  for disk in response['disks']:
919373
+    if disk_name in disk['source']:
919373
+      device_name = disk['deviceName']
919373
+      break
919373
+
919373
+  if not device_name:
919373
+    logger.error("Didn't find %(d)s deviceName attached to %(i)s" % {
919373
+        'd': disk_name,
919373
+        'i': instance,
919373
+    })
919373
+    return
919373
+
919373
+  request = CONN.instances().detachDisk(
919373
+      project=PROJECT, zone=ZONE, instance=instance, deviceName=device_name)
919373
+  wait_for_operation(request.execute())
919373
+
919373
+
919373
+def attach_disk(instance, disk_name):
919373
+  location = 'zones/%s' % ZONE
919373
+  if PARAMETERS['disk_scope'] == 'regional':
919373
+    location = 'regions/%s' % REGION
919373
+  prefix = 'https://www.googleapis.com/compute/v1'
919373
+  body = {
919373
+    'source': '%(prefix)s/projects/%(project)s/%(location)s/disks/%(disk)s' % {
919373
+        'prefix': prefix,
919373
+        'project': PROJECT,
919373
+        'location': location,
919373
+        'disk': disk_name,
919373
+    },
919373
+  }
919373
+
919373
+  # Customer-Supplied Encryption Key (CSEK)
919373
+  if PARAMETERS['disk_csek_file']:
919373
+    with open(PARAMETERS['disk_csek_file']) as csek_file:
919373
+      body['diskEncryptionKey'] = {
919373
+          'rawKey': csek_file.read(),
919373
+      }
919373
+
919373
+  if PARAMETERS['device_name']:
919373
+    body['deviceName'] = PARAMETERS['device_name']
919373
+
919373
+  if PARAMETERS['mode']:
919373
+    body['mode'] = PARAMETERS['mode']
919373
+
919373
+  force_attach = None
919373
+  if PARAMETERS['disk_scope'] == 'regional':
919373
+    # Python API misses disk-scope argument.
919373
+    force_attach = True
919373
+  else:
919373
+    # If this disk is attached to some instance, detach it first.
919373
+    for other_instance in LIST_DISK_ATTACHED_INSTANCES:
919373
+      logger.info("Detaching disk %(disk_name)s from other instance %(i)s" % {
919373
+          'disk_name': PARAMETERS['disk_name'],
919373
+          'i': other_instance,
919373
+      })
919373
+      detach_disk(other_instance, PARAMETERS['disk_name'])
919373
+
919373
+  request = CONN.instances().attachDisk(
919373
+      project=PROJECT, zone=ZONE, instance=instance, body=body,
919373
+      forceAttach=force_attach)
919373
+  wait_for_operation(request.execute())
919373
+
919373
+
919373
+def fetch_data():
919373
+  configure_logs()
919373
+  populate_vars()
919373
+
919373
+
919373
+def gcp_pd_move_start():
919373
+  fetch_data()
919373
+  if not is_disk_attached(INSTANCE_NAME):
919373
+    logger.info("Attaching disk %(disk_name)s to %(instance)s" % {
919373
+        'disk_name': PARAMETERS['disk_name'],
919373
+        'instance': INSTANCE_NAME,
919373
+    })
919373
+    attach_disk(INSTANCE_NAME, PARAMETERS['disk_name'])
919373
+
919373
+
919373
+def gcp_pd_move_stop():
919373
+  fetch_data()
919373
+  if is_disk_attached(INSTANCE_NAME):
919373
+    logger.info("Detaching disk %(disk_name)s to %(instance)s" % {
919373
+        'disk_name': PARAMETERS['disk_name'],
919373
+        'instance': INSTANCE_NAME,
919373
+    })
919373
+    detach_disk(INSTANCE_NAME, PARAMETERS['disk_name'])
919373
+
919373
+
919373
+def gcp_pd_move_status():
919373
+  fetch_data()
919373
+  if is_disk_attached(INSTANCE_NAME):
919373
+    logger.info("Disk %(disk_name)s is correctly attached to %(instance)s" % {
919373
+        'disk_name': PARAMETERS['disk_name'],
919373
+        'instance': INSTANCE_NAME,
919373
+    })
919373
+  else:
919373
+    sys.exit(ocf.OCF_NOT_RUNNING)
919373
+
919373
+
919373
+def main():
919373
+  if len(sys.argv) < 2:
919373
+    logger.error('Missing argument')
919373
+    return
919373
+
919373
+  command = sys.argv[1]
919373
+  if 'meta-data' in command:
919373
+    print(METADATA)
919373
+    return
919373
+
919373
+  if command in 'start':
919373
+    gcp_pd_move_start()
919373
+  elif command in 'stop':
919373
+    gcp_pd_move_stop()
919373
+  elif command in ('monitor', 'status'):
919373
+    gcp_pd_move_status()
919373
+  else:
919373
+    configure_logs()
919373
+    logger.error('no such function %s' % str(command))
919373
+
919373
+
919373
+if __name__ == "__main__":
919373
+  main()