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

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