Skip to content

Commit 4349a4a

Browse files
authored
Merge pull request #953 from cderici/handle-pending-upload-resources-deployfromrepository
#953 #### Description This is the continuation of #949, that implements handling of the local resources that need to be uploaded after a (server-side) deploy. In particular, this splits out the second part of the `add_local_resources` into a separate `_upload` function to use after the `DeployFromRepository` call which reports the pending file uploads if there's any. #### QA Steps Following the #949, this needs the server side deploy support from the controller (i.e. `>= 3.3`). So, ```sh $ juju version 3.3-beta2-ubuntu-amd64 $ juju bootstrap localhost lxd33 && juju add-model test ``` Now let's make a local resource to use: ```sh $ cd python-libjuju $ echo "jujurulez" > ./foo.txt $ cat ./foo.txt jujurulez ``` Then just manually deploy the `juju-qa-test` charm with the local resource `foo.txt`. ```python python -m asyncio asyncio REPL 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux Use "await" directly instead of "asyncio.run()". Type "help", "copyright", "credits" or "license" for more information. >>> import asyncio >>> from juju import model;m=model.Model();await m.connect();await m.deploy('juju-qa-test', application_name='j1', resources={'foo-file':'./foo.txt'})) <Application entity_id="j1"> >>> exiting asyncio REPL... ``` Now confirm that the resource is uploaded: ```sh $ juju resources j1 Resource Supplied by Revision foo-file admin 2023-09-19T22:55 ``` All CI tests need to pass. #### Notes & Discussion JUJU-3638
2 parents 48570bb + 8eaad01 commit 4349a4a

3 files changed

Lines changed: 59 additions & 35 deletions

File tree

juju/model.py

Lines changed: 52 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1743,6 +1743,8 @@ async def deploy(
17431743
if base:
17441744
charm_origin.base = utils.parse_base_arg(base)
17451745

1746+
server_side_deploy = False
1747+
17461748
if res.is_bundle:
17471749
handler = BundleHandler(self, trusted=trust, forced=force)
17481750
await handler.fetch_plan(url, charm_origin, overlays=overlays)
@@ -1774,9 +1776,20 @@ async def deploy(
17741776
else:
17751777
charm_origin = add_charm_res.charm_origin
17761778
if Schema.CHARM_HUB.matches(url.schema):
1777-
resources = await self._add_charmhub_resources(res.app_name,
1778-
identifier,
1779-
add_charm_res.charm_origin)
1779+
1780+
if client.ApplicationFacade.best_facade_version(self.connection()) >= 19:
1781+
server_side_deploy = True
1782+
else:
1783+
# TODO (cderici): this is an awkward workaround for basically not calling
1784+
# the AddPendingResources in case this is a server side deploy.
1785+
# If that's the case, then the store resources (and revisioned local
1786+
# resources) are handled at the server side if this is a server side deploy
1787+
# (local uploads are handled right after we get the pendingIDs returned
1788+
# from the facade call).
1789+
resources = await self._add_charmhub_resources(res.app_name,
1790+
identifier,
1791+
add_charm_res.charm_origin)
1792+
17801793
is_sub = await self.charmhub.is_subordinate(url.name)
17811794
if is_sub:
17821795
if num_units > 1:
@@ -1829,6 +1842,7 @@ async def deploy(
18291842
charm_origin=charm_origin,
18301843
attach_storage=attach_storage,
18311844
force=force,
1845+
server_side_deploy=server_side_deploy,
18321846
)
18331847

18341848
async def _add_charm(self, charm_url, origin):
@@ -2029,42 +2043,42 @@ async def add_local_resources(self, application, entity_url, metadata, resources
20292043
'username': '',
20302044
'password': '',
20312045
}
2032-
20332046
data = yaml.dump(docker_image_details)
2047+
else:
2048+
p = Path(path)
2049+
data = p.read_text() if p.exists() else ''
20342050

2035-
hash_alg = hashlib.sha3_384
2036-
2037-
charmresource['fingerprint'] = hash_alg(bytes(data, 'utf-8')).digest()
2051+
self._upload(data, path, application, name, resource_type, pending_id)
20382052

2039-
conn, headers, path_prefix = self.connection().https_connection()
2053+
return resource_map
20402054

2041-
query = "?pendingid={}".format(pending_id)
2042-
url = "{}/applications/{}/resources/{}{}".format(
2043-
path_prefix, application, name, query)
2044-
if resource_type == "oci-image":
2045-
disp = "multipart/form-data; filename=\"{}\"".format(path)
2046-
else:
2047-
disp = "form-data; filename=\"{}\"".format(path)
2055+
def _upload(self, data, path, app_name, res_name, res_type, pending_id):
2056+
conn, headers, path_prefix = self.connection().https_connection()
20482057

2049-
headers['Content-Type'] = 'application/octet-stream'
2050-
headers['Content-Length'] = len(data)
2051-
headers['Content-Sha384'] = charmresource['fingerprint'].hex()
2052-
headers['Content-Disposition'] = disp
2058+
query = "?pendingid={}".format(pending_id)
2059+
url = "{}/applications/{}/resources/{}{}".format(path_prefix, app_name, res_name, query)
2060+
if res_type == "oci-image":
2061+
disp = "multipart/form-data; filename=\"{}\"".format(path)
2062+
else:
2063+
disp = "form-data; filename=\"{}\"".format(path)
20532064

2054-
conn.request('PUT', url, data, headers)
2065+
headers['Content-Type'] = 'application/octet-stream'
2066+
headers['Content-Length'] = len(data)
2067+
headers['Content-Sha384'] = hashlib.sha384(bytes(data, 'utf-8')).hexdigest()
2068+
headers['Content-Disposition'] = disp
20552069

2056-
response = conn.getresponse()
2057-
result = response.read().decode()
2058-
if not response.status == 200:
2059-
raise JujuError(result)
2070+
conn.request('PUT', url, data, headers)
20602071

2061-
return resource_map
2072+
response = conn.getresponse()
2073+
result = response.read().decode()
2074+
if not response.status == 200:
2075+
raise JujuError(result)
20622076

20632077
async def _deploy(self, charm_url, application, series, config,
20642078
constraints, endpoint_bindings, resources, storage,
20652079
channel=None, num_units=None, placement=None,
20662080
devices=None, charm_origin=None, attach_storage=[],
2067-
force=False):
2081+
force=False, server_side_deploy=False):
20682082
"""Logic shared between `Model.deploy` and `BundleHandler.deploy`.
20692083
"""
20702084
log.info('Deploying %s', charm_url)
@@ -2077,7 +2091,7 @@ async def _deploy(self, charm_url, application, series, config,
20772091

20782092
app_facade = client.ApplicationFacade.from_connection(self.connection())
20792093

2080-
if client.ApplicationFacade.best_facade_version(self.connection()) >= 19:
2094+
if server_side_deploy:
20812095
# Call DeployFromRepository
20822096
app = client.DeployFromRepositoryArg(
20832097
applicationname=application,
@@ -2099,10 +2113,18 @@ async def _deploy(self, charm_url, application, series, config,
20992113
revision=charm_origin.revision,
21002114
)
21012115
result = await app_facade.DeployFromRepository([app])
2116+
# Collect the errors
21022117
errors = []
21032118
for r in result.results:
21042119
if r.errors:
21052120
errors.extend([e.message for e in r.errors])
2121+
# Upload pending local resources if any
2122+
for _result in result.results:
2123+
for pending_upload_resource in getattr(_result, 'pendingresourceuploads', []):
2124+
_path = pending_upload_resource.filename
2125+
p = Path(_path)
2126+
data = p.read_text() if p.exists() else ''
2127+
self._upload(data, _path, application, pending_upload_resource.name, 'file', '')
21062128
else:
21072129
app = client.ApplicationDeploy(
21082130
charm_url=charm_url,
@@ -2125,6 +2147,7 @@ async def _deploy(self, charm_url, application, series, config,
21252147
errors = [r.error.message for r in result.results if r.error]
21262148
if errors:
21272149
raise JujuError('\n'.join(errors))
2150+
21282151
return await self._wait_for_new('application', application)
21292152

21302153
async def destroy_unit(self, unit_id, destroy_storage=False, dry_run=False, force=False, max_wait=None):
@@ -2729,10 +2752,10 @@ def _raise_for_status(entities, status):
27292752
# errors to raise at the end
27302753
break
27312754
for unit in app.units:
2732-
if unit.machine is not None and unit.machine.status == "error":
2755+
if raise_on_error and unit.machine is not None and unit.machine.status == "error":
27332756
errors.setdefault("Machine", []).append(unit.machine.id)
27342757
continue
2735-
if unit.agent_status == "error":
2758+
if raise_on_error and unit.agent_status == "error":
27362759
errors.setdefault("Agent", []).append(unit.name)
27372760
continue
27382761
if raise_on_error and unit.workload_status == "error":

tests/integration/test_application.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
logger = logging.getLogger(__name__)
1616

17+
from ..utils import INTEGRATION_TEST_DIR
18+
1719

1820
@base.bootstrapped
1921
async def test_action(event_loop):
@@ -191,17 +193,16 @@ async def test_upgrade_local_charm(event_loop):
191193
@base.bootstrapped
192194
async def test_upgrade_local_charm_resource(event_loop):
193195
async with base.CleanModel() as model:
194-
tests_dir = Path(__file__).absolute().parent
195-
charm_path = tests_dir / 'file-resource-charm'
196+
charm_path = INTEGRATION_TEST_DIR / 'file-resource-charm'
196197
resources = {"file-res": "test.file"}
197198

198199
app = await model.deploy(str(charm_path), resources=resources)
199200
assert 'file-resource-charm' in model.applications
200-
await model.wait_for_idle()
201+
await model.wait_for_idle(raise_on_error=False)
201202
assert app.units[0].agent_status == 'idle'
202203

203204
await app.upgrade_charm(path=charm_path, resources=resources)
204-
await model.wait_for_idle()
205+
await model.wait_for_idle(raise_on_error=False)
205206
ress = await app.get_resources()
206207
assert 'file-res' in ress
207208
assert ress['file-res']

tests/integration/test_model.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,7 @@ async def test_local_file_resource_charm(event_loop):
702702
app = await model.deploy(str(charm_path), resources=resources)
703703
assert 'file-resource-charm' in model.applications
704704

705-
await model.wait_for_idle()
705+
await model.wait_for_idle(raise_on_error=False)
706706
assert app.units[0].agent_status == 'idle'
707707

708708
ress = await app.get_resources()
@@ -718,7 +718,7 @@ async def test_attach_resource(event_loop):
718718
app = await model.deploy(str(charm_path), resources=resources)
719719
assert 'file-resource-charm' in model.applications
720720

721-
await model.wait_for_idle()
721+
await model.wait_for_idle(raise_on_error=False)
722722
assert app.units[0].agent_status == 'idle'
723723

724724
with open(str(charm_path / 'test.file')) as f:

0 commit comments

Comments
 (0)