sailesh1993 / rpms / cloud-init

Forked from rpms/cloud-init 10 months ago
Clone
0a07cd
From a758c579c707df04734efb4390bd4d45ff398eab Mon Sep 17 00:00:00 2001
0a07cd
From: Eduardo Otubo <otubo@redhat.com>
0a07cd
Date: Wed, 29 May 2019 13:41:47 +0200
0a07cd
Subject: [PATCH 3/5] Azure: Changes to the Hyper-V KVP Reporter
0a07cd
MIME-Version: 1.0
0a07cd
Content-Type: text/plain; charset=UTF-8
0a07cd
Content-Transfer-Encoding: 8bit
0a07cd
0a07cd
RH-Author: Eduardo Otubo <otubo@redhat.com>
0a07cd
Message-id: <20190529134149.842-4-otubo@redhat.com>
0a07cd
Patchwork-id: 88266
0a07cd
O-Subject: [RHEL-8.0.1/RHEL-8.1.0 cloud-init PATCHv2 3/5] Azure: Changes to the Hyper-V KVP Reporter
0a07cd
Bugzilla: 1648375
0a07cd
RH-Acked-by: Vitaly Kuznetsov <vkuznets@redhat.com>
0a07cd
RH-Acked-by: Cathy Avery <cavery@redhat.com>
0a07cd
0a07cd
From: Anh Vo <anhvo@microsoft.com>
0a07cd
commit 86674f013dfcea3c075ab41373ffb475881066f6
0a07cd
Author: Anh Vo <anhvo@microsoft.com>
0a07cd
Date:   Mon Apr 29 20:22:16 2019 +0000
0a07cd
0a07cd
    Azure: Changes to the Hyper-V KVP Reporter
0a07cd
0a07cd
     + Truncate KVP Pool file to prevent stale entries from
0a07cd
       being processed by the Hyper-V KVP reporter.
0a07cd
     + Drop filtering of KVPs as it is no longer needed.
0a07cd
     + Batch appending of existing KVP entries.
0a07cd
0a07cd
Signed-off-by: Eduardo Otubo <otubo@redhat.com>
0a07cd
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
0a07cd
---
0a07cd
 cloudinit/reporting/handlers.py          | 117 +++++++++++++++----------------
0a07cd
 tests/unittests/test_reporting_hyperv.py | 104 +++++++++++++--------------
0a07cd
 2 files changed, 106 insertions(+), 115 deletions(-)
0a07cd
 mode change 100644 => 100755 cloudinit/reporting/handlers.py
0a07cd
 mode change 100644 => 100755 tests/unittests/test_reporting_hyperv.py
0a07cd
0a07cd
diff --git a/cloudinit/reporting/handlers.py b/cloudinit/reporting/handlers.py
0a07cd
old mode 100644
0a07cd
new mode 100755
0a07cd
index 6d23558..10165ae
0a07cd
--- a/cloudinit/reporting/handlers.py
0a07cd
+++ b/cloudinit/reporting/handlers.py
0a07cd
@@ -5,7 +5,6 @@ import fcntl
0a07cd
 import json
0a07cd
 import six
0a07cd
 import os
0a07cd
-import re
0a07cd
 import struct
0a07cd
 import threading
0a07cd
 import time
0a07cd
@@ -14,6 +13,7 @@ from cloudinit import log as logging
0a07cd
 from cloudinit.registry import DictRegistry
0a07cd
 from cloudinit import (url_helper, util)
0a07cd
 from datetime import datetime
0a07cd
+from six.moves.queue import Empty as QueueEmptyError
0a07cd
 
0a07cd
 if six.PY2:
0a07cd
     from multiprocessing.queues import JoinableQueue as JQueue
0a07cd
@@ -129,24 +129,50 @@ class HyperVKvpReportingHandler(ReportingHandler):
0a07cd
     DESC_IDX_KEY = 'msg_i'
0a07cd
     JSON_SEPARATORS = (',', ':')
0a07cd
     KVP_POOL_FILE_GUEST = '/var/lib/hyperv/.kvp_pool_1'
0a07cd
+    _already_truncated_pool_file = False
0a07cd
 
0a07cd
     def __init__(self,
0a07cd
                  kvp_file_path=KVP_POOL_FILE_GUEST,
0a07cd
                  event_types=None):
0a07cd
         super(HyperVKvpReportingHandler, self).__init__()
0a07cd
         self._kvp_file_path = kvp_file_path
0a07cd
+        HyperVKvpReportingHandler._truncate_guest_pool_file(
0a07cd
+            self._kvp_file_path)
0a07cd
+
0a07cd
         self._event_types = event_types
0a07cd
         self.q = JQueue()
0a07cd
-        self.kvp_file = None
0a07cd
         self.incarnation_no = self._get_incarnation_no()
0a07cd
         self.event_key_prefix = u"{0}|{1}".format(self.EVENT_PREFIX,
0a07cd
                                                   self.incarnation_no)
0a07cd
-        self._current_offset = 0
0a07cd
         self.publish_thread = threading.Thread(
0a07cd
                 target=self._publish_event_routine)
0a07cd
         self.publish_thread.daemon = True
0a07cd
         self.publish_thread.start()
0a07cd
 
0a07cd
+    @classmethod
0a07cd
+    def _truncate_guest_pool_file(cls, kvp_file):
0a07cd
+        """
0a07cd
+        Truncate the pool file if it has not been truncated since boot.
0a07cd
+        This should be done exactly once for the file indicated by
0a07cd
+        KVP_POOL_FILE_GUEST constant above. This method takes a filename
0a07cd
+        so that we can use an arbitrary file during unit testing.
0a07cd
+        Since KVP is a best-effort telemetry channel we only attempt to
0a07cd
+        truncate the file once and only if the file has not been modified
0a07cd
+        since boot. Additional truncation can lead to loss of existing
0a07cd
+        KVPs.
0a07cd
+        """
0a07cd
+        if cls._already_truncated_pool_file:
0a07cd
+            return
0a07cd
+        boot_time = time.time() - float(util.uptime())
0a07cd
+        try:
0a07cd
+            if os.path.getmtime(kvp_file) < boot_time:
0a07cd
+                with open(kvp_file, "w"):
0a07cd
+                    pass
0a07cd
+        except (OSError, IOError) as e:
0a07cd
+            LOG.warning("failed to truncate kvp pool file, %s", e)
0a07cd
+        finally:
0a07cd
+            cls._already_truncated_pool_file = True
0a07cd
+
0a07cd
     def _get_incarnation_no(self):
0a07cd
         """
0a07cd
         use the time passed as the incarnation number.
0a07cd
@@ -162,20 +188,15 @@ class HyperVKvpReportingHandler(ReportingHandler):
0a07cd
 
0a07cd
     def _iterate_kvps(self, offset):
0a07cd
         """iterate the kvp file from the current offset."""
0a07cd
-        try:
0a07cd
-            with open(self._kvp_file_path, 'rb+') as f:
0a07cd
-                self.kvp_file = f
0a07cd
-                fcntl.flock(f, fcntl.LOCK_EX)
0a07cd
-                f.seek(offset)
0a07cd
+        with open(self._kvp_file_path, 'rb') as f:
0a07cd
+            fcntl.flock(f, fcntl.LOCK_EX)
0a07cd
+            f.seek(offset)
0a07cd
+            record_data = f.read(self.HV_KVP_RECORD_SIZE)
0a07cd
+            while len(record_data) == self.HV_KVP_RECORD_SIZE:
0a07cd
+                kvp_item = self._decode_kvp_item(record_data)
0a07cd
+                yield kvp_item
0a07cd
                 record_data = f.read(self.HV_KVP_RECORD_SIZE)
0a07cd
-                while len(record_data) == self.HV_KVP_RECORD_SIZE:
0a07cd
-                    self._current_offset += self.HV_KVP_RECORD_SIZE
0a07cd
-                    kvp_item = self._decode_kvp_item(record_data)
0a07cd
-                    yield kvp_item
0a07cd
-                    record_data = f.read(self.HV_KVP_RECORD_SIZE)
0a07cd
-                fcntl.flock(f, fcntl.LOCK_UN)
0a07cd
-        finally:
0a07cd
-            self.kvp_file = None
0a07cd
+            fcntl.flock(f, fcntl.LOCK_UN)
0a07cd
 
0a07cd
     def _event_key(self, event):
0a07cd
         """
0a07cd
@@ -207,23 +228,13 @@ class HyperVKvpReportingHandler(ReportingHandler):
0a07cd
 
0a07cd
         return {'key': k, 'value': v}
0a07cd
 
0a07cd
-    def _update_kvp_item(self, record_data):
0a07cd
-        if self.kvp_file is None:
0a07cd
-            raise ReportException(
0a07cd
-                "kvp file '{0}' not opened."
0a07cd
-                .format(self._kvp_file_path))
0a07cd
-        self.kvp_file.seek(-self.HV_KVP_RECORD_SIZE, 1)
0a07cd
-        self.kvp_file.write(record_data)
0a07cd
-
0a07cd
     def _append_kvp_item(self, record_data):
0a07cd
-        with open(self._kvp_file_path, 'rb+') as f:
0a07cd
+        with open(self._kvp_file_path, 'ab') as f:
0a07cd
             fcntl.flock(f, fcntl.LOCK_EX)
0a07cd
-            # seek to end of the file
0a07cd
-            f.seek(0, 2)
0a07cd
-            f.write(record_data)
0a07cd
+            for data in record_data:
0a07cd
+                f.write(data)
0a07cd
             f.flush()
0a07cd
             fcntl.flock(f, fcntl.LOCK_UN)
0a07cd
-            self._current_offset = f.tell()
0a07cd
 
0a07cd
     def _break_down(self, key, meta_data, description):
0a07cd
         del meta_data[self.MSG_KEY]
0a07cd
@@ -279,40 +290,26 @@ class HyperVKvpReportingHandler(ReportingHandler):
0a07cd
 
0a07cd
     def _publish_event_routine(self):
0a07cd
         while True:
0a07cd
+            items_from_queue = 0
0a07cd
             try:
0a07cd
                 event = self.q.get(block=True)
0a07cd
-                need_append = True
0a07cd
+                items_from_queue += 1
0a07cd
+                encoded_data = []
0a07cd
+                while event is not None:
0a07cd
+                    encoded_data += self._encode_event(event)
0a07cd
+                    try:
0a07cd
+                        # get all the rest of the events in the queue
0a07cd
+                        event = self.q.get(block=False)
0a07cd
+                        items_from_queue += 1
0a07cd
+                    except QueueEmptyError:
0a07cd
+                        event = None
0a07cd
                 try:
0a07cd
-                    if not os.path.exists(self._kvp_file_path):
0a07cd
-                        LOG.warning(
0a07cd
-                            "skip writing events %s to %s. file not present.",
0a07cd
-                            event.as_string(),
0a07cd
-                            self._kvp_file_path)
0a07cd
-                    encoded_event = self._encode_event(event)
0a07cd
-                    # for each encoded_event
0a07cd
-                    for encoded_data in (encoded_event):
0a07cd
-                        for kvp in self._iterate_kvps(self._current_offset):
0a07cd
-                            match = (
0a07cd
-                                re.match(
0a07cd
-                                    r"^{0}\|(\d+)\|.+"
0a07cd
-                                    .format(self.EVENT_PREFIX),
0a07cd
-                                    kvp['key']
0a07cd
-                                ))
0a07cd
-                            if match:
0a07cd
-                                match_groups = match.groups(0)
0a07cd
-                                if int(match_groups[0]) < self.incarnation_no:
0a07cd
-                                    need_append = False
0a07cd
-                                    self._update_kvp_item(encoded_data)
0a07cd
-                                    continue
0a07cd
-                        if need_append:
0a07cd
-                            self._append_kvp_item(encoded_data)
0a07cd
-                except IOError as e:
0a07cd
-                    LOG.warning(
0a07cd
-                        "failed posting event to kvp: %s e:%s",
0a07cd
-                        event.as_string(), e)
0a07cd
+                    self._append_kvp_item(encoded_data)
0a07cd
+                except (OSError, IOError) as e:
0a07cd
+                    LOG.warning("failed posting events to kvp, %s", e)
0a07cd
                 finally:
0a07cd
-                    self.q.task_done()
0a07cd
-
0a07cd
+                    for _ in range(items_from_queue):
0a07cd
+                        self.q.task_done()
0a07cd
             # when main process exits, q.get() will through EOFError
0a07cd
             # indicating we should exit this thread.
0a07cd
             except EOFError:
0a07cd
@@ -322,7 +319,7 @@ class HyperVKvpReportingHandler(ReportingHandler):
0a07cd
     # if the kvp pool already contains a chunk of data,
0a07cd
     # so defer it to another thread.
0a07cd
     def publish_event(self, event):
0a07cd
-        if (not self._event_types or event.event_type in self._event_types):
0a07cd
+        if not self._event_types or event.event_type in self._event_types:
0a07cd
             self.q.put(event)
0a07cd
 
0a07cd
     def flush(self):
0a07cd
diff --git a/tests/unittests/test_reporting_hyperv.py b/tests/unittests/test_reporting_hyperv.py
0a07cd
old mode 100644
0a07cd
new mode 100755
0a07cd
index 2e64c6c..d01ed5b
0a07cd
--- a/tests/unittests/test_reporting_hyperv.py
0a07cd
+++ b/tests/unittests/test_reporting_hyperv.py
0a07cd
@@ -1,10 +1,12 @@
0a07cd
 # This file is part of cloud-init. See LICENSE file for license information.
0a07cd
 
0a07cd
 from cloudinit.reporting import events
0a07cd
-from cloudinit.reporting import handlers
0a07cd
+from cloudinit.reporting.handlers import HyperVKvpReportingHandler
0a07cd
 
0a07cd
 import json
0a07cd
 import os
0a07cd
+import struct
0a07cd
+import time
0a07cd
 
0a07cd
 from cloudinit import util
0a07cd
 from cloudinit.tests.helpers import CiTestCase
0a07cd
@@ -13,7 +15,7 @@ from cloudinit.tests.helpers import CiTestCase
0a07cd
 class TestKvpEncoding(CiTestCase):
0a07cd
     def test_encode_decode(self):
0a07cd
         kvp = {'key': 'key1', 'value': 'value1'}
0a07cd
-        kvp_reporting = handlers.HyperVKvpReportingHandler()
0a07cd
+        kvp_reporting = HyperVKvpReportingHandler()
0a07cd
         data = kvp_reporting._encode_kvp_item(kvp['key'], kvp['value'])
0a07cd
         self.assertEqual(len(data), kvp_reporting.HV_KVP_RECORD_SIZE)
0a07cd
         decoded_kvp = kvp_reporting._decode_kvp_item(data)
0a07cd
@@ -26,57 +28,9 @@ class TextKvpReporter(CiTestCase):
0a07cd
         self.tmp_file_path = self.tmp_path('kvp_pool_file')
0a07cd
         util.ensure_file(self.tmp_file_path)
0a07cd
 
0a07cd
-    def test_event_type_can_be_filtered(self):
0a07cd
-        reporter = handlers.HyperVKvpReportingHandler(
0a07cd
-            kvp_file_path=self.tmp_file_path,
0a07cd
-            event_types=['foo', 'bar'])
0a07cd
-
0a07cd
-        reporter.publish_event(
0a07cd
-            events.ReportingEvent('foo', 'name', 'description'))
0a07cd
-        reporter.publish_event(
0a07cd
-            events.ReportingEvent('some_other', 'name', 'description3'))
0a07cd
-        reporter.q.join()
0a07cd
-
0a07cd
-        kvps = list(reporter._iterate_kvps(0))
0a07cd
-        self.assertEqual(1, len(kvps))
0a07cd
-
0a07cd
-        reporter.publish_event(
0a07cd
-            events.ReportingEvent('bar', 'name', 'description2'))
0a07cd
-        reporter.q.join()
0a07cd
-        kvps = list(reporter._iterate_kvps(0))
0a07cd
-        self.assertEqual(2, len(kvps))
0a07cd
-
0a07cd
-        self.assertIn('foo', kvps[0]['key'])
0a07cd
-        self.assertIn('bar', kvps[1]['key'])
0a07cd
-        self.assertNotIn('some_other', kvps[0]['key'])
0a07cd
-        self.assertNotIn('some_other', kvps[1]['key'])
0a07cd
-
0a07cd
-    def test_events_are_over_written(self):
0a07cd
-        reporter = handlers.HyperVKvpReportingHandler(
0a07cd
-            kvp_file_path=self.tmp_file_path)
0a07cd
-
0a07cd
-        self.assertEqual(0, len(list(reporter._iterate_kvps(0))))
0a07cd
-
0a07cd
-        reporter.publish_event(
0a07cd
-            events.ReportingEvent('foo', 'name1', 'description'))
0a07cd
-        reporter.publish_event(
0a07cd
-            events.ReportingEvent('foo', 'name2', 'description'))
0a07cd
-        reporter.q.join()
0a07cd
-        self.assertEqual(2, len(list(reporter._iterate_kvps(0))))
0a07cd
-
0a07cd
-        reporter2 = handlers.HyperVKvpReportingHandler(
0a07cd
-            kvp_file_path=self.tmp_file_path)
0a07cd
-        reporter2.incarnation_no = reporter.incarnation_no + 1
0a07cd
-        reporter2.publish_event(
0a07cd
-            events.ReportingEvent('foo', 'name3', 'description'))
0a07cd
-        reporter2.q.join()
0a07cd
-
0a07cd
-        self.assertEqual(2, len(list(reporter2._iterate_kvps(0))))
0a07cd
-
0a07cd
     def test_events_with_higher_incarnation_not_over_written(self):
0a07cd
-        reporter = handlers.HyperVKvpReportingHandler(
0a07cd
+        reporter = HyperVKvpReportingHandler(
0a07cd
             kvp_file_path=self.tmp_file_path)
0a07cd
-
0a07cd
         self.assertEqual(0, len(list(reporter._iterate_kvps(0))))
0a07cd
 
0a07cd
         reporter.publish_event(
0a07cd
@@ -86,7 +40,7 @@ class TextKvpReporter(CiTestCase):
0a07cd
         reporter.q.join()
0a07cd
         self.assertEqual(2, len(list(reporter._iterate_kvps(0))))
0a07cd
 
0a07cd
-        reporter3 = handlers.HyperVKvpReportingHandler(
0a07cd
+        reporter3 = HyperVKvpReportingHandler(
0a07cd
             kvp_file_path=self.tmp_file_path)
0a07cd
         reporter3.incarnation_no = reporter.incarnation_no - 1
0a07cd
         reporter3.publish_event(
0a07cd
@@ -95,7 +49,7 @@ class TextKvpReporter(CiTestCase):
0a07cd
         self.assertEqual(3, len(list(reporter3._iterate_kvps(0))))
0a07cd
 
0a07cd
     def test_finish_event_result_is_logged(self):
0a07cd
-        reporter = handlers.HyperVKvpReportingHandler(
0a07cd
+        reporter = HyperVKvpReportingHandler(
0a07cd
             kvp_file_path=self.tmp_file_path)
0a07cd
         reporter.publish_event(
0a07cd
             events.FinishReportingEvent('name2', 'description1',
0a07cd
@@ -105,7 +59,7 @@ class TextKvpReporter(CiTestCase):
0a07cd
 
0a07cd
     def test_file_operation_issue(self):
0a07cd
         os.remove(self.tmp_file_path)
0a07cd
-        reporter = handlers.HyperVKvpReportingHandler(
0a07cd
+        reporter = HyperVKvpReportingHandler(
0a07cd
             kvp_file_path=self.tmp_file_path)
0a07cd
         reporter.publish_event(
0a07cd
             events.FinishReportingEvent('name2', 'description1',
0a07cd
@@ -113,7 +67,7 @@ class TextKvpReporter(CiTestCase):
0a07cd
         reporter.q.join()
0a07cd
 
0a07cd
     def test_event_very_long(self):
0a07cd
-        reporter = handlers.HyperVKvpReportingHandler(
0a07cd
+        reporter = HyperVKvpReportingHandler(
0a07cd
             kvp_file_path=self.tmp_file_path)
0a07cd
         description = 'ab' * reporter.HV_KVP_EXCHANGE_MAX_VALUE_SIZE
0a07cd
         long_event = events.FinishReportingEvent(
0a07cd
@@ -132,3 +86,43 @@ class TextKvpReporter(CiTestCase):
0a07cd
             self.assertEqual(msg_slice['msg_i'], i)
0a07cd
             full_description += msg_slice['msg']
0a07cd
         self.assertEqual(description, full_description)
0a07cd
+
0a07cd
+    def test_not_truncate_kvp_file_modified_after_boot(self):
0a07cd
+        with open(self.tmp_file_path, "wb+") as f:
0a07cd
+            kvp = {'key': 'key1', 'value': 'value1'}
0a07cd
+            data = (struct.pack("%ds%ds" % (
0a07cd
+                    HyperVKvpReportingHandler.HV_KVP_EXCHANGE_MAX_KEY_SIZE,
0a07cd
+                    HyperVKvpReportingHandler.HV_KVP_EXCHANGE_MAX_VALUE_SIZE),
0a07cd
+                    kvp['key'].encode('utf-8'), kvp['value'].encode('utf-8')))
0a07cd
+            f.write(data)
0a07cd
+        cur_time = time.time()
0a07cd
+        os.utime(self.tmp_file_path, (cur_time, cur_time))
0a07cd
+
0a07cd
+        # reset this because the unit test framework
0a07cd
+        # has already polluted the class variable
0a07cd
+        HyperVKvpReportingHandler._already_truncated_pool_file = False
0a07cd
+
0a07cd
+        reporter = HyperVKvpReportingHandler(kvp_file_path=self.tmp_file_path)
0a07cd
+        kvps = list(reporter._iterate_kvps(0))
0a07cd
+        self.assertEqual(1, len(kvps))
0a07cd
+
0a07cd
+    def test_truncate_stale_kvp_file(self):
0a07cd
+        with open(self.tmp_file_path, "wb+") as f:
0a07cd
+            kvp = {'key': 'key1', 'value': 'value1'}
0a07cd
+            data = (struct.pack("%ds%ds" % (
0a07cd
+                HyperVKvpReportingHandler.HV_KVP_EXCHANGE_MAX_KEY_SIZE,
0a07cd
+                HyperVKvpReportingHandler.HV_KVP_EXCHANGE_MAX_VALUE_SIZE),
0a07cd
+                kvp['key'].encode('utf-8'), kvp['value'].encode('utf-8')))
0a07cd
+            f.write(data)
0a07cd
+
0a07cd
+        # set the time ways back to make it look like
0a07cd
+        # we had an old kvp file
0a07cd
+        os.utime(self.tmp_file_path, (1000000, 1000000))
0a07cd
+
0a07cd
+        # reset this because the unit test framework
0a07cd
+        # has already polluted the class variable
0a07cd
+        HyperVKvpReportingHandler._already_truncated_pool_file = False
0a07cd
+
0a07cd
+        reporter = HyperVKvpReportingHandler(kvp_file_path=self.tmp_file_path)
0a07cd
+        kvps = list(reporter._iterate_kvps(0))
0a07cd
+        self.assertEqual(0, len(kvps))
0a07cd
-- 
0a07cd
1.8.3.1
0a07cd