Repository: ansible/ansible

Issue:
oVirt disk module uses inefficient upload function
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### ISSUE TYPE
<!--- Pick one below and delete the rest -->
 - Feature Idea

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
oVirt
##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
2.5.2
```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->

##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->

##### SUMMARY
<!--- Explain the problem briefly -->
The code (https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/ovirt/ovirt_disk.py#L366 for example is inefficient, therefore somewhat slow.
For example, there's no need at all for transfer_service.extend() for each chunk.
See https://gerrit.ovirt.org/gitweb?p=ovirt-imageio.git;a=blob;f=examples/upload;h=225f2144d67d276275a731869a6e2f02c6190537;hb=HEAD for an example (upload, but download is very similar).

This could have an important positive performance boost.

##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

<!--- Paste example playbooks or commands between quotes below -->
```yaml

```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```

```



Discussion:
Files identified in the description:
* [lib/ansible/modules/cloud/misc/ovirt.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/misc/ovirt.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @joshainglis @karmab @machacekondra @mwperina
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->

Resolving patch:
diff --git a/lib/ansible/modules/cloud/ovirt/ovirt_disk.py b/lib/ansible/modules/cloud/ovirt/ovirt_disk.py
--- a/lib/ansible/modules/cloud/ovirt/ovirt_disk.py
+++ b/lib/ansible/modules/cloud/ovirt/ovirt_disk.py
@@ -365,34 +365,28 @@ def transfer(connection, module, direction, transfer_func):
 
 def download_disk_image(connection, module):
     def _transfer(transfer_service, proxy_connection, proxy_url, transfer_ticket):
-        disks_service = connection.system_service().disks_service()
-        disk = disks_service.disk_service(module.params['id']).get()
-        size = disk.actual_size
+        BUF_SIZE = 128 * 1024
         transfer_headers = {
             'Authorization': transfer_ticket,
         }
-        with open(module.params['download_image_path'], "wb") as mydisk:
+        proxy_connection.request(
+            'GET',
+            proxy_url.path,
+            headers=transfer_headers,
+        )
+        r = proxy_connection.getresponse()
+        path = module.params["download_image_path"]
+        image_size = int(r.getheader('Content-Length'))
+        with open(path, "wb") as mydisk:
             pos = 0
-            MiB_per_request = 8
-            chunk_size = 1024 * 1024 * MiB_per_request
-            while pos < size:
-                transfer_service.extend()
-                transfer_headers['Range'] = 'bytes=%d-%d' % (pos, min(size, pos + chunk_size) - 1)
-                proxy_connection.request(
-                    'GET',
-                    proxy_url.path,
-                    headers=transfer_headers,
-                )
-                r = proxy_connection.getresponse()
-                if r.status >= 300:
-                    raise Exception("Error: %s" % r.read())
-
-                try:
-                    mydisk.write(r.read())
-                except IncompleteRead as e:
-                    mydisk.write(e.partial)
-                    break
-                pos += chunk_size
+            while pos < image_size:
+                to_read = min(image_size - pos, BUF_SIZE)
+                chunk = r.read(to_read)
+                if not chunk:
+                    raise RuntimeError("Socket disconnected")
+                mydisk.write(chunk)
+                pos += len(chunk)
+
     return transfer(
         connection,
         module,
@@ -403,28 +397,24 @@ def _transfer(transfer_service, proxy_connection, proxy_url, transfer_ticket):
 
 def upload_disk_image(connection, module):
     def _transfer(transfer_service, proxy_connection, proxy_url, transfer_ticket):
+        BUF_SIZE = 128 * 1024
         path = module.params['upload_image_path']
-        transfer_headers = {
-            'Authorization': transfer_ticket,
-        }
+
+        image_size = os.path.getsize(path)
+        proxy_connection.putrequest("PUT", proxy_url.path)
+        proxy_connection.putheader('Content-Length', "%d" % (image_size,))
+        proxy_connection.endheaders()
         with open(path, "rb") as disk:
             pos = 0
-            MiB_per_request = 8
-            size = os.path.getsize(path)
-            chunk_size = 1024 * 1024 * MiB_per_request
-            while pos < size:
-                transfer_service.extend()
-                transfer_headers['Content-Range'] = "bytes %d-%d/%d" % (pos, min(pos + chunk_size, size) - 1, size)
-                proxy_connection.request(
-                    'PUT',
-                    proxy_url.path,
-                    disk.read(chunk_size),
-                    headers=transfer_headers,
-                )
-                r = proxy_connection.getresponse()
-                if r.status >= 400:
-                    raise Exception("Failed to upload disk image.")
-                pos += chunk_size
+            while pos < image_size:
+                to_read = min(image_size - pos, BUF_SIZE)
+                chunk = disk.read(to_read)
+                if not chunk:
+                    transfer_service.pause()
+                    raise RuntimeError("Unexpected end of file at pos=%d" % pos)
+                proxy_connection.send(chunk)
+                pos += len(chunk)
+
     return transfer(
         connection,
         module,


Test patch: