Skip to content

Commit

Permalink
Handle users/groups with no names.
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyandrewmeyer committed Nov 28, 2023
1 parent a7f34cb commit aacee63
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
14 changes: 12 additions & 2 deletions ops/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2467,6 +2467,16 @@ def _build_fileinfo(path: Union[str, Path]) -> pebble.FileInfo:
import grp
import pwd
info = path.lstat()
try:
pw_name = pwd.getpwuid(info.st_uid).pw_name
except KeyError:
logger.warning("Could not get name for user %s", info.st_uid)
pw_name = None
try:
gr_name = grp.getgrgid(info.st_gid).gr_name
except KeyError:
logger.warning("Could not get name for group %s", info.st_gid)
gr_name = None
return pebble.FileInfo(
path=str(path),
name=path.name,
Expand All @@ -2475,9 +2485,9 @@ def _build_fileinfo(path: Union[str, Path]) -> pebble.FileInfo:
permissions=stat.S_IMODE(info.st_mode),
last_modified=datetime.datetime.fromtimestamp(info.st_mtime),
user_id=info.st_uid,
user=pwd.getpwuid(info.st_uid).pw_name,
user=pw_name,
group_id=info.st_gid,
group=grp.getgrgid(info.st_gid).gr_name)
group=gr_name)

@staticmethod
def _list_recursive(list_func: Callable[[Path], Iterable[pebble.FileInfo]],
Expand Down
24 changes: 23 additions & 1 deletion test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from collections import OrderedDict
from test.test_helpers import fake_script, fake_script_calls
from textwrap import dedent
from unittest.mock import patch
from unittest.mock import MagicMock, patch

import pytest

Expand Down Expand Up @@ -969,6 +969,28 @@ def test_run_error(self):
self.assertEqual(str(cm.exception), 'ERROR cannot get status\n')
self.assertEqual(cm.exception.args[0], 'ERROR cannot get status\n')

@patch("pwd.getpwuid")
@patch("grp.getgrgid")
def test_push_path_unnamed(self, getpwuid: MagicMock, getgrgid: MagicMock):
getpwuid.side_effect = KeyError
getgrgid.side_effect = KeyError
harness = ops.testing.Harness(ops.CharmBase, meta='''
name: test-app
containers:
foo:
resource: foo-image
''')
harness.begin()
harness.set_can_connect('foo', True)
c = harness.model.unit.containers['foo']

with tempfile.TemporaryDirectory() as push_src:
push_path = pathlib.Path(push_src) / 'src.txt'
with push_path.open('w') as f:
f.write('hello')
c.push_path(push_path, "/")
assert c.exists("/src.txt"), 'push_path failed: file "src.txt" missing at destination'


class PushPullCase:
"""Test case for table-driven tests."""
Expand Down

0 comments on commit aacee63

Please sign in to comment.