CA-355289: ensure xapi is initialised before starting GC

From: Mark Syms <mark.syms@citrix.com>

Signed-off-by: Mark Syms <mark.syms@citrix.com>
---
 drivers/cleanup.py |   25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/drivers/cleanup.py b/drivers/cleanup.py
index f8eb188..9d84134 100755
--- a/drivers/cleanup.py
+++ b/drivers/cleanup.py
@@ -2867,8 +2867,33 @@ def _gcLoop(sr, dryRun):
         _create_init_file(sr.uuid)
         lockActive.release()
 
+
+def _xapi_enabled(session, hostref):
+    host = session.xenapi.host.get_record(hostref)
+    return host['enabled']
+
+
+def _ensure_xapi_initialised(session):
+    """
+    Don't want to start GC until Xapi is fully initialised
+    """
+    local_session = None
+    if not session:
+        local_session = util.get_localAPI_session()
+        session = local_session
+
+    try:
+        hostref = session.xenapi.host.get_by_uuid(util.get_this_host())
+        while not _xapi_enabled(session, hostref):
+            util.SMlog("Xapi not ready, GC waiting")
+            time.sleep(15)
+    finally:
+        if local_session is not None:
+            local_session.logout()
+
 def _gc(session, srUuid, dryRun):
     init(srUuid)
+    _ensure_xapi_initialised(session)
     sr = SR.getInstance(srUuid, session)
     if not sr.gcEnabled(False):
         return
